{"text":"\/*************************************************************************\n *\n * $RCSfile: MABResultSet.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: hr $ $Date: 2001-10-17 18:18: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#ifndef _CONNECTIVITY_MAB_RESULTSET_HXX_\n#define _CONNECTIVITY_MAB_RESULTSET_HXX_\n\n#ifndef _CONNECTIVITY_FILE_FRESULTSET_HXX_\n#include \"file\/FResultSet.hxx\"\n#endif\n#ifndef _CONNECTIVITY_MAB_TABLE_HXX_\n#include \"mozaddressbook\/MABTable.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XROWLOCATE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XDELETEROWS_HPP_\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include \n#endif\n\nnamespace connectivity\n{\n namespace mozaddressbook\n {\n class OMozabResultSet;\n \/\/ these typedef's are only necessary for the compiler\n typedef ::cppu::ImplHelper2< ::com::sun::star::sdbcx::XRowLocate,\n ::com::sun::star::sdbcx::XDeleteRows> OMozabResultSet_BASE;\n typedef file::OResultSet OMozabResultSet_BASE2;\n typedef ::comphelper::OPropertyArrayUsageHelper OMozabResultSet_BASE3;\n\n\n class OMozabResultSet : public OMozabResultSet_BASE2,\n public OMozabResultSet_BASE,\n public OMozabResultSet_BASE3\n {\n sal_Bool m_bBookmarkable;\n protected:\n OMozabTable *m_pMozTable;\n\n \/\/ OPropertyArrayUsageHelper\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const;\n \/\/ OPropertySetHelper\n virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();\n virtual sal_Bool fillIndexValues(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier> &_xIndex);\n\n public:\n DECLARE_SERVICE_INFO();\n\n OMozabResultSet( file::OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator& _aSQLIterator);\n\n \/\/ XInterface\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL acquire() throw();\n virtual void SAL_CALL release() throw();\n \/\/XTypeProvider\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);\n \/\/ XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XRowLocate\n virtual ::com::sun::star::uno::Any SAL_CALL getBookmark( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL moveToBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL moveRelativeToBookmark( const ::com::sun::star::uno::Any& bookmark, sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL compareBookmarks( const ::com::sun::star::uno::Any& first, const ::com::sun::star::uno::Any& second ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasOrderedBookmarks( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL hashBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/ XDeleteRows\n virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL deleteRows( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ special methods\n \/\/ virtual BOOL OpenImpl();\n virtual void doTableSpecials(const OSQLTable& _xTable);\n };\n }\n}\n\n#endif \/\/_CONNECTIVITY_MAB_RESULTSET_HXX_\n\nINTEGRATION: CWS ooo19126 (1.8.342); FILE MERGED 2005\/09\/05 17:25:41 rt 1.8.342.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: MABResultSet.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 07:31: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 _CONNECTIVITY_MAB_RESULTSET_HXX_\n#define _CONNECTIVITY_MAB_RESULTSET_HXX_\n\n#ifndef _CONNECTIVITY_FILE_FRESULTSET_HXX_\n#include \"file\/FResultSet.hxx\"\n#endif\n#ifndef _CONNECTIVITY_MAB_TABLE_HXX_\n#include \"mozaddressbook\/MABTable.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XROWLOCATE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XDELETEROWS_HPP_\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include \n#endif\n\nnamespace connectivity\n{\n namespace mozaddressbook\n {\n class OMozabResultSet;\n \/\/ these typedef's are only necessary for the compiler\n typedef ::cppu::ImplHelper2< ::com::sun::star::sdbcx::XRowLocate,\n ::com::sun::star::sdbcx::XDeleteRows> OMozabResultSet_BASE;\n typedef file::OResultSet OMozabResultSet_BASE2;\n typedef ::comphelper::OPropertyArrayUsageHelper OMozabResultSet_BASE3;\n\n\n class OMozabResultSet : public OMozabResultSet_BASE2,\n public OMozabResultSet_BASE,\n public OMozabResultSet_BASE3\n {\n sal_Bool m_bBookmarkable;\n protected:\n OMozabTable *m_pMozTable;\n\n \/\/ OPropertyArrayUsageHelper\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const;\n \/\/ OPropertySetHelper\n virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();\n virtual sal_Bool fillIndexValues(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier> &_xIndex);\n\n public:\n DECLARE_SERVICE_INFO();\n\n OMozabResultSet( file::OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator& _aSQLIterator);\n\n \/\/ XInterface\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL acquire() throw();\n virtual void SAL_CALL release() throw();\n \/\/XTypeProvider\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);\n \/\/ XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XRowLocate\n virtual ::com::sun::star::uno::Any SAL_CALL getBookmark( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL moveToBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL moveRelativeToBookmark( const ::com::sun::star::uno::Any& bookmark, sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL compareBookmarks( const ::com::sun::star::uno::Any& first, const ::com::sun::star::uno::Any& second ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasOrderedBookmarks( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL hashBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/ XDeleteRows\n virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL deleteRows( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ special methods\n \/\/ virtual BOOL OpenImpl();\n virtual void doTableSpecials(const OSQLTable& _xTable);\n };\n }\n}\n\n#endif \/\/_CONNECTIVITY_MAB_RESULTSET_HXX_\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTextMapper.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n Thanks: Thanks to Matt Turek who developed this class.\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 \"vtkTextMapper.h\"\n\n#ifdef _WIN32\n #include \"vtkWin32OpenGLTextMapper.h\"\n #include \"vtkWin32TextMapper.h\"\n#else\n#ifdef VTK_USE_OGLR\n #include \"vtkXOpenGLTextMapper.h\"\n#endif\n #include \"vtkXTextMapper.h\"\n#endif\n\n\/\/ Creates a new text mapper with Font size 12, bold off, italic off,\n\/\/ and Arial font\nvtkTextMapper::vtkTextMapper()\n{\n this->Input = (char*) NULL;\n this->FontSize = 12;\n this->Bold = 0;\n this->Italic = 0;\n this->Shadow = 0;\n this->FontFamily = VTK_ARIAL;\n this->Justification = VTK_TEXT_LEFT;\n this->VerticalJustification = VTK_TEXT_BOTTOM;\n\n this->TextLines = NULL;\n this->NumberOfLines = 0;\n this->NumberOfLinesAllocated = 0;\n this->LineOffset = 0.0;\n this->LineSpacing = 1.0;\n}\n\nvtkTextMapper *vtkTextMapper::New()\n{\n#ifdef _WIN32\n#ifndef VTK_USE_NATIVE_IMAGING\n return vtkWin32OpenGLTextMapper::New();\n#else\n return vtkWin32TextMapper::New();\n#endif\n#else\n#ifdef VTK_USE_OGLR\n#ifndef VTK_USE_NATIVE_IMAGING\n return vtkXOpenGLTextMapper::New();\n#else\n return vtkXTextMapper::New();\n#endif\n#else\n return vtkXTextMapper::New();\n#endif\n#endif\n\n}\n\nvtkTextMapper::~vtkTextMapper()\n{\n if (this->Input)\n {\n delete [] this->Input;\n this->Input = NULL;\n }\n\n if ( this->TextLines != NULL )\n {\n for (int i=0; i < this->NumberOfLinesAllocated; i++)\n {\n this->TextLines[i]->Delete();\n }\n delete [] this->TextLines;\n }\n \n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkTextMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n os << indent << \"Line Offset: \" << this->LineOffset;\n os << indent << \"Line Spacing: \" << this->LineSpacing;\n os << indent << \"Bold: \" << (this->Bold ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Italic: \" << (this->Italic ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Shadow: \" << (this->Shadow ? \"On\\n\" : \"Off\\n\");\n os << indent << \"FontFamily: \" << this->FontFamily << \"\\n\";\n os << indent << \"FontSize: \" << this->FontSize << \"\\n\";\n os << indent << \"Input: \" << (this->Input ? this->Input : \"(none)\") << \"\\n\";\n os << indent << \"Justification: \";\n switch (this->Justification)\n {\n case 0: os << \"Left (0)\" << endl; break;\n case 1: os << \"Centered (1)\" << endl; break;\n case 2: os << \"Right (2)\" << endl; break;\n }\n os << indent << \"VerticalJustification: \";\n switch (this->VerticalJustification)\n {\n case VTK_TEXT_TOP: os << \"Top\" << endl; break;\n case VTK_TEXT_CENTERED: os << \"Centered\" << endl; break;\n case VTK_TEXT_BOTTOM: os << \"Bottom\" << endl; break;\n }\n \n vtkMapper2D::PrintSelf(os,indent);\n}\n\nint vtkTextMapper::GetWidth(vtkViewport* viewport)\n{\n int size[2];\n this->GetSize(viewport, size);\n return size[0];\n}\n\nint vtkTextMapper::GetHeight(vtkViewport* viewport)\n{\n int size[2];\n this->GetSize(viewport, size);\n return size[1];\n}\n\n\/\/ Parse the input and create multiple text mappers if multiple lines\n\/\/ (delimited by \\n) are specified.\nvoid vtkTextMapper::SetInput(char *input)\n{\n if ( this->Input && input && (!strcmp(this->Input,input))) \n {\n return;\n }\n if (this->Input) \n { \n delete [] this->Input; \n } \n if (input)\n {\n this->Input = new char[strlen(input)+1];\n strcpy(this->Input,input);\n }\n else\n {\n this->Input = NULL;\n }\n this->Modified();\n \n int numLines = this->GetNumberOfLines(input);\n \n if ( numLines <= 1) \/\/ a line with no \"\\n\"\n {\n this->NumberOfLines = numLines;\n this->LineOffset = 0.0;\n }\n\n else \/\/multiple lines\n {\n char *line;\n int i;\n\n if ( numLines > this->NumberOfLinesAllocated )\n {\n \/\/ delete old stuff\n if ( this->TextLines )\n {\n for (i=0; i < this->NumberOfLinesAllocated; i++)\n {\n this->TextLines[i]->Delete();\n }\n delete [] this->TextLines;\n }\n \n \/\/ allocate new text mappers\n this->NumberOfLinesAllocated = numLines;\n this->TextLines = new vtkTextMapper *[numLines];\n for (i=0; i < numLines; i++)\n {\n this->TextLines[i] = vtkTextMapper::New();\n }\n } \/\/if we need to reallocate\n \n \/\/ set the input strings\n this->NumberOfLines = numLines;\n for (i=0; i < this->NumberOfLines; i++)\n {\n line = this->NextLine(input, i);\n this->TextLines[i]->SetInput( line );\n delete [] line;\n }\n }\n}\n\n\/\/ Determine the number of lines in the Input string (delimited by \"\\n\").\nint vtkTextMapper::GetNumberOfLines(char *input)\n{\n if ( input == NULL )\n {\n return 0;\n }\n\n int numLines=1;\n char *ptr = input;\n\n while ( ptr != NULL )\n {\n if ( (ptr=strstr(ptr,\"\\n\")) != NULL )\n {\n numLines++;\n ptr++; \/\/skip over \\n\n }\n }\n \n return numLines;\n}\n\n\/\/ Get the next \\n delimited line. Returns a string that\n\/\/ must be freed by the calling function.\nchar *vtkTextMapper::NextLine(char *input, int lineNum)\n{\n char *line, *ptr, *ptrEnd;\n int strLen;\n\n ptr = input;\n for (int i=0; i != lineNum; i++)\n {\n ptr = strstr(ptr,\"\\n\");\n ptr++;\n }\n ptrEnd = strstr(ptr,\"\\n\");\n if ( ptrEnd == NULL )\n {\n ptrEnd = strchr(ptr, '\\0');\n }\n \n strLen = ptrEnd - ptr;\n line = new char[strLen+1];\n strncpy(line, ptr, strLen);\n line[strLen] = '\\0';\n\n return line;\n}\n\n\/\/ Get the size of a multi-line text string\nvoid vtkTextMapper::GetMultiLineSize(vtkViewport* viewport, int size[2])\n{\n int i;\n int lineSize[2];\n \n lineSize[0] = lineSize[1] = size[0] = size[1] = 0;\n for ( i=0; i < this->NumberOfLines; i++ )\n {\n this->TextLines[i]->SetItalic(this->Italic);\n this->TextLines[i]->SetBold(this->Bold);\n this->TextLines[i]->SetShadow(this->Shadow);\n this->TextLines[i]->SetFontSize(this->FontSize);\n this->TextLines[i]->SetFontFamily(this->FontFamily);\n this->TextLines[i]->GetSize(viewport, lineSize);\n size[0] = (lineSize[0] > size[0] ? lineSize[0] : size[0]);\n size[1] = (lineSize[1] > size[1] ? lineSize[1] : size[1]);\n }\n \n \/\/ add in the line spacing\n this->LineSize = size[1];\n size[1] = this->NumberOfLines* this->LineSpacing * size[1];\n}\n\nvoid vtkTextMapper::RenderOverlayMultipleLines(vtkViewport *viewport, \n vtkActor2D *actor) \n{\n float offset;\n int size[2];\n \/\/ make sure LineSize is up to date \n this->GetMultiLineSize(viewport,size);\n \n switch (this->VerticalJustification)\n {\n case VTK_TEXT_TOP:\n offset = 1.0;\n break;\n case VTK_TEXT_CENTERED:\n offset = -this->NumberOfLines\/2.0 + 1;\n break;\n case VTK_TEXT_BOTTOM:\n offset = -(this->NumberOfLines - 1.0);\n break;\n }\n\n for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++)\n {\n this->TextLines[lineNum]->SetItalic(this->Italic);\n this->TextLines[lineNum]->SetBold(this->Bold);\n this->TextLines[lineNum]->SetShadow(this->Shadow);\n this->TextLines[lineNum]->SetFontSize(this->FontSize);\n this->TextLines[lineNum]->SetFontFamily(this->FontFamily);\n this->TextLines[lineNum]->SetJustification(this->Justification);\n this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset));\n this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing);\n this->TextLines[lineNum]->RenderOverlay(viewport,actor);\n }\n}\n\nvoid vtkTextMapper::RenderOpaqueGeometryMultipleLines(vtkViewport *viewport, \n vtkActor2D *actor) \n{\n float offset;\n int size[2];\n \/\/ make sure LineSize is up to date \n this->GetMultiLineSize(viewport,size);\n\n switch (this->VerticalJustification)\n {\n case VTK_TEXT_TOP:\n offset = 1.0;\n break;\n case VTK_TEXT_CENTERED:\n offset = -this->NumberOfLines\/2.0 + 1;\n break;\n case VTK_TEXT_BOTTOM:\n offset = -(this->NumberOfLines - 1.0);\n break;\n }\n\n for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++)\n {\n this->TextLines[lineNum]->SetItalic(this->Italic);\n this->TextLines[lineNum]->SetBold(this->Bold);\n this->TextLines[lineNum]->SetShadow(this->Shadow);\n this->TextLines[lineNum]->SetFontSize(this->FontSize);\n this->TextLines[lineNum]->SetFontFamily(this->FontFamily);\n this->TextLines[lineNum]->SetJustification(this->Justification);\n this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset));\n this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing);\n this->TextLines[lineNum]->RenderOpaqueGeometry(viewport,actor);\n }\n}\nfixed print self\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTextMapper.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n Thanks: Thanks to Matt Turek who developed this class.\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 \"vtkTextMapper.h\"\n\n#ifdef _WIN32\n #include \"vtkWin32OpenGLTextMapper.h\"\n #include \"vtkWin32TextMapper.h\"\n#else\n#ifdef VTK_USE_OGLR\n #include \"vtkXOpenGLTextMapper.h\"\n#endif\n #include \"vtkXTextMapper.h\"\n#endif\n\n\/\/ Creates a new text mapper with Font size 12, bold off, italic off,\n\/\/ and Arial font\nvtkTextMapper::vtkTextMapper()\n{\n this->Input = (char*) NULL;\n this->FontSize = 12;\n this->Bold = 0;\n this->Italic = 0;\n this->Shadow = 0;\n this->FontFamily = VTK_ARIAL;\n this->Justification = VTK_TEXT_LEFT;\n this->VerticalJustification = VTK_TEXT_BOTTOM;\n\n this->TextLines = NULL;\n this->NumberOfLines = 0;\n this->NumberOfLinesAllocated = 0;\n this->LineOffset = 0.0;\n this->LineSpacing = 1.0;\n}\n\nvtkTextMapper *vtkTextMapper::New()\n{\n#ifdef _WIN32\n#ifndef VTK_USE_NATIVE_IMAGING\n return vtkWin32OpenGLTextMapper::New();\n#else\n return vtkWin32TextMapper::New();\n#endif\n#else\n#ifdef VTK_USE_OGLR\n#ifndef VTK_USE_NATIVE_IMAGING\n return vtkXOpenGLTextMapper::New();\n#else\n return vtkXTextMapper::New();\n#endif\n#else\n return vtkXTextMapper::New();\n#endif\n#endif\n\n}\n\nvtkTextMapper::~vtkTextMapper()\n{\n if (this->Input)\n {\n delete [] this->Input;\n this->Input = NULL;\n }\n\n if ( this->TextLines != NULL )\n {\n for (int i=0; i < this->NumberOfLinesAllocated; i++)\n {\n this->TextLines[i]->Delete();\n }\n delete [] this->TextLines;\n }\n \n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkTextMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkMapper2D::PrintSelf(os,indent);\n\n os << indent << \"Line Offset: \" << this->LineOffset;\n os << indent << \"Line Spacing: \" << this->LineSpacing;\n os << indent << \"Bold: \" << (this->Bold ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Italic: \" << (this->Italic ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Shadow: \" << (this->Shadow ? \"On\\n\" : \"Off\\n\");\n os << indent << \"FontFamily: \" << this->FontFamily << \"\\n\";\n os << indent << \"FontSize: \" << this->FontSize << \"\\n\";\n os << indent << \"Input: \" << (this->Input ? this->Input : \"(none)\") << \"\\n\";\n os << indent << \"Justification: \";\n switch (this->Justification)\n {\n case 0: os << \"Left (0)\" << endl; break;\n case 1: os << \"Centered (1)\" << endl; break;\n case 2: os << \"Right (2)\" << endl; break;\n }\n os << indent << \"VerticalJustification: \";\n switch (this->VerticalJustification)\n {\n case VTK_TEXT_TOP: os << \"Top\" << endl; break;\n case VTK_TEXT_CENTERED: os << \"Centered\" << endl; break;\n case VTK_TEXT_BOTTOM: os << \"Bottom\" << endl; break;\n }\n \n os << indent << \"NumberOfLines: \" << this->NumberOfLines << \"\\n\"; \n}\n\nint vtkTextMapper::GetWidth(vtkViewport* viewport)\n{\n int size[2];\n this->GetSize(viewport, size);\n return size[0];\n}\n\nint vtkTextMapper::GetHeight(vtkViewport* viewport)\n{\n int size[2];\n this->GetSize(viewport, size);\n return size[1];\n}\n\n\/\/ Parse the input and create multiple text mappers if multiple lines\n\/\/ (delimited by \\n) are specified.\nvoid vtkTextMapper::SetInput(char *input)\n{\n if ( this->Input && input && (!strcmp(this->Input,input))) \n {\n return;\n }\n if (this->Input) \n { \n delete [] this->Input; \n } \n if (input)\n {\n this->Input = new char[strlen(input)+1];\n strcpy(this->Input,input);\n }\n else\n {\n this->Input = NULL;\n }\n this->Modified();\n \n int numLines = this->GetNumberOfLines(input);\n \n if ( numLines <= 1) \/\/ a line with no \"\\n\"\n {\n this->NumberOfLines = numLines;\n this->LineOffset = 0.0;\n }\n\n else \/\/multiple lines\n {\n char *line;\n int i;\n\n if ( numLines > this->NumberOfLinesAllocated )\n {\n \/\/ delete old stuff\n if ( this->TextLines )\n {\n for (i=0; i < this->NumberOfLinesAllocated; i++)\n {\n this->TextLines[i]->Delete();\n }\n delete [] this->TextLines;\n }\n \n \/\/ allocate new text mappers\n this->NumberOfLinesAllocated = numLines;\n this->TextLines = new vtkTextMapper *[numLines];\n for (i=0; i < numLines; i++)\n {\n this->TextLines[i] = vtkTextMapper::New();\n }\n } \/\/if we need to reallocate\n \n \/\/ set the input strings\n this->NumberOfLines = numLines;\n for (i=0; i < this->NumberOfLines; i++)\n {\n line = this->NextLine(input, i);\n this->TextLines[i]->SetInput( line );\n delete [] line;\n }\n }\n}\n\n\/\/ Determine the number of lines in the Input string (delimited by \"\\n\").\nint vtkTextMapper::GetNumberOfLines(char *input)\n{\n if ( input == NULL )\n {\n return 0;\n }\n\n int numLines=1;\n char *ptr = input;\n\n while ( ptr != NULL )\n {\n if ( (ptr=strstr(ptr,\"\\n\")) != NULL )\n {\n numLines++;\n ptr++; \/\/skip over \\n\n }\n }\n \n return numLines;\n}\n\n\/\/ Get the next \\n delimited line. Returns a string that\n\/\/ must be freed by the calling function.\nchar *vtkTextMapper::NextLine(char *input, int lineNum)\n{\n char *line, *ptr, *ptrEnd;\n int strLen;\n\n ptr = input;\n for (int i=0; i != lineNum; i++)\n {\n ptr = strstr(ptr,\"\\n\");\n ptr++;\n }\n ptrEnd = strstr(ptr,\"\\n\");\n if ( ptrEnd == NULL )\n {\n ptrEnd = strchr(ptr, '\\0');\n }\n \n strLen = ptrEnd - ptr;\n line = new char[strLen+1];\n strncpy(line, ptr, strLen);\n line[strLen] = '\\0';\n\n return line;\n}\n\n\/\/ Get the size of a multi-line text string\nvoid vtkTextMapper::GetMultiLineSize(vtkViewport* viewport, int size[2])\n{\n int i;\n int lineSize[2];\n \n lineSize[0] = lineSize[1] = size[0] = size[1] = 0;\n for ( i=0; i < this->NumberOfLines; i++ )\n {\n this->TextLines[i]->SetItalic(this->Italic);\n this->TextLines[i]->SetBold(this->Bold);\n this->TextLines[i]->SetShadow(this->Shadow);\n this->TextLines[i]->SetFontSize(this->FontSize);\n this->TextLines[i]->SetFontFamily(this->FontFamily);\n this->TextLines[i]->GetSize(viewport, lineSize);\n size[0] = (lineSize[0] > size[0] ? lineSize[0] : size[0]);\n size[1] = (lineSize[1] > size[1] ? lineSize[1] : size[1]);\n }\n \n \/\/ add in the line spacing\n this->LineSize = size[1];\n size[1] = this->NumberOfLines* this->LineSpacing * size[1];\n}\n\nvoid vtkTextMapper::RenderOverlayMultipleLines(vtkViewport *viewport, \n vtkActor2D *actor) \n{\n float offset;\n int size[2];\n \/\/ make sure LineSize is up to date \n this->GetMultiLineSize(viewport,size);\n \n switch (this->VerticalJustification)\n {\n case VTK_TEXT_TOP:\n offset = 1.0;\n break;\n case VTK_TEXT_CENTERED:\n offset = -this->NumberOfLines\/2.0 + 1;\n break;\n case VTK_TEXT_BOTTOM:\n offset = -(this->NumberOfLines - 1.0);\n break;\n }\n\n for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++)\n {\n this->TextLines[lineNum]->SetItalic(this->Italic);\n this->TextLines[lineNum]->SetBold(this->Bold);\n this->TextLines[lineNum]->SetShadow(this->Shadow);\n this->TextLines[lineNum]->SetFontSize(this->FontSize);\n this->TextLines[lineNum]->SetFontFamily(this->FontFamily);\n this->TextLines[lineNum]->SetJustification(this->Justification);\n this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset));\n this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing);\n this->TextLines[lineNum]->RenderOverlay(viewport,actor);\n }\n}\n\nvoid vtkTextMapper::RenderOpaqueGeometryMultipleLines(vtkViewport *viewport, \n vtkActor2D *actor) \n{\n float offset;\n int size[2];\n \/\/ make sure LineSize is up to date \n this->GetMultiLineSize(viewport,size);\n\n switch (this->VerticalJustification)\n {\n case VTK_TEXT_TOP:\n offset = 1.0;\n break;\n case VTK_TEXT_CENTERED:\n offset = -this->NumberOfLines\/2.0 + 1;\n break;\n case VTK_TEXT_BOTTOM:\n offset = -(this->NumberOfLines - 1.0);\n break;\n }\n\n for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++)\n {\n this->TextLines[lineNum]->SetItalic(this->Italic);\n this->TextLines[lineNum]->SetBold(this->Bold);\n this->TextLines[lineNum]->SetShadow(this->Shadow);\n this->TextLines[lineNum]->SetFontSize(this->FontSize);\n this->TextLines[lineNum]->SetFontFamily(this->FontFamily);\n this->TextLines[lineNum]->SetJustification(this->Justification);\n this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset));\n this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing);\n this->TextLines[lineNum]->RenderOpaqueGeometry(viewport,actor);\n }\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2008-2019 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 * Covered Software is provided under this License on an \"as is\"\n * basis, without warranty of any kind, either expressed, implied, or\n * statutory, including, without limitation, warranties that the\n * Covered Software is free of defects, merchantable, fit for a\n * particular purpose or non-infringing.\n * See the Mozilla Public License v. 2.0 for more details.\n *\n * For more details, see http:\/\/www.mrtrix.org\/.\n *\/\n\n#include \"command.h\"\n#include \"debug.h\"\n#include \"file\/path.h\"\n#include \"file\/dicom\/element.h\"\n#include \"file\/dicom\/quick_scan.h\"\n#include \"file\/dicom\/definitions.h\"\n\n\nusing namespace MR;\nusing namespace App;\n\nvoid usage ()\n{\n AUTHOR = \"J-Donald Tournier (jdtournier@gmail.com)\";\n\n SYNOPSIS = \"Edit DICOM file in-place\";\n\n DESCRIPTION\n + \"Note that this command simply replaces the existing \"\n \"values without modifying the DICOM structure in any way. Replacement text \"\n \"will be truncated if it is too long to fit inside the existing tag.\"\n\n + \"WARNING: this command will modify existing data! It is recommended to run \"\n \"this command on a copy of the original data set to avoid loss of data.\";\n\n\n ARGUMENTS\n + Argument (\"file\", \"the DICOM file to be edited.\").type_file_in();\n\n OPTIONS\n + Option (\"anonymise\", \"remove any identifiable information, by replacing the following tags:\\n\"\n \"- any tag with Value Representation PN will be replaced with 'anonymous'\\n\"\n \"- tag (0010,0030) PatientBirthDate will be replaced with an empty string\\n\\n\"\n \"WARNING: there is no guarantee that this command will remove all identiable \"\n \"information, since such information may be contained in any number \"\n \"of private vendor-specific tags. You will need to double-check the \"\n \"results independently if you \" \"need to ensure anonymity.\")\n\n + Option (\"id\", \"replace all ID tags with string supplied. This consists of tags \"\n \"(0010, 0020) PatientID and (0010, 1000) OtherPatientIDs\")\n + Argument (\"text\").type_text()\n\n + Option (\"tag\", \"replace specific tag.\").allow_multiple()\n + Argument (\"group\")\n + Argument (\"element\")\n + Argument (\"newvalue\");\n}\n\n\nclass Tag { NOMEMALIGN\n public:\n Tag (uint16_t group, uint16_t element, const std::string& newvalue) :\n group (group), element (element), newvalue (newvalue) { }\n uint16_t group, element;\n std::string newvalue;\n};\n\n\n\n\ninline std::string hex (uint16_t value)\n{\n std::ostringstream hex;\n hex << std::hex << value;\n return hex.str();\n}\n\ninline uint16_t read_hex (const std::string& m)\n{\n uint16_t value;\n std::istringstream hex (m);\n hex >> std::hex >> value;\n return value;\n}\n\n\n\n\nvoid run ()\n{\n vector tags;\n vector VRs;\n\n auto opt = get_options (\"anonymise\");\n if (opt.size()) {\n tags.push_back (Tag (0x0010U, 0x0030U, \"\")); \/\/ PatientBirthDate\n VRs.push_back (VR_PN);\n }\n\n\n opt = get_options (\"tag\");\n if (opt.size())\n for (size_t n = 0; n < opt.size(); ++n)\n tags.push_back (Tag (read_hex (opt[n][0]), read_hex (opt[n][1]), opt[n][2]));\n\n opt = get_options (\"id\");\n if (opt.size()) {\n std::string newid = opt[0][0];\n tags.push_back (Tag (0x0010U, 0x0020U, newid)); \/\/ PatientID\n tags.push_back (Tag (0x0010U, 0x1000U, newid)); \/\/ OtherPatientIDs\n }\n\n for (size_t n = 0; n < VRs.size(); ++n) {\n union __VR { uint16_t i; char c[2]; } VR;\n VR.i = VRs[n];\n INFO (std::string (\"clearing entries with VR \\\"\") + VR.c[1] + VR.c[0] + \"\\\"\");\n }\n for (size_t n = 0; n < tags.size(); ++n)\n INFO (\"replacing tag (\" + hex(tags[n].group) + \",\" + hex(tags[n].element) + \") with value \\\"\" + tags[n].newvalue + \"\\\"\");\n\n File::Dicom::Element item;\n item.set (argument[0], true, true);\n while (item.read()) {\n for (size_t n = 0; n < VRs.size(); ++n) {\n if (item.VR == VRs[n]) {\n memset (item.data, 32, item.size);\n memcpy (item.data, \"anonymous\", std::min (item.size, 9));\n }\n }\n for (size_t n = 0; n < tags.size(); ++n) {\n if (item.is (tags[n].group, tags[n].element)) {\n memset (item.data, 32, item.size);\n memcpy (item.data, tags[n].newvalue.c_str(), std::min (item.size, tags[n].newvalue.size()));\n }\n }\n }\n}\n\ndcmedit: minor tweaks to docs\/* Copyright (c) 2008-2019 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 * Covered Software is provided under this License on an \"as is\"\n * basis, without warranty of any kind, either expressed, implied, or\n * statutory, including, without limitation, warranties that the\n * Covered Software is free of defects, merchantable, fit for a\n * particular purpose or non-infringing.\n * See the Mozilla Public License v. 2.0 for more details.\n *\n * For more details, see http:\/\/www.mrtrix.org\/.\n *\/\n\n#include \"command.h\"\n#include \"debug.h\"\n#include \"file\/path.h\"\n#include \"file\/dicom\/element.h\"\n#include \"file\/dicom\/quick_scan.h\"\n#include \"file\/dicom\/definitions.h\"\n\n\nusing namespace MR;\nusing namespace App;\n\nvoid usage ()\n{\n AUTHOR = \"J-Donald Tournier (jdtournier@gmail.com)\";\n\n SYNOPSIS = \"Edit DICOM file in-place\";\n\n DESCRIPTION\n + \"Note that this command simply replaces the existing \"\n \"values without modifying the DICOM structure in any way. Replacement text \"\n \"will be truncated if it is too long to fit inside the existing tag.\"\n\n + \"WARNING: this command will modify existing data! It is recommended to run \"\n \"this command on a copy of the original data set to avoid loss of data.\";\n\n\n ARGUMENTS\n + Argument (\"file\", \"the DICOM file to be edited.\").type_file_in();\n\n OPTIONS\n + Option (\"anonymise\", \"remove any identifiable information, by replacing the following tags:\\n\"\n \"- any tag with Value Representation PN will be replaced with 'anonymous'\\n\"\n \"- tag (0010,0030) PatientBirthDate will be replaced with an empty string\\n\"\n \"WARNING: there is no guarantee that this command will remove all identiable \"\n \"information, since such information may be contained in any number \"\n \"of private vendor-specific tags. You will need to double-check the \"\n \"results independently if you \" \"need to ensure anonymity.\")\n\n + Option (\"id\", \"replace all ID tags with string supplied. This consists of tags \"\n \"(0010, 0020) PatientID and (0010, 1000) OtherPatientIDs\")\n + Argument (\"text\").type_text()\n\n + Option (\"tag\", \"replace specific tag.\").allow_multiple()\n + Argument (\"group\")\n + Argument (\"element\")\n + Argument (\"newvalue\");\n}\n\n\nclass Tag { NOMEMALIGN\n public:\n Tag (uint16_t group, uint16_t element, const std::string& newvalue) :\n group (group), element (element), newvalue (newvalue) { }\n uint16_t group, element;\n std::string newvalue;\n};\n\n\n\n\ninline std::string hex (uint16_t value)\n{\n std::ostringstream hex;\n hex << std::hex << value;\n return hex.str();\n}\n\ninline uint16_t read_hex (const std::string& m)\n{\n uint16_t value;\n std::istringstream hex (m);\n hex >> std::hex >> value;\n return value;\n}\n\n\n\n\nvoid run ()\n{\n vector tags;\n vector VRs;\n\n auto opt = get_options (\"anonymise\");\n if (opt.size()) {\n tags.push_back (Tag (0x0010U, 0x0030U, \"\")); \/\/ PatientBirthDate\n VRs.push_back (VR_PN);\n }\n\n\n opt = get_options (\"tag\");\n if (opt.size())\n for (size_t n = 0; n < opt.size(); ++n)\n tags.push_back (Tag (read_hex (opt[n][0]), read_hex (opt[n][1]), opt[n][2]));\n\n opt = get_options (\"id\");\n if (opt.size()) {\n std::string newid = opt[0][0];\n tags.push_back (Tag (0x0010U, 0x0020U, newid)); \/\/ PatientID\n tags.push_back (Tag (0x0010U, 0x1000U, newid)); \/\/ OtherPatientIDs\n }\n\n for (size_t n = 0; n < VRs.size(); ++n) {\n union __VR { uint16_t i; char c[2]; } VR;\n VR.i = VRs[n];\n INFO (std::string (\"clearing entries with VR \\\"\") + VR.c[1] + VR.c[0] + \"\\\"\");\n }\n for (size_t n = 0; n < tags.size(); ++n)\n INFO (\"replacing tag (\" + hex(tags[n].group) + \",\" + hex(tags[n].element) + \") with value \\\"\" + tags[n].newvalue + \"\\\"\");\n\n File::Dicom::Element item;\n item.set (argument[0], true, true);\n while (item.read()) {\n for (size_t n = 0; n < VRs.size(); ++n) {\n if (item.VR == VRs[n]) {\n memset (item.data, 32, item.size);\n memcpy (item.data, \"anonymous\", std::min (item.size, 9));\n }\n }\n for (size_t n = 0; n < tags.size(); ++n) {\n if (item.is (tags[n].group, tags[n].element)) {\n memset (item.data, 32, item.size);\n memcpy (item.data, tags[n].newvalue.c_str(), std::min (item.size, tags[n].newvalue.size()));\n }\n }\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 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\/browser.h\"\n\n#include \n\n#include \"atom\/browser\/native_window.h\"\n#include \"atom\/browser\/window_list.h\"\n#include \"atom\/common\/atom_version.h\"\n#include \"brightray\/common\/application_info.h\"\n#include \"chrome\/browser\/ui\/libgtk2ui\/unity_service.h\"\n\nnamespace atom {\n\nvoid Browser::Focus() {\n \/\/ Focus on the first visible window.\n WindowList* list = WindowList::GetInstance();\n for (WindowList::iterator iter = list->begin(); iter != list->end(); ++iter) {\n NativeWindow* window = *iter;\n if (window->IsVisible()) {\n window->Focus(true);\n break;\n }\n }\n}\n\nvoid Browser::AddRecentDocument(const base::FilePath& path) {\n}\n\nvoid Browser::ClearRecentDocuments() {\n}\n\nvoid Browser::SetAppUserModelID(const base::string16& name) {\n}\n\nbool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol) {\n return false;\n}\n\nbool Browser::SetAsDefaultProtocolClient(const std::string& protocol) {\n return false;\n}\n\nbool Browser::IsDefaultProtocolClient(const std::string& protocol) {\n return false;\n}\n\nbool Browser::SetBadgeCount(int count) {\n if (IsUnityRunning()) {\n unity::SetDownloadCount(count);\n badge_count_ = count;\n return true;\n } else {\n return false;\n }\n}\n\nvoid Browser::SetLoginItemSettings(LoginItemSettings settings) {\n}\n\nLoginItemSettings Browser::GetLoginItemSettings() {\n return LoginItemSettings();\n}\n\nstd::string Browser::GetExecutableFileVersion() const {\n return brightray::GetApplicationVersion();\n}\n\nstd::string Browser::GetExecutableFileProductName() const {\n return brightray::GetApplicationName();\n}\n\nbool Browser::IsUnityRunning() {\n return unity::IsRunning();\n}\n\n} \/\/ namespace atom\nAdd Browser namespace\/\/ Copyright (c) 2013 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\/browser.h\"\n\n#include \n\n#include \"atom\/browser\/native_window.h\"\n#include \"atom\/browser\/window_list.h\"\n#include \"atom\/common\/atom_version.h\"\n#include \"brightray\/common\/application_info.h\"\n#include \"chrome\/browser\/ui\/libgtk2ui\/unity_service.h\"\n\nnamespace atom {\n\nvoid Browser::Focus() {\n \/\/ Focus on the first visible window.\n WindowList* list = WindowList::GetInstance();\n for (WindowList::iterator iter = list->begin(); iter != list->end(); ++iter) {\n NativeWindow* window = *iter;\n if (window->IsVisible()) {\n window->Focus(true);\n break;\n }\n }\n}\n\nvoid Browser::AddRecentDocument(const base::FilePath& path) {\n}\n\nvoid Browser::ClearRecentDocuments() {\n}\n\nvoid Browser::SetAppUserModelID(const base::string16& name) {\n}\n\nbool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol) {\n return false;\n}\n\nbool Browser::SetAsDefaultProtocolClient(const std::string& protocol) {\n return false;\n}\n\nbool Browser::IsDefaultProtocolClient(const std::string& protocol) {\n return false;\n}\n\nbool Browser::SetBadgeCount(int count) {\n if (IsUnityRunning()) {\n unity::SetDownloadCount(count);\n badge_count_ = count;\n return true;\n } else {\n return false;\n }\n}\n\nvoid Browser::SetLoginItemSettings(LoginItemSettings settings) {\n}\n\nBrowser::LoginItemSettings Browser::GetLoginItemSettings() {\n return LoginItemSettings();\n}\n\nstd::string Browser::GetExecutableFileVersion() const {\n return brightray::GetApplicationVersion();\n}\n\nstd::string Browser::GetExecutableFileProductName() const {\n return brightray::GetApplicationName();\n}\n\nbool Browser::IsUnityRunning() {\n return unity::IsRunning();\n}\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved\n *\/\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\n#ifndef _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_\n#define _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_\n\n#include \"..\/Concrete\/KeyedCollection_LinkedList.h\"\n\nnamespace Stroika::Foundation::Containers::Factory {\n\n \/*\n ********************************************************************************\n ****** KeyedCollection_Factory *******\n ********************************************************************************\n *\/\n#if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy\n template \n atomic (*) (KEY_EXTRACTOR&& keyExtractor, KEY_EQUALS_COMPARER&& keyComparer)> KeyedCollection_Factory::sFactory_ (nullptr);\n#endif\n template \n inline KeyedCollection_Factory::KeyedCollection_Factory (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)\n : fKeyExtractorType_{keyExtractor}\n , fKeyEqualsComparer_{keyComparer}\n {\n }\n template \n inline KeyedCollection KeyedCollection_Factory::operator() () const\n {\n \/*\n * Would have been more performant to just and assure always properly set, but to initialize\n * sFactory_ with a value other than nullptr requires waiting until after main() - so causes problems\n * with containers constructed before main.\n *\n * This works more generally (and with hopefully modest enough performance impact).\n *\/\n if (auto f = sFactory_.load ()) {\n return f (fKeyExtractorType_, fKeyEqualsComparer_);\n }\n else {\n return Default_ (fKeyExtractorType_, fKeyEqualsComparer_);\n }\n }\n template \n void KeyedCollection_Factory::Register (KeyedCollection (*factory) (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer))\n {\n sFactory_ = factory;\n }\n template \n inline KeyedCollection KeyedCollection_Factory::Default_ (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)\n {\n \/*\n * Note - though this is not an efficient implementation of KeyedCollection<> for large sizes, its probably the most\n * efficeint representation which adds no requirements to KEY_TYPE, such as operator< (or a traits less) or\n * a hash function. And its quite reasonable for small KeyedCollection's - which are often the case.\n *\n * Calls may use an explicit initializer of KeyedCollection_xxx<> to get better performance for large sized\n * maps.\n *\/\n return Concrete::KeyedCollection_LinkedList{keyExtractor, keyComparer};\n }\n\n}\n\n#endif \/* _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_ *\/\nfix typo in vs2k17 BWA\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved\n *\/\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\n#ifndef _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_\n#define _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_\n\n#include \"..\/Concrete\/KeyedCollection_LinkedList.h\"\n\nnamespace Stroika::Foundation::Containers::Factory {\n\n \/*\n ********************************************************************************\n ****** KeyedCollection_Factory *******\n ********************************************************************************\n *\/\n#if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy\n template \n atomic (*) (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)> KeyedCollection_Factory::sFactory_ (nullptr);\n#endif\n template \n inline KeyedCollection_Factory::KeyedCollection_Factory (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)\n : fKeyExtractorType_{keyExtractor}\n , fKeyEqualsComparer_{keyComparer}\n {\n }\n template \n inline KeyedCollection KeyedCollection_Factory::operator() () const\n {\n \/*\n * Would have been more performant to just and assure always properly set, but to initialize\n * sFactory_ with a value other than nullptr requires waiting until after main() - so causes problems\n * with containers constructed before main.\n *\n * This works more generally (and with hopefully modest enough performance impact).\n *\/\n if (auto f = sFactory_.load ()) {\n return f (fKeyExtractorType_, fKeyEqualsComparer_);\n }\n else {\n return Default_ (fKeyExtractorType_, fKeyEqualsComparer_);\n }\n }\n template \n void KeyedCollection_Factory::Register (KeyedCollection (*factory) (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer))\n {\n sFactory_ = factory;\n }\n template \n inline KeyedCollection KeyedCollection_Factory::Default_ (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)\n {\n \/*\n * Note - though this is not an efficient implementation of KeyedCollection<> for large sizes, its probably the most\n * efficeint representation which adds no requirements to KEY_TYPE, such as operator< (or a traits less) or\n * a hash function. And its quite reasonable for small KeyedCollection's - which are often the case.\n *\n * Calls may use an explicit initializer of KeyedCollection_xxx<> to get better performance for large sized\n * maps.\n *\/\n return Concrete::KeyedCollection_LinkedList{keyExtractor, keyComparer};\n }\n\n}\n\n#endif \/* _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_ *\/\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#ifndef itkGradientDescentLineSearchOptimizerv4_hxx\n#define itkGradientDescentLineSearchOptimizerv4_hxx\n\n#include \"itkGradientDescentLineSearchOptimizerv4.h\"\n\nnamespace itk\n{\n\n\/**\n * Default constructor\n *\/\ntemplate\nGradientDescentLineSearchOptimizerv4Template\n::GradientDescentLineSearchOptimizerv4Template()\n{\n this->m_MaximumLineSearchIterations = 20;\n this->m_LineSearchIterations = NumericTraits::ZeroValue();\n this->m_LowerLimit = itk::NumericTraits< TInternalComputationValueType >::ZeroValue();\n this->m_UpperLimit = 5.0;\n this->m_Phi = 1.618034;\n this->m_Resphi = 2 - this->m_Phi;\n this->m_Epsilon = 0.01;\n this->m_ReturnBestParametersAndValue = true;\n}\n\n\/**\n* Destructor\n*\/\ntemplate\nGradientDescentLineSearchOptimizerv4Template\n::~GradientDescentLineSearchOptimizerv4Template() = default;\n\n\n\/**\n*PrintSelf\n*\/\ntemplate\nvoid\nGradientDescentLineSearchOptimizerv4Template\n::PrintSelf(std::ostream & os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n }\n\n\/**\n* Advance one Step following the gradient direction\n*\/\ntemplate\nvoid\nGradientDescentLineSearchOptimizerv4Template\n::AdvanceOneStep()\n{\n itkDebugMacro(\"AdvanceOneStep\");\n\n \/* Modify the gradient by scales once at the begin *\/\n this->ModifyGradientByScales();\n\n \/* This will estimate the learning rate (m_LearningRate)\n * if the options are set to do so. We only ever want to\n * estimate at the first step for this class. *\/\n if ( this->m_CurrentIteration == 0 )\n {\n this->EstimateLearningRate();\n }\n\n this->m_LineSearchIterations = 0;\n this->m_LearningRate = this->GoldenSectionSearch( this->m_LearningRate * this->m_LowerLimit ,\n this->m_LearningRate , this->m_LearningRate * this->m_UpperLimit );\n\n \/* Begin threaded gradient modification of m_Gradient variable. *\/\n this->ModifyGradientByLearningRate();\n\n try\n {\n \/* Pass gradient to transform and let it do its own updating *\/\n this->m_Metric->UpdateTransformParameters( this->m_Gradient );\n }\n catch ( ExceptionObject & err )\n {\n this->m_StopCondition = Superclass::UPDATE_PARAMETERS_ERROR;\n this->m_StopConditionDescription << \"UpdateTransformParameters error\";\n this->StopOptimization();\n \/\/ Pass exception to caller\n throw err;\n }\n\n this->InvokeEvent( IterationEvent() );\n }\n\n\n\/\/ a and c are the current bounds; the minimum is between them.\n\/\/ b is a center point\n\/\/ f(x) is some mathematical function elsewhere defined\n\/\/ a corresponds to x1; b corresponds to x2; c corresponds to x3\n\/\/ x corresponds to x4\ntemplate\nTInternalComputationValueType\nGradientDescentLineSearchOptimizerv4Template\n::GoldenSectionSearch( TInternalComputationValueType a, TInternalComputationValueType b, TInternalComputationValueType c )\n{\n if ( this->m_LineSearchIterations > this->m_MaximumLineSearchIterations )\n {\n return ( c + a ) \/ 2;\n }\n this->m_LineSearchIterations++;\n\n TInternalComputationValueType x;\n if ( c - b > b - a )\n {\n x = b + this->m_Resphi * ( c - b );\n }\n else\n {\n x = b - this->m_Resphi * ( b - a );\n }\n if ( std::abs( c - a ) < this->m_Epsilon * ( std::abs( b ) + std::abs( x ) ) )\n {\n return ( c + a ) \/ 2;\n }\n\n TInternalComputationValueType metricx, metricb;\n\n {\n \/\/ Cache the learning rate , parameters , gradient\n \/\/ Contain this in a block so these variables go out of\n \/\/ scope before we call recursively below. With dense transforms\n \/\/ we would otherwise eat up a lot of memory unnecessarily.\n TInternalComputationValueType baseLearningRate = this->m_LearningRate;\n DerivativeType baseGradient( this->m_Gradient );\n ParametersType baseParameters( this->GetCurrentPosition() );\n\n this->m_LearningRate = x;\n this->ModifyGradientByLearningRate();\n this->m_Metric->UpdateTransformParameters( this->m_Gradient );\n metricx = this->GetMetric()->GetValue( );\n\n \/** reset position of transform and gradient *\/\n this->m_Metric->SetParameters( baseParameters );\n this->m_Gradient = baseGradient;\n\n this->m_LearningRate = b;\n this->ModifyGradientByLearningRate();\n\n this->m_Metric->UpdateTransformParameters( this->m_Gradient );\n metricb = this->GetMetric()->GetValue( );\n\n \/** reset position of transform and learning rate *\/\n this->m_Metric->SetParameters( baseParameters );\n this->m_Gradient = baseGradient;\n this->m_LearningRate = baseLearningRate;\n }\n\n \/** golden section *\/\n if ( metricx < metricb )\n {\n if (c - b > b - a)\n {\n return this->GoldenSectionSearch( b, x, c );\n }\n else\n {\n return this->GoldenSectionSearch( a, x, b );\n }\n }\n else\n {\n if ( c - b > b - a )\n {\n return this->GoldenSectionSearch( a, b, x );\n }\n else\n {\n return this->GoldenSectionSearch( x, b, c );\n }\n }\n }\n\n}\/\/namespace itk\n\n#endif\nBUG: Handle boundary case with max metric\/*=========================================================================\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 itkGradientDescentLineSearchOptimizerv4_hxx\n#define itkGradientDescentLineSearchOptimizerv4_hxx\n\n#include \"itkGradientDescentLineSearchOptimizerv4.h\"\n\nnamespace itk\n{\n\n\/**\n * Default constructor\n *\/\ntemplate\nGradientDescentLineSearchOptimizerv4Template\n::GradientDescentLineSearchOptimizerv4Template()\n{\n this->m_MaximumLineSearchIterations = 20;\n this->m_LineSearchIterations = NumericTraits::ZeroValue();\n this->m_LowerLimit = itk::NumericTraits< TInternalComputationValueType >::ZeroValue();\n this->m_UpperLimit = 5.0;\n this->m_Phi = 1.618034;\n this->m_Resphi = 2 - this->m_Phi;\n this->m_Epsilon = 0.01;\n this->m_ReturnBestParametersAndValue = true;\n}\n\n\/**\n* Destructor\n*\/\ntemplate\nGradientDescentLineSearchOptimizerv4Template\n::~GradientDescentLineSearchOptimizerv4Template() = default;\n\n\n\/**\n*PrintSelf\n*\/\ntemplate\nvoid\nGradientDescentLineSearchOptimizerv4Template\n::PrintSelf(std::ostream & os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n }\n\n\/**\n* Advance one Step following the gradient direction\n*\/\ntemplate\nvoid\nGradientDescentLineSearchOptimizerv4Template\n::AdvanceOneStep()\n{\n itkDebugMacro(\"AdvanceOneStep\");\n\n \/* Modify the gradient by scales once at the begin *\/\n this->ModifyGradientByScales();\n\n \/* This will estimate the learning rate (m_LearningRate)\n * if the options are set to do so. We only ever want to\n * estimate at the first step for this class. *\/\n if ( this->m_CurrentIteration == 0 )\n {\n this->EstimateLearningRate();\n }\n\n this->m_LineSearchIterations = 0;\n this->m_LearningRate = this->GoldenSectionSearch( this->m_LearningRate * this->m_LowerLimit ,\n this->m_LearningRate , this->m_LearningRate * this->m_UpperLimit );\n\n \/* Begin threaded gradient modification of m_Gradient variable. *\/\n this->ModifyGradientByLearningRate();\n\n try\n {\n \/* Pass gradient to transform and let it do its own updating *\/\n this->m_Metric->UpdateTransformParameters( this->m_Gradient );\n }\n catch ( ExceptionObject & err )\n {\n this->m_StopCondition = Superclass::UPDATE_PARAMETERS_ERROR;\n this->m_StopConditionDescription << \"UpdateTransformParameters error\";\n this->StopOptimization();\n \/\/ Pass exception to caller\n throw err;\n }\n\n this->InvokeEvent( IterationEvent() );\n }\n\n\n\/\/ a and c are the current bounds; the minimum is between them.\n\/\/ b is a center point\n\/\/ f(x) is some mathematical function elsewhere defined\n\/\/ a corresponds to x1; b corresponds to x2; c corresponds to x3\n\/\/ x corresponds to x4\ntemplate\nTInternalComputationValueType\nGradientDescentLineSearchOptimizerv4Template\n::GoldenSectionSearch( TInternalComputationValueType a, TInternalComputationValueType b, TInternalComputationValueType c )\n{\n if ( this->m_LineSearchIterations > this->m_MaximumLineSearchIterations )\n {\n return ( c + a ) \/ 2;\n }\n this->m_LineSearchIterations++;\n\n TInternalComputationValueType x;\n if ( c - b > b - a )\n {\n x = b + this->m_Resphi * ( c - b );\n }\n else\n {\n x = b - this->m_Resphi * ( b - a );\n }\n if ( std::abs( c - a ) < this->m_Epsilon * ( std::abs( b ) + std::abs( x ) ) )\n {\n return ( c + a ) \/ 2;\n }\n\n TInternalComputationValueType metricx, metricb;\n\n {\n \/\/ Cache the learning rate , parameters , gradient\n \/\/ Contain this in a block so these variables go out of\n \/\/ scope before we call recursively below. With dense transforms\n \/\/ we would otherwise eat up a lot of memory unnecessarily.\n TInternalComputationValueType baseLearningRate = this->m_LearningRate;\n DerivativeType baseGradient( this->m_Gradient );\n ParametersType baseParameters( this->GetCurrentPosition() );\n\n this->m_LearningRate = x;\n this->ModifyGradientByLearningRate();\n this->m_Metric->UpdateTransformParameters( this->m_Gradient );\n metricx = this->GetMetric()->GetValue( );\n\n \/** reset position of transform and gradient *\/\n this->m_Metric->SetParameters( baseParameters );\n this->m_Gradient = baseGradient;\n\n this->m_LearningRate = b;\n this->ModifyGradientByLearningRate();\n\n this->m_Metric->UpdateTransformParameters( this->m_Gradient );\n metricb = this->GetMetric()->GetValue( );\n\n \/** reset position of transform and learning rate *\/\n this->m_Metric->SetParameters( baseParameters );\n this->m_Gradient = baseGradient;\n this->m_LearningRate = baseLearningRate;\n }\n\n \/** golden section *\/\n if ( metricx < metricb )\n {\n if (c - b > b - a)\n {\n return this->GoldenSectionSearch( b, x, c );\n }\n else\n {\n return this->GoldenSectionSearch( a, x, b );\n }\n }\n else\n {\n if ( c - b > b - a )\n {\n return this->GoldenSectionSearch( a, b, x );\n }\n else if ( metricx == NumericTraits::max() )\n {\n \/\/ Keep the lower bounds when metricx and metricb are both max,\n \/\/ likely due to no valid sample points, from too large of a\n \/\/ learning rate.\n return this->GoldenSectionSearch( a, x, b );\n }\n else\n {\n return this->GoldenSectionSearch( x, b, c );\n }\n }\n }\n\n}\/\/namespace itk\n\n#endif\n<|endoftext|>"} {"text":"Answer to question 5.5 is complete and close issue #46<|endoftext|>"} {"text":"\/\/===- 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 \"Support\/CommandLine.h\"\n#include \"Support\/FileUtilities.h\"\n#include \"Config\/fcntl.h\"\n#include \"Config\/sys\/mman.h\"\n#include \n#include \n\nusing namespace llvm;\n\nnamespace {\n cl::opt\n File1(cl::Positional, cl::desc(\"\"), cl::Required);\n cl::opt\n File2(cl::Positional, cl::desc(\"\"), cl::Required);\n\n cl::opt\n RelTolerance(\"r\", cl::desc(\"Relative error tolerated\"), cl::init(0));\n cl::opt\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 int FD = open(Filename.c_str(), O_RDONLY);\n if (FD == -1 || (Len = getFileSize(Filename)) == ~0U) {\n std::cerr << \"Error: cannot open file '\" << Filename << \"'\\n\";\n exit(2);\n }\n\n \/\/ mmap in the file all at once...\n BufPtr = (char*)mmap(0, Len, PROT_READ, MAP_PRIVATE, FD, 0);\n \n if (BufPtr == (char*)MAP_FAILED) {\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 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 = strtod(F1P, &F1NumEnd);\n double V2 = strtod(F2P, &F2NumEnd);\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\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 while (1) {\n \/\/ Scan for the end of file or first 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 if (F1P >= File1End && F2P >= File2End) return 0;\n\n \/\/ Otherwise, we might have run off the end due to a number, backup and retry.\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\nmmap of a zero length file returns null on some platforms, so hack around it.\/\/===- 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 \"Support\/CommandLine.h\"\n#include \"Support\/FileUtilities.h\"\n#include \"Config\/fcntl.h\"\n#include \"Config\/sys\/mman.h\"\n#include \n#include \n\nusing namespace llvm;\n\nnamespace {\n cl::opt\n File1(cl::Positional, cl::desc(\"\"), cl::Required);\n cl::opt\n File2(cl::Positional, cl::desc(\"\"), cl::Required);\n\n cl::opt\n RelTolerance(\"r\", cl::desc(\"Relative error tolerated\"), cl::init(0));\n cl::opt\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 int FD = open(Filename.c_str(), O_RDONLY);\n if (FD == -1 || (Len = getFileSize(Filename)) == ~0U) {\n std::cerr << \"Error: cannot open file '\" << Filename << \"'\\n\";\n exit(2);\n }\n\n \/\/ mmap in the file all at once...\n BufPtr = (char*)mmap(0, Len, PROT_READ, MAP_PRIVATE, FD, 0);\n \n if (BufPtr == (char*)MAP_FAILED) {\n std::cerr << \"Error: cannot open file '\" << Filename << \"'\\n\";\n exit(2);\n }\n\n \/\/ If mmap decided that the files were empty, it might have returned a\n \/\/ null pointer. If so, make a new, fake pointer -- it shouldn't matter\n \/\/ what it contains, because Len is 0, and it should never be read.\n if (BufPtr == 0 && Len == 0)\n BufPtr = new char[1];\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 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 = strtod(F1P, &F1NumEnd);\n double V2 = strtod(F2P, &F2NumEnd);\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\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 while (1) {\n \/\/ Scan for the end of file or first 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 if (F1P >= File1End && F2P >= File2End) return 0;\n\n \/\/ Otherwise, we might have run off the end due to a number, backup and retry.\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<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ik_ce.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 11:48: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#ifndef ARY_IDL_IK_CE_HXX\n#define ARY_IDL_IK_CE_HXX\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ COMPONENTS\n \/\/ PARAMETERS\n#include \n#include \n\nnamespace ary\n{\nnamespace info\n{\n class Text;\n}\nnamespace idl\n{\n\n\nnamespace ifc_ce\n{\n\n\ntypedef ::ary::Dyn_StdConstIterator Dyn_CeIterator;\ntypedef ::ary::Dyn_StdConstIterator Dyn_TypeIterator;\ntypedef ::ary::info::Text DocText;\n\n\n\nstruct attr\n{\n static Ce_id CeId(\n const CodeEntity & i_ce );\n static const String &\n LocalName(\n const CodeEntity & i_ce );\n static Ce_id NameRoom(\n const CodeEntity & i_ce );\n static Rid Owner(\n const CodeEntity & i_ce );\n static E_SightLevel SightLevel(\n const CodeEntity & i_ce );\n static bool Search_Member(\n const CodeEntity & ,\n const String & )\n { return true; } \/\/ KORR_FUTURE\n};\n\nstruct xref\n{\n};\n\nstruct doc\n{\n static const DocText &\n ShortInfo( \/\/\/ @return a short description of the CodeEntity\n const CodeEntity & i_ce );\n\n static const DocText &\n TagAuthor(\n const CodeEntity & i_ce );\n static const DocText &\n TagExample(\n const CodeEntity & i_ce );\n static const DocText &\n TagDescr(\n const CodeEntity & i_ce );\n static const DocText &\n TagGuarantees(\n const CodeEntity & i_ce );\n static const DocText &\n TagKey(\n const CodeEntity & i_ce );\n static const DocText &\n TagMissing(\n const CodeEntity & i_ce );\n static const DocText &\n TagSee(\n const CodeEntity & i_ce );\n static const DocText &\n TagShort(\n const CodeEntity & i_ce );\n static const DocText &\n TagVersion(\n const CodeEntity & i_ce );\n\n void Get_UnkownTags(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n\n bool IsDeprecated(\n const CodeEntity & i_ce );\n bool IsIncomplete(\n const CodeEntity & i_ce );\n bool IsInternal(\n const CodeEntity & i_ce );\n bool IsNodoc(\n const CodeEntity & i_ce );\n bool IsOptional(\n const CodeEntity & i_ce );\n bool IsSuspicious(\n const CodeEntity & i_ce );\n\n};\n\n\n} \/\/ namespace ifc_ce\n\n\n} \/\/ namspace idl\n} \/\/ namspace ary\n\n#endif\n\n\nINTEGRATION: CWS adc18 (1.3.32); FILE MERGED 2007\/10\/18 13:06:37 np 1.3.32.1: #i81775#\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ik_ce.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2007-11-02 15:13: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#ifndef ARY_IDL_IK_CE_HXX\n#define ARY_IDL_IK_CE_HXX\n\/\/ KORR_DEPRECATED_3.0\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ COMPONENTS\n \/\/ PARAMETERS\n#include \n#include \n\nnamespace ary\n{\nnamespace info\n{\n class Text;\n}\nnamespace idl\n{\n\n\nnamespace ifc_ce\n{\n\n\ntypedef ::ary::Dyn_StdConstIterator Dyn_CeIterator;\ntypedef ::ary::Dyn_StdConstIterator Dyn_TypeIterator;\ntypedef ::ary::info::Text DocText;\n\n\n\nstruct attr\n{\n static Ce_id CeId(\n const CodeEntity & i_ce );\n static const String &\n LocalName(\n const CodeEntity & i_ce );\n static Ce_id NameRoom(\n const CodeEntity & i_ce );\n static Rid Owner(\n const CodeEntity & i_ce );\n static E_SightLevel SightLevel(\n const CodeEntity & i_ce );\n static bool Search_Member(\n const CodeEntity & ,\n const String & )\n { return true; } \/\/ KORR_FUTURE\n};\n\nstruct xref\n{\n};\n\nstruct doc\n{\n static const DocText &\n ShortInfo( \/\/\/ @return a short description of the CodeEntity\n const CodeEntity & i_ce );\n\n static const DocText &\n TagAuthor(\n const CodeEntity & i_ce );\n static const DocText &\n TagExample(\n const CodeEntity & i_ce );\n static const DocText &\n TagDescr(\n const CodeEntity & i_ce );\n static const DocText &\n TagGuarantees(\n const CodeEntity & i_ce );\n static const DocText &\n TagKey(\n const CodeEntity & i_ce );\n static const DocText &\n TagMissing(\n const CodeEntity & i_ce );\n static const DocText &\n TagSee(\n const CodeEntity & i_ce );\n static const DocText &\n TagShort(\n const CodeEntity & i_ce );\n static const DocText &\n TagVersion(\n const CodeEntity & i_ce );\n\n void Get_UnkownTags(\n Dyn_CeIterator & o_result,\n const CodeEntity & i_ce );\n\n bool IsDeprecated(\n const CodeEntity & i_ce );\n bool IsIncomplete(\n const CodeEntity & i_ce );\n bool IsInternal(\n const CodeEntity & i_ce );\n bool IsNodoc(\n const CodeEntity & i_ce );\n bool IsOptional(\n const CodeEntity & i_ce );\n bool IsSuspicious(\n const CodeEntity & i_ce );\n\n};\n\n\n} \/\/ namespace ifc_ce\n\n\n} \/\/ namspace idl\n} \/\/ namspace ary\n\n#endif\n\n\n<|endoftext|>"} {"text":"\/\/---------------------------- vertex_as_face_05.cc ---------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2010 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\/\/---------------------------- vertex_as_face_05.cc ---------------------------\n\n\/\/ verify that we can do things like cell->face() in 1d as well. here:\n\/\/ test DoFHandler accessors for the same thing as the _01 test\n\n\n#include \"..\/tests.h\"\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n\ntemplate \nvoid test ()\n{\n Triangulation<1,spacedim> tria;\n GridGenerator::hyper_cube (tria);\n\n FESystem<1,spacedim> fe(FE_Q<1,spacedim>(2),2,\n\t\t\t FE_Q<1,spacedim>(1),1);\n DoFHandler<1,spacedim> dof_handler (tria);\n dof_handler.distribute_dofs (fe);\n\n deallog << \"Coarse mesh:\" << std::endl;\n deallog << \"Left vertex=\" << dof_handler.begin_active()->face(0)->vertex(0) << std::endl;\n deallog << \"Right vertex=\" << dof_handler.begin_active()->face(1)->vertex(0) << std::endl;\n\n tria.refine_global (2);\n dof_handler.distribute_dofs (fe);\n\n for (typename Triangulation<1,spacedim>::active_cell_iterator\n\t cell = dof_handler.begin_active();\n cell != dof_handler.end(); ++cell)\n {\n deallog << \"Cell: \" << cell << std::endl;\n deallog << \"Left vertex=\" << cell->face(0)->vertex(0) << std::endl;\n deallog << \"Right vertex=\" << cell->face(1)->vertex(0) << std::endl;\n }\n}\n\n\n\nint main ()\n{\n std::ofstream logfile(\"vertex_as_face_05\/output\");\n deallog.attach(logfile);\n deallog.depth_console(0);\n\n test<1> ();\n test<2> ();\n\n return 0;\n}\nFix type of iterator.\/\/---------------------------- vertex_as_face_05.cc ---------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2010 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\/\/---------------------------- vertex_as_face_05.cc ---------------------------\n\n\/\/ verify that we can do things like cell->face() in 1d as well. here:\n\/\/ test DoFHandler accessors for the same thing as the _01 test\n\n\n#include \"..\/tests.h\"\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n\ntemplate \nvoid test ()\n{\n Triangulation<1,spacedim> tria;\n GridGenerator::hyper_cube (tria);\n\n FESystem<1,spacedim> fe(FE_Q<1,spacedim>(2),2,\n\t\t\t FE_Q<1,spacedim>(1),1);\n DoFHandler<1,spacedim> dof_handler (tria);\n dof_handler.distribute_dofs (fe);\n\n deallog << \"Coarse mesh:\" << std::endl;\n deallog << \"Left vertex=\" << dof_handler.begin_active()->face(0)->vertex(0) << std::endl;\n deallog << \"Right vertex=\" << dof_handler.begin_active()->face(1)->vertex(0) << std::endl;\n\n tria.refine_global (2);\n dof_handler.distribute_dofs (fe);\n\n for (typename DoFHandler<1,spacedim>::active_cell_iterator\n\t cell = dof_handler.begin_active();\n cell != dof_handler.end(); ++cell)\n {\n deallog << \"Cell: \" << cell << std::endl;\n deallog << \"Left vertex=\" << cell->face(0)->vertex(0) << std::endl;\n deallog << \"Right vertex=\" << cell->face(1)->vertex(0) << std::endl;\n }\n}\n\n\n\nint main ()\n{\n std::ofstream logfile(\"vertex_as_face_05\/output\");\n deallog.attach(logfile);\n deallog.depth_console(0);\n\n test<1> ();\n test<2> ();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n\n This source file is part of the Avogadro project.\n\n Copyright 2013 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 \"gromacsformat.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing Avogadro::Core::Atom;\nusing Avogadro::Core::Molecule;\nusing Avogadro::Core::UnitCell;\nusing Avogadro::Core::lexicalCast;\nusing Avogadro::Core::trimmed;\nusing Avogadro::Core::split;\n\nnamespace Avogadro {\nnamespace Io {\n\nGromacsFormat::GromacsFormat()\n{\n}\n\nGromacsFormat::~GromacsFormat()\n{\n}\n\nstd::vector GromacsFormat::fileExtensions() const\n{\n return std::vector(1, std::string(\"gro\"));\n}\n\nstd::vector GromacsFormat::mimeTypes() const\n{\n return std::vector(1, std::string(\"chemical\/x-gro\"));\n}\n\nbool GromacsFormat::read(std::istream &in, Molecule &molecule)\n{\n std::string buffer;\n std::string value;\n\n \/\/ Title\n std::getline(in, buffer);\n if (!buffer.empty())\n molecule.setData(\"name\", trimmed(buffer));\n\n \/\/ Atom count\n std::getline(in, buffer);\n buffer = trimmed(buffer);\n bool ok;\n size_t numAtoms = lexicalCast(buffer, ok);\n if (buffer.empty() || !ok) {\n appendError(\"Number of atoms (line 2) invalid.\");\n return false;\n }\n\n \/\/ read atom info:\n typedef std::map AtomTypeMap;\n AtomTypeMap atomTypes;\n unsigned char customElementCounter = CustomElementMin;\n Vector3 pos;\n while (numAtoms-- > 0) {\n std::getline(in, buffer);\n if (buffer.size() < 44) {\n appendError(\"Error reading atom specification -- line too short: \"\n + buffer);\n return false;\n }\n\n \/\/ Format of buffer is: (all indices start at 1)\n \/\/ Offset: 0 format: %5i value: Residue number\n \/\/ Offset: 5 format: %-5s value: Residue name\n \/\/ Offset: 10 format: %5s value: Atom name\n \/\/ Offset: 15 format: %5i value: Atom number\n \/\/ Offset: 20 format: %8.3f value: x coordinate (nm)\n \/\/ Offset: 28 format: %8.3f value: y coordinate (nm)\n \/\/ Offset: 36 format: %8.3f value: z coordinate (nm)\n \/\/ Offset: 44 format: %8.4f value: x velocity (nm\/ps, a.k.a. km\/s)\n \/\/ Offset: 52 format: %8.4f value: y velocity (nm\/ps, a.k.a. km\/s)\n \/\/ Offset: 60 format: %8.4f value: z velocity (nm\/ps, a.k.a. km\/s)\n\n \/\/ Atom name:\n value = trimmed(buffer.substr(10, 5));\n AtomTypeMap::const_iterator it = atomTypes.find(value);\n if (it == atomTypes.end()) {\n atomTypes.insert(std::make_pair(value, customElementCounter++));\n it = atomTypes.find(value);\n if (customElementCounter > CustomElementMax) {\n appendError(\"Custom element type limit exceeded.\");\n return false;\n }\n }\n Atom atom = molecule.addAtom(it->second);\n\n \/\/ Coords\n for (int i = 0; i < 3; ++i) {\n value = trimmed(buffer.substr(20 + i * 8, 8));\n pos[i] = lexicalCast(value, ok);\n if (!ok || value.empty()) {\n appendError(\"Error reading atom specification -- invalid coordinate: '\"\n + buffer + \"' (bad coord: '\" + value + \"')\");\n return false;\n }\n }\n atom.setPosition3d(pos * static_cast(10.0)); \/\/ nm --> Angstrom\n }\n\n \/\/ Set the custom element map if needed:\n if (!atomTypes.empty()) {\n Molecule::CustomElementMap elementMap;\n for (AtomTypeMap::const_iterator it = atomTypes.begin(),\n itEnd = atomTypes.end(); it != itEnd; ++it) {\n elementMap.insert(std::make_pair(it->second, it->first));\n }\n molecule.setCustomElementMap(elementMap);\n }\n\n \/\/ Box description:\n \/\/ v1(x) v2(y) v3(z) [v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)]\n \/\/ The last six values may be omitted, set all non-specified values to 0.\n \/\/ v1(y) == v1(z) == v2(z) == 0 always.\n std::getline(in, buffer);\n std::vector tokens(split(buffer, ' ', true));\n if (tokens.size() > 0) {\n if (tokens.size() != 3 && tokens.size() != 9) {\n appendError(\"Invalid box specification -- need either 3 or 9 values: '\"\n + buffer + \"'\");\n return false;\n }\n\n \/\/ Index arrays for parsing loop:\n const int rows[] = {0, 1, 2, 1, 2, 0, 2, 0, 1};\n const int cols[] = {0, 1, 2, 0, 0, 1, 1, 2, 2};\n\n Matrix3 cellMatrix = Matrix3::Zero();\n for (size_t i = 0; i < tokens.size(); ++i) {\n cellMatrix(rows[i], cols[i]) = lexicalCast(tokens[i], ok);\n if (!ok || tokens[i].empty()) {\n appendError(\"Invalid box specification -- bad value: '\"\n + tokens[i] + \"'\");\n return false;\n }\n }\n\n UnitCell *cell = new UnitCell;\n cell->setCellMatrix(cellMatrix * static_cast(10)); \/\/ nm --> Angstrom\n molecule.setUnitCell(cell);\n }\n\n return true;\n}\n\nbool GromacsFormat::write(std::ostream &, const Core::Molecule &)\n{\n return false;\n}\n\n} \/\/ namespace Io\n} \/\/ namespace Avogadro\nAdded some code to deal with variable decimal places\/******************************************************************************\n\n This source file is part of the Avogadro project.\n\n Copyright 2013 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 \"gromacsformat.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\nnamespace Avogadro {\nnamespace Io {\n\nusing Core::Atom;\nusing Core::Molecule;\nusing Core::UnitCell;\nusing Core::lexicalCast;\nusing Core::trimmed;\nusing Core::split;\n\nusing std::string;\nusing std::getline;\nusing std::map;\nusing std::vector;\n\nGromacsFormat::GromacsFormat()\n{\n}\n\nGromacsFormat::~GromacsFormat()\n{\n}\n\nstd::vector GromacsFormat::fileExtensions() const\n{\n return std::vector(1, std::string(\"gro\"));\n}\n\nstd::vector GromacsFormat::mimeTypes() const\n{\n return std::vector(1, std::string(\"chemical\/x-gro\"));\n}\n\nbool GromacsFormat::read(std::istream &in, Molecule &molecule)\n{\n string buffer;\n string value;\n\n \/\/ Title\n getline(in, buffer);\n if (!buffer.empty())\n molecule.setData(\"name\", trimmed(buffer));\n\n \/\/ Atom count\n getline(in, buffer);\n buffer = trimmed(buffer);\n bool ok;\n size_t numAtoms = lexicalCast(buffer, ok);\n if (buffer.empty() || !ok) {\n appendError(\"Number of atoms (line 2) invalid.\");\n return false;\n }\n\n \/\/ read atom info:\n typedef map AtomTypeMap;\n AtomTypeMap atomTypes;\n unsigned char customElementCounter = CustomElementMin;\n Vector3 pos;\n while (numAtoms-- > 0) {\n getline(in, buffer);\n \/\/ Figure out the distance between decimal points, implement support for\n \/\/ variable precision as specified:\n \/\/ \"any number of decimal places, the format will then be n+5 positions with\n \/\/ n decimal places (n+1 for velocities) in stead of 8 with 3 (with 4 for\n \/\/ velocities)\".\n size_t decimal1 = buffer.find(\".\", 20);\n size_t decimal2 = string::npos;\n int decimalSep = 0;\n if (decimal1 != string::npos)\n decimal2 = buffer.find(\".\", decimal1 + 1);\n if (decimal2 != string::npos)\n decimalSep = decimal2 - decimal1;\n if (decimalSep == 0) {\n appendError(\"Decimal separation of 0 found in atom positions: \" + buffer);\n return false;\n }\n\n if (buffer.size() < static_cast(20 + 3 * decimalSep)) {\n appendError(\"Error reading atom specification -- line too short: \"\n + buffer);\n return false;\n }\n\n \/\/ Format of buffer is: (all indices start at 1, variable dp throws this).\n \/\/ Offset: 0 format: %5i value: Residue number\n \/\/ Offset: 5 format: %-5s value: Residue name\n \/\/ Offset: 10 format: %5s value: Atom name\n \/\/ Offset: 15 format: %5i value: Atom number\n \/\/ Offset: 20 format: %8.3f value: x coordinate (nm)\n \/\/ Offset: 28 format: %8.3f value: y coordinate (nm)\n \/\/ Offset: 36 format: %8.3f value: z coordinate (nm)\n \/\/ Offset: 44 format: %8.4f value: x velocity (nm\/ps, a.k.a. km\/s)\n \/\/ Offset: 52 format: %8.4f value: y velocity (nm\/ps, a.k.a. km\/s)\n \/\/ Offset: 60 format: %8.4f value: z velocity (nm\/ps, a.k.a. km\/s)\n\n \/\/ Atom name:\n value = trimmed(buffer.substr(10, 5));\n AtomTypeMap::const_iterator it = atomTypes.find(value);\n if (it == atomTypes.end()) {\n atomTypes.insert(std::make_pair(value, customElementCounter++));\n it = atomTypes.find(value);\n if (customElementCounter > CustomElementMax) {\n appendError(\"Custom element type limit exceeded.\");\n return false;\n }\n }\n Atom atom = molecule.addAtom(it->second);\n\n \/\/ Coords\n for (int i = 0; i < 3; ++i) {\n value = trimmed(buffer.substr(20 + i * decimalSep, decimalSep));\n pos[i] = lexicalCast(value, ok);\n if (!ok || value.empty()) {\n appendError(\"Error reading atom specification -- invalid coordinate: '\"\n + buffer + \"' (bad coord: '\" + value + \"')\");\n return false;\n }\n }\n atom.setPosition3d(pos * static_cast(10.0)); \/\/ nm --> Angstrom\n }\n\n \/\/ Set the custom element map if needed:\n if (!atomTypes.empty()) {\n Molecule::CustomElementMap elementMap;\n for (AtomTypeMap::const_iterator it = atomTypes.begin(),\n itEnd = atomTypes.end(); it != itEnd; ++it) {\n elementMap.insert(std::make_pair(it->second, it->first));\n }\n molecule.setCustomElementMap(elementMap);\n }\n\n \/\/ Box description:\n \/\/ v1(x) v2(y) v3(z) [v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)]\n \/\/ The last six values may be omitted, set all non-specified values to 0.\n \/\/ v1(y) == v1(z) == v2(z) == 0 always.\n getline(in, buffer);\n vector tokens(split(buffer, ' ', true));\n if (tokens.size() > 0) {\n if (tokens.size() != 3 && tokens.size() != 9) {\n appendError(\"Invalid box specification -- need either 3 or 9 values: '\"\n + buffer + \"'\");\n return false;\n }\n\n \/\/ Index arrays for parsing loop:\n const int rows[] = {0, 1, 2, 1, 2, 0, 2, 0, 1};\n const int cols[] = {0, 1, 2, 0, 0, 1, 1, 2, 2};\n\n Matrix3 cellMatrix = Matrix3::Zero();\n for (size_t i = 0; i < tokens.size(); ++i) {\n cellMatrix(rows[i], cols[i]) = lexicalCast(tokens[i], ok);\n if (!ok || tokens[i].empty()) {\n appendError(\"Invalid box specification -- bad value: '\"\n + tokens[i] + \"'\");\n return false;\n }\n }\n\n UnitCell *cell = new UnitCell;\n cell->setCellMatrix(cellMatrix * static_cast(10)); \/\/ nm --> Angstrom\n molecule.setUnitCell(cell);\n }\n\n return true;\n}\n\nbool GromacsFormat::write(std::ostream &, const Core::Molecule &)\n{\n return false;\n}\n\n} \/\/ namespace Io\n} \/\/ namespace Avogadro\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Typedef for our primary data types\ntypedef std::vector pages_t;\ntypedef std::unordered_map page_ids_t;\ntypedef std::unordered_map> page_links_t;\n\n\/* Load in the page titles and page ids from a file.\n *\n * Each line of the file will represent the page ID, starting from line 1 until\n * the end of the file. The page titles will be stored into the pages vector.\n * The page titles => ids will be stored in the page_ids map\n *\n * Returns: The total number of pages loaded\n *\/\nint load_page_titles(const std::string &file_path, pages_t &pages, page_ids_t &page_ids)\n{\n\tstd::ifstream page_titles_file(file_path);\n\tstd::string page_name;\n\n\t\/\/ We won't be using the first index of the vector for anything since\n\t\/\/ the page_id indexes start at 1 instead of 0. This should help to\n\t\/\/ prevent any errors during development\n\tpages.push_back(\"\");\n\n\t\/\/ Read the page name into the vector and into the hash-map\n\tint index = 1;\n\n\twhile (std::getline(page_titles_file, page_name))\n\t{\n\t\tpages.push_back(page_name);\n\t\tpage_ids[page_name] = index++;\n\t}\n\n\treturn index - 1;\n}\n\n\/* Load in the page links from a file.\n *\n * Each line of the file should start with a page_id that represents a page, it\n * should then follow with a colon (':'). All numbers after the colon represent\n * page_ids that that page links to.\n *\n * Read all page links into the page_links hash map, where the key is the\n * page_id and the value is a vector of page_ids the page links to.\n *\n * Returns: The total number of links loaded\n *\/\nint load_page_links(const std::string &file_path, page_links_t &page_links)\n{\n\tstd::ifstream page_links_file(file_path);\n\tstd::string link_id;\n\n\tint current_link = 0;\n\tint total_links = 0;\n\n\twhile (page_links_file >> link_id)\n\t{\n\t\tif (link_id.back() == ':')\n\t\t{\n\t\t\tcurrent_link = atoi(link_id.c_str());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpage_links[current_link].push_back(atoi(link_id.c_str()));\n\t\t\ttotal_links++;\n\t\t}\n\t}\n\n\treturn total_links;\n}\n\n\/* Given a hash map containing page_ids that represent a path back to a given\n * root node extract those Ids and order them so that we move from the root node\n * back to the tail_id.\n *\n * The root node is the node whos parent value is -1.\n *\n * Returns: A vector containing the page ids of the path in order.\n *\/\nstd::vector path_from_parents(std::unordered_map &parent_links,\n\tint target_id)\n{\n\tint current = target_id;\n\tstd::vector target_path;\n\n\t\/\/ Only fill the target_path vector if we have a parent link chain\n\tif (parent_links[target_id])\n\t{\n\t\t\/\/ Traverse thrugh the parent_links till we reach the root node\n\t\tdo\n\t\t{\n\t\t\ttarget_path.push_back(current);\n\t\t}\n\t\twhile ((current = parent_links[current]) != -1);\n\n\t\t\/\/ Reverse the target path list to be in proper order\n\t\tstd::reverse(target_path.begin(), target_path.end());\n\t}\n\n\treturn target_path;\n}\n\n\/* Calculate the shortest path between two page_ids in the page links graph.\n * This uses the Depth First Search algorithm to travers through each of the\n * child nodes looking to see if they are the target id. If none are, then we\n * will traverse through all their children, up until we can find the target id.\n *\n * Returns: See the return value of `path_from_parents`.\n *\/\nstd::vector path_between_pages(page_links_t &page_links,\n\tint start_id, int target_id)\n{\n\t\/\/ Keep track of parent nodes so we can traverse back through the path\n\tstd::unordered_map parent_links;\n\n\t\/\/ The starting node will always be considered 'visited'\n\tparent_links[start_id] = -1;\n\n\t\/\/ Queue of the current nodes to look at\n\tstd::deque current_nodes;\n\tcurrent_nodes.push_back(start_id);\n\n\tbool found_target = false;\n\n\t\/\/ Search until we find our target node\n\twhile ( ! found_target && ! current_nodes.empty())\n\t{\n\t\tint available_nodes = current_nodes.size();\n\n\t\t#pragma omp parallel for\n\t\tfor (int i = 0; i < available_nodes; ++i)\n\t\t{\n\t\t\t\/\/ Since we can't break out of parallelize loops we just need to\n\t\t\t\/\/ finish off what evers left by continuing through them all\n\t\t\t#pragma omp flush (found_target)\n\t\t\tif (found_target) continue;\n\n\t\t\tint current;\n\n\t\t\t#pragma omp critical\n\t\t\t{\n\t\t\t\tcurrent = current_nodes.front();\n\t\t\t\tcurrent_nodes.pop_front();\n\t\t\t}\n\n\t\t\t\/\/ Iterate through all linked pages\n\t\t\tfor (int page_id : page_links[current])\n\t\t\t{\n\t\t\t\t\/\/ Keep track of how we traveled to this node\n\t\t\t\t#pragma omp critical\n\t\t\t\tif (parent_links[page_id] == 0)\n\t\t\t\t{\n\t\t\t\t\tparent_links[page_id] = current;\n\n\t\t\t\t\tif (target_id == page_id)\n\t\t\t\t\t{\n\t\t\t\t\t\tfound_target = true;\n\t\t\t\t\t\t#pragma omp flush (found_target)\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcurrent_nodes.push_back(page_id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn path_from_parents(parent_links, target_id);\n}\n\n\nint main(int argc, char* argv[])\n{\n\tif (argc != 5)\n\t{\n\t\tstd::cerr << \"Path Finder only accepts 4 arguments\\n\";\n\t\texit(1);\n\t}\n\n\t\/\/ Used to store a list of page titles. Each index represents a page title\n\tpages_t pages;\n\n\t\/\/ Used to reverse lookup a page ID by it's title\n\tpage_ids_t page_ids;\n\n\t\/\/ Used to store a list of page_ids that a given page_id links to\n\tpage_links_t page_links;\n\n\t\/\/ Load in all page titles into a vector\n\tstd::cout << \"\\033[92m==>\\033[0m Reading in page titles as a vector & map\\n\";\n\n\t{\n\t\tstruct timeval start, end;\n\n\t\tgettimeofday(&start, 0);\n\t\tint total = load_page_titles(std::string(argv[1]), pages, page_ids);\n\t\tgettimeofday(&end, 0);\n\n\t\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\t\tstd::cout << \"\\033[94m -> \\033[0mRead in \" << total << \" page titles\\n\";\n\t\tstd::cout << \"\\033[94m -> \\033[0mTook \" << duration << \" seconds\\n\";\n\t}\n\n\t\/\/ Load in all page links into a hash map\n\tstd::cout << \"\\033[92m==>\\033[0m Reading in page links as a map\\n\";\n\n\t{\n\t\tstruct timeval start, end;\n\n\t\tgettimeofday(&start, 0);\n\t\tint total = load_page_links(std::string(argv[2]), page_links);\n\t\tgettimeofday(&end, 0);\n\n\t\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\t\tstd::cout << \"\\033[94m -> \\033[0mRead in \" << total << \" page links\\n\";\n\t\tstd::cout << \"\\033[94m -> \\033[0mTook \" << duration << \" seconds\\n\";\n\t}\n\n\tstd::cout << \"\\033[92m==>\\033[0m Beginning BFS on Wikipedia graph\\n\";\n\n\t\/\/ Get the ID's of the start and target nodes\n\tint start_id = page_ids[argv[3]],\n\t target_id = page_ids[argv[4]];\n\n\tif (start_id == target_id)\n\t{\n\t\tstd::cout << \"\\n\\033[92mNo clicks required. The page is the same!\\n\";\n\t}\n\n\tstd::vector target_path;\n\n\tstruct timeval start, end;\n\n\tgettimeofday(&start, 0);\n\ttarget_path = path_between_pages(page_links, start_id, target_id);\n\tgettimeofday(&end, 0);\n\n\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\tstd::cout << \"\\033[94m -> \\033[0mTook \" << duration << \" seconds\\n\\n\";\n\n\t\/\/ Print out the path between the pages\n\tfor (int page_id : target_path)\n\t{\n\t\tstd::cout << \" * \" << pages[page_id] << '\\n';\n\t}\n\n\treturn 0;\n}\nGet data paths from relative bin location#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Typedef for our primary data types\ntypedef std::vector pages_t;\ntypedef std::unordered_map page_ids_t;\ntypedef std::unordered_map> page_links_t;\n\n\/* Load in the page titles and page ids from a file.\n *\n * Each line of the file will represent the page ID, starting from line 1 until\n * the end of the file. The page titles will be stored into the pages vector.\n * The page titles => ids will be stored in the page_ids map\n *\n * Returns: The total number of pages loaded\n *\/\nint load_page_titles(const std::string &file_path, pages_t &pages, page_ids_t &page_ids)\n{\n\tstd::ifstream page_titles_file(file_path);\n\tstd::string page_name;\n\n\t\/\/ We won't be using the first index of the vector for anything since\n\t\/\/ the page_id indexes start at 1 instead of 0. This should help to\n\t\/\/ prevent any errors during development\n\tpages.push_back(\"\");\n\n\t\/\/ Read the page name into the vector and into the hash-map\n\tint index = 1;\n\n\twhile (std::getline(page_titles_file, page_name))\n\t{\n\t\tpages.push_back(page_name);\n\t\tpage_ids[page_name] = index++;\n\t}\n\n\treturn index - 1;\n}\n\n\/* Load in the page links from a file.\n *\n * Each line of the file should start with a page_id that represents a page, it\n * should then follow with a colon (':'). All numbers after the colon represent\n * page_ids that that page links to.\n *\n * Read all page links into the page_links hash map, where the key is the\n * page_id and the value is a vector of page_ids the page links to.\n *\n * Returns: The total number of links loaded\n *\/\nint load_page_links(const std::string &file_path, page_links_t &page_links)\n{\n\tstd::ifstream page_links_file(file_path);\n\tstd::string link_id;\n\n\tint current_link = 0;\n\tint total_links = 0;\n\n\twhile (page_links_file >> link_id)\n\t{\n\t\tif (link_id.back() == ':')\n\t\t{\n\t\t\tcurrent_link = atoi(link_id.c_str());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpage_links[current_link].push_back(atoi(link_id.c_str()));\n\t\t\ttotal_links++;\n\t\t}\n\t}\n\n\treturn total_links;\n}\n\n\/* Given a hash map containing page_ids that represent a path back to a given\n * root node extract those Ids and order them so that we move from the root node\n * back to the tail_id.\n *\n * The root node is the node whos parent value is -1.\n *\n * Returns: A vector containing the page ids of the path in order.\n *\/\nstd::vector path_from_parents(std::unordered_map &parent_links,\n\tint target_id)\n{\n\tint current = target_id;\n\tstd::vector target_path;\n\n\t\/\/ Only fill the target_path vector if we have a parent link chain\n\tif (parent_links[target_id])\n\t{\n\t\t\/\/ Traverse thrugh the parent_links till we reach the root node\n\t\tdo\n\t\t{\n\t\t\ttarget_path.push_back(current);\n\t\t}\n\t\twhile ((current = parent_links[current]) != -1);\n\n\t\t\/\/ Reverse the target path list to be in proper order\n\t\tstd::reverse(target_path.begin(), target_path.end());\n\t}\n\n\treturn target_path;\n}\n\n\/* Calculate the shortest path between two page_ids in the page links graph.\n * This uses the Depth First Search algorithm to travers through each of the\n * child nodes looking to see if they are the target id. If none are, then we\n * will traverse through all their children, up until we can find the target id.\n *\n * Returns: See the return value of `path_from_parents`.\n *\/\nstd::vector path_between_pages(page_links_t &page_links,\n\tint start_id, int target_id)\n{\n\t\/\/ Keep track of parent nodes so we can traverse back through the path\n\tstd::unordered_map parent_links;\n\n\t\/\/ The starting node will always be considered 'visited'\n\tparent_links[start_id] = -1;\n\n\t\/\/ Queue of the current nodes to look at\n\tstd::deque current_nodes;\n\tcurrent_nodes.push_back(start_id);\n\n\tbool found_target = false;\n\n\t\/\/ Search until we find our target node\n\twhile ( ! found_target && ! current_nodes.empty())\n\t{\n\t\tint available_nodes = current_nodes.size();\n\n\t\t#pragma omp parallel for\n\t\tfor (int i = 0; i < available_nodes; ++i)\n\t\t{\n\t\t\t\/\/ Since we can't break out of parallelize loops we just need to\n\t\t\t\/\/ finish off what evers left by continuing through them all\n\t\t\t#pragma omp flush (found_target)\n\t\t\tif (found_target) continue;\n\n\t\t\tint current;\n\n\t\t\t#pragma omp critical\n\t\t\t{\n\t\t\t\tcurrent = current_nodes.front();\n\t\t\t\tcurrent_nodes.pop_front();\n\t\t\t}\n\n\t\t\t\/\/ Iterate through all linked pages\n\t\t\tfor (int page_id : page_links[current])\n\t\t\t{\n\t\t\t\t\/\/ Keep track of how we traveled to this node\n\t\t\t\t#pragma omp critical\n\t\t\t\tif (parent_links[page_id] == 0)\n\t\t\t\t{\n\t\t\t\t\tparent_links[page_id] = current;\n\n\t\t\t\t\tif (target_id == page_id)\n\t\t\t\t\t{\n\t\t\t\t\t\tfound_target = true;\n\t\t\t\t\t\t#pragma omp flush (found_target)\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcurrent_nodes.push_back(page_id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn path_from_parents(parent_links, target_id);\n}\n\n\nint main(int argc, char* argv[])\n{\n\t\/\/ Used to store a list of page titles. Each index represents a page title\n\tpages_t pages;\n\n\t\/\/ Used to reverse lookup a page ID by it's title\n\tpage_ids_t page_ids;\n\n\t\/\/ Used to store a list of page_ids that a given page_id links to\n\tpage_links_t page_links;\n\n\tstd::cout << \"Welcome to Six-Degrees-of-Wikipedia path finder\\n\"\n\t << \"Please while we load Wikipedia into memory.\\n\\n\";\n\n\t\/\/ Determine the base directory path\n\tchar path_buffer[1024];\n\treadlink(\"\/proc\/self\/exe\", path_buffer, sizeof(path_buffer) - 1);\n\tstd::string base_path = std::string(dirname(path_buffer)) + \"\/..\/\";\n\n\t\/\/ Load in all page titles into a vector\n\tstd::cout << \"\\033[92m==>\\033[0m Reading in page titles as a vector & map\\n\";\n\n\t{\n\t\tstruct timeval start, end;\n\n\t\tgettimeofday(&start, 0);\n\t\tint total = load_page_titles(base_path + \"data\/titles-sorted\", pages, page_ids);\n\t\tgettimeofday(&end, 0);\n\n\t\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\t\tstd::cout << \"\\033[94m -> \\033[0mRead in \" << total << \" page titles\\n\";\n\t\tstd::cout << \"\\033[94m -> \\033[0mTook \" << duration << \" seconds\\n\";\n\t}\n\n\t\/\/ Load in all page links into a hash map\n\tstd::cout << \"\\033[92m==>\\033[0m Reading in page links as a map\\n\";\n\n\t{\n\t\tstruct timeval start, end;\n\n\t\tgettimeofday(&start, 0);\n\t\tint total = load_page_links(base_path + \"data\/links-simple-sorted\", page_links);\n\t\tgettimeofday(&end, 0);\n\n\t\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\t\tstd::cout << \"\\033[94m -> \\033[0mRead in \" << total << \" page links\\n\";\n\t\tstd::cout << \"\\033[94m -> \\033[0mTook \" << duration << \" seconds\\n\";\n\t}\n\n\tstd::cout << \"\\033[92m==>\\033[0m Beginning BFS on Wikipedia graph\\n\";\n\n\t\/\/ Get the ID's of the start and target nodes\n\tint start_id = page_ids[argv[3]],\n\t target_id = page_ids[argv[4]];\n\n\tif (start_id == target_id)\n\t{\n\t\tstd::cout << \"\\n\\033[92mNo clicks required. The page is the same!\\n\";\n\t}\n\n\tstd::vector target_path;\n\n\tstruct timeval start, end;\n\n\tgettimeofday(&start, 0);\n\ttarget_path = path_between_pages(page_links, start_id, target_id);\n\tgettimeofday(&end, 0);\n\n\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\tstd::cout << \"\\033[94m -> \\033[0mTook \" << duration << \" seconds\\n\\n\";\n\n\t\/\/ Print out the path between the pages\n\tfor (int page_id : target_path)\n\t{\n\t\tstd::cout << \" * \" << pages[page_id] << '\\n';\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Typedef for our primary data types\ntypedef std::vector pages_t;\ntypedef std::unordered_map page_ids_t;\ntypedef std::unordered_map> page_links_t;\n\n\/* Load in the page titles and page ids from a file.\n *\n * Each line of the file will represent the page ID, starting from line 1 until\n * the end of the file. The page titles will be stored into the pages vector.\n * The page titles => ids will be stored in the page_ids map\n *\n * Returns: The total number of pages loaded\n *\/\nint load_page_titles(const std::string &file_path, pages_t &pages, page_ids_t &page_ids)\n{\n\tstd::ifstream page_titles_file(file_path);\n\tstd::string page_name;\n\n\t\/\/ We won't be using the first index of the vector for anything since\n\t\/\/ the page_id indexes start at 1 instead of 0. This should help to\n\t\/\/ prevent any errors during development\n\tpages.push_back(\"\");\n\n\t\/\/ Read the page name into the vector and into the hash-map\n\tint index = 1;\n\n\twhile (std::getline(page_titles_file, page_name))\n\t{\n\t\tpages.push_back(page_name);\n\t\tpage_ids[page_name] = index++;\n\t}\n\n\treturn index - 1;\n}\n\n\/* Load in the page links from a file.\n *\n * Each line of the file should start with a page_id that represents a page, it\n * should then follow with a colon (':'). All numbers after the colon represent\n * page_ids that that page links to.\n *\n * Read all page links into the page_links hash map, where the key is the\n * page_id and the value is a vector of page_ids the page links to.\n *\n * Returns: The total number of links loaded\n *\/\nint load_page_links(const std::string &file_path, page_links_t &page_links)\n{\n\tstd::ifstream page_links_file(file_path);\n\tstd::string link_id;\n\n\tint current_link = 0;\n\tint total_links = 0;\n\n\twhile (page_links_file >> link_id)\n\t{\n\t\tif (link_id.back() == ':')\n\t\t{\n\t\t\tcurrent_link = atoi(link_id.c_str());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpage_links[current_link].push_back(atoi(link_id.c_str()));\n\t\t\ttotal_links++;\n\t\t}\n\t}\n\n\treturn total_links;\n}\n\n\/* Given a hash map containing page_ids that represent a path back to a given\n * root node extract those Ids and order them so that we move from the root node\n * back to the tail_id.\n *\n * The root node is the node whos parent value is -1.\n *\n * Returns: A vector containing the page ids of the path in order.\n *\/\nstd::vector path_from_parents(std::unordered_map &parent_links,\n\tint target_id)\n{\n\tint current = target_id;\n\tstd::vector target_path;\n\n\t\/\/ Only fill the target_path vector if we have a parent link chain\n\tif (parent_links[target_id])\n\t{\n\t\t\/\/ Traverse thrugh the parent_links till we reach the root node\n\t\tdo\n\t\t{\n\t\t\ttarget_path.push_back(current);\n\t\t}\n\t\twhile ((current = parent_links[current]) != -1);\n\n\t\t\/\/ Reverse the target path list to be in proper order\n\t\tstd::reverse(target_path.begin(), target_path.end());\n\t}\n\n\treturn target_path;\n}\n\n\/* Calculate the shortest path between two page_ids in the page links graph.\n * This uses the Depth First Search algorithm to travers through each of the\n * child nodes looking to see if they are the target id. If none are, then we\n * will traverse through all their children, up until we can find the target id.\n *\n * Returns: See the return value of `path_from_parents`.\n *\/\nstd::vector path_between_pages(page_links_t &page_links,\n\tint start_id, int target_id)\n{\n\t\/\/ Keep track of parent nodes so we can traverse back through the path\n\tstd::unordered_map parent_links;\n\n\t\/\/ The starting node will always be considered 'visited'\n\tparent_links[start_id] = -1;\n\n\t\/\/ Queue of the current nodes to look at\n\tstd::deque current_nodes;\n\tcurrent_nodes.push_back(start_id);\n\n\tbool found_target = false;\n\n\t\/\/ Search until we find our target node\n\twhile ( ! found_target && ! current_nodes.empty())\n\t{\n\t\tint available_nodes = current_nodes.size();\n\n\t\t#pragma omp parallel for\n\t\tfor (int i = 0; i < available_nodes; ++i)\n\t\t{\n\t\t\t\/\/ Since we can't break out of parallelize loops we just need to\n\t\t\t\/\/ finish off what evers left by continuing through them all\n\t\t\t#pragma omp flush (found_target)\n\t\t\tif (found_target) continue;\n\n\t\t\tint current;\n\n\t\t\t#pragma omp critical\n\t\t\t{\n\t\t\t\tcurrent = current_nodes.front();\n\t\t\t\tcurrent_nodes.pop_front();\n\t\t\t}\n\n\t\t\t\/\/ Iterate through all linked pages\n\t\t\tfor (int page_id : page_links[current])\n\t\t\t{\n\t\t\t\t\/\/ Keep track of how we traveled to this node\n\t\t\t\t#pragma omp critical\n\t\t\t\tif (parent_links[page_id] == 0)\n\t\t\t\t{\n\t\t\t\t\tparent_links[page_id] = current;\n\n\t\t\t\t\tif (target_id == page_id)\n\t\t\t\t\t{\n\t\t\t\t\t\tfound_target = true;\n\t\t\t\t\t\t#pragma omp flush (found_target)\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcurrent_nodes.push_back(page_id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn path_from_parents(parent_links, target_id);\n}\n\n\/* Use the external python searcher script to find a given page by a search term\n * and output the resulting page name.\n *\n * Returns: Valid Wikipedia page name, or an empty string if one cannot be found\n *\/\nstd::string search_for_page(const std::string &py_searcher_bin, const std::string &search)\n{\n\tFILE *pipe = popen((py_searcher_bin + \" \\\"\" + search + \"\\\"\").c_str(), \"r\");\n\n\tchar buffer[255];\n\tstd::string page_name = \"\";\n\n\twhile ( ! feof(pipe))\n\t{\n\t\tif (fgets(buffer, 255, pipe) != NULL)\n\t\t{\n\t\t\tpage_name += buffer;\n\t\t}\n\t}\n\n\treturn page_name;\n}\n\nstd::string pretty_print_path(const std::vector &path_ids, const pages_t &pages)\n{\n\tstd::string path = \"\";\n\tint left_padding = 2;\n\n\tfor (int page_id : path_ids)\n\t{\n\t\tstd::string page_title = pages[page_id];\n\t\tstd::string left_pad = std::string(left_padding, ' ');\n\n\t\tpath += left_pad + page_title + '\\n';\n\n\t\tif (pages[page_id] != pages[path_ids.size() - 1])\n\t\t{\n\t\t\tpath += left_pad + \"↓\\n\";\n\t\t}\n\t}\n\n\treturn path;\n}\n\n\/* Kick off the main process:\n *\n * 1. Load in all of the wikipedia pages and page links into memory as a vector\n * and hash map. Do this in parallel if possible\n * 2. Begin reading user input for what pages they would like to path find\n * 3. Use an external python script to get the page names from wikis search\n * 4. Path find using the BFS algorithm (again, in parallel)\n * 5. Repeat 2\n *\/\nint main(int argc, char* argv[])\n{\n\t\/\/ Used to store a list of page titles. Each index represents a page title\n\tpages_t pages;\n\n\t\/\/ Used to reverse lookup a page ID by it's title\n\tpage_ids_t page_ids;\n\n\t\/\/ Used to store a list of page_ids that a given page_id links to\n\tpage_links_t page_links;\n\n\tstd::cout << \"Welcome to Six-Degrees-of-Wikipedia path finder\\n\"\n\t << \"Please while we load Wikipedia into memory.\\n\\n\";\n\n\t\/\/ Determine the base directory path\n\tchar path_buffer[1024];\n\treadlink(\"\/proc\/self\/exe\", path_buffer, sizeof(path_buffer) - 1);\n\tstd::string base_path = std::string(dirname(path_buffer)) + \"\/..\/\";\n\n\n\t#pragma omp parallel sections\n\t{\n\t\t\/\/ Load in all data, in parallel\n\t\tstd::cout << \"\\033[32m==>\\033[0m Loading in page titles and page links\\n\";\n\n\t\t#pragma omp section\n\t\t{\n\t\t\tstruct timeval start, end;\n\n\t\t\tgettimeofday(&start, 0);\n\t\t\tint total = load_page_titles(base_path + \"data\/titles-sorted\", pages, page_ids);\n\t\t\tgettimeofday(&end, 0);\n\n\t\t\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\t\t\tstd::cout << \"\\033[34m -> \\033[0mRead in \" << total << \" page titles\\n\";\n\t\t\tstd::cout << \"\\033[34m -> \\033[0mTook \" << duration << \" seconds\\n\";\n\t\t}\n\n\t\t#pragma omp section\n\t\t{\n\t\t\tstruct timeval start, end;\n\n\t\t\tgettimeofday(&start, 0);\n\t\t\tint total = load_page_links(base_path + \"data\/links-simple-sorted\", page_links);\n\t\t\tgettimeofday(&end, 0);\n\n\t\t\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\t\t\tstd::cout << \"\\033[34m -> \\033[0mRead in \" << total << \" page links\\n\";\n\t\t\tstd::cout << \"\\033[34m -> \\033[0mTook \" << duration << \" seconds\\n\";\n\t\t}\n\t}\n\n\tstd::cout << \"\\033[32m==>\\033[0m Wikipedia graph loaded! Ready to path find!\\n\\n\";\n\n\twhile (true)\n\t{\n\t\tstd::string start_page, target_page;\n\n\t\tstd::cout << \"Start Wikipedia Page: \";\n\t\tstd::getline(std::cin, start_page);\n\n\t\tstd::cout << \"Target Wikipedia Page: \";\n\t\tstd::getline(std::cin, target_page);\n\n\t\t\/\/ Use the the wiki_search.py script to lookup the wikipedia article name\n\t\tstd::cout << \"\\n\\033[32m==>\\033[0m Looking up pages through Wikipedia search API\\n\";\n\n\t\tstart_page = search_for_page(base_path + \"bin\/wiki_search.py\", start_page);\n\t\ttarget_page = search_for_page(base_path + \"bin\/wiki_search.py\", target_page);\n\n\t\t\/\/ Ensure both pages exist\n\t\tif (start_page == \"\")\n\t\t{\n\t\t\tstd::cout << \"\\033[31m==>\\033[0m Start page is not a valid Wikipedia page\\n\\n\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (target_page == \"\")\n\t\t{\n\t\t\tstd::cout << \"\\033[31m==>\\033[0m Target page is not a valid Wikipedia page\\n\\n\";\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Remove newline from page names\n\t\tstart_page.pop_back();\n\t\ttarget_page.pop_back();\n\n\t\t\/\/ Locate page Ids\n\t\tint start_id = page_ids[start_page],\n\t\t\ttarget_id = page_ids[target_page];\n\n\t\t\/\/ Begin search\n\t\tstd::cout << \"\\033[32m==>\\033[0m Finding path from \\033[35m\"\n\t\t << start_page << \"\\033[0m → \\033[34m\"\n\t\t << target_page << \"\\033[0m\\n\";\n\n\t\tstd::vector target_path;\n\t\tstruct timeval start, end;\n\n\t\tgettimeofday(&start, 0);\n\t\ttarget_path = path_between_pages(page_links, start_id, target_id);\n\t\tgettimeofday(&end, 0);\n\n\t\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\t\tstd::cout << \"\\033[34m -> \\033[0mFound path in \\033[32m\" << target_path.size() -1 << \" clicks\\033[0m\\n\";\n\t\tstd::cout << \"\\033[34m -> \\033[0mTook \" << duration << \" seconds\\n\\n\";\n\n\t\t\/\/ Pretty print the page path\n\t\tfor (int page_id : target_path)\n\t\t{\n\t\t\tstd::cout << \" \\033[34m↓\\033[0m \" << pages[page_id] << \"\\n\";\n\t\t}\n\n\t\tstd::cout << '\\n';\n\t}\n\n\treturn 0;\n}\nTime total boot process#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Typedef for our primary data types\ntypedef std::vector pages_t;\ntypedef std::unordered_map page_ids_t;\ntypedef std::unordered_map> page_links_t;\n\n\/* Load in the page titles and page ids from a file.\n *\n * Each line of the file will represent the page ID, starting from line 1 until\n * the end of the file. The page titles will be stored into the pages vector.\n * The page titles => ids will be stored in the page_ids map\n *\n * Returns: The total number of pages loaded\n *\/\nint load_page_titles(const std::string &file_path, pages_t &pages, page_ids_t &page_ids)\n{\n\tstd::ifstream page_titles_file(file_path);\n\tstd::string page_name;\n\n\t\/\/ We won't be using the first index of the vector for anything since\n\t\/\/ the page_id indexes start at 1 instead of 0. This should help to\n\t\/\/ prevent any errors during development\n\tpages.push_back(\"\");\n\n\t\/\/ Read the page name into the vector and into the hash-map\n\tint index = 1;\n\n\twhile (std::getline(page_titles_file, page_name))\n\t{\n\t\tpages.push_back(page_name);\n\t\tpage_ids[page_name] = index++;\n\t}\n\n\treturn index - 1;\n}\n\n\/* Load in the page links from a file.\n *\n * Each line of the file should start with a page_id that represents a page, it\n * should then follow with a colon (':'). All numbers after the colon represent\n * page_ids that that page links to.\n *\n * Read all page links into the page_links hash map, where the key is the\n * page_id and the value is a vector of page_ids the page links to.\n *\n * Returns: The total number of links loaded\n *\/\nint load_page_links(const std::string &file_path, page_links_t &page_links)\n{\n\tstd::ifstream page_links_file(file_path);\n\tstd::string link_id;\n\n\tint current_link = 0;\n\tint total_links = 0;\n\n\twhile (page_links_file >> link_id)\n\t{\n\t\tif (link_id.back() == ':')\n\t\t{\n\t\t\tcurrent_link = atoi(link_id.c_str());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpage_links[current_link].push_back(atoi(link_id.c_str()));\n\t\t\ttotal_links++;\n\t\t}\n\t}\n\n\treturn total_links;\n}\n\n\/* Given a hash map containing page_ids that represent a path back to a given\n * root node extract those Ids and order them so that we move from the root node\n * back to the tail_id.\n *\n * The root node is the node whos parent value is -1.\n *\n * Returns: A vector containing the page ids of the path in order.\n *\/\nstd::vector path_from_parents(std::unordered_map &parent_links,\n\tint target_id)\n{\n\tint current = target_id;\n\tstd::vector target_path;\n\n\t\/\/ Only fill the target_path vector if we have a parent link chain\n\tif (parent_links[target_id])\n\t{\n\t\t\/\/ Traverse thrugh the parent_links till we reach the root node\n\t\tdo\n\t\t{\n\t\t\ttarget_path.push_back(current);\n\t\t}\n\t\twhile ((current = parent_links[current]) != -1);\n\n\t\t\/\/ Reverse the target path list to be in proper order\n\t\tstd::reverse(target_path.begin(), target_path.end());\n\t}\n\n\treturn target_path;\n}\n\n\/* Calculate the shortest path between two page_ids in the page links graph.\n * This uses the Depth First Search algorithm to travers through each of the\n * child nodes looking to see if they are the target id. If none are, then we\n * will traverse through all their children, up until we can find the target id.\n *\n * Returns: See the return value of `path_from_parents`.\n *\/\nstd::vector path_between_pages(page_links_t &page_links,\n\tint start_id, int target_id)\n{\n\t\/\/ Keep track of parent nodes so we can traverse back through the path\n\tstd::unordered_map parent_links;\n\n\t\/\/ The starting node will always be considered 'visited'\n\tparent_links[start_id] = -1;\n\n\t\/\/ Queue of the current nodes to look at\n\tstd::deque current_nodes;\n\tcurrent_nodes.push_back(start_id);\n\n\tbool found_target = false;\n\n\t\/\/ Search until we find our target node\n\twhile ( ! found_target && ! current_nodes.empty())\n\t{\n\t\tint available_nodes = current_nodes.size();\n\n\t\t#pragma omp parallel for\n\t\tfor (int i = 0; i < available_nodes; ++i)\n\t\t{\n\t\t\t\/\/ Since we can't break out of parallelize loops we just need to\n\t\t\t\/\/ finish off what evers left by continuing through them all\n\t\t\t#pragma omp flush (found_target)\n\t\t\tif (found_target) continue;\n\n\t\t\tint current;\n\n\t\t\t#pragma omp critical\n\t\t\t{\n\t\t\t\tcurrent = current_nodes.front();\n\t\t\t\tcurrent_nodes.pop_front();\n\t\t\t}\n\n\t\t\t\/\/ Iterate through all linked pages\n\t\t\tfor (int page_id : page_links[current])\n\t\t\t{\n\t\t\t\t\/\/ Keep track of how we traveled to this node\n\t\t\t\t#pragma omp critical\n\t\t\t\tif (parent_links[page_id] == 0)\n\t\t\t\t{\n\t\t\t\t\tparent_links[page_id] = current;\n\n\t\t\t\t\tif (target_id == page_id)\n\t\t\t\t\t{\n\t\t\t\t\t\tfound_target = true;\n\t\t\t\t\t\t#pragma omp flush (found_target)\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcurrent_nodes.push_back(page_id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn path_from_parents(parent_links, target_id);\n}\n\n\/* Use the external python searcher script to find a given page by a search term\n * and output the resulting page name.\n *\n * Returns: Valid Wikipedia page name, or an empty string if one cannot be found\n *\/\nstd::string search_for_page(const std::string &py_searcher_bin, const std::string &search)\n{\n\tFILE *pipe = popen((py_searcher_bin + \" \\\"\" + search + \"\\\"\").c_str(), \"r\");\n\n\tchar buffer[255];\n\tstd::string page_name = \"\";\n\n\twhile ( ! feof(pipe))\n\t{\n\t\tif (fgets(buffer, 255, pipe) != NULL)\n\t\t{\n\t\t\tpage_name += buffer;\n\t\t}\n\t}\n\n\treturn page_name;\n}\n\nstd::string pretty_print_path(const std::vector &path_ids, const pages_t &pages)\n{\n\tstd::string path = \"\";\n\tint left_padding = 2;\n\n\tfor (int page_id : path_ids)\n\t{\n\t\tstd::string page_title = pages[page_id];\n\t\tstd::string left_pad = std::string(left_padding, ' ');\n\n\t\tpath += left_pad + page_title + '\\n';\n\n\t\tif (pages[page_id] != pages[path_ids.size() - 1])\n\t\t{\n\t\t\tpath += left_pad + \"↓\\n\";\n\t\t}\n\t}\n\n\treturn path;\n}\n\n\/* Kick off the main process:\n *\n * 1. Load in all of the wikipedia pages and page links into memory as a vector\n * and hash map. Do this in parallel if possible\n * 2. Begin reading user input for what pages they would like to path find\n * 3. Use an external python script to get the page names from wikis search\n * 4. Path find using the BFS algorithm (again, in parallel)\n * 5. Repeat 2\n *\/\nint main(int argc, char* argv[])\n{\n\t\/\/ Used to store a list of page titles. Each index represents a page title\n\tpages_t pages;\n\n\t\/\/ Used to reverse lookup a page ID by it's title\n\tpage_ids_t page_ids;\n\n\t\/\/ Used to store a list of page_ids that a given page_id links to\n\tpage_links_t page_links;\n\n\tstd::cout << \"Welcome to Six-Degrees-of-Wikipedia path finder\\n\"\n\t << \"Please while we load Wikipedia into memory.\\n\\n\";\n\n\t\/\/ Determine the base directory path\n\tchar path_buffer[1024];\n\treadlink(\"\/proc\/self\/exe\", path_buffer, sizeof(path_buffer) - 1);\n\tstd::string base_path = std::string(dirname(path_buffer)) + \"\/..\/\";\n\n\tstruct timeval boot_start, boot_end;\n\tgettimeofday(&boot_start, 0);\n\n\t#pragma omp parallel sections\n\t{\n\t\t\/\/ Load in all data, in parallel\n\t\tstd::cout << \"\\033[32m==>\\033[0m Loading in page titles and page links\\n\";\n\n\t\t#pragma omp section\n\t\t{\n\t\t\tstruct timeval start, end;\n\n\t\t\tgettimeofday(&start, 0);\n\t\t\tint total = load_page_titles(base_path + \"data\/titles-sorted\", pages, page_ids);\n\t\t\tgettimeofday(&end, 0);\n\n\t\t\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\t\t\tstd::cout << \"\\033[34m -> \\033[0mRead in \" << total << \" page titles\\n\";\n\t\t\tstd::cout << \"\\033[34m -> \\033[0mTook \" << duration << \" seconds\\n\";\n\t\t}\n\n\t\t#pragma omp section\n\t\t{\n\t\t\tstruct timeval start, end;\n\n\t\t\tgettimeofday(&start, 0);\n\t\t\tint total = load_page_links(base_path + \"data\/links-simple-sorted\", page_links);\n\t\t\tgettimeofday(&end, 0);\n\n\t\t\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\t\t\tstd::cout << \"\\033[34m -> \\033[0mRead in \" << total << \" page links\\n\";\n\t\t\tstd::cout << \"\\033[34m -> \\033[0mTook \" << duration << \" seconds\\n\";\n\t\t}\n\t}\n\n\tgettimeofday(&boot_end, 0);\n\tdouble duration = ((boot_end.tv_sec - boot_start.tv_sec) * 1000000u\n\t\t+ boot_end.tv_usec - boot_start.tv_usec) \/ 1.e6;\n\n\tstd::cout << \"\\033[32m==>\\033[0m Wikipedia graph loaded in \" << duration << \" seconds. Ready to path find!\\n\\n\";\n\n\twhile (true)\n\t{\n\t\tstd::string start_page, target_page;\n\n\t\tstd::cout << \"Start Wikipedia Page: \";\n\t\tstd::getline(std::cin, start_page);\n\n\t\tstd::cout << \"Target Wikipedia Page: \";\n\t\tstd::getline(std::cin, target_page);\n\n\t\t\/\/ Use the the wiki_search.py script to lookup the wikipedia article name\n\t\tstd::cout << \"\\n\\033[32m==>\\033[0m Looking up pages through Wikipedia search API\\n\";\n\n\t\tstart_page = search_for_page(base_path + \"bin\/wiki_search.py\", start_page);\n\t\ttarget_page = search_for_page(base_path + \"bin\/wiki_search.py\", target_page);\n\n\t\t\/\/ Ensure both pages exist\n\t\tif (start_page == \"\")\n\t\t{\n\t\t\tstd::cout << \"\\033[31m==>\\033[0m Start page is not a valid Wikipedia page\\n\\n\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (target_page == \"\")\n\t\t{\n\t\t\tstd::cout << \"\\033[31m==>\\033[0m Target page is not a valid Wikipedia page\\n\\n\";\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Remove newline from page names\n\t\tstart_page.pop_back();\n\t\ttarget_page.pop_back();\n\n\t\t\/\/ Locate page Ids\n\t\tint start_id = page_ids[start_page],\n\t\t\ttarget_id = page_ids[target_page];\n\n\t\t\/\/ Begin search\n\t\tstd::cout << \"\\033[32m==>\\033[0m Finding path from \\033[35m\"\n\t\t << start_page << \"\\033[0m → \\033[34m\"\n\t\t << target_page << \"\\033[0m\\n\";\n\n\t\tstd::vector target_path;\n\t\tstruct timeval start, end;\n\n\t\tgettimeofday(&start, 0);\n\t\ttarget_path = path_between_pages(page_links, start_id, target_id);\n\t\tgettimeofday(&end, 0);\n\n\t\tdouble duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) \/ 1.e6;\n\t\tstd::cout << \"\\033[34m -> \\033[0mFound path in \\033[32m\" << target_path.size() -1 << \" clicks\\033[0m\\n\";\n\t\tstd::cout << \"\\033[34m -> \\033[0mTook \" << duration << \" seconds\\n\\n\";\n\n\t\t\/\/ Pretty print the page path\n\t\tfor (int page_id : target_path)\n\t\t{\n\t\t\tstd::cout << \" \\033[34m↓\\033[0m \" << pages[page_id] << \"\\n\";\n\t\t}\n\n\t\tstd::cout << '\\n';\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2015 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 \"search.h\"\n#include \n\nnamespace {\nvoid add_value(QString &s, QString value, QString key, QString &v_1, QString &v_2, QString &v_3, QString &v_4, QString &v_5, QString &v_6, QString &v_7, QString &v_8, int &count)\n{\n ++count;\n switch(count)\n {\n case 1:\n v_1 = value;\n s.append(\" WHERE \");\n s.append(key);\n break;\n case 2:\n v_2 = value;\n s.append(\" AND \");\n s.append(key);\n break;\n case 3:\n v_3 = value;\n s.append(\" AND \");\n s.append(key);\n break;\n case 4:\n v_4 = value;\n s.append(\" AND \");\n s.append(key);\n break;\n case 5:\n v_5 = value;\n s.append(\" AND \");\n s.append(key);\n break;\n case 6:\n v_6 = value;\n s.append(\" AND \");\n s.append(key);\n break;\n case 7:\n v_7 = value;\n s.append(\" AND \");\n s.append(key);\n break;\n case 8:\n v_8 = value;\n s.append(\" AND \");\n s.append(key);\n break;\n default:\n qDebug() << \"ERROR in \" __FILE__ << \" \" << __LINE__ << \": Too many search terms\";\n }\n}\n}\n\nsearch::search(QString settings_path, QObject *parent) :\n QObject(parent),\n _database(),\n _kanji_query(),\n _settings_query(),\n _literal_result(\"\"),\n _meaning_result(\"\"),\n _saved(\"\"),\n _literal(\"\"),\n _radical(-1),\n _strokecount(-1),\n _jlpt(-1),\n _meaning(\"\"),\n _search_for_saved(false),\n _saved_search_value(false),\n _skip1(0),\n _skip2(0),\n _skip3(0),\n _search_started(false)\n{\n _database = QSqlDatabase::addDatabase(\"QSQLITE\");\n _database.setDatabaseName(\":memory:\");\n if(!_database.open())\n {\n qCritical() << \"ERROR in \" __FILE__ << \" \" << __LINE__ << \": Can not create database\";\n }\n _kanji_query = QSqlQuery(_database);\n _settings_query = QSqlQuery(_database);\n\n QString s = QString(\"ATTACH DATABASE '\/usr\/share\/harbour-kanji\/kanjidb.sqlite3' AS kanjidb\");\n if(!_kanji_query.exec(s))\n {\n QString error = s.append(\": \").append(_kanji_query.lastError().text());\n qWarning() << error;\n }\n s = QString(\"ATTACH DATABASE ? AS settingsdb\");\n _kanji_query.clear();\n _kanji_query.prepare(s);\n _kanji_query.addBindValue(settings_path);\n if(!_kanji_query.exec())\n {\n QString error = s.append(\": \").append(_kanji_query.lastError().text());\n qWarning() << error;\n }\n _kanji_query.clear();\n}\n\nvoid search::clear()\n{\n _kanji_query.clear();\n _settings_query.clear();\n _literal_result = \"\";\n _meaning_result = \"\";\n _saved = false;\n _literal = \"\";\n _radical = -1;\n _strokecount = -1;\n _jlpt = -1;\n _meaning = \"\";\n _search_for_saved = false;\n _saved_search_value = false;\n _skip1 = 0;\n _skip2 = 0;\n _skip3 = 0;\n _search_started = false;\n}\n\nvoid search::search_literal(QString literal)\n{\n _literal = literal;\n}\n\nvoid search::search_radical(int radical)\n{\n _radical = radical;\n}\n\nvoid search::search_strokecount(int strokecount)\n{\n _strokecount = strokecount;\n}\n\nvoid search::search_jlpt(int jlpt)\n{\n _jlpt = jlpt;\n}\n\nvoid search::search_meaning(QString meaning)\n{\n _meaning = meaning;\n}\n\nvoid search::search_saved(bool saved)\n{\n _search_for_saved = true;\n _saved_search_value = saved;\n}\n\nvoid search::search_skip(int skip1, int skip2, int skip3)\n{\n _skip1 = skip1;\n _skip2 = skip2;\n _skip3 = skip3;\n}\n\nbool search::start_search()\n{\n if(_literal == \"\" && _radical == 0 && _strokecount == 0 && _jlpt == 0 && _meaning == \"\")\n {\n \/\/ Get all kanji\n QString s = QString(\"SELECT literal,meaning FROM kanjidb.kanji\");\n if(!_kanji_query.exec(s))\n {\n QString error = s.append(\": \").append(_kanji_query.lastError().text());\n qWarning() << error;\n _search_started = false;\n return false;\n }\n if(!_kanji_query.isSelect())\n {\n QString error = s.append(\": No SELECT\");\n qWarning() << error;\n _search_started = false;\n return false;\n }\n }\n else\n {\n \/\/ Search for all fitting kanji\n int count = 0;\n\n QString v_1;\n QString v_2;\n QString v_3;\n QString v_4;\n QString v_5;\n QString v_6;\n QString v_7;\n QString v_8;\n\n QString s = QString(\"SELECT literal,meaning FROM kanjidb.kanji\");\n if(_literal != \"\")\n {\n add_value(s,QString(\"\\%%1\\%\").arg(_literal),QString(\"literal LIKE ?\"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);\n }\n if(_radical != -1)\n {\n add_value(s,QString(\"%1\").arg(_radical),QString(\"radical=?\"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);\n }\n if(_strokecount != -1)\n {\n add_value(s,QString(\"%1\").arg(_strokecount),QString(\"strokecount=?\"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);\n }\n if(_jlpt != -1)\n {\n add_value(s,QString(\"%1\").arg(_jlpt),QString(\"JLPT=?\"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);\n }\n if(_meaning != \"\")\n {\n add_value(s,QString(\"\\%%1\\%\").arg(_meaning),QString(\"meaning LIKE ?\"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);\n }\n if(_skip1 != 0)\n {\n add_value(s,QString(\"%1\").arg(_skip1),QString(\"skip_1=?\"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);\n }\n if(_skip2 != 0)\n {\n add_value(s,QString(\"%1\").arg(_skip2),QString(\"skip_2=?\"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);\n }\n if(_skip3 != 0)\n {\n add_value(s,QString(\"%1\").arg(_skip3),QString(\"skip_3=?\"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);\n }\n\n _kanji_query.clear();\n _kanji_query.prepare(s);\n\n if(count >= 1)\n {\n _kanji_query.addBindValue(v_1);\n }\n if(count >= 2)\n {\n _kanji_query.addBindValue(v_2);\n }\n if(count >= 3)\n {\n _kanji_query.addBindValue(v_3);\n }\n if(count >= 4)\n {\n _kanji_query.addBindValue(v_4);\n }\n if(count >= 5)\n {\n _kanji_query.addBindValue(v_5);\n }\n if(count >= 6)\n {\n _kanji_query.addBindValue(v_6);\n }\n if(count >= 7)\n {\n _kanji_query.addBindValue(v_7);\n }\n if(count >= 8)\n {\n _kanji_query.addBindValue(v_8);\n }\n\n qDebug() << \"DEBUG in \" __FILE__ << \" \" << __LINE__ << \": SELECT statement:\" << s;\n\n if(!_kanji_query.exec())\n {\n QString error = s.append(\": \").append(_kanji_query.lastError().text());\n qWarning() << error;\n _search_started = false;\n return false;\n }\n if(!_kanji_query.isSelect())\n {\n QString error = s.append(\": No SELECT\");\n qWarning() << error;\n _search_started = false;\n return false;\n }\n }\n _search_started = true;\n return true;\n}\n\nbool search::next_hidden()\n{\n if(!_search_started)\n {\n return false;\n }\n if(_kanji_query.next())\n {\n _literal_result = _kanji_query.value(0).toString();\n _meaning_result = _kanji_query.value(1).toString();\n\n QString s = QString(\"SELECT count(*) FROM settingsdb.saved_kanji WHERE literal=?\");\n _settings_query.prepare(s);\n _settings_query.addBindValue(_literal_result);\n if(_settings_query.exec() && _settings_query.isSelect() && _settings_query.next() && _settings_query.value(0).toInt() > 0)\n {\n _saved = true;\n }\n else\n {\n _saved = false;\n }\n _settings_query.finish();\n return true;\n }\n else\n {\n _search_started = false;\n return false;\n }\n}\n\nbool search::next()\n{\n if(!_search_started)\n {\n return false;\n }\n if(!_search_for_saved)\n {\n return next_hidden();\n }\n else\n {\n while(next_hidden())\n {\n if(_saved_search_value == _saved)\n {\n return true;\n }\n }\n return false;\n }\n}\n\nQString search::literal()\n{\n return _literal_result;\n}\n\nQString search::meaning()\n{\n return _meaning_result;\n}\n\nbool search::kanji_is_saved()\n{\n return _saved;\n}\nIf \"meaning\" is selected for search both \"meaning\" and \"custom_translation\" will be considered.\/*\n Copyright (C) 2015 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 \"search.h\"\n#include \n#include \n#include \n\nnamespace {\nQString get_seperator(int &count)\n{\n ++count;\n if(count == 1)\n {\n return \" WHERE \";\n }\n else\n {\n return \" AND \";\n }\n}\n}\n\nsearch::search(QString settings_path, QObject *parent) :\n QObject(parent),\n _database(),\n _kanji_query(),\n _settings_query(),\n _literal_result(\"\"),\n _meaning_result(\"\"),\n _saved(\"\"),\n _literal(\"\"),\n _radical(-1),\n _strokecount(-1),\n _jlpt(-1),\n _meaning(\"\"),\n _search_for_saved(false),\n _saved_search_value(false),\n _skip1(0),\n _skip2(0),\n _skip3(0),\n _search_started(false)\n{\n _database = QSqlDatabase::addDatabase(\"QSQLITE\");\n _database.setDatabaseName(\":memory:\");\n if(!_database.open())\n {\n qCritical() << \"ERROR in \" __FILE__ << \" \" << __LINE__ << \": Can not create database\";\n }\n _kanji_query = QSqlQuery(_database);\n _settings_query = QSqlQuery(_database);\n\n QString s = QString(\"ATTACH DATABASE '\/usr\/share\/harbour-kanji\/kanjidb.sqlite3' AS kanjidb\");\n if(!_kanji_query.exec(s))\n {\n QString error = s.append(\": \").append(_kanji_query.lastError().text());\n qWarning() << error;\n }\n s = QString(\"ATTACH DATABASE ? AS settingsdb\");\n _kanji_query.clear();\n _kanji_query.prepare(s);\n _kanji_query.addBindValue(settings_path);\n if(!_kanji_query.exec())\n {\n QString error = s.append(\": \").append(_kanji_query.lastError().text());\n qWarning() << error;\n }\n _kanji_query.clear();\n}\n\nvoid search::clear()\n{\n _kanji_query.clear();\n _settings_query.clear();\n _literal_result = \"\";\n _meaning_result = \"\";\n _saved = false;\n _literal = \"\";\n _radical = -1;\n _strokecount = -1;\n _jlpt = -1;\n _meaning = \"\";\n _search_for_saved = false;\n _saved_search_value = false;\n _skip1 = 0;\n _skip2 = 0;\n _skip3 = 0;\n _search_started = false;\n}\n\nvoid search::search_literal(QString literal)\n{\n _literal = literal;\n}\n\nvoid search::search_radical(int radical)\n{\n _radical = radical;\n}\n\nvoid search::search_strokecount(int strokecount)\n{\n _strokecount = strokecount;\n}\n\nvoid search::search_jlpt(int jlpt)\n{\n _jlpt = jlpt;\n}\n\nvoid search::search_meaning(QString meaning)\n{\n _meaning = meaning;\n}\n\nvoid search::search_saved(bool saved)\n{\n _search_for_saved = true;\n _saved_search_value = saved;\n}\n\nvoid search::search_skip(int skip1, int skip2, int skip3)\n{\n _skip1 = skip1;\n _skip2 = skip2;\n _skip3 = skip3;\n}\n\nbool search::start_search()\n{\n if(_literal == \"\" && _radical == -1 && _strokecount == -1 && _jlpt == -1 && _meaning == \"\" && _skip1 == 0 && _skip2 == 0 && _skip3 == 0)\n {\n \/\/ Get all kanji\n QString s = QString(\"SELECT literal,meaning FROM kanjidb.kanji\");\n if(!_kanji_query.exec(s))\n {\n QString error = s.append(\": \").append(_kanji_query.lastError().text());\n qWarning() << error;\n _search_started = false;\n return false;\n }\n if(!_kanji_query.isSelect())\n {\n QString error = s.append(\": No SELECT\");\n qWarning() << error;\n _search_started = false;\n return false;\n }\n }\n else\n {\n \/\/ Search for all fitting kanji\n int count = 0;\n QVariantList search_list;\n\n QString s = QString(\"SELECT kanjidb.kanji.literal,meaning FROM kanjidb.kanji LEFT JOIN settingsdb.custom_translation ON kanjidb.kanji.literal=settingsdb.custom_translation.literal\");\n if(_literal != \"\")\n {\n s.append(get_seperator(count));\n s.append(\"literal LIKE ?\");\n search_list.append(QString(\"\\%%1\\%\").arg(_literal));\n }\n if(_radical != -1)\n {\n s.append(get_seperator(count));\n s.append(\"radical=?\");\n search_list.append(_radical);\n }\n if(_strokecount != -1)\n {\n s.append(get_seperator(count));\n s.append(\"strokecount=?\");\n search_list.append(_strokecount);\n }\n if(_jlpt != -1)\n {\n s.append(get_seperator(count));\n s.append(\"JLPT=?\");\n search_list.append(_jlpt);\n }\n if(_meaning != \"\")\n {\n s.append(get_seperator(count));\n s.append(\"(meaning LIKE ? OR translation LIKE ?)\");\n search_list.append(QString(\"\\%%1\\%\").arg(_meaning));\n search_list.append(QString(\"\\%%1\\%\").arg(_meaning));\n }\n if(_skip1 != 0)\n {\n s.append(get_seperator(count));\n s.append(\"skip_1=?\");\n search_list.append(_skip1);\n }\n if(_skip2 != 0)\n {\n s.append(get_seperator(count));\n s.append(\"skip_2=?\");\n search_list.append(_skip2);\n }\n if(_skip3 != 0)\n {\n s.append(get_seperator(count));\n s.append(\"skip_3=?\");\n search_list.append(_skip3);\n }\n\n _kanji_query.clear();\n _kanji_query.prepare(s);\n foreach (QVariant var, search_list) {\n _kanji_query.addBindValue(var);\n }\n\n qDebug() << \"DEBUG in \" __FILE__ << \" \" << __LINE__ << \": SELECT statement:\" << s;\n\n if(!_kanji_query.exec())\n {\n QString error = s.append(\": \").append(_kanji_query.lastError().text());\n qWarning() << error;\n _search_started = false;\n return false;\n }\n if(!_kanji_query.isSelect())\n {\n QString error = s.append(\": No SELECT\");\n qWarning() << error;\n _search_started = false;\n return false;\n }\n }\n _search_started = true;\n return true;\n}\n\nbool search::next_hidden()\n{\n if(!_search_started)\n {\n return false;\n }\n if(_kanji_query.next())\n {\n _literal_result = _kanji_query.value(0).toString();\n _meaning_result = _kanji_query.value(1).toString();\n\n QString s = QString(\"SELECT count(*) FROM settingsdb.saved_kanji WHERE literal=?\");\n _settings_query.prepare(s);\n _settings_query.addBindValue(_literal_result);\n if(_settings_query.exec() && _settings_query.isSelect() && _settings_query.next() && _settings_query.value(0).toInt() > 0)\n {\n _saved = true;\n }\n else\n {\n _saved = false;\n }\n _settings_query.finish();\n return true;\n }\n else\n {\n _search_started = false;\n return false;\n }\n}\n\nbool search::next()\n{\n if(!_search_started)\n {\n return false;\n }\n if(!_search_for_saved)\n {\n return next_hidden();\n }\n else\n {\n while(next_hidden())\n {\n if(_saved_search_value == _saved)\n {\n return true;\n }\n }\n return false;\n }\n}\n\nQString search::literal()\n{\n return _literal_result;\n}\n\nQString search::meaning()\n{\n return _meaning_result;\n}\n\nbool search::kanji_is_saved()\n{\n return _saved;\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2021 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#ifdef PADDLE_WITH_XPU\n\n#include \"paddle\/fluid\/operators\/sequence_ops\/sequence_conv_op.h\"\n#include \"paddle\/fluid\/platform\/device\/device_wrapper.h\"\n\nnamespace paddle {\nnamespace operators {\nusing Tensor = framework::Tensor;\n\ntemplate \nclass SequenceConvXPUKernel : public framework::OpKernel {\n public:\n void Compute(const framework::ExecutionContext& context) const override {\n auto* in = context.Input(\"X\");\n auto* out = context.Output(\"Out\");\n auto filter = *context.Input(\"Filter\");\n\n out->mutable_data(context.GetPlace());\n\n int context_start = context.Attr(\"contextStart\");\n int context_length = context.Attr(\"contextLength\");\n int context_stride = context.Attr(\"contextStride\");\n bool padding_trainable = context.Attr(\"paddingTrainable\");\n\n PADDLE_ENFORCE_EQ(\n in->lod().empty(), false,\n platform::errors::InvalidArgument(\"Input(X) Tensor of SequenceConvOp \"\n \"does not contain LoD information.\"));\n PADDLE_ENFORCE_EQ(\n in->lod().size(), 1UL,\n platform::errors::InvalidArgument(\n \"Only support input sequence with lod level equal to 1 at \"\n \"present. But received: lod level %u.\",\n in->lod().size()));\n\n PADDLE_ENFORCE_EQ(\n padding_trainable, false,\n platform::errors::InvalidArgument(\"Only support padding_trainable \"\n \"equal false.\"));\n\n int up_pad = std::max(0, -context_start);\n int down_pad = std::max(0, context_start + context_length - 1);\n PADDLE_ENFORCE_EQ(up_pad, 2, platform::errors::InvalidArgument(\n \"Only support up_pad equal 2.\"));\n PADDLE_ENFORCE_EQ(down_pad, 2, platform::errors::InvalidArgument(\n \"Only support down_pad equal 2.\"));\n\n auto xpu_context =\n context.template device_context().x_context();\n auto sequence_width = static_cast(in->dims()[1]);\n framework::DDim col_shape = {in->dims()[0],\n context_length * sequence_width};\n xpu::ctx_guard RAII_GUARD(xpu_context);\n int col_numel = col_shape[0] * col_shape[1];\n T* col_data = RAII_GUARD.alloc_l3_or_gm(col_numel);\n PADDLE_ENFORCE_NOT_NULL(\n col_data, paddle::platform::errors::Fatal(\"XPU memory is not enough\"));\n\n auto lod_level_0 = in->lod()[0];\n int lod_size = lod_level_0.size();\n \/\/ If batch size set to 256, the lod is {0, batch[0] - 0,\n \/\/ batch[1] - batch [0], ..., batch[255] - batch[254]},\n \/\/ so the lod_size will be 257.\n PADDLE_ENFORCE_LE(lod_size, 257, platform::errors::InvalidArgument(\n \"Only support batch size <= 256.\"));\n\n std::vector cpu_lodx(lod_size);\n for (int i = 0; i < lod_size; i++) {\n cpu_lodx[i] = lod_level_0[i];\n }\n xpu::VectorParam lodx = {cpu_lodx.data(),\n static_cast(cpu_lodx.size()), nullptr};\n\n int r = xpu::sequence_context_projection(\n xpu_context, in->data(), col_data, nullptr, lodx, sequence_width,\n context_start, context_length, context_stride, {2, 2});\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"sequence_context_projection\");\n\n bool trans_a = false;\n bool trans_b = false;\n int m = col_shape[0];\n int k = col_shape[1];\n int k1 = filter.dims()[0];\n int n = filter.dims()[1];\n PADDLE_ENFORCE_EQ(k, k1,\n platform::errors::InvalidArgument(\n \"The shape of FC in SequenceConvOp is invalid.\"\n \"The k of matrix A is %d, k1 of matrix B is %d.\"\n \"But expect k == k1\",\n k, k1));\n int lda = (!trans_a) ? k : m;\n int ldb = (!trans_b) ? n : k;\n int ldc = n;\n T alpha = static_cast(1.0);\n T beta = static_cast(0.0);\n const T* data_a = col_data;\n const T* data_b = filter.data();\n T* data_c = out->data();\n\n r = xpu::fc_fusion(\n xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b, nullptr,\n nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr,\n xpu::Activation_t::LINEAR);\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"fc_fusion\");\n if (xpu_context->xpu_stream != nullptr) {\n xpu_wait(xpu_context->xpu_stream);\n }\n }\n};\n\ntemplate \nclass SequenceConvGradXPUKernel : public framework::OpKernel {\n public:\n void Compute(const framework::ExecutionContext& context) const override {\n auto* in_g = context.Output(framework::GradVarName(\"X\"));\n auto* out_g = context.Input(framework::GradVarName(\"Out\"));\n auto* filter_g = context.Output(framework::GradVarName(\"Filter\"));\n auto* in = context.Input(\"X\");\n auto* filter = context.Input(\"Filter\");\n\n int context_start = context.Attr(\"contextStart\");\n int context_length = context.Attr(\"contextLength\");\n int context_stride = context.Attr(\"contextStride\");\n bool padding_trainable = context.Attr(\"paddingTrainable\");\n\n PADDLE_ENFORCE_EQ(\n in->lod().empty(), false,\n platform::errors::InvalidArgument(\"Input(X) Tensor of SequenceConvOp \"\n \"does not contain LoD information.\"));\n PADDLE_ENFORCE_EQ(\n in->lod().size(), 1UL,\n platform::errors::InvalidArgument(\n \"Only support input sequence with lod level equal to 1 at \"\n \"present. But received: lod level %u.\",\n in->lod().size()));\n\n PADDLE_ENFORCE_EQ(\n padding_trainable, false,\n platform::errors::InvalidArgument(\"Only support padding_trainable \"\n \"equal false.\"));\n\n int up_pad = std::max(0, -context_start);\n int down_pad = std::max(0, context_start + context_length - 1);\n PADDLE_ENFORCE_EQ(up_pad, 2, platform::errors::InvalidArgument(\n \"Only support up_pad equal 2.\"));\n PADDLE_ENFORCE_EQ(down_pad, 2, platform::errors::InvalidArgument(\n \"Only support down_pad equal 2.\"));\n\n auto lod_level_0 = in->lod()[0];\n int lod_size = lod_level_0.size();\n PADDLE_ENFORCE_LE(lod_size, 257, platform::errors::InvalidArgument(\n \"Only support batch size <= 256.\"));\n\n std::vector cpu_lodx(lod_size);\n for (int i = 0; i < lod_size; i++) {\n cpu_lodx[i] = lod_level_0[i];\n }\n xpu::VectorParam lodx = {cpu_lodx.data(),\n static_cast(cpu_lodx.size()), nullptr};\n\n auto xpu_context =\n context.template device_context().x_context();\n auto sequence_width = static_cast(in->dims()[1]);\n framework::DDim col_shape = {in->dims()[0],\n context_length * sequence_width};\n xpu::ctx_guard RAII_GUARD(xpu_context);\n int col_numel = col_shape[0] * col_shape[1];\n T* col_data = RAII_GUARD.alloc_l3_or_gm(col_numel);\n PADDLE_ENFORCE_NOT_NULL(\n col_data, paddle::platform::errors::Fatal(\"XPU memory is not enough\"));\n\n if (in_g || filter_g) {\n int r = xpu::constant(xpu_context, col_data, col_numel, T(0));\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"constant\");\n\n bool trans_a = false;\n bool trans_b = true;\n int m = out_g->dims()[0];\n int k = out_g->dims()[1];\n int n = filter->dims()[0];\n int k1 = filter->dims()[1];\n PADDLE_ENFORCE_EQ(k, k1,\n platform::errors::InvalidArgument(\n \"The shape of FC in SequenceConvGradOp is invalid.\"\n \"The k of matrix A is %d, k1 of matrix B is %d.\"\n \"But expect k == k1\",\n k, k1));\n int lda = (!trans_a) ? k : m;\n int ldb = (!trans_b) ? n : k;\n int ldc = n;\n T alpha = static_cast(1.0);\n T beta = static_cast(0.0);\n const T* data_a = out_g->data();\n const T* data_b = filter->data();\n T* data_c = col_data;\n\n r = xpu::fc_fusion(\n xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b,\n nullptr, nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr,\n xpu::Activation_t::LINEAR);\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"fc_fusion\");\n }\n\n if (in_g) {\n PADDLE_ENFORCE_LT(sequence_width, 512,\n platform::errors::InvalidArgument(\n \"Only support sequence_width < 512.\"));\n\n in_g->mutable_data(context.GetPlace());\n in_g->set_lod(in->lod());\n xpu::constant(xpu_context, in_g->data(), in_g->numel(), T(0));\n\n int r = xpu::sequence_context_projection_grad(\n xpu_context, in_g->data(), col_data, nullptr, lodx, sequence_width,\n context_start, context_length, context_stride, {2, 2});\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"sequence_context_projection_grad\");\n }\n\n if (filter_g) {\n filter_g->mutable_data(context.GetPlace());\n xpu::constant(xpu_context, filter_g->data(), filter_g->numel(),\n T(0));\n\n int r = xpu::sequence_context_projection(\n xpu_context, in->data(), col_data, nullptr, lodx, sequence_width,\n context_start, context_length, context_stride, {2, 2});\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"sequence_context_projection\");\n\n bool trans_a = true;\n bool trans_b = false;\n int k = col_shape[0];\n int m = col_shape[1];\n int k1 = out_g->dims()[0];\n int n = out_g->dims()[1];\n PADDLE_ENFORCE_EQ(k, k1,\n platform::errors::InvalidArgument(\n \"The shape of FC in SequenceConvGradOp is invalid.\"\n \"The k of matrix A is %d, k1 of matrix B is %d.\"\n \"But expect k == k1\",\n k, k1));\n int lda = (!trans_a) ? k : m;\n int ldb = (!trans_b) ? n : k;\n int ldc = n;\n T alpha = static_cast(1.0);\n T beta = static_cast(0.0);\n const T* data_a = col_data;\n const T* data_b = out_g->data();\n T* data_c = filter_g->data();\n\n r = xpu::fc_fusion(\n xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b,\n nullptr, nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr,\n xpu::Activation_t::LINEAR);\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"fc_fusion\");\n if (xpu_context->xpu_stream != nullptr) {\n xpu_wait(xpu_context->xpu_stream);\n }\n }\n }\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nREGISTER_OP_XPU_KERNEL(\n sequence_conv,\n ops::SequenceConvXPUKernel);\n\nREGISTER_OP_XPU_KERNEL(\n sequence_conv_grad,\n ops::SequenceConvGradXPUKernel);\n\n#endif\nremove unnecessary constant fill in sequence conv test=kunlun. (#40126)\/* Copyright (c) 2021 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#ifdef PADDLE_WITH_XPU\n\n#include \"paddle\/fluid\/operators\/sequence_ops\/sequence_conv_op.h\"\n#include \"paddle\/fluid\/platform\/device\/device_wrapper.h\"\n\nnamespace paddle {\nnamespace operators {\nusing Tensor = framework::Tensor;\n\ntemplate \nclass SequenceConvXPUKernel : public framework::OpKernel {\n public:\n void Compute(const framework::ExecutionContext& context) const override {\n auto* in = context.Input(\"X\");\n auto* out = context.Output(\"Out\");\n auto filter = *context.Input(\"Filter\");\n\n out->mutable_data(context.GetPlace());\n\n int context_start = context.Attr(\"contextStart\");\n int context_length = context.Attr(\"contextLength\");\n int context_stride = context.Attr(\"contextStride\");\n bool padding_trainable = context.Attr(\"paddingTrainable\");\n\n PADDLE_ENFORCE_EQ(\n in->lod().empty(), false,\n platform::errors::InvalidArgument(\"Input(X) Tensor of SequenceConvOp \"\n \"does not contain LoD information.\"));\n PADDLE_ENFORCE_EQ(\n in->lod().size(), 1UL,\n platform::errors::InvalidArgument(\n \"Only support input sequence with lod level equal to 1 at \"\n \"present. But received: lod level %u.\",\n in->lod().size()));\n\n PADDLE_ENFORCE_EQ(\n padding_trainable, false,\n platform::errors::InvalidArgument(\"Only support padding_trainable \"\n \"equal false.\"));\n\n int up_pad = std::max(0, -context_start);\n int down_pad = std::max(0, context_start + context_length - 1);\n PADDLE_ENFORCE_EQ(up_pad, 2, platform::errors::InvalidArgument(\n \"Only support up_pad equal 2.\"));\n PADDLE_ENFORCE_EQ(down_pad, 2, platform::errors::InvalidArgument(\n \"Only support down_pad equal 2.\"));\n\n auto xpu_context =\n context.template device_context().x_context();\n auto sequence_width = static_cast(in->dims()[1]);\n framework::DDim col_shape = {in->dims()[0],\n context_length * sequence_width};\n xpu::ctx_guard RAII_GUARD(xpu_context);\n int col_numel = col_shape[0] * col_shape[1];\n T* col_data = RAII_GUARD.alloc_l3_or_gm(col_numel);\n PADDLE_ENFORCE_NOT_NULL(\n col_data, paddle::platform::errors::Fatal(\"XPU memory is not enough\"));\n\n auto lod_level_0 = in->lod()[0];\n int lod_size = lod_level_0.size();\n \/\/ If batch size set to 256, the lod is {0, batch[0] - 0,\n \/\/ batch[1] - batch [0], ..., batch[255] - batch[254]},\n \/\/ so the lod_size will be 257.\n PADDLE_ENFORCE_LE(lod_size, 257, platform::errors::InvalidArgument(\n \"Only support batch size <= 256.\"));\n\n std::vector cpu_lodx(lod_size);\n for (int i = 0; i < lod_size; i++) {\n cpu_lodx[i] = lod_level_0[i];\n }\n xpu::VectorParam lodx = {cpu_lodx.data(),\n static_cast(cpu_lodx.size()), nullptr};\n\n int r = xpu::sequence_context_projection(\n xpu_context, in->data(), col_data, nullptr, lodx, sequence_width,\n context_start, context_length, context_stride, {2, 2});\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"sequence_context_projection\");\n\n bool trans_a = false;\n bool trans_b = false;\n int m = col_shape[0];\n int k = col_shape[1];\n int k1 = filter.dims()[0];\n int n = filter.dims()[1];\n PADDLE_ENFORCE_EQ(k, k1,\n platform::errors::InvalidArgument(\n \"The shape of FC in SequenceConvOp is invalid.\"\n \"The k of matrix A is %d, k1 of matrix B is %d.\"\n \"But expect k == k1\",\n k, k1));\n int lda = (!trans_a) ? k : m;\n int ldb = (!trans_b) ? n : k;\n int ldc = n;\n T alpha = static_cast(1.0);\n T beta = static_cast(0.0);\n const T* data_a = col_data;\n const T* data_b = filter.data();\n T* data_c = out->data();\n\n r = xpu::fc_fusion(\n xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b, nullptr,\n nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr,\n xpu::Activation_t::LINEAR);\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"fc_fusion\");\n if (xpu_context->xpu_stream != nullptr) {\n xpu_wait(xpu_context->xpu_stream);\n }\n }\n};\n\ntemplate \nclass SequenceConvGradXPUKernel : public framework::OpKernel {\n public:\n void Compute(const framework::ExecutionContext& context) const override {\n auto* in_g = context.Output(framework::GradVarName(\"X\"));\n auto* out_g = context.Input(framework::GradVarName(\"Out\"));\n auto* filter_g = context.Output(framework::GradVarName(\"Filter\"));\n auto* in = context.Input(\"X\");\n auto* filter = context.Input(\"Filter\");\n\n int context_start = context.Attr(\"contextStart\");\n int context_length = context.Attr(\"contextLength\");\n int context_stride = context.Attr(\"contextStride\");\n bool padding_trainable = context.Attr(\"paddingTrainable\");\n\n PADDLE_ENFORCE_EQ(\n in->lod().empty(), false,\n platform::errors::InvalidArgument(\"Input(X) Tensor of SequenceConvOp \"\n \"does not contain LoD information.\"));\n PADDLE_ENFORCE_EQ(\n in->lod().size(), 1UL,\n platform::errors::InvalidArgument(\n \"Only support input sequence with lod level equal to 1 at \"\n \"present. But received: lod level %u.\",\n in->lod().size()));\n\n PADDLE_ENFORCE_EQ(\n padding_trainable, false,\n platform::errors::InvalidArgument(\"Only support padding_trainable \"\n \"equal false.\"));\n\n int up_pad = std::max(0, -context_start);\n int down_pad = std::max(0, context_start + context_length - 1);\n PADDLE_ENFORCE_EQ(up_pad, 2, platform::errors::InvalidArgument(\n \"Only support up_pad equal 2.\"));\n PADDLE_ENFORCE_EQ(down_pad, 2, platform::errors::InvalidArgument(\n \"Only support down_pad equal 2.\"));\n\n auto lod_level_0 = in->lod()[0];\n int lod_size = lod_level_0.size();\n PADDLE_ENFORCE_LE(lod_size, 257, platform::errors::InvalidArgument(\n \"Only support batch size <= 256.\"));\n\n std::vector cpu_lodx(lod_size);\n for (int i = 0; i < lod_size; i++) {\n cpu_lodx[i] = lod_level_0[i];\n }\n xpu::VectorParam lodx = {cpu_lodx.data(),\n static_cast(cpu_lodx.size()), nullptr};\n\n auto xpu_context =\n context.template device_context().x_context();\n auto sequence_width = static_cast(in->dims()[1]);\n framework::DDim col_shape = {in->dims()[0],\n context_length * sequence_width};\n xpu::ctx_guard RAII_GUARD(xpu_context);\n int col_numel = col_shape[0] * col_shape[1];\n T* col_data = RAII_GUARD.alloc_l3_or_gm(col_numel);\n PADDLE_ENFORCE_NOT_NULL(\n col_data, paddle::platform::errors::Fatal(\"XPU memory is not enough\"));\n\n if (in_g || filter_g) {\n bool trans_a = false;\n bool trans_b = true;\n int m = out_g->dims()[0];\n int k = out_g->dims()[1];\n int n = filter->dims()[0];\n int k1 = filter->dims()[1];\n PADDLE_ENFORCE_EQ(k, k1,\n platform::errors::InvalidArgument(\n \"The shape of FC in SequenceConvGradOp is invalid.\"\n \"The k of matrix A is %d, k1 of matrix B is %d.\"\n \"But expect k == k1\",\n k, k1));\n int lda = (!trans_a) ? k : m;\n int ldb = (!trans_b) ? n : k;\n int ldc = n;\n T alpha = static_cast(1.0);\n T beta = static_cast(0.0);\n const T* data_a = out_g->data();\n const T* data_b = filter->data();\n T* data_c = col_data;\n\n int r = xpu::fc_fusion(\n xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b,\n nullptr, nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr,\n xpu::Activation_t::LINEAR);\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"fc_fusion\");\n }\n\n if (in_g) {\n PADDLE_ENFORCE_LT(sequence_width, 512,\n platform::errors::InvalidArgument(\n \"Only support sequence_width < 512.\"));\n\n in_g->mutable_data(context.GetPlace());\n in_g->set_lod(in->lod());\n\n int r = xpu::sequence_context_projection_grad(\n xpu_context, in_g->data(), col_data, nullptr, lodx, sequence_width,\n context_start, context_length, context_stride, {2, 2});\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"sequence_context_projection_grad\");\n }\n\n if (filter_g) {\n filter_g->mutable_data(context.GetPlace());\n\n int r = xpu::sequence_context_projection(\n xpu_context, in->data(), col_data, nullptr, lodx, sequence_width,\n context_start, context_length, context_stride, {2, 2});\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"sequence_context_projection\");\n\n bool trans_a = true;\n bool trans_b = false;\n int k = col_shape[0];\n int m = col_shape[1];\n int k1 = out_g->dims()[0];\n int n = out_g->dims()[1];\n PADDLE_ENFORCE_EQ(k, k1,\n platform::errors::InvalidArgument(\n \"The shape of FC in SequenceConvGradOp is invalid.\"\n \"The k of matrix A is %d, k1 of matrix B is %d.\"\n \"But expect k == k1\",\n k, k1));\n int lda = (!trans_a) ? k : m;\n int ldb = (!trans_b) ? n : k;\n int ldc = n;\n T alpha = static_cast(1.0);\n T beta = static_cast(0.0);\n const T* data_a = col_data;\n const T* data_b = out_g->data();\n T* data_c = filter_g->data();\n\n r = xpu::fc_fusion(\n xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b,\n nullptr, nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr,\n xpu::Activation_t::LINEAR);\n PADDLE_ENFORCE_XDNN_SUCCESS(r, \"fc_fusion\");\n if (xpu_context->xpu_stream != nullptr) {\n xpu_wait(xpu_context->xpu_stream);\n }\n }\n }\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nREGISTER_OP_XPU_KERNEL(\n sequence_conv,\n ops::SequenceConvXPUKernel);\n\nREGISTER_OP_XPU_KERNEL(\n sequence_conv_grad,\n ops::SequenceConvGradXPUKernel);\n\n#endif\n<|endoftext|>"} {"text":"\/\/===--- XPCService.cpp ---------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 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#include \"sourcekitd\/Internal-XPC.h\"\n#include \"sourcekitd\/Logging.h\"\n#include \"sourcekitd\/XpcTracing.h\"\n\n#include \"SourceKit\/Core\/LLVM.h\"\n#include \"SourceKit\/Support\/Concurrency.h\"\n#include \"SourceKit\/Support\/UIdent.h\"\n#include \"SourceKit\/Support\/Logging.h\"\n\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/Errno.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Threading.h\"\n\n#include \n\nusing namespace SourceKit;\nusing namespace sourcekitd;\n\nstatic xpc_connection_t MainConnection = nullptr;\n\nvoid sourcekitd::postNotification(sourcekitd_response_t Notification) {\n xpc_connection_t peer = MainConnection;\n if (!peer)\n goto done;\n\n {\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::Notification);\n xpc_array_set_value(contents, XPC_ARRAY_APPEND, Notification);\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_connection_send_message(peer, msg);\n xpc_release(msg);\n }\n\ndone:\n \/\/ The function accepted ownership.\n xpc_release(Notification);\n}\n\nnamespace {\n\/\/\/ \\brief Associates sourcekitd_uid_t to a UIdent.\nclass SKUIDToUIDMap {\n typedef llvm::DenseMap MapTy;\n MapTy Map;\n WorkQueue Queue{ WorkQueue::Dequeuing::Concurrent, \"UIDMap\" };\n\npublic:\n UIdent get(sourcekitd_uid_t SKDUID);\n void set(sourcekitd_uid_t SKDUID, UIdent UID);\n};\n}\n\nstatic SKUIDToUIDMap UIDMap;\n\nsourcekitd_uid_t sourcekitd::SKDUIDFromUIdent(UIdent UID) {\n if (void *Tag = UID.getTag())\n return reinterpret_cast(Tag);\n\n \/\/ FIXME: The following should run in the synchronous dispatch queue of the\n \/\/ connection. But does it matter, since if MainConnection is null or gets\n \/\/ destroyed it means the client crashed ?\n xpc_connection_t peer = MainConnection;\n if (!peer)\n return nullptr;\n\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::UIDSynchronization);\n xpc_array_set_string(contents, XPC_ARRAY_APPEND, UID.c_str());\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return nullptr;\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n uint64_t val = xpc_dictionary_get_uint64(reply, xpc::KeyMsgResponse);\n xpc_release(reply);\n\n sourcekitd_uid_t skduid = sourcekitd_uid_t(val);\n UID.setTag(skduid);\n UIDMap.set(skduid, UID);\n return skduid;\n}\n\nUIdent sourcekitd::UIdentFromSKDUID(sourcekitd_uid_t SKDUID) {\n \/\/ This should be used only for debugging\/logging purposes.\n\n UIdent UID = UIDMap.get(SKDUID);\n if (UID.isValid())\n return UID;\n\n xpc_connection_t Peer = MainConnection;\n if (!Peer)\n return UIdent();\n\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::UIDSynchronization);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, uintptr_t(SKDUID));\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(Peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return UIdent();\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n const char *Str = xpc_dictionary_get_string(reply, xpc::KeyMsgResponse);\n\n UID = UIdent(Str);\n UID.setTag(SKDUID);\n UIDMap.set(SKDUID, UID);\n\n xpc_release(reply);\n return UID;\n}\n\nvoid anchorForGetMainExecutableInXPCService() {}\n\nnamespace {\n\/\/\/ Responsible for replying to an XPC request.\nclass XPCResponder {\n xpc_connection_t Peer;\n xpc_object_t Event;\n bool Responded = false;\n\npublic:\n XPCResponder(xpc_object_t event, xpc_connection_t peer)\n : Peer(xpc_connection_t(xpc_retain(peer))), Event(xpc_retain(event)) {}\n\n ~XPCResponder() {\n if (!Responded) {\n LOG_WARN_FUNC(\"failed to respond to request\");\n sendReply(createErrorRequestFailed(\"Internal error: no response was \"\n \"provided for the request\"));\n }\n xpc_release(Event);\n xpc_release(Peer);\n }\n\n \/\/\/ Accepts ownership of the response object.\n void sendReply(sourcekitd_response_t response) {\n if (Responded) {\n LOG_WARN_FUNC(\"tried to respond to an already handled request\");\n return;\n }\n\n xpc_object_t reply = xpc_dictionary_create_reply(Event);\n xpc_dictionary_set_value(reply, xpc::KeyMsgResponse, response);\n xpc_release(response);\n\n xpc_connection_send_message(Peer, reply);\n xpc_release(reply);\n Responded = true;\n }\n};\n}\n\nstd::string sourcekitd::getRuntimeLibPath() {\n std::string MainExePath = llvm::sys::fs::getMainExecutable(\"sourcekit\",\n reinterpret_cast(&anchorForGetMainExecutableInXPCService));\n#ifdef SOURCEKIT_UNVERSIONED_FRAMEWORK_BUNDLE\n \/\/ MainExePath points to \"lib\/sourcekitd.framework\/XPCServices\/\n \/\/ SourceKitService.xpc\/SourceKitService\"\n const unsigned MainExeLibNestingLevel = 4;\n#else\n \/\/ MainExePath points to \"lib\/sourcekitd.framework\/Versions\/Current\/XPCServices\/\n \/\/ SourceKitService.xpc\/Contents\/MacOS\/SourceKitService\"\n const unsigned MainExeLibNestingLevel = 8;\n#endif\n\n \/\/ Get it to lib.\n StringRef Path = MainExePath;\n for (unsigned i = 0; i < MainExeLibNestingLevel; ++i)\n Path = llvm::sys::path::parent_path(Path);\n return Path;\n}\n\nstatic void sourcekitdServer_peer_event_handler(xpc_connection_t peer,\n xpc_object_t event) {\n xpc_type_t type = xpc_get_type(event);\n if (type == XPC_TYPE_ERROR) {\n if (event == XPC_ERROR_CONNECTION_INVALID) {\n \/\/ The client process on the other end of the connection has either\n \/\/ crashed or cancelled the connection. After receiving this error,\n \/\/ the connection is in an invalid state, and we do not need to\n \/\/ call xpc_connection_cancel(). Tear down any associated state\n \/\/ here.\n sourcekitd::shutdown();\n xpc_transaction_end();\n } else if (event == XPC_ERROR_TERMINATION_IMMINENT) {\n \/\/ Handle per-connection termination cleanup.\n xpc_connection_cancel(peer);\n }\n\n } else {\n assert(type == XPC_TYPE_DICTIONARY);\n \/\/ Handle the message\n xpc_retain(event);\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),\n ^{\n xpc_object_t contents = xpc_dictionary_get_value(event, \"msg\");\n\n if (!contents) {\n \/\/ Ping back.\n contents = xpc_dictionary_get_value(event, \"ping\");\n assert(contents && \"unexpected message\");\n xpc_object_t reply = xpc_dictionary_create_reply(event);\n assert(reply);\n xpc_connection_send_message(peer, reply);\n xpc_release(reply);\n return;\n }\n\n auto Responder = std::make_shared(event, peer);\n xpc_release(event);\n\n assert(xpc_get_type(contents) == XPC_TYPE_ARRAY);\n sourcekitd_object_t req = xpc_array_get_value(contents, 0);\n sourcekitd::handleRequest(req,\n [Responder](sourcekitd_response_t response) {\n Responder->sendReply(response);\n });\n });\n }\n}\n\nstatic void getInitializationInfo(xpc_connection_t peer) {\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::Initialization);\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return;\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n uint64_t Delay = xpc_dictionary_get_uint64(reply, xpc::KeySemaEditorDelay);\n uint64_t TracingEnabled = xpc_dictionary_get_uint64(reply,\n xpc::KeyTracingEnabled);\n xpc_release(reply);\n\n if (Delay != 0) {\n llvm::SmallString<4> Buf;\n {\n llvm::raw_svector_ostream OS(Buf);\n OS << Delay;\n }\n setenv(\"SOURCEKIT_DELAY_SEMA_EDITOR\", Buf.c_str(), \/*overwrite=*\/1);\n }\n\n if (TracingEnabled) {\n SourceKit::trace::enable();\n }\n}\n\nstatic void sourcekitdServer_event_handler(xpc_connection_t peer) {\n \/\/ Keep the service alive even when idle.\n xpc_transaction_begin();\n\n \/\/ By defaults, new connections will target the default dispatch\n \/\/ concurrent queue.\n xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {\n sourcekitdServer_peer_event_handler(peer, event);\n });\n\n MainConnection = peer;\n\n \/\/ This will tell the connection to begin listening for events. If you\n \/\/ have some other initialization that must be done asynchronously, then\n \/\/ you can defer this call until after that initialization is done.\n xpc_connection_resume(peer);\n\n dispatch_async(dispatch_get_main_queue(), ^{\n getInitializationInfo(MainConnection);\n });\n}\n\nstatic void fatal_error_handler(void *user_data, const std::string& reason,\n bool gen_crash_diag) {\n \/\/ Write the result out to stderr avoiding errs() because raw_ostreams can\n \/\/ call report_fatal_error.\n fprintf(stderr, \"SOURCEKITD SERVER FATAL ERROR: %s\\n\", reason.c_str());\n ::abort();\n}\n\nint main(int argc, const char *argv[]) {\n llvm::install_fatal_error_handler(fatal_error_handler, 0);\n sourcekitd::enableLogging(\"sourcekit-serv\");\n sourcekitd::initialize();\n sourcekitd::trace::initialize();\n\n \/\/ Increase the file descriptor limit.\n \/\/ FIXME: Portability ?\n static const size_t FDLimit = 4096;\n struct rlimit l;\n if (getrlimit(RLIMIT_NOFILE, &l) == 0) {\n if (l.rlim_cur < FDLimit) {\n l.rlim_cur = FDLimit;\n if (setrlimit(RLIMIT_NOFILE, &l) == 0) {\n LOG_INFO_FUNC(Low, \"bumped file descriptor limit to \" << FDLimit);\n } else {\n LOG_WARN_FUNC(\"setrlimit failed: \" << llvm::sys::StrError());\n }\n }\n } else {\n LOG_WARN_FUNC(\"getrlimit failed: \" << llvm::sys::StrError());\n }\n\n xpc_main(sourcekitdServer_event_handler);\n return 0;\n}\n\nUIdent SKUIDToUIDMap::get(sourcekitd_uid_t SKDUID) {\n UIdent UID;\n Queue.dispatchSync([&]{\n MapTy::iterator It = Map.find(SKDUID);\n if (It != Map.end())\n UID = It->second;\n });\n\n return UID;\n}\n\nvoid SKUIDToUIDMap::set(sourcekitd_uid_t SKDUID, UIdent UID) {\n Queue.dispatchBarrier([=]{\n this->Map[SKDUID] = UID;\n });\n}\n\nvoid sourcekitd::trace::sendTraceMessage(trace::sourcekitd_trace_message_t Msg) {\n if (!SourceKit::trace::enabled()) {\n xpc_release(Msg);\n return;\n }\n\n xpc_connection_t Peer = MainConnection;\n if (!Peer) {\n SourceKit::trace::disable();\n xpc_release(Msg);\n return;\n }\n\n xpc_object_t Contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(Contents, XPC_ARRAY_APPEND,\n static_cast(xpc::Message::TraceMessage));\n xpc_array_set_uint64(Contents, XPC_ARRAY_APPEND,\n trace::getTracingSession());\n xpc_array_set_value(Contents, XPC_ARRAY_APPEND, Msg);\n xpc_release(Msg);\n\n xpc_object_t Message = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(Message, xpc::KeyInternalMsg, Contents);\n xpc_release(Contents);\n\n xpc_object_t Reply =\n xpc_connection_send_message_with_reply_sync(Peer, Message);\n xpc_release(Message);\n\n if (xpc_get_type(Reply) == XPC_TYPE_ERROR) {\n SourceKit::trace::disable();\n xpc_release(Reply);\n return;\n }\n\n xpc_release(Reply);\n}\n\n[SourceKit] Avoid calling \"sourcekitd::shutdown()\" on the service side, when the connection closes.\/\/===--- XPCService.cpp ---------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 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#include \"sourcekitd\/Internal-XPC.h\"\n#include \"sourcekitd\/Logging.h\"\n#include \"sourcekitd\/XpcTracing.h\"\n\n#include \"SourceKit\/Core\/LLVM.h\"\n#include \"SourceKit\/Support\/Concurrency.h\"\n#include \"SourceKit\/Support\/UIdent.h\"\n#include \"SourceKit\/Support\/Logging.h\"\n\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/Errno.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Threading.h\"\n\n#include \n\nusing namespace SourceKit;\nusing namespace sourcekitd;\n\nstatic xpc_connection_t MainConnection = nullptr;\n\nvoid sourcekitd::postNotification(sourcekitd_response_t Notification) {\n xpc_connection_t peer = MainConnection;\n if (!peer)\n goto done;\n\n {\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::Notification);\n xpc_array_set_value(contents, XPC_ARRAY_APPEND, Notification);\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_connection_send_message(peer, msg);\n xpc_release(msg);\n }\n\ndone:\n \/\/ The function accepted ownership.\n xpc_release(Notification);\n}\n\nnamespace {\n\/\/\/ \\brief Associates sourcekitd_uid_t to a UIdent.\nclass SKUIDToUIDMap {\n typedef llvm::DenseMap MapTy;\n MapTy Map;\n WorkQueue Queue{ WorkQueue::Dequeuing::Concurrent, \"UIDMap\" };\n\npublic:\n UIdent get(sourcekitd_uid_t SKDUID);\n void set(sourcekitd_uid_t SKDUID, UIdent UID);\n};\n}\n\nstatic SKUIDToUIDMap UIDMap;\n\nsourcekitd_uid_t sourcekitd::SKDUIDFromUIdent(UIdent UID) {\n if (void *Tag = UID.getTag())\n return reinterpret_cast(Tag);\n\n \/\/ FIXME: The following should run in the synchronous dispatch queue of the\n \/\/ connection. But does it matter, since if MainConnection is null or gets\n \/\/ destroyed it means the client crashed ?\n xpc_connection_t peer = MainConnection;\n if (!peer)\n return nullptr;\n\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::UIDSynchronization);\n xpc_array_set_string(contents, XPC_ARRAY_APPEND, UID.c_str());\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return nullptr;\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n uint64_t val = xpc_dictionary_get_uint64(reply, xpc::KeyMsgResponse);\n xpc_release(reply);\n\n sourcekitd_uid_t skduid = sourcekitd_uid_t(val);\n UID.setTag(skduid);\n UIDMap.set(skduid, UID);\n return skduid;\n}\n\nUIdent sourcekitd::UIdentFromSKDUID(sourcekitd_uid_t SKDUID) {\n \/\/ This should be used only for debugging\/logging purposes.\n\n UIdent UID = UIDMap.get(SKDUID);\n if (UID.isValid())\n return UID;\n\n xpc_connection_t Peer = MainConnection;\n if (!Peer)\n return UIdent();\n\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::UIDSynchronization);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, uintptr_t(SKDUID));\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(Peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return UIdent();\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n const char *Str = xpc_dictionary_get_string(reply, xpc::KeyMsgResponse);\n\n UID = UIdent(Str);\n UID.setTag(SKDUID);\n UIDMap.set(SKDUID, UID);\n\n xpc_release(reply);\n return UID;\n}\n\nvoid anchorForGetMainExecutableInXPCService() {}\n\nnamespace {\n\/\/\/ Responsible for replying to an XPC request.\nclass XPCResponder {\n xpc_connection_t Peer;\n xpc_object_t Event;\n bool Responded = false;\n\npublic:\n XPCResponder(xpc_object_t event, xpc_connection_t peer)\n : Peer(xpc_connection_t(xpc_retain(peer))), Event(xpc_retain(event)) {}\n\n ~XPCResponder() {\n if (!Responded) {\n LOG_WARN_FUNC(\"failed to respond to request\");\n sendReply(createErrorRequestFailed(\"Internal error: no response was \"\n \"provided for the request\"));\n }\n xpc_release(Event);\n xpc_release(Peer);\n }\n\n \/\/\/ Accepts ownership of the response object.\n void sendReply(sourcekitd_response_t response) {\n if (Responded) {\n LOG_WARN_FUNC(\"tried to respond to an already handled request\");\n return;\n }\n\n xpc_object_t reply = xpc_dictionary_create_reply(Event);\n xpc_dictionary_set_value(reply, xpc::KeyMsgResponse, response);\n xpc_release(response);\n\n xpc_connection_send_message(Peer, reply);\n xpc_release(reply);\n Responded = true;\n }\n};\n}\n\nstd::string sourcekitd::getRuntimeLibPath() {\n std::string MainExePath = llvm::sys::fs::getMainExecutable(\"sourcekit\",\n reinterpret_cast(&anchorForGetMainExecutableInXPCService));\n#ifdef SOURCEKIT_UNVERSIONED_FRAMEWORK_BUNDLE\n \/\/ MainExePath points to \"lib\/sourcekitd.framework\/XPCServices\/\n \/\/ SourceKitService.xpc\/SourceKitService\"\n const unsigned MainExeLibNestingLevel = 4;\n#else\n \/\/ MainExePath points to \"lib\/sourcekitd.framework\/Versions\/Current\/XPCServices\/\n \/\/ SourceKitService.xpc\/Contents\/MacOS\/SourceKitService\"\n const unsigned MainExeLibNestingLevel = 8;\n#endif\n\n \/\/ Get it to lib.\n StringRef Path = MainExePath;\n for (unsigned i = 0; i < MainExeLibNestingLevel; ++i)\n Path = llvm::sys::path::parent_path(Path);\n return Path;\n}\n\nstatic void sourcekitdServer_peer_event_handler(xpc_connection_t peer,\n xpc_object_t event) {\n xpc_type_t type = xpc_get_type(event);\n if (type == XPC_TYPE_ERROR) {\n if (event == XPC_ERROR_CONNECTION_INVALID) {\n \/\/ The client process on the other end of the connection has either\n \/\/ crashed or cancelled the connection. After receiving this error,\n \/\/ the connection is in an invalid state, and we do not need to\n \/\/ call xpc_connection_cancel().\n \/\/ No need to call sourcekitd::shutdown() since the process is going down\n \/\/ anyway, plus if we get a new connection before the process closes then\n \/\/ we will fail to re-initialize properly since the initialize call is at\n \/\/ main.\n xpc_transaction_end();\n } else if (event == XPC_ERROR_TERMINATION_IMMINENT) {\n \/\/ Handle per-connection termination cleanup.\n xpc_connection_cancel(peer);\n }\n\n } else {\n assert(type == XPC_TYPE_DICTIONARY);\n \/\/ Handle the message\n xpc_retain(event);\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),\n ^{\n xpc_object_t contents = xpc_dictionary_get_value(event, \"msg\");\n\n if (!contents) {\n \/\/ Ping back.\n contents = xpc_dictionary_get_value(event, \"ping\");\n assert(contents && \"unexpected message\");\n xpc_object_t reply = xpc_dictionary_create_reply(event);\n assert(reply);\n xpc_connection_send_message(peer, reply);\n xpc_release(reply);\n return;\n }\n\n auto Responder = std::make_shared(event, peer);\n xpc_release(event);\n\n assert(xpc_get_type(contents) == XPC_TYPE_ARRAY);\n sourcekitd_object_t req = xpc_array_get_value(contents, 0);\n sourcekitd::handleRequest(req,\n [Responder](sourcekitd_response_t response) {\n Responder->sendReply(response);\n });\n });\n }\n}\n\nstatic void getInitializationInfo(xpc_connection_t peer) {\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::Initialization);\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return;\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n uint64_t Delay = xpc_dictionary_get_uint64(reply, xpc::KeySemaEditorDelay);\n uint64_t TracingEnabled = xpc_dictionary_get_uint64(reply,\n xpc::KeyTracingEnabled);\n xpc_release(reply);\n\n if (Delay != 0) {\n llvm::SmallString<4> Buf;\n {\n llvm::raw_svector_ostream OS(Buf);\n OS << Delay;\n }\n setenv(\"SOURCEKIT_DELAY_SEMA_EDITOR\", Buf.c_str(), \/*overwrite=*\/1);\n }\n\n if (TracingEnabled) {\n SourceKit::trace::enable();\n }\n}\n\nstatic void sourcekitdServer_event_handler(xpc_connection_t peer) {\n \/\/ Keep the service alive even when idle.\n xpc_transaction_begin();\n\n \/\/ By defaults, new connections will target the default dispatch\n \/\/ concurrent queue.\n xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {\n sourcekitdServer_peer_event_handler(peer, event);\n });\n\n MainConnection = peer;\n\n \/\/ This will tell the connection to begin listening for events. If you\n \/\/ have some other initialization that must be done asynchronously, then\n \/\/ you can defer this call until after that initialization is done.\n xpc_connection_resume(peer);\n\n dispatch_async(dispatch_get_main_queue(), ^{\n getInitializationInfo(MainConnection);\n });\n}\n\nstatic void fatal_error_handler(void *user_data, const std::string& reason,\n bool gen_crash_diag) {\n \/\/ Write the result out to stderr avoiding errs() because raw_ostreams can\n \/\/ call report_fatal_error.\n fprintf(stderr, \"SOURCEKITD SERVER FATAL ERROR: %s\\n\", reason.c_str());\n ::abort();\n}\n\nint main(int argc, const char *argv[]) {\n llvm::install_fatal_error_handler(fatal_error_handler, 0);\n sourcekitd::enableLogging(\"sourcekit-serv\");\n sourcekitd::initialize();\n sourcekitd::trace::initialize();\n\n \/\/ Increase the file descriptor limit.\n \/\/ FIXME: Portability ?\n static const size_t FDLimit = 4096;\n struct rlimit l;\n if (getrlimit(RLIMIT_NOFILE, &l) == 0) {\n if (l.rlim_cur < FDLimit) {\n l.rlim_cur = FDLimit;\n if (setrlimit(RLIMIT_NOFILE, &l) == 0) {\n LOG_INFO_FUNC(Low, \"bumped file descriptor limit to \" << FDLimit);\n } else {\n LOG_WARN_FUNC(\"setrlimit failed: \" << llvm::sys::StrError());\n }\n }\n } else {\n LOG_WARN_FUNC(\"getrlimit failed: \" << llvm::sys::StrError());\n }\n\n xpc_main(sourcekitdServer_event_handler);\n return 0;\n}\n\nUIdent SKUIDToUIDMap::get(sourcekitd_uid_t SKDUID) {\n UIdent UID;\n Queue.dispatchSync([&]{\n MapTy::iterator It = Map.find(SKDUID);\n if (It != Map.end())\n UID = It->second;\n });\n\n return UID;\n}\n\nvoid SKUIDToUIDMap::set(sourcekitd_uid_t SKDUID, UIdent UID) {\n Queue.dispatchBarrier([=]{\n this->Map[SKDUID] = UID;\n });\n}\n\nvoid sourcekitd::trace::sendTraceMessage(trace::sourcekitd_trace_message_t Msg) {\n if (!SourceKit::trace::enabled()) {\n xpc_release(Msg);\n return;\n }\n\n xpc_connection_t Peer = MainConnection;\n if (!Peer) {\n SourceKit::trace::disable();\n xpc_release(Msg);\n return;\n }\n\n xpc_object_t Contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(Contents, XPC_ARRAY_APPEND,\n static_cast(xpc::Message::TraceMessage));\n xpc_array_set_uint64(Contents, XPC_ARRAY_APPEND,\n trace::getTracingSession());\n xpc_array_set_value(Contents, XPC_ARRAY_APPEND, Msg);\n xpc_release(Msg);\n\n xpc_object_t Message = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(Message, xpc::KeyInternalMsg, Contents);\n xpc_release(Contents);\n\n xpc_object_t Reply =\n xpc_connection_send_message_with_reply_sync(Peer, Message);\n xpc_release(Message);\n\n if (xpc_get_type(Reply) == XPC_TYPE_ERROR) {\n SourceKit::trace::disable();\n xpc_release(Reply);\n return;\n }\n\n xpc_release(Reply);\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\n\nusing boost::asio::ip::tcp;\n\n\nNetworkSender::NetworkSender(std::shared_ptr replicaset_)\n : io_service_(),\n socket_(io_service_),\n replicaset(replicaset_)\n{\n}\n\n\nNetworkSender::NetworkSender()\n : io_service_(),\n socket_(io_service_),\n replicaset(new ReplicaSet())\n{\n}\n\n\nNetworkSender::~NetworkSender()\n{\n io_service_.post([this]() { socket_.close(); } );\n}\n\n\nvoid\nNetworkSender::Reply(Message message)\n{\n tcp::resolver resolver(io_service_);\n auto endpoint = resolver.resolve(\n {\n message.to.hostname,\n std::to_string(message.to.port)\n });\n boost::asio::async_connect(socket_, endpoint,\n [this, message](boost::system::error_code ec, tcp::resolver::iterator)\n {\n if (!ec)\n {\n \/\/ 1. serialize message\n std::string message_str = Serialize(message).str();\n\n \/\/ 2. write message\n boost::asio::write(\n socket_,\n boost::asio::buffer(\n message_str.c_str(),\n message_str.size()));\n }\n });\n}\n\n\nvoid\nNetworkSender::ReplyAll(Message message)\n{\n for (auto r : *replicaset)\n {\n Message m = message;\n m.to = r;\n Reply(m);\n }\n}\nUpdate network sender to execute synchronous write operations#include \n#include \n\n#include \n\n\nusing boost::asio::ip::tcp;\n\n\nNetworkSender::NetworkSender(std::shared_ptr replicaset_)\n : io_service_(),\n socket_(io_service_),\n replicaset(replicaset_)\n{\n}\n\n\nNetworkSender::NetworkSender()\n : io_service_(),\n socket_(io_service_),\n replicaset(new ReplicaSet())\n{\n}\n\n\nNetworkSender::~NetworkSender()\n{\n socket_.close();\n}\n\n\nvoid\nNetworkSender::Reply(Message message)\n{\n tcp::resolver resolver(io_service_);\n auto endpoint = resolver.resolve(\n {\n message.to.hostname,\n std::to_string(message.to.port)\n });\n boost::asio::connect(socket_, endpoint);\n\n \/\/ 1. serialize message\n std::string message_str = Serialize(message).str();\n\n \/\/ 2. write message\n boost::asio::write(socket_, boost::asio::buffer(message_str.c_str(), message_str.size()));\n}\n\n\nvoid\nNetworkSender::ReplyAll(Message message)\n{\n for (auto r : *replicaset)\n {\n Message m = message;\n m.to = r;\n Reply(m);\n }\n}\n<|endoftext|>"} {"text":"#include \"zonotope_halfspaces.hpp\"\n\n#include \n#include \n\nint main() {\n using namespace std;\n \n typedef mpz_class NT;\n\n int n_tests;\n cin >> n_tests;\n for ( int t = 0; t < n_tests; ++t ) {\n int n, d;\n cin >> n >> d;\n vector > generators ( n, vector ( d ) );\n for ( int i = 0; i < n; ++i ) {\n for ( int j = 0; j < d; ++j ) {\n cin >> generators[i][j];\n }\n }\n\n set > halfspaces = zonotope_halfspaces (generators);\n cout << \"n=\" << n << \" \"\n << \"d=\" << d << \" \"\n << \"ieqs=\" << halfspaces.size() << \"\\n\";\n }\n\n \n return 0;\n}\nUpdate the halfspaces test to also test `long` input\/output#include \"zonotope_halfspaces.hpp\"\n\n#include \n#include \n\nint main() {\n using namespace std;\n \n int n_tests;\n cin >> n_tests;\n for ( int t = 0; t < n_tests; ++t ) {\n int n, d;\n cin >> n >> d;\n\n vector >\n generators_mpz ( n, vector ( d ) );\n\n vector >\n generators_long ( n, vector ( d ) );\n\n for ( int k = 0; k < n; ++k ) {\n for ( int i = 0; i < d; ++i ) {\n cin >> generators_long[k][i];\n generators_mpz[k][i] = generators_long[k][i];\n }\n }\n\n set > halfspaces_mpz;\n zonotope_halfspaces (generators_mpz, halfspaces_mpz);\n\n set > halfspaces_long;\n zonotope_halfspaces (generators_long, halfspaces_long);\n\n cout << \"n=\" << n << \" \"\n << \"d=\" << d << \" \"\n << \"ieqs=\" << halfspaces_mpz.size() << \" \"\n << \"ieqs_long=\" << halfspaces_long.size() << \"\\n\";\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Aki \"lethalbit\" Van Ness \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\/\/ MYAU - Metadata for Yosys-Assisted Utilities\n\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/register.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/cellaigs.h\"\n#include \"kernel\/log.h\"\n#include \n#include \n#include \n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\n\nstruct MetadataWriter\n{\n private:\n std::ostream &f;\n bool _use_selection;\n std::unordered_map> _cells{};\n\n \/\/ XXX(aki): this was pulled from the json backend, needs to be pulled\n \/\/ out possibly into some sort of utilities file, or integrated into rtlil.h\n \/\/ directly\n string get_string(string str)\n {\n string newstr = \"\\\"\";\n for (char c : str) {\n if (c == '\\\\')\n newstr += c;\n newstr += c;\n }\n return newstr + \"\\\"\";\n }\n\n \/\/ XXX(aki): I know this is far from ideal but i'm out of spoons and cant focus so\n \/\/ it'll have to do for now,\n void coalesce_cells(Module* mod)\n {\n for (auto cell : mod->cells()) {\n const auto cell_type = get_string(RTLIL::unescape_id(cell->type));\n\n if (_cells.find(cell_type) == _cells.end())\n _cells.emplace(cell_type, std::vector());\n\n _cells.at(cell_type).push_back(cell);\n }\n }\n\n public:\n MetadataWriter(std::ostream &f, bool use_selection) noexcept: f(f), _use_selection(use_selection) { }\n\n void write_metadata(Design *design)\n {\n log_assert(design != nullptr);\n\n design->sort();\n\n f << stringf(\"{\\n\");\n f << stringf(\" \\\"generator\\\": %s,\\n\", get_string(yosys_version_str).c_str());\n \/\/ XXX(aki): Replace this with a proper version info eventually:tm:\n f << stringf(\" \\\"version\\\": \\\"0.0.0\\\",\\n\");\n f << stringf(\" \\\"modules\\\": [\\n\");\n\n bool first{true};\n for (auto mod : _use_selection ? design->selected_modules() : design->modules()) {\n if (!first)\n f << stringf(\",\\n\");\n write_module(mod);\n\n f << stringf(\"\\n\");\n\n first = false;\n }\n\n f << stringf(\" ]\\n\");\n f << stringf(\"}\\n\");\n }\n\n void write_module(Module* mod)\n {\n log_assert(mod != nullptr);\n\n coalesce_cells(mod);\n\n f << stringf(\" {\\n\");\n f << stringf(\" \\\"name\\\": %s,\\n\", get_string(RTLIL::unescape_id(mod->name)).c_str());\n f << stringf(\" \\\"cell_sorts\\\": [\\n\");\n\n bool first_sort{true};\n for (auto& sort : _cells) {\n if (!first_sort)\n f << stringf(\",\\n\");\n\n write_cell_sort(sort);\n\n first_sort = false;\n }\n f << stringf(\"\\n\");\n\n f << stringf(\" ],\\n\");\n f << stringf(\" \\\"connections\\\": [\\n\");\n\n f << stringf(\" ]\\n\");\n f << stringf(\" }\");\n }\n\n\n void write_cell_sort(std::pair>& sort)\n {\n const auto port_cell = sort.second.front();\n\n f << stringf(\" {\\n\");\n f << stringf(\" \\\"type\\\": %s,\\n\", sort.first.c_str());\n f << stringf(\" \\\"ports\\\": [\\n\");\n\n bool first_port{true};\n for (auto con : port_cell->connections()) {\n if (!first_port)\n f << stringf(\",\\n\");\n\n f << stringf(\" {\\n\");\n f << stringf(\" \\\"name\\\": %s,\\n\", get_string(RTLIL::unescape_id(con.first)).c_str());\n f << stringf(\" \\\"direction\\\": \\\"\");\n if (port_cell->input(con.first))\n f << stringf(\"i\");\n if (port_cell->input(con.first))\n f << stringf(\"o\");\n f << stringf(\"\\\",\\n\");\n if (con.second.size() == 1)\n f << stringf(\" \\\"range\\\": [0, 0]\\n\");\n else\n f << stringf(\" \\\"range\\\": [%d, %d]\\n\", con.second.size(), 0);\n f << stringf(\" }\");\n\n first_port = false;\n }\n f << stringf(\"\\n\");\n\n f << stringf(\" ],\\n \\\"cells\\\": [\\n\");\n bool first_cell{true};\n for (auto& cell : sort.second) {\n if (!first_cell)\n f << stringf(\",\\n\");\n\n write_cell(cell);\n\n first_cell = false;\n }\n f << stringf(\"\\n\");\n f << stringf(\" ]\\n\");\n f << stringf(\" }\");\n }\n\n void write_cell(Cell* cell)\n {\n log_assert(cell != nullptr);\n\n f << stringf(\" {\\n\");\n f << stringf(\" \\\"name\\\": %s,\\n\", get_string(RTLIL::unescape_id(cell->name)).c_str());\n f << stringf(\" \\\"attributes\\\": {\\n\");\n\n bool first_attr{true};\n for (auto& attr : cell->attributes) {\n if (!first_attr)\n f << stringf(\",\\n\");\n const auto attr_val = attr.second.decode_string();\n if (attr_val.size() > 0)\n f << stringf(\" %s: \\\"%s\\\"\\n\", get_string(RTLIL::unescape_id(attr.first)).c_str(), attr_val.c_str());\n else\n f << stringf(\" %s: true\\n\", get_string(RTLIL::unescape_id(attr.first)).c_str());\n\n first_attr = false;\n }\n\n f << stringf(\" },\\n\");\n f << stringf(\" \\\"parameters\\\": {\\n\");\n\n bool first_param{true};\n for (auto& param : cell->parameters) {\n if (!first_param)\n f << stringf(\",\\n\");\n const auto param_val = param.second.decode_string();\n if (param_val.size() > 0)\n f << stringf(\" %s: \\\"%s\\\"\\n\", get_string(RTLIL::unescape_id(param.first)).c_str(), param_val.c_str());\n else\n f << stringf(\" %s: true\\n\", get_string(RTLIL::unescape_id(param.first)).c_str());\n\n first_param = false;\n }\n\n f << stringf(\" },\\n\");\n f << stringf(\" }\");\n }\n};\n\nstruct MetadataBackend : public Backend {\n MetadataBackend() : Backend(\"metadata\", \"generate design metadata\") { }\n void help() override\n {\n \/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n log(\"\\n\");\n log(\" metadata [options] [selection]\\n\");\n log(\"\\n\");\n log(\"Write a JSON metadata for the current design\\n\");\n log(\"\\n\");\n log(\"\\n\");\n }\n\n void execute(std::ostream *&f, std::string filename, std::vector args, RTLIL::Design *design) override\n {\n size_t argidx{1};\n extra_args(f, filename, args, argidx);\n\n log_header(design, \"Executing metadata backend.\\n\");\n\n MetadataWriter metadata_writier(*f, false);\n metadata_writier.write_metadata(design);\n }\n\n} MetadataBackend;\n\n\nstruct MetadataPass : public Pass {\n MetadataPass() : Pass(\"metadata\", \"write design metadata\") { }\n\n void help() override\n {\n \/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n log(\"\\n\");\n log(\" metadata [options] [selection]\\n\");\n log(\"\\n\");\n log(\"Write a JSON metadata for the current design\\n\");\n log(\"\\n\");\n log(\" -o \\n\");\n log(\" write to the specified file.\\n\");\n log(\"\\n\");\n log(\"See 'help write_metadata' for a description of the JSON format used.\\n\");\n log(\"\\n\");\n }\n void execute(std::vector args, RTLIL::Design *design) override\n {\n std::string filename{};\n\n size_t argidx;\n for (argidx = 1; argidx < args.size(); argidx++)\n {\n if (args[argidx] == \"-o\" && argidx+1 < args.size()) {\n filename = args[++argidx];\n continue;\n }\n break;\n }\n extra_args(args, argidx, design);\n\n std::ostream *f;\n std::stringstream buf;\n\n if (!filename.empty()) {\n rewrite_filename(filename);\n std::ofstream *ff = new std::ofstream;\n ff->open(filename.c_str(), std::ofstream::trunc);\n if (ff->fail()) {\n delete ff;\n log_error(\"Can't open file `%s' for writing: %s\\n\", filename.c_str(), strerror(errno));\n }\n f = ff;\n } else {\n f = &buf;\n }\n\n\n MetadataWriter metadata_writier(*f, false);\n metadata_writier.write_metadata(design);\n\n if (!filename.empty()) {\n delete f;\n } else {\n log(\"%s\", buf.str().c_str());\n }\n }\n\n} MetadataPass;\n\nPRIVATE_NAMESPACE_END\npass metadata: some more rough work on dumping the parameters and attributes\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Aki \"lethalbit\" Van Ness \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\/\/ MYAU - Metadata for Yosys-Assisted Utilities\n\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/register.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/cellaigs.h\"\n#include \"kernel\/log.h\"\n#include \n#include \n#include \n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\n\nstruct MetadataWriter\n{\n private:\n std::ostream &f;\n bool _use_selection;\n std::unordered_map> _cells{};\n\n \/\/ XXX(aki): this was pulled from the json backend, needs to be pulled\n \/\/ out possibly into some sort of utilities file, or integrated into rtlil.h\n \/\/ directly\n string get_string(string str)\n {\n string newstr = \"\\\"\";\n for (char c : str) {\n if (c == '\\\\')\n newstr += c;\n newstr += c;\n }\n return newstr + \"\\\"\";\n }\n\n \/\/ XXX(aki): I know this is far from ideal but i'm out of spoons and cant focus so\n \/\/ it'll have to do for now,\n void coalesce_cells(Module* mod)\n {\n for (auto cell : mod->cells()) {\n const auto cell_type = get_string(RTLIL::unescape_id(cell->type));\n\n if (_cells.find(cell_type) == _cells.end())\n _cells.emplace(cell_type, std::vector());\n\n _cells.at(cell_type).push_back(cell);\n }\n }\n\n public:\n MetadataWriter(std::ostream &f, bool use_selection) noexcept: f(f), _use_selection(use_selection) { }\n\n void write_metadata(Design *design)\n {\n log_assert(design != nullptr);\n\n design->sort();\n\n f << stringf(\"{\\n\");\n f << stringf(\" \\\"generator\\\": %s,\\n\", get_string(yosys_version_str).c_str());\n \/\/ XXX(aki): Replace this with a proper version info eventually:tm:\n f << stringf(\" \\\"version\\\": \\\"0.0.0\\\",\\n\");\n f << stringf(\" \\\"modules\\\": [\\n\");\n\n bool first{true};\n for (auto mod : _use_selection ? design->selected_modules() : design->modules()) {\n if (!first)\n f << stringf(\",\\n\");\n write_module(mod);\n\n f << stringf(\"\\n\");\n\n first = false;\n }\n\n f << stringf(\" ]\\n\");\n f << stringf(\"}\\n\");\n }\n\n void write_module(Module* mod)\n {\n log_assert(mod != nullptr);\n\n coalesce_cells(mod);\n\n f << stringf(\" {\\n\");\n f << stringf(\" \\\"name\\\": %s,\\n\", get_string(RTLIL::unescape_id(mod->name)).c_str());\n f << stringf(\" \\\"cell_sorts\\\": [\\n\");\n\n bool first_sort{true};\n for (auto& sort : _cells) {\n if (!first_sort)\n f << stringf(\",\\n\");\n\n write_cell_sort(sort);\n\n first_sort = false;\n }\n f << stringf(\"\\n\");\n\n f << stringf(\" ],\\n\");\n f << stringf(\" \\\"connections\\\": [\\n\");\n\n f << stringf(\" ]\\n\");\n f << stringf(\" }\");\n }\n\n\n void write_cell_sort(std::pair>& sort)\n {\n const auto port_cell = sort.second.front();\n\n f << stringf(\" {\\n\");\n f << stringf(\" \\\"type\\\": %s,\\n\", sort.first.c_str());\n f << stringf(\" \\\"ports\\\": [\\n\");\n\n bool first_port{true};\n for (auto con : port_cell->connections()) {\n if (!first_port)\n f << stringf(\",\\n\");\n\n f << stringf(\" {\\n\");\n f << stringf(\" \\\"name\\\": %s,\\n\", get_string(RTLIL::unescape_id(con.first)).c_str());\n f << stringf(\" \\\"direction\\\": \\\"\");\n if (port_cell->input(con.first))\n f << stringf(\"i\");\n if (port_cell->input(con.first))\n f << stringf(\"o\");\n f << stringf(\"\\\",\\n\");\n if (con.second.size() == 1)\n f << stringf(\" \\\"range\\\": [0, 0]\\n\");\n else\n f << stringf(\" \\\"range\\\": [%d, %d]\\n\", con.second.size(), 0);\n f << stringf(\" }\");\n\n first_port = false;\n }\n f << stringf(\"\\n\");\n\n f << stringf(\" ],\\n \\\"cells\\\": [\\n\");\n bool first_cell{true};\n for (auto& cell : sort.second) {\n if (!first_cell)\n f << stringf(\",\\n\");\n\n write_cell(cell);\n\n first_cell = false;\n }\n f << stringf(\"\\n\");\n f << stringf(\" ]\\n\");\n f << stringf(\" }\");\n }\n\n void write_cell(Cell* cell)\n {\n log_assert(cell != nullptr);\n\n f << stringf(\" {\\n\");\n f << stringf(\" \\\"name\\\": %s,\\n\", get_string(RTLIL::unescape_id(cell->name)).c_str());\n f << stringf(\" \\\"attributes\\\": {\\n\");\n\n bool first_attr{true};\n for (auto& attr : cell->attributes) {\n if (!first_attr)\n f << stringf(\",\\n\");\n const auto attr_val = attr.second;\n if (!attr_val.empty())\n f << stringf(\" %s: \\\"%s\\\"\\n\", get_string(RTLIL::unescape_id(attr.first)).c_str(), attr_val.decode_string().c_str());\n else\n f << stringf(\" %s: true\\n\", get_string(RTLIL::unescape_id(attr.first)).c_str());\n\n first_attr = false;\n }\n\n f << stringf(\" },\\n\");\n f << stringf(\" \\\"parameters\\\": {\\n\");\n\n bool first_param{true};\n for (auto& param : cell->parameters) {\n if (!first_param)\n f << stringf(\",\\n\");\n const auto param_val = param.second;\n if (!param_val.empty())\n f << stringf(\" %s: \\\"%s\\\"\\n\", get_string(RTLIL::unescape_id(param.first)).c_str(), param_val.decode_string().c_str());\n else\n f << stringf(\" %s: true\\n\", get_string(RTLIL::unescape_id(param.first)).c_str());\n\n first_param = false;\n }\n\n f << stringf(\" },\\n\");\n f << stringf(\" }\");\n }\n};\n\nstruct MetadataBackend : public Backend {\n MetadataBackend() : Backend(\"metadata\", \"generate design metadata\") { }\n void help() override\n {\n \/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n log(\"\\n\");\n log(\" metadata [options] [selection]\\n\");\n log(\"\\n\");\n log(\"Write a JSON metadata for the current design\\n\");\n log(\"\\n\");\n log(\"\\n\");\n }\n\n void execute(std::ostream *&f, std::string filename, std::vector args, RTLIL::Design *design) override\n {\n size_t argidx{1};\n extra_args(f, filename, args, argidx);\n\n log_header(design, \"Executing metadata backend.\\n\");\n\n MetadataWriter metadata_writier(*f, false);\n metadata_writier.write_metadata(design);\n }\n\n} MetadataBackend;\n\n\nstruct MetadataPass : public Pass {\n MetadataPass() : Pass(\"metadata\", \"write design metadata\") { }\n\n void help() override\n {\n \/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n log(\"\\n\");\n log(\" metadata [options] [selection]\\n\");\n log(\"\\n\");\n log(\"Write a JSON metadata for the current design\\n\");\n log(\"\\n\");\n log(\" -o \\n\");\n log(\" write to the specified file.\\n\");\n log(\"\\n\");\n log(\"See 'help write_metadata' for a description of the JSON format used.\\n\");\n log(\"\\n\");\n }\n void execute(std::vector args, RTLIL::Design *design) override\n {\n std::string filename{};\n\n size_t argidx;\n for (argidx = 1; argidx < args.size(); argidx++)\n {\n if (args[argidx] == \"-o\" && argidx+1 < args.size()) {\n filename = args[++argidx];\n continue;\n }\n break;\n }\n extra_args(args, argidx, design);\n\n std::ostream *f;\n std::stringstream buf;\n\n if (!filename.empty()) {\n rewrite_filename(filename);\n std::ofstream *ff = new std::ofstream;\n ff->open(filename.c_str(), std::ofstream::trunc);\n if (ff->fail()) {\n delete ff;\n log_error(\"Can't open file `%s' for writing: %s\\n\", filename.c_str(), strerror(errno));\n }\n f = ff;\n } else {\n f = &buf;\n }\n\n\n MetadataWriter metadata_writier(*f, false);\n metadata_writier.write_metadata(design);\n\n if (!filename.empty()) {\n delete f;\n } else {\n log(\"%s\", buf.str().c_str());\n }\n }\n\n} MetadataPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"\/*\n Copyright 2002-2013 CEA LIST\n\n This file is part of LIMA.\n\n LIMA 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 LIMA is distributed in the hope that it 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 LIMA. If not, see \n*\/\n\/************************************************************************\n *\n * @file ExternalProcessUnit.cpp\n * @author besancon (besanconr@zoe.cea.fr)\n * @date Mon Jan 17 2011\n * copyright Copyright (C) 2011 by CEA LIST (LVIC)\n *\n ***********************************************************************\/\n\n#include \"ExternalProcessUnit.h\"\n\n#include \"common\/AbstractFactoryPattern\/SimpleFactory.h\"\n#include \"linguisticProcessing\/common\/annotationGraph\/AnnotationData.h\"\n#include \"common\/XMLConfigurationFiles\/xmlConfigurationFileExceptions.h\"\n#include \"common\/time\/traceUtils.h\"\n#include \"linguisticProcessing\/core\/LinguisticProcessors\/LinguisticMetaData.h\"\n#include \"linguisticProcessing\/core\/LinguisticResources\/AbstractResource.h\"\n#include \"linguisticProcessing\/core\/LinguisticResources\/LinguisticResources.h\"\n#include \"linguisticProcessing\/core\/LinguisticAnalysisStructure\/AnalysisGraph.h\"\n#include \"linguisticProcessing\/core\/TextSegmentation\/SegmentationData.h\"\n#include \"linguisticProcessing\/client\/AnalysisHandlers\/SimpleStreamHandler.h\"\n\n\/\/#include \"boost\/process.hpp\"\n#include \n\n#include \n\n\/\/namespace bp = ::boost::process; \n\nusing namespace std;\n\nnamespace Lima {\nnamespace LinguisticProcessing {\n\n#define DEFAULT_TEMPFILE \"\/tmp\/lp_external_tmp\"\n\nSimpleFactory ExternalProcessUnitFactory(EXTERNALPROCESSUNIT_CLASSID);\n\nExternalProcessUnit::ExternalProcessUnit():\nMediaProcessUnit(),\nm_dumper(),\nm_loader(),\nm_commandLine(),\nm_useTemporaryFile(true),\nm_cleanTemporaryFile(true),\nm_tmpFileName(DEFAULT_TEMPFILE),\nm_handler(0),\nm_out(0),\nm_inputSuffix(),\nm_outputSuffix()\n{\n}\n\nExternalProcessUnit::~ExternalProcessUnit()\n{\n}\n\n\/\/************************************************************************\nbool \ngetBooleanParameter(Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration,\n const std::string& param) {\n string value=unitConfiguration.getParamsValueAtKey(param);\n if (value == \"yes\" ||\n value == \"true\" ||\n value == \"1\") {\n return true;\n }\n return false;\n}\n \n\nvoid ExternalProcessUnit::init(\n Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration,\n Manager* manager)\n\n{\n LOGINIT(\"LP:External\");\n LDEBUG << \"Initialization\";\n\n MediaId language=manager->getInitializationParameters().media;\n try {\n string dumperName=unitConfiguration.getParamsValueAtKey(\"dumper\");\n \/\/ create the dumper\n m_dumper=manager->getObject(dumperName);\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n LERROR << \"Missing 'dumper' parameter in ExternalProcessUnit group for language \"\n << (int)language << \" !\";\n throw InvalidConfiguration();\n }\n\n try {\n string loaderName=unitConfiguration.getParamsValueAtKey(\"loader\");\n \/\/ create the loader\n m_loader=manager->getObject(loaderName);\n }\n catch (InvalidConfiguration& ) {\n m_loader = 0;\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n LERROR << \"Missing 'loader' parameter in ExternalProcessUnit group for language \"\n << (int)language << \" !\";\n throw InvalidConfiguration();\n }\n\n try {\n m_inputSuffix=QString::fromUtf8(unitConfiguration.getParamsValueAtKey(\"inputSuffix\").c_str());\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n \/\/ optional parameter: keep default value\n }\n\n try {\n m_outputSuffix=QString::fromUtf8(unitConfiguration.getParamsValueAtKey(\"outputSuffix\").c_str());\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n \/\/ optional parameter: keep default value\n }\n\n try {\n m_useTemporaryFile=getBooleanParameter(unitConfiguration,\"useTmpFile\");\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n \/\/ optional parameter: keep default value\n }\n\n try {\n m_cleanTemporaryFile=getBooleanParameter(unitConfiguration,\"cleanTmpFile\");\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n \/\/ optional parameter: keep default value\n }\n\n try {\n m_tmpFileName=unitConfiguration.getParamsValueAtKey(\"tmpFileName\");\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n \/\/ optional parameter: keep default value\n }\n\n try {\n m_commandLine=QString::fromUtf8(unitConfiguration.getParamsValueAtKey(\"command\").c_str());\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n LERROR << \"Missing 'command' parameter in ExternalProcessUnit group for language \"\n << (int)language << \" !\";\n throw InvalidConfiguration();\n }\n}\n\nLimaStatusCode ExternalProcessUnit::process(AnalysisContent& analysis) const\n{\n TimeUtils::updateCurrentTime();\n LOGINIT(\"LP:External\");\n LINFO << \"ExternalProcessUnit: start\";\n\n LinguisticMetaData* metadata=static_cast(analysis.getData(\"LinguisticMetaData\"));\n if (metadata == 0) {\n LERROR << \"no LinguisticMetaData ! abort\";\n return MISSING_DATA;\n }\n\n LimaStatusCode returnCode(SUCCESS_ID);\n\n \/\/ produce temporary file with the given dumper\n LDEBUG << \"ExternalProcessUnit: write tmp file\";\n returnCode=m_dumper->process(analysis);\n if (returnCode!=SUCCESS_ID) {\n LERROR << \"ExternalProcessUnit: failed to dump data to temporary file\";\n return returnCode;\n }\n\n QString fileName = QString::fromUtf8(metadata->getMetaData(\"FileName\").c_str());\n QString inputFilename, outputFilename;\n \/\/ apply command line\n LDEBUG << \"ExternalProcessUnit: apply external program\";\n QString commandLine = m_commandLine;\n if (!m_inputSuffix.isEmpty())\n {\n inputFilename = fileName+ m_inputSuffix;\n }\n if (!m_outputSuffix.isEmpty())\n {\n outputFilename = fileName + m_outputSuffix;\n }\n\/\/ commandLine = commandLine.arg(inputFilename).arg(outputFilename);\n LDEBUG << \"Launching \" << commandLine;\n QProcess::execute(commandLine);\n\n if (m_loader != 0) {\n \/\/ load results from the external program with the given loader\n LDEBUG << \"ExternalProcessUnit: read results\";\n returnCode=m_loader->process(analysis);\n if (returnCode!=SUCCESS_ID) {\n LERROR << \"ExternalProcessUnit: failed to load data from temporary file\";\n return returnCode;\n }\n }\n else {\n LWARN << \"ExternalProcessUnit: no loader defined for the current external process unit\";\n }\n \n TimeUtils::logElapsedTime(\"ExternalProcessUnit\");\n return returnCode;\n}\n\n\n} \/\/ end namespace\n} \/\/ end namespace\nUncomment the line to launch the srl command with arguments\/*\n Copyright 2002-2013 CEA LIST\n\n This file is part of LIMA.\n\n LIMA 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 LIMA is distributed in the hope that it 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 LIMA. If not, see \n*\/\n\/************************************************************************\n *\n * @file ExternalProcessUnit.cpp\n * @author besancon (besanconr@zoe.cea.fr)\n * @date Mon Jan 17 2011\n * copyright Copyright (C) 2011 by CEA LIST (LVIC)\n *\n ***********************************************************************\/\n\n#include \"ExternalProcessUnit.h\"\n\n#include \"common\/AbstractFactoryPattern\/SimpleFactory.h\"\n#include \"linguisticProcessing\/common\/annotationGraph\/AnnotationData.h\"\n#include \"common\/XMLConfigurationFiles\/xmlConfigurationFileExceptions.h\"\n#include \"common\/time\/traceUtils.h\"\n#include \"linguisticProcessing\/core\/LinguisticProcessors\/LinguisticMetaData.h\"\n#include \"linguisticProcessing\/core\/LinguisticResources\/AbstractResource.h\"\n#include \"linguisticProcessing\/core\/LinguisticResources\/LinguisticResources.h\"\n#include \"linguisticProcessing\/core\/LinguisticAnalysisStructure\/AnalysisGraph.h\"\n#include \"linguisticProcessing\/core\/TextSegmentation\/SegmentationData.h\"\n#include \"linguisticProcessing\/client\/AnalysisHandlers\/SimpleStreamHandler.h\"\n\n\/\/#include \"boost\/process.hpp\"\n#include \n\n#include \n\n\/\/namespace bp = ::boost::process; \n\nusing namespace std;\n\nnamespace Lima {\nnamespace LinguisticProcessing {\n\n#define DEFAULT_TEMPFILE \"\/tmp\/lp_external_tmp\"\n\nSimpleFactory ExternalProcessUnitFactory(EXTERNALPROCESSUNIT_CLASSID);\n\nExternalProcessUnit::ExternalProcessUnit():\nMediaProcessUnit(),\nm_dumper(),\nm_loader(),\nm_commandLine(),\nm_useTemporaryFile(true),\nm_cleanTemporaryFile(true),\nm_tmpFileName(DEFAULT_TEMPFILE),\nm_handler(0),\nm_out(0),\nm_inputSuffix(),\nm_outputSuffix()\n{\n}\n\nExternalProcessUnit::~ExternalProcessUnit()\n{\n}\n\n\/\/************************************************************************\nbool \ngetBooleanParameter(Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration,\n const std::string& param) {\n string value=unitConfiguration.getParamsValueAtKey(param);\n if (value == \"yes\" ||\n value == \"true\" ||\n value == \"1\") {\n return true;\n }\n return false;\n}\n \n\nvoid ExternalProcessUnit::init(\n Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration,\n Manager* manager)\n\n{\n LOGINIT(\"LP:External\");\n LDEBUG << \"Initialization\";\n\n MediaId language=manager->getInitializationParameters().media;\n try {\n string dumperName=unitConfiguration.getParamsValueAtKey(\"dumper\");\n \/\/ create the dumper\n m_dumper=manager->getObject(dumperName);\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n LERROR << \"Missing 'dumper' parameter in ExternalProcessUnit group for language \"\n << (int)language << \" !\";\n throw InvalidConfiguration();\n }\n\n try {\n string loaderName=unitConfiguration.getParamsValueAtKey(\"loader\");\n \/\/ create the loader\n m_loader=manager->getObject(loaderName);\n }\n catch (InvalidConfiguration& ) {\n m_loader = 0;\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n LERROR << \"Missing 'loader' parameter in ExternalProcessUnit group for language \"\n << (int)language << \" !\";\n throw InvalidConfiguration();\n }\n\n try {\n m_inputSuffix=QString::fromUtf8(unitConfiguration.getParamsValueAtKey(\"inputSuffix\").c_str());\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n \/\/ optional parameter: keep default value\n }\n\n try {\n m_outputSuffix=QString::fromUtf8(unitConfiguration.getParamsValueAtKey(\"outputSuffix\").c_str());\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n \/\/ optional parameter: keep default value\n }\n\n try {\n m_useTemporaryFile=getBooleanParameter(unitConfiguration,\"useTmpFile\");\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n \/\/ optional parameter: keep default value\n }\n\n try {\n m_cleanTemporaryFile=getBooleanParameter(unitConfiguration,\"cleanTmpFile\");\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n \/\/ optional parameter: keep default value\n }\n\n try {\n m_tmpFileName=unitConfiguration.getParamsValueAtKey(\"tmpFileName\");\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n \/\/ optional parameter: keep default value\n }\n\n try {\n m_commandLine=QString::fromUtf8(unitConfiguration.getParamsValueAtKey(\"command\").c_str());\n }\n catch (Common::XMLConfigurationFiles::NoSuchParam& ) {\n LERROR << \"Missing 'command' parameter in ExternalProcessUnit group for language \"\n << (int)language << \" !\";\n throw InvalidConfiguration();\n }\n}\n\nLimaStatusCode ExternalProcessUnit::process(AnalysisContent& analysis) const\n{\n TimeUtils::updateCurrentTime();\n LOGINIT(\"LP:External\");\n LINFO << \"ExternalProcessUnit: start\";\n\n LinguisticMetaData* metadata=static_cast(analysis.getData(\"LinguisticMetaData\"));\n if (metadata == 0) {\n LERROR << \"no LinguisticMetaData ! abort\";\n return MISSING_DATA;\n }\n\n LimaStatusCode returnCode(SUCCESS_ID);\n\n \/\/ produce temporary file with the given dumper\n LDEBUG << \"ExternalProcessUnit: write tmp file\";\n returnCode=m_dumper->process(analysis);\n if (returnCode!=SUCCESS_ID) {\n LERROR << \"ExternalProcessUnit: failed to dump data to temporary file\";\n return returnCode;\n }\n\n QString fileName = QString::fromUtf8(metadata->getMetaData(\"FileName\").c_str());\n QString inputFilename, outputFilename;\n \/\/ apply command line\n LDEBUG << \"ExternalProcessUnit: apply external program\";\n QString commandLine = m_commandLine;\n if (!m_inputSuffix.isEmpty())\n {\n inputFilename = fileName+ m_inputSuffix;\n }\n if (!m_outputSuffix.isEmpty())\n {\n outputFilename = fileName + m_outputSuffix;\n }\n commandLine = commandLine.arg(inputFilename).arg(outputFilename);\n LDEBUG << \"Launching \" << commandLine;\n QProcess::execute(commandLine);\n\n if (m_loader != 0) {\n \/\/ load results from the external program with the given loader\n LDEBUG << \"ExternalProcessUnit: read results\";\n returnCode=m_loader->process(analysis);\n if (returnCode!=SUCCESS_ID) {\n LERROR << \"ExternalProcessUnit: failed to load data from temporary file\";\n return returnCode;\n }\n }\n else {\n LWARN << \"ExternalProcessUnit: no loader defined for the current external process unit\";\n }\n \n TimeUtils::logElapsedTime(\"ExternalProcessUnit\");\n return returnCode;\n}\n\n\n} \/\/ end namespace\n} \/\/ end namespace\n<|endoftext|>"} {"text":"#include \"server.h\"\n#include \"unique_fd.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace\n{\n\nconst int fail = -1;\nconst int inet_aton_fail = 0;\n\nstatic bool terminated = false;\n\nvoid termination(int signum)\n{\n terminated = true;\n}\n\nbool setSignalsHandlers()\n{\n struct sigaction sa;\n sa.sa_handler = termination;\n sigaddset(&sa.sa_mask, SIGTERM);\n sigaddset(&sa.sa_mask, SIGINT);\n sa.sa_flags = 0;\n if (sigaction(SIGTERM, &sa, nullptr) == fail) {\n perror(\"sigaction\");\n return false;\n }\n if (sigaction(SIGINT, &sa, nullptr) == fail) {\n perror(\"sigaction\");\n return false;\n }\n return true;\n}\n\nbool init(const http_server::Options& options)\n{\n\n if (options.daemon()) {\n if (daemon(0, 1) == fail) {\n perror(\"daemon\");\n return false;\n }\n }\n\n if (options.verbose()) {\n std::cout << \"The server started as \"\n << (options.daemon()? \"daemon\": \"application\")\n << std::endl;\n std::cout << \"pid = \" << getpid() << std::endl;\n }\n\n return setSignalsHandlers();\n}\n\naux::UniqueFd makeListeningSocket()\n{\n \/\/aux::UniqueFd sd {socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0)};\n aux::UniqueFd sockfd {socket(AF_INET, SOCK_STREAM, 0)};\n if (!sockfd) {\n perror(\"socket\");\n return aux::UniqueFd();\n }\n\n const int yes = 1;\n if (setsockopt(sockfd, SOL_SOCKET,\n SO_REUSEADDR, &yes, sizeof(yes)) == fail) {\n perror(\"setsockopt\");\n return aux::UniqueFd();\n }\n\n return sockfd;\n}\n\nbool startListen(const aux::UniqueFd& sockfd, const http_server::Options& options)\n{\n struct sockaddr_in addr_in;\n addr_in.sin_family = AF_INET;\n addr_in.sin_port = htons(options.port());\n if (inet_aton(options.ip(), &addr_in.sin_addr) == inet_aton_fail) {\n std::cerr << \"inet_aton: \" << \"The address '\"\n << options.ip() << \"' is wrong\" << std::endl;\n return false;\n }\n\n if (options.verbose()) {\n std::cout << \"Listening: \"\n << inet_ntoa(addr_in.sin_addr) << \":\" << ntohs(addr_in.sin_port)\n << std::endl;\n }\n\n if (bind(sockfd,\n reinterpret_cast(&addr_in),\n sizeof(addr_in)) == fail) {\n perror(\"bind\");\n return false;\n }\n\n if (listen(sockfd, SOMAXCONN) == fail) {\n perror(\"listen\");\n return false;\n }\n\n return true;\n}\n\nvoid outputBinaryData(const char * data, size_t size)\n{\n std::cout << std::setfill('0');\n for(size_t i = 0; i < size; ++i)\n std::cout << std::setw(2) << std::hex\n << static_cast(data[i]) << \" \";\n std::cout << std::setfill(' ');\n std::cout << std::dec;\n std::cout << std::endl;\n std::cout << std::endl;\n}\n\nint sendData(int sockfd, const char * data, size_t size, bool verbose, std::ofstream& logout)\n{\n logout << std::string(data, size);\n\n if (verbose)\n {\n std::cout << \"Send: \";\n outputBinaryData(data, size);\n }\n\n int res = send(sockfd, data, size, 0);\n if (res == -1)\n perror(\"send\");\n\n return res;\n}\n\nint sendBadRequest(int sockfd, bool verbose, std::ofstream& logout)\n{\n static const char badRequest[] = \"HTTP\/1.0 400 Bad Request\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"Content-Length: 43\\r\\n\"\n \"\\r\\n\"\n \"400 Bad Request<\/body><\/html>\\r\\n\";\n\n return sendData(sockfd, badRequest, sizeof(badRequest) - 1, verbose, logout);\n}\n\nint sendNotFound(int sockfd, bool verbose, std::ofstream& logout)\n{\n static const char notFound[] = \"HTTP\/1.0 404 Not Found\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"Content-Length: 41\\r\\n\"\n \"\\r\\n\"\n \"404 Not Found<\/body><\/html>\\r\\n\";\n\n return sendData(sockfd, notFound, sizeof(notFound) - 1, verbose, logout);\n}\n\nint sendAnswer(int sockfd, const std::string& data, bool verbose, std::ofstream& logout)\n{\n std::ostringstream os;\n os << \"HTTP\/1.0 200 OK\\r\\n\" \n << \"Content-Type: text\/html\\r\\n\"\n << \"Content-Length: \" << data.length() << \"\\r\\n\"\n << \"\\r\\n\"\n << data;\n\n return sendData(sockfd, os.str().c_str(), os.str().length(), verbose, logout);\n}\n\nvoid clientWorker(aux::UniqueFd&& sockfd,\n const sockaddr_in peerAddr,\n const http_server::Options& options)\n{\n aux::UniqueFd clientfd(std::move(sockfd));\n\n std::string logName;\n {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n std::ostringstream os;\n os << \"\/tmp\/\" << tv.tv_sec << \"_\" << tv.tv_usec << \".log\";\n logName = os.str();\n os.str(\"\");\n }\n\n std::ofstream logout(logName);\n\n if (options.verbose()) {\n std::cout << \"Connection with: \"\n << inet_ntoa(peerAddr.sin_addr)\n << \":\" << ntohs(peerAddr.sin_port)\n << std::endl;\n }\n logout << \"Connection with: \"\n << inet_ntoa(peerAddr.sin_addr)\n << \":\" << ntohs(peerAddr.sin_port)\n << \"\\n\" << std::endl;\n\n char buf[1024];\n ssize_t received = recv(clientfd, &buf, sizeof(buf), 0);\n switch (received)\n {\n case -1:\n perror(\"recv\");\n break;\n case 0:\n break;\n default:\n if (options.verbose()) {\n std::cout << \"Received: \";\n outputBinaryData(buf, received);\n }\n\n logout << std::string(buf, received);\n logout.flush();\n\n const char* getLine = std::strtok(buf, \"\\r\\n\");\n\n if ((getLine == NULL) || (strncmp(getLine, \"GET \", 4) != 0))\n {\n sendBadRequest(clientfd, options.verbose(), logout);\n return;\n }\n\n const char* protocolStr = std::strrchr(getLine, 'H');\n if ((protocolStr == NULL) || (std::strncmp(protocolStr, \"HTTP\/\", 5) != 0))\n {\n sendBadRequest(clientfd, options.verbose(), logout);\n return;\n }\n\n std::string filename(getLine + 4, protocolStr - getLine - 5);\n\n std::filebuf file;\n if (file.open(options.directory() + filename, std::ios_base::in) == nullptr)\n {\n sendNotFound(clientfd, options.verbose(), logout);\n return;\n }\n\n using std::ios_base;\n auto posEnd = file.pubseekoff(0, ios_base::end);\n file.pubseekpos(0);\n\n \/\/sendAnswer(clientfd, filename, options.verbose());\n\n if (options.verbose())\n std::cout << \"Sending header...\" << std::endl;\n\n std::ostringstream os;\n int fileSize = posEnd;\n os << \"HTTP\/1.0 200 OK\\r\\n\" \n << \"Content-Type: text\/html\\r\\n\"\n << \"Content-Length: \" << (fileSize - 1) << \"\\r\\n\"\n << \"\\r\\n\";\n\n int read = 0;\n do\n {\n read = file.sgetn(buf, sizeof(buf));\n os << std::string(buf, read);\n } while(read == sizeof(buf));\n\n if (sendData(clientfd, os.str().c_str(), os.str().length(), options.verbose(), logout) == -1)\n return;\n\/*\n if (options.verbose())\n std::cout << \"Sending content...\" << std::endl;\n int read = 0;\n do\n {\n read = file.sgetn(buf, sizeof(buf));\n if (sendData(clientfd, buf, read, options.verbose()) == -1)\n return;\n } while(read == sizeof(buf));\n*\/\n break;\n }\n}\n\n} \/* anonymous namespace *\/\n\nint http_server::run(const http_server::Options& options)\n{\n if (!init(options))\n return EXIT_FAILURE;\n\n aux::UniqueFd sockfd { makeListeningSocket() };\n if (!sockfd)\n return EXIT_FAILURE;\n\n if (!startListen(sockfd, options))\n return EXIT_FAILURE;\n\n std::ofstream logout(\"\/tmp\/mainfinal.log\");\n logout << \"start\" << std::endl;\n\n while(!terminated) {\n struct sockaddr_in peerAddr;\n socklen_t peerAddrSize = sizeof(peerAddr);\n aux::UniqueFd clientfd {\n accept(sockfd,\n reinterpret_cast(&peerAddr),\n &peerAddrSize)\n };\n\n if (clientfd) {\n \/\/clientWorker(std::move(clientfd), peerAddr, options);\n logout << \"Connection with: \"\n << inet_ntoa(peerAddr.sin_addr)\n << \":\" << ntohs(peerAddr.sin_port)\n << \"\\n\" << std::endl;\n std::thread t(clientWorker, std::move(clientfd), peerAddr, options);\n t.detach();\n } else {\n perror(\"accept\");\n }\n }\n\n if (options.verbose())\n std::cout << \"The server stoped\" << std::endl;\n\n logout << \"stop\\n\";\n logout.close();\n\n return 0;\n}\n\nsingle log#include \"server.h\"\n#include \"unique_fd.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace\n{\n\nconst int fail = -1;\nconst int inet_aton_fail = 0;\n\nstatic bool terminated = false;\n\nvoid termination(int signum)\n{\n terminated = true;\n}\n\nbool setSignalsHandlers()\n{\n struct sigaction sa;\n sa.sa_handler = termination;\n sigaddset(&sa.sa_mask, SIGTERM);\n sigaddset(&sa.sa_mask, SIGINT);\n sa.sa_flags = 0;\n if (sigaction(SIGTERM, &sa, nullptr) == fail) {\n perror(\"sigaction\");\n return false;\n }\n if (sigaction(SIGINT, &sa, nullptr) == fail) {\n perror(\"sigaction\");\n return false;\n }\n return true;\n}\n\nbool init(const http_server::Options& options)\n{\n\n if (options.daemon()) {\n if (daemon(0, 1) == fail) {\n perror(\"daemon\");\n return false;\n }\n }\n\n if (options.verbose()) {\n std::cout << \"The server started as \"\n << (options.daemon()? \"daemon\": \"application\")\n << std::endl;\n std::cout << \"pid = \" << getpid() << std::endl;\n }\n\n return setSignalsHandlers();\n}\n\naux::UniqueFd makeListeningSocket()\n{\n \/\/aux::UniqueFd sd {socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0)};\n aux::UniqueFd sockfd {socket(AF_INET, SOCK_STREAM, 0)};\n if (!sockfd) {\n perror(\"socket\");\n return aux::UniqueFd();\n }\n\n const int yes = 1;\n if (setsockopt(sockfd, SOL_SOCKET,\n SO_REUSEADDR, &yes, sizeof(yes)) == fail) {\n perror(\"setsockopt\");\n return aux::UniqueFd();\n }\n\n return sockfd;\n}\n\nbool startListen(const aux::UniqueFd& sockfd, const http_server::Options& options)\n{\n struct sockaddr_in addr_in;\n addr_in.sin_family = AF_INET;\n addr_in.sin_port = htons(options.port());\n if (inet_aton(options.ip(), &addr_in.sin_addr) == inet_aton_fail) {\n std::cerr << \"inet_aton: \" << \"The address '\"\n << options.ip() << \"' is wrong\" << std::endl;\n return false;\n }\n\n if (options.verbose()) {\n std::cout << \"Listening: \"\n << inet_ntoa(addr_in.sin_addr) << \":\" << ntohs(addr_in.sin_port)\n << std::endl;\n }\n\n if (bind(sockfd,\n reinterpret_cast(&addr_in),\n sizeof(addr_in)) == fail) {\n perror(\"bind\");\n return false;\n }\n\n if (listen(sockfd, SOMAXCONN) == fail) {\n perror(\"listen\");\n return false;\n }\n\n return true;\n}\n\nvoid outputBinaryData(const char * data, size_t size)\n{\n std::cout << std::setfill('0');\n for(size_t i = 0; i < size; ++i)\n std::cout << std::setw(2) << std::hex\n << static_cast(data[i]) << \" \";\n std::cout << std::setfill(' ');\n std::cout << std::dec;\n std::cout << std::endl;\n std::cout << std::endl;\n}\n\nint sendData(int sockfd, const char * data, size_t size, bool verbose, std::ofstream& logout)\n{\n logout << std::string(data, size);\n\n if (verbose)\n {\n std::cout << \"Send: \";\n outputBinaryData(data, size);\n }\n\n int res = send(sockfd, data, size, 0);\n if (res == -1)\n perror(\"send\");\n\n return res;\n}\n\nint sendBadRequest(int sockfd, bool verbose, std::ofstream& logout)\n{\n static const char badRequest[] = \"HTTP\/1.0 400 Bad Request\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"Content-Length: 43\\r\\n\"\n \"\\r\\n\"\n \"400 Bad Request<\/body><\/html>\\r\\n\";\n\n return sendData(sockfd, badRequest, sizeof(badRequest) - 1, verbose, logout);\n}\n\nint sendNotFound(int sockfd, bool verbose, std::ofstream& logout)\n{\n static const char notFound[] = \"HTTP\/1.0 404 Not Found\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"Content-Length: 41\\r\\n\"\n \"\\r\\n\"\n \"404 Not Found<\/body><\/html>\\r\\n\";\n\n return sendData(sockfd, notFound, sizeof(notFound) - 1, verbose, logout);\n}\n\nint sendAnswer(int sockfd, const std::string& data, bool verbose, std::ofstream& logout)\n{\n std::ostringstream os;\n os << \"HTTP\/1.0 200 OK\\r\\n\" \n << \"Content-Type: text\/html\\r\\n\"\n << \"Content-Length: \" << data.length() << \"\\r\\n\"\n << \"\\r\\n\"\n << data;\n\n return sendData(sockfd, os.str().c_str(), os.str().length(), verbose, logout);\n}\n\nvoid clientWorker(aux::UniqueFd&& sockfd,\n const sockaddr_in peerAddr,\n const http_server::Options& options,\n std::ofstream& logout\n )\n{\n aux::UniqueFd clientfd(std::move(sockfd));\n\n std::string logName;\n {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n std::ostringstream os;\n os << \"\/tmp\/\" << tv.tv_sec << \"_\" << tv.tv_usec << \".log\";\n logName = os.str();\n os.str(\"\");\n }\n\n \/\/std::ofstream logout(logName);\n\n if (options.verbose()) {\n std::cout << \"Connection with: \"\n << inet_ntoa(peerAddr.sin_addr)\n << \":\" << ntohs(peerAddr.sin_port)\n << std::endl;\n }\n logout << \"Connection with: \"\n << inet_ntoa(peerAddr.sin_addr)\n << \":\" << ntohs(peerAddr.sin_port)\n << \"\\n\" << std::endl;\n\n char buf[1024];\n ssize_t received = recv(clientfd, &buf, sizeof(buf), 0);\n switch (received)\n {\n case -1:\n perror(\"recv\");\n break;\n case 0:\n break;\n default:\n if (options.verbose()) {\n std::cout << \"Received: \";\n outputBinaryData(buf, received);\n }\n\n logout << std::string(buf, received);\n logout.flush();\n\n const char* getLine = std::strtok(buf, \"\\r\\n\");\n\n if ((getLine == NULL) || (strncmp(getLine, \"GET \", 4) != 0))\n {\n sendBadRequest(clientfd, options.verbose(), logout);\n return;\n }\n\n const char* protocolStr = std::strrchr(getLine, 'H');\n if ((protocolStr == NULL) || (std::strncmp(protocolStr, \"HTTP\/\", 5) != 0))\n {\n sendBadRequest(clientfd, options.verbose(), logout);\n return;\n }\n\n std::string filename(getLine + 4, protocolStr - getLine - 5);\n\n std::filebuf file;\n if (file.open(options.directory() + filename, std::ios_base::in) == nullptr)\n {\n sendNotFound(clientfd, options.verbose(), logout);\n return;\n }\n\n using std::ios_base;\n auto posEnd = file.pubseekoff(0, ios_base::end);\n file.pubseekpos(0);\n\n \/\/sendAnswer(clientfd, filename, options.verbose());\n\n if (options.verbose())\n std::cout << \"Sending header...\" << std::endl;\n\n std::ostringstream os;\n int fileSize = posEnd;\n os << \"HTTP\/1.0 200 OK\\r\\n\" \n << \"Content-Type: text\/html\\r\\n\"\n << \"Content-Length: \" << (fileSize - 1) << \"\\r\\n\"\n << \"\\r\\n\";\n\n int read = 0;\n do\n {\n read = file.sgetn(buf, sizeof(buf));\n os << std::string(buf, read);\n } while(read == sizeof(buf));\n\n if (sendData(clientfd, os.str().c_str(), os.str().length(), options.verbose(), logout) == -1)\n return;\n\/*\n if (options.verbose())\n std::cout << \"Sending content...\" << std::endl;\n int read = 0;\n do\n {\n read = file.sgetn(buf, sizeof(buf));\n if (sendData(clientfd, buf, read, options.verbose()) == -1)\n return;\n } while(read == sizeof(buf));\n*\/\n break;\n }\n}\n\n} \/* anonymous namespace *\/\n\nint http_server::run(const http_server::Options& options)\n{\n if (!init(options))\n return EXIT_FAILURE;\n\n aux::UniqueFd sockfd { makeListeningSocket() };\n if (!sockfd)\n return EXIT_FAILURE;\n\n if (!startListen(sockfd, options))\n return EXIT_FAILURE;\n\n std::ofstream logout(\"\/tmp\/mainfinal.log\");\n logout << \"start\" << std::endl;\n\n while(!terminated) {\n struct sockaddr_in peerAddr;\n socklen_t peerAddrSize = sizeof(peerAddr);\n aux::UniqueFd clientfd {\n accept(sockfd,\n reinterpret_cast(&peerAddr),\n &peerAddrSize)\n };\n\n if (clientfd) {\n \/\/clientWorker(std::move(clientfd), peerAddr, options);\n logout << \"Connection with: \"\n << inet_ntoa(peerAddr.sin_addr)\n << \":\" << ntohs(peerAddr.sin_port)\n << \"\\n\" << std::endl;\n std::thread t(clientWorker, std::move(clientfd), peerAddr, options, std::ref(logout));\n t.detach();\n } else {\n perror(\"accept\");\n }\n }\n\n if (options.verbose())\n std::cout << \"The server stoped\" << std::endl;\n\n logout << \"stop\\n\";\n logout.close();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"#ifndef SAVE_STATE_H\n# define SAVE_STATE_H\n# pragma once\n\nstruct statebuf\n{\n void* sp;\n void* label;\n};\n\n#if defined(__GNUC__)\ninline bool __attribute__((always_inline)) savestate(statebuf& ssb) noexcept\n{\n\tbool r;\n\n#if defined(i386) || defined(__i386) || defined(__i386__)\n\tasm volatile (\n\t\t\"movl %%esp, %0\\n\\t\" \/\/ store sp\n\t\t\"movl $1f, %1\\n\\t\" \/\/ store label\n\t\t\"movb $0, %2\\n\\t\" \/\/ return false\n\t\t\"jmp 2f\\n\\t\"\n\t\t\"1:movb $1, %2\\n\\t\" \/\/ return true\n\t\t\"2:\"\n\t\t: \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n\t\t:\n\t\t: \"memory\"\n\t);\n#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)\n\tasm volatile (\n\t\t\"movq %%rsp, %0\\n\\t\" \/\/ store sp\n\t\t\"movq $1f, %1\\n\\t\" \/\/ store label\n\t\t\"movb $0, %2\\n\\t\" \/\/ return false\n\t\t\"jmp 2f\\n\\t\"\n\t\t\"1:movb $1, %2\\n\\t\" \/\/ return true\n\t\t\"2:\"\n\t\t: \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n\t\t:\n\t\t: \"memory\"\n\t);\n#elif defined(__arm__)\n asm volatile (\n \"str sp, %0\"\n \"b 2f\\n\\t\"\n \"2:\"\n : \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n :\n : \"memory\"\n );\n#endif\n\n\treturn r;\n}\n#elif defined(_MSC_VER)\n__forceinline bool savestate(statebuf& ssb) noexcept\n{\n\tbool r;\n\n\t__asm {\n\t\tpush ebp\n\t\tmov ebx, ssb\n\t\tmov [ebx]ssb.sp, esp\n\t\tmov [ebx]ssb.label, offset _1f\n\t\tmov r, 0x0\n\t\tjmp _2f\n\t\t_1f: pop ebp\n\t\t\t mov r, 0x1\n\t\t_2f:\n\t}\n\n\treturn r;\n}\n#else\n# error \"unsupported compiler\"\n#endif\n\n#if defined(__GNUC__)\n#if defined(i386) || defined(__i386) || defined(__i386__)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"movl %0, %%esp\\n\\t\" \\\n \"jmp *%1\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"movq %0, %%rsp\\n\\t\" \\\n \"jmp *%1\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#elif defined(__arm__)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"ldr sp, %0\\n\\t\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#else\n# error \"unsupported architecture\"\n#endif\n#elif defined(_MSC_VER)\n#define restorestate(SSB) \\\n __asm mov ebx, this \\\n __asm add ebx, [SSB] \\\n __asm mov esp, [ebx]SSB.sp\\\n __asm jmp [ebx]SSB.label\n#else\n# error \"unsupported compiler\"\n#endif\n\n#endif \/\/ SAVE_STATE_H\nsome fixes#ifndef SAVE_STATE_H\n# define SAVE_STATE_H\n# pragma once\n\nstruct statebuf\n{\n void* sp;\n void* label;\n};\n\n#if defined(__GNUC__)\ninline bool __attribute__((always_inline)) savestate(statebuf& ssb) noexcept\n{\n\tbool r;\n\n#if defined(i386) || defined(__i386) || defined(__i386__)\n\tasm volatile (\n\t\t\"movl %%esp, %0\\n\\t\" \/\/ store sp\n\t\t\"movl $1f, %1\\n\\t\" \/\/ store label\n\t\t\"movb $0, %2\\n\\t\" \/\/ return false\n\t\t\"jmp 2f\\n\\t\"\n\t\t\"1:movb $1, %2\\n\\t\" \/\/ return true\n\t\t\"2:\"\n\t\t: \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n\t\t:\n\t\t: \"memory\"\n\t);\n#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)\n\tasm volatile (\n\t\t\"movq %%rsp, %0\\n\\t\" \/\/ store sp\n\t\t\"movq $1f, %1\\n\\t\" \/\/ store label\n\t\t\"movb $0, %2\\n\\t\" \/\/ return false\n\t\t\"jmp 2f\\n\\t\"\n\t\t\"1:movb $1, %2\\n\\t\" \/\/ return true\n\t\t\"2:\"\n\t\t: \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n\t\t:\n\t\t: \"memory\"\n\t);\n#elif defined(__arm__)\n asm volatile (\n \"str sp, %0\\n\\t\"\n \"b 2f\\n\\t\"\n \"2:\"\n : \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n :\n : \"memory\"\n );\n#endif\n\n\treturn r;\n}\n#elif defined(_MSC_VER)\n__forceinline bool savestate(statebuf& ssb) noexcept\n{\n\tbool r;\n\n\t__asm {\n\t\tpush ebp\n\t\tmov ebx, ssb\n\t\tmov [ebx]ssb.sp, esp\n\t\tmov [ebx]ssb.label, offset _1f\n\t\tmov r, 0x0\n\t\tjmp _2f\n\t\t_1f: pop ebp\n\t\t\t mov r, 0x1\n\t\t_2f:\n\t}\n\n\treturn r;\n}\n#else\n# error \"unsupported compiler\"\n#endif\n\n#if defined(__GNUC__)\n#if defined(i386) || defined(__i386) || defined(__i386__)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"movl %0, %%esp\\n\\t\" \\\n \"jmp *%1\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"movq %0, %%rsp\\n\\t\" \\\n \"jmp *%1\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#elif defined(__arm__)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"ldr sp, %0\\n\\t\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#else\n# error \"unsupported architecture\"\n#endif\n#elif defined(_MSC_VER)\n#define restorestate(SSB) \\\n __asm mov ebx, this \\\n __asm add ebx, [SSB] \\\n __asm mov esp, [ebx]SSB.sp\\\n __asm jmp [ebx]SSB.label\n#else\n# error \"unsupported compiler\"\n#endif\n\n#endif \/\/ SAVE_STATE_H\n<|endoftext|>"} {"text":"#ifdef SHRINK\n\n#include \"internal.hpp\"\n#include \"macros.hpp\"\n\n#include \n\nnamespace CaDiCaL {\n\n\/\/ This is an extended minimization which goes over all alternative reasons\n\/\/ as first explored in PrecoSAT and discussed by Allen Van Gelder later.\n\/\/ The most important observation in PrecoSAT was that alternative reasons\n\/\/ for resolution need to have all literals but one set to false and thus\n\/\/ the true literal will be watched. It subsumes clause minimization, but\n\/\/ is more expensive and thus should be called only on clauses for which\n\/\/ shrinking is useful (such as small clauses with small glue). As in\n\/\/ PrecoSAT we restrict traversal to follow the topological assignment order\n\/\/ to avoid cycles (which would yield unsound removals).\n\nbool Internal::shrink_literal (int lit, int depth) {\n assert (val (lit) > 0);\n Flags & f = flags (lit);\n Var & v = var (lit);\n if (!v.level || f.removable || f.clause) return true;\n if (!v.reason || f.poison || v.level == level) return false;\n const Level & l = control[v.level];\n if (!depth && l.seen < 2) return false;\n if (v.trail <= l.trail) return false;\n if (depth > opts.shrinkdepth) return false;\n bool remove = false;\n Watches & ws = watches (lit);\n\n \/\/ The difference to 'minimize_literal' is here, where we iterate over all\n \/\/ clauses watches by 'lit' instead of 'just' the reason clause except for\n \/\/ '(!!!)' where we have to make sure that we respect assignment order in\n \/\/ resolutions to avoid cyclic derivations. For the actual reason this\n \/\/ test is not necessary.\n\n const const_watch_iterator eow = ws.end ();\n const_watch_iterator i;\n for (i = ws.begin (); !remove && i != eow; i++) {\n Clause * c = i->clause;\n const const_literal_iterator eoc = c->end ();\n const_literal_iterator j;\n bool failed = false;\n int lit_trail = var (lit).trail;\n for (j = c->begin (); !failed && j != eoc; j++) {\n int other = *j;\n if (other == lit) continue;\n else if (val (other) >= 0) failed = true;\n else if (var (other).trail > lit_trail) failed = true; \/\/ (!!!)\n else failed = !shrink_literal (-other, depth+1);\n }\n if (!failed) remove = true;\n }\n\n if (remove) f.removable = true; else f.poison = true;\n minimized.push_back (lit);\n if (!depth) LOG (\"shrinking %d %s\", lit, remove ? \"succeeded\" : \"failed\");\n return remove;\n}\n\nvoid Internal::shrink_clause () {\n START (shrink);\n LOG (clause, \"shrinking minimized first UIP clause\");\n stats.shrinktried += clause.size ();\n sort (clause.begin (), clause.end (), trail_smaller (this));\n assert (minimized.empty ());\n int_iterator j = clause.begin ();\n for (const_int_iterator i = j; i != clause.end (); i++)\n if (shrink_literal (-*i)) stats.shrunken++;\n else flags (*j++ = *i).clause = true;\n LOG (\"shrunken %d literals\", (long)(clause.end () - j));\n clause.resize (j - clause.begin ());\n clear_minimized ();\n check_learned_clause ();\n STOP (shrink);\n}\n\n};\n\n#endif\nshrink#ifdef SHRINK\n\n#include \"internal.hpp\"\n#include \"macros.hpp\"\n\n#include \n\nnamespace CaDiCaL {\n\n\/\/ This is an extended minimization which goes over all alternative reasons\n\/\/ as first explored in PrecoSAT and discussed by Allen Van Gelder later.\n\/\/ The most important observation in PrecoSAT was that alternative reasons\n\/\/ for resolution need to have all literals but one set to false and thus\n\/\/ the true literal will be watched. It subsumes clause minimization, but\n\/\/ is more expensive and thus should be called only on clauses for which\n\/\/ shrinking is useful (such as small clauses with small glue). As in\n\/\/ PrecoSAT we restrict traversal to follow the topological assignment order\n\/\/ to avoid cycles (which could yield unsound removals).\n\nbool Internal::shrink_literal (int lit, int depth) {\n assert (val (lit) > 0);\n Flags & f = flags (lit);\n Var & v = var (lit);\n if (!v.level || f.removable || f.clause) return true;\n if (!v.reason || f.poison || v.level == level) return false;\n const Level & l = control[v.level];\n if (!depth && l.seen < 2) return false;\n if (v.trail <= l.trail) return false;\n if (depth > opts.shrinkdepth) return false;\n bool remove = false;\n Watches & ws = watches (lit);\n\n \/\/ The difference to 'minimize_literal' is here, where we iterate over all\n \/\/ clauses watched by 'lit' instead of 'just' the reason clause except for\n \/\/ '(!!!)' where we have to make sure that we respect assignment order in\n \/\/ resolutions to avoid cyclic derivations. For the actual reason this\n \/\/ test is not necessary.\n\n const const_watch_iterator eow = ws.end ();\n const_watch_iterator i;\n for (i = ws.begin (); !remove && i != eow; i++) {\n Clause * c = i->clause;\n const const_literal_iterator eoc = c->end ();\n const_literal_iterator j;\n bool failed = false;\n int lit_trail = var (lit).trail;\n for (j = c->begin (); !failed && j != eoc; j++) {\n int other = *j;\n if (other == lit) continue;\n else if (val (other) >= 0) failed = true;\n else if (var (other).trail > lit_trail) failed = true; \/\/ (!!!)\n else failed = !shrink_literal (-other, depth+1);\n }\n if (!failed) remove = true;\n }\n\n if (remove) f.removable = true; else f.poison = true;\n minimized.push_back (lit);\n if (!depth) LOG (\"shrinking %d %s\", lit, remove ? \"succeeded\" : \"failed\");\n return remove;\n}\n\nvoid Internal::shrink_clause () {\n START (shrink);\n LOG (clause, \"shrinking minimized first UIP clause\");\n stats.shrinktried += clause.size ();\n sort (clause.begin (), clause.end (), trail_smaller (this));\n assert (minimized.empty ());\n int_iterator j = clause.begin ();\n for (const_int_iterator i = j; i != clause.end (); i++)\n if (shrink_literal (-*i)) stats.shrunken++;\n else flags (*j++ = *i).clause = true;\n LOG (\"shrunken %d literals\", (long)(clause.end () - j));\n clause.resize (j - clause.begin ());\n clear_minimized ();\n check_learned_clause ();\n STOP (shrink);\n}\n\n};\n\n#endif\n<|endoftext|>"} {"text":"\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra \n * Copyright (c) 2011 Laszlo Papp \n *\n * This 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 \"propertiesdock.h\"\n\n#include \"widgets\/propertywidget.h\"\n#include \"objectmanager.h\"\n#include \"historymanager.h\"\n\n#include \n#include \n\nusing namespace GluonCreator;\n\nclass PropertiesDock::PropertiesDockPrivate\n{\n public:\n PropertiesDockPrivate() { }\n\n PropertyWidget* widget;\n};\n\nPropertiesDock::PropertiesDock( const QString& title, QWidget* parent, Qt::WindowFlags flags )\n : QDockWidget( title, parent, flags ), d( new PropertiesDockPrivate )\n{\n setObjectName( \"PropertiesDock\" );\n\n d->widget = new PropertyWidget( this );\n setWidget( d->widget );\n\n connect( SelectionManager::instance(), SIGNAL( selectionChanged( SelectionManager::SelectionList ) ), SLOT( selectionChanged( SelectionManager::SelectionList ) ) );\n connect( d->widget, SIGNAL( propertyChanged( QObject*, QString, QVariant, QVariant ) ), SLOT( propertyChanged( QObject*, QString, QVariant, QVariant ) ) );\n connect( ObjectManager::instance(), SIGNAL( newComponent( GluonEngine::Component* ) ), SLOT( newComponent( GluonEngine::Component* ) ) );\n}\n\nPropertiesDock::~PropertiesDock()\n{\n delete d;\n}\n\nvoid PropertiesDock::selectionChanged( SelectionManager::SelectionList selection )\n{\n if( selection.empty() )\n d->widget->clear();\n else\n d->widget->setObject( selection.at( 0 ) );\n}\n\nvoid PropertiesDock::newComponent( GluonEngine::Component* comp )\n{\n if( comp->parent() == d->widget->object() )\n {\n d->widget->setObject( d->widget->object() );\n }\n}\n\nvoid PropertiesDock::propertyChanged( QObject* object, QString property, QVariant oldValue, QVariant newValue )\n{\n GluonCore::GluonObject* obj = qobject_cast( object );\n\n if( obj )\n ObjectManager::instance()->changeProperty( obj, property, oldValue, newValue );\n}\n\n\nA little cleanup in the properties dock\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra \n * Copyright (c) 2011 Laszlo Papp \n *\n * This 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 \"propertiesdock.h\"\n\n#include \"widgets\/propertywidget.h\"\n#include \"objectmanager.h\"\n#include \"historymanager.h\"\n\n#include \n#include \n\nusing namespace GluonCreator;\n\nclass PropertiesDock::PropertiesDockPrivate\n{\n public:\n PropertiesDockPrivate(PropertyWidget* widget)\n : widget(widget)\n { }\n\n PropertyWidget* widget;\n};\n\nPropertiesDock::PropertiesDock( const QString& title, QWidget* parent, Qt::WindowFlags flags )\n : QDockWidget( title, parent, flags )\n , d( new PropertiesDockPrivate( new PropertyWidget( this ) ) )\n{\n setObjectName( \"PropertiesDock\" );\n\n setWidget( d->widget );\n\n connect( SelectionManager::instance(), SIGNAL( selectionChanged( SelectionManager::SelectionList ) ), SLOT( selectionChanged( SelectionManager::SelectionList ) ) );\n connect( d->widget, SIGNAL( propertyChanged( QObject*, QString, QVariant, QVariant ) ), SLOT( propertyChanged( QObject*, QString, QVariant, QVariant ) ) );\n connect( ObjectManager::instance(), SIGNAL( newComponent( GluonEngine::Component* ) ), SLOT( newComponent( GluonEngine::Component* ) ) );\n}\n\nPropertiesDock::~PropertiesDock()\n{\n delete d;\n}\n\nvoid PropertiesDock::selectionChanged( SelectionManager::SelectionList selection )\n{\n d->widget->clear();\n if( !selection.empty() )\n d->widget->setObject( selection.at( 0 ) );\n}\n\nvoid PropertiesDock::newComponent( GluonEngine::Component* comp )\n{\n if( comp->parent() == d->widget->object() )\n {\n d->widget->setObject( d->widget->object() );\n }\n}\n\nvoid PropertiesDock::propertyChanged( QObject* object, QString property, QVariant oldValue, QVariant newValue )\n{\n GluonCore::GluonObject* obj = qobject_cast( object );\n\n if( obj )\n ObjectManager::instance()->changeProperty( obj, property, oldValue, newValue );\n}\n\n\n<|endoftext|>"} {"text":"#ifndef SAVE_STATE_H\n# define SAVE_STATE_H\n# pragma once\n\nstruct statebuf\n{\n void* sp;\n void* label;\n};\n\n#if defined(__GNUC__)\ninline bool __attribute__((always_inline)) savestate(statebuf& ssb) noexcept\n{\n\tbool volatile r;\n\n#if defined(i386) || defined(__i386) || defined(__i386__)\n\tasm volatile (\n\t\t\"movl %%esp, %0\\n\\t\" \/\/ store sp\n\t\t\"movl $1f, %1\\n\\t\" \/\/ store label\n\t\t\"movb $0, %2\\n\\t\" \/\/ return false\n\t\t\"jmp 2f\\n\\t\"\n\t\t\"1:movb $1, %2\\n\\t\" \/\/ return true\n\t\t\"2:\"\n\t\t: \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n\t\t:\n\t\t: \"memory\"\n\t);\n#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)\n\tasm volatile (\n\t\t\"movq %%rsp, %0\\n\\t\" \/\/ store sp\n\t\t\"movq $1f, %1\\n\\t\" \/\/ store label\n\t\t\"movb $0, %2\\n\\t\" \/\/ return false\n\t\t\"jmp 2f\\n\\t\"\n\t\t\"1:movb $1, %2\\n\\t\" \/\/ return true\n\t\t\"2:\"\n\t\t: \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n\t\t:\n\t\t: \"memory\"\n\t);\n#elif defined(__arm__)\n asm volatile (\n \"push {r11}\\n\\t\" \/\/ push r0\n \"str sp, %0\\n\\t\" \/\/ store sp\n \"ldr r0, =1f\\n\\t\" \/\/ load label into r0\n \"str r0, %1\\n\\t\" \/\/ store r0 into label\n \"mov %2, $0\\n\\t\" \/\/ store 0 into result\n \"b 2f\\n\\t\"\n \"1:pop {r11}\\n\\t\"\n \"mov %2, $1\\n\\t\" \/\/ store 1 into result\n \"2:\"\n : \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n :\n : \"memory\"\n );\n#endif\n\n\treturn r;\n}\n#elif defined(_MSC_VER)\n__forceinline bool savestate(statebuf& ssb) noexcept\n{\n\tbool volatile r;\n\n\t__asm {\n\t\tpush ebp\n\t\tmov ebx, ssb\n\t\tmov [ebx]ssb.sp, esp\n\t\tmov [ebx]ssb.label, offset _1f\n\t\tmov r, 0x0\n\t\tjmp _2f\n\t\t_1f: pop ebp\n\t\t\t mov r, 0x1\n\t\t_2f:\n\t}\n\n\treturn r;\n}\n#else\n# error \"unsupported compiler\"\n#endif\n\n#if defined(__GNUC__)\n#if defined(i386) || defined(__i386) || defined(__i386__)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"movl %0, %%esp\\n\\t\" \\\n \"jmp *%1\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"movq %0, %%rsp\\n\\t\" \\\n \"jmp *%1\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#elif defined(__arm__)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"ldr sp, %0\\n\\t\" \\\n \"ldr pc, %1\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#else\n# error \"unsupported architecture\"\n#endif\n#elif defined(_MSC_VER)\n#define restorestate(SSB) \\\n __asm mov ebx, this \\\n __asm add ebx, [SSB] \\\n __asm mov esp, [ebx]SSB.sp\\\n __asm jmp [ebx]SSB.label\n#else\n# error \"unsupported compiler\"\n#endif\n\n#endif \/\/ SAVE_STATE_H\nsome fixes#ifndef SAVE_STATE_H\n# define SAVE_STATE_H\n# pragma once\n\nstruct statebuf\n{\n void* sp;\n void* label;\n};\n\n#if defined(__GNUC__)\ninline bool __attribute__((always_inline)) savestate(statebuf& ssb) noexcept\n{\n\tbool r;\n\n#if defined(i386) || defined(__i386) || defined(__i386__)\n\tasm volatile (\n\t\t\"movl %%esp, %0\\n\\t\" \/\/ store sp\n\t\t\"movl $1f, %1\\n\\t\" \/\/ store label\n\t\t\"movb $0, %2\\n\\t\" \/\/ return false\n\t\t\"jmp 2f\\n\\t\"\n\t\t\"1:movb $1, %2\\n\\t\" \/\/ return true\n\t\t\"2:\"\n\t\t: \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n\t\t:\n\t\t: \"memory\"\n\t);\n#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)\n\tasm volatile (\n\t\t\"movq %%rsp, %0\\n\\t\" \/\/ store sp\n\t\t\"movq $1f, %1\\n\\t\" \/\/ store label\n\t\t\"movb $0, %2\\n\\t\" \/\/ return false\n\t\t\"jmp 2f\\n\\t\"\n\t\t\"1:movb $1, %2\\n\\t\" \/\/ return true\n\t\t\"2:\"\n\t\t: \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n\t\t:\n\t\t: \"memory\"\n\t);\n#elif defined(__arm__)\n asm volatile (\n \"push {r11}\\n\\t\" \/\/ push r0\n \"str sp, %0\\n\\t\" \/\/ store sp\n \"ldr r0, =1f\\n\\t\" \/\/ load label into r0\n \"str r0, %1\\n\\t\" \/\/ store r0 into label\n \"mov %2, $0\\n\\t\" \/\/ store 0 into result\n \"b 2f\\n\\t\"\n \"1:pop {r11}\\n\\t\"\n \"mov %2, $1\\n\\t\" \/\/ store 1 into result\n \"2:\"\n : \"=m\" (ssb.sp), \"=m\" (ssb.label), \"=r\" (r)\n :\n : \"memory\"\n );\n#endif\n\n\treturn r;\n}\n#elif defined(_MSC_VER)\n__forceinline bool savestate(statebuf& ssb) noexcept\n{\n\tbool r;\n\n\t__asm {\n\t\tpush ebp\n\t\tmov ebx, ssb\n\t\tmov [ebx]ssb.sp, esp\n\t\tmov [ebx]ssb.label, offset _1f\n\t\tmov r, 0x0\n\t\tjmp _2f\n\t\t_1f: pop ebp\n\t\t\t mov r, 0x1\n\t\t_2f:\n\t}\n\n\treturn r;\n}\n#else\n# error \"unsupported compiler\"\n#endif\n\n#if defined(__GNUC__)\n#if defined(i386) || defined(__i386) || defined(__i386__)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"movl %0, %%esp\\n\\t\" \\\n \"jmp *%1\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"movq %0, %%rsp\\n\\t\" \\\n \"jmp *%1\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#elif defined(__arm__)\n#define restorestate(SSB) \\\n asm volatile ( \\\n \"ldr sp, %0\\n\\t\" \\\n \"ldr pc, %1\" \\\n : \\\n : \"m\" (SSB.sp), \"m\" (SSB.label)\\\n );\n#else\n# error \"unsupported architecture\"\n#endif\n#elif defined(_MSC_VER)\n#define restorestate(SSB) \\\n __asm mov ebx, this \\\n __asm add ebx, [SSB] \\\n __asm mov esp, [ebx]SSB.sp\\\n __asm jmp [ebx]SSB.label\n#else\n# error \"unsupported compiler\"\n#endif\n\n#endif \/\/ SAVE_STATE_H\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/\/ \\file string.cpp\n\/\/------------------------------------------------------------------------------\n\/\/\/ \\brief Implementation of general purpose functions for string processing\n\/\/------------------------------------------------------------------------------\n\/\/ Copyright (c) 2010 Serge Aleynikov \n\/\/ Created: 2010-05-06\n\/\/------------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is part of the utxx open-source project.\n\nCopyright (C) 2010 Serge Aleynikov \n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\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\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n\n#include \n#include \n\nnamespace utxx {\n\nstd::string to_bin_string(const char* buf, size_t sz,\n bool hex, bool readable, bool eol)\n{\n std::stringstream out;\n const char* begin = buf, *end = buf + sz;\n print_opts opts = hex\n ? (readable ? print_opts::printable_or_hex : print_opts::hex)\n : (readable ? print_opts::printable_or_dec : print_opts::dec);\n output(out, begin, end, opts, \",\", \"\", \"\\\"\", \"<<\", \">>\");\n if (eol) out << std::endl;\n return out.str();\n}\n\nbool wildcard_match(const char* a_input, const char* a_pattern)\n{\n const char* ip = nullptr, *pp = nullptr;\n\n \/\/ Match until the first '*' or '?':\n for(; *a_input && *a_pattern != '*'; ++a_pattern, ++a_input)\n if ((*a_pattern != *a_input) && (*a_pattern != '?'))\n return false;\n\n \/\/ Pattern match on everything that follows '*', and exit\n \/\/ at the end of the input string\n while (*a_input) {\n if (*a_pattern == '*') {\n if (!*++a_pattern)\n return true;\n \/\/ Store state after '*':\n pp = a_pattern;\n ip = a_input+1;\n } else if ((*a_pattern == *a_input) || (*a_pattern == '?')) {\n \/\/ Continue successful match\n a_pattern++;\n a_input++;\n } else {\n \/\/ Match failed - restore state of pattern after '*':\n a_pattern = pp;\n a_input = ip++;\n }\n }\n\n \/\/ Skip trailing '*' in the pattern, since they don't affect the outcome:\n while (*a_pattern == '*') a_pattern++;\n\n \/\/ Are both input and pattern complete?\n return !*a_pattern;\n}\n\n} \/\/ namespace utxx\nMove closer to use\/\/------------------------------------------------------------------------------\n\/\/\/ \\file string.cpp\n\/\/------------------------------------------------------------------------------\n\/\/\/ \\brief Implementation of general purpose functions for string processing\n\/\/------------------------------------------------------------------------------\n\/\/ Copyright (c) 2010 Serge Aleynikov \n\/\/ Created: 2010-05-06\n\/\/------------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is part of the utxx open-source project.\n\nCopyright (C) 2010 Serge Aleynikov \n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\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\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n\n#include \n#include \n\nnamespace utxx {\n\nstd::string to_bin_string(const char* buf, size_t sz,\n bool hex, bool readable, bool eol)\n{\n std::stringstream out;\n const char* begin = buf, *end = buf + sz;\n print_opts opts = hex\n ? (readable ? print_opts::printable_or_hex : print_opts::hex)\n : (readable ? print_opts::printable_or_dec : print_opts::dec);\n output(out, begin, end, opts, \",\", \"\", \"\\\"\", \"<<\", \">>\");\n if (eol) out << std::endl;\n return out.str();\n}\n\nbool wildcard_match(const char* a_input, const char* a_pattern)\n{\n \/\/ Match until the first '*' or '?':\n for(; *a_input && *a_pattern != '*'; ++a_pattern, ++a_input)\n if ((*a_pattern != *a_input) && (*a_pattern != '?'))\n return false;\n\n const char* ip = nullptr, *pp = nullptr;\n\n \/\/ Pattern match on everything that follows '*', and exit\n \/\/ at the end of the input string\n while (*a_input) {\n if (*a_pattern == '*') {\n if (!*++a_pattern)\n return true;\n \/\/ Store state after '*':\n pp = a_pattern;\n ip = a_input+1;\n } else if ((*a_pattern == *a_input) || (*a_pattern == '?')) {\n \/\/ Continue successful match\n a_pattern++;\n a_input++;\n } else {\n \/\/ Match failed - restore state of pattern after '*':\n a_pattern = pp;\n a_input = ip++;\n }\n }\n\n \/\/ Skip trailing '*' in the pattern, since they don't affect the outcome:\n while (*a_pattern == '*') a_pattern++;\n\n \/\/ Are both input and pattern complete?\n return !*a_pattern;\n}\n\n} \/\/ namespace utxx\n<|endoftext|>"} {"text":"#include \"subcommand.hpp\"\n#include \"..\/vg.hpp\"\n#include \"..\/utility.hpp\"\n#include \"..\/counter.hpp\"\n#include \"..\/stream.hpp\"\n\n#include \n#include \n\nusing namespace vg;\nusing namespace vg::subcommand;\n\nvoid help_count(char** argv) {\n cerr << \"usage: \" << argv[0] << \" count [options]\" << endl\n << \"options:\" << endl\n << \" -x, --xg FILE use this basis graph\" << endl\n << \" -o, --counts-out FILE write compressed coverage counts to this output file\" << endl\n << \" -i, --counts-in FILE begin by summing coverage counts from each provided FILE\" << endl\n << \" -g, --gam FILE read alignments from this file (could be '-' for stdin)\" << endl\n << \" -d, --as-table write table on stdout representing counts\" << endl\n << \" -n, --no-edits don't record or write edits, just graph-matching coverage\" << endl\n << \" -t, --threads N use N threads (defaults to numCPUs)\" << endl;\n}\n\nint main_count(int argc, char** argv) {\n\n string xg_name;\n vector counts_in;\n string counts_out;\n string gam_in;\n bool write_table = false;\n int thread_count = 1;\n bool record_edits = true;\n\n if (argc == 2) {\n help_count(argv);\n return 1;\n }\n\n int c;\n optind = 2; \/\/ force optind past command positional argument\n while (true) {\n static struct option long_options[] =\n {\n {\"help\", no_argument, 0, 'h'},\n {\"xg\", required_argument,0, 'x'},\n {\"counts-out\", required_argument,0, 'o'},\n {\"count-in\", required_argument, 0, 'i'},\n {\"gam\", required_argument, 0, 'g'},\n {\"as-table\", no_argument, 0, 'd'},\n {\"threads\", required_argument, 0, 't'},\n {\"no-edits\", no_argument, 0, 'n'},\n {0, 0, 0, 0}\n\n };\n int option_index = 0;\n c = getopt_long (argc, argv, \"hx:o:i:g:dt:n\",\n long_options, &option_index);\n\n \/\/ Detect the end of the options.\n if (c == -1)\n break;\n\n switch (c)\n {\n\n case '?':\n case 'h':\n help_count(argv);\n return 1;\n case 'x':\n xg_name = optarg;\n break;\n case 'o':\n counts_out = optarg;\n break;\n case 'i':\n counts_in.push_back(optarg);\n break;\n case 'g':\n gam_in = optarg;\n break;\n case 'd':\n write_table = true;\n break;\n case 'n':\n record_edits = false;\n break;\n case 't':\n thread_count = atoi(optarg);\n break;\n\n default:\n abort();\n }\n }\n\n omp_set_num_threads(thread_count);\n\n xg::XG xgidx;\n if (xg_name.empty()) {\n cerr << \"No XG index given. An XG index must be provided.\" << endl;\n exit(1);\n } else {\n ifstream in(xg_name.c_str());\n xgidx.load(in);\n }\n\n \/\/ todo one counter per thread and merge\n vg::Counter counter(&xgidx);\n if (!counts_in.empty()) {\n counter.load_from_file(counts_in.front());\n }\n\n if (!gam_in.empty()) {\n ifstream gam_stream(gam_in);\n std::function lambda = [&counter,&record_edits](Alignment& aln) { counter.add(aln, record_edits); };\n stream::for_each(gam_stream, lambda);\n gam_stream.close();\n }\n if (!counts_out.empty()) {\n counter.save_to_file(counts_out);\n }\n if (write_table) {\n counter.make_compact();\n counter.as_table(cout, record_edits);\n }\n\n return 0;\n}\n\n\/\/ Register subcommand\nstatic Subcommand vg_count(\"count\", \"count features on the graph\", main_count);\ncount: enable reading gam from stdin#include \"subcommand.hpp\"\n#include \"..\/vg.hpp\"\n#include \"..\/utility.hpp\"\n#include \"..\/counter.hpp\"\n#include \"..\/stream.hpp\"\n\n#include \n#include \n\nusing namespace vg;\nusing namespace vg::subcommand;\n\nvoid help_count(char** argv) {\n cerr << \"usage: \" << argv[0] << \" count [options]\" << endl\n << \"options:\" << endl\n << \" -x, --xg FILE use this basis graph\" << endl\n << \" -o, --counts-out FILE write compressed coverage counts to this output file\" << endl\n << \" -i, --counts-in FILE begin by summing coverage counts from each provided FILE\" << endl\n << \" -g, --gam FILE read alignments from this file (could be '-' for stdin)\" << endl\n << \" -d, --as-table write table on stdout representing counts\" << endl\n << \" -n, --no-edits don't record or write edits, just graph-matching coverage\" << endl\n << \" -t, --threads N use N threads (defaults to numCPUs)\" << endl;\n}\n\nint main_count(int argc, char** argv) {\n\n string xg_name;\n vector counts_in;\n string counts_out;\n string gam_in;\n bool write_table = false;\n int thread_count = 1;\n bool record_edits = true;\n\n if (argc == 2) {\n help_count(argv);\n return 1;\n }\n\n int c;\n optind = 2; \/\/ force optind past command positional argument\n while (true) {\n static struct option long_options[] =\n {\n {\"help\", no_argument, 0, 'h'},\n {\"xg\", required_argument,0, 'x'},\n {\"counts-out\", required_argument,0, 'o'},\n {\"count-in\", required_argument, 0, 'i'},\n {\"gam\", required_argument, 0, 'g'},\n {\"as-table\", no_argument, 0, 'd'},\n {\"threads\", required_argument, 0, 't'},\n {\"no-edits\", no_argument, 0, 'n'},\n {0, 0, 0, 0}\n\n };\n int option_index = 0;\n c = getopt_long (argc, argv, \"hx:o:i:g:dt:n\",\n long_options, &option_index);\n\n \/\/ Detect the end of the options.\n if (c == -1)\n break;\n\n switch (c)\n {\n\n case '?':\n case 'h':\n help_count(argv);\n return 1;\n case 'x':\n xg_name = optarg;\n break;\n case 'o':\n counts_out = optarg;\n break;\n case 'i':\n counts_in.push_back(optarg);\n break;\n case 'g':\n gam_in = optarg;\n break;\n case 'd':\n write_table = true;\n break;\n case 'n':\n record_edits = false;\n break;\n case 't':\n thread_count = atoi(optarg);\n break;\n\n default:\n abort();\n }\n }\n\n omp_set_num_threads(thread_count);\n\n xg::XG xgidx;\n if (xg_name.empty()) {\n cerr << \"No XG index given. An XG index must be provided.\" << endl;\n exit(1);\n } else {\n ifstream in(xg_name.c_str());\n xgidx.load(in);\n }\n\n \/\/ todo one counter per thread and merge\n vg::Counter counter(&xgidx);\n if (!counts_in.empty()) {\n counter.load_from_file(counts_in.front());\n }\n\n if (!gam_in.empty()) {\n std::function lambda = [&counter,&record_edits](Alignment& aln) { counter.add(aln, record_edits); };\n if (gam_in == \"-\") {\n stream::for_each(std::cin, lambda);\n } else {\n ifstream gam_stream(gam_in);\n stream::for_each(gam_stream, lambda);\n gam_stream.close();\n }\n }\n if (!counts_out.empty()) {\n counter.save_to_file(counts_out);\n }\n if (write_table) {\n counter.make_compact();\n counter.as_table(cout, record_edits);\n }\n\n return 0;\n}\n\n\/\/ Register subcommand\nstatic Subcommand vg_count(\"count\", \"count features on the graph\", main_count);\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ File: cmnserver.hpp\n\/\/\n\/\/ Desc: Common HTTP server - HTTP server for all application\n\/\/\n\/\/ Copyright (c) 2014-2018 opencvr.com. All rights reserved.\n\/\/------------------------------------------------------------------------------\n#ifndef __VSC_CMN_SERVER__H_\n#define __VSC_CMN_SERVER__H_\n#include \"utility.hpp\"\n#include \"debug.hpp\"\n#include \n\n#include \"XSDK\/XHash.h\"\n#include \"XSDK\/TimeUtils.h\"\n#include \"XSDK\/XSocket.h\"\n#include \"XSDK\/XSSLSocket.h\"\n#include \"Webby\/ClientSideRequest.h\"\n#include \"Webby\/ClientSideResponse.h\"\n#include \"Webby\/ServerSideRequest.h\"\n#include \"Webby\/ServerSideResponse.h\"\n#include \"Webby\/WebbyException.h\"\n\nusing namespace std;\nusing namespace XSDK;\nusing namespace WEBBY;\n\n\/* each app can register a http REST path can move \n the socket to itself, for streaming, it it for performance.\n*\/\n\nusing namespace UtilityLib;\n\nclass CmnHttpServer:public QThread\n{\n\tQ_OBJECT\npublic:\n\tinline CmnHttpServer(u16 port);\n\tinline ~CmnHttpServer();\n\t\npublic:\n\tvoid Lock()\n\t{\n\t\tm_Lock.lock();\n\t}\n\tvoid UnLock()\n\t{\n\t\tm_Lock.unlock();\n\t}\npublic:\n\tinline void run();\n\nprivate:\n\tfast_mutex m_Lock;\n\tu16 m_port;\n};\n\nclass CmnHttpsServer:public QThread\n{\n\tQ_OBJECT\npublic:\n\tinline CmnHttpsServer(u16 port);\n\tinline ~CmnHttpsServer();\n\t\npublic:\n\tvoid Lock()\n\t{\n\t\tm_Lock.lock();\n\t}\n\tvoid UnLock()\n\t{\n\t\tm_Lock.unlock();\n\t}\npublic:\n\tinline void run();\n\nprivate:\n\tfast_mutex m_Lock;\n\tu16 m_port;\n};\n\ntypedef CmnHttpServer* LPCmnHttpServer;\ntypedef CmnHttpsServer* LPCmnHttpsServer;\n\n\n#include \"cmnserverimpl.hpp\"\n\n\n#endif \/* __VSC_CMN_SERVER__H_ *\/\n\nadd oapi.hpp\/\/------------------------------------------------------------------------------\n\/\/ File: cmnserver.hpp\n\/\/\n\/\/ Desc: Common HTTP server - HTTP server for all application\n\/\/\n\/\/ Copyright (c) 2014-2018 opencvr.com. All rights reserved.\n\/\/------------------------------------------------------------------------------\n#ifndef __VSC_CMN_SERVER__H_\n#define __VSC_CMN_SERVER__H_\n#include \"utility.hpp\"\n#include \"debug.hpp\"\n#include \n\n#include \"XSDK\/XHash.h\"\n#include \"XSDK\/TimeUtils.h\"\n#include \"XSDK\/XSocket.h\"\n#include \"XSDK\/XSSLSocket.h\"\n#include \"Webby\/ClientSideRequest.h\"\n#include \"Webby\/ClientSideResponse.h\"\n#include \"Webby\/ServerSideRequest.h\"\n#include \"Webby\/ServerSideResponse.h\"\n#include \"Webby\/WebbyException.h\"\n\n#include \"oapi.hpp\"\n\nusing namespace std;\nusing namespace XSDK;\nusing namespace WEBBY;\n\n\/* each app can register a http REST path can move \n the socket to itself, for streaming, it it for performance.\n*\/\n\nusing namespace UtilityLib;\n\nclass CmnHttpServer:public QThread\n{\n\tQ_OBJECT\npublic:\n\tinline CmnHttpServer(u16 port);\n\tinline ~CmnHttpServer();\n\t\npublic:\n\tvoid Lock()\n\t{\n\t\tm_Lock.lock();\n\t}\n\tvoid UnLock()\n\t{\n\t\tm_Lock.unlock();\n\t}\npublic:\n\tinline void run();\n\nprivate:\n\tfast_mutex m_Lock;\n\tu16 m_port;\n};\n\nclass CmnHttpsServer:public QThread\n{\n\tQ_OBJECT\npublic:\n\tinline CmnHttpsServer(u16 port);\n\tinline ~CmnHttpsServer();\n\t\npublic:\n\tvoid Lock()\n\t{\n\t\tm_Lock.lock();\n\t}\n\tvoid UnLock()\n\t{\n\t\tm_Lock.unlock();\n\t}\npublic:\n\tinline void run();\n\nprivate:\n\tfast_mutex m_Lock;\n\tu16 m_port;\n};\n\ntypedef CmnHttpServer* LPCmnHttpServer;\ntypedef CmnHttpsServer* LPCmnHttpsServer;\n\n\n#include \"cmnserverimpl.hpp\"\n\n\n#endif \/* __VSC_CMN_SERVER__H_ *\/\n\n<|endoftext|>"} {"text":"\/\/ Prints the tag of a audio file \n\/\/ mp3, m4a ogg and flac supported\n\n\/\/ Bilal Hussain\n\n\/\/ install:\n\/\/ g++ `taglib-config --cflags --libs` taginfo.cpp -o taginfo\n\/\/ or \n\/\/ g++ -ltag -I\/usr\/local\/include\/taglib -L\/usr\/local\/lib taginfo.cpp -o taginfo\n\/\/ if no taglib-config\n\n#include \n#include \n#include \n\n#include \n#include \n\nvoid usage() {\n\tfprintf(stderr, \"taginfo \\n\");\n\tfprintf(stderr, \"Usage: taginfo \\n\");\n\tfprintf(stderr, \"Usage: taginfo --short \\n\");\n\tfprintf(stderr, \"Usage: taginfo --info \\n\");\n\tfprintf(stderr, \"Usage: taginfo --details \\n\");\n\tfprintf(stderr, \"Usage: taginfo --details-colour \\n\");\t\n}\n\nint main(int argc, char *argv[]) {\n\tif(argc < 2) {\n\t\tusage();\n\t\texit(1);\n\t}\n\n\tif (argc == 3 && strcmp(\"--short\", argv[1]) == 0){\n\t\tTagLib::FileRef f(argv[2]);\n\t\t\n\t\tprintf(\"%s\\n\", f.tag()->title().toCString(true));\n\t\tprintf(\"%s\\n\", f.tag()->album().toCString(true));\n\t\tprintf(\"%s\\n\", f.tag()->artist().toCString(true));\n\t\tint time = f.audioProperties()->length();\n\t\tprintf(\"%d:%d\\n\", (time%3600\/60), (time%60) );\n\t\texit(0);\n\t}\n\n\telse if (argc == 3 && strcmp(\"--info\", argv[1]) == 0){\n\t\tTagLib::FileRef f(argv[2]);\n\t\t\n\t\tprintf(\"%s - %02d %s - %s\\n\", \n\t\t\tf.tag()->artist().toCString(true),\n\t\t\tf.tag()->track(),\n\t\t\tf.tag()->title().toCString(true),\n\t\t\tf.tag()->album().toCString(true)\n\t\t);\n\t\texit(0);\n\t}\n\t\n\telse if (argc == 4 && strcmp(\"--details\", argv[1]) == 0){\n\t\tTagLib::FileRef f(argv[2]);\n\t\tlong start_time = strtol(argv[3],NULL,10);\n\t\tconst int end_time = f.audioProperties()->length();\n\t\t\n\t\tprintf(\"%s - %02d %s - %s - %ld:%02ld\/%d:%02d\\n\", \n\t\t\tf.tag()->artist().toCString(true),\n\t\t\tf.tag()->track(),\n\t\t\tf.tag()->title().toCString(true),\n\t\t\tf.tag()->album().toCString(true),\n\t\t\t(start_time%3600\/60), (start_time%60),\n\t\t\t(end_time%3600\/60), (end_time%60)\n\t\t);\n\t\texit(0);\n\t}\n\t\n\telse if (argc == 4 && strcmp(\"--details-colour\", argv[1]) == 0){\n\t\tTagLib::FileRef f(argv[2]);\n\t\tlong start_time = strtol(argv[3],NULL,10);\n\t\tconst int end_time = f.audioProperties()->length();\n\t\t\n\t\t\/\/ adds %s before and after\n\t\t#define SSS(str) \"%s\" str \"%s\"\n\t\t#define BLUE \"\\033[34m\" \/\/ Blue \n\t\t#define RED \"\\033[31m\" \/\/ Red \n\t\t#define GREEN \"\\033[32m\" \/\/ Green \n\t\t#define RESET \"\\033[0m\" \/\/ Need before and after \n\t\t#define COLOUR(string, colour) RESET colour, string, RESET\n\t\t\n\t\t\n\t\tprintf(\"%s - %02d \" SSS(\"%s\") \" - %s - %ld:%02ld\/%d:%02d\\n\", \n\t\t\tf.tag()->artist().toCString(true),\n\t\t\tf.tag()->track(),\n\t\t\tCOLOUR(f.tag()->title().toCString(true),BLUE),\n\t\t\tf.tag()->album().toCString(true),\n\t\t\t(start_time%3600\/60), (start_time%60),\n\t\t\t(end_time%3600\/60), (end_time%60)\n\t\t);\n\t\texit(0);\n\t}\n\n\tfor(int i = 1; i < argc; i++) {\n\t\tTagLib::FileRef f(argv[i]);\n\t\tif(!f.isNull() && f.tag()) {\n\t\t\tprintf(\"FILE=\\\"%s\\\"\\n\", argv[i]);\n\t\t\tprintf(\"ALBUM=\\\"%s\\\"\\n\", f.tag()->album().toCString(true));\n\t\t\tprintf(\"TRACK=\\\"%d\\\"\\n\", f.tag()->track());\n\t\t\tprintf(\"ARTIST=\\\"%s\\\"\\n\", f.tag()->artist().toCString(true));\n\t\t\tprintf(\"TITLE=\\\"%s\\\"\\n\", f.tag()->title().toCString(true));\n\t\t\tprintf(\"GENRE=\\\"%s\\\"\\n\", f.tag()->genre().toCString(true));\n\t\t\tprintf(\"YEAR=\\\"%d\\\"\\n\", f.tag()->year());\n\t\t\tprintf(\"COMMENT=\\\"%s\\\"\\n\", f.tag()->comment().toCString(true));\n\t\t\tprintf(\"LENGTH=\\\"%d\\\"\\n\", f.audioProperties()->length());\n\t\t\tprintf(\"BITRATE=\\\"%d\\\"\\n\", f.audioProperties()->bitrate());\n\t\t\tprintf(\"SAMPLERATE=\\\"%d\\\"\\n\", f.audioProperties()->sampleRate());\n\t\t\tprintf(\"CHANNELS=\\\"%d\\\"\\n\\n\", f.audioProperties()->channels());\n\t\t} else {\n\t\t\tfprintf(stderr, \"Error opening file: %s\\n\", argv[i]);\n\t\t}\n\t}\n\n\treturn 0;\n}\npretty print\/\/ Prints the tag of a audio file \n\/\/ mp3, m4a ogg and flac supported\n\n\/\/ Bilal Hussain\n\n\/\/ install:\n\/\/ g++ `taglib-config --cflags --libs` taginfo.cpp -o taginfo\n\/\/ or \n\/\/ g++ -ltag -I\/usr\/local\/include\/taglib -L\/usr\/local\/lib taginfo.cpp -o taginfo\n\/\/ if no taglib-config\n\n#include \n#include \n#include \n\n#include \n#include \n\nvoid usage() {\n\tfprintf(stderr, \"taginfo \\n\");\n\tfprintf(stderr, \"Usage: taginfo \\n\");\n\tfprintf(stderr, \"Usage: taginfo --short \\n\");\n\tfprintf(stderr, \"Usage: taginfo --info \\n\");\n\tfprintf(stderr, \"Usage: taginfo --pretty \\n\");\n\tfprintf(stderr, \"Usage: taginfo --pretty \\n\");\n\tfprintf(stderr, \"Usage: taginfo --details \\n\");\n\tfprintf(stderr, \"Usage: taginfo --details-colour \\n\");\t\n}\n\n\/\/ adds %s before and after\n#define SSS(str) \"%s\" str \"%s\"\n#define S3 \"%s%s%s\"\n#define BLUE \"\\033[34m\" \/\/ Blue \n#define RED \"\\033[31m\" \/\/ Red \n#define GREEN \"\\033[32m\" \/\/ Green \n#define RESET \"\\033[0m\" \/\/ Need before and after \n#define COLOUR(string, colour) RESET colour, string, RESET\n#define COLOURN(string, colour) string\n\n\nint main(int argc, char *argv[]) {\n\tif(argc < 2) {\n\t\tusage();\n\t\texit(1);\n\t}\n\n\tif (argc == 3 && strcmp(\"--short\", argv[1]) == 0){\n\t\tTagLib::FileRef f(argv[2]);\n\t\t\n\t\tprintf(\"%s\\n\", f.tag()->title().toCString(true));\n\t\tprintf(\"%s\\n\", f.tag()->album().toCString(true));\n\t\tprintf(\"%s\\n\", f.tag()->artist().toCString(true));\n\t\tint time = f.audioProperties()->length();\n\t\tprintf(\"%d:%d\\n\", (time%3600\/60), (time%60) );\n\t\texit(0);\n\t}\n\n\telse if (argc == 3 && strcmp(\"--info\", argv[1]) == 0){\n\t\tTagLib::FileRef f(argv[2]);\n\t\t\n\t\tprintf(\"%s - %02d %s - %s\\n\", \n\t\t\tf.tag()->artist().toCString(true),\n\t\t\tf.tag()->track(),\n\t\t\tf.tag()->title().toCString(true),\n\t\t\tf.tag()->album().toCString(true)\n\t\t);\n\t\texit(0);\n\t}\n\t\n\telse if (argc == 4 && strcmp(\"--details\", argv[1]) == 0){\n\t\tTagLib::FileRef f(argv[2]);\n\t\tlong start_time = strtol(argv[3],NULL,10);\n\t\tconst int end_time = f.audioProperties()->length();\n\t\t\n\t\tprintf(\"%s - %02d %s - %s - %ld:%02ld\/%d:%02d\\n\", \n\t\t\tf.tag()->artist().toCString(true),\n\t\t\tf.tag()->track(),\n\t\t\tf.tag()->title().toCString(true),\n\t\t\tf.tag()->album().toCString(true),\n\t\t\t(start_time%3600\/60), (start_time%60),\n\t\t\t(end_time%3600\/60), (end_time%60)\n\t\t);\n\t\texit(0);\n\t}\n\t\n\telse if (argc == 4 && strcmp(\"--details-colour\", argv[1]) == 0){\n\t\tTagLib::FileRef f(argv[2]);\n\t\tlong start_time = strtol(argv[3],NULL,10);\n\t\tconst int end_time = f.audioProperties()->length();\n\t\t\t\t\n\t\tprintf(\"%s - %02d \" SSS(\"%s\") \" - %s - %ld:%02ld\/%d:%02d\\n\", \n\t\t\tf.tag()->artist().toCString(true),\n\t\t\tf.tag()->track(),\n\t\t\tCOLOUR(f.tag()->title().toCString(true),BLUE),\n\t\t\tf.tag()->album().toCString(true),\n\t\t\t(start_time%3600\/60), (start_time%60),\n\t\t\t(end_time%3600\/60), (end_time%60)\n\t\t);\n\t\texit(0);\n\t}\n\t\n\telse if (argc == 4 && strcmp(\"--pretty\", argv[1]) == 0){\n\t\tTagLib::FileRef f(argv[2]);\n\t\tlong start_time = strtol(argv[3],NULL,10);\n\t\tconst int end_time = f.audioProperties()->length();\n\t\t\n\t\t\n\t \/\/ Track : Faraway ★★★★★\n\t \/\/ Album : Day After Tomorrow\n\t \/\/ Artist: Day After Tomorrow\n\t \/\/ Time : 5:00\/5:84\n\t\t\n\t\tprintf(\n\t\t\t\"Track : %d - \" S3 \"\\n\"\n\t\t\t\"Album : %s\\n\"\n\t\t\t\"Artist : %s\\n\"\n\t\t\t\"Time : %ld:%02ld\/%d:%02d\\n\",\n\t\t\t\n\t\t\tf.tag()->track(), COLOUR(f.tag()->title().toCString(true),BLUE),\n\t\t\tf.tag()->artist().toCString(true),\n\t\t\tf.tag()->album().toCString(true),\n\t\t\t\n\t\t\t(start_time%3600\/60), (start_time%60), (end_time%3600\/60), (end_time%60)\n\t\t);\n\t\t\n\t\texit(0);\n\t}\n\n\telse if (argc == 3 && strcmp(\"--pretty\", argv[1]) == 0){\n\t\tTagLib::FileRef f(argv[2]);\n\t\tconst int end_time = f.audioProperties()->length();\n\t\t\n\t\t\n\t \/\/ Track : Faraway ★★★★★\n\t \/\/ Album : Day After Tomorrow\n\t \/\/ Artist: Day After Tomorrow\n\t \/\/ Time : 5:00\/5:84\n\t\t\n\t\tprintf(\n\t\t\t\"Track : %d - \" S3 \"\\n\"\n\t\t\t\"Album : %s\\n\"\n\t\t\t\"Artist : %s\\n\"\n\t\t\t\"Time : %d:%02d\\n\",\n\t\t\t\n\t\t\tf.tag()->track(), COLOUR(f.tag()->title().toCString(true),BLUE),\n\t\t\tf.tag()->artist().toCString(true),\n\t\t\tf.tag()->album().toCString(true),\n\t\t\t(end_time%3600\/60), (end_time%60)\n\t\t);\n\t\t\n\t\texit(0);\n\t}\n\t\n\n\tfor(int i = 1; i < argc; i++) {\n\t\tTagLib::FileRef f(argv[i]);\n\t\tif(!f.isNull() && f.tag()) {\n\t\t\tprintf(\"FILE=\\\"%s\\\"\\n\", argv[i]);\n\t\t\tprintf(\"ALBUM=\\\"%s\\\"\\n\", f.tag()->album().toCString(true));\n\t\t\tprintf(\"TRACK=\\\"%d\\\"\\n\", f.tag()->track());\n\t\t\tprintf(\"ARTIST=\\\"%s\\\"\\n\", f.tag()->artist().toCString(true));\n\t\t\tprintf(\"TITLE=\\\"%s\\\"\\n\", f.tag()->title().toCString(true));\n\t\t\tprintf(\"GENRE=\\\"%s\\\"\\n\", f.tag()->genre().toCString(true));\n\t\t\tprintf(\"YEAR=\\\"%d\\\"\\n\", f.tag()->year());\n\t\t\tprintf(\"COMMENT=\\\"%s\\\"\\n\", f.tag()->comment().toCString(true));\n\t\t\tprintf(\"LENGTH=\\\"%d\\\"\\n\", f.audioProperties()->length());\n\t\t\tprintf(\"BITRATE=\\\"%d\\\"\\n\", f.audioProperties()->bitrate());\n\t\t\tprintf(\"SAMPLERATE=\\\"%d\\\"\\n\", f.audioProperties()->sampleRate());\n\t\t\tprintf(\"CHANNELS=\\\"%d\\\"\\n\\n\", f.audioProperties()->channels());\n\t\t} else {\n\t\t\tfprintf(stderr, \"Error opening file: %s\\n\", argv[i]);\n\t\t}\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin\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 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#include \n#include \n\n#ifdef TRACK_LOCKS\n#include \n#endif\n\n#include \n\nvoid Spinlock::acquire()\n{\n \/\/ Save the current irq status.\n\n \/\/ This save to local variable prevents a heinous race condition where the thread is\n \/\/ preempted between the getInterrupts and setInterrupts, then this same spinlock is called\n \/\/ in the new thread with interrupts disabled. It gets back to us, and m_bInterrupts==false.\n \/\/ Oh dear, hanging time.\n \/\/\n \/\/ We write to a local so the interrupt value is saved onto the stack until interrupts are\n \/\/ definately disabled; then we can write it back to the member variable.\n bool bInterrupts = Processor::getInterrupts();\n\n \/\/ Disable irqs if not already done\n if (bInterrupts)\n Processor::setInterrupts(false);\n\n if (m_Magic != 0xdeadbaba)\n {\n FATAL(\"Wrong magic in acquire.\");\n }\n\n while (m_Atom.compareAndSwap(true, false) == false)\n {\n#ifndef MULTIPROCESSOR\n \/\/\/ \\note When we hit this breakpoint, we're not able to backtrace as backtracing\n \/\/\/ depends on the log spinlock, which may have deadlocked. So we actually\n \/\/\/ force the spinlock to release here, then hit the breakpoint.\n size_t atom = m_Atom;\n m_Atom = true;\n\n \/\/ Break into the debugger, with the return address in EAX to make debugging easier\n#ifdef X86\n FATAL_NOLOCK(\"Spinlock has deadlocked, return address of other locker is \" << m_Ra << \", spinlock is \" << reinterpret_cast(this) << \", atom is \" << atom << \".\");\n \/\/ asm volatile(\"mov %0, %%eax; mov %1, %%ebx; int3\" : : \"r\"(reinterpret_cast(this)), \"r\"(atom));\n#endif\n#ifdef X64\n asm volatile(\"mov %0, %%rax; mov %1, %%rbx; int3\" : : \"r\"(reinterpret_cast(this)), \"r\"(atom));\n#endif\n\n \/\/ Panic in case there's a return from the debugger (or the debugger isn't available)\n panic(\"Spinlock has deadlocked\");\n#endif\n }\n m_Ra = reinterpret_cast(__builtin_return_address(0));\n\n#ifdef TRACK_LOCKS\n\/\/ if (!m_bAvoidTracking)\n g_LocksCommand.lockAcquired(this);\n#endif\n\n m_bInterrupts = bInterrupts;\n\n}\nvoid Spinlock::release()\n{\n bool bWasInterrupts = Processor::getInterrupts();\n if (bWasInterrupts == true)\n {\n FATAL(\"Spinlock: release() called with interrupts enabled.\");\n }\n bool bInterrupts = m_bInterrupts;\n\n if (m_Magic != 0xdeadbaba)\n {\n FATAL(\"Wrong magic in release.\");\n }\n\n if (m_Atom.compareAndSwap(false, true) == false)\n {\n \/\/\/ \\note When we hit this breakpoint, we're not able to backtrace as backtracing\n \/\/\/ depends on the log spinlock, which may have deadlocked. So we actually\n \/\/\/ force the spinlock to release here, then hit the breakpoint.\n m_Atom = true;\n\n \/\/ Break into the debugger, with the return address in EAX to make debugging easier\n#ifdef X86\n asm volatile(\"mov %0, %%eax; mov %1, %%ebx; int3\" : : \"r\"(reinterpret_cast(this)), \"m\"(m_Atom));\n#endif\n#ifdef X64\n asm volatile(\"mov %0, %%rax; mov %1, %%rbx; int3\" : : \"r\"(reinterpret_cast(this)), \"m\"(m_Atom));\n#endif\n\n \/\/ Panic in case there's a return from the debugger (or the debugger isn't available)\n panic(\"Spinlock has deadlocked\");\n }\n\n#ifdef TRACK_LOCKS\n\/\/ if (!m_bAvoidTracking)\n g_LocksCommand.lockReleased(this);\n#endif\n\n \/\/ Reenable irqs if they were enabled before\n if (bInterrupts)\n {\n Processor::setInterrupts(true);\n }\n}\nAdd Log.h to list of includes in Spinlock.cc. Previously assumed that other headers would indirectly include Log.h\/*\n * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin\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 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#include \n#include \n\n#ifdef TRACK_LOCKS\n#include \n#endif\n\n#include \n\n#include \n\nvoid Spinlock::acquire()\n{\n \/\/ Save the current irq status.\n\n \/\/ This save to local variable prevents a heinous race condition where the thread is\n \/\/ preempted between the getInterrupts and setInterrupts, then this same spinlock is called\n \/\/ in the new thread with interrupts disabled. It gets back to us, and m_bInterrupts==false.\n \/\/ Oh dear, hanging time.\n \/\/\n \/\/ We write to a local so the interrupt value is saved onto the stack until interrupts are\n \/\/ definately disabled; then we can write it back to the member variable.\n bool bInterrupts = Processor::getInterrupts();\n\n \/\/ Disable irqs if not already done\n if (bInterrupts)\n Processor::setInterrupts(false);\n\n if (m_Magic != 0xdeadbaba)\n {\n FATAL(\"Wrong magic in acquire.\");\n }\n\n while (m_Atom.compareAndSwap(true, false) == false)\n {\n#ifndef MULTIPROCESSOR\n \/\/\/ \\note When we hit this breakpoint, we're not able to backtrace as backtracing\n \/\/\/ depends on the log spinlock, which may have deadlocked. So we actually\n \/\/\/ force the spinlock to release here, then hit the breakpoint.\n size_t atom = m_Atom;\n m_Atom = true;\n\n \/\/ Break into the debugger, with the return address in EAX to make debugging easier\n#ifdef X86\n FATAL_NOLOCK(\"Spinlock has deadlocked, return address of other locker is \" << m_Ra << \", spinlock is \" << reinterpret_cast(this) << \", atom is \" << atom << \".\");\n \/\/ asm volatile(\"mov %0, %%eax; mov %1, %%ebx; int3\" : : \"r\"(reinterpret_cast(this)), \"r\"(atom));\n#endif\n#ifdef X64\n asm volatile(\"mov %0, %%rax; mov %1, %%rbx; int3\" : : \"r\"(reinterpret_cast(this)), \"r\"(atom));\n#endif\n\n \/\/ Panic in case there's a return from the debugger (or the debugger isn't available)\n panic(\"Spinlock has deadlocked\");\n#endif\n }\n m_Ra = reinterpret_cast(__builtin_return_address(0));\n\n#ifdef TRACK_LOCKS\n\/\/ if (!m_bAvoidTracking)\n g_LocksCommand.lockAcquired(this);\n#endif\n\n m_bInterrupts = bInterrupts;\n\n}\nvoid Spinlock::release()\n{\n bool bWasInterrupts = Processor::getInterrupts();\n if (bWasInterrupts == true)\n {\n FATAL(\"Spinlock: release() called with interrupts enabled.\");\n }\n bool bInterrupts = m_bInterrupts;\n\n if (m_Magic != 0xdeadbaba)\n {\n FATAL(\"Wrong magic in release.\");\n }\n\n if (m_Atom.compareAndSwap(false, true) == false)\n {\n \/\/\/ \\note When we hit this breakpoint, we're not able to backtrace as backtracing\n \/\/\/ depends on the log spinlock, which may have deadlocked. So we actually\n \/\/\/ force the spinlock to release here, then hit the breakpoint.\n m_Atom = true;\n\n \/\/ Break into the debugger, with the return address in EAX to make debugging easier\n#ifdef X86\n asm volatile(\"mov %0, %%eax; mov %1, %%ebx; int3\" : : \"r\"(reinterpret_cast(this)), \"m\"(m_Atom));\n#endif\n#ifdef X64\n asm volatile(\"mov %0, %%rax; mov %1, %%rbx; int3\" : : \"r\"(reinterpret_cast(this)), \"m\"(m_Atom));\n#endif\n\n \/\/ Panic in case there's a return from the debugger (or the debugger isn't available)\n panic(\"Spinlock has deadlocked\");\n }\n\n#ifdef TRACK_LOCKS\n\/\/ if (!m_bAvoidTracking)\n g_LocksCommand.lockReleased(this);\n#endif\n\n \/\/ Reenable irqs if they were enabled before\n if (bInterrupts)\n {\n Processor::setInterrupts(true);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n *\/\n\n#include \"arch\/utility.hh\"\n#include \"arch\/faults.hh\"\n#include \"base\/cprintf.hh\"\n#include \"base\/inifile.hh\"\n#include \"base\/loader\/symtab.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/pollevent.hh\"\n#include \"base\/range.hh\"\n#include \"base\/stats\/events.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/exetrace.hh\"\n#include \"cpu\/profile.hh\"\n#include \"cpu\/simple\/base.hh\"\n#include \"cpu\/simple_thread.hh\"\n#include \"cpu\/smt.hh\"\n#include \"cpu\/static_inst.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"mem\/packet.hh\"\n#include \"sim\/builder.hh\"\n#include \"sim\/byteswap.hh\"\n#include \"sim\/debug.hh\"\n#include \"sim\/host.hh\"\n#include \"sim\/sim_events.hh\"\n#include \"sim\/sim_object.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n\n#if FULL_SYSTEM\n#include \"arch\/kernel_stats.hh\"\n#include \"arch\/stacktrace.hh\"\n#include \"arch\/tlb.hh\"\n#include \"arch\/vtophys.hh\"\n#include \"base\/remote_gdb.hh\"\n#else \/\/ !FULL_SYSTEM\n#include \"mem\/mem_object.hh\"\n#endif \/\/ FULL_SYSTEM\n\nusing namespace std;\nusing namespace TheISA;\n\nBaseSimpleCPU::BaseSimpleCPU(Params *p)\n : BaseCPU(p), traceData(NULL), thread(NULL), predecoder(NULL)\n{\n#if FULL_SYSTEM\n thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb);\n#else\n thread = new SimpleThread(this, \/* thread_num *\/ 0, p->process,\n \/* asid *\/ 0);\n#endif \/\/ !FULL_SYSTEM\n\n thread->setStatus(ThreadContext::Unallocated);\n\n tc = thread->getTC();\n\n numInst = 0;\n startNumInst = 0;\n numLoad = 0;\n startNumLoad = 0;\n lastIcacheStall = 0;\n lastDcacheStall = 0;\n\n threadContexts.push_back(tc);\n\n fetchOffset = 0;\n stayAtPC = false;\n}\n\nBaseSimpleCPU::~BaseSimpleCPU()\n{\n}\n\nvoid\nBaseSimpleCPU::deallocateContext(int thread_num)\n{\n \/\/ for now, these are equivalent\n suspendContext(thread_num);\n}\n\n\nvoid\nBaseSimpleCPU::haltContext(int thread_num)\n{\n \/\/ for now, these are equivalent\n suspendContext(thread_num);\n}\n\n\nvoid\nBaseSimpleCPU::regStats()\n{\n using namespace Stats;\n\n BaseCPU::regStats();\n\n numInsts\n .name(name() + \".num_insts\")\n .desc(\"Number of instructions executed\")\n ;\n\n numMemRefs\n .name(name() + \".num_refs\")\n .desc(\"Number of memory references\")\n ;\n\n notIdleFraction\n .name(name() + \".not_idle_fraction\")\n .desc(\"Percentage of non-idle cycles\")\n ;\n\n idleFraction\n .name(name() + \".idle_fraction\")\n .desc(\"Percentage of idle cycles\")\n ;\n\n icacheStallCycles\n .name(name() + \".icache_stall_cycles\")\n .desc(\"ICache total stall cycles\")\n .prereq(icacheStallCycles)\n ;\n\n dcacheStallCycles\n .name(name() + \".dcache_stall_cycles\")\n .desc(\"DCache total stall cycles\")\n .prereq(dcacheStallCycles)\n ;\n\n icacheRetryCycles\n .name(name() + \".icache_retry_cycles\")\n .desc(\"ICache total retry cycles\")\n .prereq(icacheRetryCycles)\n ;\n\n dcacheRetryCycles\n .name(name() + \".dcache_retry_cycles\")\n .desc(\"DCache total retry cycles\")\n .prereq(dcacheRetryCycles)\n ;\n\n idleFraction = constant(1.0) - notIdleFraction;\n}\n\nvoid\nBaseSimpleCPU::resetStats()\n{\n\/\/ startNumInst = numInst;\n \/\/ notIdleFraction = (_status != Idle);\n}\n\nvoid\nBaseSimpleCPU::serialize(ostream &os)\n{\n BaseCPU::serialize(os);\n\/\/ SERIALIZE_SCALAR(inst);\n nameOut(os, csprintf(\"%s.xc.0\", name()));\n thread->serialize(os);\n}\n\nvoid\nBaseSimpleCPU::unserialize(Checkpoint *cp, const string §ion)\n{\n BaseCPU::unserialize(cp, section);\n\/\/ UNSERIALIZE_SCALAR(inst);\n thread->unserialize(cp, csprintf(\"%s.xc.0\", section));\n}\n\nvoid\nchange_thread_state(int thread_number, int activate, int priority)\n{\n}\n\nFault\nBaseSimpleCPU::copySrcTranslate(Addr src)\n{\n#if 0\n static bool no_warn = true;\n int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;\n \/\/ Only support block sizes of 64 atm.\n assert(blk_size == 64);\n int offset = src & (blk_size - 1);\n\n \/\/ Make sure block doesn't span page\n if (no_warn &&\n (src & PageMask) != ((src + blk_size) & PageMask) &&\n (src >> 40) != 0xfffffc) {\n warn(\"Copied block source spans pages %x.\", src);\n no_warn = false;\n }\n\n memReq->reset(src & ~(blk_size - 1), blk_size);\n\n \/\/ translate to physical address\n Fault fault = thread->translateDataReadReq(req);\n\n if (fault == NoFault) {\n thread->copySrcAddr = src;\n thread->copySrcPhysAddr = memReq->paddr + offset;\n } else {\n assert(!fault->isAlignmentFault());\n\n thread->copySrcAddr = 0;\n thread->copySrcPhysAddr = 0;\n }\n return fault;\n#else\n return NoFault;\n#endif\n}\n\nFault\nBaseSimpleCPU::copy(Addr dest)\n{\n#if 0\n static bool no_warn = true;\n int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;\n \/\/ Only support block sizes of 64 atm.\n assert(blk_size == 64);\n uint8_t data[blk_size];\n \/\/assert(thread->copySrcAddr);\n int offset = dest & (blk_size - 1);\n\n \/\/ Make sure block doesn't span page\n if (no_warn &&\n (dest & PageMask) != ((dest + blk_size) & PageMask) &&\n (dest >> 40) != 0xfffffc) {\n no_warn = false;\n warn(\"Copied block destination spans pages %x. \", dest);\n }\n\n memReq->reset(dest & ~(blk_size -1), blk_size);\n \/\/ translate to physical address\n Fault fault = thread->translateDataWriteReq(req);\n\n if (fault == NoFault) {\n Addr dest_addr = memReq->paddr + offset;\n \/\/ Need to read straight from memory since we have more than 8 bytes.\n memReq->paddr = thread->copySrcPhysAddr;\n thread->mem->read(memReq, data);\n memReq->paddr = dest_addr;\n thread->mem->write(memReq, data);\n if (dcacheInterface) {\n memReq->cmd = Copy;\n memReq->completionEvent = NULL;\n memReq->paddr = thread->copySrcPhysAddr;\n memReq->dest = dest_addr;\n memReq->size = 64;\n memReq->time = curTick;\n memReq->flags &= ~INST_READ;\n dcacheInterface->access(memReq);\n }\n }\n else\n assert(!fault->isAlignmentFault());\n\n return fault;\n#else\n panic(\"copy not implemented\");\n return NoFault;\n#endif\n}\n\n#if FULL_SYSTEM\nAddr\nBaseSimpleCPU::dbg_vtophys(Addr addr)\n{\n return vtophys(tc, addr);\n}\n#endif \/\/ FULL_SYSTEM\n\n#if FULL_SYSTEM\nvoid\nBaseSimpleCPU::post_interrupt(int int_num, int index)\n{\n BaseCPU::post_interrupt(int_num, index);\n\n if (thread->status() == ThreadContext::Suspended) {\n DPRINTF(Quiesce,\"Suspended Processor awoke\\n\");\n thread->activate();\n }\n}\n#endif \/\/ FULL_SYSTEM\n\nvoid\nBaseSimpleCPU::checkForInterrupts()\n{\n#if FULL_SYSTEM\n if (check_interrupts(tc)) {\n Fault interrupt = interrupts.getInterrupt(tc);\n\n if (interrupt != NoFault) {\n interrupts.updateIntrInfo(tc);\n interrupt->invoke(tc);\n }\n }\n#endif\n}\n\n\nFault\nBaseSimpleCPU::setupFetchRequest(Request *req)\n{\n uint64_t threadPC = thread->readPC();\n\n \/\/ set up memory request for instruction fetch\n#if ISA_HAS_DELAY_SLOT\n DPRINTF(Fetch,\"Fetch: PC:%08p NPC:%08p NNPC:%08p\\n\",threadPC,\n thread->readNextPC(),thread->readNextNPC());\n#else\n DPRINTF(Fetch,\"Fetch: PC:%08p NPC:%08p\",threadPC,\n thread->readNextPC());\n#endif\n\n const Addr PCMask = ~(sizeof(MachInst) - 1);\n Addr fetchPC = thread->readPC() + fetchOffset;\n req->setVirt(0, fetchPC & PCMask, sizeof(MachInst), 0, threadPC());\n\n Fault fault = thread->translateInstReq(req);\n\n return fault;\n}\n\n\nvoid\nBaseSimpleCPU::preExecute()\n{\n \/\/ maintain $r0 semantics\n thread->setIntReg(ZeroReg, 0);\n#if THE_ISA == ALPHA_ISA\n thread->setFloatReg(ZeroReg, 0.0);\n#endif \/\/ ALPHA_ISA\n\n \/\/ keep an instruction count\n numInst++;\n numInsts++;\n\n thread->funcExeInst++;\n\n \/\/ check for instruction-count-based events\n comInstEventQueue[0]->serviceEvents(numInst);\n\n \/\/ decode the instruction\n inst = gtoh(inst);\n\n \/\/If we're not in the middle of a macro instruction\n if (!curMacroStaticInst) {\n\n StaticInstPtr instPtr = NULL;\n\n \/\/Predecode, ie bundle up an ExtMachInst\n \/\/This should go away once the constructor can be set up properly\n predecoder.setTC(thread->getTC());\n \/\/If more fetch data is needed, pass it in.\n const Addr PCMask = ~(sizeof(MachInst) - 1);\n if(predecoder.needMoreBytes())\n predecoder.moreBytes((thread->readPC() & PCMask) + fetchOffset,\n 0, inst);\n else\n predecoder.process();\n\n \/\/If an instruction is ready, decode it. Otherwise, we'll have to\n \/\/fetch beyond the MachInst at the current pc.\n if (predecoder.extMachInstReady()) {\n#if THE_ISA == X86_ISA\n thread->setNextPC(thread->readPC() + predecoder.getInstSize());\n#endif \/\/ X86_ISA\n stayAtPC = false;\n instPtr = StaticInst::decode(predecoder.getExtMachInst());\n } else {\n stayAtPC = true;\n fetchOffset += sizeof(MachInst);\n }\n\n \/\/If we decoded an instruction and it's microcoded, start pulling\n \/\/out micro ops\n if (instPtr && instPtr->isMacroOp()) {\n curMacroStaticInst = instPtr;\n curStaticInst = curMacroStaticInst->\n fetchMicroOp(thread->readMicroPC());\n } else {\n curStaticInst = instPtr;\n }\n } else {\n \/\/Read the next micro op from the macro op\n curStaticInst = curMacroStaticInst->\n fetchMicroOp(thread->readMicroPC());\n }\n\n#if TRACING_ON\n \/\/If we decoded an instruction this \"tick\", record information about it.\n if(curStaticInst)\n {\n traceData = Trace::getInstRecord(curTick, tc, curStaticInst,\n thread->readPC());\n\n DPRINTF(Decode,\"Decode: Decoded %s instruction: 0x%x\\n\",\n curStaticInst->getName(), curStaticInst->machInst);\n\n#if FULL_SYSTEM\n thread->setInst(inst);\n#endif \/\/ FULL_SYSTEM\n }\n#endif \/\/ TRACING_ON\n}\n\nvoid\nBaseSimpleCPU::postExecute()\n{\n#if FULL_SYSTEM\n if (thread->profile) {\n bool usermode = TheISA::inUserMode(tc);\n thread->profilePC = usermode ? 1 : thread->readPC();\n StaticInstPtr si(inst);\n ProfileNode *node = thread->profile->consume(tc, si);\n if (node)\n thread->profileNode = node;\n }\n#endif\n\n if (curStaticInst->isMemRef()) {\n numMemRefs++;\n }\n\n if (curStaticInst->isLoad()) {\n ++numLoad;\n comLoadEventQueue[0]->serviceEvents(numLoad);\n }\n\n traceFunctions(thread->readPC());\n\n if (traceData) {\n traceData->dump();\n delete traceData;\n traceData = NULL;\n }\n}\n\n\nvoid\nBaseSimpleCPU::advancePC(Fault fault)\n{\n \/\/Since we're moving to a new pc, zero out the offset\n fetchOffset = 0;\n if (fault != NoFault) {\n curMacroStaticInst = StaticInst::nullStaticInstPtr;\n fault->invoke(tc);\n thread->setMicroPC(0);\n thread->setNextMicroPC(1);\n } else {\n \/\/If we're at the last micro op for this instruction\n if (curStaticInst && curStaticInst->isLastMicroOp()) {\n \/\/We should be working with a macro op\n assert(curMacroStaticInst);\n \/\/Close out this macro op, and clean up the\n \/\/microcode state\n curMacroStaticInst = StaticInst::nullStaticInstPtr;\n thread->setMicroPC(0);\n thread->setNextMicroPC(1);\n }\n \/\/If we're still in a macro op\n if (curMacroStaticInst) {\n \/\/Advance the micro pc\n thread->setMicroPC(thread->readNextMicroPC());\n \/\/Advance the \"next\" micro pc. Note that there are no delay\n \/\/slots, and micro ops are \"word\" addressed.\n thread->setNextMicroPC(thread->readNextMicroPC() + 1);\n } else {\n \/\/ go to the next instruction\n thread->setPC(thread->readNextPC());\n thread->setNextPC(thread->readNextNPC());\n thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));\n assert(thread->readNextPC() != thread->readNextNPC());\n }\n }\n\n#if FULL_SYSTEM\n Addr oldpc;\n do {\n oldpc = thread->readPC();\n system->pcEventQueue.service(tc);\n } while (oldpc != thread->readPC());\n#endif\n}\n\nMinor error. Forgotten to remove brackets for threadPC.\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n *\/\n\n#include \"arch\/utility.hh\"\n#include \"arch\/faults.hh\"\n#include \"base\/cprintf.hh\"\n#include \"base\/inifile.hh\"\n#include \"base\/loader\/symtab.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/pollevent.hh\"\n#include \"base\/range.hh\"\n#include \"base\/stats\/events.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/exetrace.hh\"\n#include \"cpu\/profile.hh\"\n#include \"cpu\/simple\/base.hh\"\n#include \"cpu\/simple_thread.hh\"\n#include \"cpu\/smt.hh\"\n#include \"cpu\/static_inst.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"mem\/packet.hh\"\n#include \"sim\/builder.hh\"\n#include \"sim\/byteswap.hh\"\n#include \"sim\/debug.hh\"\n#include \"sim\/host.hh\"\n#include \"sim\/sim_events.hh\"\n#include \"sim\/sim_object.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n\n#if FULL_SYSTEM\n#include \"arch\/kernel_stats.hh\"\n#include \"arch\/stacktrace.hh\"\n#include \"arch\/tlb.hh\"\n#include \"arch\/vtophys.hh\"\n#include \"base\/remote_gdb.hh\"\n#else \/\/ !FULL_SYSTEM\n#include \"mem\/mem_object.hh\"\n#endif \/\/ FULL_SYSTEM\n\nusing namespace std;\nusing namespace TheISA;\n\nBaseSimpleCPU::BaseSimpleCPU(Params *p)\n : BaseCPU(p), traceData(NULL), thread(NULL), predecoder(NULL)\n{\n#if FULL_SYSTEM\n thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb);\n#else\n thread = new SimpleThread(this, \/* thread_num *\/ 0, p->process,\n \/* asid *\/ 0);\n#endif \/\/ !FULL_SYSTEM\n\n thread->setStatus(ThreadContext::Unallocated);\n\n tc = thread->getTC();\n\n numInst = 0;\n startNumInst = 0;\n numLoad = 0;\n startNumLoad = 0;\n lastIcacheStall = 0;\n lastDcacheStall = 0;\n\n threadContexts.push_back(tc);\n\n fetchOffset = 0;\n stayAtPC = false;\n}\n\nBaseSimpleCPU::~BaseSimpleCPU()\n{\n}\n\nvoid\nBaseSimpleCPU::deallocateContext(int thread_num)\n{\n \/\/ for now, these are equivalent\n suspendContext(thread_num);\n}\n\n\nvoid\nBaseSimpleCPU::haltContext(int thread_num)\n{\n \/\/ for now, these are equivalent\n suspendContext(thread_num);\n}\n\n\nvoid\nBaseSimpleCPU::regStats()\n{\n using namespace Stats;\n\n BaseCPU::regStats();\n\n numInsts\n .name(name() + \".num_insts\")\n .desc(\"Number of instructions executed\")\n ;\n\n numMemRefs\n .name(name() + \".num_refs\")\n .desc(\"Number of memory references\")\n ;\n\n notIdleFraction\n .name(name() + \".not_idle_fraction\")\n .desc(\"Percentage of non-idle cycles\")\n ;\n\n idleFraction\n .name(name() + \".idle_fraction\")\n .desc(\"Percentage of idle cycles\")\n ;\n\n icacheStallCycles\n .name(name() + \".icache_stall_cycles\")\n .desc(\"ICache total stall cycles\")\n .prereq(icacheStallCycles)\n ;\n\n dcacheStallCycles\n .name(name() + \".dcache_stall_cycles\")\n .desc(\"DCache total stall cycles\")\n .prereq(dcacheStallCycles)\n ;\n\n icacheRetryCycles\n .name(name() + \".icache_retry_cycles\")\n .desc(\"ICache total retry cycles\")\n .prereq(icacheRetryCycles)\n ;\n\n dcacheRetryCycles\n .name(name() + \".dcache_retry_cycles\")\n .desc(\"DCache total retry cycles\")\n .prereq(dcacheRetryCycles)\n ;\n\n idleFraction = constant(1.0) - notIdleFraction;\n}\n\nvoid\nBaseSimpleCPU::resetStats()\n{\n\/\/ startNumInst = numInst;\n \/\/ notIdleFraction = (_status != Idle);\n}\n\nvoid\nBaseSimpleCPU::serialize(ostream &os)\n{\n BaseCPU::serialize(os);\n\/\/ SERIALIZE_SCALAR(inst);\n nameOut(os, csprintf(\"%s.xc.0\", name()));\n thread->serialize(os);\n}\n\nvoid\nBaseSimpleCPU::unserialize(Checkpoint *cp, const string §ion)\n{\n BaseCPU::unserialize(cp, section);\n\/\/ UNSERIALIZE_SCALAR(inst);\n thread->unserialize(cp, csprintf(\"%s.xc.0\", section));\n}\n\nvoid\nchange_thread_state(int thread_number, int activate, int priority)\n{\n}\n\nFault\nBaseSimpleCPU::copySrcTranslate(Addr src)\n{\n#if 0\n static bool no_warn = true;\n int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;\n \/\/ Only support block sizes of 64 atm.\n assert(blk_size == 64);\n int offset = src & (blk_size - 1);\n\n \/\/ Make sure block doesn't span page\n if (no_warn &&\n (src & PageMask) != ((src + blk_size) & PageMask) &&\n (src >> 40) != 0xfffffc) {\n warn(\"Copied block source spans pages %x.\", src);\n no_warn = false;\n }\n\n memReq->reset(src & ~(blk_size - 1), blk_size);\n\n \/\/ translate to physical address\n Fault fault = thread->translateDataReadReq(req);\n\n if (fault == NoFault) {\n thread->copySrcAddr = src;\n thread->copySrcPhysAddr = memReq->paddr + offset;\n } else {\n assert(!fault->isAlignmentFault());\n\n thread->copySrcAddr = 0;\n thread->copySrcPhysAddr = 0;\n }\n return fault;\n#else\n return NoFault;\n#endif\n}\n\nFault\nBaseSimpleCPU::copy(Addr dest)\n{\n#if 0\n static bool no_warn = true;\n int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;\n \/\/ Only support block sizes of 64 atm.\n assert(blk_size == 64);\n uint8_t data[blk_size];\n \/\/assert(thread->copySrcAddr);\n int offset = dest & (blk_size - 1);\n\n \/\/ Make sure block doesn't span page\n if (no_warn &&\n (dest & PageMask) != ((dest + blk_size) & PageMask) &&\n (dest >> 40) != 0xfffffc) {\n no_warn = false;\n warn(\"Copied block destination spans pages %x. \", dest);\n }\n\n memReq->reset(dest & ~(blk_size -1), blk_size);\n \/\/ translate to physical address\n Fault fault = thread->translateDataWriteReq(req);\n\n if (fault == NoFault) {\n Addr dest_addr = memReq->paddr + offset;\n \/\/ Need to read straight from memory since we have more than 8 bytes.\n memReq->paddr = thread->copySrcPhysAddr;\n thread->mem->read(memReq, data);\n memReq->paddr = dest_addr;\n thread->mem->write(memReq, data);\n if (dcacheInterface) {\n memReq->cmd = Copy;\n memReq->completionEvent = NULL;\n memReq->paddr = thread->copySrcPhysAddr;\n memReq->dest = dest_addr;\n memReq->size = 64;\n memReq->time = curTick;\n memReq->flags &= ~INST_READ;\n dcacheInterface->access(memReq);\n }\n }\n else\n assert(!fault->isAlignmentFault());\n\n return fault;\n#else\n panic(\"copy not implemented\");\n return NoFault;\n#endif\n}\n\n#if FULL_SYSTEM\nAddr\nBaseSimpleCPU::dbg_vtophys(Addr addr)\n{\n return vtophys(tc, addr);\n}\n#endif \/\/ FULL_SYSTEM\n\n#if FULL_SYSTEM\nvoid\nBaseSimpleCPU::post_interrupt(int int_num, int index)\n{\n BaseCPU::post_interrupt(int_num, index);\n\n if (thread->status() == ThreadContext::Suspended) {\n DPRINTF(Quiesce,\"Suspended Processor awoke\\n\");\n thread->activate();\n }\n}\n#endif \/\/ FULL_SYSTEM\n\nvoid\nBaseSimpleCPU::checkForInterrupts()\n{\n#if FULL_SYSTEM\n if (check_interrupts(tc)) {\n Fault interrupt = interrupts.getInterrupt(tc);\n\n if (interrupt != NoFault) {\n interrupts.updateIntrInfo(tc);\n interrupt->invoke(tc);\n }\n }\n#endif\n}\n\n\nFault\nBaseSimpleCPU::setupFetchRequest(Request *req)\n{\n uint64_t threadPC = thread->readPC();\n\n \/\/ set up memory request for instruction fetch\n#if ISA_HAS_DELAY_SLOT\n DPRINTF(Fetch,\"Fetch: PC:%08p NPC:%08p NNPC:%08p\\n\",threadPC,\n thread->readNextPC(),thread->readNextNPC());\n#else\n DPRINTF(Fetch,\"Fetch: PC:%08p NPC:%08p\",threadPC,\n thread->readNextPC());\n#endif\n\n const Addr PCMask = ~(sizeof(MachInst) - 1);\n Addr fetchPC = thread->readPC() + fetchOffset;\n req->setVirt(0, fetchPC & PCMask, sizeof(MachInst), 0, threadPC);\n\n Fault fault = thread->translateInstReq(req);\n\n return fault;\n}\n\n\nvoid\nBaseSimpleCPU::preExecute()\n{\n \/\/ maintain $r0 semantics\n thread->setIntReg(ZeroReg, 0);\n#if THE_ISA == ALPHA_ISA\n thread->setFloatReg(ZeroReg, 0.0);\n#endif \/\/ ALPHA_ISA\n\n \/\/ keep an instruction count\n numInst++;\n numInsts++;\n\n thread->funcExeInst++;\n\n \/\/ check for instruction-count-based events\n comInstEventQueue[0]->serviceEvents(numInst);\n\n \/\/ decode the instruction\n inst = gtoh(inst);\n\n \/\/If we're not in the middle of a macro instruction\n if (!curMacroStaticInst) {\n\n StaticInstPtr instPtr = NULL;\n\n \/\/Predecode, ie bundle up an ExtMachInst\n \/\/This should go away once the constructor can be set up properly\n predecoder.setTC(thread->getTC());\n \/\/If more fetch data is needed, pass it in.\n const Addr PCMask = ~(sizeof(MachInst) - 1);\n if(predecoder.needMoreBytes())\n predecoder.moreBytes((thread->readPC() & PCMask) + fetchOffset,\n 0, inst);\n else\n predecoder.process();\n\n \/\/If an instruction is ready, decode it. Otherwise, we'll have to\n \/\/fetch beyond the MachInst at the current pc.\n if (predecoder.extMachInstReady()) {\n#if THE_ISA == X86_ISA\n thread->setNextPC(thread->readPC() + predecoder.getInstSize());\n#endif \/\/ X86_ISA\n stayAtPC = false;\n instPtr = StaticInst::decode(predecoder.getExtMachInst());\n } else {\n stayAtPC = true;\n fetchOffset += sizeof(MachInst);\n }\n\n \/\/If we decoded an instruction and it's microcoded, start pulling\n \/\/out micro ops\n if (instPtr && instPtr->isMacroOp()) {\n curMacroStaticInst = instPtr;\n curStaticInst = curMacroStaticInst->\n fetchMicroOp(thread->readMicroPC());\n } else {\n curStaticInst = instPtr;\n }\n } else {\n \/\/Read the next micro op from the macro op\n curStaticInst = curMacroStaticInst->\n fetchMicroOp(thread->readMicroPC());\n }\n\n#if TRACING_ON\n \/\/If we decoded an instruction this \"tick\", record information about it.\n if(curStaticInst)\n {\n traceData = Trace::getInstRecord(curTick, tc, curStaticInst,\n thread->readPC());\n\n DPRINTF(Decode,\"Decode: Decoded %s instruction: 0x%x\\n\",\n curStaticInst->getName(), curStaticInst->machInst);\n\n#if FULL_SYSTEM\n thread->setInst(inst);\n#endif \/\/ FULL_SYSTEM\n }\n#endif \/\/ TRACING_ON\n}\n\nvoid\nBaseSimpleCPU::postExecute()\n{\n#if FULL_SYSTEM\n if (thread->profile) {\n bool usermode = TheISA::inUserMode(tc);\n thread->profilePC = usermode ? 1 : thread->readPC();\n StaticInstPtr si(inst);\n ProfileNode *node = thread->profile->consume(tc, si);\n if (node)\n thread->profileNode = node;\n }\n#endif\n\n if (curStaticInst->isMemRef()) {\n numMemRefs++;\n }\n\n if (curStaticInst->isLoad()) {\n ++numLoad;\n comLoadEventQueue[0]->serviceEvents(numLoad);\n }\n\n traceFunctions(thread->readPC());\n\n if (traceData) {\n traceData->dump();\n delete traceData;\n traceData = NULL;\n }\n}\n\n\nvoid\nBaseSimpleCPU::advancePC(Fault fault)\n{\n \/\/Since we're moving to a new pc, zero out the offset\n fetchOffset = 0;\n if (fault != NoFault) {\n curMacroStaticInst = StaticInst::nullStaticInstPtr;\n fault->invoke(tc);\n thread->setMicroPC(0);\n thread->setNextMicroPC(1);\n } else {\n \/\/If we're at the last micro op for this instruction\n if (curStaticInst && curStaticInst->isLastMicroOp()) {\n \/\/We should be working with a macro op\n assert(curMacroStaticInst);\n \/\/Close out this macro op, and clean up the\n \/\/microcode state\n curMacroStaticInst = StaticInst::nullStaticInstPtr;\n thread->setMicroPC(0);\n thread->setNextMicroPC(1);\n }\n \/\/If we're still in a macro op\n if (curMacroStaticInst) {\n \/\/Advance the micro pc\n thread->setMicroPC(thread->readNextMicroPC());\n \/\/Advance the \"next\" micro pc. Note that there are no delay\n \/\/slots, and micro ops are \"word\" addressed.\n thread->setNextMicroPC(thread->readNextMicroPC() + 1);\n } else {\n \/\/ go to the next instruction\n thread->setPC(thread->readNextPC());\n thread->setNextPC(thread->readNextNPC());\n thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));\n assert(thread->readNextPC() != thread->readNextNPC());\n }\n }\n\n#if FULL_SYSTEM\n Addr oldpc;\n do {\n oldpc = thread->readPC();\n system->pcEventQueue.service(tc);\n } while (oldpc != thread->readPC());\n#endif\n}\n\n<|endoftext|>"} {"text":"\/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008.\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#include \"Relay.h\"\n#include \n#include \n#include \"Tools.hpp\"\n\n\n#include \"Simulation.h\"\n#include \"RelayNSL.h\"\n\n\nusing namespace std;\nusing namespace RELATION;\n\n\/* nslaw dispatch on bounds *\/\n\nstruct Relay::_BoundsNSLEffect : public SiconosVisitor\n{\n Relay *parent;\n unsigned int pos;\n SP::UnitaryRelation UR;\n\n _BoundsNSLEffect(Relay *p, SP::UnitaryRelation UR, unsigned int pos) :\n parent(p), UR(UR), pos(pos) {};\n\n void visit(RelayNSL& nslaw)\n {\n\n \/\/ cout << \"Relay::_BoundsNSLEffect visit\" << endl;\n for (int i = 0; i < UR->getNonSmoothLawSize(); i++)\n {\n (*(parent->lb()))(pos + i) =\n nslaw.lb();\n (*(parent->ub()))(pos + i) =\n nslaw.ub();\n }\n }\n\n void visit(ComplementarityConditionNSL& nslaw)\n {\n for (int i = 0; i < UR->getNonSmoothLawSize(); i++)\n {\n (*(parent->lb()))(pos + i) = 0.0;\n (*(parent->ub()))(pos + i) = 1e+24;\n }\n\n\n \/\/ \\warning Introduce the infinte double symbol rather 1e+24\n\n }\n\n};\n\nvoid Relay::initialize(SP::Simulation sim)\n{\n LinearOSNS::initialize(sim);\n \/\/cout << \"Relay::initialize\" << endl;\n\n\n \/\/ initialize memory for _lb and _ub\n if (! _lb)\n _lb.reset(new SimpleVector(maxSize()));\n else\n {\n if (_lb->size() != maxSize())\n _lb->resize(maxSize());\n }\n if (! _ub)\n _ub.reset(new SimpleVector(maxSize()));\n else\n {\n if (_ub->size() != maxSize())\n _ub->resize(maxSize());\n }\n\n \/\/ fill _lb and _ub wiht the value of the NonSmooth Law\n\n SP::UnitaryRelationsGraph indexSet = simulation()->indexSet(levelMin());\n\n \/\/cout << \" _sizeOutput =\" <<_sizeOutput << endl;\n if (_lb->size() != _sizeOutput)\n {\n _lb->resize(_sizeOutput, false);\n _lb->zero();\n }\n if (_ub->size() != _sizeOutput)\n {\n _ub->resize(_sizeOutput, false);\n _ub->zero();\n }\n\n unsigned int pos = 0;\n UnitaryRelationsGraph::VIterator ui, uiend;\n for (boost::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)\n {\n SP::UnitaryRelation ur = indexSet->bundle(*ui);\n\n \/\/ Compute q, this depends on the type of non smooth problem, on\n \/\/ the relation type and on the non smooth law\n pos = _M->getPositionOfUnitaryBlock(ur);\n SP::SiconosVisitor NSLEffect(new _BoundsNSLEffect(this, ur, pos));\n ur->interaction()->nonSmoothLaw()->accept(*NSLEffect);\n }\n\n}\n\n\nint Relay::compute(double time)\n{\n \/\/ --- Prepare data for Relay computing ---\n preCompute(time);\n\n int info = 0;\n \/\/ --- Call Numerics driver ---\n \/\/ Inputs:\n \/\/ - the problem (M,q ...)\n \/\/ - the unknowns (z,w)\n \/\/ - the options for the solver (name, max iteration number ...)\n \/\/ - the global options for Numerics (verbose mode ...)\n\n if (_sizeOutput != 0)\n {\n \/\/ The Relay in Numerics format\n Relay_Problem numerics_problem;\n numerics_problem.M = &*_M->getNumericsMatrix();\n numerics_problem.q = _q->getArray();\n numerics_problem.lb = _lb->getArray();\n numerics_problem.ub = _ub->getArray();\n numerics_problem.size = _sizeOutput;\n\n int nbSolvers = 1;\n \/\/ Call Relay Driver\n info = relay_driver(&numerics_problem, _z->getArray() , _w->getArray() ,\n &*_solver->numericsSolverOptions(), &*_numerics_options);\n\n \/\/ --- Recovering of the desired variables from Relay output ---\n postCompute();\n\n }\n\n return info;\n}\n\nvoid Relay::display() const\n{\n cout << \"======= Relay of size \" << _sizeOutput << \" with: \" << endl;\n LinearOSNS::display();\n}\n\nRelay* Relay::convert(OneStepNSProblem* osnsp)\n{\n Relay* lcp = dynamic_cast(osnsp);\n return lcp;\n}\n\n\nnew Relay.cpp\/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008.\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#include \"Relay.h\"\n#include \n#include \n#include \"Tools.hpp\"\n\n\n#include \"Simulation.h\"\n#include \"RelayNSL.h\"\n\n\nusing namespace std;\nusing namespace RELATION;\n\n\/* nslaw dispatch on bounds *\/\n\nstruct Relay::_BoundsNSLEffect : public SiconosVisitor\n{\n Relay *parent;\n unsigned int pos;\n SP::UnitaryRelation UR;\n\n _BoundsNSLEffect(Relay *p, SP::UnitaryRelation UR, unsigned int pos) :\n parent(p), UR(UR), pos(pos) {};\n\n void visit(RelayNSL& nslaw)\n {\n\n \/\/ cout << \"Relay::_BoundsNSLEffect visit\" << endl;\n for (int i = 0; i < UR->getNonSmoothLawSize(); i++)\n {\n (*(parent->lb()))(pos + i) =\n nslaw.lb();\n (*(parent->ub()))(pos + i) =\n nslaw.ub();\n }\n }\n\n void visit(ComplementarityConditionNSL& nslaw)\n {\n for (int i = 0; i < UR->getNonSmoothLawSize(); i++)\n {\n (*(parent->lb()))(pos + i) = 0.0;\n (*(parent->ub()))(pos + i) = 1e+24;\n }\n\n\n \/\/ \\warning Introduce the infinte double symbol rather 1e+24\n\n }\n\n};\n\nvoid Relay::initialize(SP::Simulation sim)\n{\n LinearOSNS::initialize(sim);\n \/\/cout << \"Relay::initialize\" << endl;\n\n\n \/\/ initialize memory for _lb and _ub\n if (! _lb)\n _lb.reset(new SimpleVector(maxSize()));\n else\n {\n if (_lb->size() != maxSize())\n _lb->resize(maxSize());\n }\n if (! _ub)\n _ub.reset(new SimpleVector(maxSize()));\n else\n {\n if (_ub->size() != maxSize())\n _ub->resize(maxSize());\n }\n\n \/\/ fill _lb and _ub wiht the value of the NonSmooth Law\n\n SP::UnitaryRelationsGraph indexSet = simulation()->indexSet(levelMin());\n\n \/\/cout << \" _sizeOutput =\" <<_sizeOutput << endl;\n if (_lb->size() != _sizeOutput)\n {\n _lb->resize(_sizeOutput, false);\n _lb->zero();\n }\n if (_ub->size() != _sizeOutput)\n {\n _ub->resize(_sizeOutput, false);\n _ub->zero();\n }\n\n unsigned int pos = 0;\n UnitaryRelationsGraph::VIterator ui, uiend;\n for (boost::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)\n {\n SP::UnitaryRelation ur = indexSet->bundle(*ui);\n\n \/\/ Compute q, this depends on the type of non smooth problem, on\n \/\/ the relation type and on the non smooth law\n pos = _M->getPositionOfUnitaryBlock(ur);\n SP::SiconosVisitor NSLEffect(new _BoundsNSLEffect(this, ur, pos));\n ur->interaction()->nonSmoothLaw()->accept(*NSLEffect);\n }\n\n}\n\n\nint Relay::compute(double time)\n{\n \/\/ --- Prepare data for Relay computing ---\n preCompute(time);\n\n int info = 0;\n \/\/ --- Call Numerics driver ---\n \/\/ Inputs:\n \/\/ - the problem (M,q ...)\n \/\/ - the unknowns (z,w)\n \/\/ - the options for the solver (name, max iteration number ...)\n \/\/ - the global options for Numerics (verbose mode ...)\n\n if (_sizeOutput != 0)\n {\n \/\/ The Relay in Numerics format\n Relay_Problem numerics_problem;\n numerics_problem.M = &*_M->getNumericsMatrix();\n numerics_problem.q = _q->getArray();\n numerics_problem.lb = _lb->getArray();\n numerics_problem.ub = _ub->getArray();\n numerics_problem.size = _sizeOutput;\n\n int nbSolvers = 1;\n \/\/ Call Relay Driver\n\n Relay_display(&numerics_problem);\n\n info = relay_driver(&numerics_problem, _z->getArray() , _w->getArray() ,\n &*_solver->numericsSolverOptions(), nbSolvers, &*_numerics_options);\n\n if (info != 0)\n {\n cout << \"Warning : Problem in Relay resolution\" << endl;\n }\n\n \/\/ --- Recovering of the desired variables from Relay output ---\n postCompute();\n\n }\n\n return info;\n}\n\nvoid Relay::display() const\n{\n cout << \"======= Relay of size \" << _sizeOutput << \" with: \" << endl;\n LinearOSNS::display();\n}\n\nRelay* Relay::convert(OneStepNSProblem* osnsp)\n{\n Relay* lcp = dynamic_cast(osnsp);\n return lcp;\n}\n\n\n<|endoftext|>"} {"text":"\/*\n * Licensed under Apache License v2. See LICENSE for more information.\n *\/\n#include \n#include \"CppUTest\/CommandLineTestRunner.h\" \n\nextern \"C\" {\n \n#include \n#include \n#include \n#include \n#include \n\n#include \"dyn_function.h\"\n\nstatic int g_count;\n\nstatic void stdLog(void *handle, int level, const char *file, int line, const char *msg, ...) {\n va_list ap;\n const char *levels[5] = {\"NIL\", \"ERROR\", \"WARNING\", \"INFO\", \"DEBUG\"};\n fprintf(stderr, \"%s: FILE:%s, LINE:%i, MSG:\",levels[level], file, line);\n va_start(ap, msg);\n vfprintf(stderr, msg, ap);\n fprintf(stderr, \"\\n\");\n}\n\n#define EXAMPLE1_SCHEMA \"example(III)I\"\nstatic void example1_binding(void *userData, void* args[], void *out) {\n printf(\"example1 closure called\\n\");\n int32_t a = *((int32_t *)args[0]);\n int32_t b = *((int32_t *)args[1]);\n int32_t c = *((int32_t *)args[2]);\n int32_t *ret = (int32_t *)out;\n *ret = a + b + c;\n g_count += 1;\n}\n\n#define EXAMPLE2_SCHEMA \"example(I{DDD val1 val2 val3}I)D\"\nstruct example2_arg2 {\n double val1;\n double val2;\n double val3;\n};\nvoid example2_binding(void *userData, void* args[], void *out) {\n printf(\"example2 closure called\\n\");\n int32_t a = *((int32_t *)args[0]);\n struct example2_arg2 b = *((struct example2_arg2 *)args[1]);\n int32_t c = *((int32_t *)args[2]);\n int32_t *ret = (int32_t *)out;\n *ret = a + b.val1 + b.val2 + b.val3 + c;\n g_count += 1;\n}\n\n\n#define EXAMPLE3_SCHEMA \"example(III){III sum max min}\"\nstruct example3_ret {\n int32_t sum;\n int32_t max;\n int32_t min;\n};\n\nstatic void example3_binding(void *userData, void* args[], void *out) {\n printf(\"example closure called\\n\");\n int32_t a = *((int32_t *)args[0]);\n int32_t b = *((int32_t *)args[1]);\n int32_t c = *((int32_t *)args[2]);\n struct example3_ret *result = (struct example3_ret *)calloc(1,sizeof(struct example3_ret));\n result->sum = a + b + c;\n result->min = a <= b ? a : b;\n result->max = a >= b ? a : b;\n result->min = result->min <= c ? result->min : c;\n result->max = result->max >= c ? result->max : c;\n\n struct example3_ret **ret = (struct example3_ret **)out;\n (*ret) = result;\n g_count += 1;\n}\n\nstatic void tests() {\n dyn_closure_type *dynClosure = NULL;\n int rc;\n\n {\n rc = dynClosure_create(EXAMPLE1_SCHEMA, example1_binding, NULL, &dynClosure);\n CHECK_EQUAL(0, rc);\n int32_t (*func)(int32_t a, int32_t b, int32_t c) = NULL;\n int rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func);\n CHECK_EQUAL(0, rc);\n int32_t ret = func(2,3,4);\n printf(\"Return value for example1 is %i\\n\", ret);\n CHECK_EQUAL(1, g_count);\n dynClosure_destroy(dynClosure);\n }\n\n {\n dynClosure = NULL;\n rc = dynClosure_create(EXAMPLE2_SCHEMA, example2_binding, NULL, &dynClosure);\n CHECK_EQUAL(0, rc);\n double (*func)(int32_t a, struct example2_arg2 b, int32_t c) = NULL;\n rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func);\n CHECK_EQUAL(0, rc);\n struct example2_arg2 b = { .val1 = 1.0, .val2 = 1.5, .val3 = 2.0 };\n double ret = func(2,b,4);\n printf(\"Return value for example2 is %f\\n\", ret);\n CHECK_EQUAL(2, g_count);\n dynClosure_destroy(dynClosure);\n }\n\n {\n dynClosure = NULL;\n rc = dynClosure_create(EXAMPLE3_SCHEMA, example3_binding, NULL, &dynClosure);\n CHECK_EQUAL(0, rc);\n struct example3_ret * (*func)(int32_t a, int32_t b, int32_t c) = NULL;\n rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func);\n CHECK_EQUAL(0, rc);\n struct example3_ret *ret = func(2,8,4);\n printf(\"Return value for example3 is {sum:%i, max:%i, min:%i}\\n\", ret->sum, ret->max, ret->min);\n CHECK_EQUAL(3, g_count);\n dynClosure_destroy(dynClosure);\n free(ret);\n }\n}\n\n}\n\n\nTEST_GROUP(DynClosureTests) {\n void setup() {\n dynFunction_logSetup(stdLog, NULL, 4);\n \/\/TODO dynType_logSetup(stdLog, NULL, 4);\n g_count = 0;\n }\n};\n\nTEST(DynClosureTests, DynCLosureTest1) {\n \/\/TODO split up\n tests();\n}\nCELIX-237: change struct assigment in ccputest.\/*\n * Licensed under Apache License v2. See LICENSE for more information.\n *\/\n#include \n#include \"CppUTest\/CommandLineTestRunner.h\" \n\nextern \"C\" {\n \n#include \n#include \n#include \n#include \n#include \n\n#include \"dyn_function.h\"\n\nstatic int g_count;\n\nstatic void stdLog(void *handle, int level, const char *file, int line, const char *msg, ...) {\n va_list ap;\n const char *levels[5] = {\"NIL\", \"ERROR\", \"WARNING\", \"INFO\", \"DEBUG\"};\n fprintf(stderr, \"%s: FILE:%s, LINE:%i, MSG:\",levels[level], file, line);\n va_start(ap, msg);\n vfprintf(stderr, msg, ap);\n fprintf(stderr, \"\\n\");\n}\n\n#define EXAMPLE1_SCHEMA \"example(III)I\"\nstatic void example1_binding(void *userData, void* args[], void *out) {\n printf(\"example1 closure called\\n\");\n int32_t a = *((int32_t *)args[0]);\n int32_t b = *((int32_t *)args[1]);\n int32_t c = *((int32_t *)args[2]);\n int32_t *ret = (int32_t *)out;\n *ret = a + b + c;\n g_count += 1;\n}\n\n#define EXAMPLE2_SCHEMA \"example(I{DDD val1 val2 val3}I)D\"\nstruct example2_arg2 {\n double val1;\n double val2;\n double val3;\n};\nvoid example2_binding(void *userData, void* args[], void *out) {\n printf(\"example2 closure called\\n\");\n int32_t a = *((int32_t *)args[0]);\n struct example2_arg2 b = *((struct example2_arg2 *)args[1]);\n int32_t c = *((int32_t *)args[2]);\n int32_t *ret = (int32_t *)out;\n *ret = a + b.val1 + b.val2 + b.val3 + c;\n g_count += 1;\n}\n\n\n#define EXAMPLE3_SCHEMA \"example(III){III sum max min}\"\nstruct example3_ret {\n int32_t sum;\n int32_t max;\n int32_t min;\n};\n\nstatic void example3_binding(void *userData, void* args[], void *out) {\n printf(\"example closure called\\n\");\n int32_t a = *((int32_t *)args[0]);\n int32_t b = *((int32_t *)args[1]);\n int32_t c = *((int32_t *)args[2]);\n struct example3_ret *result = (struct example3_ret *)calloc(1,sizeof(struct example3_ret));\n result->sum = a + b + c;\n result->min = a <= b ? a : b;\n result->max = a >= b ? a : b;\n result->min = result->min <= c ? result->min : c;\n result->max = result->max >= c ? result->max : c;\n\n struct example3_ret **ret = (struct example3_ret **)out;\n (*ret) = result;\n g_count += 1;\n}\n\nstatic void tests() {\n dyn_closure_type *dynClosure = NULL;\n int rc;\n\n {\n rc = dynClosure_create(EXAMPLE1_SCHEMA, example1_binding, NULL, &dynClosure);\n CHECK_EQUAL(0, rc);\n int32_t (*func)(int32_t a, int32_t b, int32_t c) = NULL;\n int rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func);\n CHECK_EQUAL(0, rc);\n int32_t ret = func(2,3,4);\n printf(\"Return value for example1 is %i\\n\", ret);\n CHECK_EQUAL(1, g_count);\n dynClosure_destroy(dynClosure);\n }\n\n {\n dynClosure = NULL;\n rc = dynClosure_create(EXAMPLE2_SCHEMA, example2_binding, NULL, &dynClosure);\n CHECK_EQUAL(0, rc);\n double (*func)(int32_t a, struct example2_arg2 b, int32_t c) = NULL;\n rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func);\n CHECK_EQUAL(0, rc);\n struct example2_arg2 b;\n b.val1 = 1.0;\n b.val2 = 1.5;\n b.val3 = 2.0;\n double ret = func(2,b,4);\n printf(\"Return value for example2 is %f\\n\", ret);\n CHECK_EQUAL(2, g_count);\n dynClosure_destroy(dynClosure);\n }\n\n {\n dynClosure = NULL;\n rc = dynClosure_create(EXAMPLE3_SCHEMA, example3_binding, NULL, &dynClosure);\n CHECK_EQUAL(0, rc);\n struct example3_ret * (*func)(int32_t a, int32_t b, int32_t c) = NULL;\n rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func);\n CHECK_EQUAL(0, rc);\n struct example3_ret *ret = func(2,8,4);\n printf(\"Return value for example3 is {sum:%i, max:%i, min:%i}\\n\", ret->sum, ret->max, ret->min);\n CHECK_EQUAL(3, g_count);\n dynClosure_destroy(dynClosure);\n free(ret);\n }\n}\n\n}\n\n\nTEST_GROUP(DynClosureTests) {\n void setup() {\n dynFunction_logSetup(stdLog, NULL, 4);\n \/\/TODO dynType_logSetup(stdLog, NULL, 4);\n g_count = 0;\n }\n};\n\nTEST(DynClosureTests, DynCLosureTest1) {\n \/\/TODO split up\n tests();\n}\n<|endoftext|>"} {"text":"\/*\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 \n#include \n#include \n#include \n#include \n\nnamespace thrust\n{\nnamespace detail\n{\n\n\ntemplate\n tagged_allocator\n ::tagged_allocator()\n{}\n\n\ntemplate\n tagged_allocator\n ::tagged_allocator(const tagged_allocator &)\n{}\n\n\ntemplate\n template\n tagged_allocator\n ::tagged_allocator(const tagged_allocator &)\n{}\n\n\ntemplate\n tagged_allocator\n ::~tagged_allocator()\n{}\n\n\ntemplate\n typename tagged_allocator::pointer\n tagged_allocator\n ::address(reference x) const\n{\n return &x;\n}\n\n\ntemplate\n typename tagged_allocator::const_pointer\n tagged_allocator\n ::address(const_reference x) const\n{\n return &x;\n}\n\n\ntemplate\n template\n typename thrust::detail::pointer_traits::raw_pointer\n tagged_allocator\n ::get(OtherPointer ptr)\n{\n return thrust::detail::pointer_traits::get(ptr);\n}\n\n\ntemplate\n typename tagged_allocator::pointer\n tagged_allocator\n ::allocate(size_type cnt)\n{\n using thrust::detail::backend::generic::select_system;\n using thrust::detail::backend::generic::malloc;\n\n \/\/ XXX should use a hypothetical thrust::static_pointer_cast here\n T* result = static_cast(get(malloc(select_system(Tag()), sizeof(value_type) * cnt)));\n\n if(result == 0)\n {\n throw thrust::system::detail::bad_alloc(\"tagged_allocator::allocate: malloc failed\");\n } \/\/ end if\n\n return pointer(result);\n}\n\n\ntemplate\n void tagged_allocator\n ::deallocate(pointer p, size_type n)\n{\n using thrust::detail::backend::generic::select_system;\n\n \/\/ XXX should probably have a using generic::free here\n \/\/ which would be an automatic failure if selected\n free(select_system(Tag()), p);\n}\n\n\ntemplate\n typename tagged_allocator::size_type\n tagged_allocator\n ::max_size() const\n{\n return (std::numeric_limits::max)() \/ sizeof(T);\n}\n\n\ntemplate\n__host__ __device__\nbool operator==(const tagged_allocator &, const tagged_allocator &)\n{\n return true;\n}\n\n\ntemplate\n__host__ __device__\nbool operator!=(const tagged_allocator &, const tagged_allocator &)\n{\n return false;\n}\n \n\n} \/\/ end detail\n} \/\/ end thrust\n\nAdd a using thrust::detail::backend::generic::free to tagged_allocator::deallocate\/*\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 \n#include \n#include \n#include \n#include \n#include \n\nnamespace thrust\n{\nnamespace detail\n{\n\n\ntemplate\n tagged_allocator\n ::tagged_allocator()\n{}\n\n\ntemplate\n tagged_allocator\n ::tagged_allocator(const tagged_allocator &)\n{}\n\n\ntemplate\n template\n tagged_allocator\n ::tagged_allocator(const tagged_allocator &)\n{}\n\n\ntemplate\n tagged_allocator\n ::~tagged_allocator()\n{}\n\n\ntemplate\n typename tagged_allocator::pointer\n tagged_allocator\n ::address(reference x) const\n{\n return &x;\n}\n\n\ntemplate\n typename tagged_allocator::const_pointer\n tagged_allocator\n ::address(const_reference x) const\n{\n return &x;\n}\n\n\ntemplate\n template\n typename thrust::detail::pointer_traits::raw_pointer\n tagged_allocator\n ::get(OtherPointer ptr)\n{\n return thrust::detail::pointer_traits::get(ptr);\n}\n\n\ntemplate\n typename tagged_allocator::pointer\n tagged_allocator\n ::allocate(size_type cnt)\n{\n using thrust::detail::backend::generic::select_system;\n using thrust::detail::backend::generic::malloc;\n\n \/\/ XXX should use a hypothetical thrust::static_pointer_cast here\n T* result = static_cast(get(malloc(select_system(Tag()), sizeof(value_type) * cnt)));\n\n if(result == 0)\n {\n throw thrust::system::detail::bad_alloc(\"tagged_allocator::allocate: malloc failed\");\n } \/\/ end if\n\n return pointer(result);\n}\n\n\ntemplate\n void tagged_allocator\n ::deallocate(pointer p, size_type n)\n{\n using thrust::detail::backend::generic::select_system;\n using thrust::detail::backend::generic::free;\n\n free(select_system(Tag()), p);\n}\n\n\ntemplate\n typename tagged_allocator::size_type\n tagged_allocator\n ::max_size() const\n{\n return (std::numeric_limits::max)() \/ sizeof(T);\n}\n\n\ntemplate\n__host__ __device__\nbool operator==(const tagged_allocator &, const tagged_allocator &)\n{\n return true;\n}\n\n\ntemplate\n__host__ __device__\nbool operator!=(const tagged_allocator &, const tagged_allocator &)\n{\n return false;\n}\n \n\n} \/\/ end detail\n} \/\/ end thrust\n\n<|endoftext|>"} {"text":"#ifndef __FUTURE_HPP__\n#define __FUTURE_HPP__\n\n#include \"SoftXMT.hpp\"\n#include \"Delegate.hpp\"\n#include \"Cache.hpp\"\n\n\/\/TODO: special ArgsCache acquire, which\n\/\/uses args pointer field as a global address\n\/\/to the future and either\n\/\/1. flip the started bit\n\/\/2. or simply acquire RW instead of RO (and Cached not Incoherent)\n\n\/\/ idea: if we had a need for futures that\n\/\/ only mutate their arguments (essentially functional but could change the inputs as well)\n\/\/ then we could allow multiple copies of\n\/\/ the future to execute RW-shared mode, where only the first release writeback wins\n\n\n\/\/ TODO: do something like this to force users to have\n\/\/ the future fields but make them invisible\n\/*\nclass FutureArgs {\n private:\n GlobalAddress futurePtr;\n void (* user_fn_p)(A *);\n};\nclass MyArgs : public FutureArgs {\n int i;\n int j;\n}\n\/\/ Additional possibility is method #2 above\n *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#if DEBUG\nstatic int64_t count_ = 0;\n#endif\n\ntemplate < typename ArgsStruct >\nclass Future {\n private:\n int64_t started;\n Thread * waiter;\n bool done;\n ArgsStruct * userArgs_lp;\n \n struct future_args {\n GlobalAddress futureAddr;\n void (* user_fn_p)(ArgsStruct *);\n GlobalAddress< ArgsStruct > userArgs;\n\n future_args( Future< ArgsStruct > * future, ArgsStruct * userArgs, void (* fn_p)(ArgsStruct *) )\n : futureAddr( make_global( future ) )\n , userArgs( make_global( userArgs ) )\n , user_fn_p( fn_p ) \n { }\n };\n \n future_args task_args;\n\n struct future_done_args { \n Future< ArgsStruct > * futurePtr;\n };\n \n static void future_done_am( future_done_args * args, size_t args_size, void * payload, size_t payload_size ) {\n args->futurePtr->done = true;\n if ( args->futurePtr->waiter != NULL ) {\n SoftXMT_wake( args->futurePtr->waiter );\n args->futurePtr->waiter = NULL;\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/Custom delegate operation\n \/\/TODO: use a generalized mechanism that abstracts all but function\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n struct started_memory_descriptor {\n Thread * t;\n GlobalAddress< Future > address;\n int64_t data;\n bool done;\n };\n\n struct started_reply_args {\n GlobalAddress descriptor;\n };\n\n static void started_reply_am( started_reply_args * args, size_t size, void * payload, size_t payload_size ) {\n assert( payload_size == sizeof(int64_t ) );\n args->descriptor.pointer()->data = *(static_cast(payload));\n args->descriptor.pointer()->done = true;\n SoftXMT_wake( args->descriptor.pointer()->t );\n }\n \n struct started_request_args {\n GlobalAddress descriptor;\n GlobalAddress< Future > address;\n };\n\n static void started_request_am( started_request_args * args, size_t size, void * payload, size_t payload_size ) {\n Future< ArgsStruct > * fptr = args->address.pointer();\n \n DVLOG(5) << \"Future(IN_AM) FID \"<< fptr->getId();\n\n CHECK((int64_t)fptr>0x1000) << \"dequeued request (descriptor gaddress:\" << args->descriptor\n << \"): future ptr:\" << (void*)fptr\n << \"(future gaddress:\"<address;\n int64_t data = fptr->started;\n fptr->started = data + 1;\n \n \/\/ If future was already started in this case, it must have been started by touching thread.\n \/\/ Incrementing started again will tell the touching thread it can deallocate the Future\n if ( data > 0 ) {\n DVLOG(5) << \"already started:(id:\"<getId();\n if ( fptr->done ) { \/\/if it is done then toucher is waiting for the dequeue\n DVLOG(5) << \"need to wake:(id:\"<getId();\n CHECK ( fptr->waiter!=NULL ) << \"future ptr:\" << (void*)fptr <<\"\\n done=\"<done<<\" (id:\"<getId()<<\") data=\"<descriptor.node();\n SoftXMT_wake( fptr->waiter );\n fptr->waiter = NULL;\n } else {\n DVLOG(5) << \"not need to wake:(id:\"<getId();\n }\n } else {\n DVLOG(5) << \"not already started:(id:\"<getId();\n }\n \n started_reply_args reply_args;\n reply_args.descriptor = args->descriptor;\n SoftXMT_call_on( args->descriptor.node(), &started_reply_am, \n &reply_args, sizeof(reply_args),\n &data, sizeof(data) );\n }\n\n static int64_t future_delegate_started( GlobalAddress< Future > address ) {\n started_memory_descriptor md;\n md.address = address;\n md.data = 0;\n md.done = false;\n md.t = CURRENT_THREAD;\n started_request_args args;\n args.descriptor = make_global(&md);\n args.address = address;\n SoftXMT_call_on( address.node(), &started_request_am, &args );\n while( !md.done ) {\n SoftXMT_suspend();\n }\n return md.data;\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static void future_function( future_args * args ) {\n DVLOG(4) << \"Future(other) \"<< args->futureAddr;\n \/\/ TODO #1: the make_global is just calculating location of Future->started\n \/\/if ( SoftXMT_delegate_fetch_and_add_word( make_global( args->startedAddr, args->futureAddr.node() ), 1 ) == 0 ) { \n DVLOG(5) << CURRENT_THREAD->id << \"args(\"<<(void*)args<<\") will call started am \" << args->futureAddr.pointer();\n if ( future_delegate_started( args->futureAddr ) == 0 ) { \n DVLOG(5) << CURRENT_THREAD->id << \"user_args=\"<userArgs<<\" for ftraddr=\"<< args->futureAddr.pointer();\n \/\/ grab the user arguments\n size_t args_size = sizeof(ArgsStruct);\n ArgsStruct argsbuf;\n typename Incoherent::RO cached_args( args->userArgs, args_size, &argsbuf );\n cached_args.block_until_acquired();\n \n \/\/ call the user task\n args->user_fn_p( &argsbuf );\n cached_args.block_until_released();\n\n \/\/ call wake up AM on Node that has the Future\n future_done_args done_args = { args->futureAddr.pointer() };\n SoftXMT_call_on( args->futureAddr.node(), &future_done_am, &done_args );\n } \n }\n\n int64_t getId() {\n#if DEBUG\n return id;\n#else \n return -1;\n#endif \n }\n \n public:\n#if DEBUG\n int64_t id;\n#endif\n\n\n \/\/ TODO: NOTE that this does not copy user arguments because we want to \n \/\/ preserve the same semantics as normal tasks.\n \/\/ --Unfortunately this means there are three communications to start\n \/\/ 1) Task.execute fetches args\n \/\/ 2) Future atomic started\n \/\/ 3) Bring in user arguments and start\n Future ( void (* fn_p)(ArgsStruct *), ArgsStruct * userArgs )\n : started( 0 )\n , waiter( NULL )\n , done( false )\n , userArgs_lp( userArgs )\n#if DEBUG\n , id( SoftXMT_mynode() + ((count_++)*SoftXMT_nodes() ) )\n#endif\n , task_args( this, userArgs, fn_p ) { \n \n DVLOG(5) << CURRENT_THREAD->id << \" creates Future:\"<< (void*)this << \" id:\"<< getId() << \" args:\"<< &task_args;\n }\n\n void touch( ) {\n DVLOG(4) << \"Future(touch) FID \"<< this->getId() << \" ga:\"<id << \" gets to touch-go \" << getId();\n task_args.user_fn_p( userArgs_lp );\n CHECK( started <= 2 ) << \"started=\" << started << \" (at most one additional increment should occur)\";\n done = true;\n while ( started < 2 ) { \/\/ wait until dequeued\n DVLOG(5) << CURRENT_THREAD->id << \" has to wait on dequeue \" << getId();\n waiter = CURRENT_THREAD;\n SoftXMT_suspend( );\n DVLOG(5) << CURRENT_THREAD->id << \" has woke on dequeue \" << getId();\n }\n } else {\n \/\/ otherwise block on done event\n while ( !done ) {\n waiter = CURRENT_THREAD;\n SoftXMT_suspend( );\n }\n }\n }\n\n void addAsPublicTask( ) {\n DVLOG(4) << \"Future(spawn) \" << this->getId() << \" ga:\"<FIXED: future was fetching count:args_size, instead of count=1 userArgs#ifndef __FUTURE_HPP__\n#define __FUTURE_HPP__\n\n#include \"SoftXMT.hpp\"\n#include \"Delegate.hpp\"\n#include \"Cache.hpp\"\n\n\/\/TODO: special ArgsCache acquire, which\n\/\/uses args pointer field as a global address\n\/\/to the future and either\n\/\/1. flip the started bit\n\/\/2. or simply acquire RW instead of RO (and Cached not Incoherent)\n\n\/\/ idea: if we had a need for futures that\n\/\/ only mutate their arguments (essentially functional but could change the inputs as well)\n\/\/ then we could allow multiple copies of\n\/\/ the future to execute RW-shared mode, where only the first release writeback wins\n\n\n\/\/ TODO: do something like this to force users to have\n\/\/ the future fields but make them invisible\n\/*\nclass FutureArgs {\n private:\n GlobalAddress futurePtr;\n void (* user_fn_p)(A *);\n};\nclass MyArgs : public FutureArgs {\n int i;\n int j;\n}\n\/\/ Additional possibility is method #2 above\n *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#if DEBUG\nstatic int64_t count_ = 0;\n#endif\n\ntemplate < typename ArgsStruct >\nclass Future {\n private:\n int64_t started;\n Thread * waiter;\n bool done;\n ArgsStruct * userArgs_lp;\n \n struct future_args {\n GlobalAddress futureAddr;\n void (* user_fn_p)(ArgsStruct *);\n GlobalAddress< ArgsStruct > userArgs;\n\n future_args( Future< ArgsStruct > * future, ArgsStruct * userArgs, void (* fn_p)(ArgsStruct *) )\n : futureAddr( make_global( future ) )\n , userArgs( make_global( userArgs ) )\n , user_fn_p( fn_p ) \n { }\n };\n \n future_args task_args;\n\n struct future_done_args { \n Future< ArgsStruct > * futurePtr;\n };\n \n static void future_done_am( future_done_args * args, size_t args_size, void * payload, size_t payload_size ) {\n args->futurePtr->done = true;\n if ( args->futurePtr->waiter != NULL ) {\n SoftXMT_wake( args->futurePtr->waiter );\n args->futurePtr->waiter = NULL;\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/Custom delegate operation\n \/\/TODO: use a generalized mechanism that abstracts all but function\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n struct started_memory_descriptor {\n Thread * t;\n GlobalAddress< Future > address;\n int64_t data;\n bool done;\n };\n\n struct started_reply_args {\n GlobalAddress descriptor;\n };\n\n static void started_reply_am( started_reply_args * args, size_t size, void * payload, size_t payload_size ) {\n assert( payload_size == sizeof(int64_t ) );\n args->descriptor.pointer()->data = *(static_cast(payload));\n args->descriptor.pointer()->done = true;\n SoftXMT_wake( args->descriptor.pointer()->t );\n }\n \n struct started_request_args {\n GlobalAddress descriptor;\n GlobalAddress< Future > address;\n };\n\n static void started_request_am( started_request_args * args, size_t size, void * payload, size_t payload_size ) {\n Future< ArgsStruct > * fptr = args->address.pointer();\n \n DVLOG(5) << \"Future(IN_AM) FID \"<< fptr->getId();\n\n CHECK((int64_t)fptr>0x1000) << \"dequeued request (descriptor gaddress:\" << args->descriptor\n << \"): future ptr:\" << (void*)fptr\n << \"(future gaddress:\"<address;\n int64_t data = fptr->started;\n fptr->started = data + 1;\n \n \/\/ If future was already started in this case, it must have been started by touching thread.\n \/\/ Incrementing started again will tell the touching thread it can deallocate the Future\n if ( data > 0 ) {\n DVLOG(5) << \"already started:(id:\"<getId();\n if ( fptr->done ) { \/\/if it is done then toucher is waiting for the dequeue\n DVLOG(5) << \"need to wake:(id:\"<getId();\n CHECK ( fptr->waiter!=NULL ) << \"future ptr:\" << (void*)fptr <<\"\\n done=\"<done<<\" (id:\"<getId()<<\") data=\"<descriptor.node();\n SoftXMT_wake( fptr->waiter );\n fptr->waiter = NULL;\n } else {\n DVLOG(5) << \"not need to wake:(id:\"<getId();\n }\n } else {\n DVLOG(5) << \"not already started:(id:\"<getId();\n }\n \n started_reply_args reply_args;\n reply_args.descriptor = args->descriptor;\n SoftXMT_call_on( args->descriptor.node(), &started_reply_am, \n &reply_args, sizeof(reply_args),\n &data, sizeof(data) );\n }\n\n static int64_t future_delegate_started( GlobalAddress< Future > address ) {\n started_memory_descriptor md;\n md.address = address;\n md.data = 0;\n md.done = false;\n md.t = CURRENT_THREAD;\n started_request_args args;\n args.descriptor = make_global(&md);\n args.address = address;\n SoftXMT_call_on( address.node(), &started_request_am, &args );\n while( !md.done ) {\n SoftXMT_suspend();\n }\n return md.data;\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static void future_function( future_args * args ) {\n DVLOG(4) << \"Future(other) \"<< args->futureAddr;\n \/\/ TODO #1: the make_global is just calculating location of Future->started\n \/\/if ( SoftXMT_delegate_fetch_and_add_word( make_global( args->startedAddr, args->futureAddr.node() ), 1 ) == 0 ) { \n DVLOG(5) << CURRENT_THREAD->id << \"args(\"<<(void*)args<<\") will call started am \" << args->futureAddr.pointer();\n if ( future_delegate_started( args->futureAddr ) == 0 ) { \n DVLOG(5) << CURRENT_THREAD->id << \"user_args=\"<userArgs<<\" for ftraddr=\"<< args->futureAddr.pointer();\n \/\/ grab the user arguments\n size_t args_size = sizeof(ArgsStruct);\n ArgsStruct argsbuf;\n typename Incoherent::RO cached_args( args->userArgs, 1, &argsbuf );\n cached_args.block_until_acquired();\n \n \/\/ call the user task\n args->user_fn_p( &argsbuf );\n cached_args.block_until_released();\n\n \/\/ call wake up AM on Node that has the Future\n future_done_args done_args = { args->futureAddr.pointer() };\n SoftXMT_call_on( args->futureAddr.node(), &future_done_am, &done_args );\n } \n }\n\n int64_t getId() {\n#if DEBUG\n return id;\n#else \n return -1;\n#endif \n }\n \n public:\n#if DEBUG\n int64_t id;\n#endif\n\n\n \/\/ TODO: NOTE that this does not copy user arguments because we want to \n \/\/ preserve the same semantics as normal tasks.\n \/\/ --Unfortunately this means there are three communications to start\n \/\/ 1) Task.execute fetches args\n \/\/ 2) Future atomic started\n \/\/ 3) Bring in user arguments and start\n Future ( void (* fn_p)(ArgsStruct *), ArgsStruct * userArgs )\n : started( 0 )\n , waiter( NULL )\n , done( false )\n , userArgs_lp( userArgs )\n#if DEBUG\n , id( SoftXMT_mynode() + ((count_++)*SoftXMT_nodes() ) )\n#endif\n , task_args( this, userArgs, fn_p ) { \n \n DVLOG(5) << CURRENT_THREAD->id << \" creates Future:\"<< (void*)this << \" id:\"<< getId() << \" args:\"<< &task_args;\n }\n\n void touch( ) {\n DVLOG(4) << \"Future(touch) FID \"<< this->getId() << \" ga:\"<id << \" gets to touch-go \" << getId();\n task_args.user_fn_p( userArgs_lp );\n CHECK( started <= 2 ) << \"started=\" << started << \" (at most one additional increment should occur)\";\n done = true;\n while ( started < 2 ) { \/\/ wait until dequeued\n DVLOG(5) << CURRENT_THREAD->id << \" has to wait on dequeue \" << getId();\n waiter = CURRENT_THREAD;\n SoftXMT_suspend( );\n DVLOG(5) << CURRENT_THREAD->id << \" has woke on dequeue \" << getId();\n }\n } else {\n \/\/ otherwise block on done event\n while ( !done ) {\n waiter = CURRENT_THREAD;\n SoftXMT_suspend( );\n }\n }\n }\n\n void addAsPublicTask( ) {\n DVLOG(4) << \"Future(spawn) \" << this->getId() << \" ga:\"<"} {"text":"#include \"pch.h\"\r\n#include \"aiMeshOps.h\"\r\n\r\n\r\nnamespace impl\r\n{\r\n template\r\n inline void BuildConnection(\r\n MeshConnectionInfo& connection, const Indices& indices, const Counts& counts, const IArray& vertices)\r\n {\r\n size_t num_points = vertices.size();\r\n size_t num_faces = counts.size();\r\n size_t num_indices = indices.size();\r\n\r\n connection.v2f_offsets.resize_discard(num_points);\r\n connection.v2f_faces.resize_discard(num_indices);\r\n connection.v2f_indices.resize_discard(num_indices);\r\n\r\n connection.v2f_counts.resize_zeroclear(num_points);\r\n {\r\n int ii = 0;\r\n for (size_t fi = 0; fi < num_faces; ++fi) {\r\n int c = counts[fi];\r\n for (int ci = 0; ci < c; ++ci) {\r\n connection.v2f_counts[indices[ii + ci]]++;\r\n }\r\n ii += c;\r\n }\r\n\r\n int offset = 0;\r\n for (size_t i = 0; i < num_points; ++i) {\r\n connection.v2f_offsets[i] = offset;\r\n offset += connection.v2f_counts[i];\r\n }\r\n }\r\n\r\n connection.v2f_counts.zeroclear();\r\n {\r\n int i = 0;\r\n for (int fi = 0; fi < (int)num_faces; ++fi) {\r\n int c = counts[fi];\r\n for (int ci = 0; ci < c; ++ci) {\r\n int vi = indices[i + ci];\r\n int ti = connection.v2f_offsets[vi] + connection.v2f_counts[vi]++;\r\n connection.v2f_faces[ti] = fi;\r\n connection.v2f_indices[ti] = i + ci;\r\n }\r\n i += c;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid MeshConnectionInfo::clear()\r\n{\r\n v2f_counts.clear();\r\n v2f_offsets.clear();\r\n v2f_faces.clear();\r\n v2f_indices.clear();\r\n\r\n weld_map.clear();\r\n weld_counts.clear();\r\n weld_offsets.clear();\r\n weld_indices.clear();\r\n}\r\n\r\nvoid MeshConnectionInfo::buildConnection(\r\n const IArray& indices, const IArray& counts, const IArray& vertices)\r\n{\r\n size_t num_points = vertices.size();\r\n size_t num_faces = counts.size();\r\n size_t num_indices = indices.size();\r\n\r\n v2f_offsets.resize_discard(num_points);\r\n v2f_faces.resize_discard(num_indices);\r\n v2f_indices.resize_discard(num_indices);\r\n\r\n v2f_counts.resize_zeroclear(num_points);\r\n {\r\n int ii = 0;\r\n for (size_t fi = 0; fi < num_faces; ++fi) {\r\n int c = counts[fi];\r\n for (int ci = 0; ci < c; ++ci) {\r\n v2f_counts[indices[ii + ci]]++;\r\n }\r\n ii += c;\r\n }\r\n\r\n int offset = 0;\r\n for (size_t i = 0; i < num_points; ++i) {\r\n v2f_offsets[i] = offset;\r\n offset += v2f_counts[i];\r\n }\r\n }\r\n\r\n v2f_counts.zeroclear();\r\n {\r\n int i = 0;\r\n for (int fi = 0; fi < (int)num_faces; ++fi) {\r\n int c = counts[fi];\r\n for (int ci = 0; ci < c; ++ci) {\r\n int vi = indices[i + ci];\r\n int ti = v2f_offsets[vi] + v2f_counts[vi]++;\r\n v2f_faces[ti] = fi;\r\n v2f_indices[ti] = i + ci;\r\n }\r\n i += c;\r\n }\r\n }\r\n}\r\n\r\n\r\nstatic inline int next_power_of_two(uint32_t v)\r\n{\r\n v--;\r\n v |= v >> 1;\r\n v |= v >> 2;\r\n v |= v >> 4;\r\n v |= v >> 8;\r\n v |= v >> 16;\r\n v++;\r\n return v + (v == 0);\r\n}\r\n\r\nvoid MeshWelder::prepare(abcV3 * points, int count)\r\n{\r\n m_points = points;\r\n m_count = count;\r\n\r\n m_hash_size = next_power_of_two(m_count);\r\n m_hash_table.resize_discard(m_hash_size + m_count);\r\n memset(m_hash_table.data(), NIL, m_hash_size * sizeof(int));\r\n\r\n m_remap.resize_discard(m_count);\r\n}\r\n\r\nconst RawVector& MeshWelder::getRemapTable() const\r\n{\r\n return m_remap;\r\n}\r\n\r\n\r\n\r\nvoid MeshRefiner::triangulate(bool swap_faces, bool turn_quads)\r\n{\r\n auto& dst = new_indices_triangulated;\r\n dst.resize(num_new_indices);\r\n\r\n const int i1 = swap_faces ? 2 : 1;\r\n const int i2 = swap_faces ? 1 : 2;\r\n size_t num_faces = counts.size();\r\n\r\n int n = 0;\r\n int i = 0;\r\n if (turn_quads) {\r\n for (size_t fi = 0; fi < num_faces; ++fi) {\r\n int count = counts[fi];\r\n if (count == 4) {\r\n int quad[4] = {\r\n new_indices[n + 3],\r\n new_indices[n + 0],\r\n new_indices[n + 1],\r\n new_indices[n + 2],\r\n };\r\n for (int ni = 0; ni < count - 2; ++ni) {\r\n dst[i + 0] = quad[0];\r\n dst[i + 1] = quad[ni + i1];\r\n dst[i + 2] = quad[ni + i2];\r\n i += 3;\r\n }\r\n n += count;\r\n }\r\n else {\r\n for (int ni = 0; ni < count - 2; ++ni) {\r\n dst[i + 0] = new_indices[n + 0];\r\n dst[i + 1] = new_indices[n + ni + i1];\r\n dst[i + 2] = new_indices[n + ni + i2];\r\n i += 3;\r\n }\r\n n += count;\r\n }\r\n }\r\n }\r\n else {\r\n for (size_t fi = 0; fi < num_faces; ++fi) {\r\n int count = counts[fi];\r\n for (int ni = 0; ni < count - 2; ++ni) {\r\n dst[i + 0] = new_indices[n + 0];\r\n dst[i + 1] = new_indices[n + ni + i1];\r\n dst[i + 2] = new_indices[n + ni + i2];\r\n i += 3;\r\n }\r\n n += count;\r\n }\r\n }\r\n}\r\n\r\nvoid MeshRefiner::genSubmeshes(IArray material_ids)\r\n{\r\n submeshes.clear();\r\n\r\n new_indices_submeshes.resize(new_indices_triangulated.size());\r\n const int *indices_read = new_indices_triangulated.data();\r\n int *indices_write = new_indices_submeshes.data();\r\n\r\n int num_splits = (int)splits.size();\r\n int offset_faces = 0;\r\n RawVector tmp_submeshes;\r\n\r\n for (int spi = 0; spi < num_splits; ++spi) {\r\n auto& split = splits[spi];\r\n int offset_vertices = split.vertex_offset;\r\n\r\n \/\/ count triangle indices\r\n for (int fi = 0; fi < split.face_count; ++fi) {\r\n int mid = material_ids[offset_faces + fi] + 1; \/\/ -1 == no material. adjust to zero based\r\n while (mid >= (int)tmp_submeshes.size()) {\r\n int id = (int)tmp_submeshes.size();\r\n tmp_submeshes.push_back({});\r\n tmp_submeshes.back().material_id = id - 1;\r\n }\r\n tmp_submeshes[mid].index_count += (counts[fi] - 2) * 3;\r\n }\r\n\r\n for (int mi = 0; mi < (int)tmp_submeshes.size(); ++mi) {\r\n auto& sm = tmp_submeshes[mi];\r\n sm.indices_write = indices_write;\r\n sm.index_offset = (int)std::distance(new_indices_submeshes.data(), indices_write);\r\n indices_write += sm.index_count;\r\n }\r\n\r\n \/\/ copy indices\r\n for (int fi = 0; fi < split.face_count; ++fi) {\r\n int mid = material_ids[offset_faces + fi] + 1;\r\n int count = counts[offset_faces + fi];\r\n int nidx = (count - 2) * 3;\r\n for (int i = 0; i < nidx; ++i) {\r\n *(tmp_submeshes[mid].indices_write++) = *(indices_read++) - offset_vertices;\r\n }\r\n }\r\n\r\n for (int mi = 0; mi < (int)tmp_submeshes.size(); ++mi) {\r\n auto& sm = tmp_submeshes[mi];\r\n if (sm.index_count > 0) {\r\n ++split.submesh_count;\r\n submeshes.push_back(sm);\r\n }\r\n }\r\n\r\n offset_faces += split.face_count;\r\n tmp_submeshes.clear();\r\n }\r\n setupSubmeshes();\r\n}\r\n\r\nvoid MeshRefiner::genSubmeshes()\r\n{\r\n submeshes.clear();\r\n\r\n new_indices_submeshes.resize(new_indices_triangulated.size());\r\n const int *indices_read = new_indices_triangulated.data();\r\n int *indices_write = new_indices_submeshes.data();\r\n\r\n int num_splits = (int)splits.size();\r\n for (int spi = 0; spi < num_splits; ++spi) {\r\n auto& split = splits[spi];\r\n int offset_vertices = split.vertex_offset;\r\n\r\n Submesh sm;\r\n sm.index_count = split.triangulated_index_count;\r\n sm.index_offset = (int)std::distance(new_indices_submeshes.data(), indices_write);\r\n for (int ii = 0; ii < sm.index_count; ++ii) {\r\n *(indices_write++) = *(indices_read++) - offset_vertices;\r\n }\r\n\r\n ++split.submesh_count;\r\n submeshes.push_back(sm);\r\n }\r\n setupSubmeshes();\r\n}\r\n\r\nvoid MeshRefiner::setupSubmeshes()\r\n{\r\n int num_splits = (int)splits.size();\r\n int total_submeshes = 0;\r\n for (int spi = 0; spi < num_splits; ++spi) {\r\n auto& split = splits[spi];\r\n split.submesh_offset = total_submeshes;\r\n total_submeshes += split.submesh_count;\r\n for (int smi = 0; smi < split.submesh_count; ++smi) {\r\n auto& sm = submeshes[smi + split.submesh_offset];\r\n sm.split_index = spi;\r\n sm.submesh_index = smi;\r\n }\r\n }\r\n}\r\n\r\n\r\nvoid MeshRefiner::clear()\r\n{\r\n split_unit = 0;\r\n counts.reset();\r\n indices.reset();\r\n points.reset();\r\n for (auto& attr : attributes) {\r\n attr->clear();\r\n \/\/ attributes are placement new-ed, so need to call destructor manually\r\n attr->~IAttribute();\r\n }\r\n attributes.clear();\r\n\r\n old2new_indices.clear();\r\n new2old_points.clear();\r\n\r\n new_indices.clear();\r\n new_indices_triangulated.clear();\r\n new_indices_submeshes.clear();\r\n\r\n new_points.clear();\r\n splits.clear();\r\n submeshes.clear();\r\n num_new_indices = 0;\r\n}\r\n\r\nvoid MeshRefiner::refine()\r\n{\r\n if (connection.v2f_counts.size() != points.size()) {\r\n connection.buildConnection(indices, counts, points);\r\n }\r\n\r\n int num_indices = (int)indices.size();\r\n new_points.reserve(num_indices);\r\n new_indices.reserve(num_indices);\r\n for (auto& attr : attributes) { attr->prepare((int)points.size(), (int)indices.size()); }\r\n\r\n old2new_indices.resize(num_indices, -1);\r\n\r\n int num_faces_total = (int)counts.size();\r\n int offset_faces = 0;\r\n int offset_indices = 0;\r\n int offset_vertices = 0;\r\n int num_faces = 0;\r\n int num_indices_triangulated = 0;\r\n\r\n auto add_new_split = [&]() {\r\n auto split = Split{};\r\n split.face_offset = offset_faces;\r\n split.index_offset = offset_indices;\r\n split.vertex_offset = offset_vertices;\r\n split.face_count = num_faces;\r\n split.triangulated_index_count = num_indices_triangulated;\r\n split.vertex_count = (int)new_points.size() - offset_vertices;\r\n split.index_count = (int)new_indices.size() - offset_indices;\r\n splits.push_back(split);\r\n\r\n offset_faces += split.face_count;\r\n offset_indices += split.index_count;\r\n offset_vertices += split.vertex_count;\r\n\r\n num_new_indices += num_indices_triangulated;\r\n num_faces = 0;\r\n num_indices_triangulated = 0;\r\n };\r\n\r\n auto compare_all_attributes = [&](int ni, int ii) -> bool {\r\n for (auto& attr : attributes)\r\n if (!attr->compare(ni, ii)) { return false; }\r\n return true;\r\n };\r\n\r\n auto find_or_emit_vertex = [&](int vi, int ii) -> int {\r\n int offset = connection.v2f_offsets[vi];\r\n int connection_count = connection.v2f_counts[vi];\r\n for (int ci = 0; ci < connection_count; ++ci) {\r\n int& ni = old2new_indices[connection.v2f_indices[offset + ci]];\r\n if (ni != -1 && compare_all_attributes(ni, ii)) {\r\n return ni;\r\n }\r\n else if (ni == -1) {\r\n ni = (int)new_points.size();\r\n new_points.push_back(points[vi]);\r\n new2old_points.push_back(vi);\r\n for (auto& attr : attributes) { attr->emit(ii); }\r\n return ni;\r\n }\r\n }\r\n return 0;\r\n };\r\n\r\n int offset = 0;\r\n for (int fi = 0; fi < num_faces_total; ++fi) {\r\n int count = counts[fi];\r\n\r\n if (split_unit > 0 && (int)new_points.size() - offset_vertices + count > split_unit) {\r\n add_new_split();\r\n\r\n \/\/ clear vertex cache\r\n memset(old2new_indices.data(), -1, old2new_indices.size() * sizeof(int));\r\n }\r\n\r\n for (int ci = 0; ci < count; ++ci) {\r\n int ii = offset + ci;\r\n int vi = indices[ii];\r\n new_indices.push_back(find_or_emit_vertex(vi, ii));\r\n }\r\n ++num_faces;\r\n num_indices_triangulated += (count - 2) * 3;\r\n offset += count;\r\n }\r\n add_new_split();\r\n}\r\n\r\nfix a bug in MeshRefiner #58#include \"pch.h\"\r\n#include \"aiMeshOps.h\"\r\n\r\n\r\nnamespace impl\r\n{\r\n template\r\n inline void BuildConnection(\r\n MeshConnectionInfo& connection, const Indices& indices, const Counts& counts, const IArray& vertices)\r\n {\r\n size_t num_points = vertices.size();\r\n size_t num_faces = counts.size();\r\n size_t num_indices = indices.size();\r\n\r\n connection.v2f_offsets.resize_discard(num_points);\r\n connection.v2f_faces.resize_discard(num_indices);\r\n connection.v2f_indices.resize_discard(num_indices);\r\n\r\n connection.v2f_counts.resize_zeroclear(num_points);\r\n {\r\n int ii = 0;\r\n for (size_t fi = 0; fi < num_faces; ++fi) {\r\n int c = counts[fi];\r\n for (int ci = 0; ci < c; ++ci) {\r\n connection.v2f_counts[indices[ii + ci]]++;\r\n }\r\n ii += c;\r\n }\r\n\r\n int offset = 0;\r\n for (size_t i = 0; i < num_points; ++i) {\r\n connection.v2f_offsets[i] = offset;\r\n offset += connection.v2f_counts[i];\r\n }\r\n }\r\n\r\n connection.v2f_counts.zeroclear();\r\n {\r\n int i = 0;\r\n for (int fi = 0; fi < (int)num_faces; ++fi) {\r\n int c = counts[fi];\r\n for (int ci = 0; ci < c; ++ci) {\r\n int vi = indices[i + ci];\r\n int ti = connection.v2f_offsets[vi] + connection.v2f_counts[vi]++;\r\n connection.v2f_faces[ti] = fi;\r\n connection.v2f_indices[ti] = i + ci;\r\n }\r\n i += c;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid MeshConnectionInfo::clear()\r\n{\r\n v2f_counts.clear();\r\n v2f_offsets.clear();\r\n v2f_faces.clear();\r\n v2f_indices.clear();\r\n\r\n weld_map.clear();\r\n weld_counts.clear();\r\n weld_offsets.clear();\r\n weld_indices.clear();\r\n}\r\n\r\nvoid MeshConnectionInfo::buildConnection(\r\n const IArray& indices, const IArray& counts, const IArray& vertices)\r\n{\r\n size_t num_points = vertices.size();\r\n size_t num_faces = counts.size();\r\n size_t num_indices = indices.size();\r\n\r\n v2f_offsets.resize_discard(num_points);\r\n v2f_faces.resize_discard(num_indices);\r\n v2f_indices.resize_discard(num_indices);\r\n\r\n v2f_counts.resize_zeroclear(num_points);\r\n {\r\n int ii = 0;\r\n for (size_t fi = 0; fi < num_faces; ++fi) {\r\n int c = counts[fi];\r\n for (int ci = 0; ci < c; ++ci) {\r\n v2f_counts[indices[ii + ci]]++;\r\n }\r\n ii += c;\r\n }\r\n\r\n int offset = 0;\r\n for (size_t i = 0; i < num_points; ++i) {\r\n v2f_offsets[i] = offset;\r\n offset += v2f_counts[i];\r\n }\r\n }\r\n\r\n v2f_counts.zeroclear();\r\n {\r\n int i = 0;\r\n for (int fi = 0; fi < (int)num_faces; ++fi) {\r\n int c = counts[fi];\r\n for (int ci = 0; ci < c; ++ci) {\r\n int vi = indices[i + ci];\r\n int ti = v2f_offsets[vi] + v2f_counts[vi]++;\r\n v2f_faces[ti] = fi;\r\n v2f_indices[ti] = i + ci;\r\n }\r\n i += c;\r\n }\r\n }\r\n}\r\n\r\n\r\nstatic inline int next_power_of_two(uint32_t v)\r\n{\r\n v--;\r\n v |= v >> 1;\r\n v |= v >> 2;\r\n v |= v >> 4;\r\n v |= v >> 8;\r\n v |= v >> 16;\r\n v++;\r\n return v + (v == 0);\r\n}\r\n\r\nvoid MeshWelder::prepare(abcV3 * points, int count)\r\n{\r\n m_points = points;\r\n m_count = count;\r\n\r\n m_hash_size = next_power_of_two(m_count);\r\n m_hash_table.resize_discard(m_hash_size + m_count);\r\n memset(m_hash_table.data(), NIL, m_hash_size * sizeof(int));\r\n\r\n m_remap.resize_discard(m_count);\r\n}\r\n\r\nconst RawVector& MeshWelder::getRemapTable() const\r\n{\r\n return m_remap;\r\n}\r\n\r\n\r\n\r\nvoid MeshRefiner::triangulate(bool swap_faces, bool turn_quads)\r\n{\r\n auto& dst = new_indices_triangulated;\r\n dst.resize(num_new_indices);\r\n\r\n const int i1 = swap_faces ? 2 : 1;\r\n const int i2 = swap_faces ? 1 : 2;\r\n size_t num_faces = counts.size();\r\n\r\n int n = 0;\r\n int i = 0;\r\n if (turn_quads) {\r\n for (size_t fi = 0; fi < num_faces; ++fi) {\r\n int count = counts[fi];\r\n if (count == 4) {\r\n int quad[4] = {\r\n new_indices[n + 3],\r\n new_indices[n + 0],\r\n new_indices[n + 1],\r\n new_indices[n + 2],\r\n };\r\n for (int ni = 0; ni < count - 2; ++ni) {\r\n dst[i + 0] = quad[0];\r\n dst[i + 1] = quad[ni + i1];\r\n dst[i + 2] = quad[ni + i2];\r\n i += 3;\r\n }\r\n n += count;\r\n }\r\n else {\r\n for (int ni = 0; ni < count - 2; ++ni) {\r\n dst[i + 0] = new_indices[n + 0];\r\n dst[i + 1] = new_indices[n + ni + i1];\r\n dst[i + 2] = new_indices[n + ni + i2];\r\n i += 3;\r\n }\r\n n += count;\r\n }\r\n }\r\n }\r\n else {\r\n for (size_t fi = 0; fi < num_faces; ++fi) {\r\n int count = counts[fi];\r\n for (int ni = 0; ni < count - 2; ++ni) {\r\n dst[i + 0] = new_indices[n + 0];\r\n dst[i + 1] = new_indices[n + ni + i1];\r\n dst[i + 2] = new_indices[n + ni + i2];\r\n i += 3;\r\n }\r\n n += count;\r\n }\r\n }\r\n}\r\n\r\nvoid MeshRefiner::genSubmeshes(IArray material_ids)\r\n{\r\n submeshes.clear();\r\n\r\n new_indices_submeshes.resize(new_indices_triangulated.size());\r\n const int *indices_read = new_indices_triangulated.data();\r\n int *indices_write = new_indices_submeshes.data();\r\n\r\n int num_splits = (int)splits.size();\r\n int offset_faces = 0;\r\n RawVector tmp_submeshes;\r\n\r\n for (int spi = 0; spi < num_splits; ++spi) {\r\n auto& split = splits[spi];\r\n int offset_vertices = split.vertex_offset;\r\n\r\n \/\/ count triangle indices\r\n for (int fi = 0; fi < split.face_count; ++fi) {\r\n int mid = material_ids[offset_faces + fi] + 1; \/\/ -1 == no material. adjust to zero based\r\n while (mid >= (int)tmp_submeshes.size()) {\r\n int id = (int)tmp_submeshes.size();\r\n tmp_submeshes.push_back({});\r\n tmp_submeshes.back().material_id = id - 1;\r\n }\r\n tmp_submeshes[mid].index_count += (counts[fi] - 2) * 3;\r\n }\r\n\r\n for (int mi = 0; mi < (int)tmp_submeshes.size(); ++mi) {\r\n auto& sm = tmp_submeshes[mi];\r\n sm.indices_write = indices_write;\r\n sm.index_offset = (int)std::distance(new_indices_submeshes.data(), indices_write);\r\n indices_write += sm.index_count;\r\n }\r\n\r\n \/\/ copy indices\r\n for (int fi = 0; fi < split.face_count; ++fi) {\r\n int mid = material_ids[offset_faces + fi] + 1;\r\n int count = counts[offset_faces + fi];\r\n int nidx = (count - 2) * 3;\r\n for (int i = 0; i < nidx; ++i) {\r\n *(tmp_submeshes[mid].indices_write++) = *(indices_read++) - offset_vertices;\r\n }\r\n }\r\n\r\n for (int mi = 0; mi < (int)tmp_submeshes.size(); ++mi) {\r\n auto& sm = tmp_submeshes[mi];\r\n if (sm.index_count > 0) {\r\n ++split.submesh_count;\r\n submeshes.push_back(sm);\r\n }\r\n }\r\n\r\n offset_faces += split.face_count;\r\n tmp_submeshes.clear();\r\n }\r\n setupSubmeshes();\r\n}\r\n\r\nvoid MeshRefiner::genSubmeshes()\r\n{\r\n submeshes.clear();\r\n\r\n new_indices_submeshes.resize(new_indices_triangulated.size());\r\n const int *indices_read = new_indices_triangulated.data();\r\n int *indices_write = new_indices_submeshes.data();\r\n\r\n int num_splits = (int)splits.size();\r\n for (int spi = 0; spi < num_splits; ++spi) {\r\n auto& split = splits[spi];\r\n int offset_vertices = split.vertex_offset;\r\n\r\n Submesh sm;\r\n sm.index_count = split.triangulated_index_count;\r\n sm.index_offset = (int)std::distance(new_indices_submeshes.data(), indices_write);\r\n for (int ii = 0; ii < sm.index_count; ++ii) {\r\n *(indices_write++) = *(indices_read++) - offset_vertices;\r\n }\r\n\r\n ++split.submesh_count;\r\n submeshes.push_back(sm);\r\n }\r\n setupSubmeshes();\r\n}\r\n\r\nvoid MeshRefiner::setupSubmeshes()\r\n{\r\n int num_splits = (int)splits.size();\r\n int total_submeshes = 0;\r\n for (int spi = 0; spi < num_splits; ++spi) {\r\n auto& split = splits[spi];\r\n split.submesh_offset = total_submeshes;\r\n total_submeshes += split.submesh_count;\r\n for (int smi = 0; smi < split.submesh_count; ++smi) {\r\n auto& sm = submeshes[smi + split.submesh_offset];\r\n sm.split_index = spi;\r\n sm.submesh_index = smi;\r\n }\r\n }\r\n}\r\n\r\n\r\nvoid MeshRefiner::clear()\r\n{\r\n split_unit = 0;\r\n counts.reset();\r\n indices.reset();\r\n points.reset();\r\n for (auto& attr : attributes) {\r\n attr->clear();\r\n \/\/ attributes are placement new-ed, so need to call destructor manually\r\n attr->~IAttribute();\r\n }\r\n attributes.clear();\r\n\r\n old2new_indices.clear();\r\n new2old_points.clear();\r\n\r\n new_indices.clear();\r\n new_indices_triangulated.clear();\r\n new_indices_submeshes.clear();\r\n\r\n new_points.clear();\r\n splits.clear();\r\n submeshes.clear();\r\n num_new_indices = 0;\r\n}\r\n\r\nvoid MeshRefiner::refine()\r\n{\r\n if (connection.v2f_counts.size() != points.size()) {\r\n connection.buildConnection(indices, counts, points);\r\n }\r\n\r\n int num_indices = (int)indices.size();\r\n new_points.reserve(num_indices);\r\n new_indices.reserve(num_indices);\r\n for (auto& attr : attributes) { attr->prepare((int)points.size(), (int)indices.size()); }\r\n\r\n old2new_indices.resize(num_indices, -1);\r\n\r\n int num_faces_total = (int)counts.size();\r\n int offset_faces = 0;\r\n int offset_indices = 0;\r\n int offset_vertices = 0;\r\n int num_faces = 0;\r\n int num_indices_triangulated = 0;\r\n\r\n auto add_new_split = [&]() {\r\n auto split = Split{};\r\n split.face_offset = offset_faces;\r\n split.index_offset = offset_indices;\r\n split.vertex_offset = offset_vertices;\r\n split.face_count = num_faces;\r\n split.triangulated_index_count = num_indices_triangulated;\r\n split.vertex_count = (int)new_points.size() - offset_vertices;\r\n split.index_count = (int)new_indices.size() - offset_indices;\r\n splits.push_back(split);\r\n\r\n offset_faces += split.face_count;\r\n offset_indices += split.index_count;\r\n offset_vertices += split.vertex_count;\r\n\r\n num_new_indices += num_indices_triangulated;\r\n num_faces = 0;\r\n num_indices_triangulated = 0;\r\n };\r\n\r\n auto compare_all_attributes = [&](int ni, int ii) -> bool {\r\n for (auto& attr : attributes)\r\n if (!attr->compare(ni, ii)) { return false; }\r\n return true;\r\n };\r\n\r\n auto find_or_emit_vertex = [&](int vi, int ii) -> int {\r\n int offset = connection.v2f_offsets[vi];\r\n int connection_count = connection.v2f_counts[vi];\r\n for (int ci = 0; ci < connection_count; ++ci) {\r\n int& ni = old2new_indices[connection.v2f_indices[offset + ci]];\r\n if (ni != -1 && compare_all_attributes(ni, ii)) {\r\n return ni;\r\n }\r\n else {\r\n ni = (int)new_points.size();\r\n new_points.push_back(points[vi]);\r\n new2old_points.push_back(vi);\r\n for (auto& attr : attributes) { attr->emit(ii); }\r\n return ni;\r\n }\r\n }\r\n return 0;\r\n };\r\n\r\n int offset = 0;\r\n for (int fi = 0; fi < num_faces_total; ++fi) {\r\n int count = counts[fi];\r\n\r\n if (split_unit > 0 && (int)new_points.size() - offset_vertices + count > split_unit) {\r\n add_new_split();\r\n\r\n \/\/ clear vertex cache\r\n memset(old2new_indices.data(), -1, old2new_indices.size() * sizeof(int));\r\n }\r\n\r\n for (int ci = 0; ci < count; ++ci) {\r\n int ii = offset + ci;\r\n int vi = indices[ii];\r\n new_indices.push_back(find_or_emit_vertex(vi, ii));\r\n }\r\n ++num_faces;\r\n num_indices_triangulated += (count - 2) * 3;\r\n offset += count;\r\n }\r\n add_new_split();\r\n}\r\n\r\n<|endoftext|>"} {"text":"\/*************************************************************************\/\n\/* audio_driver_ao.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. *\/\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#include \"audio_driver_ao.h\"\n\n#include \"globals.h\"\n#include \"os\/os.h\"\n\nError AudioDriverAO::init() {\n\n\tactive = false;\n\tthread_exited = false;\n\texit_thread = false;\n\tpcm_open = false;\n\tsamples_in = NULL;\n\n\tmix_rate = 44100;\n\toutput_format = OUTPUT_STEREO;\n\tchannels = 2;\n\n\tao_sample_format format;\n\n\tformat.bits = 16;\n\tformat.rate = mix_rate;\n\tformat.channels = channels;\n\tformat.byte_format = AO_FMT_LITTLE;\n\tformat.matrix = \"L,R\";\n\n\tdevice = ao_open_live(ao_default_driver_id(), &format, NULL);\n\tERR_FAIL_COND_V(device == NULL, ERR_CANT_OPEN);\n\n\tint latency = GLOBAL_DEF(\"audio\/output_latency\", 25);\n\tbuffer_size = nearest_power_of_2( latency * mix_rate \/ 1000 );\n\n\tsamples_in = memnew_arr(int32_t, buffer_size * channels);\n\n\tmutex = Mutex::create();\n\tthread = Thread::create(AudioDriverAO::thread_func, this);\n\n\treturn OK;\n};\n\nvoid AudioDriverAO::thread_func(void* p_udata) {\n\tAudioDriverAO* ad = (AudioDriverAO*)p_udata;\n\n\tint16_t* samples_out = ad->samples_in; \/\/ Overwrite samples on conversion\n\tunsigned int n_samples = ad->buffer_size * ad->channels;\n\tunsigned int n_bytes = n_samples * sizeof(int16_t);\n\n\twhile (!ad->exit_thread) {\n\t\tif (ad->active) {\n\t\t\tad->lock();\n\t\t\tad->audio_server_process(ad->buffer_size, ad->samples_in);\n\t\t\tad->unlock();\n\n\t\t\tfor (unsigned int i = 0; i < n_samples; i++) {\n\t\t\t\tsamples_out[i] = ad->samples_in[i] >> 16;\n\t\t\t}\n\t\t} else {\n\t\t\tmemset(samples_out, 0, n_bytes);\n\t\t}\n\n\t\tif (ad->exit_thread)\n\t\t\tbreak;\n\n\t\tif (!ao_play(ad->device, reinterpret_cast(samples_out), n_bytes)) {\n\t\t\tERR_PRINT(\"ao_play() failed\");\n\t\t}\n\t};\n\n\tad->thread_exited = true;\n};\n\nvoid AudioDriverAO::start() {\n\tactive = true;\n};\n\nint AudioDriverAO::get_mix_rate() const {\n\treturn mix_rate;\n};\n\nAudioDriverSW::OutputFormat AudioDriverAO::get_output_format() const {\n\treturn output_format;\n};\n\nvoid AudioDriverAO::lock() {\n\tif (!thread || !mutex)\n\t\treturn;\n\tmutex->lock();\n};\n\nvoid AudioDriverAO::unlock() {\n\tif (!thread || !mutex)\n\t\treturn;\n\tmutex->unlock();\n};\n\nvoid AudioDriverAO::finish() {\n\tif (!thread)\n\t\treturn;\n\n\texit_thread = true;\n\tThread::wait_to_finish(thread);\n\n\tif (samples_in) {\n\t\tmemdelete_arr(samples_in);\n\t};\n\n\tmemdelete(thread);\n\tif (mutex)\n\t\tmemdelete(mutex);\n\n\tif (device)\n\t\tao_close(device);\n\n\tthread = NULL;\n};\n\nAudioDriverAO::AudioDriverAO() {\n\tmutex = NULL;\n\tthread = NULL;\n\n\tao_initialize();\n};\n\nAudioDriverAO::~AudioDriverAO() {\n\tao_shutdown();\n};\nCast samples_in to samples_out with reinterpret_cast\/*************************************************************************\/\n\/* audio_driver_ao.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. *\/\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#include \"audio_driver_ao.h\"\n\n#include \"globals.h\"\n#include \"os\/os.h\"\n\nError AudioDriverAO::init() {\n\n\tactive = false;\n\tthread_exited = false;\n\texit_thread = false;\n\tpcm_open = false;\n\tsamples_in = NULL;\n\n\tmix_rate = 44100;\n\toutput_format = OUTPUT_STEREO;\n\tchannels = 2;\n\n\tao_sample_format format;\n\n\tformat.bits = 16;\n\tformat.rate = mix_rate;\n\tformat.channels = channels;\n\tformat.byte_format = AO_FMT_LITTLE;\n\tformat.matrix = \"L,R\";\n\n\tdevice = ao_open_live(ao_default_driver_id(), &format, NULL);\n\tERR_FAIL_COND_V(device == NULL, ERR_CANT_OPEN);\n\n\tint latency = GLOBAL_DEF(\"audio\/output_latency\", 25);\n\tbuffer_size = nearest_power_of_2( latency * mix_rate \/ 1000 );\n\n\tsamples_in = memnew_arr(int32_t, buffer_size * channels);\n\n\tmutex = Mutex::create();\n\tthread = Thread::create(AudioDriverAO::thread_func, this);\n\n\treturn OK;\n};\n\nvoid AudioDriverAO::thread_func(void* p_udata) {\n\tAudioDriverAO* ad = (AudioDriverAO*)p_udata;\n\n\t\/\/ Overwrite samples on conversion\n\tint16_t* samples_out = reinterpret_cast(ad->samples_in);\n\tunsigned int n_samples = ad->buffer_size * ad->channels;\n\tunsigned int n_bytes = n_samples * sizeof(int16_t);\n\n\twhile (!ad->exit_thread) {\n\t\tif (ad->active) {\n\t\t\tad->lock();\n\t\t\tad->audio_server_process(ad->buffer_size, ad->samples_in);\n\t\t\tad->unlock();\n\n\t\t\tfor (unsigned int i = 0; i < n_samples; i++) {\n\t\t\t\tsamples_out[i] = ad->samples_in[i] >> 16;\n\t\t\t}\n\t\t} else {\n\t\t\tmemset(samples_out, 0, n_bytes);\n\t\t}\n\n\t\tif (ad->exit_thread)\n\t\t\tbreak;\n\n\t\tif (!ao_play(ad->device, reinterpret_cast(samples_out), n_bytes)) {\n\t\t\tERR_PRINT(\"ao_play() failed\");\n\t\t}\n\t};\n\n\tad->thread_exited = true;\n};\n\nvoid AudioDriverAO::start() {\n\tactive = true;\n};\n\nint AudioDriverAO::get_mix_rate() const {\n\treturn mix_rate;\n};\n\nAudioDriverSW::OutputFormat AudioDriverAO::get_output_format() const {\n\treturn output_format;\n};\n\nvoid AudioDriverAO::lock() {\n\tif (!thread || !mutex)\n\t\treturn;\n\tmutex->lock();\n};\n\nvoid AudioDriverAO::unlock() {\n\tif (!thread || !mutex)\n\t\treturn;\n\tmutex->unlock();\n};\n\nvoid AudioDriverAO::finish() {\n\tif (!thread)\n\t\treturn;\n\n\texit_thread = true;\n\tThread::wait_to_finish(thread);\n\n\tif (samples_in) {\n\t\tmemdelete_arr(samples_in);\n\t};\n\n\tmemdelete(thread);\n\tif (mutex)\n\t\tmemdelete(mutex);\n\n\tif (device)\n\t\tao_close(device);\n\n\tthread = NULL;\n};\n\nAudioDriverAO::AudioDriverAO() {\n\tmutex = NULL;\n\tthread = NULL;\n\n\tao_initialize();\n};\n\nAudioDriverAO::~AudioDriverAO() {\n\tao_shutdown();\n};\n<|endoftext|>"} {"text":"{\n \/\/\n \/\/This macro produces the flowchart of TFormula::Analyze\n \/\/Author: Rene Brun\n \n gROOT->Reset();\n c1 = new TCanvas(\"c1\",\"Analyze.mac\",620,790);\n c1->Range(-1,0,19,30);\n TPaveLabel pl1(0,27,3.5,29,\"Analyze\");\n pl1.SetFillColor(42);\n pl1.Draw();\n TPaveText pt1(0,22.8,4,25.2);\n TText *t1=pt1.AddText(\"Parenthesis matching\");\n TText *t2=pt1.AddText(\"Remove unnecessary\");\n TText *t2a=pt1.AddText(\"parenthesis\");\n pt1.Draw();\n TPaveText pt2(6,23,10,25);\n TText *t3=pt2.AddText(\"break of\");\n TText *t4=pt2.AddText(\"Analyze\");\n pt2.Draw();\n TPaveText pt3(0,19,4,21);\n TText *t4=pt3.AddText(\"look for simple\");\n TText *t5=pt3.AddText(\"operators\");\n pt3.Draw();\n TPaveText pt4(0,15,4,17);\n TText *t6=pt4.AddText(\"look for an already\");\n TText *t7=pt4.AddText(\"defined expression\");\n pt4.Draw();\n TPaveText pt5(0,11,4,13);\n TText *t8=pt5.AddText(\"look for usual\");\n TText *t9=pt5.AddText(\"functions :cos sin ..\");\n pt5.Draw();\n TPaveText pt6(0,7,4,9);\n TText *t10=pt6.AddText(\"look for a\");\n TText *t11=pt6.AddText(\"numeric value\");\n pt6.Draw();\n TPaveText pt7(6,18.5,10,21.5);\n TText *t12=pt7.AddText(\"Analyze left and\");\n TText *t13=pt7.AddText(\"right part of\");\n TText *t14=pt7.AddText(\"the expression\");\n pt7.Draw();\n TPaveText pt8(6,15,10,17);\n TText *t15=pt8.AddText(\"Replace expression\");\n pt8.Draw();\n TPaveText pt9(6,11,10,13);\n TText *t16=pt9.AddText(\"Analyze\");\n pt9.SetFillColor(42);\n pt9.Draw();\n TPaveText pt10(6,7,10,9);\n TText *t17=pt10.AddText(\"Error\");\n TText *t18=pt10.AddText(\"Break of Analyze\");\n pt10.Draw();\n TPaveText pt11(14,22,17,24);\n pt11.SetFillColor(42);\n TText *t19=pt11.AddText(\"Analyze\");\n TText *t19a=pt11.AddText(\"Left\");\n pt11.Draw();\n TPaveText pt12(14,19,17,21);\n pt12.SetFillColor(42);\n TText *t20=pt12.AddText(\"Analyze\");\n TText *t20a=pt12.AddText(\"Right\");\n pt12.Draw();\n TPaveText pt13(14,15,18,18);\n TText *t21=pt13.AddText(\"StackNumber++\");\n TText *t22=pt13.AddText(\"operator[StackNumber]\");\n TText *t23=pt13.AddText(\"= operator found\");\n pt13.Draw();\n TPaveText pt14(12,10.8,17,13.2);\n TText *t24=pt14.AddText(\"StackNumber++\");\n TText *t25=pt14.AddText(\"operator[StackNumber]\");\n TText *t26=pt14.AddText(\"= function found\");\n pt14.Draw();\n TPaveText pt15(6,7,10,9);\n TText *t27=pt15.AddText(\"Error\");\n TText *t28=pt15.AddText(\"break of Analyze\");\n pt15.Draw();\n TPaveText pt16(0,2,7,5);\n TText *t29=pt16.AddText(\"StackNumber++\");\n TText *t30=pt16.AddText(\"operator[StackNumber] = 0\");\n TText *t31=pt16.AddText(\"value[StackNumber] = value found\");\n pt16.Draw();\n TArrow ar(2,27,2,25.4,0.012,\"|>\");\n ar.SetFillColor(1);\n ar.Draw();\n ar.DrawArrow(2,22.8,2,21.2,0.012,\"|>\");\n ar.DrawArrow(2,19,2,17.2,0.012,\"|>\");\n ar.DrawArrow(2,15,2,13.2,0.012,\"|>\");\n ar.DrawArrow(2,11,2, 9.2,0.012,\"|>\");\n ar.DrawArrow(2, 7,2, 5.2,0.012,\"|>\");\n ar.DrawArrow(4,24,6,24,0.012,\"|>\");\n ar.DrawArrow(4,20,6,20,0.012,\"|>\");\n ar.DrawArrow(4,16,6,16,0.012,\"|>\");\n ar.DrawArrow(4,12,6,12,0.012,\"|>\");\n ar.DrawArrow(4, 8,6, 8,0.012,\"|>\");\n ar.DrawArrow(10,20,14,20,0.012,\"|>\");\n ar.DrawArrow(12,23,14,23,0.012,\"|>\");\n ar.DrawArrow(12,16.5,14,16.5,0.012,\"|>\");\n ar.DrawArrow(10,12,12,12,0.012,\"|>\");\n TText ta(2.2,22.2,\"err = 0\");\n ta.SetTextFont(71);\n ta.SetTextSize(0.015);\n ta.SetTextColor(4);\n ta.SetTextAlign(12);\n ta.Draw();\n ta.DrawText(2.2,18.2,\"not found\");\n ta.DrawText(2.2,6.2,\"found\");\n TText tb(4.2,24.1,\"err != 0\");\n tb.SetTextFont(71);\n tb.SetTextSize(0.015);\n tb.SetTextColor(4);\n tb.SetTextAlign(11);\n tb.Draw();\n tb.DrawText(4.2,20.1,\"found\");\n tb.DrawText(4.2,16.1,\"found\");\n tb.DrawText(4.2,12.1,\"found\");\n tb.DrawText(4.2, 8.1,\"not found\");\n TLine l1(12,16.5,12,23);\n l1.Draw();\n}\nFix a redefinition.{\n \/\/\n \/\/This macro produces the flowchart of TFormula::Analyze\n \/\/Author: Rene Brun\n \n gROOT->Reset();\n c1 = new TCanvas(\"c1\",\"Analyze.mac\",620,790);\n c1->Range(-1,0,19,30);\n TPaveLabel pl1(0,27,3.5,29,\"Analyze\");\n pl1.SetFillColor(42);\n pl1.Draw();\n TPaveText pt1(0,22.8,4,25.2);\n TText *t1=pt1.AddText(\"Parenthesis matching\");\n TText *t2=pt1.AddText(\"Remove unnecessary\");\n TText *t2a=pt1.AddText(\"parenthesis\");\n pt1.Draw();\n TPaveText pt2(6,23,10,25);\n TText *t3=pt2.AddText(\"break of\");\n TText *t4=pt2.AddText(\"Analyze\");\n pt2.Draw();\n TPaveText pt3(0,19,4,21);\n t4=pt3.AddText(\"look for simple\");\n TText *t5=pt3.AddText(\"operators\");\n pt3.Draw();\n TPaveText pt4(0,15,4,17);\n TText *t6=pt4.AddText(\"look for an already\");\n TText *t7=pt4.AddText(\"defined expression\");\n pt4.Draw();\n TPaveText pt5(0,11,4,13);\n TText *t8=pt5.AddText(\"look for usual\");\n TText *t9=pt5.AddText(\"functions :cos sin ..\");\n pt5.Draw();\n TPaveText pt6(0,7,4,9);\n TText *t10=pt6.AddText(\"look for a\");\n TText *t11=pt6.AddText(\"numeric value\");\n pt6.Draw();\n TPaveText pt7(6,18.5,10,21.5);\n TText *t12=pt7.AddText(\"Analyze left and\");\n TText *t13=pt7.AddText(\"right part of\");\n TText *t14=pt7.AddText(\"the expression\");\n pt7.Draw();\n TPaveText pt8(6,15,10,17);\n TText *t15=pt8.AddText(\"Replace expression\");\n pt8.Draw();\n TPaveText pt9(6,11,10,13);\n TText *t16=pt9.AddText(\"Analyze\");\n pt9.SetFillColor(42);\n pt9.Draw();\n TPaveText pt10(6,7,10,9);\n TText *t17=pt10.AddText(\"Error\");\n TText *t18=pt10.AddText(\"Break of Analyze\");\n pt10.Draw();\n TPaveText pt11(14,22,17,24);\n pt11.SetFillColor(42);\n TText *t19=pt11.AddText(\"Analyze\");\n TText *t19a=pt11.AddText(\"Left\");\n pt11.Draw();\n TPaveText pt12(14,19,17,21);\n pt12.SetFillColor(42);\n TText *t20=pt12.AddText(\"Analyze\");\n TText *t20a=pt12.AddText(\"Right\");\n pt12.Draw();\n TPaveText pt13(14,15,18,18);\n TText *t21=pt13.AddText(\"StackNumber++\");\n TText *t22=pt13.AddText(\"operator[StackNumber]\");\n TText *t23=pt13.AddText(\"= operator found\");\n pt13.Draw();\n TPaveText pt14(12,10.8,17,13.2);\n TText *t24=pt14.AddText(\"StackNumber++\");\n TText *t25=pt14.AddText(\"operator[StackNumber]\");\n TText *t26=pt14.AddText(\"= function found\");\n pt14.Draw();\n TPaveText pt15(6,7,10,9);\n TText *t27=pt15.AddText(\"Error\");\n TText *t28=pt15.AddText(\"break of Analyze\");\n pt15.Draw();\n TPaveText pt16(0,2,7,5);\n TText *t29=pt16.AddText(\"StackNumber++\");\n TText *t30=pt16.AddText(\"operator[StackNumber] = 0\");\n TText *t31=pt16.AddText(\"value[StackNumber] = value found\");\n pt16.Draw();\n TArrow ar(2,27,2,25.4,0.012,\"|>\");\n ar.SetFillColor(1);\n ar.Draw();\n ar.DrawArrow(2,22.8,2,21.2,0.012,\"|>\");\n ar.DrawArrow(2,19,2,17.2,0.012,\"|>\");\n ar.DrawArrow(2,15,2,13.2,0.012,\"|>\");\n ar.DrawArrow(2,11,2, 9.2,0.012,\"|>\");\n ar.DrawArrow(2, 7,2, 5.2,0.012,\"|>\");\n ar.DrawArrow(4,24,6,24,0.012,\"|>\");\n ar.DrawArrow(4,20,6,20,0.012,\"|>\");\n ar.DrawArrow(4,16,6,16,0.012,\"|>\");\n ar.DrawArrow(4,12,6,12,0.012,\"|>\");\n ar.DrawArrow(4, 8,6, 8,0.012,\"|>\");\n ar.DrawArrow(10,20,14,20,0.012,\"|>\");\n ar.DrawArrow(12,23,14,23,0.012,\"|>\");\n ar.DrawArrow(12,16.5,14,16.5,0.012,\"|>\");\n ar.DrawArrow(10,12,12,12,0.012,\"|>\");\n TText ta(2.2,22.2,\"err = 0\");\n ta.SetTextFont(71);\n ta.SetTextSize(0.015);\n ta.SetTextColor(4);\n ta.SetTextAlign(12);\n ta.Draw();\n ta.DrawText(2.2,18.2,\"not found\");\n ta.DrawText(2.2,6.2,\"found\");\n TText tb(4.2,24.1,\"err != 0\");\n tb.SetTextFont(71);\n tb.SetTextSize(0.015);\n tb.SetTextColor(4);\n tb.SetTextAlign(11);\n tb.Draw();\n tb.DrawText(4.2,20.1,\"found\");\n tb.DrawText(4.2,16.1,\"found\");\n tb.DrawText(4.2,12.1,\"found\");\n tb.DrawText(4.2, 8.1,\"not found\");\n TLine l1(12,16.5,12,23);\n l1.Draw();\n}\n<|endoftext|>"} {"text":"\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_math\n\/\/\/ Demo for quantiles (with highlight mode)\n\/\/\/\n\/\/\/ \\macro_image\n\/\/\/ \\macro_code\n\/\/\/\n\/\/\/ \\authors Rene Brun, Eddy Offermann\n\nTList *lq = 0;\nTGraph *gr = 0;\n\nvoid hlquantiles() {\n const Int_t nq = 100;\n const Int_t nshots = 10;\n Double_t xq[nq]; \/\/ position where to compute the quantiles in [0,1]\n Double_t yq[nq]; \/\/ array to contain the quantiles\n for (Int_t i=0;iFillRandom(\"gaus\",50);\n h->GetQuantiles(nq,yq,xq);\n gr70->SetPoint(shot,shot+1,yq[70]);\n gr90->SetPoint(shot,shot+1,yq[90]);\n gr98->SetPoint(shot,shot+1,yq[98]);\n for (Int_t ig = 0; ig < nq; ig++)\n grq[ig]->SetPoint(shot,shot+1,yq[ig]);\n }\n\n \/\/show the original histogram in the top pad\n TCanvas *c1 = new TCanvas(\"c1\",\"demo quantiles\",10,10,600,900);\n c1->SetFillColor(41);\n c1->Divide(1,3);\n c1->cd(1);\n h->SetFillColor(38);\n h->Draw();\n\n \/\/ show the final quantiles in the middle pad\n c1->cd(2);\n gPad->SetFrameFillColor(33);\n gPad->SetGrid();\n gr = new TGraph(nq,xq,yq);\n gr->SetTitle(\"final quantiles\");\n gr->SetMarkerStyle(21);\n gr->SetMarkerColor(kRed);\n gr->SetMarkerSize(0.3);\n gr->Draw(\"ap\");\n\n \/\/ prepare quantiles\n lq = new TList();\n for (Int_t ig = 0; ig < nq; ig++) {\n grq[ig]->SetMinimum(gr->GetYaxis()->GetXmin());\n grq[ig]->SetMaximum(gr->GetYaxis()->GetXmax());\n grq[ig]->SetMarkerStyle(23);\n grq[ig]->SetMarkerColor(ig%100);\n grq[ig]->SetTitle(TString::Format(\"q%02d\", ig));\n lq->Add(grq[ig]);\n }\n\n TText *info = new TText(0.1, 2.4, \"please move the mouse over the graph\");\n info->SetTextSize(0.08);\n info->SetTextColor(gr->GetMarkerColor());\n info->SetBit(kCannotPick);\n info->Draw();\n\n gr->SetHighlight();\n c1->HighlightConnect(\"HighlightQuantile(TVirtualPad*,TObject*,Int_t,Int_t)\");\n\n \/\/ show the evolution of some quantiles in the bottom pad\n c1->cd(3);\n gPad->SetFrameFillColor(17);\n gPad->DrawFrame(0,0,nshots+1,3.2);\n gPad->SetGrid();\n gr98->SetMarkerStyle(22);\n gr98->SetMarkerColor(kRed);\n gr98->Draw(\"lp\");\n gr90->SetMarkerStyle(21);\n gr90->SetMarkerColor(kBlue);\n gr90->Draw(\"lp\");\n gr70->SetMarkerStyle(20);\n gr70->SetMarkerColor(kMagenta);\n gr70->Draw(\"lp\");\n \/\/ add a legend\n TLegend *legend = new TLegend(0.85,0.74,0.95,0.95);\n legend->SetTextFont(72);\n legend->SetTextSize(0.05);\n legend->AddEntry(gr98,\" q98\",\"lp\");\n legend->AddEntry(gr90,\" q90\",\"lp\");\n legend->AddEntry(gr70,\" q70\",\"lp\");\n legend->Draw();\n}\n\nvoid HighlightQuantile(TVirtualPad *pad, TObject *obj, Int_t ihp, Int_t y)\n{\n \/\/ show the evolution of all quantiles in the bottom pad\n if (obj != gr) return;\n if (ihp == -1) return;\n\n TVirtualPad *savepad = gPad;\n pad->GetCanvas()->cd(3);\n lq->At(ihp)->Draw(\"alp\");\n gPad->Update();\n savepad->cd();\n}\nChange authors\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_math\n\/\/\/ Demo for quantiles (with highlight mode)\n\/\/\/\n\/\/\/ \\macro_image\n\/\/\/ \\macro_code\n\/\/\/\n\/\/\/ \\authors Rene Brun, Eddy Offermann, Jan Musinsky\n\nTList *lq = 0;\nTGraph *gr = 0;\n\nvoid hlquantiles() {\n const Int_t nq = 100;\n const Int_t nshots = 10;\n Double_t xq[nq]; \/\/ position where to compute the quantiles in [0,1]\n Double_t yq[nq]; \/\/ array to contain the quantiles\n for (Int_t i=0;iFillRandom(\"gaus\",50);\n h->GetQuantiles(nq,yq,xq);\n gr70->SetPoint(shot,shot+1,yq[70]);\n gr90->SetPoint(shot,shot+1,yq[90]);\n gr98->SetPoint(shot,shot+1,yq[98]);\n for (Int_t ig = 0; ig < nq; ig++)\n grq[ig]->SetPoint(shot,shot+1,yq[ig]);\n }\n\n \/\/show the original histogram in the top pad\n TCanvas *c1 = new TCanvas(\"c1\",\"demo quantiles\",10,10,600,900);\n c1->SetFillColor(41);\n c1->Divide(1,3);\n c1->cd(1);\n h->SetFillColor(38);\n h->Draw();\n\n \/\/ show the final quantiles in the middle pad\n c1->cd(2);\n gPad->SetFrameFillColor(33);\n gPad->SetGrid();\n gr = new TGraph(nq,xq,yq);\n gr->SetTitle(\"final quantiles\");\n gr->SetMarkerStyle(21);\n gr->SetMarkerColor(kRed);\n gr->SetMarkerSize(0.3);\n gr->Draw(\"ap\");\n\n \/\/ prepare quantiles\n lq = new TList();\n for (Int_t ig = 0; ig < nq; ig++) {\n grq[ig]->SetMinimum(gr->GetYaxis()->GetXmin());\n grq[ig]->SetMaximum(gr->GetYaxis()->GetXmax());\n grq[ig]->SetMarkerStyle(23);\n grq[ig]->SetMarkerColor(ig%100);\n grq[ig]->SetTitle(TString::Format(\"q%02d\", ig));\n lq->Add(grq[ig]);\n }\n\n TText *info = new TText(0.1, 2.4, \"please move the mouse over the graph\");\n info->SetTextSize(0.08);\n info->SetTextColor(gr->GetMarkerColor());\n info->SetBit(kCannotPick);\n info->Draw();\n\n gr->SetHighlight();\n c1->HighlightConnect(\"HighlightQuantile(TVirtualPad*,TObject*,Int_t,Int_t)\");\n\n \/\/ show the evolution of some quantiles in the bottom pad\n c1->cd(3);\n gPad->SetFrameFillColor(17);\n gPad->DrawFrame(0,0,nshots+1,3.2);\n gPad->SetGrid();\n gr98->SetMarkerStyle(22);\n gr98->SetMarkerColor(kRed);\n gr98->Draw(\"lp\");\n gr90->SetMarkerStyle(21);\n gr90->SetMarkerColor(kBlue);\n gr90->Draw(\"lp\");\n gr70->SetMarkerStyle(20);\n gr70->SetMarkerColor(kMagenta);\n gr70->Draw(\"lp\");\n \/\/ add a legend\n TLegend *legend = new TLegend(0.85,0.74,0.95,0.95);\n legend->SetTextFont(72);\n legend->SetTextSize(0.05);\n legend->AddEntry(gr98,\" q98\",\"lp\");\n legend->AddEntry(gr90,\" q90\",\"lp\");\n legend->AddEntry(gr70,\" q70\",\"lp\");\n legend->Draw();\n}\n\nvoid HighlightQuantile(TVirtualPad *pad, TObject *obj, Int_t ihp, Int_t y)\n{\n \/\/ show the evolution of all quantiles in the bottom pad\n if (obj != gr) return;\n if (ihp == -1) return;\n\n TVirtualPad *savepad = gPad;\n pad->GetCanvas()->cd(3);\n lq->At(ihp)->Draw(\"alp\");\n gPad->Update();\n savepad->cd();\n}\n<|endoftext|>"} {"text":"#include \"updaterbody.hpp\"\n#include \"usbshell.hpp\"\n\nusing namespace Updater;\nusing namespace UpdaterAPI;\n\nUpdaterBody *GetBody(bool flag, UPDATER_ACTION_MODE mode, firmware_information_t::information *info)\n{\n return new UpdaterBodyImpl;\n}\n\nvoid ReleaseBody(UpdaterBody *body)\n{\n delete body;\n}\n\nbool UpdaterBodyImpl::Execute(RingBuffer *buffer, CallbackInterface *interface)\n{\n usbshell_loop();\n return true;\n}\nUpdaterBody: Catch exceptions#include \"updaterbody.hpp\"\n#include \"usbshell.hpp\"\n\nusing namespace Updater;\nusing namespace UpdaterAPI;\n\nUpdaterBody *GetBody(bool flag, UPDATER_ACTION_MODE mode, firmware_information_t::information *info)\n{\n return new UpdaterBodyImpl;\n}\n\nvoid ReleaseBody(UpdaterBody *body)\n{\n delete body;\n}\n\nbool UpdaterBodyImpl::Execute(RingBuffer *buffer, CallbackInterface *interface)\n{\n try {\n usbshell_loop();\n } catch (...) {\n \/\/ ignore\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \"detectJumps.h\"\n#include \"utils.h\"\n\n\n\nusing namespace std;\n\n\nuint64_t transformRegionInReadToHash(regionInRead region){\n\thash regionHash;\n\treturn regionHash(region.read + region.firstWindow + region.lastWindow);\n}\n\n\nvoid detectJumps(const vector& vec, uint indexReadT, uint indexReadQ, unordered_map >& correspondance){\n\tuint indexT(0);\n\tuint indexQ(0);\n\tfor (uint i(0); i2){\n\t\t\tcout << \"jump\" << endl;\n\t\t\t\/\/~ if (correspondance.count(regionTarget)){\n\t\t\t\t\/\/~ correspondance[regionTarget].push_back({indexQ, vec[i].query, indexReadQ});\n\t\t\t\/\/~ } else {\n\t\t\t\t\/\/~ regionInRead r({indexQ, vec[i].query, indexReadQ});\n\t\t\t\t\/\/~ vector v;\n\t\t\t\t\/\/~ v.push_back(r);\n\t\t\t\t\/\/~ correspondance[regionTarget] = v;\n\t\t\t\/\/~ }\n\t\t\t\/\/~ cout << \"jump in target\" << indexT << \"to\" << vec[i+1].target << endl;\n\t\t\tindexT = vec[i+1].target;\n\t\t\tindexQ = vec[i+1].query;\n\t\t} else if (i != vec.size()-1 and absolute(int(vec[i].query)-int(vec[i+1].query))>2){\n\t\t\tcout << \"jump\" << endl;\n\t\t\t\/\/~ if (correspondance.count(regionTarget)){\n\t\t\t\t\/\/~ correspondance[regionTarget].push_back({indexQ, vec[i].query, indexReadQ});\n\t\t\t\/\/~ } else {\n\t\t\t\t\/\/~ regionInRead r({indexQ, vec[i].query, indexReadQ});\n\t\t\t\t\/\/~ vector v;\n\t\t\t\t\/\/~ v.push_back(r);\n\t\t\t\t\/\/~ correspondance[regionTarget] = v;\n\t\t\t\/\/~ }\n\t\t\t\/\/~ cout << \"jump in query\" << indexQ << \"to\" << vec[i+1].query << endl;\n\t\t\tindexT = vec[i+1].target;\n\t\t\tindexQ = vec[i+1].query;\n\t\t}\n\t}\n\tif (indexT==0){\n\t\tcout << \"no jump\" << endl;\n\t\t\/\/~ regionInRead regionTarget({vec[0].target, vec.back().target, indexReadT});\n\t\t\/\/~ if (correspondance.count(regionTarget)){\n\t\t\t\t\/\/~ correspondance[regionTarget].push_back({vec[0].query, vec.back().query, indexReadQ});\n\t\t\/\/~ } else {\n\t\t\t\t\/\/~ regionInRead r({vec[0].query, vec.back().query, indexReadQ});\n\t\t\t\t\/\/~ vector v;\n\t\t\t\t\/\/~ v.push_back(r);\n\t\t\t\t\/\/~ correspondance[regionTarget] = v;\n\t\t\/\/~ }\n\t}\n}\nfirst simple jump detection#include \n#include \n#include \n#include \n#include \n#include \n#include \"detectJumps.h\"\n#include \"utils.h\"\n\n\n\nusing namespace std;\n\n\nuint64_t transformRegionInReadToHash(regionInRead region){\n\thash regionHash;\n\treturn regionHash(region.read + region.firstWindow + region.lastWindow);\n}\n\n\nvoid detectJumps(const vector& vec, uint indexReadT, uint indexReadQ, unordered_map >& correspondance){\n\tuint indexT(0);\n\tuint indexQ(0);\n\tfor (uint i(0); i2){\n\t\t\t\/\/~ cout << \"jump\" << endl;\n\t\t\t\/\/~ if (correspondance.count(regionTarget)){\n\t\t\t\t\/\/~ correspondance[regionTarget].push_back({indexQ, vec[i].query, indexReadQ});\n\t\t\t\/\/~ } else {\n\t\t\t\t\/\/~ regionInRead r({indexQ, vec[i].query, indexReadQ});\n\t\t\t\t\/\/~ vector v;\n\t\t\t\t\/\/~ v.push_back(r);\n\t\t\t\t\/\/~ correspondance[regionTarget] = v;\n\t\t\t\/\/~ }\n\t\t\tcout << \"jump in target\" << indexT << \"to\" << vec[i+1].target << endl;\n\t\t\tindexT = vec[i+1].target;\n\t\t\tindexQ = vec[i+1].query;\n\t\t} else if (i != vec.size()-1 and absolute(int(vec[i].query)-int(vec[i+1].query))>2){\n\t\t\t\/\/~ cout << \"jump\" << endl;\n\t\t\t\/\/~ if (correspondance.count(regionTarget)){\n\t\t\t\t\/\/~ correspondance[regionTarget].push_back({indexQ, vec[i].query, indexReadQ});\n\t\t\t\/\/~ } else {\n\t\t\t\t\/\/~ regionInRead r({indexQ, vec[i].query, indexReadQ});\n\t\t\t\t\/\/~ vector v;\n\t\t\t\t\/\/~ v.push_back(r);\n\t\t\t\t\/\/~ correspondance[regionTarget] = v;\n\t\t\t\/\/~ }\n\t\t\tcout << \"jump in query\" << indexQ << \"to\" << vec[i+1].query << endl;\n\t\t\tindexT = vec[i+1].target;\n\t\t\tindexQ = vec[i+1].query;\n\t\t}\n\t}\n\tif (indexT==0){\n\t\tcout << \"no jump\" << endl;\n\t\t\/\/~ regionInRead regionTarget({vec[0].target, vec.back().target, indexReadT});\n\t\t\/\/~ if (correspondance.count(regionTarget)){\n\t\t\t\t\/\/~ correspondance[regionTarget].push_back({vec[0].query, vec.back().query, indexReadQ});\n\t\t\/\/~ } else {\n\t\t\t\t\/\/~ regionInRead r({vec[0].query, vec.back().query, indexReadQ});\n\t\t\t\t\/\/~ vector v;\n\t\t\t\t\/\/~ v.push_back(r);\n\t\t\t\t\/\/~ correspondance[regionTarget] = v;\n\t\t\/\/~ }\n\t}\n}\n<|endoftext|>"} {"text":"#include \"combat\/combat.h\"\n\n#include \"random.h\"\n#include \"logconsole.h\"\n#include \"dataconsts.h\"\n#include \"entity_system.h\"\n\n#include \"srv_attack.h\"\n#include \"srv_damage.h\"\n#include \"srv_hp_reply.h\"\n\n#include \"components\/basic_info.h\"\n#include \"components\/destination.h\"\n#include \"components\/life.h\"\n#include \"components\/magic.h\"\n#include \"components\/player_spawn.h\"\n#include \"components\/position.h\"\n#include \"components\/target.h\"\n#include \"components\/damage.h\"\n#include \"components\/skills.h\"\n#include \"components\/stamina.h\"\n#include \"components\/stats.h\"\n\n#include \n\nusing namespace RoseCommon;\nusing namespace RoseCommon::Packet;\n\n\nvoid Combat::hp_request(EntitySystem& entitySystem, Entity entity, const CliHpReq& packet) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n if (packet.get_targetId()) {\n Entity t = entitySystem.get_entity_from_id(packet.get_targetId());\n if (t != entt::null) {\n const auto& life = entitySystem.get_component(t);\n \n auto p = SrvHpReply::create(packet.get_targetId(), life.hp);\n entitySystem.send_to(entity, p);\n }\n }\n}\n\n\nstd::pair Combat::get_range_position(const EntitySystem& entitySystem, Entity character, Entity target, float range) {\n const auto& char_pos = entitySystem.get_component(character);\n const auto& target_pos = entitySystem.get_component(target);\n std::pair vector{char_pos.x - target_pos.x, char_pos.y - target_pos.y};\n const float length = sqrt(vector.first * vector.first + vector.second * vector.second);\n vector.first \/= length;\n vector.second \/= length;\n return {vector.first * range, vector.second * range};\n}\n\nfloat Combat::get_range_to(const EntitySystem& entitySystem, Entity character, Entity target) {\n const auto& char_pos = entitySystem.get_component(character);\n const auto& target_pos = entitySystem.get_component(target);\n \n const float dx = char_pos.x - target_pos.x;\n const float dy = char_pos.y - target_pos.y;\n \n return std::sqrt(dx * dx + dy * dy);\n}\n\nvoid Combat::attack(EntitySystem& entitySystem, Entity entity, const CliAttack& packet) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Combat::attack\");\n logger->trace(\"entity {}, target {}\", entity, packet.get_targetId());\n\n const auto& basicInfo = entitySystem.get_component(entity);\n const auto& pos = entitySystem.get_component(entity);\n const auto& stats = entitySystem.get_component(entity);\n \n if (packet.get_targetId()) {\n Entity t = entitySystem.get_entity_from_id(packet.get_targetId());\n if (t != entt::null) {\n auto& target = entitySystem.add_or_replace_component(entity);\n target.target = t;\n \n \/\/TODO: Check distance to target, if not in attack range, move into max attack range\n if(get_range_to(entitySystem, entity, t) > 1)\n {\n auto& dest = entitySystem.add_or_replace_component(entity);\n auto npos = get_range_position(entitySystem, entity, t);\n dest.x = npos.first;\n dest.y = npos.second;\n dest.z = 0;\n \n const float dx = pos.x - dest.x;\n const float dy = pos.y - dest.y;\n dest.dist = std::sqrt(dx * dx + dy * dy);\n }\n \n \/\/ This packet acts as an attack and mouse_cmd all in one, we don't want the mouse_cmd portion \n \/\/ of it as it can cause some issues with attack animations going off before it should\n \/\/ auto p = SrvAttack::create(basicInfo.id, packet.get_targetId());\n \/\/ p.set_x(dest.x);\n \/\/ p.set_y(dest.y);\n \/\/ p.set_distance(dest.dist);\n \/\/ entitySystem.send_nearby(entity, p);\n }\n }\n}\n\nvoid Combat::update(EntitySystem& entitySystem, Entity entity) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n const auto& basicInfo = entitySystem.get_component(entity);\n const auto& pos = entitySystem.get_component(entity);\n auto& life = entitySystem.get_component(entity);\n \n \/\/TODO:: Update buffs\n \/\/TODO:: Update HP\n \n if(entitySystem.has_component(entity) == true)\n {\n auto& queuedDamage = entitySystem.get_component(entity);\n int32_t adjusted_hp = life.hp;\n uint32_t total_applied_damage = 0;\n \n for(auto attack : queuedDamage.damage_)\n {\n if(attack.apply_) {\n \/\/ We waited at least one update before applying damage, apply it now\n \/\/TODO:: Apply damage to this entity\n Entity attacker = entitySystem.get_entity_from_id(attack.attacker_);\n logger->debug(\"Applying damage to entity {} {}\", basicInfo.name, basicInfo.id);\n \n if((adjusted_hp - attack.value_) <= 0) {\n logger->debug(\"Entity {} {} will die from {} damage\", basicInfo.name, basicInfo.id, attack.value_);\n total_applied_damage = attack.value_ + adjusted_hp;\n adjusted_hp = 0;\n \/\/TODO: Credit this attacker as the one who killed this entity.\n } else {\n total_applied_damage += attack.value_;\n adjusted_hp -= attack.value_;\n }\n \n if(adjusted_hp <= 0) {\n \/\/TODO: Get dropped item data here and send it with the DAMAGE packet\n attack.action_ &= ~DAMAGE_ACTION_HIT;\n attack.action_ |= DAMAGE_ACTION_DEAD;\n auto p = SrvDamage::create(attack.attacker_, basicInfo.id, attack.value_ + 30000, attack.action_);\n entitySystem.send_nearby(entity, p);\n \n \/\/ remove components that we can't have if we are dead!\n entitySystem.remove_component(entity);\n entitySystem.remove_component(entity);\n entitySystem.remove_component(entity);\n } else {\n logger->debug(\"applied {} damage to entity {} {}.\", attack.value_, basicInfo.name, basicInfo.id);\n \n auto p = SrvDamage::create(attack.attacker_, basicInfo.id, attack.value_, attack.action_);\n entitySystem.send_to(entity, p);\n entitySystem.send_to(attacker, p);\n }\n \n \/\/ Reset the damage value to 0 for next pass\n attack.value_ = 0;\n } else {\n \/\/ Apply any new damage on next update\n attack.apply_ = true;\n }\n }\n }\n \n \/\/ Check to see if we have a target component\n if(entitySystem.has_component(entity) == true)\n {\n auto& target = entitySystem.get_component(entity);\n \/\/ Are we in attack range?\n \/\/TODO:: Update apply damage to target\n }\n}\n\nRoseCommon::Entity Combat::get_closest_spawn(EntitySystem& entitySystem, RoseCommon::Entity player) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Combat::get_closest_spawn start\");\n const auto& position = entitySystem.get_component(player);\n \n RoseCommon::Entity closest = {};\n float closestDist = 999999999999;\n \n for (RoseCommon::Entity entity : entitySystem.get_entities_with_components()) {\n const auto& spawnPosition = entitySystem.get_component(entity);\n \n if(spawnPosition.map != position.map) continue;\n \n float dx = spawnPosition.x - position.x;\n float dy = spawnPosition.y - position.y;\n float distance = std::sqrt(dx * dx + dy * dy);\n \n if(distance < closestDist) {\n closest = entity;\n closestDist = distance;\n }\n }\n logger->trace(\"Combat::get_closest_spawn end\");\n return closest;\n}\n\nRoseCommon::Entity Combat::get_saved_spawn(EntitySystem& entitySystem, RoseCommon::Entity player) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Combat::get_saved_spawn start\");\n const auto& position = entitySystem.get_component(player);\n\n for (RoseCommon::Entity entity : entitySystem.get_entities_with_components()) {\n const auto& spawninfo = entitySystem.get_component(entity);\n if(spawninfo.type == Component::PlayerSpawn::RESPAWN_POINT) {\n const auto& spawnPosition = entitySystem.get_component(entity);\n\n if(spawnPosition.map == position.spawn)\n return entity;\n }\n }\n \n logger->trace(\"Combat::get_saved_spawn unable to find the saved spawn point\");\n return {};\n}\n\nRoseCommon::Entity Combat::get_start_spawn(EntitySystem& entitySystem) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Combat::get_start_spawn start\");\n for (RoseCommon::Entity entity : entitySystem.get_entities_with_components()) {\n const auto& spawninfo = entitySystem.get_component(entity);\n \n if(spawninfo.type == Component::PlayerSpawn::START_POINT)\n return entity;\n }\n \n return {};\n}\n\nvoid Combat::revive(EntitySystem& entitySystem, Entity entity, const RoseCommon::Packet::CliReviveReq& packet) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Combat::revive\");\n \n const auto& basicInfo = entitySystem.get_component(entity);\n const auto& pos = entitySystem.get_component(entity);\n auto& life = entitySystem.get_component(entity);\n auto& magic = entitySystem.get_component(entity);\n \n uint16_t map_id = pos.map;\n float x = 0.f, y = 0.f;\n \n switch(packet.get_reviveType())\n {\n case CliReviveReq::ReviveRequest::REVIVE_POSITION: \n {\n if (Entity e = get_closest_spawn(entitySystem, entity); e) {\n auto& dest = entitySystem.get_component(e);\n x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n }\n break;\n }\n case CliReviveReq::ReviveRequest::SAVE_POSITION: \n {\n if (Entity e = get_saved_spawn(entitySystem, entity); e) {\n auto& dest = entitySystem.get_component(e);\n \n if(dest.map == 20 && basicInfo.job) {\n if (Entity e = get_closest_spawn(entitySystem, entity); e) {\n auto& dest = entitySystem.get_component(e);\n x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n }\n break;\n }\n \n if(pos.map != dest.map) {\n map_id = dest.map;\n }\n x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n }\n break;\n }\n case CliReviveReq::ReviveRequest::START_POSITION: \n {\n if (Entity e = get_start_spawn(entitySystem); e) {\n auto& dest = entitySystem.get_component(e);\n x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n }\n break;\n }\n case CliReviveReq::ReviveRequest::CURRENT_POSITION: \n {\n x = pos.x;\n y = pos.y;\n break;\n }\n default:\n {\n logger->warn(\"Combat::revive player {} sent a revive type that doesn't exist...\", basicInfo.name);\n break;\n }\n }\n \n life.hp = (life.maxHp * 0.3f);\n magic.mp = 0;\n\n entitySystem.teleport_entity(entity, x, y, map_id);\n}Cleanup queued damage that has been applied already#include \n#include \"combat\/combat.h\"\n\n#include \"random.h\"\n#include \"logconsole.h\"\n#include \"dataconsts.h\"\n#include \"entity_system.h\"\n\n#include \"srv_attack.h\"\n#include \"srv_damage.h\"\n#include \"srv_hp_reply.h\"\n\n#include \"components\/basic_info.h\"\n#include \"components\/destination.h\"\n#include \"components\/life.h\"\n#include \"components\/magic.h\"\n#include \"components\/player_spawn.h\"\n#include \"components\/position.h\"\n#include \"components\/target.h\"\n#include \"components\/damage.h\"\n#include \"components\/skills.h\"\n#include \"components\/stamina.h\"\n#include \"components\/stats.h\"\n\n#include \n\nusing namespace RoseCommon;\nusing namespace RoseCommon::Packet;\n\n\nvoid Combat::hp_request(EntitySystem& entitySystem, Entity entity, const CliHpReq& packet) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n if (packet.get_targetId()) {\n Entity t = entitySystem.get_entity_from_id(packet.get_targetId());\n if (t != entt::null) {\n const auto& life = entitySystem.get_component(t);\n \n auto p = SrvHpReply::create(packet.get_targetId(), life.hp);\n entitySystem.send_to(entity, p);\n }\n }\n}\n\n\nstd::pair Combat::get_range_position(const EntitySystem& entitySystem, Entity character, Entity target, float range) {\n const auto& char_pos = entitySystem.get_component(character);\n const auto& target_pos = entitySystem.get_component(target);\n std::pair vector{char_pos.x - target_pos.x, char_pos.y - target_pos.y};\n const float length = sqrt(vector.first * vector.first + vector.second * vector.second);\n vector.first \/= length;\n vector.second \/= length;\n return {vector.first * range, vector.second * range};\n}\n\nfloat Combat::get_range_to(const EntitySystem& entitySystem, Entity character, Entity target) {\n const auto& char_pos = entitySystem.get_component(character);\n const auto& target_pos = entitySystem.get_component(target);\n \n const float dx = char_pos.x - target_pos.x;\n const float dy = char_pos.y - target_pos.y;\n \n return std::sqrt(dx * dx + dy * dy);\n}\n\nvoid Combat::attack(EntitySystem& entitySystem, Entity entity, const CliAttack& packet) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Combat::attack\");\n logger->trace(\"entity {}, target {}\", entity, packet.get_targetId());\n\n const auto& basicInfo = entitySystem.get_component(entity);\n const auto& pos = entitySystem.get_component(entity);\n const auto& stats = entitySystem.get_component(entity);\n \n if (packet.get_targetId()) {\n Entity t = entitySystem.get_entity_from_id(packet.get_targetId());\n if (t != entt::null) {\n auto& target = entitySystem.add_or_replace_component(entity);\n target.target = t;\n \n \/\/TODO: Check distance to target, if not in attack range, move into max attack range\n if(get_range_to(entitySystem, entity, t) > 1)\n {\n auto& dest = entitySystem.add_or_replace_component(entity);\n auto npos = get_range_position(entitySystem, entity, t);\n dest.x = npos.first;\n dest.y = npos.second;\n dest.z = 0;\n \n const float dx = pos.x - dest.x;\n const float dy = pos.y - dest.y;\n dest.dist = std::sqrt(dx * dx + dy * dy);\n }\n \n \/\/ This packet acts as an attack and mouse_cmd all in one, we don't want the mouse_cmd portion \n \/\/ of it as it can cause some issues with attack animations going off before it should\n \/\/ auto p = SrvAttack::create(basicInfo.id, packet.get_targetId());\n \/\/ p.set_x(dest.x);\n \/\/ p.set_y(dest.y);\n \/\/ p.set_distance(dest.dist);\n \/\/ entitySystem.send_nearby(entity, p);\n }\n }\n}\n\nvoid Combat::update(EntitySystem& entitySystem, Entity entity) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n const auto& basicInfo = entitySystem.get_component(entity);\n const auto& pos = entitySystem.get_component(entity);\n auto& life = entitySystem.get_component(entity);\n \n \/\/TODO:: Update buffs\n \/\/TODO:: Update HP\n \n if(entitySystem.has_component(entity) == true)\n {\n auto& queuedDamage = entitySystem.get_component(entity);\n int32_t adjusted_hp = life.hp;\n uint32_t total_applied_damage = 0;\n \n for(auto attack : queuedDamage.damage_)\n {\n if(attack.apply_) {\n \/\/ We waited at least one update before applying damage, apply it now\n \/\/TODO:: Apply damage to this entity\n Entity attacker = entitySystem.get_entity_from_id(attack.attacker_);\n logger->debug(\"Applying damage to entity {} {}\", basicInfo.name, basicInfo.id);\n \n if((adjusted_hp - attack.value_) <= 0) {\n logger->debug(\"Entity {} {} will die from {} damage\", basicInfo.name, basicInfo.id, attack.value_);\n total_applied_damage = attack.value_ + adjusted_hp;\n adjusted_hp = 0;\n \/\/TODO: Credit this attacker as the one who killed this entity.\n } else {\n total_applied_damage += attack.value_;\n adjusted_hp -= attack.value_;\n }\n \n if(adjusted_hp <= 0) {\n \/\/TODO: Get dropped item data here and send it with the DAMAGE packet\n attack.action_ &= ~DAMAGE_ACTION_HIT;\n attack.action_ |= DAMAGE_ACTION_DEAD;\n auto p = SrvDamage::create(attack.attacker_, basicInfo.id, attack.value_ + 30000, attack.action_);\n entitySystem.send_nearby(entity, p);\n \n \/\/ remove components that we can't have if we are dead!\n entitySystem.remove_component(entity);\n entitySystem.remove_component(entity);\n entitySystem.remove_component(entity);\n } else {\n logger->debug(\"applied {} damage to entity {} {}.\", attack.value_, basicInfo.name, basicInfo.id);\n \n auto p = SrvDamage::create(attack.attacker_, basicInfo.id, attack.value_, attack.action_);\n entitySystem.send_to(entity, p);\n entitySystem.send_to(attacker, p);\n }\n \n \/\/ Reset the damage value to 0 for next pass\n attack.value_ = 0;\n } else {\n \/\/ Apply any new damage on next update\n attack.apply_ = true;\n }\n }\n \n std::remove_if(queuedDamage.damage_.begin(), queuedDamage.damage_.end(), [] (auto &i) { return (true == i.apply_ && 0 == i.value_); });\n }\n \n \/\/ Check to see if we have a target component\n if(entitySystem.has_component(entity) == true)\n {\n auto& target = entitySystem.get_component(entity);\n \/\/ Are we in attack range?\n \/\/TODO:: Update apply damage to target\n }\n}\n\nRoseCommon::Entity Combat::get_closest_spawn(EntitySystem& entitySystem, RoseCommon::Entity player) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Combat::get_closest_spawn start\");\n const auto& position = entitySystem.get_component(player);\n \n RoseCommon::Entity closest = {};\n float closestDist = 999999999999;\n \n for (RoseCommon::Entity entity : entitySystem.get_entities_with_components()) {\n const auto& spawnPosition = entitySystem.get_component(entity);\n \n if(spawnPosition.map != position.map) continue;\n \n float dx = spawnPosition.x - position.x;\n float dy = spawnPosition.y - position.y;\n float distance = std::sqrt(dx * dx + dy * dy);\n \n if(distance < closestDist) {\n closest = entity;\n closestDist = distance;\n }\n }\n logger->trace(\"Combat::get_closest_spawn end\");\n return closest;\n}\n\nRoseCommon::Entity Combat::get_saved_spawn(EntitySystem& entitySystem, RoseCommon::Entity player) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Combat::get_saved_spawn start\");\n const auto& position = entitySystem.get_component(player);\n\n for (RoseCommon::Entity entity : entitySystem.get_entities_with_components()) {\n const auto& spawninfo = entitySystem.get_component(entity);\n if(spawninfo.type == Component::PlayerSpawn::RESPAWN_POINT) {\n const auto& spawnPosition = entitySystem.get_component(entity);\n\n if(spawnPosition.map == position.spawn)\n return entity;\n }\n }\n \n logger->trace(\"Combat::get_saved_spawn unable to find the saved spawn point\");\n return {};\n}\n\nRoseCommon::Entity Combat::get_start_spawn(EntitySystem& entitySystem) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Combat::get_start_spawn start\");\n for (RoseCommon::Entity entity : entitySystem.get_entities_with_components()) {\n const auto& spawninfo = entitySystem.get_component(entity);\n \n if(spawninfo.type == Component::PlayerSpawn::START_POINT)\n return entity;\n }\n \n return {};\n}\n\nvoid Combat::revive(EntitySystem& entitySystem, Entity entity, const RoseCommon::Packet::CliReviveReq& packet) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Combat::revive\");\n \n const auto& basicInfo = entitySystem.get_component(entity);\n const auto& pos = entitySystem.get_component(entity);\n auto& life = entitySystem.get_component(entity);\n auto& magic = entitySystem.get_component(entity);\n \n uint16_t map_id = pos.map;\n float x = 0.f, y = 0.f;\n \n switch(packet.get_reviveType())\n {\n case CliReviveReq::ReviveRequest::REVIVE_POSITION: \n {\n if (Entity e = get_closest_spawn(entitySystem, entity); e) {\n auto& dest = entitySystem.get_component(e);\n x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n }\n break;\n }\n case CliReviveReq::ReviveRequest::SAVE_POSITION: \n {\n if (Entity e = get_saved_spawn(entitySystem, entity); e) {\n auto& dest = entitySystem.get_component(e);\n \n if(dest.map == 20 && basicInfo.job) {\n if (Entity e = get_closest_spawn(entitySystem, entity); e) {\n auto& dest = entitySystem.get_component(e);\n x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n }\n break;\n }\n \n if(pos.map != dest.map) {\n map_id = dest.map;\n }\n x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n }\n break;\n }\n case CliReviveReq::ReviveRequest::START_POSITION: \n {\n if (Entity e = get_start_spawn(entitySystem); e) {\n auto& dest = entitySystem.get_component(e);\n x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500);\n }\n break;\n }\n case CliReviveReq::ReviveRequest::CURRENT_POSITION: \n {\n x = pos.x;\n y = pos.y;\n break;\n }\n default:\n {\n logger->warn(\"Combat::revive player {} sent a revive type that doesn't exist...\", basicInfo.name);\n break;\n }\n }\n \n life.hp = (life.maxHp * 0.3f);\n magic.mp = 0;\n\n entitySystem.teleport_entity(entity, x, y, map_id);\n}<|endoftext|>"} {"text":"\/*\nResembla: Word-based Japanese similar sentence search library\nhttps:\/\/github.com\/tuem\/resembla\n\nCopyright 2017 Takashi Uemura\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 RESEMBLA_LETTER_WEIGHT_HPP\n#define RESEMBLA_LETTER_WEIGHT_HPP\n\n#include \n#include \n#include \n#include \n\n#include \"..\/string_util.hpp\"\n\nnamespace resembla {\n\n\/\/ simple weight function for sets of letters\ntemplate\nstruct LetterWeight\n{\n using value_type = typename string_type::value_type;\n\n LetterWeight(double base_weight, double delete_insert_ratio, const std::string& letter_weight_file_path):\n base_weight(base_weight), delete_insert_ratio(delete_insert_ratio)\n {\n if(letter_weight_file_path.empty()){\n return;\n }\n\n std::basic_ifstream ifs(letter_weight_file_path);\n if(ifs.fail()){\n throw std::runtime_error(\"input file is not available: \" + letter_weight_file_path);\n }\n\n while(ifs.good()){\n string_type line;\n std::getline(ifs, line);\n if(ifs.eof() || line.length() == 0){\n break;\n }\n\n auto columns = split(line, column_delimiter());\n if(columns.size() < 2){\n throw std::runtime_error(\"invalid line in \" + letter_weight_file_path + \": \" + cast_string(line));\n }\n\n auto letters= columns[0];\n auto weight = std::stod(columns[1]);\n for(size_t i = 0; i < letters.size(); ++i){\n letter_weights[letters[i]] = weight;\n }\n }\n }\n\n double operator()(const value_type c, bool is_original = false, size_t total = -1, size_t position = -1) const\n {\n (void)total;\n (void)position;\n\n double w = base_weight;\n if(is_original){\n w *= delete_insert_ratio;\n }\n\n auto p = letter_weights.find(c);\n if(p != std::end(letter_weights)){\n w *= p->second;\n }\n\n return w;\n }\n\nprotected:\n double base_weight;\n double delete_insert_ratio;\n\n std::unordered_map letter_weights;\n};\n\n}\n#endif\nuse csv_reader in letter_weight\/*\nResembla: Word-based Japanese similar sentence search library\nhttps:\/\/github.com\/tuem\/resembla\n\nCopyright 2017 Takashi Uemura\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 RESEMBLA_LETTER_WEIGHT_HPP\n#define RESEMBLA_LETTER_WEIGHT_HPP\n\n#include \n#include \n#include \n\n#include \"..\/string_util.hpp\"\n#include \"..\/csv_reader.hpp\"\n\nnamespace resembla {\n\n\/\/ simple weight function for sets of letters\ntemplate\nstruct LetterWeight\n{\n using value_type = typename string_type::value_type;\n\n LetterWeight(double base_weight, double delete_insert_ratio, const std::string& letter_weight_file_path):\n base_weight(base_weight), delete_insert_ratio(delete_insert_ratio)\n {\n if(letter_weight_file_path.empty()){\n return;\n }\n\n for(const auto& columns: CsvReader<>(letter_weight_file_path, 2)){\n auto letters = cast_string(columns[0]);\n auto weight = std::stod(columns[1]);\n\n for(auto c: letters){\n letter_weights[c] = weight;\n }\n }\n }\n\n double operator()(const value_type c, bool is_original = false, size_t total = -1, size_t position = -1) const\n {\n (void)total;\n (void)position;\n\n double w = base_weight;\n if(is_original){\n w *= delete_insert_ratio;\n }\n\n auto p = letter_weights.find(c);\n if(p != std::end(letter_weights)){\n w *= p->second;\n }\n\n return w;\n }\n\nprotected:\n double base_weight;\n double delete_insert_ratio;\n\n std::unordered_map letter_weights;\n};\n\n}\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \/\/ std::bad_cast\n\nusing namespace aikido::statespace;\nusing namespace std;\n\nTEST(RealVectorStateSpace, Compose)\n{\n RealVectorStateSpace rvss(3);\n\n RealVectorStateSpace::ScopedState s1 = rvss.createState();\n s1.getValue() = Eigen::Vector3d(1, 2, 3);\n\n RealVectorStateSpace::ScopedState s2 = rvss.createState();\n s2.getValue() = Eigen::Vector3d(2, 3, 4);\n\n RealVectorStateSpace::ScopedState out = rvss.createState();\n rvss.compose(*s1, *s2, *out);\n\n EXPECT_TRUE(out.getValue().isApprox(Eigen::Vector3d(3, 5, 7)));\n\n}\n\n\nTEST(SO2StateSpace, Compose)\n{\n SO2StateSpace::State s1(M_PI\/4);\n SO2StateSpace::State s2(M_PI\/2);\n SO2StateSpace::State out;\n SO2StateSpace::State expected(3.0\/4.0*M_PI);\n\n SO2StateSpace so2;\n so2.compose(s1, s2, out);\n\n EXPECT_TRUE(out.getRotation().isApprox(expected.getRotation()));\n\n}\n\n\nTEST(SO3StateSpace, Compose)\n{\n SO3StateSpace::State identity;\n EXPECT_TRUE(identity.getQuaternion().isApprox(\n Eigen::Quaterniond::Identity()));\n\n SO3StateSpace::State s2(Eigen::Quaterniond(\n Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitZ())));\n SO3StateSpace::State s3(Eigen::Quaterniond(\n Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitZ())));\n SO3StateSpace::State expected(Eigen::Quaterniond(\n Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitZ())));\n\n SO3StateSpace::State out;\n SO3StateSpace so3;\n so3.compose(s2, s3, out);\n\n EXPECT_TRUE(expected.getQuaternion().isApprox(out.getQuaternion()));\n}\n\nTEST(SE2StateSpace, Compose)\n{\n SE2StateSpace space;\n\n SE2StateSpace::ScopedState identity(&space);\n EXPECT_TRUE(identity.getIsometry().isApprox(Eigen::Isometry2d::Identity()));\n\n Eigen::Isometry2d pose2 = Eigen::Isometry2d::Identity();\n pose2.rotate(Eigen::Rotation2Dd(M_PI_2));\n SE2StateSpace::ScopedState state2(&space);\n state2.setIsometry(pose2);\n\n Eigen::Isometry2d pose3 = Eigen::Isometry2d::Identity();\n pose3.rotate(Eigen::Rotation2Dd(M_PI_4));\n SE2StateSpace::ScopedState state3(&space);\n state3.setIsometry(pose3);\n\n Eigen::Isometry2d expected_pose = Eigen::Isometry2d::Identity();\n expected_pose.rotate(Eigen::Rotation2Dd(3. * M_PI_4));\n\n SE2StateSpace::ScopedState out(&space);\n space.compose(*state2, *state3, *out);\n\n EXPECT_TRUE(expected_pose.isApprox(out.getIsometry()));\n}\n\nTEST(SE3StateSpace, Compose)\n{\n SE3StateSpace space;\n\n SE3StateSpace::ScopedState identity(&space);\n EXPECT_TRUE(identity.getIsometry().isApprox(Eigen::Isometry3d::Identity()));\n\n Eigen::Isometry3d pose2 = Eigen::Isometry3d::Identity();\n pose2.rotate(Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitX()));\n SE3StateSpace::ScopedState s2(&space);\n s2.setIsometry(pose2);\n\n Eigen::Isometry3d pose3 = Eigen::Isometry3d::Identity();\n pose3.rotate(Eigen::AngleAxisd(M_PI_4, Eigen::Vector3d::UnitX()));\n SE3StateSpace::ScopedState s3(&space);\n s2.setIsometry(pose3);\n\n Eigen::Isometry3d expected = Eigen::Isometry3d::Identity();\n expected.rotate(Eigen::AngleAxisd(3. * M_PI_4, Eigen::Vector3d::UnitX()));\n\n SE3StateSpace::ScopedState out(&space);\n space.compose(*s2, *s3, *out);\n\n std::cout << \"expected\\n\" << expected.matrix() << \"\\n\"\n << \"actual\\n\" << out.getIsometry().matrix() << \"\\n\"\n << std::endl;\n\n EXPECT_TRUE(expected.isApprox(out.getIsometry()));\n}\n\n\nTEST(CompoundStateSpace, Compose)\n{\n using Eigen::Vector2d;\n\n CompoundStateSpace space({\n std::make_shared(),\n std::make_shared(2)\n });\n\n \/\/ TODO: This syntax is _really_ bad.\n CompoundStateSpace::ScopedState s1 = space.createState();\n s1.getSubState(0).setAngle(M_PI_2);\n s1.getSubStateHandle(1).getValue() = Vector2d(3., 4.);\n\n CompoundStateSpace::ScopedState s2 = space.createState();\n space.getSubState(*s2, 0).setAngle(M_PI_2);\n space.getSubSpace(1).getValue(\n space.getSubState(*s2, 1)) = Vector2d(5., 10.);\n\n CompoundStateSpace::ScopedState out = space.createState();\n space.compose(*s1, *s2, *out);\n\n const double out1 = out.getSubState(0).getAngle();\n EXPECT_DOUBLE_EQ(M_PI, out1);\n\n const Vector2d out2 = out.getSubStateHandle(1).getValue();\n EXPECT_TRUE(out2.isApprox(Vector2d(8., 14.)));\n}\nTweaks to test.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \/\/ std::bad_cast\n\nusing namespace aikido::statespace;\nusing namespace std;\n\nTEST(RealVectorStateSpace, Compose)\n{\n RealVectorStateSpace rvss(3);\n\n RealVectorStateSpace::ScopedState s1 = rvss.createState();\n s1.getValue() = Eigen::Vector3d(1, 2, 3);\n\n RealVectorStateSpace::ScopedState s2 = rvss.createState();\n s2.getValue() = Eigen::Vector3d(2, 3, 4);\n\n RealVectorStateSpace::ScopedState out = rvss.createState();\n rvss.compose(*s1, *s2, *out);\n\n EXPECT_TRUE(out.getValue().isApprox(Eigen::Vector3d(3, 5, 7)));\n\n}\n\n\nTEST(SO2StateSpace, Compose)\n{\n SO2StateSpace::State s1(M_PI\/4);\n SO2StateSpace::State s2(M_PI\/2);\n SO2StateSpace::State out;\n SO2StateSpace::State expected(3.0\/4.0*M_PI);\n\n SO2StateSpace so2;\n so2.compose(s1, s2, out);\n\n EXPECT_TRUE(out.getRotation().isApprox(expected.getRotation()));\n\n}\n\n\nTEST(SO3StateSpace, Compose)\n{\n SO3StateSpace::State identity;\n EXPECT_TRUE(identity.getQuaternion().isApprox(\n Eigen::Quaterniond::Identity()));\n\n SO3StateSpace::State s2(Eigen::Quaterniond(\n Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitZ())));\n SO3StateSpace::State s3(Eigen::Quaterniond(\n Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitZ())));\n SO3StateSpace::State expected(Eigen::Quaterniond(\n Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitZ())));\n\n SO3StateSpace::State out;\n SO3StateSpace so3;\n so3.compose(s2, s3, out);\n\n EXPECT_TRUE(expected.getQuaternion().isApprox(out.getQuaternion()));\n}\n\nTEST(SE2StateSpace, Compose)\n{\n SE2StateSpace space;\n\n SE2StateSpace::ScopedState identity(&space);\n EXPECT_TRUE(identity.getIsometry().isApprox(Eigen::Isometry2d::Identity()));\n\n Eigen::Isometry2d pose2 = Eigen::Isometry2d::Identity();\n pose2.rotate(Eigen::Rotation2Dd(M_PI_2));\n SE2StateSpace::ScopedState state2(&space);\n state2.setIsometry(pose2);\n\n Eigen::Isometry2d pose3 = Eigen::Isometry2d::Identity();\n pose3.rotate(Eigen::Rotation2Dd(M_PI_4));\n SE2StateSpace::ScopedState state3(&space);\n state3.setIsometry(pose3);\n\n Eigen::Isometry2d expected_pose = Eigen::Isometry2d::Identity();\n expected_pose.rotate(Eigen::Rotation2Dd(3. * M_PI_4));\n\n SE2StateSpace::ScopedState out(&space);\n space.compose(*state2, *state3, *out);\n\n EXPECT_TRUE(expected_pose.isApprox(out.getIsometry()));\n}\n\nTEST(SE3StateSpace, Compose)\n{\n SE3StateSpace space;\n\n SE3StateSpace::ScopedState identity(&space);\n EXPECT_TRUE(identity.getIsometry().isApprox(Eigen::Isometry3d::Identity()));\n\n Eigen::Isometry3d pose2 = Eigen::Isometry3d::Identity();\n pose2.rotate(Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitX()));\n SE3StateSpace::ScopedState s2(&space);\n s2.setIsometry(pose2);\n\n Eigen::Isometry3d pose3 = Eigen::Isometry3d::Identity();\n pose3.rotate(Eigen::AngleAxisd(M_PI_4, Eigen::Vector3d::UnitX()));\n SE3StateSpace::ScopedState s3(&space);\n s2.setIsometry(pose3);\n\n Eigen::Isometry3d expected = pose2 * pose3;\n\n SE3StateSpace::ScopedState out(&space);\n space.compose(*s2, *s3, *out);\n\n std::cout << \"expected\\n\" << expected.matrix() << \"\\n\"\n << \"actual\\n\" << out.getIsometry().matrix() << \"\\n\"\n << std::endl;\n\n EXPECT_TRUE(expected.isApprox(out.getIsometry()));\n}\n\n\nTEST(CompoundStateSpace, Compose)\n{\n using Eigen::Vector2d;\n\n CompoundStateSpace space({\n std::make_shared(),\n std::make_shared(2)\n });\n\n \/\/ TODO: This syntax is _really_ bad.\n CompoundStateSpace::ScopedState s1 = space.createState();\n s1.getSubState(0).setAngle(M_PI_2);\n s1.getSubStateHandle(1).getValue() = Vector2d(3., 4.);\n\n CompoundStateSpace::ScopedState s2 = space.createState();\n space.getSubState(*s2, 0).setAngle(M_PI_2);\n space.getSubSpace(1).getValue(\n space.getSubState(*s2, 1)) = Vector2d(5., 10.);\n\n CompoundStateSpace::ScopedState out = space.createState();\n space.compose(*s1, *s2, *out);\n\n const double out1 = out.getSubState(0).getAngle();\n EXPECT_DOUBLE_EQ(M_PI, out1);\n\n const Vector2d out2 = out.getSubStateHandle(1).getValue();\n EXPECT_TRUE(out2.isApprox(Vector2d(8., 14.)));\n}\n<|endoftext|>"} {"text":"#include \"mem\/cache\/tags\/utillru.hh\"\n#include \"base\/intmath.hh\"\n#include \"debug\/CacheRepl.hh\"\n#include \"mem\/cache\/tags\/cacheset.hh\"\n#include \"mem\/cache\/tags\/lru.hh\"\n#include \"mem\/cache\/base.hh\"\n#include \"sim\/core.hh\"\n#include \"mem\/cache\/blk.hh\"\n#include \n\nUTILLRU::UTILLRU( unsigned _numSets,\n unsigned _blkSize,\n unsigned _assoc,\n unsigned _hit_latency,\n\t\tunsigned _L_assoc)\n : LRU(_numSets, _blkSize, _assoc, _hit_latency )\n{\n\tL_assoc = _L_assoc;\n\tH_assoc = _assoc - L_assoc;\n\tassoc = _assoc;\n\t\/\/ umon counters\n\tumon_counters = new unsigned*[2];\n\tfor (unsigned i = 0; i < 2; i++)\n\t\tumon_counters[i] = new unsigned[assoc];\n\t\n\tfor (unsigned i = 0; i < 2; i++)\n\t\tfor (unsigned j = 0; j < assoc; j++) \n\t\t\tumon_counters[i][j] = 0;\n\t\n\tinit_sets();\n}\n\nvoid UTILLRU::reset_umon()\n{\n\tfor (unsigned i = 0; i < 2; i++)\n\t\tfor (unsigned j = 0; j < assoc; j++) \n\t\t\tumon_counters[i][j] = umon_counters[i][j]\/2;\n}\n\nunsigned UTILLRU::curr_L_assoc()\n{\n\treturn L_assoc;\n}\n\nunsigned UTILLRU::lookup_umon(int index, uint64_t tid)\n{\n\treturn umon_counters[tid][index];\n}\n\nint\nUTILLRU::assoc_of_tc( int tcid ){\n if (tcid == 0) return L_assoc;\n\telse return H_assoc;\n}\n\nCacheSet\nUTILLRU::get_set( int setnum, uint64_t tid, Addr addr ){\n return sets[setnum];\n}\n\nvoid\nUTILLRU::init_sets(){\n sets = new CacheSet[numSets];\n\n numBlocks = numSets * assoc;\n blks = new BlkType[numBlocks];\n dataBlks = new uint8_t[numBlocks * blkSize];\n\n unsigned blkIndex = 0;\n for( unsigned i = 0; i< numSets; i++ ){\n sets[i].assoc = assoc;\n sets[i].blks = new BlkType*[assoc];\n for( unsigned j = 0; jdata = &dataBlks[blkSize*blkIndex];\n ++blkIndex;\n\n blk->status = 0;\n blk->tag = j;\n blk->whenReady = 0;\n blk->isTouched = false;\n blk->size = blkSize;\n blk->set = i;\n\t\t\t\/\/ initialize the threadID\n\t\t\tblk->threadID = 0;\n sets[i].blks[j]=blk;\n }\n }\n\t\n\t\/\/ shadow tags for monitoring\n\tumon_sets = new CacheSet*[2];\n\tfor( int i=0; i< 2; i++ ){ umon_sets[i] = new CacheSet[numSets]; }\n\tumon_blks = new BlkType*[2];\n\tfor( int i=0; i< 2; i++ ){ umon_blks[i] = new BlkType[numBlocks]; }\n\t\n\tfor( unsigned tc=0; tc<2; tc++ ){\n\t\tblkIndex = 0;\n\t\tfor( unsigned i = 0; i < numSets; i++){\n\t\t\tumon_sets[tc][i].assoc = assoc;\n\t\t\tumon_sets[tc][i].blks = new BlkType*[assoc];\n\t for( unsigned j = 0; jdata = 0;\n\t ++blkIndex;\n\n\t blk->status = 0;\n\t blk->tag = j;\n\t blk->whenReady = 0;\n\t blk->isTouched = false;\n\t blk->size = blkSize;\n\t blk->set = i;\n\t\t\t\t\/\/ initialize the threadID\n\t\t\t\tblk->threadID = tc;\n\t umon_sets[tc][i].blks[j]=blk;\n\t }\n\t\t}\n\t}\n}\n\n\/\/ increase the size of Low partition\nunsigned\nUTILLRU::inc_size(){\n\tif(H_assoc == 1) return 0;\n\t\n\tL_assoc += 1;\n\tH_assoc -= 1;\n\t\n\tfprintf(stderr, \"L_assoc = %2d H_assoc = %2d\\n\", L_assoc, H_assoc);\n\t\n\treturn numSets;\n}\n\nunsigned \nUTILLRU::dec_size(){\n\tif(L_assoc == 1) return 0;\n\t\n\tL_assoc -= 1;\n\tH_assoc += 1;\n\t\n\tfprintf(stderr, \"L_assoc = %2d H_assoc = %2d\\n\", L_assoc, H_assoc);\n\t\n\treturn numSets;\n}\n\nUTILLRU::BlkType*\nUTILLRU::accessBlock(Addr addr, int &lat, int master_id, uint64_t tid)\n{\n Addr tag = extractTag(addr);\n unsigned set = extractSet(addr);\n \/\/ BlkType *blk = sets[set].findBlk(tag);\n BlkType *blk = get_set(set,tid,addr).findBlk(tag);\n lat = hitLatency;\n if (blk != 0 ) {\n \/\/ move this block to head of the MRU list\n get_set(set,tid,addr).moveToHead(blk);\n DPRINTF(CacheRepl, \"set %x: moving blk %x to MRU\\n\",\n set, regenerateBlkAddr(tag, set));\n if (blk->whenReady > curTick()\n && blk->whenReady - curTick() > hitLatency) {\n lat = blk->whenReady - curTick();\n }\n blk->refCount += 1;\n\t\t\/\/ set the used bit\n\t\tblk->isTouched = 1;\n }\n\t\n\tBlkType *umon_blk = umon_sets[tid][set].findBlk(tag);\n\tunsigned index = umon_sets[tid][set].findBlkIndex(tag);\n\t\/\/ cache hit on umon tags\n\tif (umon_blk != 0) {\n\t\tumon_counters[index]++;\n\t\tumon_sets[tid][set].moveToHead(umon_blk);\n\t}\n\t\/\/ cache miss on umon tags\n\telse {\n\t\tumon_sets[tid][set].blks[assoc-1]->tag = tag;\n\t\tumon_sets[tid][set].blks[assoc-1]->status = BlkValid | BlkReadable;\n\t\tumon_sets[tid][set].moveToHead(umon_sets[tid][set].blks[assoc-1]);\n\t}\n\t\n return blk;\n}\n\nUTILLRU::BlkType*\nUTILLRU::findBlock(Addr addr, uint64_t tid)\n{\n Addr tag = extractTag(addr);\n unsigned set = extractSet(addr);\n BlkType *blk = get_set(set,tid,addr).findBlk(tag);\n return blk;\n}\n\nUTILLRU::BlkType*\nUTILLRU::findVictim(Addr addr, PacketList &writebacks, uint64_t tid)\n{\n unsigned set = extractSet(addr);\n \/\/ grab a replacement candidate\n BlkType *blk = get_set(set,tid,addr).findVictim(tid, L_assoc);\n\n if (blk->isValid()) {\n DPRINTF(CacheRepl, \"set %x: selecting blk %x for replacement\\n\",\n set, regenerateBlkAddr(blk->tag, set));\n }\n return blk;\n}\n\nvoid\nUTILLRU::invalidateBlk(BlkType *blk, uint64_t tid)\n{\n if (blk) {\n if (blk->isValid()) {\n tagsInUse--;\n assert(blk->srcMasterId < cache->system->maxMasters());\n occupancies[blk->srcMasterId]--;\n blk->srcMasterId = Request::invldMasterId;\n unsigned set = blk->set;\n\t\t\tget_set(set,tid,blk->set).moveToTail(blk);\n }\n blk->status = 0;\n blk->isTouched = false;\n blk->clearLoadLocks();\n\n \/\/ should be evicted before valid blocks\n \/\/unsigned set = blk->set;\n \/\/sets[set].moveToTail(blk);\n }\n\t\n\tBlkType *umon_blk = umon_sets[tid][blk->set].findBlk(blk->tag);\n\tif (umon_blk != 0) {\n\t\tif (umon_blk->isValid()) {\n\t\t\tumon_sets[tid][blk->set].moveToTail(umon_blk);\n\t\t}\n\t\tumon_blk->status = 0;\n\t\tumon_blk->isTouched = false;\n\t}\n}fixed a segmentation fault#include \"mem\/cache\/tags\/utillru.hh\"\n#include \"base\/intmath.hh\"\n#include \"debug\/CacheRepl.hh\"\n#include \"mem\/cache\/tags\/cacheset.hh\"\n#include \"mem\/cache\/tags\/lru.hh\"\n#include \"mem\/cache\/base.hh\"\n#include \"sim\/core.hh\"\n#include \"mem\/cache\/blk.hh\"\n#include \n\nUTILLRU::UTILLRU( unsigned _numSets,\n unsigned _blkSize,\n unsigned _assoc,\n unsigned _hit_latency,\n\t\tunsigned _L_assoc)\n : LRU(_numSets, _blkSize, _assoc, _hit_latency )\n{\n\tL_assoc = _L_assoc;\n\tH_assoc = _assoc - L_assoc;\n\tassoc = _assoc;\n\t\/\/ umon counters\n\tumon_counters = new unsigned*[2];\n\tfor (unsigned i = 0; i < 2; i++)\n\t\tumon_counters[i] = new unsigned[assoc];\n\t\n\tfor (unsigned i = 0; i < 2; i++)\n\t\tfor (unsigned j = 0; j < assoc; j++) \n\t\t\tumon_counters[i][j] = 0;\n\t\n\tinit_sets();\n}\n\nvoid UTILLRU::reset_umon()\n{\n\tfor (unsigned i = 0; i < 2; i++)\n\t\tfor (unsigned j = 0; j < assoc; j++) \n\t\t\tumon_counters[i][j] = umon_counters[i][j]\/2;\n}\n\nunsigned UTILLRU::curr_L_assoc()\n{\n\treturn L_assoc;\n}\n\nunsigned UTILLRU::lookup_umon(int index, uint64_t tid)\n{\n\treturn umon_counters[tid][index];\n}\n\nint\nUTILLRU::assoc_of_tc( int tcid ){\n if (tcid == 0) return L_assoc;\n\telse return H_assoc;\n}\n\nCacheSet\nUTILLRU::get_set( int setnum, uint64_t tid, Addr addr ){\n return sets[setnum];\n}\n\nvoid\nUTILLRU::init_sets(){\n sets = new CacheSet[numSets];\n\n numBlocks = numSets * assoc;\n blks = new BlkType[numBlocks];\n dataBlks = new uint8_t[numBlocks * blkSize];\n\n unsigned blkIndex = 0;\n for( unsigned i = 0; i< numSets; i++ ){\n sets[i].assoc = assoc;\n sets[i].blks = new BlkType*[assoc];\n for( unsigned j = 0; jdata = &dataBlks[blkSize*blkIndex];\n ++blkIndex;\n\n blk->status = 0;\n blk->tag = j;\n blk->whenReady = 0;\n blk->isTouched = false;\n blk->size = blkSize;\n blk->set = i;\n\t\t\t\/\/ initialize the threadID\n\t\t\tblk->threadID = 0;\n sets[i].blks[j]=blk;\n }\n }\n\t\n\t\/\/ shadow tags for monitoring\n\tumon_sets = new CacheSet*[2];\n\tfor( int i=0; i< 2; i++ ){ umon_sets[i] = new CacheSet[numSets]; }\n\tumon_blks = new BlkType*[2];\n\tfor( int i=0; i< 2; i++ ){ umon_blks[i] = new BlkType[numBlocks]; }\n\t\n\tfor( unsigned tc=0; tc<2; tc++ ){\n\t\tblkIndex = 0;\n\t\tfor( unsigned i = 0; i < numSets; i++){\n\t\t\tumon_sets[tc][i].assoc = assoc;\n\t\t\tumon_sets[tc][i].blks = new BlkType*[assoc];\n\t for( unsigned j = 0; jdata = 0;\n\t ++blkIndex;\n\n\t blk->status = 0;\n\t blk->tag = j;\n\t blk->whenReady = 0;\n\t blk->isTouched = false;\n\t blk->size = blkSize;\n\t blk->set = i;\n\t\t\t\t\/\/ initialize the threadID\n\t\t\t\tblk->threadID = tc;\n\t umon_sets[tc][i].blks[j]=blk;\n\t }\n\t\t}\n\t}\n}\n\n\/\/ increase the size of Low partition\nunsigned\nUTILLRU::inc_size(){\n\tif(H_assoc == 1) return 0;\n\t\n\tL_assoc += 1;\n\tH_assoc -= 1;\n\t\n\tfprintf(stderr, \"L_assoc = %2d H_assoc = %2d\\n\", L_assoc, H_assoc);\n\t\n\treturn numSets;\n}\n\nunsigned \nUTILLRU::dec_size(){\n\tif(L_assoc == 1) return 0;\n\t\n\tL_assoc -= 1;\n\tH_assoc += 1;\n\t\n\tfprintf(stderr, \"L_assoc = %2d H_assoc = %2d\\n\", L_assoc, H_assoc);\n\t\n\treturn numSets;\n}\n\nUTILLRU::BlkType*\nUTILLRU::accessBlock(Addr addr, int &lat, int master_id, uint64_t tid)\n{\n Addr tag = extractTag(addr);\n unsigned set = extractSet(addr);\n \/\/ BlkType *blk = sets[set].findBlk(tag);\n BlkType *blk = get_set(set,tid,addr).findBlk(tag);\n lat = hitLatency;\n if (blk != 0 ) {\n \/\/ move this block to head of the MRU list\n get_set(set,tid,addr).moveToHead(blk);\n DPRINTF(CacheRepl, \"set %x: moving blk %x to MRU\\n\",\n set, regenerateBlkAddr(tag, set));\n if (blk->whenReady > curTick()\n && blk->whenReady - curTick() > hitLatency) {\n lat = blk->whenReady - curTick();\n }\n blk->refCount += 1;\n\t\t\/\/ set the used bit\n\t\tblk->isTouched = 1;\n }\n\t\n\tBlkType *umon_blk = umon_sets[tid][set].findBlk(tag);\n\tunsigned index = umon_sets[tid][set].findBlkIndex(tag);\n\t\/\/ cache hit on umon tags\n\tif (umon_blk != 0) {\n\t\tumon_counters[tid][index]++;\n\t\tumon_sets[tid][set].moveToHead(umon_blk);\n\t}\n\t\/\/ cache miss on umon tags\n\telse {\n\t\tumon_sets[tid][set].blks[assoc-1]->tag = tag;\n\t\tumon_sets[tid][set].blks[assoc-1]->status = BlkValid | BlkReadable;\n\t\tumon_sets[tid][set].moveToHead(umon_sets[tid][set].blks[assoc-1]);\n\t}\n\t\n return blk;\n}\n\nUTILLRU::BlkType*\nUTILLRU::findBlock(Addr addr, uint64_t tid)\n{\n Addr tag = extractTag(addr);\n unsigned set = extractSet(addr);\n BlkType *blk = get_set(set,tid,addr).findBlk(tag);\n return blk;\n}\n\nUTILLRU::BlkType*\nUTILLRU::findVictim(Addr addr, PacketList &writebacks, uint64_t tid)\n{\n unsigned set = extractSet(addr);\n \/\/ grab a replacement candidate\n BlkType *blk = get_set(set,tid,addr).findVictim(tid, L_assoc);\n\n if (blk->isValid()) {\n DPRINTF(CacheRepl, \"set %x: selecting blk %x for replacement\\n\",\n set, regenerateBlkAddr(blk->tag, set));\n }\n return blk;\n}\n\nvoid\nUTILLRU::invalidateBlk(BlkType *blk, uint64_t tid)\n{\n if (blk) {\n if (blk->isValid()) {\n tagsInUse--;\n assert(blk->srcMasterId < cache->system->maxMasters());\n occupancies[blk->srcMasterId]--;\n blk->srcMasterId = Request::invldMasterId;\n unsigned set = blk->set;\n\t\t\tget_set(set,tid,blk->set).moveToTail(blk);\n }\n blk->status = 0;\n blk->isTouched = false;\n blk->clearLoadLocks();\n\n \/\/ should be evicted before valid blocks\n \/\/unsigned set = blk->set;\n \/\/sets[set].moveToTail(blk);\n }\n\t\n\tBlkType *umon_blk = umon_sets[tid][blk->set].findBlk(blk->tag);\n\tif (umon_blk != 0) {\n\t\tif (umon_blk->isValid()) {\n\t\t\tumon_sets[tid][blk->set].moveToTail(umon_blk);\n\t\t}\n\t\tumon_blk->status = 0;\n\t\tumon_blk->isTouched = false;\n\t}\n}<|endoftext|>"} {"text":"#ifndef VIENNAMETA_TYPELIST_HPP\n#define VIENNAMETA_TYPELIST_HPP\n\n\n#include \"utils.hpp\"\n#include \"typelist_macros.hpp\"\n\n\nnamespace viennameta\n{\n\n template \n struct typelist_t\n {\n typedef head_ head;\n typedef tail_ tail;\n };\n\n \n \n namespace typelist\n {\n namespace result_of\n {\n \n \/\/ size of a typelist\n template struct size;\n \n template <> struct size\n {\n enum { value = 0 };\n };\n \n template \n struct size< typelist_t >\n {\n enum { value = 1 + size::value };\n };\n \n \n \/\/ index access\n template struct at\n {\n typedef out_of_range type;\n };\n \n template \n struct at, 0>\n {\n typedef head type;\n };\n\n template \n struct at, i>\n {\n typedef typename at::type type;\n };\n \n \n \n \/\/ find first type\n template struct find;\n \n template \n struct find\n {\n enum { value = -1 };\n };\n \n template \n struct find, to_find>\n {\n enum { value = 0 };\n };\n \n template \n struct find, to_find>\n {\n private:\n enum { temp = find::value };\n public:\n enum { value = (temp == -1 ? -1 : 1 + temp) };\n };\n \n \n \n \/\/ push back a single type\n template struct push_back;\n \n template <>\n struct push_back\n {\n typedef null_type type;\n };\n \n template \n struct push_back\n {\n typedef typelist_t type;\n };\n\n template \n struct push_back, to_add>\n {\n typedef typelist_t::type> type;\n };\n \n \n \n \/\/ push back list\n template struct push_back_list;\n \n template <>\n struct push_back_list\n {\n typedef null_type type;\n };\n \n template \n struct push_back_list >\n {\n typedef typelist_t type;\n };\n\n template \n struct push_back_list, null_type >\n {\n typedef typelist_t type;\n };\n \n template \n struct push_back_list, typelist_t >\n {\n typedef typename push_back_list< typename push_back< typelist_t, head2>::type, tail2 >::type type;\n };\n\n \n \n \/\/ erase_at the type at index\n template struct erase_at;\n \n template \n struct erase_at\n {\n typedef null_type type;\n };\n\n template \n struct erase_at< typelist_t, 0>\n {\n typedef tail type;\n };\n \n template \n struct erase_at< typelist_t, index_to_erase>\n {\n typedef typelist_t::type> type;\n };\n \n \n \n \/\/ erase the first type\n template struct erase;\n \n template \n struct erase\n {\n typedef null_type type;\n };\n\n template \n struct erase< typelist_t, to_erase>\n {\n typedef tail type;\n };\n\n template \n struct erase< typelist_t, to_erase>\n {\n typedef typelist_t::type> type;\n };\n \n \n \/\/ erase all types\n template \n struct erase_all;\n \n template \n struct erase_all\n {\n typedef null_type type;\n };\n \n template \n struct erase_all< typelist_t, to_erase>\n {\n \/\/ Go all the way down the list removing the type\n typedef typename erase_all::type type;\n };\n template \n \n struct erase_all< typelist_t, to_erase>\n {\n \/\/ Go all the way down the list removing the type\n typedef typelist_t::type> type;\n };\n \n \n \/\/ no duplicate types\n template struct no_duplicates;\n \n template <> struct\n no_duplicates\n {\n typedef null_type type;\n };\n\n template \n struct no_duplicates< typelist_t >\n {\n private:\n typedef typename no_duplicates::type L1;\n typedef typename erase::type L2;\n public:\n typedef typelist_t type;\n };\n \n\n \/\/ replace the type at index by another type\n template struct replace_at;\n \n template \n struct replace_at\n {\n typedef null_type type;\n };\n\n template \n struct replace_at, 0, replaced>\n {\n typedef typelist_t type;\n };\n\n template \n struct replace_at, index_to_replace, replaced>\n {\n typedef typelist_t::type> type;\n };\n \n \/\/ replace the first type by another type\n template struct replace;\n \n template \n struct replace\n {\n typedef null_type type;\n };\n\n template \n struct replace, to_replace, replaced>\n {\n typedef typelist_t type;\n };\n\n template \n struct replace, to_replace, replaced>\n {\n typedef typelist_t::type> type;\n };\n \n \n \/\/ replace all types by another type\n template struct replace_all;\n \n template \n struct replace_all\n {\n typedef null_type type;\n };\n \n template \n struct replace_all, to_replace, replaced>\n {\n typedef typelist_t::type> type;\n };\n \n template \n struct replace_all, to_replace, replaced>\n {\n typedef typelist_t::type> type;\n };\n }\n } \n}\n\n\n#endif \/\/ end file guardian\n\nrenamed find to index_of#ifndef VIENNAMETA_TYPELIST_HPP\n#define VIENNAMETA_TYPELIST_HPP\n\n\n#include \"utils.hpp\"\n#include \"typelist_macros.hpp\"\n\n\nnamespace viennameta\n{\n\n template \n struct typelist_t\n {\n typedef head_ head;\n typedef tail_ tail;\n };\n\n \n \n namespace typelist\n {\n namespace result_of\n {\n \n \/\/ size of a typelist\n template struct size;\n \n template <> struct size\n {\n enum { value = 0 };\n };\n \n template \n struct size< typelist_t >\n {\n enum { value = 1 + size::value };\n };\n \n \n \/\/ index access\n template struct at\n {\n typedef out_of_range type;\n };\n \n template \n struct at, 0>\n {\n typedef head type;\n };\n\n template \n struct at, i>\n {\n typedef typename at::type type;\n };\n \n \n \n \/\/ returns the index of the first type in the typelist\n template struct index_of;\n \n template \n struct index_of\n {\n enum { value = -1 };\n };\n \n template \n struct index_of, to_find>\n {\n enum { value = 0 };\n };\n \n template \n struct index_of, to_find>\n {\n private:\n enum { temp = index_of::value };\n public:\n enum { value = (temp == -1 ? -1 : 1 + temp) };\n };\n \n \n \n \/\/ push back a single type\n template struct push_back;\n \n template <>\n struct push_back\n {\n typedef null_type type;\n };\n \n template \n struct push_back\n {\n typedef typelist_t type;\n };\n\n template \n struct push_back, to_add>\n {\n typedef typelist_t::type> type;\n };\n \n \n \n \/\/ push back list\n template struct push_back_list;\n \n template <>\n struct push_back_list\n {\n typedef null_type type;\n };\n \n template \n struct push_back_list >\n {\n typedef typelist_t type;\n };\n\n template \n struct push_back_list, null_type >\n {\n typedef typelist_t type;\n };\n \n template \n struct push_back_list, typelist_t >\n {\n typedef typename push_back_list< typename push_back< typelist_t, head2>::type, tail2 >::type type;\n };\n\n \n \n \/\/ erase_at the type at index\n template struct erase_at;\n \n template \n struct erase_at\n {\n typedef null_type type;\n };\n\n template \n struct erase_at< typelist_t, 0>\n {\n typedef tail type;\n };\n \n template \n struct erase_at< typelist_t, index_to_erase>\n {\n typedef typelist_t::type> type;\n };\n \n \n \n \/\/ erase the first type\n template struct erase;\n \n template \n struct erase\n {\n typedef null_type type;\n };\n\n template \n struct erase< typelist_t, to_erase>\n {\n typedef tail type;\n };\n\n template \n struct erase< typelist_t, to_erase>\n {\n typedef typelist_t::type> type;\n };\n \n \n \/\/ erase all types\n template \n struct erase_all;\n \n template \n struct erase_all\n {\n typedef null_type type;\n };\n \n template \n struct erase_all< typelist_t, to_erase>\n {\n \/\/ Go all the way down the list removing the type\n typedef typename erase_all::type type;\n };\n template \n \n struct erase_all< typelist_t, to_erase>\n {\n \/\/ Go all the way down the list removing the type\n typedef typelist_t::type> type;\n };\n \n \n \/\/ no duplicate types\n template struct no_duplicates;\n \n template <> struct\n no_duplicates\n {\n typedef null_type type;\n };\n\n template \n struct no_duplicates< typelist_t >\n {\n private:\n typedef typename no_duplicates::type L1;\n typedef typename erase::type L2;\n public:\n typedef typelist_t type;\n };\n \n\n \/\/ replace the type at index by another type\n template struct replace_at;\n \n template \n struct replace_at\n {\n typedef null_type type;\n };\n\n template \n struct replace_at, 0, replaced>\n {\n typedef typelist_t type;\n };\n\n template \n struct replace_at, index_to_replace, replaced>\n {\n typedef typelist_t::type> type;\n };\n \n \/\/ replace the first type by another type\n template struct replace;\n \n template \n struct replace\n {\n typedef null_type type;\n };\n\n template \n struct replace, to_replace, replaced>\n {\n typedef typelist_t type;\n };\n\n template \n struct replace, to_replace, replaced>\n {\n typedef typelist_t::type> type;\n };\n \n \n \/\/ replace all types by another type\n template struct replace_all;\n \n template \n struct replace_all\n {\n typedef null_type type;\n };\n \n template \n struct replace_all, to_replace, replaced>\n {\n typedef typelist_t::type> type;\n };\n \n template \n struct replace_all, to_replace, replaced>\n {\n typedef typelist_t::type> type;\n };\n }\n } \n}\n\n\n#endif \/\/ end file guardian\n\n<|endoftext|>"} {"text":"#ifndef VIENNAGRID_STORAGE_RANGE_HPP\n#define VIENNAGRID_STORAGE_RANGE_HPP\n\n\n\nnamespace viennagrid\n{\n \n namespace storage\n {\n \n \n template\n class container_range_wrapper\n {\n friend class container_range_wrapper;\n \n public:\n \n container_range_wrapper(container_type & _container) : container(_container) {}\n \n typedef typename container_type::size_type size_type;\n typedef typename container_type::value_type value_type;\n \n typedef typename container_type::reference reference;\n typedef typename container_type::const_reference const_reference;\n \n typedef typename container_type::pointer pointer;\n typedef typename container_type::const_pointer const_pointer;\n \n typedef typename container_type::iterator iterator;\n typedef typename container_type::const_iterator const_iterator;\n \n typedef typename container_type::reverse_iterator reverse_iterator;\n typedef typename container_type::const_reverse_iterator const_reverse_iterator;\n \n \n \n iterator begin() { return container.begin(); }\n const_iterator begin() const { return container.begin(); }\n iterator end() { return container.end(); }\n const_iterator end() const { return container.end(); }\n \n reverse_iterator rbegin() { return container.rbegin(); }\n const_reverse_iterator rbegin() const { return container.rbegin(); }\n reverse_iterator rend() { return container.rend(); }\n const_reverse_iterator rend() const { return container.rend(); }\n \n \n \n reference front() { return container.front(); }\n const_reference front() const { return container.front(); }\n reference back() { return container.back(); }\n const_reference back() const { return container.back(); }\n \n \n \n reference operator[] (size_type index) { return container[index]; }\n const_reference operator[] (size_type index) const { return container[index]; }\n \n \n \n bool empty() const { return container.empty(); }\n size_type size() const { return container.size(); }\n \n \n private:\n \n container_type & container;\n };\n \n template\n class container_range_wrapper\n {\n public:\n \n container_range_wrapper(const container_type & _container) : container(_container) {}\n container_range_wrapper(const container_range_wrapper & rhs) : container(rhs.container) {}\n \n typedef typename container_type::size_type size_type;\n typedef typename container_type::value_type value_type;\n \n typedef typename container_type::const_reference reference;\n typedef typename container_type::const_reference const_reference;\n \n typedef typename container_type::const_pointer pointer;\n typedef typename container_type::const_pointer const_pointer;\n \n typedef typename container_type::const_iterator iterator;\n typedef typename container_type::const_iterator const_iterator;\n \n typedef typename container_type::const_reverse_iterator reverse_iterator;\n typedef typename container_type::const_reverse_iterator const_reverse_iterator;\n \n \n \n iterator begin() { return container.begin(); }\n const_iterator begin() const { return container.begin(); }\n iterator end() { return container.end(); }\n const_iterator end() const { return container.end(); }\n \n reverse_iterator rbegin() { return container.rbegin(); }\n const_reverse_iterator rbegin() const { return container.rbegin(); }\n reverse_iterator rend() { return container.rend(); }\n const_reverse_iterator rend() const { return container.rend(); }\n \n \n \n reference front() { return container.front(); }\n const_reference front() const { return container.front(); }\n reference back() { return container.back(); }\n const_reference back() const { return container.back(); }\n \n \n \n reference operator[] (size_type index) { return container[index]; }\n const_reference operator[] (size_type index) const { return container[index]; }\n \n \n \n bool empty() const { return container.empty(); }\n size_type size() const { return container.size(); }\n \n \n private:\n \n const container_type & container;\n };\n \n \n \n template\n class forward_iterator_range\n {\n public:\n \n forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}\n \n typedef typename iterator_type::T value_type;\n \n typedef typename iterator_type::Reference reference;\n typedef const typename iterator_type::Reference const_reference;\n \n typedef typename iterator_type::Pointer pointer;\n typedef const typename iterator_type::Pointer const_pointer;\n \n typedef iterator_type iterator;\n typedef const iterator_type const_iterator;\n \n \n \n iterator begin() { return first; }\n const_iterator begin() const { return first; }\n iterator end() { return last; }\n const_iterator end() const { return last; }\n \n \n reference front() { return *first; }\n const_reference front() const { return *first; }\n reference back() { iterator_type tmp = last; return *(--tmp); }\n const_reference back() const { iterator_type tmp = last; return *(--tmp); }\n \n \n \n bool empty() const { return first == last; }\n \n \n \n private:\n iterator_type first;\n iterator_type last;\n };\n\n }\n \n}\n\n#endif\n\nadded hook support for container_range_wrapper#ifndef VIENNAGRID_STORAGE_RANGE_HPP\n#define VIENNAGRID_STORAGE_RANGE_HPP\n\n\n\nnamespace viennagrid\n{\n \n namespace storage\n {\n \n \n template\n class container_range_wrapper\n {\n friend class container_range_wrapper;\n \n public:\n \n container_range_wrapper(container_type & _container) : container(_container) {}\n \n typedef typename container_type::size_type size_type;\n typedef typename container_type::value_type value_type;\n \n typedef typename container_type::reference reference;\n typedef typename container_type::const_reference const_reference;\n \n typedef typename container_type::pointer pointer;\n typedef typename container_type::const_pointer const_pointer;\n \n typedef typename container_type::iterator iterator;\n typedef typename container_type::const_iterator const_iterator;\n \n typedef typename container_type::reverse_iterator reverse_iterator;\n typedef typename container_type::const_reverse_iterator const_reverse_iterator;\n \n \n \n iterator begin() { return container.begin(); }\n const_iterator begin() const { return container.begin(); }\n iterator end() { return container.end(); }\n const_iterator end() const { return container.end(); }\n \n reverse_iterator rbegin() { return container.rbegin(); }\n const_reverse_iterator rbegin() const { return container.rbegin(); }\n reverse_iterator rend() { return container.rend(); }\n const_reverse_iterator rend() const { return container.rend(); }\n \n \n \n reference front() { return container.front(); }\n const_reference front() const { return container.front(); }\n reference back() { return container.back(); }\n const_reference back() const { return container.back(); }\n \n \n \n reference operator[] (size_type index) { return container[index]; }\n const_reference operator[] (size_type index) const { return container[index]; }\n \n \n \n bool empty() const { return container.empty(); }\n size_type size() const { return container.size(); }\n \n \n \n \n typedef typename container_type::hook_type hook_type;\n typedef typename container_type::hook_iterator hook_iterator;\n hook_iterator hook_begin() { return container.hook_begin(); }\n hook_iterator hook_end() { return container.hook_end(); }\n\n typedef typename container_type::const_hook_type const_hook_type;\n typedef typename container_type::const_hook_iterator const_hook_iterator;\n const_hook_iterator hook_begin() const { return container.hook_begin(); }\n const_hook_iterator hook_end() const { return container.hook_end(); }\n \n private:\n \n container_type & container;\n };\n \n template\n class container_range_wrapper\n {\n public:\n \n container_range_wrapper(const container_type & _container) : container(_container) {}\n container_range_wrapper(const container_range_wrapper & rhs) : container(rhs.container) {}\n \n typedef typename container_type::size_type size_type;\n typedef typename container_type::value_type value_type;\n \n typedef typename container_type::const_reference reference;\n typedef typename container_type::const_reference const_reference;\n \n typedef typename container_type::const_pointer pointer;\n typedef typename container_type::const_pointer const_pointer;\n \n typedef typename container_type::const_iterator iterator;\n typedef typename container_type::const_iterator const_iterator;\n \n typedef typename container_type::const_reverse_iterator reverse_iterator;\n typedef typename container_type::const_reverse_iterator const_reverse_iterator;\n \n \n \n iterator begin() { return container.begin(); }\n const_iterator begin() const { return container.begin(); }\n iterator end() { return container.end(); }\n const_iterator end() const { return container.end(); }\n \n reverse_iterator rbegin() { return container.rbegin(); }\n const_reverse_iterator rbegin() const { return container.rbegin(); }\n reverse_iterator rend() { return container.rend(); }\n const_reverse_iterator rend() const { return container.rend(); }\n \n \n \n reference front() { return container.front(); }\n const_reference front() const { return container.front(); }\n reference back() { return container.back(); }\n const_reference back() const { return container.back(); }\n \n \n \n reference operator[] (size_type index) { return container[index]; }\n const_reference operator[] (size_type index) const { return container[index]; }\n \n \n \n bool empty() const { return container.empty(); }\n size_type size() const { return container.size(); }\n \n \n \n typedef typename container_type::const_hook_type hook_type;\n typedef typename container_type::const_hook_iterator hook_iterator;\n hook_iterator hook_begin() { return container.hook_begin(); }\n hook_iterator hook_end() { return container.hook_end(); }\n\n typedef typename container_type::const_hook_type const_hook_type;\n typedef typename container_type::const_hook_iterator const_hook_iterator;\n const_hook_iterator hook_begin() const { return container.hook_begin(); }\n const_hook_iterator hook_end() const { return container.hook_end(); }\n \n private:\n \n const container_type & container;\n };\n \n \n \n template\n class forward_iterator_range\n {\n public:\n \n forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}\n \n typedef typename iterator_type::T value_type;\n \n typedef typename iterator_type::Reference reference;\n typedef const typename iterator_type::Reference const_reference;\n \n typedef typename iterator_type::Pointer pointer;\n typedef const typename iterator_type::Pointer const_pointer;\n \n typedef iterator_type iterator;\n typedef const iterator_type const_iterator;\n \n \n \n iterator begin() { return first; }\n const_iterator begin() const { return first; }\n iterator end() { return last; }\n const_iterator end() const { return last; }\n \n \n reference front() { return *first; }\n const_reference front() const { return *first; }\n reference back() { iterator_type tmp = last; return *(--tmp); }\n const_reference back() const { iterator_type tmp = last; return *(--tmp); }\n \n \n \n bool empty() const { return first == last; }\n \n \n \n private:\n iterator_type first;\n iterator_type last;\n };\n\n }\n \n}\n\n#endif\n\n<|endoftext|>"} {"text":"\/**\n * @file gmm_test.cpp\n * @author Ryan Curtin\n *\n * Test for the Gaussian Mixture Model class.\n *\/\n#include \n\n#include \n#include \n\n#include \n\nusing namespace mlpack;\nusing namespace mlpack::gmm;\n\nBOOST_AUTO_TEST_SUITE(GMMTest);\n\n\/**\n * Test the phi() function, in the univariate Gaussian case.\n *\/\nBOOST_AUTO_TEST_CASE(UnivariatePhiTest)\n{\n \/\/ Simple case.\n BOOST_REQUIRE_CLOSE(phi(0.0, 0.0, 1.0), 0.398942280401433, 1e-5);\n\n \/\/ A few more cases...\n BOOST_REQUIRE_CLOSE(phi(0.0, 0.0, 2.0), 0.282094791773878, 1e-5);\n\n BOOST_REQUIRE_CLOSE(phi(1.0, 0.0, 1.0), 0.241970724519143, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-1.0, 0.0, 1.0), 0.241970724519143, 1e-5);\n\n BOOST_REQUIRE_CLOSE(phi(1.0, 0.0, 2.0), 0.219695644733861, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-1.0, 0.0, 2.0), 0.219695644733861, 1e-5);\n\n BOOST_REQUIRE_CLOSE(phi(1.0, 1.0, 1.0), 0.398942280401433, 1e-5);\n\n BOOST_REQUIRE_CLOSE(phi(-1.0, 1.0, 2.0), 0.103776874355149, 1e-5);\n}\n\n\/**\n * Test the phi() function, in the multivariate Gaussian case.\n *\/\nBOOST_AUTO_TEST_CASE(MultivariatePhiTest)\n{\n \/\/ Simple case.\n arma::vec mean = \"0 0\";\n arma::mat cov = \"1 0; 0 1\";\n arma::vec x = \"0 0\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.159154943091895, 1e-5);\n\n cov = \"2 0; 0 2\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0795774715459477, 1e-5);\n\n x = \"1 1\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0482661763150270, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 0.0482661763150270, 1e-5);\n\n mean = \"1 1\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0795774715459477, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 0.0795774715459477, 1e-5);\n\n cov = \"2 1.5; 1 4\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0624257046546403, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 0.0624257046546403, 1e-5);\n\n x = \"-1 4\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.00144014867515135, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 0.00133352162064845, 1e-5);\n\n \/\/ Higher-dimensional case.\n x = \"0 1 2 3 4\";\n mean = \"5 6 3 3 2\";\n cov = \"6 1 1 0 2;\"\n \"0 7 1 0 1;\"\n \"1 1 4 1 1;\"\n \"1 0 1 7 0;\"\n \"2 0 1 1 6\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 1.02531207499358e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 1.02531207499358e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(x, -mean, cov), 1.06784794079363e-8, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 1.06784794079363e-8, 1e-5);\n}\n\n\/**\n * Test the phi() function, for multiple points in the multivariate Gaussian\n * case.\n *\/\nBOOST_AUTO_TEST_CASE(MultipointMultivariatePhiTest)\n{\n \/\/ Same case as before.\n arma::vec mean = \"5 6 3 3 2\";\n arma::mat cov = \"6 1 1 0 2; 0 7 1 0 1; 1 1 4 1 1; 1 0 1 7 0; 2 0 1 1 6\";\n\n arma::mat points = \"0 3 2 2 3 4;\"\n \"1 2 2 1 0 0;\"\n \"2 3 0 5 5 6;\"\n \"3 7 8 0 1 1;\"\n \"4 8 1 1 0 0;\";\n\n arma::vec phis;\n phi(points, mean, cov, phis);\n\n BOOST_REQUIRE_EQUAL(phis.n_elem, 6);\n\n BOOST_REQUIRE_CLOSE(phis(0), 1.02531207499358e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phis(1), 1.82353695848039e-7, 1e-5);\n BOOST_REQUIRE_CLOSE(phis(2), 1.29759261892949e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phis(3), 1.33218060268258e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phis(4), 1.12120427975708e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phis(5), 4.57951032485297e-7, 1e-5);\n}\n\n\/**\n * Test training a model on only one Gaussian (randomly generated) in two\n * dimensions. We will vary the dataset size from small to large. The EM\n * algorithm is used for training the GMM.\n *\/\nBOOST_AUTO_TEST_CASE(GMMTrainEMOneGaussian)\n{\n \/\/ Initialize random seed.\n srand(time(NULL));\n\n for (size_t iterations = 0; iterations < 4; iterations++)\n {\n \/\/ Determine random covariance and mean.\n arma::vec mean;\n mean.randu(2);\n arma::vec covar;\n covar.randu(2);\n\n arma::mat data;\n data.randn(2 \/* dimension *\/, 100 * pow(10, (iterations \/ 3.0)));\n\n \/\/ Now apply mean and covariance.\n data.row(0) *= covar(0);\n data.row(1) *= covar(1);\n\n data.row(0) += mean(0);\n data.row(1) += mean(1);\n\n \/\/ Now, train the model.\n GMM gmm(1, 2);\n gmm.ExpectationMaximization(data);\n\n arma::vec actual_mean = arma::mean(data, 1);\n arma::mat actual_covar = ccov(data, 1 \/* biased estimator *\/);\n\n \/\/ Check the model to see that it is correct.\n BOOST_REQUIRE_CLOSE((gmm.Means()[0])[0], actual_mean(0), 1e-5);\n BOOST_REQUIRE_CLOSE((gmm.Means()[0])[1], actual_mean(1), 1e-5);\n\n BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(0, 0), actual_covar(0, 0), 1e-5);\n BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(0, 1), actual_covar(0, 1), 1e-5);\n BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(1, 0), actual_covar(1, 0), 1e-5);\n BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(1, 1), actual_covar(1, 1), 1e-5);\n\n BOOST_REQUIRE_CLOSE(gmm.Weights()[0], 1.0, 1e-5);\n }\n}\n\n\/**\n * Test a training model on multiple Gaussians in higher dimensionality than\n * two. We will hold the dataset size constant at 10k points. The EM algorithm\n * is used for training the GMM.\n *\/\nBOOST_AUTO_TEST_CASE(GMMTrainEMMultipleGaussians)\n{\n \/\/ Higher dimensionality gives us a greater chance of having separated\n \/\/ Gaussians.\n size_t dims = 8;\n size_t gaussians = 3;\n\n \/\/ Generate dataset.\n arma::mat data;\n data.zeros(dims, 500);\n\n std::vector means(gaussians);\n std::vector covars(gaussians);\n arma::vec weights(gaussians);\n arma::Col counts(gaussians);\n\n \/\/ Choose weights randomly.\n weights.zeros();\n while (weights.min() < 0.02)\n {\n weights.randu(gaussians);\n weights \/= accu(weights);\n }\n\n for (size_t i = 0; i < gaussians; i++)\n counts[i] = round(weights[i] * (data.n_cols - gaussians));\n \/\/ Ensure one point minimum in each.\n counts += 1;\n\n \/\/ Account for rounding errors (possibly necessary).\n counts[gaussians - 1] += (data.n_cols - arma::accu(counts));\n\n \/\/ Build each Gaussian individually.\n size_t point = 0;\n for (int i = 0; i < gaussians; i++)\n {\n arma::mat gaussian;\n gaussian.randn(dims, counts[i]);\n\n \/\/ Randomly generate mean and covariance.\n means[i].randu(dims);\n means[i] -= 0.5;\n means[i] *= 50;\n\n covars[i].randu(dims, dims);\n covars[i] *= 2;\n\n data.cols(point, point + counts[i] - 1) = (covars[i] * gaussian + means[i]\n * arma::ones(counts[i]));\n\n \/\/ Calculate the actual means and covariances because they will probably\n \/\/ be different (this is easier to do before we shuffle the points).\n means[i] = arma::mean(data.cols(point, point + counts[i] - 1), 1);\n covars[i] = ccov(data.cols(point, point + counts[i] - 1), 1 \/* biased *\/);\n\n point += counts[i];\n }\n\n \/\/ Calculate actual weights.\n for (size_t i = 0; i < gaussians; i++)\n weights[i] = (double) counts[i] \/ data.n_cols;\n\n \/\/ Now train the model.\n GMM gmm(gaussians, dims);\n gmm.ExpectationMaximization(data);\n\n arma::uvec sort_ref = sort_index(weights);\n arma::uvec sort_try = sort_index(gmm.Weights());\n\n \/\/ Check the model to see that it is correct.\n for (int i = 0; i < gaussians; i++)\n {\n \/\/ Check the mean.\n for (int j = 0; j < dims; j++)\n BOOST_REQUIRE_CLOSE((gmm.Means()[sort_try[i]])[j],\n (means[sort_ref[i]])[j], 1e-5);\n\n \/\/ Check the covariance.\n for (int row = 0; row < dims; row++)\n for (int col = 0; col < dims; col++)\n BOOST_REQUIRE_CLOSE((gmm.Covariances()[sort_try[i]])(row, col),\n (covars[sort_ref[i]])(row, col), 1e-5);\n\n \/\/ Check the weight.\n BOOST_REQUIRE_CLOSE(gmm.Weights()[sort_try[i]], weights[sort_ref[i]],\n 1e-5);\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\nFix some warnings I inadvertently introduced.\/**\n * @file gmm_test.cpp\n * @author Ryan Curtin\n *\n * Test for the Gaussian Mixture Model class.\n *\/\n#include \n\n#include \n#include \n\n#include \n\nusing namespace mlpack;\nusing namespace mlpack::gmm;\n\nBOOST_AUTO_TEST_SUITE(GMMTest);\n\n\/**\n * Test the phi() function, in the univariate Gaussian case.\n *\/\nBOOST_AUTO_TEST_CASE(UnivariatePhiTest)\n{\n \/\/ Simple case.\n BOOST_REQUIRE_CLOSE(phi(0.0, 0.0, 1.0), 0.398942280401433, 1e-5);\n\n \/\/ A few more cases...\n BOOST_REQUIRE_CLOSE(phi(0.0, 0.0, 2.0), 0.282094791773878, 1e-5);\n\n BOOST_REQUIRE_CLOSE(phi(1.0, 0.0, 1.0), 0.241970724519143, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-1.0, 0.0, 1.0), 0.241970724519143, 1e-5);\n\n BOOST_REQUIRE_CLOSE(phi(1.0, 0.0, 2.0), 0.219695644733861, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-1.0, 0.0, 2.0), 0.219695644733861, 1e-5);\n\n BOOST_REQUIRE_CLOSE(phi(1.0, 1.0, 1.0), 0.398942280401433, 1e-5);\n\n BOOST_REQUIRE_CLOSE(phi(-1.0, 1.0, 2.0), 0.103776874355149, 1e-5);\n}\n\n\/**\n * Test the phi() function, in the multivariate Gaussian case.\n *\/\nBOOST_AUTO_TEST_CASE(MultivariatePhiTest)\n{\n \/\/ Simple case.\n arma::vec mean = \"0 0\";\n arma::mat cov = \"1 0; 0 1\";\n arma::vec x = \"0 0\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.159154943091895, 1e-5);\n\n cov = \"2 0; 0 2\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0795774715459477, 1e-5);\n\n x = \"1 1\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0482661763150270, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 0.0482661763150270, 1e-5);\n\n mean = \"1 1\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0795774715459477, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 0.0795774715459477, 1e-5);\n\n cov = \"2 1.5; 1 4\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0624257046546403, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 0.0624257046546403, 1e-5);\n\n x = \"-1 4\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.00144014867515135, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 0.00133352162064845, 1e-5);\n\n \/\/ Higher-dimensional case.\n x = \"0 1 2 3 4\";\n mean = \"5 6 3 3 2\";\n cov = \"6 1 1 0 2;\"\n \"0 7 1 0 1;\"\n \"1 1 4 1 1;\"\n \"1 0 1 7 0;\"\n \"2 0 1 1 6\";\n\n BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 1.02531207499358e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 1.02531207499358e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(x, -mean, cov), 1.06784794079363e-8, 1e-5);\n BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 1.06784794079363e-8, 1e-5);\n}\n\n\/**\n * Test the phi() function, for multiple points in the multivariate Gaussian\n * case.\n *\/\nBOOST_AUTO_TEST_CASE(MultipointMultivariatePhiTest)\n{\n \/\/ Same case as before.\n arma::vec mean = \"5 6 3 3 2\";\n arma::mat cov = \"6 1 1 0 2; 0 7 1 0 1; 1 1 4 1 1; 1 0 1 7 0; 2 0 1 1 6\";\n\n arma::mat points = \"0 3 2 2 3 4;\"\n \"1 2 2 1 0 0;\"\n \"2 3 0 5 5 6;\"\n \"3 7 8 0 1 1;\"\n \"4 8 1 1 0 0;\";\n\n arma::vec phis;\n phi(points, mean, cov, phis);\n\n BOOST_REQUIRE_EQUAL(phis.n_elem, 6);\n\n BOOST_REQUIRE_CLOSE(phis(0), 1.02531207499358e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phis(1), 1.82353695848039e-7, 1e-5);\n BOOST_REQUIRE_CLOSE(phis(2), 1.29759261892949e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phis(3), 1.33218060268258e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phis(4), 1.12120427975708e-6, 1e-5);\n BOOST_REQUIRE_CLOSE(phis(5), 4.57951032485297e-7, 1e-5);\n}\n\n\/**\n * Test training a model on only one Gaussian (randomly generated) in two\n * dimensions. We will vary the dataset size from small to large. The EM\n * algorithm is used for training the GMM.\n *\/\nBOOST_AUTO_TEST_CASE(GMMTrainEMOneGaussian)\n{\n \/\/ Initialize random seed.\n srand(time(NULL));\n\n for (size_t iterations = 0; iterations < 4; iterations++)\n {\n \/\/ Determine random covariance and mean.\n arma::vec mean;\n mean.randu(2);\n arma::vec covar;\n covar.randu(2);\n\n arma::mat data;\n data.randn(2 \/* dimension *\/, 100 * pow(10, (iterations \/ 3.0)));\n\n \/\/ Now apply mean and covariance.\n data.row(0) *= covar(0);\n data.row(1) *= covar(1);\n\n data.row(0) += mean(0);\n data.row(1) += mean(1);\n\n \/\/ Now, train the model.\n GMM gmm(1, 2);\n gmm.ExpectationMaximization(data);\n\n arma::vec actual_mean = arma::mean(data, 1);\n arma::mat actual_covar = ccov(data, 1 \/* biased estimator *\/);\n\n \/\/ Check the model to see that it is correct.\n BOOST_REQUIRE_CLOSE((gmm.Means()[0])[0], actual_mean(0), 1e-5);\n BOOST_REQUIRE_CLOSE((gmm.Means()[0])[1], actual_mean(1), 1e-5);\n\n BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(0, 0), actual_covar(0, 0), 1e-5);\n BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(0, 1), actual_covar(0, 1), 1e-5);\n BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(1, 0), actual_covar(1, 0), 1e-5);\n BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(1, 1), actual_covar(1, 1), 1e-5);\n\n BOOST_REQUIRE_CLOSE(gmm.Weights()[0], 1.0, 1e-5);\n }\n}\n\n\/**\n * Test a training model on multiple Gaussians in higher dimensionality than\n * two. We will hold the dataset size constant at 10k points. The EM algorithm\n * is used for training the GMM.\n *\/\nBOOST_AUTO_TEST_CASE(GMMTrainEMMultipleGaussians)\n{\n \/\/ Higher dimensionality gives us a greater chance of having separated\n \/\/ Gaussians.\n size_t dims = 8;\n size_t gaussians = 3;\n\n \/\/ Generate dataset.\n arma::mat data;\n data.zeros(dims, 500);\n\n std::vector means(gaussians);\n std::vector covars(gaussians);\n arma::vec weights(gaussians);\n arma::Col counts(gaussians);\n\n \/\/ Choose weights randomly.\n weights.zeros();\n while (weights.min() < 0.02)\n {\n weights.randu(gaussians);\n weights \/= accu(weights);\n }\n\n for (size_t i = 0; i < gaussians; i++)\n counts[i] = round(weights[i] * (data.n_cols - gaussians));\n \/\/ Ensure one point minimum in each.\n counts += 1;\n\n \/\/ Account for rounding errors (possibly necessary).\n counts[gaussians - 1] += (data.n_cols - arma::accu(counts));\n\n \/\/ Build each Gaussian individually.\n size_t point = 0;\n for (size_t i = 0; i < gaussians; i++)\n {\n arma::mat gaussian;\n gaussian.randn(dims, counts[i]);\n\n \/\/ Randomly generate mean and covariance.\n means[i].randu(dims);\n means[i] -= 0.5;\n means[i] *= 50;\n\n covars[i].randu(dims, dims);\n covars[i] *= 2;\n\n data.cols(point, point + counts[i] - 1) = (covars[i] * gaussian + means[i]\n * arma::ones(counts[i]));\n\n \/\/ Calculate the actual means and covariances because they will probably\n \/\/ be different (this is easier to do before we shuffle the points).\n means[i] = arma::mean(data.cols(point, point + counts[i] - 1), 1);\n covars[i] = ccov(data.cols(point, point + counts[i] - 1), 1 \/* biased *\/);\n\n point += counts[i];\n }\n\n \/\/ Calculate actual weights.\n for (size_t i = 0; i < gaussians; i++)\n weights[i] = (double) counts[i] \/ data.n_cols;\n\n \/\/ Now train the model.\n GMM gmm(gaussians, dims);\n gmm.ExpectationMaximization(data);\n\n arma::uvec sort_ref = sort_index(weights);\n arma::uvec sort_try = sort_index(gmm.Weights());\n\n \/\/ Check the model to see that it is correct.\n for (size_t i = 0; i < gaussians; i++)\n {\n \/\/ Check the mean.\n for (size_t j = 0; j < dims; j++)\n BOOST_REQUIRE_CLOSE((gmm.Means()[sort_try[i]])[j],\n (means[sort_ref[i]])[j], 1e-5);\n\n \/\/ Check the covariance.\n for (size_t row = 0; row < dims; row++)\n for (size_t col = 0; col < dims; col++)\n BOOST_REQUIRE_CLOSE((gmm.Covariances()[sort_try[i]])(row, col),\n (covars[sort_ref[i]])(row, col), 1e-5);\n\n \/\/ Check the weight.\n BOOST_REQUIRE_CLOSE(gmm.Weights()[sort_try[i]], weights[sort_ref[i]],\n 1e-5);\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2013-2014 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 * @file navigator_rtl.cpp\n * Helper class to access RTL\n * @author Julian Oes \n * @author Anton Babushkin \n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"navigator.h\"\n#include \"rtl.h\"\n\nRTL::RTL(Navigator *navigator, const char *name) :\n\tNavigatorMode(navigator, name),\n\tMissionBlock(navigator),\n\t_rtl_state(RTL_STATE_NONE),\n\t_param_return_alt(this, \"RETURN_ALT\"),\n\t_param_descend_alt(this, \"DESCEND_ALT\"),\n\t_param_land_delay(this, \"LAND_DELAY\"),\n\t_param_acceptance_radius(this, \"ACCEPT_RAD\")\n{\n\t\/* load initial params *\/\n\tupdateParams();\n\t\/* initial reset *\/\n\ton_inactive();\n}\n\nRTL::~RTL()\n{\n}\n\nvoid\nRTL::on_inactive()\n{\n\t_first_run = true;\n\t_rtl_state = RTL_STATE_NONE;\n}\n\nbool\nRTL::on_active(struct position_setpoint_triplet_s *pos_sp_triplet)\n{\n\tbool updated = false;\n\n\tif (_first_run) {\n\t\tset_rtl_item(pos_sp_triplet);\n\t\tupdated = true;\n\t\t_first_run = false;\n\t}\n\n\tif ((_rtl_state == RTL_STATE_CLIMB\n\t || _rtl_state == RTL_STATE_RETURN)\n\t && is_mission_item_reached()) {\n\t\tadvance_rtl();\n\t\tset_rtl_item(pos_sp_triplet);\n\t\tupdated = true;\n\t}\n\n\treturn updated;\n}\n\nvoid\nRTL::set_rtl_item(position_setpoint_triplet_s *pos_sp_triplet)\n{\n\t\/* make sure we have the latest params *\/\n\tupdateParams();\n\n\t\/* decide where to enter the RTL procedure when we switch into it *\/\n\tif (_rtl_state == RTL_STATE_NONE) {\n\t\t\/* for safety reasons don't go into RTL if landed *\/\n\t\tif (_navigator->get_vstatus()->condition_landed) {\n\t\t\t_rtl_state = RTL_STATE_FINISHED;\n\t\t\tmavlink_log_info(_navigator->get_mavlink_fd(), \"#audio: no RTL when landed\");\n\t\t\/* if lower than return altitude, climb up first *\/\n\t\t} else if (_navigator->get_global_position()->alt < _navigator->get_home_position()->alt\n\t\t\t + _param_return_alt.get()) {\n\t\t\t_rtl_state = RTL_STATE_CLIMB;\n\t\t\/* otherwise go straight to return *\/\n\t\t} else {\n\t\t\t_rtl_state = RTL_STATE_RETURN;\n\t\t}\n\t}\n\n\t\/* if switching directly to return state, set altitude setpoint to current altitude *\/\n\tif (_rtl_state == RTL_STATE_RETURN) {\n\t\t_mission_item.altitude_is_relative = false;\n\t\t_mission_item.altitude = _navigator->get_global_position()->alt;\n\t}\n\n\tswitch (_rtl_state) {\n\tcase RTL_STATE_CLIMB: {\n\n\t\tfloat climb_alt = _navigator->get_home_position()->alt + _param_return_alt.get();\n\n\t\t_mission_item.lat = _navigator->get_global_position()->lat;\n\t\t_mission_item.lon = _navigator->get_global_position()->lon;\n\t\t_mission_item.altitude_is_relative = false;\n\t\t_mission_item.altitude = climb_alt;\n\t\t_mission_item.yaw = NAN;\n\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t_mission_item.loiter_direction = 1;\n\t\t_mission_item.nav_cmd = NAV_CMD_WAYPOINT;\n\t\t_mission_item.acceptance_radius = _param_acceptance_radius.get();\n\t\t_mission_item.time_inside = 0.0f;\n\t\t_mission_item.pitch_min = 0.0f;\n\t\t_mission_item.autocontinue = true;\n\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t_navigator->set_is_in_loiter(false);\n\n\t\tmavlink_log_info(_navigator->get_mavlink_fd(), \"#audio: RTL: climb to %d meters above home\",\n\t\t\t(int)(climb_alt - _navigator->get_home_position()->alt));\n\t\tbreak;\n\t}\n\tcase RTL_STATE_RETURN: {\n\n\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\n\t\t\/* TODO: add this again *\/\n\t\t\/\/ don't change altitude\n\t\t\/\/ if (_pos_sp_triplet.previous.valid) {\n\t\t\/\/ \t\/* if previous setpoint is valid then use it to calculate heading to home *\/\n\t\t\/\/ \t_mission_item.yaw = get_bearing_to_next_waypoint(_pos_sp_triplet.previous.lat, _pos_sp_triplet.previous.lon, _mission_item.lat, _mission_item.lon);\n\n\t\t\/\/ } else {\n\t\t\/\/ \t\/* else use current position *\/\n\t\t\/\/ \t_mission_item.yaw = get_bearing_to_next_waypoint(_global_pos.lat, _global_pos.lon, _mission_item.lat, _mission_item.lon);\n\t\t\/\/ }\n\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t_mission_item.loiter_direction = 1;\n\t\t_mission_item.nav_cmd = NAV_CMD_WAYPOINT;\n\t\t_mission_item.acceptance_radius = _param_acceptance_radius.get();\n\t\t_mission_item.time_inside = 0.0f;\n\t\t_mission_item.pitch_min = 0.0f;\n\t\t_mission_item.autocontinue = true;\n\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t_navigator->set_is_in_loiter(false);\n\n\t\tmavlink_log_info(_navigator->get_mavlink_fd(), \"#audio: RTL: return at %d meters above home\",\n\t\t\t(int)(_mission_item.altitude - _navigator->get_home_position()->alt));\n\t\tbreak;\n\t}\n\tcase RTL_STATE_DESCEND: {\n\n\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\t\t_mission_item.altitude_is_relative = false;\n\t\t_mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get();\n\t\t_mission_item.yaw = NAN;\n\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t_mission_item.loiter_direction = 1;\n\t\t_mission_item.nav_cmd = NAV_CMD_LOITER_TIME_LIMIT;\n\t\t_mission_item.acceptance_radius = _param_acceptance_radius.get();\n\t\t_mission_item.time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get();\n\t\t_mission_item.pitch_min = 0.0f;\n\t\t_mission_item.autocontinue = _param_land_delay.get() > -0.001f;\n\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t_navigator->set_is_in_loiter(true);\n\n\t\tmavlink_log_info(_navigator->get_mavlink_fd(), \"#audio: RTL: descend to %d meters above home\",\n\t\t\t(int)(_mission_item.altitude - _navigator->get_home_position()->alt));\n\t\tbreak;\n\t}\n\n\tcase RTL_STATE_LAND: {\n\n\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\t\t_mission_item.altitude_is_relative = false;\n\t\t_mission_item.altitude = _navigator->get_home_position()->alt;\n\t\t_mission_item.yaw = NAN;\n\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t_mission_item.loiter_direction = 1;\n\t\t_mission_item.nav_cmd = NAV_CMD_LAND;\n\t\t_mission_item.acceptance_radius = _param_acceptance_radius.get();\n\t\t_mission_item.time_inside = 0.0f;\n\t\t_mission_item.pitch_min = 0.0f;\n\t\t_mission_item.autocontinue = true;\n\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t_navigator->set_is_in_loiter(false);\n\n\t\tmavlink_log_info(_navigator->get_mavlink_fd(), \"#audio: RTL: land at home\");\n\t\tbreak;\n\t}\n\n\tcase RTL_STATE_FINISHED: {\n\t\t\/* nothing to do, report fail *\/\n\t}\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\tif (_rtl_state == RTL_STATE_FINISHED) {\n\t\tpos_sp_triplet->current.valid = false;\n\t\tpos_sp_triplet->next.valid = false;\n\t} else {\n\t\t\/* if not finished, convert mission item to current position setpoint and make it valid *\/\n\t\tmission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);\n\t\treset_mission_item_reached();\n\t\tpos_sp_triplet->current.valid = true;\n\t\tpos_sp_triplet->next.valid = false;\n\t}\n}\n\nvoid\nRTL::advance_rtl()\n{\n\tswitch (_rtl_state) {\n\tcase RTL_STATE_CLIMB:\n\t\t_rtl_state = RTL_STATE_RETURN;\n\t\tbreak;\n\n\tcase RTL_STATE_RETURN:\n\t\t_rtl_state = RTL_STATE_DESCEND;\n\t\tbreak;\n\n\tcase RTL_STATE_DESCEND:\n\t\t\/* only go to land if autoland is enabled *\/\n\t\tif (_param_land_delay.get() < 0) {\n\t\t\t_rtl_state = RTL_STATE_FINISHED;\n\t\t} else {\n\t\t\t_rtl_state = RTL_STATE_LAND;\n\t\t}\n\t\tbreak;\n\n\tcase RTL_STATE_LAND:\n\t\t_rtl_state = RTL_STATE_FINISHED;\n\t\tbreak;\n\n\tcase RTL_STATE_FINISHED:\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n}\nnavigator: RTL return altitude fixed\/****************************************************************************\n *\n * Copyright (c) 2013-2014 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 * @file navigator_rtl.cpp\n * Helper class to access RTL\n * @author Julian Oes \n * @author Anton Babushkin \n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"navigator.h\"\n#include \"rtl.h\"\n\nRTL::RTL(Navigator *navigator, const char *name) :\n\tNavigatorMode(navigator, name),\n\tMissionBlock(navigator),\n\t_rtl_state(RTL_STATE_NONE),\n\t_param_return_alt(this, \"RETURN_ALT\"),\n\t_param_descend_alt(this, \"DESCEND_ALT\"),\n\t_param_land_delay(this, \"LAND_DELAY\"),\n\t_param_acceptance_radius(this, \"ACCEPT_RAD\")\n{\n\t\/* load initial params *\/\n\tupdateParams();\n\t\/* initial reset *\/\n\ton_inactive();\n}\n\nRTL::~RTL()\n{\n}\n\nvoid\nRTL::on_inactive()\n{\n\t_first_run = true;\n\t_rtl_state = RTL_STATE_NONE;\n}\n\nbool\nRTL::on_active(struct position_setpoint_triplet_s *pos_sp_triplet)\n{\n\tbool updated = false;\n\n\tif (_first_run) {\n\t\tset_rtl_item(pos_sp_triplet);\n\t\tupdated = true;\n\t\t_first_run = false;\n\t}\n\n\tif ((_rtl_state == RTL_STATE_CLIMB\n\t || _rtl_state == RTL_STATE_RETURN)\n\t && is_mission_item_reached()) {\n\t\tadvance_rtl();\n\t\tset_rtl_item(pos_sp_triplet);\n\t\tupdated = true;\n\t}\n\n\treturn updated;\n}\n\nvoid\nRTL::set_rtl_item(position_setpoint_triplet_s *pos_sp_triplet)\n{\n\t\/* make sure we have the latest params *\/\n\tupdateParams();\n\n\t\/* decide where to enter the RTL procedure when we switch into it *\/\n\tif (_rtl_state == RTL_STATE_NONE) {\n\t\t\/* for safety reasons don't go into RTL if landed *\/\n\t\tif (_navigator->get_vstatus()->condition_landed) {\n\t\t\t_rtl_state = RTL_STATE_FINISHED;\n\t\t\tmavlink_log_info(_navigator->get_mavlink_fd(), \"#audio: no RTL when landed\");\n\n\t\t\/* if lower than return altitude, climb up first *\/\n\t\t} else if (_navigator->get_global_position()->alt < _navigator->get_home_position()->alt\n\t\t\t + _param_return_alt.get()) {\n\t\t\t_rtl_state = RTL_STATE_CLIMB;\n\n\t\t\/* otherwise go straight to return *\/\n\t\t} else {\n\t\t \/* set altitude setpoint to current altitude *\/\n\t\t\t_rtl_state = RTL_STATE_RETURN;\n\t _mission_item.altitude_is_relative = false;\n\t _mission_item.altitude = _navigator->get_global_position()->alt;\n\t\t}\n\t}\n\n if (_rtl_state == RTL_STATE_FINISHED) {\n \/* RTL finished, nothing to do *\/\n pos_sp_triplet->current.valid = false;\n pos_sp_triplet->next.valid = false;\n return;\n }\n\n set_previous_pos_setpoint(pos_sp_triplet);\n\n\tswitch (_rtl_state) {\n\tcase RTL_STATE_CLIMB: {\n\n\t\tfloat climb_alt = _navigator->get_home_position()->alt + _param_return_alt.get();\n\n\t\t_mission_item.lat = _navigator->get_global_position()->lat;\n\t\t_mission_item.lon = _navigator->get_global_position()->lon;\n\t\t_mission_item.altitude_is_relative = false;\n\t\t_mission_item.altitude = climb_alt;\n\t\t_mission_item.yaw = NAN;\n\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t_mission_item.loiter_direction = 1;\n\t\t_mission_item.nav_cmd = NAV_CMD_WAYPOINT;\n\t\t_mission_item.acceptance_radius = _param_acceptance_radius.get();\n\t\t_mission_item.time_inside = 0.0f;\n\t\t_mission_item.pitch_min = 0.0f;\n\t\t_mission_item.autocontinue = true;\n\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t_navigator->set_is_in_loiter(false);\n\n\t\tmavlink_log_info(_navigator->get_mavlink_fd(), \"#audio: RTL: climb to %d meters above home\",\n\t\t\t(int)(climb_alt - _navigator->get_home_position()->alt));\n\t\tbreak;\n\t}\n\tcase RTL_STATE_RETURN: {\n\n\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\t\t \/\/ don't change altitude\n\n\t\t if (pos_sp_triplet->previous.valid) {\n\t\t \t\/* if previous setpoint is valid then use it to calculate heading to home *\/\n\t\t \t_mission_item.yaw = get_bearing_to_next_waypoint(\n\t\t \t pos_sp_triplet->previous.lat, pos_sp_triplet->previous.lon,\n\t\t \t _mission_item.lat, _mission_item.lon);\n\n\t\t } else {\n\t\t \t\/* else use current position *\/\n\t\t \t_mission_item.yaw = get_bearing_to_next_waypoint(\n\t\t \t _navigator->get_global_position()->lat, _navigator->get_global_position()->lon,\n\t\t \t _mission_item.lat, _mission_item.lon);\n\t\t }\n\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t_mission_item.loiter_direction = 1;\n\t\t_mission_item.nav_cmd = NAV_CMD_WAYPOINT;\n\t\t_mission_item.acceptance_radius = _param_acceptance_radius.get();\n\t\t_mission_item.time_inside = 0.0f;\n\t\t_mission_item.pitch_min = 0.0f;\n\t\t_mission_item.autocontinue = true;\n\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t_navigator->set_is_in_loiter(false);\n\n\t\tmavlink_log_info(_navigator->get_mavlink_fd(), \"#audio: RTL: return at %d meters above home\",\n\t\t\t(int)(_mission_item.altitude - _navigator->get_home_position()->alt));\n\t\tbreak;\n\t}\n\tcase RTL_STATE_DESCEND: {\n\n\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\t\t_mission_item.altitude_is_relative = false;\n\t\t_mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get();\n\t\t_mission_item.yaw = NAN;\n\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t_mission_item.loiter_direction = 1;\n\t\t_mission_item.nav_cmd = NAV_CMD_LOITER_TIME_LIMIT;\n\t\t_mission_item.acceptance_radius = _param_acceptance_radius.get();\n\t\t_mission_item.time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get();\n\t\t_mission_item.pitch_min = 0.0f;\n\t\t_mission_item.autocontinue = _param_land_delay.get() > -0.001f;\n\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t_navigator->set_is_in_loiter(true);\n\n\t\tmavlink_log_info(_navigator->get_mavlink_fd(), \"#audio: RTL: descend to %d meters above home\",\n\t\t\t(int)(_mission_item.altitude - _navigator->get_home_position()->alt));\n\t\tbreak;\n\t}\n\n\tcase RTL_STATE_LAND: {\n\n\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\t\t_mission_item.altitude_is_relative = false;\n\t\t_mission_item.altitude = _navigator->get_home_position()->alt;\n\t\t_mission_item.yaw = NAN;\n\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t_mission_item.loiter_direction = 1;\n\t\t_mission_item.nav_cmd = NAV_CMD_LAND;\n\t\t_mission_item.acceptance_radius = _param_acceptance_radius.get();\n\t\t_mission_item.time_inside = 0.0f;\n\t\t_mission_item.pitch_min = 0.0f;\n\t\t_mission_item.autocontinue = true;\n\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t_navigator->set_is_in_loiter(false);\n\n\t\tmavlink_log_info(_navigator->get_mavlink_fd(), \"#audio: RTL: land at home\");\n\t\tbreak;\n\t}\n\n\tdefault:\n\t\tbreak;\n\t}\n\n \/* convert mission item to current position setpoint and make it valid *\/\n mission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);\n reset_mission_item_reached();\n pos_sp_triplet->current.valid = true;\n pos_sp_triplet->next.valid = false;\n}\n\nvoid\nRTL::advance_rtl()\n{\n\tswitch (_rtl_state) {\n\tcase RTL_STATE_CLIMB:\n\t\t_rtl_state = RTL_STATE_RETURN;\n\t\tbreak;\n\n\tcase RTL_STATE_RETURN:\n\t\t_rtl_state = RTL_STATE_DESCEND;\n\t\tbreak;\n\n\tcase RTL_STATE_DESCEND:\n\t\t\/* only go to land if autoland is enabled *\/\n\t\tif (_param_land_delay.get() < 0) {\n\t\t\t_rtl_state = RTL_STATE_FINISHED;\n\t\t} else {\n\t\t\t_rtl_state = RTL_STATE_LAND;\n\t\t}\n\t\tbreak;\n\n\tcase RTL_STATE_LAND:\n\t\t_rtl_state = RTL_STATE_FINISHED;\n\t\tbreak;\n\n\tcase RTL_STATE_FINISHED:\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\n\/\/ LibSourcey\n\/\/ Copyright (c) 2005, Sourcey \n\/\/\n\/\/ SPDX-License-Identifier: LGPL-2.1+\n\/\/\n\/\/\/ @addtogroup net\n\/\/\/ @{\n\n\n#include \"scy\/net\/socketadapter.h\"\n#include \"scy\/net\/socket.h\"\n\n#include \n\n\nusing std::endl;\n\n\nnamespace scy {\nnamespace net {\n\n\nSocketAdapter::SocketAdapter(SocketAdapter* sender)\n : priority(0)\n , _sender(sender)\n , _dirty(false)\n{\n \/\/ TraceS(this) << \"Create\" << endl;\n assert(sender != this);\n}\n\n\nSocketAdapter::~SocketAdapter()\n{\n \/\/ TraceS(this) << \"Destroy\" << endl;\n \/\/ assert(_receivers.empty());\n}\n\n\nssize_t SocketAdapter::send(const char* data, size_t len, int flags)\n{\n assert(_sender); \/\/ should have output adapter if default impl is used\n if (!_sender)\n return -1;\n return _sender->send(data, len, flags);\n}\n\n\nssize_t SocketAdapter::send(const char* data, size_t len, const Address& peerAddress, int flags)\n{\n assert(_sender); \/\/ should have output adapter if default impl is used\n if (!_sender)\n return -1;\n return _sender->send(data, len, peerAddress, flags);\n}\n\n\nssize_t SocketAdapter::sendPacket(const IPacket& packet, int flags)\n{\n \/\/ Try to cast as RawPacket so we can send without copying any data.\n auto raw = dynamic_cast(&packet);\n if (raw)\n return send((const char*)raw->data(), raw->size(), flags);\n\n \/\/ Dynamically generated packets need to be written to a\n \/\/ temp buffer for sending.\n else {\n Buffer buf;\n packet.write(buf);\n return send(buf.data(), buf.size(), flags);\n }\n}\n\n\nssize_t SocketAdapter::sendPacket(const IPacket& packet, const Address& peerAddress, int flags)\n{\n \/\/ Try to cast as RawPacket so we can send without copying any data.\n auto raw = dynamic_cast(&packet);\n if (raw)\n return send((const char*)raw->data(), raw->size(), peerAddress, flags);\n\n \/\/ Dynamically generated packets need to be written to a\n \/\/ temp buffer for sending.\n else {\n Buffer buf;\n buf.reserve(2048);\n packet.write(buf);\n return send(buf.data(), buf.size(), peerAddress, flags);\n }\n}\n\n\nvoid SocketAdapter::sendPacket(IPacket& packet)\n{\n size_t res = sendPacket(packet, 0);\n if (res < 0)\n throw std::runtime_error(\"Invalid socket operation\");\n}\n\n\nvoid SocketAdapter::onSocketConnect(Socket& socket)\n{\n try {\n cleanupReceivers();\n size_t current = _receivers.size() - 1;\n while (current >= 0) {\n auto ref = _receivers[current--];\n if (ref->alive)\n ref->ptr->onSocketConnect(socket);\n }\n }\n catch (StopPropagation&) {\n }\n}\n\n\nvoid SocketAdapter::onSocketRecv(Socket& socket, const MutableBuffer& buffer, const Address& peerAddress)\n{\n try {\n cleanupReceivers();\n size_t current = _receivers.size() - 1;\n while (current >= 0) {\n auto ref = _receivers[current--];\n if (ref->alive)\n ref->ptr->onSocketRecv(socket, buffer, peerAddress);\n }\n }\n catch (StopPropagation&) {\n }\n}\n\n\nvoid SocketAdapter::onSocketError(Socket& socket, const scy::Error& error)\n{\n try {\n cleanupReceivers();\n size_t current = _receivers.size() - 1;\n while (current >= 0) {\n auto ref = _receivers[current--];\n if (ref->alive)\n ref->ptr->onSocketError(socket, error);\n }\n }\n catch (StopPropagation&) {\n }\n} \n\n\nvoid SocketAdapter::onSocketClose(Socket& socket)\n{\n try {\n cleanupReceivers();\n size_t current = _receivers.size() - 1;\n while (current >= 0) {\n auto ref = _receivers[current--];\n if (ref->alive) {\n ref->ptr->onSocketClose(socket);\n }\n }\n }\n catch (StopPropagation&) {\n }\n}\n\n\nvoid SocketAdapter::setSender(SocketAdapter* adapter)\n{\n assert(adapter != this);\n if (_sender == adapter)\n return;\n _sender = adapter;\n}\n\n\nbool SocketAdapter::hasReceiver(SocketAdapter* adapter)\n{\n for (auto& receiver : _receivers) {\n if (receiver->ptr == adapter)\n return true;\n }\n return false;\n}\n\n\nvoid SocketAdapter::addReceiver(SocketAdapter* adapter)\n{\n assert(adapter->priority <= 100);\n assert(adapter != this);\n if (hasReceiver(adapter))\n return;\n\n \/\/ Note that we insert new adapters in the back of the queue,\n \/\/ and iterate in reverse to ensure calling order is preserved.\n _dirty = true;\n _receivers.push_back(new Ref{ adapter, true });\n \/\/ _receivers.insert(_receivers.begin(), new Ref{ adapter, false }); \/\/ insert front\n \/\/ std::sort(_receivers.begin(), _receivers.end(),\n \/\/ [](SocketAdapter const& l, SocketAdapter const& r) {\n \/\/ return l.priority > r.priority; });\n}\n\n\nvoid SocketAdapter::removeReceiver(SocketAdapter* adapter)\n{\n assert(adapter != this);\n auto it = std::find_if(_receivers.begin(), _receivers.end(),\n [&](const Ref* ref) { return ref->ptr == adapter; });\n if (it != _receivers.end()) { (*it)->alive = false; }\n}\n\n\nvoid SocketAdapter::cleanupReceivers()\n{\n if (!_dirty) return;\n for (auto it = _receivers.begin(); it != _receivers.end();) {\n auto ref = *it;\n if (!ref->alive) {\n delete ref;\n it = _receivers.erase(it);\n }\n else ++it;\n }\n _dirty = false;\n}\n\n\nSocketAdapter* SocketAdapter::sender()\n{\n return _sender;\n}\n\n\nstd::vector SocketAdapter::receivers()\n{\n std::vector items;\n std::transform(_receivers.begin(), _receivers.end(), std::back_inserter(items),\n [](const Ref* ref) { return ref->ptr; });\n return items;\n}\n\n\n} \/\/ namespace net\n} \/\/ namespace scy\n\n\n\/\/\/ @\\}\nUpdate the use of signed\/unsigned integers\/\/\/\n\/\/\n\/\/ LibSourcey\n\/\/ Copyright (c) 2005, Sourcey \n\/\/\n\/\/ SPDX-License-Identifier: LGPL-2.1+\n\/\/\n\/\/\/ @addtogroup net\n\/\/\/ @{\n\n\n#include \"scy\/net\/socketadapter.h\"\n#include \"scy\/net\/socket.h\"\n\n#include \n\n\nusing std::endl;\n\n\nnamespace scy {\nnamespace net {\n\n\nSocketAdapter::SocketAdapter(SocketAdapter* sender)\n : priority(0)\n , _sender(sender)\n , _dirty(false)\n{\n \/\/ TraceS(this) << \"Create\" << endl;\n assert(sender != this);\n}\n\n\nSocketAdapter::~SocketAdapter()\n{\n \/\/ TraceS(this) << \"Destroy\" << endl;\n \/\/ assert(_receivers.empty());\n}\n\n\nssize_t SocketAdapter::send(const char* data, size_t len, int flags)\n{\n assert(_sender); \/\/ should have output adapter if default impl is used\n if (!_sender)\n return -1;\n return _sender->send(data, len, flags);\n}\n\n\nssize_t SocketAdapter::send(const char* data, size_t len, const Address& peerAddress, int flags)\n{\n assert(_sender); \/\/ should have output adapter if default impl is used\n if (!_sender)\n return -1;\n return _sender->send(data, len, peerAddress, flags);\n}\n\n\nssize_t SocketAdapter::sendPacket(const IPacket& packet, int flags)\n{\n \/\/ Try to cast as RawPacket so we can send without copying any data.\n auto raw = dynamic_cast(&packet);\n if (raw)\n return send((const char*)raw->data(), raw->size(), flags);\n\n \/\/ Dynamically generated packets need to be written to a\n \/\/ temp buffer for sending.\n else {\n Buffer buf;\n packet.write(buf);\n return send(buf.data(), buf.size(), flags);\n }\n}\n\n\nssize_t SocketAdapter::sendPacket(const IPacket& packet, const Address& peerAddress, int flags)\n{\n \/\/ Try to cast as RawPacket so we can send without copying any data.\n auto raw = dynamic_cast(&packet);\n if (raw)\n return send((const char*)raw->data(), raw->size(), peerAddress, flags);\n\n \/\/ Dynamically generated packets need to be written to a\n \/\/ temp buffer for sending.\n else {\n Buffer buf;\n buf.reserve(2048);\n packet.write(buf);\n return send(buf.data(), buf.size(), peerAddress, flags);\n }\n}\n\n\nvoid SocketAdapter::sendPacket(IPacket& packet)\n{\n size_t res = sendPacket(packet, 0);\n if (res < 0)\n throw std::runtime_error(\"Invalid socket operation\");\n}\n\n\nvoid SocketAdapter::onSocketConnect(Socket& socket)\n{\n try {\n cleanupReceivers();\n int current = int(_receivers.size() - 1);\n while (current >= 0) {\n auto ref = _receivers[current--];\n if (ref->alive)\n ref->ptr->onSocketConnect(socket);\n }\n }\n catch (StopPropagation&) {\n }\n}\n\n\nvoid SocketAdapter::onSocketRecv(Socket& socket, const MutableBuffer& buffer, const Address& peerAddress)\n{\n try {\n cleanupReceivers();\n int current = int(_receivers.size() - 1);\n while (current >= 0) {\n auto ref = _receivers[current--];\n if (ref->alive)\n ref->ptr->onSocketRecv(socket, buffer, peerAddress);\n }\n }\n catch (StopPropagation&) {\n }\n}\n\n\nvoid SocketAdapter::onSocketError(Socket& socket, const scy::Error& error)\n{\n try {\n cleanupReceivers();\n int current = int(_receivers.size() - 1);\n while (current >= 0) {\n auto ref = _receivers[current--];\n if (ref->alive)\n ref->ptr->onSocketError(socket, error);\n }\n }\n catch (StopPropagation&) {\n }\n} \n\n\nvoid SocketAdapter::onSocketClose(Socket& socket)\n{\n try {\n cleanupReceivers();\n int current = int(_receivers.size() - 1);\n while (current >= 0) {\n auto ref = _receivers[current--];\n if (ref->alive) {\n ref->ptr->onSocketClose(socket);\n }\n }\n }\n catch (StopPropagation&) {\n }\n}\n\n\nvoid SocketAdapter::setSender(SocketAdapter* adapter)\n{\n assert(adapter != this);\n if (_sender == adapter)\n return;\n _sender = adapter;\n}\n\n\nbool SocketAdapter::hasReceiver(SocketAdapter* adapter)\n{\n for (auto& receiver : _receivers) {\n if (receiver->ptr == adapter)\n return true;\n }\n return false;\n}\n\n\nvoid SocketAdapter::addReceiver(SocketAdapter* adapter)\n{\n assert(adapter->priority <= 100);\n assert(adapter != this);\n if (hasReceiver(adapter))\n return;\n\n \/\/ Note that we insert new adapters in the back of the queue,\n \/\/ and iterate in reverse to ensure calling order is preserved.\n _dirty = true;\n _receivers.push_back(new Ref{ adapter, true });\n \/\/ _receivers.insert(_receivers.begin(), new Ref{ adapter, false }); \/\/ insert front\n \/\/ std::sort(_receivers.begin(), _receivers.end(),\n \/\/ [](SocketAdapter const& l, SocketAdapter const& r) {\n \/\/ return l.priority > r.priority; });\n}\n\n\nvoid SocketAdapter::removeReceiver(SocketAdapter* adapter)\n{\n assert(adapter != this);\n auto it = std::find_if(_receivers.begin(), _receivers.end(),\n [&](const Ref* ref) { return ref->ptr == adapter; });\n if (it != _receivers.end()) { (*it)->alive = false; }\n}\n\n\nvoid SocketAdapter::cleanupReceivers()\n{\n if (!_dirty) return;\n for (auto it = _receivers.begin(); it != _receivers.end();) {\n auto ref = *it;\n if (!ref->alive) {\n delete ref;\n it = _receivers.erase(it);\n }\n else ++it;\n }\n _dirty = false;\n}\n\n\nSocketAdapter* SocketAdapter::sender()\n{\n return _sender;\n}\n\n\nstd::vector SocketAdapter::receivers()\n{\n std::vector items;\n std::transform(_receivers.begin(), _receivers.end(), std::back_inserter(items),\n [](const Ref* ref) { return ref->ptr; });\n return items;\n}\n\n\n} \/\/ namespace net\n} \/\/ namespace scy\n\n\n\/\/\/ @\\}\n<|endoftext|>"} {"text":"\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2010, 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\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 Rice University 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 \"ompl\/base\/Planner.h\"\n#include \"ompl\/util\/Exception.h\"\n#include \"ompl\/base\/GoalSampleableRegion.h\"\n#include \n\nompl::base::Planner::Planner(const SpaceInformationPtr &si, const std::string &name) :\n si_(si), pis_(this), name_(name), setup_(false), msg_(name)\n{\n if (!si_)\n throw Exception(name_, \"Invalid space information instance for planner\");\n}\n\nconst ompl::base::PlannerSpecs& ompl::base::Planner::getSpecs(void) const\n{\n return specs_;\n}\n\nconst std::string& ompl::base::Planner::getName(void) const\n{\n return name_;\n}\n\nvoid ompl::base::Planner::setName(const std::string &name)\n{\n name_ = name;\n msg_.setPrefix(name_);\n}\n\nconst ompl::base::SpaceInformationPtr& ompl::base::Planner::getSpaceInformation(void) const\n{\n return si_;\n}\n\nconst ompl::base::ProblemDefinitionPtr& ompl::base::Planner::getProblemDefinition(void) const\n{\n return pdef_;\n}\n\nvoid ompl::base::Planner::setProblemDefinition(const ProblemDefinitionPtr &pdef)\n{\n pdef_ = pdef;\n pis_.update();\n}\n\nconst ompl::base::PlannerInputStates& ompl::base::Planner::getPlannerInputStates(void) const\n{\n return pis_;\n}\n\nvoid ompl::base::Planner::setup(void)\n{\n if (!si_->isSetup())\n {\n msg_.inform(\"Space information setup was not yet called. Calling now.\");\n si_->setup();\n }\n\n if (setup_)\n msg_.warn(\"Planner setup called multiple times\");\n else\n setup_ = true;\n}\n\nvoid ompl::base::Planner::checkValidity(void)\n{\n if (!isSetup())\n setup();\n pis_.checkValidity();\n}\n\nbool ompl::base::Planner::isSetup(void) const\n{\n return setup_;\n}\n\nvoid ompl::base::Planner::clear(void)\n{\n pis_.clear();\n pis_.update();\n}\n\nvoid ompl::base::Planner::getPlannerData(PlannerData &data) const\n{\n}\n\nompl::base::PlannerStatus ompl::base::Planner::solve(const PlannerTerminationConditionFn &ptc, double checkInterval)\n{\n return solve(PlannerThreadedTerminationCondition(ptc, checkInterval));\n}\n\nompl::base::PlannerStatus ompl::base::Planner::solve(double solveTime)\n{\n if (solveTime < 1.0)\n return solve(timedPlannerTerminationCondition(solveTime));\n else\n return solve(timedPlannerTerminationCondition(solveTime, std::min(solveTime \/ 100.0, 0.1)));\n}\n\nvoid ompl::base::Planner::printProperties(std::ostream &out) const\n{\n out << \"Planner \" + getName() + \" specs:\" << std::endl;\n out << \"Multithreaded: \" << (getSpecs().multithreaded ? \"Yes\" : \"No\") << std::endl;\n out << \"Reports approximate solutions: \" << (getSpecs().approximateSolutions ? \"Yes\" : \"No\") << std::endl;\n out << \"Can optimize solutions: \" << (getSpecs().optimizingPaths ? \"Yes\" : \"No\") << std::endl;\n out << \"Aware of the following parameters:\";\n std::vector params;\n params_.getParamNames(params);\n for (unsigned int i = 0 ; i < params.size() ; ++i)\n out << \" \" << params[i];\n out << std::endl;\n}\n\nvoid ompl::base::Planner::printSettings(std::ostream &out) const\n{\n out << \"Declared parameters for planner \" << getName() << \":\" << std::endl;\n params_.print(out);\n}\n\nvoid ompl::base::PlannerInputStates::clear(void)\n{\n if (tempState_)\n {\n si_->freeState(tempState_);\n tempState_ = NULL;\n }\n addedStartStates_ = 0;\n sampledGoalsCount_ = 0;\n pdef_ = NULL;\n si_ = NULL;\n}\n\nvoid ompl::base::PlannerInputStates::restart(void)\n{\n addedStartStates_ = 0;\n sampledGoalsCount_ = 0;\n}\n\nbool ompl::base::PlannerInputStates::update(void)\n{\n if (!planner_)\n throw Exception(\"No planner set for PlannerInputStates\");\n return use(planner_->getSpaceInformation(), planner_->getProblemDefinition());\n}\n\nvoid ompl::base::PlannerInputStates::checkValidity(void) const\n{\n std::string error;\n\n if (!pdef_)\n error = \"Problem definition not specified\";\n else\n {\n if (pdef_->getStartStateCount() <= 0)\n error = \"No start states specified\";\n else\n if (!pdef_->getGoal())\n error = \"No goal specified\";\n }\n\n if (!error.empty())\n {\n if (planner_)\n throw Exception(planner_->getName(), error);\n else\n throw Exception(error);\n }\n}\n\nbool ompl::base::PlannerInputStates::use(const SpaceInformationPtr &si, const ProblemDefinitionPtr &pdef)\n{\n if (si && pdef)\n return use(si.get(), pdef.get());\n else\n {\n clear();\n return true;\n }\n}\n\nbool ompl::base::PlannerInputStates::use(const SpaceInformation *si, const ProblemDefinition *pdef)\n{\n if (pdef_ != pdef || si_ != si)\n {\n clear();\n pdef_ = pdef;\n si_ = si;\n return true;\n }\n return false;\n}\n\nconst ompl::base::State* ompl::base::PlannerInputStates::nextStart(void)\n{\n if (pdef_ == NULL || si_ == NULL)\n {\n std::string error = \"Missing space information or problem definition\";\n if (planner_)\n throw Exception(planner_->getName(), error);\n else\n throw Exception(error);\n }\n\n while (addedStartStates_ < pdef_->getStartStateCount())\n {\n const base::State *st = pdef_->getStartState(addedStartStates_);\n addedStartStates_++;\n bool bounds = si_->satisfiesBounds(st);\n bool valid = bounds ? si_->isValid(st) : false;\n if (bounds && valid)\n return st;\n else\n {\n msg::Interface msg(planner_ ? planner_->getName() : \"\");\n msg.warn(\"Skipping invalid start state (invalid %s)\", bounds ? \"state\": \"bounds\");\n }\n }\n return NULL;\n}\n\nconst ompl::base::State* ompl::base::PlannerInputStates::nextGoal(void)\n{\n static PlannerAlwaysTerminatingCondition ptc;\n return nextGoal(ptc);\n}\n\nconst ompl::base::State* ompl::base::PlannerInputStates::nextGoal(const PlannerTerminationCondition &ptc)\n{\n if (pdef_ == NULL || si_ == NULL)\n {\n std::string error = \"Missing space information or problem definition\";\n if (planner_)\n throw Exception(planner_->getName(), error);\n else\n throw Exception(error);\n }\n\n const GoalSampleableRegion *goal = pdef_->getGoal()->hasType(GOAL_SAMPLEABLE_REGION) ? pdef_->getGoal()->as() : NULL;\n\n if (goal)\n {\n time::point start_wait;\n bool first = true;\n bool attempt = true;\n while (attempt)\n {\n attempt = false;\n\n if (sampledGoalsCount_ < goal->maxSampleCount() && goal->canSample())\n {\n if (tempState_ == NULL)\n tempState_ = si_->allocState();\n do\n {\n goal->sampleGoal(tempState_);\n sampledGoalsCount_++;\n bool bounds = si_->satisfiesBounds(tempState_);\n bool valid = bounds ? si_->isValid(tempState_) : false;\n if (bounds && valid)\n {\n if (!first) \/\/ if we waited, show how long\n {\n msg::Interface msg(planner_ ? planner_->getName() : \"\");\n msg.debug(\"Waited %lf seconds for the first goal sample.\", time::seconds(time::now() - start_wait));\n }\n return tempState_;\n }\n else\n {\n msg::Interface msg(planner_ ? planner_->getName() : \"\");\n msg.warn(\"Skipping invalid goal state (invalid %s)\", bounds ? \"state\": \"bounds\");\n }\n }\n while (!ptc() && sampledGoalsCount_ < goal->maxSampleCount() && goal->canSample());\n }\n if (goal->couldSample() && !ptc())\n {\n if (first)\n {\n first = false;\n start_wait = time::now();\n msg::Interface msg(planner_ ? planner_->getName() : \"\");\n msg.debug(\"Waiting for goal region samples ...\");\n }\n boost::this_thread::sleep(time::seconds(0.01));\n attempt = !ptc();\n }\n }\n }\n\n return NULL;\n}\n\nbool ompl::base::PlannerInputStates::haveMoreStartStates(void) const\n{\n if (pdef_)\n return addedStartStates_ < pdef_->getStartStateCount();\n return false;\n}\n\nbool ompl::base::PlannerInputStates::haveMoreGoalStates(void) const\n{\n if (pdef_ && pdef_->getGoal())\n if (pdef_->getGoal()->hasType(GOAL_SAMPLEABLE_REGION))\n return sampledGoalsCount_ < pdef_->getGoal()->as()->maxSampleCount();\n return false;\n}\nmore debug info\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2010, 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\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 Rice University 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 \"ompl\/base\/Planner.h\"\n#include \"ompl\/util\/Exception.h\"\n#include \"ompl\/base\/GoalSampleableRegion.h\"\n#include \n#include \n\nompl::base::Planner::Planner(const SpaceInformationPtr &si, const std::string &name) :\n si_(si), pis_(this), name_(name), setup_(false), msg_(name)\n{\n if (!si_)\n throw Exception(name_, \"Invalid space information instance for planner\");\n}\n\nconst ompl::base::PlannerSpecs& ompl::base::Planner::getSpecs(void) const\n{\n return specs_;\n}\n\nconst std::string& ompl::base::Planner::getName(void) const\n{\n return name_;\n}\n\nvoid ompl::base::Planner::setName(const std::string &name)\n{\n name_ = name;\n msg_.setPrefix(name_);\n}\n\nconst ompl::base::SpaceInformationPtr& ompl::base::Planner::getSpaceInformation(void) const\n{\n return si_;\n}\n\nconst ompl::base::ProblemDefinitionPtr& ompl::base::Planner::getProblemDefinition(void) const\n{\n return pdef_;\n}\n\nvoid ompl::base::Planner::setProblemDefinition(const ProblemDefinitionPtr &pdef)\n{\n pdef_ = pdef;\n pis_.update();\n}\n\nconst ompl::base::PlannerInputStates& ompl::base::Planner::getPlannerInputStates(void) const\n{\n return pis_;\n}\n\nvoid ompl::base::Planner::setup(void)\n{\n if (!si_->isSetup())\n {\n msg_.inform(\"Space information setup was not yet called. Calling now.\");\n si_->setup();\n }\n\n if (setup_)\n msg_.warn(\"Planner setup called multiple times\");\n else\n setup_ = true;\n}\n\nvoid ompl::base::Planner::checkValidity(void)\n{\n if (!isSetup())\n setup();\n pis_.checkValidity();\n}\n\nbool ompl::base::Planner::isSetup(void) const\n{\n return setup_;\n}\n\nvoid ompl::base::Planner::clear(void)\n{\n pis_.clear();\n pis_.update();\n}\n\nvoid ompl::base::Planner::getPlannerData(PlannerData &data) const\n{\n}\n\nompl::base::PlannerStatus ompl::base::Planner::solve(const PlannerTerminationConditionFn &ptc, double checkInterval)\n{\n return solve(PlannerThreadedTerminationCondition(ptc, checkInterval));\n}\n\nompl::base::PlannerStatus ompl::base::Planner::solve(double solveTime)\n{\n if (solveTime < 1.0)\n return solve(timedPlannerTerminationCondition(solveTime));\n else\n return solve(timedPlannerTerminationCondition(solveTime, std::min(solveTime \/ 100.0, 0.1)));\n}\n\nvoid ompl::base::Planner::printProperties(std::ostream &out) const\n{\n out << \"Planner \" + getName() + \" specs:\" << std::endl;\n out << \"Multithreaded: \" << (getSpecs().multithreaded ? \"Yes\" : \"No\") << std::endl;\n out << \"Reports approximate solutions: \" << (getSpecs().approximateSolutions ? \"Yes\" : \"No\") << std::endl;\n out << \"Can optimize solutions: \" << (getSpecs().optimizingPaths ? \"Yes\" : \"No\") << std::endl;\n out << \"Aware of the following parameters:\";\n std::vector params;\n params_.getParamNames(params);\n for (unsigned int i = 0 ; i < params.size() ; ++i)\n out << \" \" << params[i];\n out << std::endl;\n}\n\nvoid ompl::base::Planner::printSettings(std::ostream &out) const\n{\n out << \"Declared parameters for planner \" << getName() << \":\" << std::endl;\n params_.print(out);\n}\n\nvoid ompl::base::PlannerInputStates::clear(void)\n{\n if (tempState_)\n {\n si_->freeState(tempState_);\n tempState_ = NULL;\n }\n addedStartStates_ = 0;\n sampledGoalsCount_ = 0;\n pdef_ = NULL;\n si_ = NULL;\n}\n\nvoid ompl::base::PlannerInputStates::restart(void)\n{\n addedStartStates_ = 0;\n sampledGoalsCount_ = 0;\n}\n\nbool ompl::base::PlannerInputStates::update(void)\n{\n if (!planner_)\n throw Exception(\"No planner set for PlannerInputStates\");\n return use(planner_->getSpaceInformation(), planner_->getProblemDefinition());\n}\n\nvoid ompl::base::PlannerInputStates::checkValidity(void) const\n{\n std::string error;\n\n if (!pdef_)\n error = \"Problem definition not specified\";\n else\n {\n if (pdef_->getStartStateCount() <= 0)\n error = \"No start states specified\";\n else\n if (!pdef_->getGoal())\n error = \"No goal specified\";\n }\n\n if (!error.empty())\n {\n if (planner_)\n throw Exception(planner_->getName(), error);\n else\n throw Exception(error);\n }\n}\n\nbool ompl::base::PlannerInputStates::use(const SpaceInformationPtr &si, const ProblemDefinitionPtr &pdef)\n{\n if (si && pdef)\n return use(si.get(), pdef.get());\n else\n {\n clear();\n return true;\n }\n}\n\nbool ompl::base::PlannerInputStates::use(const SpaceInformation *si, const ProblemDefinition *pdef)\n{\n if (pdef_ != pdef || si_ != si)\n {\n clear();\n pdef_ = pdef;\n si_ = si;\n return true;\n }\n return false;\n}\n\nconst ompl::base::State* ompl::base::PlannerInputStates::nextStart(void)\n{\n if (pdef_ == NULL || si_ == NULL)\n {\n std::string error = \"Missing space information or problem definition\";\n if (planner_)\n throw Exception(planner_->getName(), error);\n else\n throw Exception(error);\n }\n\n while (addedStartStates_ < pdef_->getStartStateCount())\n {\n const base::State *st = pdef_->getStartState(addedStartStates_);\n addedStartStates_++;\n bool bounds = si_->satisfiesBounds(st);\n bool valid = bounds ? si_->isValid(st) : false;\n if (bounds && valid)\n return st;\n else\n {\n msg::Interface msg(planner_ ? planner_->getName() : \"\");\n msg.warn(\"Skipping invalid start state (invalid %s)\", bounds ? \"state\": \"bounds\");\n std::stringstream ss;\n si_->printState(st, ss);\n msg.debug(\"Discarded start state %s\", ss.str().c_str());\n }\n }\n return NULL;\n}\n\nconst ompl::base::State* ompl::base::PlannerInputStates::nextGoal(void)\n{\n static PlannerAlwaysTerminatingCondition ptc;\n return nextGoal(ptc);\n}\n\nconst ompl::base::State* ompl::base::PlannerInputStates::nextGoal(const PlannerTerminationCondition &ptc)\n{\n if (pdef_ == NULL || si_ == NULL)\n {\n std::string error = \"Missing space information or problem definition\";\n if (planner_)\n throw Exception(planner_->getName(), error);\n else\n throw Exception(error);\n }\n\n const GoalSampleableRegion *goal = pdef_->getGoal()->hasType(GOAL_SAMPLEABLE_REGION) ? pdef_->getGoal()->as() : NULL;\n\n if (goal)\n {\n time::point start_wait;\n bool first = true;\n bool attempt = true;\n while (attempt)\n {\n attempt = false;\n\n if (sampledGoalsCount_ < goal->maxSampleCount() && goal->canSample())\n {\n if (tempState_ == NULL)\n tempState_ = si_->allocState();\n do\n {\n goal->sampleGoal(tempState_);\n sampledGoalsCount_++;\n bool bounds = si_->satisfiesBounds(tempState_);\n bool valid = bounds ? si_->isValid(tempState_) : false;\n if (bounds && valid)\n {\n if (!first) \/\/ if we waited, show how long\n {\n msg::Interface msg(planner_ ? planner_->getName() : \"\");\n msg.debug(\"Waited %lf seconds for the first goal sample.\", time::seconds(time::now() - start_wait));\n }\n return tempState_;\n }\n else\n {\n msg::Interface msg(planner_ ? planner_->getName() : \"\");\n msg.warn(\"Skipping invalid goal state (invalid %s)\", bounds ? \"state\": \"bounds\");\n std::stringstream ss;\n si_->printState(tempState_, ss);\n msg.debug(\"Discarded goal state %s\", ss.str().c_str());\n }\n }\n while (!ptc() && sampledGoalsCount_ < goal->maxSampleCount() && goal->canSample());\n }\n if (goal->couldSample() && !ptc())\n {\n if (first)\n {\n first = false;\n start_wait = time::now();\n msg::Interface msg(planner_ ? planner_->getName() : \"\");\n msg.debug(\"Waiting for goal region samples ...\");\n }\n boost::this_thread::sleep(time::seconds(0.01));\n attempt = !ptc();\n }\n }\n }\n\n return NULL;\n}\n\nbool ompl::base::PlannerInputStates::haveMoreStartStates(void) const\n{\n if (pdef_)\n return addedStartStates_ < pdef_->getStartStateCount();\n return false;\n}\n\nbool ompl::base::PlannerInputStates::haveMoreGoalStates(void) const\n{\n if (pdef_ && pdef_->getGoal())\n if (pdef_->getGoal()->hasType(GOAL_SAMPLEABLE_REGION))\n return sampledGoalsCount_ < pdef_->getGoal()->as()->maxSampleCount();\n return false;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"simple_label.h\"\n#include \"cache.h\"\n#include \"rand48.h\"\n#include \"vw.h\"\n\nusing namespace std;\n\nchar* bufread_simple_label(shared_data* sd, label_data* ld, char* c)\n{\n ld->label = *(float *)c;\n c += sizeof(ld->label);\n if (sd->binary_label && fabs(ld->label) != 1.f && ld->label != FLT_MAX)\n cout << \"You are using a label not -1 or 1 with a loss function expecting that!\" << endl;\n ld->weight = *(float *)c;\n c += sizeof(ld->weight);\n ld->initial = *(float *)c;\n c += sizeof(ld->initial);\n return c;\n}\n\nsize_t read_cached_simple_label(shared_data* sd, void* v, io_buf& cache)\n{\n label_data* ld = (label_data*) v;\n char *c;\n size_t total = sizeof(ld->label)+sizeof(ld->weight)+sizeof(ld->initial);\n if (buf_read(cache, c, total) < total) \n return 0;\n c = bufread_simple_label(sd, ld,c);\n\n return total;\n}\n\nfloat get_weight(void* v)\n{\n label_data* ld = (label_data*) v;\n return ld->weight;\n}\n\nfloat get_initial(void* v)\n{\n label_data* ld = (label_data*) v;\n return ld->initial;\n}\n\nchar* bufcache_simple_label(label_data* ld, char* c)\n{\n *(float *)c = ld->label;\n c += sizeof(ld->label);\n *(float *)c = ld->weight;\n c += sizeof(ld->weight);\n *(float *)c = ld->initial;\n c += sizeof(ld->initial);\n return c;\n}\n\nvoid cache_simple_label(void* v, io_buf& cache)\n{\n char *c;\n label_data* ld = (label_data*) v;\n buf_write(cache, c, sizeof(ld->label)+sizeof(ld->weight)+sizeof(ld->initial));\n c = bufcache_simple_label(ld,c);\n}\n\nvoid default_simple_label(void* v)\n{\n label_data* ld = (label_data*) v;\n ld->label = FLT_MAX;\n ld->weight = 1.;\n ld->initial = 0.;\n}\n\nvoid delete_simple_label(void* v)\n{\n}\n\nvoid parse_simple_label(parser* p, shared_data* sd, void* v, v_array& words)\n{\n label_data* ld = (label_data*)v;\n\n switch(words.size()) {\n case 0:\n break;\n case 1:\n ld->label = float_of_substring(words[0]);\n break;\n case 2:\n ld->label = float_of_substring(words[0]);\n ld->weight = float_of_substring(words[1]);\n break;\n case 3:\n ld->label = float_of_substring(words[0]);\n ld->weight = float_of_substring(words[1]);\n ld->initial = float_of_substring(words[2]);\n break;\n default:\n cerr << \"malformed example!\\n\";\n cerr << \"words.size() = \" << words.size() << endl;\n }\n if (words.size() > 0 && sd->binary_label && fabs(ld->label) != 1.f)\n cout << \"You are using a label not -1 or 1 with a loss function expecting that!\" << endl;\n}\n\nfloat get_active_coin_bias(float k, float l, float g, float c0)\n{\n float b,sb,rs,sl;\n b=(float)(c0*(log(k+1.)+0.0001)\/(k+0.0001));\n sb=sqrt(b);\n if (l > 1.0) { l = 1.0; } else if (l < 0.0) { l = 0.0; } \/\/loss should be in [0,1]\n sl=sqrt(l)+sqrt(l+g);\n if (g<=sb*sl+b)\n return 1;\n rs = (sl+sqrt(sl*sl+4*g))\/(2*g);\n return b*rs*rs;\n}\n\nfloat query_decision(vw& all, example* ec, float k)\n{\n float bias, avg_loss, weighted_queries;\n if (k<=1.)\n bias=1.;\n else{\n weighted_queries = (float)(all.initial_t + all.sd->weighted_examples - all.sd->weighted_unlabeled_examples);\n avg_loss = (float)(all.sd->sum_loss\/k + sqrt((1.+0.5*log(k))\/(weighted_queries+0.0001)));\n bias = get_active_coin_bias(k, avg_loss, ec->revert_weight\/k, all.active_c0);\n }\n if(frand48()weighted_examples > all.sd->dump_interval && !all.quiet && !all.bfgs)\n {\n label_data* ld = (label_data*) ec->ld;\n char label_buf[32];\n if (ld->label == FLT_MAX)\n\tstrcpy(label_buf,\" unknown\");\n else\n\tsprintf(label_buf,\"%8.4f\",ld->label);\n \n if(!all.holdout_set_off && all.current_pass >= 1){\n\n fprintf(stderr, \"%-6.5fh %-6.5fh %10ld %11.1f %s %8.4f %8lu\\n\",\n\t all.sd->holdout_sum_loss\/all.sd->weighted_holdout_examples,\n\t all.sd->holdout_sum_loss_since_last_dump \/ all.sd->weighted_holdout_examples_since_last_dump,\n\t (long int)all.sd->example_number,\n\t all.sd->weighted_examples,\n\t label_buf,\n\t ec->final_prediction,\n\t (long unsigned int)ec->num_features);\n\n all.sd->weighted_holdout_examples_since_last_dump = 0;\n all.sd->holdout_sum_loss_since_last_dump = 0.0;\n }\n else\n fprintf(stderr, \"%-10.6f %-10.6f %10ld %11.1f %s %8.4f %8lu\\n\",\n\t all.sd->sum_loss\/all.sd->weighted_examples,\n\t all.sd->sum_loss_since_last_dump \/ (all.sd->weighted_examples - all.sd->old_weighted_examples),\n\t (long int)all.sd->example_number,\n\t all.sd->weighted_examples,\n\t label_buf,\n\t ec->final_prediction,\n\t (long unsigned int)ec->num_features);\n \n all.sd->sum_loss_since_last_dump = 0.0;\n all.sd->old_weighted_examples = all.sd->weighted_examples;\n all.sd->dump_interval *= 2;\n }\n}\n\nvoid output_and_account_example(vw& all, example* ec)\n{\n label_data* ld = (label_data*)ec->ld;\n\n if(ec->test_only)\n {\n all.sd->weighted_holdout_examples += ec->global_weight;\/\/test weight seen\n all.sd->weighted_holdout_examples_since_last_dump += ec->global_weight;\n }\n else\n {\n all.sd->weighted_examples += ld->weight;\n all.sd->weighted_labels += ld->label == FLT_MAX ? 0 : ld->label * ld->weight;\n all.sd->total_features += ec->num_features;\n all.sd->sum_loss += ec->loss;\n all.sd->sum_loss_since_last_dump += ec->loss;\n all.sd->example_number++;\n }\n all.print(all.raw_prediction, ec->partial_prediction, -1, ec->tag);\n\n float ai=-1; \n if(all.active && ld->label == FLT_MAX)\n ai=query_decision(all, ec, (float)all.sd->weighted_unlabeled_examples);\n all.sd->weighted_unlabeled_examples += ld->label == FLT_MAX ? ld->weight : 0;\n \n for (size_t i = 0; ifinal_prediction, ai, ec->tag);\n else if (all.lda > 0)\n\tprint_lda_result(all, f,ec->topic_predictions.begin,0.,ec->tag);\n else\n\tall.print(f, ec->final_prediction, 0, ec->tag);\n }\n\n \n\n print_update(all, ec);\n}\n\nvoid return_simple_example(vw& all, example* ec)\n{\n if (!command_example(&all, ec))\n output_and_account_example(all, ec);\n VW::finish_example(all,ec);\n}\n\nadd h to the end of each line#include \n#include \n#include \n\n#include \"simple_label.h\"\n#include \"cache.h\"\n#include \"rand48.h\"\n#include \"vw.h\"\n\nusing namespace std;\n\nchar* bufread_simple_label(shared_data* sd, label_data* ld, char* c)\n{\n ld->label = *(float *)c;\n c += sizeof(ld->label);\n if (sd->binary_label && fabs(ld->label) != 1.f && ld->label != FLT_MAX)\n cout << \"You are using a label not -1 or 1 with a loss function expecting that!\" << endl;\n ld->weight = *(float *)c;\n c += sizeof(ld->weight);\n ld->initial = *(float *)c;\n c += sizeof(ld->initial);\n return c;\n}\n\nsize_t read_cached_simple_label(shared_data* sd, void* v, io_buf& cache)\n{\n label_data* ld = (label_data*) v;\n char *c;\n size_t total = sizeof(ld->label)+sizeof(ld->weight)+sizeof(ld->initial);\n if (buf_read(cache, c, total) < total) \n return 0;\n c = bufread_simple_label(sd, ld,c);\n\n return total;\n}\n\nfloat get_weight(void* v)\n{\n label_data* ld = (label_data*) v;\n return ld->weight;\n}\n\nfloat get_initial(void* v)\n{\n label_data* ld = (label_data*) v;\n return ld->initial;\n}\n\nchar* bufcache_simple_label(label_data* ld, char* c)\n{\n *(float *)c = ld->label;\n c += sizeof(ld->label);\n *(float *)c = ld->weight;\n c += sizeof(ld->weight);\n *(float *)c = ld->initial;\n c += sizeof(ld->initial);\n return c;\n}\n\nvoid cache_simple_label(void* v, io_buf& cache)\n{\n char *c;\n label_data* ld = (label_data*) v;\n buf_write(cache, c, sizeof(ld->label)+sizeof(ld->weight)+sizeof(ld->initial));\n c = bufcache_simple_label(ld,c);\n}\n\nvoid default_simple_label(void* v)\n{\n label_data* ld = (label_data*) v;\n ld->label = FLT_MAX;\n ld->weight = 1.;\n ld->initial = 0.;\n}\n\nvoid delete_simple_label(void* v)\n{\n}\n\nvoid parse_simple_label(parser* p, shared_data* sd, void* v, v_array& words)\n{\n label_data* ld = (label_data*)v;\n\n switch(words.size()) {\n case 0:\n break;\n case 1:\n ld->label = float_of_substring(words[0]);\n break;\n case 2:\n ld->label = float_of_substring(words[0]);\n ld->weight = float_of_substring(words[1]);\n break;\n case 3:\n ld->label = float_of_substring(words[0]);\n ld->weight = float_of_substring(words[1]);\n ld->initial = float_of_substring(words[2]);\n break;\n default:\n cerr << \"malformed example!\\n\";\n cerr << \"words.size() = \" << words.size() << endl;\n }\n if (words.size() > 0 && sd->binary_label && fabs(ld->label) != 1.f)\n cout << \"You are using a label not -1 or 1 with a loss function expecting that!\" << endl;\n}\n\nfloat get_active_coin_bias(float k, float l, float g, float c0)\n{\n float b,sb,rs,sl;\n b=(float)(c0*(log(k+1.)+0.0001)\/(k+0.0001));\n sb=sqrt(b);\n if (l > 1.0) { l = 1.0; } else if (l < 0.0) { l = 0.0; } \/\/loss should be in [0,1]\n sl=sqrt(l)+sqrt(l+g);\n if (g<=sb*sl+b)\n return 1;\n rs = (sl+sqrt(sl*sl+4*g))\/(2*g);\n return b*rs*rs;\n}\n\nfloat query_decision(vw& all, example* ec, float k)\n{\n float bias, avg_loss, weighted_queries;\n if (k<=1.)\n bias=1.;\n else{\n weighted_queries = (float)(all.initial_t + all.sd->weighted_examples - all.sd->weighted_unlabeled_examples);\n avg_loss = (float)(all.sd->sum_loss\/k + sqrt((1.+0.5*log(k))\/(weighted_queries+0.0001)));\n bias = get_active_coin_bias(k, avg_loss, ec->revert_weight\/k, all.active_c0);\n }\n if(frand48()weighted_examples > all.sd->dump_interval && !all.quiet && !all.bfgs)\n {\n label_data* ld = (label_data*) ec->ld;\n char label_buf[32];\n if (ld->label == FLT_MAX)\n\tstrcpy(label_buf,\" unknown\");\n else\n\tsprintf(label_buf,\"%8.4f\",ld->label);\n \n if(!all.holdout_set_off && all.current_pass >= 1){\n\n fprintf(stderr, \"%-10.6f %-10.6f %10ld %11.1f %s %8.4f %8luh\\n\",\n\t all.sd->holdout_sum_loss\/all.sd->weighted_holdout_examples,\n\t all.sd->holdout_sum_loss_since_last_dump \/ all.sd->weighted_holdout_examples_since_last_dump,\n\t (long int)all.sd->example_number,\n\t all.sd->weighted_examples,\n\t label_buf,\n\t ec->final_prediction,\n\t (long unsigned int)ec->num_features);\n\n all.sd->weighted_holdout_examples_since_last_dump = 0;\n all.sd->holdout_sum_loss_since_last_dump = 0.0;\n }\n else\n fprintf(stderr, \"%-10.6f %-10.6f %10ld %11.1f %s %8.4f %8lu\\n\",\n\t all.sd->sum_loss\/all.sd->weighted_examples,\n\t all.sd->sum_loss_since_last_dump \/ (all.sd->weighted_examples - all.sd->old_weighted_examples),\n\t (long int)all.sd->example_number,\n\t all.sd->weighted_examples,\n\t label_buf,\n\t ec->final_prediction,\n\t (long unsigned int)ec->num_features);\n \n all.sd->sum_loss_since_last_dump = 0.0;\n all.sd->old_weighted_examples = all.sd->weighted_examples;\n all.sd->dump_interval *= 2;\n }\n}\n\nvoid output_and_account_example(vw& all, example* ec)\n{\n label_data* ld = (label_data*)ec->ld;\n\n if(ec->test_only)\n {\n all.sd->weighted_holdout_examples += ec->global_weight;\/\/test weight seen\n all.sd->weighted_holdout_examples_since_last_dump += ec->global_weight;\n }\n else\n {\n all.sd->weighted_examples += ld->weight;\n all.sd->weighted_labels += ld->label == FLT_MAX ? 0 : ld->label * ld->weight;\n all.sd->total_features += ec->num_features;\n all.sd->sum_loss += ec->loss;\n all.sd->sum_loss_since_last_dump += ec->loss;\n all.sd->example_number++;\n }\n all.print(all.raw_prediction, ec->partial_prediction, -1, ec->tag);\n\n float ai=-1; \n if(all.active && ld->label == FLT_MAX)\n ai=query_decision(all, ec, (float)all.sd->weighted_unlabeled_examples);\n all.sd->weighted_unlabeled_examples += ld->label == FLT_MAX ? ld->weight : 0;\n \n for (size_t i = 0; ifinal_prediction, ai, ec->tag);\n else if (all.lda > 0)\n\tprint_lda_result(all, f,ec->topic_predictions.begin,0.,ec->tag);\n else\n\tall.print(f, ec->final_prediction, 0, ec->tag);\n }\n\n \n\n print_update(all, ec);\n}\n\nvoid return_simple_example(vw& all, example* ec)\n{\n if (!command_example(&all, ec))\n output_and_account_example(all, ec);\n VW::finish_example(all,ec);\n}\n\n<|endoftext|>"} {"text":"\/* * This file is part of m-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#include \"mkeyboardsettings.h\"\n#include \"mkeyboardsettingswidget.h\"\n#include \"keyboarddata.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace {\n const QString SettingsIMCorrectionSetting(\"\/meegotouch\/inputmethods\/correctionenabled\");\n const QString InputMethodLanguages(\"\/meegotouch\/inputmethods\/languages\");\n const QString VKBConfigurationPath(\"\/usr\/share\/meegotouch\/virtual-keyboard\/layouts\/\");\n const QString VKBLayoutsFilterRule(\"*.xml\");\n const QString VKBLayoutsIgnoreRules(\"number|test\"); \/\/ use as regexp to ignore number and test layouts\n};\n\nMKeyboardSettings::MKeyboardSettings()\n : keyboardErrorCorrectionConf(SettingsIMCorrectionSetting, this),\n selectedKeyboardsConf(InputMethodLanguages, this)\n{\n readAvailableKeyboards();\n connect(&keyboardErrorCorrectionConf, SIGNAL(valueChanged()),\n this, SIGNAL(errorCorrectionChanged()));\n connect(&selectedKeyboardsConf, SIGNAL(valueChanged()),\n this, SIGNAL(selectedKeyboardsChanged()));\n}\n\nMKeyboardSettings::~MKeyboardSettings()\n{\n}\n\nQGraphicsWidget *MKeyboardSettings::createContentWidget(QGraphicsWidget *parent)\n{\n \/\/ the pointer of returned QGraphicsWidget is owned by the caller,\n \/\/ so we just always create a new containerWidget.\n return new MKeyboardSettingsWidget(this, parent);\n}\n\nQString MKeyboardSettings::title()\n{\n \/\/% \"Virtual keyboards\";\n return qtTrId(\"qtn_txts_virtual_keyboards\");;\n}\n\nQString MKeyboardSettings::icon()\n{\n return \"\";\n}\n\nvoid MKeyboardSettings::readAvailableKeyboards()\n{\n availableKeyboardInfos.clear();\n \/\/ available keyboard languages are determined by xml layouts that can be found\n const QDir layoutsDir(VKBConfigurationPath, VKBLayoutsFilterRule);\n QRegExp ignoreExp(VKBLayoutsIgnoreRules, Qt::CaseInsensitive);\n\n foreach (QFileInfo keyboardFileInfo, layoutsDir.entryInfoList()) {\n if (keyboardFileInfo.fileName().contains(ignoreExp))\n continue;\n KeyboardData keyboard;\n if (keyboard.loadNokiaKeyboard(keyboardFileInfo.fileName())) {\n bool duplicated = false;\n foreach (const KeyboardInfo &info, availableKeyboardInfos) {\n if (info.language == keyboard.language()) {\n duplicated = true;\n break;\n }\n }\n if (!duplicated) {\n KeyboardInfo keyboardInfo;\n keyboardInfo.fileName = keyboardFileInfo.fileName();\n keyboardInfo.language = keyboard.language();\n keyboardInfo.title = keyboard.title();\n availableKeyboardInfos.append(keyboardInfo);\n }\n }\n }\n}\n\nQMap MKeyboardSettings::availableKeyboards() const\n{\n QMap keyboards;\n foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {\n keyboards.insert(keyboardInfo.language, keyboardInfo.title);\n }\n return keyboards;\n}\n\nQMap MKeyboardSettings::selectedKeyboards() const\n{\n QMap keyboards;\n foreach (const QString language, selectedKeyboardsConf.value().toStringList()) {\n keyboards.insert(language, keyboardTitle(language));\n }\n return keyboards;\n}\n\nvoid MKeyboardSettings::setSelectedKeyboards(const QStringList &keyboardTitles)\n{\n QStringList languages;\n foreach (const QString &title, keyboardTitles) {\n QString language = keyboardLanguage(title);\n if (!language.isEmpty() && !languages.contains(language)) {\n languages.append(language);\n }\n }\n selectedKeyboardsConf.set(languages);\n}\n\nQString MKeyboardSettings::keyboardTitle(const QString &language) const\n{\n QString title;\n foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {\n if (keyboardInfo.language == language) {\n title = keyboardInfo.title;\n break;\n }\n }\n return title;\n}\n\nQString MKeyboardSettings::keyboardLanguage(const QString &title) const\n{\n QString language;\n foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {\n if (keyboardInfo.title == title) {\n language = keyboardInfo.language;\n break;\n }\n }\n return language;\n}\n\nbool MKeyboardSettings::errorCorrection() const\n{\n return keyboardErrorCorrectionConf.value().toBool();\n}\n\nvoid MKeyboardSettings::setErrorCorrection(bool enabled)\n{\n if (keyboardErrorCorrectionConf.value().toBool() != enabled)\n keyboardErrorCorrectionConf.set(enabled);\n}\nFixes: keyboard settings should filter invalid layouts\/* * This file is part of m-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#include \"mkeyboardsettings.h\"\n#include \"mkeyboardsettingswidget.h\"\n#include \"keyboarddata.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace {\n const QString SettingsIMCorrectionSetting(\"\/meegotouch\/inputmethods\/correctionenabled\");\n const QString InputMethodLanguages(\"\/meegotouch\/inputmethods\/languages\");\n const QString VKBConfigurationPath(\"\/usr\/share\/meegotouch\/virtual-keyboard\/layouts\/\");\n const QString VKBLayoutsFilterRule(\"*.xml\");\n const QString VKBLayoutsIgnoreRules(\"number|test\"); \/\/ use as regexp to ignore number and test layouts\n};\n\nMKeyboardSettings::MKeyboardSettings()\n : keyboardErrorCorrectionConf(SettingsIMCorrectionSetting, this),\n selectedKeyboardsConf(InputMethodLanguages, this)\n{\n readAvailableKeyboards();\n connect(&keyboardErrorCorrectionConf, SIGNAL(valueChanged()),\n this, SIGNAL(errorCorrectionChanged()));\n connect(&selectedKeyboardsConf, SIGNAL(valueChanged()),\n this, SIGNAL(selectedKeyboardsChanged()));\n}\n\nMKeyboardSettings::~MKeyboardSettings()\n{\n}\n\nQGraphicsWidget *MKeyboardSettings::createContentWidget(QGraphicsWidget *parent)\n{\n \/\/ the pointer of returned QGraphicsWidget is owned by the caller,\n \/\/ so we just always create a new containerWidget.\n return new MKeyboardSettingsWidget(this, parent);\n}\n\nQString MKeyboardSettings::title()\n{\n \/\/% \"Virtual keyboards\";\n return qtTrId(\"qtn_txts_virtual_keyboards\");;\n}\n\nQString MKeyboardSettings::icon()\n{\n return \"\";\n}\n\nvoid MKeyboardSettings::readAvailableKeyboards()\n{\n availableKeyboardInfos.clear();\n \/\/ available keyboard languages are determined by xml layouts that can be found\n const QDir layoutsDir(VKBConfigurationPath, VKBLayoutsFilterRule);\n QRegExp ignoreExp(VKBLayoutsIgnoreRules, Qt::CaseInsensitive);\n\n foreach (QFileInfo keyboardFileInfo, layoutsDir.entryInfoList()) {\n if (keyboardFileInfo.fileName().contains(ignoreExp))\n continue;\n KeyboardData keyboard;\n if (keyboard.loadNokiaKeyboard(keyboardFileInfo.fileName())) {\n if (keyboard.language().isEmpty() || keyboard.title().isEmpty())\n continue;\n bool duplicated = false;\n foreach (const KeyboardInfo &info, availableKeyboardInfos) {\n if (info.language == keyboard.language()) {\n duplicated = true;\n break;\n }\n }\n if (!duplicated) {\n KeyboardInfo keyboardInfo;\n keyboardInfo.fileName = keyboardFileInfo.fileName();\n keyboardInfo.language = keyboard.language();\n keyboardInfo.title = keyboard.title();\n availableKeyboardInfos.append(keyboardInfo);\n }\n }\n }\n}\n\nQMap MKeyboardSettings::availableKeyboards() const\n{\n QMap keyboards;\n foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {\n keyboards.insert(keyboardInfo.language, keyboardInfo.title);\n }\n return keyboards;\n}\n\nQMap MKeyboardSettings::selectedKeyboards() const\n{\n QMap keyboards;\n foreach (const QString language, selectedKeyboardsConf.value().toStringList()) {\n keyboards.insert(language, keyboardTitle(language));\n }\n return keyboards;\n}\n\nvoid MKeyboardSettings::setSelectedKeyboards(const QStringList &keyboardTitles)\n{\n QStringList languages;\n foreach (const QString &title, keyboardTitles) {\n QString language = keyboardLanguage(title);\n if (!language.isEmpty() && !languages.contains(language)) {\n languages.append(language);\n }\n }\n selectedKeyboardsConf.set(languages);\n}\n\nQString MKeyboardSettings::keyboardTitle(const QString &language) const\n{\n QString title;\n foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {\n if (keyboardInfo.language == language) {\n title = keyboardInfo.title;\n break;\n }\n }\n return title;\n}\n\nQString MKeyboardSettings::keyboardLanguage(const QString &title) const\n{\n QString language;\n foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {\n if (keyboardInfo.title == title) {\n language = keyboardInfo.language;\n break;\n }\n }\n return language;\n}\n\nbool MKeyboardSettings::errorCorrection() const\n{\n return keyboardErrorCorrectionConf.value().toBool();\n}\n\nvoid MKeyboardSettings::setErrorCorrection(bool enabled)\n{\n if (keyboardErrorCorrectionConf.value().toBool() != enabled)\n keyboardErrorCorrectionConf.set(enabled);\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/tree:$Id$\n\/\/ Author: Marek Biskup 07\/06\/2005\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\/\/ A Chain Index\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TChainIndex.h\"\n#include \"TChain.h\"\n#include \"TTreeFormula.h\"\n#include \"TTreeIndex.h\"\n#include \"TFile.h\"\n#include \"TError.h\"\n\nClassImp(TChainIndex)\n\n\/\/______________________________________________________________________________\nTChainIndex::TChainIndex(): TVirtualIndex()\n{\n\/\/ Default constructor for TChainIndex\n\n fTree = 0;\n fMajorFormulaParent = fMinorFormulaParent = 0;\n}\n\n\/\/______________________________________________________________________________\nTChainIndex::TChainIndex(const TTree *T, const char *majorname, const char *minorname)\n : TVirtualIndex()\n{\n \/\/ Normal constructor for TChainIndex. See TTreeIndex::TTreeIndex for the description of the\n \/\/ parameters.\n \/\/ The tree must be a TChain.\n \/\/ All the index values in the first tree of the chain must be\n \/\/ less then any index value in the second one, and so on.\n \/\/ If any of those requirements isn't met the object becomes a zombie.\n \/\/ If some subtrees don't have indices the indices are created and stored inside this\n \/\/ TChainIndex.\n\n fTree = 0;\n fMajorFormulaParent = fMinorFormulaParent = 0;\n\n TChain *chain = dynamic_cast(const_cast(T));\n if (!chain) {\n MakeZombie();\n Error(\"TChainIndex\", \"Cannot create a TChainIndex.\"\n \" The Tree passed as an argument is not a TChain\");\n return;\n }\n\n fTree = (TTree*)T;\n fMajorName = majorname;\n fMinorName = minorname;\n Int_t i = 0;\n\n \/\/ Go through all the trees and check if they have indeces. If not then build them.\n for (i = 0; i < chain->GetNtrees(); i++) {\n chain->LoadTree((chain->GetTreeOffset())[i]);\n TVirtualIndex *index = chain->GetTree()->GetTreeIndex();\n\n TChainIndexEntry entry;\n entry.fTreeIndex = 0;\n\n \/\/if an index already exists, we must check if major\/minorname correspond\n \/\/to the major\/minor names in this function call\n if (index) {\n if (strcmp(majorname,index->GetMajorName()) || strcmp(minorname,index->GetMinorName())) {\n MakeZombie();\n Error(\"TChainIndex\",\"Tree in file %s has an index built with majorname=%s and minorname=%s\",chain->GetTree()->GetCurrentFile()->GetName(),index->GetMajorName(),index->GetMinorName());\n return;\n }\n }\n if (!index) {\n chain->GetTree()->BuildIndex(majorname, minorname);\n index = chain->GetTree()->GetTreeIndex();\n chain->GetTree()->SetTreeIndex(0);\n entry.fTreeIndex = index;\n }\n if (!index || index->IsZombie() || index->GetN() == 0) {\n DeleteIndices();\n MakeZombie();\n Error(\"TChainIndex\", \"Error creating a tree index on a tree in the chain\");\n return;\n }\n\n TTreeIndex *ti_index = dynamic_cast(index);\n if (ti_index == 0) {\n Error(\"TChainIndex\", \"The underlying TTree must have a TTreeIndex but has a %s.\",\n index->IsA()->GetName());\n return;\n }\n\n entry.fMinIndexValue = ti_index->GetIndexValues()[0];\n entry.fMaxIndexValue = ti_index->GetIndexValues()[index->GetN() - 1];\n fEntries.push_back(entry);\n }\n\n \/\/ Check if the indices of different trees are in order. If not then return an error.\n for (i = 0; i < Int_t(fEntries.size() - 1); i++) {\n if (fEntries[i].fMaxIndexValue > fEntries[i+1].fMinIndexValue) {\n DeleteIndices();\n MakeZombie();\n Error(\"TChainIndex\", \"The indices in files of this chain aren't sorted.\");\n }\n }\n\n}\n\n\/\/______________________________________________________________________________\nvoid TChainIndex::Append(const TVirtualIndex *index, Bool_t delaySort )\n{\n \/\/ add an index to this chain\n \/\/ if delaySort is kFALSE (default) check if the indices of different trees are in order.\n if (index) {\n const TTreeIndex *ti_index = dynamic_cast(index);\n if (ti_index == 0) {\n Error(\"Append\", \"The given index is not a TTreeIndex but a %s\",\n index->IsA()->GetName());\n }\n \n TChainIndexEntry entry;\n entry.fTreeIndex = 0;\n entry.fMinIndexValue = ti_index->GetIndexValues()[0];\n entry.fMaxIndexValue = ti_index->GetIndexValues()[index->GetN() - 1];\n fEntries.push_back(entry);\n }\n \n if (!delaySort) {\n \/\/ Check if the indices of different trees are in order. If not then return an error.\n for (Int_t i = 0; i < Int_t(fEntries.size() - 1); i++) {\n if (fEntries[i].fMaxIndexValue > fEntries[i+1].fMinIndexValue) {\n DeleteIndices();\n MakeZombie();\n Error(\"Append\", \"The indices in files of this chain aren't sorted.\");\n }\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TChainIndex::DeleteIndices()\n{\n \/\/ Delete all the indices which were built by this object\n for (unsigned int i = 0; i < fEntries.size(); i++) {\n if (fEntries[i].fTreeIndex) {\n if (fTree->GetTree() && fTree->GetTree()->GetTreeIndex() == fEntries[i].fTreeIndex) {\n fTree->GetTree()->SetTreeIndex(0);\n SafeDelete(fEntries[i].fTreeIndex);\n }\n SafeDelete(fEntries[i].fTreeIndex);\n }\n }\n}\n\n\/\/______________________________________________________________________________\nTChainIndex::~TChainIndex()\n{\n \/\/ The destructor.\n DeleteIndices();\n if (fTree && fTree->GetTreeIndex() == this)\n fTree->SetTreeIndex(0);\n}\n\n\/\/______________________________________________________________________________\nstd::pair TChainIndex::GetSubTreeIndex(Int_t major, Int_t minor) const\n{\n \/\/ Returns a TVirtualIndex for a tree which holds the entry with the specified\n \/\/ major and minor values and the number of that tree.\n \/\/ If the index for that tree was created by this object it's set to the tree.\n \/\/ The tree index should be later released using ReleaseSubTreeIndex();\n\n using namespace std;\n if (fEntries.size() == 0) {\n Warning(\"GetSubTreeIndex\", \"No subindices in the chain. The chain is probably empty\");\n return make_pair(static_cast(0), 0);\n }\n\n Long64_t indexValue = (Long64_t(major) << 31) + minor;\n\n if (indexValue < fEntries[0].fMinIndexValue) {\n Warning(\"GetSubTreeIndex\", \"The index value is less than the smallest index values in subtrees\");\n return make_pair(static_cast(0), 0);\n }\n\n Int_t treeNo = fEntries.size() - 1;\n for (unsigned int i = 0; i < fEntries.size() - 1; i++) {\n if (indexValue < fEntries[i+1].fMinIndexValue) {\n treeNo = i;\n break;\n }\n }\n \/\/ Double check we found the right range.\n if (0 && indexValue > fEntries[treeNo].fMaxIndexValue) {\n return make_pair(static_cast(0), 0);\n }\n TChain* chain = dynamic_cast (fTree);\n R__ASSERT(chain);\n chain->LoadTree(chain->GetTreeOffset()[treeNo]);\n TVirtualIndex* index = fTree->GetTree()->GetTreeIndex();\n if (index)\n return make_pair(static_cast(index), treeNo);\n else {\n index = fEntries[treeNo].fTreeIndex;\n if (!index) {\n Warning(\"GetSubTreeIndex\", \"The tree has no index and the chain index\"\n \" doesn't store an index for that tree\");\n return make_pair(static_cast(0), 0);\n }\n else {\n fTree->GetTree()->SetTreeIndex(index);\n return make_pair(static_cast(index), treeNo);\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TChainIndex::ReleaseSubTreeIndex(TVirtualIndex* index, int treeNo) const\n{\n \/\/ Releases the tree index got using GetSubTreeIndex. If the index was\n \/\/ created by this object it is removed from the current tree, so that it isn't\n \/\/ deleted in its destructor.\n\n if (fEntries[treeNo].fTreeIndex == index) {\n R__ASSERT(fTree->GetTree()->GetTreeIndex() == index);\n fTree->GetTree()->SetTreeIndex(0);\n }\n}\n\n\/\/______________________________________________________________________________\nLong64_t TChainIndex::GetEntryNumberFriend(const TTree *parent)\n{\n \/\/ see TTreeIndex::GetEntryNumberFriend for description\n\n if (!parent) return -3;\n GetMajorFormulaParent(parent);\n GetMinorFormulaParent(parent);\n if (!fMajorFormulaParent || !fMinorFormulaParent) return -1;\n if (!fMajorFormulaParent->GetNdim() || !fMinorFormulaParent->GetNdim()) {\n \/\/ The Tree Index in the friend has a pair majorname,minorname\n \/\/ not available in the parent Tree T.\n \/\/ if the friend Tree has less entries than the parent, this is an error\n Long64_t pentry = parent->GetReadEntry();\n if (pentry >= fTree->GetEntries()) return -2;\n \/\/ otherwise we ignore the Tree Index and return the entry number\n \/\/ in the parent Tree.\n return pentry;\n }\n\n \/\/ majorname, minorname exist in the parent Tree\n \/\/ we find the current values pair majorv,minorv in the parent Tree\n Double_t majord = fMajorFormulaParent->EvalInstance();\n Double_t minord = fMinorFormulaParent->EvalInstance();\n Long64_t majorv = (Long64_t)majord;\n Long64_t minorv = (Long64_t)minord;\n \/\/ we check if this pair exist in the index.\n \/\/ if yes, we return the corresponding entry number\n \/\/ if not the function returns -1\n return fTree->GetEntryNumberWithIndex(majorv,minorv);\n}\n\n\/\/______________________________________________________________________________\nLong64_t TChainIndex::GetEntryNumberWithBestIndex(Int_t major, Int_t minor) const\n{\n \/\/ See TTreeIndex::GetEntryNumberWithBestIndex for details.\n\n std::pair indexAndNumber = GetSubTreeIndex(major, minor);\n if (!indexAndNumber.first) {\n Error(\"GetEntryNumberWithBestIndex\",\"no index found\");\n return -1;\n }\n else {\n Long64_t rv = indexAndNumber.first->GetEntryNumberWithBestIndex(major, minor);\n ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second);\n TChain* chain = dynamic_cast (fTree);\n R__ASSERT(chain);\n return rv + chain->GetTreeOffset()[indexAndNumber.second];\n }\n}\n\n\/\/______________________________________________________________________________\nLong64_t TChainIndex::GetEntryNumberWithIndex(Int_t major, Int_t minor) const\n{\n \/\/ Returns the entry number with given index values.\n \/\/ See TTreeIndex::GetEntryNumberWithIndex for details.\n\n std::pair indexAndNumber = GetSubTreeIndex(major, minor);\n if (!indexAndNumber.first) {\n Error(\"GetEntryNumberWithIndex\",\"no index found\");\n return -1;\n }\n else {\n Long64_t rv = indexAndNumber.first->GetEntryNumberWithIndex(major, minor);\n ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second);\n TChain* chain = dynamic_cast (fTree);\n R__ASSERT(chain);\n if (rv > 0) {\n return rv + chain->GetTreeOffset()[indexAndNumber.second];\n } else {\n return rv;\n }\n }\n}\n\n\/\/______________________________________________________________________________\nTTreeFormula *TChainIndex::GetMajorFormulaParent(const TTree *parent)\n{\n \/\/ return a pointer to the TreeFormula corresponding to the majorname in parent tree T\n\n if (!fMajorFormulaParent) {\n TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf);\n fMajorFormulaParent = new TTreeFormula(\"MajorP\",fMajorName.Data(),const_cast(parent));\n fMajorFormulaParent->SetQuickLoad(kTRUE);\n }\n if (fMajorFormulaParent->GetTree() != parent) {\n fMajorFormulaParent->SetTree(const_cast(parent));\n fMajorFormulaParent->UpdateFormulaLeaves();\n }\n return fMajorFormulaParent;\n}\n\n\/\/______________________________________________________________________________\nTTreeFormula *TChainIndex::GetMinorFormulaParent(const TTree *parent)\n{\n \/\/ return a pointer to the TreeFormula corresponding to the minorname in parent tree T\n\n if (!fMinorFormulaParent) {\n \/\/ Prevent TTreeFormula from finding any of the branches in our TTree even if it\n \/\/ is a friend of the parent TTree.\n TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf);\n fMinorFormulaParent = new TTreeFormula(\"MinorP\",fMinorName.Data(),const_cast(parent));\n fMinorFormulaParent->SetQuickLoad(kTRUE);\n }\n if (fMinorFormulaParent->GetTree() != parent) {\n fMinorFormulaParent->SetTree(const_cast(parent));\n fMinorFormulaParent->UpdateFormulaLeaves();\n }\n\n return fMinorFormulaParent;\n}\n\n\/\/______________________________________________________________________________\nvoid TChainIndex::UpdateFormulaLeaves(const TTree *parent)\n{\n \/\/ Updates the parent formulae.\n \/\/ Called by TChain::LoadTree when the parent chain changes it's tree.\n if (fMajorFormulaParent) { \n \/\/ Prevent TTreeFormula from finding any of the branches in our TTree even if it\n \/\/ is a friend of the parent TTree.\n TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf);\n if (parent) fMajorFormulaParent->SetTree((TTree*)parent);\n fMajorFormulaParent->UpdateFormulaLeaves();\n }\n if (fMinorFormulaParent) { \n if (parent) fMinorFormulaParent->SetTree((TTree*)parent);\n fMinorFormulaParent->UpdateFormulaLeaves();\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TChainIndex::SetTree(const TTree *T)\n{\n \/\/ See TTreeIndex::SetTree.\n\n R__ASSERT(fTree == 0 || fTree == T || T==0);\n}\n\nGetEntryNumberWith[Best]Index is not suppose to complain on stderr\/stdout when the index is out of range, just return -1. (also remove debug '0' in if statement)\/\/ @(#)root\/tree:$Id$\n\/\/ Author: Marek Biskup 07\/06\/2005\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\/\/ A Chain Index\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TChainIndex.h\"\n#include \"TChain.h\"\n#include \"TTreeFormula.h\"\n#include \"TTreeIndex.h\"\n#include \"TFile.h\"\n#include \"TError.h\"\n\nClassImp(TChainIndex)\n\n\/\/______________________________________________________________________________\nTChainIndex::TChainIndex(): TVirtualIndex()\n{\n\/\/ Default constructor for TChainIndex\n\n fTree = 0;\n fMajorFormulaParent = fMinorFormulaParent = 0;\n}\n\n\/\/______________________________________________________________________________\nTChainIndex::TChainIndex(const TTree *T, const char *majorname, const char *minorname)\n : TVirtualIndex()\n{\n \/\/ Normal constructor for TChainIndex. See TTreeIndex::TTreeIndex for the description of the\n \/\/ parameters.\n \/\/ The tree must be a TChain.\n \/\/ All the index values in the first tree of the chain must be\n \/\/ less then any index value in the second one, and so on.\n \/\/ If any of those requirements isn't met the object becomes a zombie.\n \/\/ If some subtrees don't have indices the indices are created and stored inside this\n \/\/ TChainIndex.\n\n fTree = 0;\n fMajorFormulaParent = fMinorFormulaParent = 0;\n\n TChain *chain = dynamic_cast(const_cast(T));\n if (!chain) {\n MakeZombie();\n Error(\"TChainIndex\", \"Cannot create a TChainIndex.\"\n \" The Tree passed as an argument is not a TChain\");\n return;\n }\n\n fTree = (TTree*)T;\n fMajorName = majorname;\n fMinorName = minorname;\n Int_t i = 0;\n\n \/\/ Go through all the trees and check if they have indeces. If not then build them.\n for (i = 0; i < chain->GetNtrees(); i++) {\n chain->LoadTree((chain->GetTreeOffset())[i]);\n TVirtualIndex *index = chain->GetTree()->GetTreeIndex();\n\n TChainIndexEntry entry;\n entry.fTreeIndex = 0;\n\n \/\/if an index already exists, we must check if major\/minorname correspond\n \/\/to the major\/minor names in this function call\n if (index) {\n if (strcmp(majorname,index->GetMajorName()) || strcmp(minorname,index->GetMinorName())) {\n MakeZombie();\n Error(\"TChainIndex\",\"Tree in file %s has an index built with majorname=%s and minorname=%s\",chain->GetTree()->GetCurrentFile()->GetName(),index->GetMajorName(),index->GetMinorName());\n return;\n }\n }\n if (!index) {\n chain->GetTree()->BuildIndex(majorname, minorname);\n index = chain->GetTree()->GetTreeIndex();\n chain->GetTree()->SetTreeIndex(0);\n entry.fTreeIndex = index;\n }\n if (!index || index->IsZombie() || index->GetN() == 0) {\n DeleteIndices();\n MakeZombie();\n Error(\"TChainIndex\", \"Error creating a tree index on a tree in the chain\");\n return;\n }\n\n TTreeIndex *ti_index = dynamic_cast(index);\n if (ti_index == 0) {\n Error(\"TChainIndex\", \"The underlying TTree must have a TTreeIndex but has a %s.\",\n index->IsA()->GetName());\n return;\n }\n\n entry.fMinIndexValue = ti_index->GetIndexValues()[0];\n entry.fMaxIndexValue = ti_index->GetIndexValues()[index->GetN() - 1];\n fEntries.push_back(entry);\n }\n\n \/\/ Check if the indices of different trees are in order. If not then return an error.\n for (i = 0; i < Int_t(fEntries.size() - 1); i++) {\n if (fEntries[i].fMaxIndexValue > fEntries[i+1].fMinIndexValue) {\n DeleteIndices();\n MakeZombie();\n Error(\"TChainIndex\", \"The indices in files of this chain aren't sorted.\");\n }\n }\n\n}\n\n\/\/______________________________________________________________________________\nvoid TChainIndex::Append(const TVirtualIndex *index, Bool_t delaySort )\n{\n \/\/ add an index to this chain\n \/\/ if delaySort is kFALSE (default) check if the indices of different trees are in order.\n if (index) {\n const TTreeIndex *ti_index = dynamic_cast(index);\n if (ti_index == 0) {\n Error(\"Append\", \"The given index is not a TTreeIndex but a %s\",\n index->IsA()->GetName());\n }\n \n TChainIndexEntry entry;\n entry.fTreeIndex = 0;\n entry.fMinIndexValue = ti_index->GetIndexValues()[0];\n entry.fMaxIndexValue = ti_index->GetIndexValues()[index->GetN() - 1];\n fEntries.push_back(entry);\n }\n \n if (!delaySort) {\n \/\/ Check if the indices of different trees are in order. If not then return an error.\n for (Int_t i = 0; i < Int_t(fEntries.size() - 1); i++) {\n if (fEntries[i].fMaxIndexValue > fEntries[i+1].fMinIndexValue) {\n DeleteIndices();\n MakeZombie();\n Error(\"Append\", \"The indices in files of this chain aren't sorted.\");\n }\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TChainIndex::DeleteIndices()\n{\n \/\/ Delete all the indices which were built by this object\n for (unsigned int i = 0; i < fEntries.size(); i++) {\n if (fEntries[i].fTreeIndex) {\n if (fTree->GetTree() && fTree->GetTree()->GetTreeIndex() == fEntries[i].fTreeIndex) {\n fTree->GetTree()->SetTreeIndex(0);\n SafeDelete(fEntries[i].fTreeIndex);\n }\n SafeDelete(fEntries[i].fTreeIndex);\n }\n }\n}\n\n\/\/______________________________________________________________________________\nTChainIndex::~TChainIndex()\n{\n \/\/ The destructor.\n DeleteIndices();\n if (fTree && fTree->GetTreeIndex() == this)\n fTree->SetTreeIndex(0);\n}\n\n\/\/______________________________________________________________________________\nstd::pair TChainIndex::GetSubTreeIndex(Int_t major, Int_t minor) const\n{\n \/\/ Returns a TVirtualIndex for a tree which holds the entry with the specified\n \/\/ major and minor values and the number of that tree.\n \/\/ If the index for that tree was created by this object it's set to the tree.\n \/\/ The tree index should be later released using ReleaseSubTreeIndex();\n\n using namespace std;\n if (fEntries.size() == 0) {\n Warning(\"GetSubTreeIndex\", \"No subindices in the chain. The chain is probably empty\");\n return make_pair(static_cast(0), 0);\n }\n\n Long64_t indexValue = (Long64_t(major) << 31) + minor;\n\n if (indexValue < fEntries[0].fMinIndexValue) {\n Warning(\"GetSubTreeIndex\", \"The index value is less than the smallest index values in subtrees\");\n return make_pair(static_cast(0), 0);\n }\n\n Int_t treeNo = fEntries.size() - 1;\n for (unsigned int i = 0; i < fEntries.size() - 1; i++) {\n if (indexValue < fEntries[i+1].fMinIndexValue) {\n treeNo = i;\n break;\n }\n }\n \/\/ Double check we found the right range.\n if (indexValue > fEntries[treeNo].fMaxIndexValue) {\n return make_pair(static_cast(0), 0);\n }\n TChain* chain = dynamic_cast (fTree);\n R__ASSERT(chain);\n chain->LoadTree(chain->GetTreeOffset()[treeNo]);\n TVirtualIndex* index = fTree->GetTree()->GetTreeIndex();\n if (index)\n return make_pair(static_cast(index), treeNo);\n else {\n index = fEntries[treeNo].fTreeIndex;\n if (!index) {\n Warning(\"GetSubTreeIndex\", \"The tree has no index and the chain index\"\n \" doesn't store an index for that tree\");\n return make_pair(static_cast(0), 0);\n }\n else {\n fTree->GetTree()->SetTreeIndex(index);\n return make_pair(static_cast(index), treeNo);\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TChainIndex::ReleaseSubTreeIndex(TVirtualIndex* index, int treeNo) const\n{\n \/\/ Releases the tree index got using GetSubTreeIndex. If the index was\n \/\/ created by this object it is removed from the current tree, so that it isn't\n \/\/ deleted in its destructor.\n\n if (fEntries[treeNo].fTreeIndex == index) {\n R__ASSERT(fTree->GetTree()->GetTreeIndex() == index);\n fTree->GetTree()->SetTreeIndex(0);\n }\n}\n\n\/\/______________________________________________________________________________\nLong64_t TChainIndex::GetEntryNumberFriend(const TTree *parent)\n{\n \/\/ see TTreeIndex::GetEntryNumberFriend for description\n\n if (!parent) return -3;\n GetMajorFormulaParent(parent);\n GetMinorFormulaParent(parent);\n if (!fMajorFormulaParent || !fMinorFormulaParent) return -1;\n if (!fMajorFormulaParent->GetNdim() || !fMinorFormulaParent->GetNdim()) {\n \/\/ The Tree Index in the friend has a pair majorname,minorname\n \/\/ not available in the parent Tree T.\n \/\/ if the friend Tree has less entries than the parent, this is an error\n Long64_t pentry = parent->GetReadEntry();\n if (pentry >= fTree->GetEntries()) return -2;\n \/\/ otherwise we ignore the Tree Index and return the entry number\n \/\/ in the parent Tree.\n return pentry;\n }\n\n \/\/ majorname, minorname exist in the parent Tree\n \/\/ we find the current values pair majorv,minorv in the parent Tree\n Double_t majord = fMajorFormulaParent->EvalInstance();\n Double_t minord = fMinorFormulaParent->EvalInstance();\n Long64_t majorv = (Long64_t)majord;\n Long64_t minorv = (Long64_t)minord;\n \/\/ we check if this pair exist in the index.\n \/\/ if yes, we return the corresponding entry number\n \/\/ if not the function returns -1\n return fTree->GetEntryNumberWithIndex(majorv,minorv);\n}\n\n\/\/______________________________________________________________________________\nLong64_t TChainIndex::GetEntryNumberWithBestIndex(Int_t major, Int_t minor) const\n{\n \/\/ See TTreeIndex::GetEntryNumberWithBestIndex for details.\n\n std::pair indexAndNumber = GetSubTreeIndex(major, minor);\n if (!indexAndNumber.first) {\n \/\/ Error(\"GetEntryNumberWithBestIndex\",\"no index found\");\n return -1;\n }\n else {\n Long64_t rv = indexAndNumber.first->GetEntryNumberWithBestIndex(major, minor);\n ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second);\n TChain* chain = dynamic_cast (fTree);\n R__ASSERT(chain);\n return rv + chain->GetTreeOffset()[indexAndNumber.second];\n }\n}\n\n\/\/______________________________________________________________________________\nLong64_t TChainIndex::GetEntryNumberWithIndex(Int_t major, Int_t minor) const\n{\n \/\/ Returns the entry number with given index values.\n \/\/ See TTreeIndex::GetEntryNumberWithIndex for details.\n\n std::pair indexAndNumber = GetSubTreeIndex(major, minor);\n if (!indexAndNumber.first) {\n \/\/ Error(\"GetEntryNumberWithIndex\",\"no index found\");\n return -1;\n }\n else {\n Long64_t rv = indexAndNumber.first->GetEntryNumberWithIndex(major, minor);\n ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second);\n TChain* chain = dynamic_cast (fTree);\n R__ASSERT(chain);\n if (rv > 0) {\n return rv + chain->GetTreeOffset()[indexAndNumber.second];\n } else {\n return rv;\n }\n }\n}\n\n\/\/______________________________________________________________________________\nTTreeFormula *TChainIndex::GetMajorFormulaParent(const TTree *parent)\n{\n \/\/ return a pointer to the TreeFormula corresponding to the majorname in parent tree T\n\n if (!fMajorFormulaParent) {\n TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf);\n fMajorFormulaParent = new TTreeFormula(\"MajorP\",fMajorName.Data(),const_cast(parent));\n fMajorFormulaParent->SetQuickLoad(kTRUE);\n }\n if (fMajorFormulaParent->GetTree() != parent) {\n fMajorFormulaParent->SetTree(const_cast(parent));\n fMajorFormulaParent->UpdateFormulaLeaves();\n }\n return fMajorFormulaParent;\n}\n\n\/\/______________________________________________________________________________\nTTreeFormula *TChainIndex::GetMinorFormulaParent(const TTree *parent)\n{\n \/\/ return a pointer to the TreeFormula corresponding to the minorname in parent tree T\n\n if (!fMinorFormulaParent) {\n \/\/ Prevent TTreeFormula from finding any of the branches in our TTree even if it\n \/\/ is a friend of the parent TTree.\n TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf);\n fMinorFormulaParent = new TTreeFormula(\"MinorP\",fMinorName.Data(),const_cast(parent));\n fMinorFormulaParent->SetQuickLoad(kTRUE);\n }\n if (fMinorFormulaParent->GetTree() != parent) {\n fMinorFormulaParent->SetTree(const_cast(parent));\n fMinorFormulaParent->UpdateFormulaLeaves();\n }\n\n return fMinorFormulaParent;\n}\n\n\/\/______________________________________________________________________________\nvoid TChainIndex::UpdateFormulaLeaves(const TTree *parent)\n{\n \/\/ Updates the parent formulae.\n \/\/ Called by TChain::LoadTree when the parent chain changes it's tree.\n if (fMajorFormulaParent) { \n \/\/ Prevent TTreeFormula from finding any of the branches in our TTree even if it\n \/\/ is a friend of the parent TTree.\n TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf);\n if (parent) fMajorFormulaParent->SetTree((TTree*)parent);\n fMajorFormulaParent->UpdateFormulaLeaves();\n }\n if (fMinorFormulaParent) { \n if (parent) fMinorFormulaParent->SetTree((TTree*)parent);\n fMinorFormulaParent->UpdateFormulaLeaves();\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TChainIndex::SetTree(const TTree *T)\n{\n \/\/ See TTreeIndex::SetTree.\n\n R__ASSERT(fTree == 0 || fTree == T || T==0);\n}\n\n<|endoftext|>"} {"text":"\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2014 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 \"tutorial\/tutorial.h\"\n#include \"tutorial\/obj_loader.h\"\n#include \"sys\/taskscheduler.h\"\n#include \"image\/image.h\"\n\nnamespace embree\n{\n \/* name of the tutorial *\/\n const char* tutorialName = \"tutorial03\";\n\n \/* configuration *\/\n static std::string g_rtcore = \"\";\n static size_t g_numThreads = 0;\n\n \/* output settings *\/\n static size_t g_width = 512;\n static size_t g_height = 512;\n static bool g_fullscreen = false;\n static FileName outFilename = \"\";\n static int g_skipBenchmarkFrames = 0;\n static int g_numBenchmarkFrames = 0;\n static bool g_interactive = true;\n \n \/* scene *\/\n OBJScene g_obj_scene;\n static FileName filename = \"\";\n\n static void parseCommandLine(Ref cin, const FileName& path)\n {\n while (true)\n {\n std::string tag = cin->getString();\n if (tag == \"\") return;\n\n \/* parse command line parameters from a file *\/\n else if (tag == \"-c\") {\n FileName file = path + cin->getFileName();\n parseCommandLine(new ParseStream(new LineCommentFilter(file, \"#\")), file.path());\n }\n\n \/* load OBJ model*\/\n else if (tag == \"-i\") {\n filename = path + cin->getFileName();\n }\n\n \/* parse camera parameters *\/\n else if (tag == \"-vp\") g_camera.from = cin->getVec3fa();\n else if (tag == \"-vi\") g_camera.to = cin->getVec3fa();\n else if (tag == \"-vd\") g_camera.to = g_camera.from + cin->getVec3fa();\n else if (tag == \"-vu\") g_camera.up = cin->getVec3fa();\n else if (tag == \"-fov\") g_camera.fov = cin->getFloat();\n\n \/* frame buffer size *\/\n else if (tag == \"-size\") {\n g_width = cin->getInt();\n g_height = cin->getInt();\n }\n\n \/* full screen mode *\/\n else if (tag == \"-fullscreen\") \n g_fullscreen = true;\n\n \/* output filename *\/\n else if (tag == \"-o\") {\n outFilename = cin->getFileName();\n\tg_interactive = false;\n }\n\n \/* number of frames to render in benchmark mode *\/\n else if (tag == \"-benchmark\") {\n g_skipBenchmarkFrames = cin->getInt();\n g_numBenchmarkFrames = cin->getInt();\n\tg_interactive = false;\n }\n\n \/* rtcore configuration *\/\n else if (tag == \"-rtcore\")\n g_rtcore = cin->getString();\n\n \/* number of threads to use *\/\n else if (tag == \"-threads\")\n g_numThreads = cin->getInt();\n\n \/* skip unknown command line parameter *\/\n else {\n std::cerr << \"unknown command line parameter: \" << tag << \" \";\n while (cin->peek() != \"\" && cin->peek()[0] != '-') std::cerr << cin->getString() << \" \";\n std::cerr << std::endl;\n }\n }\n }\n \n void renderBenchmark(const FileName& fileName)\n {\n resize(g_width,g_height);\n AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);\n\n double dt = 0.0f;\n size_t numTotalFrames = g_skipBenchmarkFrames + g_numBenchmarkFrames;\n for (size_t i=0; i= g_skipBenchmarkFrames) dt += t1-t0;\n }\n std::cout << \"frame [\" << g_skipBenchmarkFrames << \" - \" << numTotalFrames << \"] \" << std::flush;\n std::cout << double(g_numBenchmarkFrames)\/dt << \"fps \" << std::endl;\n std::cout << \"BENCHMARK_RENDER \" << double(g_numBenchmarkFrames)\/dt << std::endl;\n }\n\n void renderToFile(const FileName& fileName)\n {\n resize(g_width,g_height);\n AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);\n render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p);\n void* ptr = map();\n Ref image = new Image4c(g_width, g_height, (Col4c*)ptr);\n storeImage(image, fileName);\n unmap();\n }\n\n \/* main function in embree namespace *\/\n int main(int argc, char** argv) \n {\n \/* create stream for parsing *\/\n Ref stream = new ParseStream(new CommandLineStream(argc, argv));\n\n \/* parse command line *\/ \n parseCommandLine(stream, FileName());\n if (g_numThreads) \n g_rtcore += \",threads=\" + std::stringOf(g_numThreads);\n if (g_numBenchmarkFrames)\n g_rtcore += \",benchmark=1\";\n\n \/* initialize task scheduler *\/\n#if !defined(__EXPORT_ALL_SYMBOLS__)\n TaskScheduler::create(g_numThreads);\n#endif\n\n \/* load scene *\/\n if (filename.str() != \"\")\n loadOBJ(filename,g_obj_scene);\n\n \/* initialize ray tracing core *\/\n init(g_rtcore.c_str());\n\n \/* send model *\/\n set_scene(&g_obj_scene);\n \n \/* benchmark mode *\/\n if (g_numBenchmarkFrames)\n renderBenchmark(outFilename);\n \n \/* render to disk *\/\n if (outFilename.str() != \"\")\n renderToFile(outFilename);\n \n \/* interactive mode *\/\n if (g_interactive) {\n initWindowState(tutorialName, g_width, g_height, g_fullscreen);\n enterWindowRunLoop();\n }\n\n return 0;\n }\n}\n\nint main(int argc, char** argv)\n{\n try {\n return embree::main(argc, argv);\n }\n catch (const std::exception& e) {\n std::cout << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n catch (...) {\n std::cout << \"Error: unknown exception caught.\" << std::endl;\n return 1;\n }\n}\nadded light parsing to tutorial03\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2014 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 \"tutorial\/tutorial.h\"\n#include \"tutorial\/obj_loader.h\"\n#include \"sys\/taskscheduler.h\"\n#include \"image\/image.h\"\n\nnamespace embree\n{\n \/* name of the tutorial *\/\n const char* tutorialName = \"tutorial03\";\n\n \/* configuration *\/\n static std::string g_rtcore = \"\";\n static size_t g_numThreads = 0;\n\n \/* output settings *\/\n static size_t g_width = 512;\n static size_t g_height = 512;\n static bool g_fullscreen = false;\n static FileName outFilename = \"\";\n static int g_skipBenchmarkFrames = 0;\n static int g_numBenchmarkFrames = 0;\n static bool g_interactive = true;\n \n \/* scene *\/\n OBJScene g_obj_scene;\n static FileName filename = \"\";\n\n static void parseCommandLine(Ref cin, const FileName& path)\n {\n while (true)\n {\n std::string tag = cin->getString();\n if (tag == \"\") return;\n\n \/* parse command line parameters from a file *\/\n else if (tag == \"-c\") {\n FileName file = path + cin->getFileName();\n parseCommandLine(new ParseStream(new LineCommentFilter(file, \"#\")), file.path());\n }\n\n \/* load OBJ model*\/\n else if (tag == \"-i\") {\n filename = path + cin->getFileName();\n }\n\n \/* parse camera parameters *\/\n else if (tag == \"-vp\") g_camera.from = cin->getVec3fa();\n else if (tag == \"-vi\") g_camera.to = cin->getVec3fa();\n else if (tag == \"-vd\") g_camera.to = g_camera.from + cin->getVec3fa();\n else if (tag == \"-vu\") g_camera.up = cin->getVec3fa();\n else if (tag == \"-fov\") g_camera.fov = cin->getFloat();\n\n \/* frame buffer size *\/\n else if (tag == \"-size\") {\n g_width = cin->getInt();\n g_height = cin->getInt();\n }\n\n \/* full screen mode *\/\n else if (tag == \"-fullscreen\") \n g_fullscreen = true;\n\n \/* output filename *\/\n else if (tag == \"-o\") {\n outFilename = cin->getFileName();\n\tg_interactive = false;\n }\n\n \/* number of frames to render in benchmark mode *\/\n else if (tag == \"-benchmark\") {\n g_skipBenchmarkFrames = cin->getInt();\n g_numBenchmarkFrames = cin->getInt();\n\tg_interactive = false;\n }\n\n \/* rtcore configuration *\/\n else if (tag == \"-rtcore\")\n g_rtcore = cin->getString();\n\n \/* number of threads to use *\/\n else if (tag == \"-threads\")\n g_numThreads = cin->getInt();\n\n \/* ambient light source *\/\n else if (tag == \"-ambientlight\") \n {\n const Vec3fa L = cin->getVec3fa();\n g_obj_scene.ambientLights.push_back(OBJScene::AmbientLight(L));\n }\n\n \/* point light source *\/\n else if (tag == \"-pointlight\") \n {\n const Vec3fa P = cin->getVec3fa();\n const Vec3fa I = cin->getVec3fa();\n g_obj_scene.pointLights.push_back(OBJScene::PointLight(P,I));\n }\n\n \/* directional light source *\/\n else if (tag == \"-directionallight\" || tag == \"-dirlight\") \n {\n const Vec3fa D = cin->getVec3fa();\n const Vec3fa E = cin->getVec3fa();\n g_obj_scene.directionalLights.push_back(OBJScene::DirectionalLight(D,E));\n }\n\n \/* distant light source *\/\n else if (tag == \"-distantlight\") \n {\n const Vec3fa D = cin->getVec3fa();\n const Vec3fa L = cin->getVec3fa();\n const float halfAngle = cin->getFloat();\n g_obj_scene.distantLights.push_back(OBJScene::DistantLight(D,L,halfAngle));\n }\n\n \/* skip unknown command line parameter *\/\n else {\n std::cerr << \"unknown command line parameter: \" << tag << \" \";\n while (cin->peek() != \"\" && cin->peek()[0] != '-') std::cerr << cin->getString() << \" \";\n std::cerr << std::endl;\n }\n }\n }\n \n void renderBenchmark(const FileName& fileName)\n {\n resize(g_width,g_height);\n AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);\n\n double dt = 0.0f;\n size_t numTotalFrames = g_skipBenchmarkFrames + g_numBenchmarkFrames;\n for (size_t i=0; i= g_skipBenchmarkFrames) dt += t1-t0;\n }\n std::cout << \"frame [\" << g_skipBenchmarkFrames << \" - \" << numTotalFrames << \"] \" << std::flush;\n std::cout << double(g_numBenchmarkFrames)\/dt << \"fps \" << std::endl;\n std::cout << \"BENCHMARK_RENDER \" << double(g_numBenchmarkFrames)\/dt << std::endl;\n }\n\n void renderToFile(const FileName& fileName)\n {\n resize(g_width,g_height);\n AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);\n render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p);\n void* ptr = map();\n Ref image = new Image4c(g_width, g_height, (Col4c*)ptr);\n storeImage(image, fileName);\n unmap();\n }\n\n \/* main function in embree namespace *\/\n int main(int argc, char** argv) \n {\n \/* create stream for parsing *\/\n Ref stream = new ParseStream(new CommandLineStream(argc, argv));\n\n \/* parse command line *\/ \n parseCommandLine(stream, FileName());\n if (g_numThreads) \n g_rtcore += \",threads=\" + std::stringOf(g_numThreads);\n if (g_numBenchmarkFrames)\n g_rtcore += \",benchmark=1\";\n\n \/* initialize task scheduler *\/\n#if !defined(__EXPORT_ALL_SYMBOLS__)\n TaskScheduler::create(g_numThreads);\n#endif\n\n \/* load scene *\/\n if (filename.str() != \"\")\n loadOBJ(filename,g_obj_scene);\n\n \/* initialize ray tracing core *\/\n init(g_rtcore.c_str());\n\n \/* send model *\/\n set_scene(&g_obj_scene);\n \n \/* benchmark mode *\/\n if (g_numBenchmarkFrames)\n renderBenchmark(outFilename);\n \n \/* render to disk *\/\n if (outFilename.str() != \"\")\n renderToFile(outFilename);\n \n \/* interactive mode *\/\n if (g_interactive) {\n initWindowState(tutorialName, g_width, g_height, g_fullscreen);\n enterWindowRunLoop();\n }\n\n return 0;\n }\n}\n\nint main(int argc, char** argv)\n{\n try {\n return embree::main(argc, argv);\n }\n catch (const std::exception& e) {\n std::cout << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n catch (...) {\n std::cout << \"Error: unknown exception caught.\" << std::endl;\n return 1;\n }\n}\n<|endoftext|>"} {"text":"\/*===================================================================\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 \"mitkLookupTablePropertySerializer.h\"\n#include \n\nTiXmlElement* mitk::LookupTablePropertySerializer::Serialize()\n{\n if (const LookupTableProperty* prop = dynamic_cast(m_Property.GetPointer()))\n {\n LookupTable::Pointer mitkLut = const_cast(prop)->GetLookupTable();\n if (mitkLut.IsNull()) return nullptr; \/\/ really?\n\n vtkLookupTable* lut = mitkLut->GetVtkLookupTable();\n if (!lut) return nullptr;\n\n auto element = new TiXmlElement(\"LookupTable\");\n\n double* range;\n double* rgba;\n\n element->SetAttribute(\"NumberOfColors\", lut->GetNumberOfTableValues());\n element->SetAttribute(\"Scale\", lut->GetScale());\n element->SetAttribute(\"Ramp\", lut->GetRamp());\n\n range = lut->GetHueRange();\n auto child = new TiXmlElement(\"HueRange\");\n element->LinkEndChild( child );\n child->SetDoubleAttribute(\"min\", range[0]);\n child->SetDoubleAttribute(\"max\", range[1]);\n\n range = lut->GetValueRange();\n child = new TiXmlElement(\"ValueRange\");\n element->LinkEndChild( child );\n child->SetDoubleAttribute(\"min\", range[0]);\n child->SetDoubleAttribute(\"max\", range[1]);\n\n range = lut->GetSaturationRange();\n\t child = new TiXmlElement(\"SaturationRange\");\n\telement->LinkEndChild( child );\n\t child->SetDoubleAttribute(\"min\", range[0]);\n\t child->SetDoubleAttribute(\"max\", range[1]);\n\n\trange = lut->GetAlphaRange();\n\t\t\t\t child = new TiXmlElement(\"AlphaRange\");\n\telement->LinkEndChild( child );\n\t child->SetDoubleAttribute(\"min\", range[0]);\n\t child->SetDoubleAttribute(\"max\", range[1]);\n\n\trange = lut->GetTableRange();\n\t\t\t\t child = new TiXmlElement(\"TableRange\");\n\telement->LinkEndChild( child );\n\t child->SetDoubleAttribute(\"min\", range[0]);\n\t child->SetDoubleAttribute(\"max\", range[1]);\n\n\tchild = new TiXmlElement(\"Table\");\n\telement->LinkEndChild( child );\n\tfor ( int index = 0; index < lut->GetNumberOfTableValues(); ++index)\n\t{\n\t auto grandChildNinife = new TiXmlElement(\"RgbaColor\");\n\t rgba = lut->GetTableValue(index);\n\t grandChildNinife->SetDoubleAttribute(\"R\", rgba[0]);\n\t grandChildNinife->SetDoubleAttribute(\"G\", rgba[1]);\n\t grandChildNinife->SetDoubleAttribute(\"B\", rgba[2]);\n\t grandChildNinife->SetDoubleAttribute(\"A\", rgba[3]);\n\t child->LinkEndChild( grandChildNinife );\n\t}\n return element;\n }\n else return nullptr;\n}\n\nmitk::BaseProperty::Pointer mitk::LookupTablePropertySerializer::Deserialize(TiXmlElement* element)\n{\n if (!element) return nullptr;\n\n typedef double OUR_VTK_FLOAT_TYPE;\n double range[2];\n double rgba[4];\n\n double d; \/\/ bec. of tinyXML's interface that takes a pointer to float or double...\n\n vtkSmartPointer lut = vtkSmartPointer::New();\n\n int numberOfColors;\n int scale;\n int ramp; \/\/ hope the int values don't change betw. vtk versions...\n if ( element->QueryIntAttribute( \"NumberOfColors\", &numberOfColors ) == TIXML_SUCCESS )\n {\n\tlut->SetNumberOfTableValues( numberOfColors );\n }\n else\n\treturn nullptr;\n if ( element->QueryIntAttribute( \"Scale\", &scale ) == TIXML_SUCCESS )\n {\n\tlut->SetScale( scale );\n }\n else\n\treturn nullptr;\n if ( element->QueryIntAttribute( \"Ramp\", &ramp ) == TIXML_SUCCESS )\n {\n\tlut->SetRamp( ramp );\n }\n else\n\treturn nullptr;\n\n TiXmlElement* child = element->FirstChildElement(\"HueRange\");\n if (child)\n {\n\tif ( child->QueryDoubleAttribute( \"min\", &d ) != TIXML_SUCCESS )\n\t return nullptr;\n\trange[0] = static_cast(d);\n\tif ( child->QueryDoubleAttribute( \"max\", &d ) != TIXML_SUCCESS )\n\t return nullptr;\n\trange[1] = static_cast(d);\n\tlut->SetHueRange( range );\n }\n\n\t\t\t\tchild = element->FirstChildElement(\"ValueRange\");\n if (child)\n {\n\tif ( child->QueryDoubleAttribute( \"min\", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast(d);\n\tif ( child->QueryDoubleAttribute( \"max\", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast(d);\n\tlut->SetValueRange( range );\n }\n\n\t\t\t\tchild = element->FirstChildElement(\"SaturationRange\");\n if (child)\n {\n\tif ( child->QueryDoubleAttribute( \"min\", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast(d);\n\tif ( child->QueryDoubleAttribute( \"max\", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast(d);\n\tlut->SetSaturationRange( range );\n }\n\n\t\t\t\tchild = element->FirstChildElement(\"AlphaRange\");\n if (child)\n {\n\tif ( child->QueryDoubleAttribute( \"min\", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast(d);\n\tif ( child->QueryDoubleAttribute( \"max\", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast(d);\n\tlut->SetAlphaRange( range );\n }\n\n\t\t\t\tchild = element->FirstChildElement(\"TableRange\");\n if (child)\n {\n\tif ( child->QueryDoubleAttribute( \"min\", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast(d);\n\tif ( child->QueryDoubleAttribute( \"max\", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast(d);\n\tlut->SetTableRange( range );\n }\n\n child = element->FirstChildElement(\"Table\");\n if (child)\n {\n\tunsigned int index(0);\n\tfor( TiXmlElement* grandChild = child->FirstChildElement(\"RgbaColor\"); grandChild; grandChild = grandChild->NextSiblingElement(\"RgbaColor\"))\n\t{\n\t if ( grandChild->QueryDoubleAttribute(\"R\", &d) != TIXML_SUCCESS ) return nullptr; rgba[0] = static_cast(d);\n\t if ( grandChild->QueryDoubleAttribute(\"G\", &d) != TIXML_SUCCESS ) return nullptr; rgba[1] = static_cast(d);\n\t if ( grandChild->QueryDoubleAttribute(\"B\", &d) != TIXML_SUCCESS ) return nullptr; rgba[2] = static_cast(d);\n\t if ( grandChild->QueryDoubleAttribute(\"A\", &d) != TIXML_SUCCESS ) return nullptr; rgba[3] = static_cast(d);\n\n\t lut->SetTableValue( index, rgba );\n\t ++index;\n\t}\n }\n\n LookupTable::Pointer mitkLut = LookupTable::New();\n mitkLut->SetVtkLookupTable( lut );\n\n return LookupTableProperty::New(mitkLut).GetPointer();\n}Revert \"Separating mitkLookupTablePropertySerliazer into header and source\"\/*===================================================================\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#ifndef mitkLookupTablePropertySerializer_h_included\n#define mitkLookupTablePropertySerializer_h_included\n\n#include \"mitkBasePropertySerializer.h\"\n\n#include \"mitkLookupTableProperty.h\"\n\nnamespace mitk\n{\n\nclass LookupTablePropertySerializer : public BasePropertySerializer\n{\n public:\n\n mitkClassMacro( LookupTablePropertySerializer, BasePropertySerializer );\n itkFactorylessNewMacro(Self)\n itkCloneMacro(Self)\n\n virtual TiXmlElement* Serialize() override\n {\n if (const LookupTableProperty* prop = dynamic_cast(m_Property.GetPointer()))\n {\n LookupTable::Pointer mitkLut = const_cast(prop)->GetLookupTable();\n if (mitkLut.IsNull()) return nullptr; \/\/ really?\n\n vtkLookupTable* lut = mitkLut->GetVtkLookupTable();\n if (!lut) return nullptr;\n\n auto element = new TiXmlElement(\"LookupTable\");\n\n double* range;\n double* rgba;\n\n element->SetAttribute(\"NumberOfColors\", lut->GetNumberOfTableValues());\n element->SetAttribute(\"Scale\", lut->GetScale());\n element->SetAttribute(\"Ramp\", lut->GetRamp());\n\n range = lut->GetHueRange();\n auto child = new TiXmlElement(\"HueRange\");\n element->LinkEndChild( child );\n child->SetDoubleAttribute(\"min\", range[0]);\n child->SetDoubleAttribute(\"max\", range[1]);\n\n range = lut->GetValueRange();\n child = new TiXmlElement(\"ValueRange\");\n element->LinkEndChild( child );\n child->SetDoubleAttribute(\"min\", range[0]);\n child->SetDoubleAttribute(\"max\", range[1]);\n\n range = lut->GetSaturationRange();\n child = new TiXmlElement(\"SaturationRange\");\n element->LinkEndChild( child );\n child->SetDoubleAttribute(\"min\", range[0]);\n child->SetDoubleAttribute(\"max\", range[1]);\n\n range = lut->GetAlphaRange();\n child = new TiXmlElement(\"AlphaRange\");\n element->LinkEndChild( child );\n child->SetDoubleAttribute(\"min\", range[0]);\n child->SetDoubleAttribute(\"max\", range[1]);\n\n range = lut->GetTableRange();\n child = new TiXmlElement(\"TableRange\");\n element->LinkEndChild( child );\n child->SetDoubleAttribute(\"min\", range[0]);\n child->SetDoubleAttribute(\"max\", range[1]);\n\n child = new TiXmlElement(\"Table\");\n element->LinkEndChild( child );\n for ( int index = 0; index < lut->GetNumberOfTableValues(); ++index)\n {\n auto grandChildNinife = new TiXmlElement(\"RgbaColor\");\n rgba = lut->GetTableValue(index);\n grandChildNinife->SetDoubleAttribute(\"R\", rgba[0]);\n grandChildNinife->SetDoubleAttribute(\"G\", rgba[1]);\n grandChildNinife->SetDoubleAttribute(\"B\", rgba[2]);\n grandChildNinife->SetDoubleAttribute(\"A\", rgba[3]);\n child->LinkEndChild( grandChildNinife );\n }\n return element;\n }\n else return nullptr;\n }\n\n virtual BaseProperty::Pointer Deserialize(TiXmlElement* element) override\n {\n if (!element) return nullptr;\n\n typedef double OUR_VTK_FLOAT_TYPE;\n double range[2];\n double rgba[4];\n\n double d; \/\/ bec. of tinyXML's interface that takes a pointer to float or double...\n\n vtkSmartPointer lut = vtkSmartPointer::New();\n\n int numberOfColors;\n int scale;\n int ramp; \/\/ hope the int values don't change betw. vtk versions...\n if ( element->QueryIntAttribute( \"NumberOfColors\", &numberOfColors ) == TIXML_SUCCESS )\n {\n lut->SetNumberOfTableValues( numberOfColors );\n }\n else\n return nullptr;\n if ( element->QueryIntAttribute( \"Scale\", &scale ) == TIXML_SUCCESS )\n {\n lut->SetScale( scale );\n }\n else\n return nullptr;\n if ( element->QueryIntAttribute( \"Ramp\", &ramp ) == TIXML_SUCCESS )\n {\n lut->SetRamp( ramp );\n }\n else\n return nullptr;\n\n TiXmlElement* child = element->FirstChildElement(\"HueRange\");\n if (child)\n {\n if ( child->QueryDoubleAttribute( \"min\", &d ) != TIXML_SUCCESS )\n return nullptr;\n range[0] = static_cast(d);\n if ( child->QueryDoubleAttribute( \"max\", &d ) != TIXML_SUCCESS )\n return nullptr;\n range[1] = static_cast(d);\n lut->SetHueRange( range );\n }\n\n child = element->FirstChildElement(\"ValueRange\");\n if (child)\n {\n if ( child->QueryDoubleAttribute( \"min\", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast(d);\n if ( child->QueryDoubleAttribute( \"max\", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast(d);\n lut->SetValueRange( range );\n }\n\n child = element->FirstChildElement(\"SaturationRange\");\n if (child)\n {\n if ( child->QueryDoubleAttribute( \"min\", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast(d);\n if ( child->QueryDoubleAttribute( \"max\", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast(d);\n lut->SetSaturationRange( range );\n }\n\n child = element->FirstChildElement(\"AlphaRange\");\n if (child)\n {\n if ( child->QueryDoubleAttribute( \"min\", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast(d);\n if ( child->QueryDoubleAttribute( \"max\", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast(d);\n lut->SetAlphaRange( range );\n }\n\n child = element->FirstChildElement(\"TableRange\");\n if (child)\n {\n if ( child->QueryDoubleAttribute( \"min\", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast(d);\n if ( child->QueryDoubleAttribute( \"max\", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast(d);\n lut->SetTableRange( range );\n }\n\n child = element->FirstChildElement(\"Table\");\n if (child)\n {\n unsigned int index(0);\n for( TiXmlElement* grandChild = child->FirstChildElement(\"RgbaColor\"); grandChild; grandChild = grandChild->NextSiblingElement(\"RgbaColor\"))\n {\n if ( grandChild->QueryDoubleAttribute(\"R\", &d) != TIXML_SUCCESS ) return nullptr; rgba[0] = static_cast(d);\n if ( grandChild->QueryDoubleAttribute(\"G\", &d) != TIXML_SUCCESS ) return nullptr; rgba[1] = static_cast(d);\n if ( grandChild->QueryDoubleAttribute(\"B\", &d) != TIXML_SUCCESS ) return nullptr; rgba[2] = static_cast(d);\n if ( grandChild->QueryDoubleAttribute(\"A\", &d) != TIXML_SUCCESS ) return nullptr; rgba[3] = static_cast(d);\n\n lut->SetTableValue( index, rgba );\n ++index;\n }\n }\n\n LookupTable::Pointer mitkLut = LookupTable::New();\n mitkLut->SetVtkLookupTable( lut );\n\n return LookupTableProperty::New(mitkLut).GetPointer();\n }\n\n protected:\n\n LookupTablePropertySerializer() {}\n virtual ~LookupTablePropertySerializer() {}\n};\n\n} \/\/ namespace\n\n\/\/ important to put this into the GLOBAL namespace (because it starts with 'namespace mitk')\nMITK_REGISTER_SERIALIZER(LookupTablePropertySerializer);\n\n#endif\n\n<|endoftext|>"} {"text":"\/\/ $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 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\/\/ library configuration\n#include \"libmesh_config.h\"\n\n\/\/ C++ includes\n#include \/\/ for std::min\n#include \/\/ for std::multimap\n#include \/\/ for std::ostringstream\n\n\n\/\/ Local includes\n#include \"boundary_info.h\"\n#include \"elem.h\"\n#include \"mesh_base.h\"\n#include \"parallel.h\"\n#include \"partitioner.h\"\n#include \"point_locator_base.h\"\n\nnamespace libMesh\n{\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ MeshBase class member functions\nMeshBase::MeshBase (unsigned int d) :\n boundary_info (new BoundaryInfo(*this)),\n _n_parts (1),\n _dim (d),\n _is_prepared (false),\n _point_locator (NULL),\n _partitioner (NULL)\n{\n libmesh_assert (LIBMESH_DIM <= 3);\n libmesh_assert (LIBMESH_DIM >= _dim);\n libmesh_assert (libMesh::initialized());\n}\n\n\n\nMeshBase::MeshBase (const MeshBase& other_mesh) :\n boundary_info (new BoundaryInfo(*this)), \/\/ no copy constructor defined for BoundaryInfo?\n _n_parts (other_mesh._n_parts),\n _dim (other_mesh._dim),\n _is_prepared (other_mesh._is_prepared),\n _point_locator (NULL),\n _partitioner (other_mesh._partitioner->clone())\n{\n}\n\n\n\nMeshBase::~MeshBase()\n{\n this->clear();\n\n libmesh_assert (!libMesh::closed());\n}\n\n\n\nvoid MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements)\n{ \n \/\/ Renumber the nodes and elements so that they in contiguous\n \/\/ blocks. By default, skip_renumber_nodes_and_elements is false,\n \/\/ however we may skip this step by passing\n \/\/ skip_renumber_nodes_and_elements==true to this function.\n \/\/\n \/\/ Instances where you if prepare_for_use() should not renumber the nodes\n \/\/ and elements include reading in e.g. an xda\/r or gmv file. In\n \/\/ this case, the ordering of the nodes may depend on an accompanying\n \/\/ solution, and the node ordering cannot be changed.\n if(!skip_renumber_nodes_and_elements)\n this->renumber_nodes_and_elements();\n \n \/\/ Let all the elements find their neighbors\n this->find_neighbors();\n\n \/\/ Partition the mesh.\n this->partition();\n \n \/\/ If we're using ParallelMesh, we'll want it parallelized.\n this->delete_remote_elements();\n\n if(!skip_renumber_nodes_and_elements)\n this->renumber_nodes_and_elements();\n\n \/\/ Reset our PointLocator. This needs to happen any time the elements\n \/\/ in the underlying elements in the mesh have changed, so we do it here.\n this->clear_point_locator();\n\n \/\/ The mesh is now prepared for use.\n _is_prepared = true;\n}\n\n\n\nvoid MeshBase::clear ()\n{\n \/\/ Reset the number of partitions\n _n_parts = 1;\n\n \/\/ Reset the _is_prepared flag\n _is_prepared = false;\n\n \/\/ Clear boundary information\n this->boundary_info->clear();\n\n \/\/ Clear our point locator.\n this->clear_point_locator();\n}\n\n\n\nunsigned int MeshBase::n_subdomains() const\n{\n \/\/ This requires an inspection on every processor\n parallel_only();\n\n const_element_iterator el = this->active_elements_begin();\n const const_element_iterator end = this->active_elements_end(); \n\n std::set subdomain_ids;\n \n for (; el!=end; ++el)\n subdomain_ids.insert((*el)->subdomain_id());\n\n \/\/ Some subdomains may only live on other processors\n Parallel::set_union(subdomain_ids, 0);\n\n unsigned int n_sbd_ids = subdomain_ids.size();\n Parallel::broadcast(n_sbd_ids);\n\n return n_sbd_ids;\n}\n\n\nunsigned int MeshBase::n_nodes_on_proc (const unsigned int proc_id) const\n{\n \/\/ We're either counting a processor's nodes or unpartitioned\n \/\/ nodes\n libmesh_assert (proc_id < libMesh::n_processors() ||\n\t proc_id == DofObject::invalid_processor_id);\n \n return static_cast(std::distance (this->pid_nodes_begin(proc_id),\n\t\t\t\t\t\t this->pid_nodes_end (proc_id)));\n}\n\n\n\nunsigned int MeshBase::n_elem_on_proc (const unsigned int proc_id) const\n{\n \/\/ We're either counting a processor's elements or unpartitioned\n \/\/ elements\n libmesh_assert (proc_id < libMesh::n_processors() ||\n\t proc_id == DofObject::invalid_processor_id);\n \n return static_cast(std::distance (this->pid_elements_begin(proc_id),\n\t\t\t\t\t\t this->pid_elements_end (proc_id)));\n}\n\n\n\nunsigned int MeshBase::n_active_elem_on_proc (const unsigned int proc_id) const\n{\n libmesh_assert (proc_id < libMesh::n_processors());\n return static_cast(std::distance (this->active_pid_elements_begin(proc_id),\n\t\t\t\t\t\t this->active_pid_elements_end (proc_id)));\n}\n \n\n\nunsigned int MeshBase::n_sub_elem () const\n{\n unsigned int ne=0;\n\n const_element_iterator el = this->elements_begin();\n const const_element_iterator end = this->elements_end(); \n\n for (; el!=end; ++el)\n ne += (*el)->n_sub_elem(); \n\n return ne;\n}\n\n\n\nunsigned int MeshBase::n_active_sub_elem () const\n{\n unsigned int ne=0;\n\n const_element_iterator el = this->active_elements_begin();\n const const_element_iterator end = this->active_elements_end(); \n\n for (; el!=end; ++el)\n ne += (*el)->n_sub_elem(); \n\n return ne;\n}\n\n\n\nstd::string MeshBase::get_info() const\n{\n std::ostringstream out;\n\n out << \" Mesh Information:\" << '\\n'\n << \" mesh_dimension()=\" << this->mesh_dimension() << '\\n'\n << \" spatial_dimension()=\" << this->spatial_dimension() << '\\n'\n << \" n_nodes()=\" << this->n_nodes() << '\\n'\n << \" n_local_nodes()=\" << this->n_local_nodes() << '\\n'\n << \" n_elem()=\" << this->n_elem() << '\\n'\n << \" n_local_elem()=\" << this->n_local_elem() << '\\n'\n#ifdef LIBMESH_ENABLE_AMR\n << \" n_active_elem()=\" << this->n_active_elem() << '\\n'\n#endif\n << \" n_subdomains()=\" << this->n_subdomains() << '\\n'\n << \" n_processors()=\" << this->n_processors() << '\\n'\n << \" processor_id()=\" << this->processor_id() << '\\n';\n\n return out.str();\n}\n\n\nvoid MeshBase::print_info(std::ostream& os) const\n{\n os << this->get_info()\n << std::endl;\n}\n\n\nstd::ostream& operator << (std::ostream& os, const MeshBase& m)\n{\n m.print_info(os);\n return os;\n}\n\n\n\n\nvoid MeshBase::partition (const unsigned int n_parts)\n{\n if (partitioner().get()) \/\/ \"NULL\" means don't partition\n partitioner()->partition (*this, n_parts);\n}\n\n\n\nunsigned int MeshBase::recalculate_n_partitions()\n{\n const_element_iterator el = this->active_elements_begin();\n const const_element_iterator end = this->active_elements_end(); \n\n unsigned int max_proc_id=0;\n \n for (; el!=end; ++el)\n max_proc_id = std::max(max_proc_id, static_cast((*el)->processor_id()));\n\n \/\/ The number of partitions is one more than the max processor ID.\n _n_parts = max_proc_id+1;\n\n return _n_parts;\n}\n\n\n\nconst PointLocatorBase & MeshBase::point_locator () const\n{\n \/\/ Double checked lock pattern for efficiency\n if (_point_locator.get() == NULL)\n {\n Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);\n \n if (_point_locator.get() == NULL)\n _point_locator.reset (PointLocatorBase::build(TREE, *this).release());\n }\n\n return *_point_locator;\n}\n\n\n\nvoid MeshBase::clear_point_locator ()\n{\n _point_locator.reset(NULL);\n}\n\n} \/\/ namespace libMesh\n\n\n\n\nRemove unnecessary\/buggy mutex acquisition from point_locator()\/\/ $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 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\/\/ library configuration\n#include \"libmesh_config.h\"\n\n\/\/ C++ includes\n#include \/\/ for std::min\n#include \/\/ for std::multimap\n#include \/\/ for std::ostringstream\n\n\n\/\/ Local includes\n#include \"boundary_info.h\"\n#include \"elem.h\"\n#include \"mesh_base.h\"\n#include \"parallel.h\"\n#include \"partitioner.h\"\n#include \"point_locator_base.h\"\n#include \"threads.h\"\n\nnamespace libMesh\n{\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ MeshBase class member functions\nMeshBase::MeshBase (unsigned int d) :\n boundary_info (new BoundaryInfo(*this)),\n _n_parts (1),\n _dim (d),\n _is_prepared (false),\n _point_locator (NULL),\n _partitioner (NULL)\n{\n libmesh_assert (LIBMESH_DIM <= 3);\n libmesh_assert (LIBMESH_DIM >= _dim);\n libmesh_assert (libMesh::initialized());\n}\n\n\n\nMeshBase::MeshBase (const MeshBase& other_mesh) :\n boundary_info (new BoundaryInfo(*this)), \/\/ no copy constructor defined for BoundaryInfo?\n _n_parts (other_mesh._n_parts),\n _dim (other_mesh._dim),\n _is_prepared (other_mesh._is_prepared),\n _point_locator (NULL),\n _partitioner (other_mesh._partitioner->clone())\n{\n}\n\n\n\nMeshBase::~MeshBase()\n{\n this->clear();\n\n libmesh_assert (!libMesh::closed());\n}\n\n\n\nvoid MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements)\n{ \n \/\/ Renumber the nodes and elements so that they in contiguous\n \/\/ blocks. By default, skip_renumber_nodes_and_elements is false,\n \/\/ however we may skip this step by passing\n \/\/ skip_renumber_nodes_and_elements==true to this function.\n \/\/\n \/\/ Instances where you if prepare_for_use() should not renumber the nodes\n \/\/ and elements include reading in e.g. an xda\/r or gmv file. In\n \/\/ this case, the ordering of the nodes may depend on an accompanying\n \/\/ solution, and the node ordering cannot be changed.\n if(!skip_renumber_nodes_and_elements)\n this->renumber_nodes_and_elements();\n \n \/\/ Let all the elements find their neighbors\n this->find_neighbors();\n\n \/\/ Partition the mesh.\n this->partition();\n \n \/\/ If we're using ParallelMesh, we'll want it parallelized.\n this->delete_remote_elements();\n\n if(!skip_renumber_nodes_and_elements)\n this->renumber_nodes_and_elements();\n\n \/\/ Reset our PointLocator. This needs to happen any time the elements\n \/\/ in the underlying elements in the mesh have changed, so we do it here.\n this->clear_point_locator();\n\n \/\/ The mesh is now prepared for use.\n _is_prepared = true;\n}\n\n\n\nvoid MeshBase::clear ()\n{\n \/\/ Reset the number of partitions\n _n_parts = 1;\n\n \/\/ Reset the _is_prepared flag\n _is_prepared = false;\n\n \/\/ Clear boundary information\n this->boundary_info->clear();\n\n \/\/ Clear our point locator.\n this->clear_point_locator();\n}\n\n\n\nunsigned int MeshBase::n_subdomains() const\n{\n \/\/ This requires an inspection on every processor\n parallel_only();\n\n const_element_iterator el = this->active_elements_begin();\n const const_element_iterator end = this->active_elements_end(); \n\n std::set subdomain_ids;\n \n for (; el!=end; ++el)\n subdomain_ids.insert((*el)->subdomain_id());\n\n \/\/ Some subdomains may only live on other processors\n Parallel::set_union(subdomain_ids, 0);\n\n unsigned int n_sbd_ids = subdomain_ids.size();\n Parallel::broadcast(n_sbd_ids);\n\n return n_sbd_ids;\n}\n\n\nunsigned int MeshBase::n_nodes_on_proc (const unsigned int proc_id) const\n{\n \/\/ We're either counting a processor's nodes or unpartitioned\n \/\/ nodes\n libmesh_assert (proc_id < libMesh::n_processors() ||\n\t proc_id == DofObject::invalid_processor_id);\n \n return static_cast(std::distance (this->pid_nodes_begin(proc_id),\n\t\t\t\t\t\t this->pid_nodes_end (proc_id)));\n}\n\n\n\nunsigned int MeshBase::n_elem_on_proc (const unsigned int proc_id) const\n{\n \/\/ We're either counting a processor's elements or unpartitioned\n \/\/ elements\n libmesh_assert (proc_id < libMesh::n_processors() ||\n\t proc_id == DofObject::invalid_processor_id);\n \n return static_cast(std::distance (this->pid_elements_begin(proc_id),\n\t\t\t\t\t\t this->pid_elements_end (proc_id)));\n}\n\n\n\nunsigned int MeshBase::n_active_elem_on_proc (const unsigned int proc_id) const\n{\n libmesh_assert (proc_id < libMesh::n_processors());\n return static_cast(std::distance (this->active_pid_elements_begin(proc_id),\n\t\t\t\t\t\t this->active_pid_elements_end (proc_id)));\n}\n \n\n\nunsigned int MeshBase::n_sub_elem () const\n{\n unsigned int ne=0;\n\n const_element_iterator el = this->elements_begin();\n const const_element_iterator end = this->elements_end(); \n\n for (; el!=end; ++el)\n ne += (*el)->n_sub_elem(); \n\n return ne;\n}\n\n\n\nunsigned int MeshBase::n_active_sub_elem () const\n{\n unsigned int ne=0;\n\n const_element_iterator el = this->active_elements_begin();\n const const_element_iterator end = this->active_elements_end(); \n\n for (; el!=end; ++el)\n ne += (*el)->n_sub_elem(); \n\n return ne;\n}\n\n\n\nstd::string MeshBase::get_info() const\n{\n std::ostringstream out;\n\n out << \" Mesh Information:\" << '\\n'\n << \" mesh_dimension()=\" << this->mesh_dimension() << '\\n'\n << \" spatial_dimension()=\" << this->spatial_dimension() << '\\n'\n << \" n_nodes()=\" << this->n_nodes() << '\\n'\n << \" n_local_nodes()=\" << this->n_local_nodes() << '\\n'\n << \" n_elem()=\" << this->n_elem() << '\\n'\n << \" n_local_elem()=\" << this->n_local_elem() << '\\n'\n#ifdef LIBMESH_ENABLE_AMR\n << \" n_active_elem()=\" << this->n_active_elem() << '\\n'\n#endif\n << \" n_subdomains()=\" << this->n_subdomains() << '\\n'\n << \" n_processors()=\" << this->n_processors() << '\\n'\n << \" processor_id()=\" << this->processor_id() << '\\n';\n\n return out.str();\n}\n\n\nvoid MeshBase::print_info(std::ostream& os) const\n{\n os << this->get_info()\n << std::endl;\n}\n\n\nstd::ostream& operator << (std::ostream& os, const MeshBase& m)\n{\n m.print_info(os);\n return os;\n}\n\n\n\n\nvoid MeshBase::partition (const unsigned int n_parts)\n{\n if (partitioner().get()) \/\/ \"NULL\" means don't partition\n partitioner()->partition (*this, n_parts);\n}\n\n\n\nunsigned int MeshBase::recalculate_n_partitions()\n{\n const_element_iterator el = this->active_elements_begin();\n const const_element_iterator end = this->active_elements_end(); \n\n unsigned int max_proc_id=0;\n \n for (; el!=end; ++el)\n max_proc_id = std::max(max_proc_id, static_cast((*el)->processor_id()));\n\n \/\/ The number of partitions is one more than the max processor ID.\n _n_parts = max_proc_id+1;\n\n return _n_parts;\n}\n\n\n\nconst PointLocatorBase & MeshBase::point_locator () const\n{\n if (_point_locator.get() == NULL)\n {\n \/\/ PointLocator construction may not be safe within threads\n libmesh_assert(!Threads::in_threads);\n\n _point_locator.reset (PointLocatorBase::build(TREE, *this).release());\n }\n}\n\n\n\nvoid MeshBase::clear_point_locator ()\n{\n _point_locator.reset(NULL);\n}\n\n} \/\/ namespace libMesh\n\n\n\n\n<|endoftext|>"} {"text":"Rename ImplGetGradientColorValue<|endoftext|>"} {"text":"help coverity out wrt coverity#1267682 String not null terminated<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"..\/core\/folder.h\"\n#include \"..\/foldermodel.h\"\n#include \"..\/folderview.h\"\n#include \"..\/cachedfoldermodel.h\"\n#include \"..\/proxyfoldermodel.h\"\n#include \"..\/pathedit.h\"\n#include \"libfmqt.h\"\n\nint main(int argc, char** argv) {\n QApplication app(argc, argv);\n\n Fm::LibFmQt contex;\n QMainWindow win;\n\n Fm::FolderView folder_view;\n win.setCentralWidget(&folder_view);\n\n auto home = Fm::FilePath::homeDir();\n Fm::CachedFolderModel* model = Fm::CachedFolderModel::modelFromPath(home);\n auto proxy_model = new Fm::ProxyFolderModel();\n proxy_model->sort(Fm::FolderModel::ColumnFileName, Qt::AscendingOrder);\n proxy_model->setSourceModel(model);\n\n proxy_model->setThumbnailSize(64);\n proxy_model->setShowThumbnails(true);\n\n folder_view.setModel(proxy_model);\n\n QToolBar toolbar;\n win.addToolBar(Qt::TopToolBarArea, &toolbar);\n Fm::PathEdit edit;\n edit.setText(home.toString().get());\n toolbar.addWidget(&edit);\n auto action = new QAction(QStringLiteral(\"Go\"), nullptr);\n toolbar.addAction(action);\n QObject::connect(action, &QAction::triggered, [&]() {\n auto path = Fm::FilePath::fromPathStr(edit.text().toLocal8Bit().constData());\n auto new_model = Fm::CachedFolderModel::modelFromPath(path);\n proxy_model->setSourceModel(new_model);\n });\n\n win.show();\n return app.exec();\n}\nUpdate test-folderview.cpp\/*\n * Copyright (C) 2017 Hong Jen Yee (PCMan) \n *\n * This 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#include \"..\/core\/folder.h\"\n#include \"..\/foldermodel.h\"\n#include \"..\/folderview.h\"\n#include \"..\/cachedfoldermodel.h\"\n#include \"..\/proxyfoldermodel.h\"\n#include \"..\/pathedit.h\"\n#include \"libfmqt.h\"\n\nint main(int argc, char** argv) {\n QApplication app(argc, argv);\n\n Fm::LibFmQt contex;\n QMainWindow win;\n\n Fm::FolderView folder_view;\n win.setCentralWidget(&folder_view);\n\n auto home = Fm::FilePath::homeDir();\n Fm::CachedFolderModel* model = Fm::CachedFolderModel::modelFromPath(home);\n auto proxy_model = new Fm::ProxyFolderModel();\n proxy_model->sort(Fm::FolderModel::ColumnFileName, Qt::AscendingOrder);\n proxy_model->setSourceModel(model);\n\n proxy_model->setThumbnailSize(64);\n proxy_model->setShowThumbnails(true);\n\n folder_view.setModel(proxy_model);\n\n QToolBar toolbar;\n win.addToolBar(Qt::TopToolBarArea, &toolbar);\n Fm::PathEdit edit;\n edit.setText(home.toString().get());\n toolbar.addWidget(&edit);\n auto action = new QAction(QStringLiteral(\"Go\"), nullptr);\n toolbar.addAction(action);\n QObject::connect(action, &QAction::triggered, [&]() {\n auto path = Fm::FilePath::fromPathStr(edit.text().toLocal8Bit().constData());\n auto new_model = Fm::CachedFolderModel::modelFromPath(path);\n proxy_model->setSourceModel(new_model);\n });\n\n win.show();\n return app.exec();\n}\n<|endoftext|>"} {"text":"#include \n#include \"..\/tlang.h\"\n\nTLANG_NAMESPACE_BEGIN\n\nauto volume_renderer = [] {\n CoreState::set_trigger_gdb_when_crash(true);\n\n int n = 512;\n int grid_resolution = 256;\n\n auto f = fopen(\"snow_density_256.bin\", \"rb\");\n TC_ASSERT_INFO(f, \".\/snow_density_256.bin not found\");\n std::vector density_field(pow<3>(grid_resolution));\n std::fread(density_field.data(), sizeof(float32), density_field.size(), f);\n std::fclose(f);\n\n Program prog(Arch::gpu);\n prog.config.print_ir = true;\n\n Vector buffer(DataType::f32, 3);\n Global(density, f32);\n\n layout([&]() {\n root.dense(Index(0), n * n * 2).place(buffer(0), buffer(1), buffer(2));\n root.dense(Indices(0, 1, 2), grid_resolution).place(density);\n });\n\n \/\/ If p is in the density field return the density, other 0\n auto query_density = [&](Vector p) {\n auto inside_box = Var(0.0f <= p(0) && p(0) < 1.0f && 0.0f <= p(1) &&\n p(1) < 1.0f && 0.0f <= p(2) && p(2) < 1.0f);\n auto ret = Var(0.0f);\n If(inside_box).Then([&] {\n auto i = floor(p(0) * float32(grid_resolution));\n auto j = floor(p(1) * float32(grid_resolution));\n auto k = floor(p(2) * float32(grid_resolution));\n ret = density[i, j, k];\n });\n return ret;\n };\n\n auto background = [](Vector dir) {\n return 1.0f * max(dir(1) + dir(0), 0.0f);\n };\n\n float32 fov = 0.7;\n\n Kernel(main).def([&]() {\n For(0, n * n * 2, [&](Expr i) {\n auto orig = Var(Vector({0.5f, 0.3f, 1.5f}));\n\n auto c = Var(Vector({fov * (cast(i \/ n) \/ float32(n \/ 2) - 2.0f),\n fov * (cast(i % n) \/ float32(n \/ 2) - 1.0f),\n -1.0f}));\n\n c = normalized(c);\n\n auto color = Var(Vector({1.0f, 1.0f, 1.0f}));\n\n For(0, 200, [&](Expr k) {\n auto p = Var(orig + c * ((cast(k) + Rand()) * 0.01f));\n color *= (1.0_f - query_density(p) * 0.1f);\n });\n\n buffer[i] += color;\n });\n });\n\n for (int i = 0; i < grid_resolution; i++) {\n for (int j = 0; j < grid_resolution; j++) {\n for (int k = 0; k < grid_resolution; k++) {\n density.val(i, j, k) =\n density_field[i * grid_resolution * grid_resolution +\n j * grid_resolution + k];\n }\n }\n }\n\n GUI gui(\"Volume Renderer\", Vector2i(n * 2, n));\n\n auto tone_map = [](real x) { return x; };\n constexpr int N = 10;\n for (int frame = 0;; frame++) {\n for (int i = 0; i < N; i++)\n main();\n real scale = 1.0f \/ ((frame + 1) * N);\n for (int i = 0; i < n * n * 2; i++) {\n gui.buffer[i \/ n][i % n] =\n Vector4(tone_map(scale * buffer(0).val(i)),\n tone_map(scale * buffer(1).val(i)),\n tone_map(scale * buffer(2).val(i)), 1);\n }\n gui.update();\n }\n};\nTC_REGISTER_TASK(volume_renderer);\n\nTLANG_NAMESPACE_END\nVolume renderer#include \n#include \"..\/tlang.h\"\n\nTLANG_NAMESPACE_BEGIN\n\nauto volume_renderer = [] {\n \/\/CoreState::set_trigger_gdb_when_crash(true);\n\n int depth_limit = 40;\n int n = 512;\n int grid_resolution = 256;\n Vector3 albedo(0.95, 0.95, 0.95);\n float32 scale = 724.0;\n float32 one_over_four_pi = 0.07957747154;\n float32 pi = 3.14159265359;\n\n auto f = fopen(\"snow_density_256.bin\", \"rb\");\n TC_ASSERT_INFO(f, \".\/snow_density_256.bin not found\");\n std::vector density_field(pow<3>(grid_resolution));\n std::fread(density_field.data(), sizeof(float32), density_field.size(), f);\n std::fclose(f);\n\n Program prog(Arch::gpu);\n prog.config.print_ir = true;\n\n Vector buffer(DataType::f32, 3);\n Global(density, f32);\n\n layout([&]() {\n root.dense(Index(0), n * n * 2).place(buffer(0), buffer(1), buffer(2));\n root.dense(Indices(0, 1, 2), grid_resolution).place(density);\n });\n\n auto point_inside_box = [&](Vector p) {\n return Var(0.0f <= p(0) && p(0) < 1.0f && 0.0f <= p(1) &&\n p(1) < 1.0f && 0.0f <= p(2) && p(2) < 1.0f);\n };\n\n \/\/ If p is in the density field, return the density, otherwise return 0\n auto query_density = [&](Vector p) {\n auto inside_box = point_inside_box(p);\n auto ret = Var(0.0f);\n If(inside_box).Then([&] {\n auto i = floor(p(0) * float32(grid_resolution));\n auto j = floor(p(1) * float32(grid_resolution));\n auto k = floor(p(2) * float32(grid_resolution));\n ret = density[i, j, k] * scale;\n });\n return ret;\n };\n\n \/\/ Adapted from Mitsuba: include\/mitsuba\/core\/aabb.h#L308\n auto box_intersect = [&](Vector o, Vector d, Expr& near_t, Expr& far_t) {\n auto result = Var(1);\n\n \/* For each pair of AABB planes *\/\n for (int i = 0; i < 3; i++) {\n auto origin = o(i);\n auto min_val = Var(0.f);\n auto max_val = Var(1.f);\n auto d_rcp = Var(1.f \/ d(i));\n\n If(d(i) == 0.f)\n .Then([&] {\n \/* The ray is parallel to the planes *\/\n If(origin < min_val || origin > max_val, [&] {\n result = 0;\n });\n }).Else([&] {\n \/* Calculate intersection distances *\/\n auto t1 = Var((min_val - origin) * d_rcp);\n auto t2 = Var((max_val - origin) * d_rcp);\n\n If(t1 > t2, [&] {\n auto tmp = Var(t1);\n t1 = t2;\n t2 = tmp;\n });\n\n near_t = max(t1, near_t);\n far_t = min(t2, far_t);\n\n If(near_t > far_t, [&] {\n result = 0;\n });\n });\n }\n\n return result;\n };\n\n \/\/ Adapted from Mitsuba: src\/libcore\/warp.cpp#L25\n auto sample_phase_isotropic = [&]() {\n auto z = Var(1.0f - 2.0f * Rand());\n auto r = Var(sqrt(1.0f - z * z));\n auto phi = Var(2.0f * pi * Rand());\n auto sin_phi = Var(sin(phi));\n auto cos_phi = Var(cos(phi));\n return Var(Vector({r * cos_phi, r * sin_phi, z}));\n };\n\n auto pdf_phase_isotropic = [&]() {\n return Var(one_over_four_pi);\n };\n\n auto eval_phase_isotropic = [&]() {\n return pdf_phase_isotropic();\n };\n\n \/\/ Direct sample light\n auto sample_light = [&](Vector p, float32 inv_max_density) {\n auto Le = Var(Vector({5.0f, 5.0f, 5.0f}));\n auto light_p = Var(Vector({0.5f, 1.5f, 0.5f}));\n auto dir_to_p = Var(p - light_p);\n auto dist_to_p = Var(dir_to_p.norm());\n auto inv_dist_to_p = Var(1.f \/ dist_to_p);\n dir_to_p = normalized(dir_to_p);\n\n auto near_t = Var(-std::numeric_limits::max());\n auto far_t = Var(std::numeric_limits::max());\n auto hit = box_intersect(light_p, dir_to_p, near_t, far_t);\n auto interaction = Var(0);\n auto transmittance = Var(1.f);\n\n If(hit, [&] {\n auto cond = Var(hit);\n auto t = Var(near_t);\n\n While(cond, [&] {\n t -= log(1.f - Rand()) * inv_max_density;\n\n p = Var(light_p + t * dir_to_p);\n If(t >= dist_to_p || !point_inside_box(p))\n .Then([&] {\n cond = 0;\n })\n .Else([&] {\n auto density_at_p = query_density(p);\n If(density_at_p * inv_max_density > Rand()).Then([&] {\n cond = 0;\n transmittance = Var(0.f);\n });\n });\n });\n });\n\n return Var(transmittance * Le * inv_dist_to_p * inv_dist_to_p);\n };\n\n \/\/ Woodcock tracking\n auto sample_distance = [&](Vector o, Vector d, float32 inv_max_density, Expr& dist, Vector& sigma_s, Expr& transmittance, Vector& p) {\n auto near_t = Var(-std::numeric_limits::max());\n auto far_t = Var(std::numeric_limits::max());\n auto hit = box_intersect(o, d, near_t, far_t);\n\n auto cond = Var(hit);\n auto interaction = Var(0);\n auto t = Var(near_t);\n\n While(cond, [&] {\n t -= log(1.f - Rand()) * inv_max_density;\n\n p = Var(o + t * d);\n If(t >= far_t || !point_inside_box(p))\n .Then([&] {\n cond = 0;\n })\n .Else([&] {\n auto density_at_p = query_density(p);\n If(density_at_p * inv_max_density > Rand()).Then([&] {\n sigma_s(0) = Var(density_at_p * albedo[0]);\n sigma_s(1) = Var(density_at_p * albedo[1]);\n sigma_s(2) = Var(density_at_p * albedo[2]);\n If(density_at_p != 0.f).Then([&] {\n transmittance = 1.f \/ density_at_p;\n });\n cond = 0;\n interaction = 1;\n });\n });\n });\n\n dist = t - near_t;\n\n return hit && interaction;\n };\n\n auto background = [](Vector dir) {\n return Vector({0.4f, 0.4f, 0.4f});\n };\n\n float32 fov = 0.7;\n\n auto max_density = *std::max_element(density_field.begin(), density_field.end()) * scale;\n auto inv_max_density = 0.f;\n if (max_density > 0.f) {\n inv_max_density = 1.f \/ max_density;\n }\n\n Kernel(main).def([&]() {\n For(0, n * n * 2, [&](Expr i) {\n auto orig = Var(Vector({0.5f, 0.3f, 1.5f}));\n\n auto c = Var(Vector({fov * ((Rand() + cast(i \/ n)) \/ float32(n \/ 2) - 2.0f),\n fov * ((Rand() + cast(i % n)) \/ float32(n \/ 2) - 1.0f),\n -1.0f}));\n\n c = normalized(c);\n\n auto color = Var(Vector({1.0f, 1.0f, 1.0f}));\n auto Li = Var(Vector({0.0f, 0.0f, 0.0f}));\n auto throughput = Var(Vector({1.0f, 1.0f, 1.0f}));\n auto depth = Var(0);\n\n While(depth < depth_limit, [&] {\n auto dist = Var(0.f);\n auto transmittance = Var(0.f);\n auto sigma_s = Var(Vector({0.f, 0.f, 0.f}));\n auto interaction_p = Var(Vector({0.f, 0.f, 0.f}));\n auto interaction = sample_distance(orig, c, inv_max_density, dist, sigma_s, transmittance, interaction_p);\n\n depth += 1;\n If(interaction)\n .Then([&] {\n throughput = throughput.element_wise_prod(sigma_s * transmittance);\n\n auto phase_value = eval_phase_isotropic();\n auto light_value = sample_light(interaction_p, inv_max_density);\n Li += phase_value * throughput.element_wise_prod(light_value);\n\n orig = interaction_p;\n c = sample_phase_isotropic();\n }).Else([&] {\n Li += throughput.element_wise_prod(background(c));\n depth = depth_limit;\n });\n });\n\n buffer[i] += Li;\n\n });\n });\n\n for (int i = 0; i < grid_resolution; i++) {\n for (int j = 0; j < grid_resolution; j++) {\n for (int k = 0; k < grid_resolution; k++) {\n density.val(i, j, k) =\n density_field[i * grid_resolution * grid_resolution +\n j * grid_resolution + k];\n }\n }\n }\n\n \/\/GUI gui(\"Volume Renderer\", Vector2i(n * 2, n));\n Vector2i render_size(n * 2, n);\n Array2D render_buffer;\n std::unique_ptr canvas;\n\n auto tone_map = [](real x) { return x; };\n constexpr int N = 1024;\n for (int frame = 0; frame < 1; frame++) {\n for (int i = 0; i < N; i++) {\n main();\n }\n\n real scale = 1.0f \/ ((frame + 1) * N);\n render_buffer.initialize(render_size);\n canvas = std::make_unique(render_buffer);\n for (int i = 0; i < n * n * 2; i++) {\n render_buffer[i \/ n][i % n] =\n Vector4(tone_map(scale * buffer(0).val(i)),\n tone_map(scale * buffer(1).val(i)),\n tone_map(scale * buffer(2).val(i)), 1);\n }\n \/\/gui.update();\n canvas->img.write_as_image(fmt::format(\"{:05d}-{:05d}-{:05d}.png\", frame, N, depth_limit));\n }\n};\nTC_REGISTER_TASK(volume_renderer);\n\nTLANG_NAMESPACE_END\n<|endoftext|>"} {"text":"\n#include \"vtrc-transport-tcp.h\"\n\n#include \"vtrc-protocol-layer.h\"\n#include \"vtrc-transport-stream-impl.h\"\n\nnamespace vtrc { namespace common {\n\n namespace basio = boost::asio;\n namespace bip = boost::asio::ip;\n namespace bsys = boost::system;\n\n namespace {\n typedef transport_tcp::socket_type socket_type;\n typedef transport_impl impl_type;\n\n }\n\n struct transport_tcp::impl: public impl_type {\n\n impl( vtrc::shared_ptr s, const std::string &n )\n :impl_type(s, n)\n { }\n\n std::string prepare_for_write(const char *data, size_t len)\n {\n return get_parent( )->prepare_for_write( data, len );\n }\n\n };\n\n std::string make_name( socket_type &sock )\n {\n std::ostringstream oss;\n oss << \"tcp:\/\/\" << sock.remote_endpoint( );\n }\n\n transport_tcp::transport_tcp( vtrc::shared_ptr sock )\n :impl_(new impl(sock, \"tcp\"))\n {\n impl_->set_parent( this );\n }\n\n transport_tcp::~transport_tcp( )\n {\n delete impl_;\n }\n\n std::string transport_tcp::name( ) const\n {\n return impl_->name( );\n }\n\n void transport_tcp::close( )\n {\n impl_->close( );\n }\n\n void transport_tcp::write( const char *data, size_t length )\n {\n return impl_->write( data, length );\n }\n\n void transport_tcp::write(const char *data, size_t length,\n const system_closure_type &success, bool on_send_success)\n {\n impl_->write( data, length, success, on_send_success );\n }\n\n std::string transport_tcp::prepare_for_write(const char *data, size_t len)\n {\n return impl_->prepare_for_write( data, len );\n }\n\n socket_type &transport_tcp::get_socket( )\n {\n return impl_->get_socket( );\n }\n\n const socket_type &transport_tcp::get_socket( ) const\n {\n return impl_->get_socket( );\n }\n\n}}\nlistener\n#include \"vtrc-transport-tcp.h\"\n\n#include \"vtrc-protocol-layer.h\"\n#include \"vtrc-transport-stream-impl.h\"\n\nnamespace vtrc { namespace common {\n\n namespace basio = boost::asio;\n namespace bip = boost::asio::ip;\n namespace bsys = boost::system;\n\n namespace {\n typedef transport_tcp::socket_type socket_type;\n typedef transport_impl impl_type;\n\n }\n\n struct transport_tcp::impl: public impl_type {\n\n impl( vtrc::shared_ptr s, const std::string &n )\n :impl_type(s, n)\n { }\n\n std::string prepare_for_write(const char *data, size_t len)\n {\n return get_parent( )->prepare_for_write( data, len );\n }\n\n };\n\n transport_tcp::transport_tcp( vtrc::shared_ptr sock )\n :impl_(new impl(sock, \"tcp\"))\n {\n impl_->set_parent( this );\n }\n\n transport_tcp::~transport_tcp( )\n {\n delete impl_;\n }\n\n std::string transport_tcp::name( ) const\n {\n return impl_->name( );\n }\n\n void transport_tcp::close( )\n {\n impl_->close( );\n }\n\n void transport_tcp::write( const char *data, size_t length )\n {\n return impl_->write( data, length );\n }\n\n void transport_tcp::write(const char *data, size_t length,\n const system_closure_type &success, bool on_send_success)\n {\n impl_->write( data, length, success, on_send_success );\n }\n\n std::string transport_tcp::prepare_for_write(const char *data, size_t len)\n {\n return impl_->prepare_for_write( data, len );\n }\n\n socket_type &transport_tcp::get_socket( )\n {\n return impl_->get_socket( );\n }\n\n const socket_type &transport_tcp::get_socket( ) const\n {\n return impl_->get_socket( );\n }\n\n}}\n<|endoftext|>"} {"text":"#ifndef MJOLNIR_UTIL_ALIGNED_STORAGE_HPP\n#define MJOLNIR_UTIL_ALIGNED_STORAGE_HPP\n#include \n#include \n#include \n\nnamespace mjolnir\n{\n\ntemplate\nstruct alignas(Align) aligned_storage\n{\n public:\n using type = T;\n static_assert(Align != 0, \"\");\n\n static constexpr std::size_t alignment_size = Align;\n static constexpr std::size_t value_size = sizeof(T);\n static constexpr std::size_t padded_size =\n alignment_size * (value_size \/ alignment_size + 1);\n static constexpr std::size_t padding_size =\n alignment_size - (value_size % alignment_size);\n\n static_assert((padding_size + value_size) % padded_size == 0, \"\");\n static_assert((padding_size + value_size) % alignment_size == 0, \"\");\n\n public:\n aligned_storage() = default;\n ~aligned_storage() = default;\n aligned_storage(aligned_storage const&) = default;\n aligned_storage(aligned_storage &&) = default;\n aligned_storage& operator=(aligned_storage const&) = default;\n aligned_storage& operator=(aligned_storage &&) = default;\n\n aligned_storage(const T& v)\n noexcept(std::is_nothrow_copy_constructible::value)\n : value(v)\n {}\n aligned_storage(T&& v)\n noexcept(std::is_nothrow_move_constructible::value)\n : value(v)\n {}\n\n T value;\n\n private:\n std::array padding_;\n};\n\nstatic_assert(alignof(aligned_storage) == 64, \"\");\nstatic_assert(sizeof (aligned_storage) == 64, \"\");\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_UTIL_ALIGNED_STORAGE_HPP\ntest: add a static_assert for aligned storage#ifndef MJOLNIR_UTIL_ALIGNED_STORAGE_HPP\n#define MJOLNIR_UTIL_ALIGNED_STORAGE_HPP\n#include \n#include \n#include \n#include \n\nnamespace mjolnir\n{\n\ntemplate\nstruct alignas(Align) aligned_storage\n{\n public:\n using type = T;\n static_assert(Align != 0, \"\");\n\n static constexpr std::size_t alignment_size = Align;\n static constexpr std::size_t value_size = sizeof(T);\n static constexpr std::size_t padded_size =\n alignment_size * (value_size \/ alignment_size + 1);\n static constexpr std::size_t padding_size =\n alignment_size - (value_size % alignment_size);\n\n static_assert((padding_size + value_size) % padded_size == 0, \"\");\n static_assert((padding_size + value_size) % alignment_size == 0, \"\");\n\n public:\n aligned_storage() = default;\n ~aligned_storage() = default;\n aligned_storage(aligned_storage const&) = default;\n aligned_storage(aligned_storage &&) = default;\n aligned_storage& operator=(aligned_storage const&) = default;\n aligned_storage& operator=(aligned_storage &&) = default;\n\n aligned_storage(const T& v)\n noexcept(std::is_nothrow_copy_constructible::value)\n : value(v)\n {}\n aligned_storage(T&& v)\n noexcept(std::is_nothrow_move_constructible::value)\n : value(v)\n {}\n\n T value;\n\n private:\n std::array padding_;\n};\n\nstatic_assert(alignof(aligned_storage) == 64, \"\");\nstatic_assert(sizeof (aligned_storage) == 64, \"\");\n\nstatic_assert(alignof(aligned_storage, 64>) == 64, \"\");\nstatic_assert(sizeof (aligned_storage, 64>) == 64, \"\");\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_UTIL_ALIGNED_STORAGE_HPP\n<|endoftext|>"} {"text":"\/**************************************************************************************\/\r\n\/* *\/\r\n\/* Visualization Library *\/\r\n\/* http:\/\/www.visualizationlibrary.com *\/\r\n\/* *\/\r\n\/* Copyright (c) 2005-2010, Michele Bosi *\/\r\n\/* All rights reserved. *\/\r\n\/* *\/\r\n\/* Redistribution and use in source and binary forms, with or without modification, *\/\r\n\/* are permitted provided that the following conditions are met: *\/\r\n\/* *\/\r\n\/* - Redistributions of source code must retain the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer. *\/\r\n\/* *\/\r\n\/* - Redistributions in binary form must reproduce the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer in the documentation and\/or *\/\r\n\/* 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 HOLDER 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 ON *\/\r\n\/* 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\/**************************************************************************************\/\r\n\r\n#ifndef DrawArrays_INCLUDE_DEFINE\r\n#define DrawArrays_INCLUDE_DEFINE\r\n\r\n#include \r\n#include \r\n\r\nnamespace vl\r\n{\r\n \/\/------------------------------------------------------------------------------\r\n \/\/ DrawArrays\r\n \/\/------------------------------------------------------------------------------\r\n \/**\r\n * Wraps the OpenGL function glDrawArrays(). See also http:\/\/www.opengl.org\/sdk\/docs\/man\/xhtml\/glDrawArrays.xml for more information.\r\n *\r\n * DrawElements, MultiDrawElements, DrawRangeElements, DrawArrays are used by Geometry to define a set of primitives to be rendered, see Geometry::drawCalls().\r\n *\r\n * \\sa DrawCall, DrawElements, MultiDrawElements, DrawRangeElements, Geometry, Actor *\/\r\n class DrawArrays: public DrawCall\r\n {\r\n public:\r\n DrawArrays(): mStart(0), mCount(0) \r\n { \r\n VL_DEBUG_SET_OBJECT_NAME()\r\n mType = PT_TRIANGLES;\r\n mInstances = 1;\r\n }\r\n DrawArrays(EPrimitiveType primitive, int start, int count, int instances=1)\r\n : mStart(start), mCount(count)\r\n { \r\n VL_DEBUG_SET_OBJECT_NAME()\r\n mInstances = instances;\r\n mType = primitive;\r\n }\r\n virtual const char* className() const { return \"vl::DrawArrays\"; }\r\n\r\n DrawArrays& operator=(const DrawArrays& other)\r\n {\r\n DrawCall::operator=(other);\r\n mStart = other.mStart;\r\n mCount = other.mCount;\r\n mInstances = other.mInstances;\r\n return *this;\r\n }\r\n\r\n virtual ref clone() const \r\n { \r\n return new DrawArrays( primitiveType(), (int)start(), (int)count(), (int)instances() ); \r\n }\r\n\r\n virtual void deleteVBOs() {}\r\n virtual void updateVBOs(bool,bool) {}\r\n virtual unsigned int handle() const { return 0; }\r\n\r\n virtual void render(bool) const\r\n {\r\n \/\/ apply patch parameters if any and if using PT_PATCHES\r\n applyPatchParameters();\r\n\r\n if ( instances() > 1 && (Has_GL_ARB_draw_instanced||Has_GL_EXT_draw_instanced) )\r\n VL_glDrawArraysInstanced( primitiveType(), (int)start(), (int)count(), (int)instances() );\r\n else\r\n glDrawArrays( primitiveType(), (int)start(), (int)count() );\r\n\r\n #ifndef NDEBUG\r\n unsigned int glerr = glGetError();\r\n if (glerr != GL_NO_ERROR)\r\n {\r\n String msg( (char*)gluErrorString(glerr) );\r\n Log::error( Say(\"glGetError() [%s:%n]: %s\\n\") << __FILE__ << __LINE__ << msg );\r\n Log::print(\r\n \"OpenGL Geometry Instancing (GL_ARB_draw_instanced) does not support display lists.\"\r\n \"If you are using geometry instancing in conjunction with display lists you will have to disable one of them.\\n\"\r\n );\r\n VL_TRAP()\r\n }\r\n #endif\r\n }\r\n\r\n \/\/! sets the starting vertex for the rendering.\r\n void setStart(int start) { mStart = start; }\r\n\r\n \/\/! returns the starting vertex for the rendering.\r\n int start() const { return mStart; }\r\n\r\n \/\/! sets the number of vertices to be rendered.\r\n void setCount(int count) { mCount = count; }\r\n\r\n \/\/! returns the number of vertices to be rendered.\r\n int count() const { return mCount; }\r\n\r\n \/\/! Sets the number of instances for this set of primitives.\r\n void setInstances(int instances) { mInstances = instances; }\r\n\r\n \/\/! Returns the number of instances for this set of primitives.\r\n int instances() const { return mInstances; }\r\n\r\n TriangleIterator triangleIterator() const\r\n {\r\n ref tid = new TriangleIteratorDirect( primitiveType() );\r\n tid->initialize(mStart, mStart+mCount);\r\n return TriangleIterator(tid.get());\r\n }\r\n\r\n IndexIterator indexIterator() const\r\n {\r\n ref iida = new IndexIteratorDrawArrays;\r\n iida->initialize( mStart, mCount );\r\n IndexIterator iit;\r\n iit.initialize( iida.get() );\r\n return iit;\r\n }\r\n\r\n protected:\r\n int mStart;\r\n int mCount;\r\n int mInstances;\r\n };\r\n\r\n}\r\n\r\n#endif\r\n\r\nRemoved glu dependency.\/**************************************************************************************\/\r\n\/* *\/\r\n\/* Visualization Library *\/\r\n\/* http:\/\/www.visualizationlibrary.com *\/\r\n\/* *\/\r\n\/* Copyright (c) 2005-2010, Michele Bosi *\/\r\n\/* All rights reserved. *\/\r\n\/* *\/\r\n\/* Redistribution and use in source and binary forms, with or without modification, *\/\r\n\/* are permitted provided that the following conditions are met: *\/\r\n\/* *\/\r\n\/* - Redistributions of source code must retain the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer. *\/\r\n\/* *\/\r\n\/* - Redistributions in binary form must reproduce the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer in the documentation and\/or *\/\r\n\/* 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 HOLDER 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 ON *\/\r\n\/* 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\/**************************************************************************************\/\r\n\r\n#ifndef DrawArrays_INCLUDE_DEFINE\r\n#define DrawArrays_INCLUDE_DEFINE\r\n\r\n#include \r\n#include \r\n\r\nnamespace vl\r\n{\r\n \/\/------------------------------------------------------------------------------\r\n \/\/ DrawArrays\r\n \/\/------------------------------------------------------------------------------\r\n \/**\r\n * Wraps the OpenGL function glDrawArrays(). See also http:\/\/www.opengl.org\/sdk\/docs\/man\/xhtml\/glDrawArrays.xml for more information.\r\n *\r\n * DrawElements, MultiDrawElements, DrawRangeElements, DrawArrays are used by Geometry to define a set of primitives to be rendered, see Geometry::drawCalls().\r\n *\r\n * \\sa DrawCall, DrawElements, MultiDrawElements, DrawRangeElements, Geometry, Actor *\/\r\n class DrawArrays: public DrawCall\r\n {\r\n public:\r\n DrawArrays(): mStart(0), mCount(0) \r\n { \r\n VL_DEBUG_SET_OBJECT_NAME()\r\n mType = PT_TRIANGLES;\r\n mInstances = 1;\r\n }\r\n DrawArrays(EPrimitiveType primitive, int start, int count, int instances=1)\r\n : mStart(start), mCount(count)\r\n { \r\n VL_DEBUG_SET_OBJECT_NAME()\r\n mInstances = instances;\r\n mType = primitive;\r\n }\r\n virtual const char* className() const { return \"vl::DrawArrays\"; }\r\n\r\n DrawArrays& operator=(const DrawArrays& other)\r\n {\r\n DrawCall::operator=(other);\r\n mStart = other.mStart;\r\n mCount = other.mCount;\r\n mInstances = other.mInstances;\r\n return *this;\r\n }\r\n\r\n virtual ref clone() const \r\n { \r\n return new DrawArrays( primitiveType(), (int)start(), (int)count(), (int)instances() ); \r\n }\r\n\r\n virtual void deleteVBOs() {}\r\n virtual void updateVBOs(bool,bool) {}\r\n virtual unsigned int handle() const { return 0; }\r\n\r\n virtual void render(bool) const\r\n {\r\n \/\/ apply patch parameters if any and if using PT_PATCHES\r\n applyPatchParameters();\r\n\r\n if ( instances() > 1 && (Has_GL_ARB_draw_instanced||Has_GL_EXT_draw_instanced) )\r\n VL_glDrawArraysInstanced( primitiveType(), (int)start(), (int)count(), (int)instances() );\r\n else\r\n glDrawArrays( primitiveType(), (int)start(), (int)count() );\r\n\r\n #ifndef NDEBUG\r\n unsigned int glerr = glGetError();\r\n if (glerr != GL_NO_ERROR)\r\n {\r\n String msg( getGLErrorString(glerr) );\r\n Log::error( Say(\"glGetError() [%s:%n]: %s\\n\") << __FILE__ << __LINE__ << msg );\r\n Log::print(\r\n \"OpenGL Geometry Instancing (GL_ARB_draw_instanced) does not support display lists.\"\r\n \"If you are using geometry instancing in conjunction with display lists you will have to disable one of them.\\n\"\r\n );\r\n VL_TRAP()\r\n }\r\n #endif\r\n }\r\n\r\n \/\/! sets the starting vertex for the rendering.\r\n void setStart(int start) { mStart = start; }\r\n\r\n \/\/! returns the starting vertex for the rendering.\r\n int start() const { return mStart; }\r\n\r\n \/\/! sets the number of vertices to be rendered.\r\n void setCount(int count) { mCount = count; }\r\n\r\n \/\/! returns the number of vertices to be rendered.\r\n int count() const { return mCount; }\r\n\r\n \/\/! Sets the number of instances for this set of primitives.\r\n void setInstances(int instances) { mInstances = instances; }\r\n\r\n \/\/! Returns the number of instances for this set of primitives.\r\n int instances() const { return mInstances; }\r\n\r\n TriangleIterator triangleIterator() const\r\n {\r\n ref tid = new TriangleIteratorDirect( primitiveType() );\r\n tid->initialize(mStart, mStart+mCount);\r\n return TriangleIterator(tid.get());\r\n }\r\n\r\n IndexIterator indexIterator() const\r\n {\r\n ref iida = new IndexIteratorDrawArrays;\r\n iida->initialize( mStart, mCount );\r\n IndexIterator iit;\r\n iit.initialize( iida.get() );\r\n return iit;\r\n }\r\n\r\n protected:\r\n int mStart;\r\n int mCount;\r\n int mInstances;\r\n };\r\n\r\n}\r\n\r\n#endif\r\n\r\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_REV_FUN_SOFTMAX_HPP\n#define STAN_MATH_REV_FUN_SOFTMAX_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the softmax of the specified Eigen vector. Softmax is\n * guaranteed to return a simplex.\n *\n * @param alpha Unconstrained input vector.\n * @return Softmax of the input.\n * @throw std::domain_error If the input vector is size 0.\n *\/\n\ninline Eigen::Matrix softmax(\n const Eigen::Matrix& alpha) {\n if (alpha.size() == 0) {\n return alpha;\n }\n\n arena_matrix res_val = softmax(value_of(alpha));\n arena_matrix> res = res_val;\n arena_matrix> alpha_arena = alpha;\n\n reverse_pass_callback([res_val, res, alpha_arena]() mutable {\n const auto& res_adj = to_ref(res.adj());\n alpha_arena.adj()\n += -res_val * res_adj.dot(res_val) + res_val.cwiseProduct(res_adj);\n });\n\n return res;\n}\n\ntemplate * = nullptr>\ninline auto softmax(const Mat& alpha) {\n if (alpha.size() == 0) {\n return alpha;\n }\n Mat res(softmax(value_of(alpha)));\n reverse_pass_callback([alpha, res]() mutable {\n alpha.adj() += alpha.adj() -res.val() * res.adj().dot(res.val()) + res.val().cwiseProduct(res.adj());\n });\n return res;\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\nremove double += alpha.adj()#ifndef STAN_MATH_REV_FUN_SOFTMAX_HPP\n#define STAN_MATH_REV_FUN_SOFTMAX_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the softmax of the specified Eigen vector. Softmax is\n * guaranteed to return a simplex.\n *\n * @param alpha Unconstrained input vector.\n * @return Softmax of the input.\n * @throw std::domain_error If the input vector is size 0.\n *\/\n\ninline Eigen::Matrix softmax(\n const Eigen::Matrix& alpha) {\n if (alpha.size() == 0) {\n return alpha;\n }\n\n arena_matrix res_val = softmax(value_of(alpha));\n arena_matrix> res = res_val;\n arena_matrix> alpha_arena = alpha;\n\n reverse_pass_callback([res_val, res, alpha_arena]() mutable {\n const auto& res_adj = to_ref(res.adj());\n alpha_arena.adj()\n += -res_val * res_adj.dot(res_val) + res_val.cwiseProduct(res_adj);\n });\n\n return res;\n}\n\ntemplate * = nullptr>\ninline auto softmax(const Mat& alpha) {\n if (alpha.size() == 0) {\n return alpha;\n }\n Mat res(softmax(value_of(alpha)));\n reverse_pass_callback([alpha, res]() mutable {\n alpha.adj() += -res.val() * res.adj().dot(res.val()) + res.val().cwiseProduct(res.adj());\n });\n return res;\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"\/*\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 \"Camera.h\"\n#include \"Device.h\"\n#include \"Types.h\"\n#include \"Renderer.h\"\n\nnamespace crown\n{\n\nCamera::Camera(const Vec3& position, bool visible, float fov, float aspect, bool active) :\n\tmPosition(position),\n\tmLookAt(0, 0, -1),\n\tmUp(0, 1, 0),\n\tmFOV(fov),\n\tmAspect(aspect),\n\tmNear(0.1f),\n\tmFar(1000.0f),\n\tmActive(active),\n\tmAutoAspect(true)\n{\n\tUpdateProjectionMatrix();\n\tUpdateViewMatrix();\n\tUpdateFrustum();\n}\n\nCamera::~Camera()\n{\n}\n\nvoid Camera::SetPosition(const Vec3& position)\n{\n\tmPosition = position;\n\tUpdateViewMatrix();\n}\n\nconst Vec3& Camera::GetLookAt() const\n{\n\treturn mLookAt;\n}\n\nvoid Camera::SetLookAt(const Vec3& lookat)\n{\n\tmLookAt = lookat;\n\tUpdateViewMatrix();\n}\n\nconst Vec3& Camera::GetUpVector() const\n{\n\treturn mUp;\n}\n\nbool Camera::IsActive() const\n{\n\treturn mActive;\n}\n\nvoid Camera::SetActive(bool active)\n{\n\tmActive = active;\n}\n\nfloat Camera::GetFOV() const\n{\n\treturn mFOV;\n}\n\nvoid Camera::SetFOV(float fov)\n{\n\tmFOV = fov;\n\tUpdateProjectionMatrix();\n}\n\nbool Camera::GetAutoAspect() const\n{\n\treturn mAutoAspect;\n}\n\nvoid Camera::SetAutoAspect(bool autoAspect)\n{\n\tmAutoAspect = autoAspect;\n}\n\nfloat Camera::GetAspect() const\n{\n\treturn mAspect;\n}\n\nvoid Camera::SetAspect(float aspect)\n{\n\tmAspect = aspect;\n\tUpdateProjectionMatrix();\n}\n\nfloat Camera::GetNearClipDistance() const\n{\n\treturn mNear;\n}\n\nvoid Camera::SetNearClipDistance(float near)\n{\n\tmNear = near;\n\tUpdateProjectionMatrix();\n}\n\nfloat Camera::GetFarClipDistance() const\n{\n\treturn mFar;\n}\n\nvoid Camera::SetFarClipDistance(float far)\n{\n\tmFar = far;\n\tUpdateProjectionMatrix();\n}\n\nconst Mat4& Camera::GetProjectionMatrix() const\n{\n\treturn mProjection;\n}\n\nconst Mat4& Camera::GetViewMatrix() const\n{\n\treturn mView;\n}\n\nconst Frustum& Camera::GetFrustum() const\n{\n\treturn mFrustum;\n}\n\nvoid Camera::Render()\n{\n\tGetDevice()->GetRenderer()->SetMatrix(MT_PROJECTION, mProjection);\n\tGetDevice()->GetRenderer()->SetMatrix(MT_VIEW, mView);\n}\n\nvoid Camera::UpdateProjectionMatrix()\n{\n\tmProjection.build_projection_perspective_rh(mFOV, mAspect, mNear, mFar);\n}\n\nvoid Camera::UpdateViewMatrix()\n{\n\tmView.build_look_at_rh(mPosition, mPosition + mLookAt, mUp);\n}\n\nvoid Camera::UpdateFrustum()\n{\n\tmFrustum.from_matrix(mProjection * mView);\n}\n\n} \/\/ namespace crown\n\nUpdate Camera.cpp\/*\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 \"Camera.h\"\n#include \"Device.h\"\n#include \"Types.h\"\n#include \"Renderer.h\"\n\nnamespace crown\n{\n\nCamera::Camera(const Vec3& position, bool visible, float fov, float aspect, bool active) :\n\tmPosition(position),\n\tmLookAt(0, 0, -1),\n\tmUp(0, 1, 0),\n\tmFOV(fov),\n\tmAspect(aspect),\n\tmNear(0.1f),\n\tmFar(1000.0f),\n\tmActive(active),\n\tmAutoAspect(true)\n{\n\tUpdateProjectionMatrix();\n\tUpdateViewMatrix();\n\tUpdateFrustum();\n}\n\nCamera::~Camera()\n{\n}\n\nvoid Camera::SetPosition(const Vec3& position)\n{\n\tmPosition = position;\n\tUpdateViewMatrix();\n}\n\nconst Vec3& Camera::GetLookAt() const\n{\n\treturn mLookAt;\n}\n\nvoid Camera::SetLookAt(const Vec3& lookat)\n{\n\tmLookAt = lookat;\n\tUpdateViewMatrix();\n}\n\nconst Vec3& Camera::GetUpVector() const\n{\n\treturn mUp;\n}\n\nbool Camera::IsActive() const\n{\n\treturn mActive;\n}\n\nvoid Camera::SetActive(bool active)\n{\n\tmActive = active;\n}\n\nfloat Camera::GetFOV() const\n{\n\treturn mFOV;\n}\n\nvoid Camera::SetFOV(float fov)\n{\n\tmFOV = fov;\n\tUpdateProjectionMatrix();\n}\n\nbool Camera::GetAutoAspect() const\n{\n\treturn mAutoAspect;\n}\n\nvoid Camera::SetAutoAspect(bool autoAspect)\n{\n\tmAutoAspect = autoAspect;\n}\n\nfloat Camera::GetAspect() const\n{\n\treturn mAspect;\n}\n\nvoid Camera::SetAspect(float aspect)\n{\n\tmAspect = aspect;\n\tUpdateProjectionMatrix();\n}\n\nfloat Camera::GetNearClipDistance() const\n{\n\treturn mNear;\n}\n\nvoid Camera::SetNearClipDistance(float near)\n{\n\tmNear = near;\n\tUpdateProjectionMatrix();\n}\n\nfloat Camera::GetFarClipDistance() const\n{\n\treturn mFar;\n}\n\nvoid Camera::SetFarClipDistance(float far)\n{\n\tmFar = far;\n\tUpdateProjectionMatrix();\n}\n\nconst Mat4& Camera::GetProjectionMatrix() const\n{\n\treturn mProjection;\n}\n\nconst Mat4& Camera::GetViewMatrix() const\n{\n\treturn mView;\n}\n\nconst Frustum& Camera::GetFrustum() const\n{\n\treturn mFrustum;\n}\n\nvoid Camera::Render()\n{\n\tGetDevice()->GetRenderer()->set_matrix(MT_PROJECTION, mProjection);\n\tGetDevice()->GetRenderer()->set_matrix(MT_VIEW, mView);\n}\n\nvoid Camera::UpdateProjectionMatrix()\n{\n\tmProjection.build_projection_perspective_rh(mFOV, mAspect, mNear, mFar);\n}\n\nvoid Camera::UpdateViewMatrix()\n{\n\tmView.build_look_at_rh(mPosition, mPosition + mLookAt, mUp);\n}\n\nvoid Camera::UpdateFrustum()\n{\n\tmFrustum.from_matrix(mProjection * mView);\n}\n\n} \/\/ namespace crown\n\n<|endoftext|>"} {"text":"#include \n\nnamespace Refal2 {\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CError\n\nvoid CError::Reset()\n{\n\tResetSeverity();\n\tResetFileName();\n\tResetToken();\n\tResetMessage();\n}\n\nbool CError::IsSet() const\n{\n\treturn ( Severity() != ES_None && !Message().empty() );\n}\n\nvoid CError::ResetSeverity()\n{\n\tseverity = ES_None;\n\tresetCache();\n}\n\nvoid CError::SetSeverity( TErrorSeverity _severity )\n{\n\tassert( _severity != ES_None );\n\tseverity = _severity;\n\tresetCache();\n}\n\nvoid CError::ResetFileName()\n{\n\tfileName.clear();\n\tresetCache();\n}\n\nvoid CError::SetFileName( const std::string& _fileName )\n{\n\tassert( !_fileName.empty() );\n\tfileName = _fileName;\n\tresetCache();\n}\n\nvoid CError::ResetToken()\n{\n\ttoken.type = TT_None;\n\tresetCache();\n}\n\nvoid CError::SetTokenData( int line, int position,\n\tconst std::string& wrongText )\n{\n\ttoken.type = TT_Word;\n\ttoken.line = line;\n\ttoken.position = position;\n\ttoken.word = wrongText;\n}\n\nvoid CError::SetToken( const CToken& _token )\n{\n\tassert( !_token.IsNone() );\n\ttoken = _token;\n\tresetCache();\n}\n\nvoid CError::ResetMessage()\n{\n\tmessage.clear();\n\tresetCache();\n}\n\nvoid CError::SetMessage( const std::string& _message )\n{\n\tassert( !_message.empty() );\n\tmessage = _message;\n\tresetCache();\n}\n\nconst std::string& CError::UserMessage() const\n{\n\tif( userMessage.empty() ) {\n\t\tstd::ostringstream userMessageStream;\n\t\tif( !fileName.empty() ) {\n\t\t\tuserMessageStream << fileName << \":\";\n\t\t\tif( !token.IsNone() ) {\n\t\t\t\tuserMessageStream << token.line << \":\" << token.position << \":\";\n\t\t\t}\n\t\t\tuserMessageStream << \" \";\n\t\t} else {\n\t\t\tassert( token.IsNone() );\n\t\t}\n\t\tswitch( Severity() ) {\n\t\t\tcase ES_Warning:\n\t\t\t\tuserMessageStream << \"warning\";\n\t\t\t\tbreak;\n\t\t\tcase ES_Error:\n\t\t\t\tuserMessageStream << \"error\";\n\t\t\t\tbreak;\n\t\t\tcase ES_LinkError:\n\t\t\t\tuserMessageStream << \"link error\";\n\t\t\t\tbreak;\n\t\t\tcase ES_FatalError:\n\t\t\t\tuserMessageStream << \"fatal error\";\n\t\t\t\tbreak;\n\t\t\tcase ES_None:\n\t\t\tdefault:\n\t\t\t\tassert( false );\n\t\t\t\tbreak;\n\t\t}\n\t\tassert( !message.empty() );\n\t\tuserMessageStream << \": \" << message << \".\";\n\t\tuserMessage = userMessageStream.str();\n\t}\n\treturn userMessage;\n}\n\n\/\/-----------------------------------------------------------------------------\n\nCErrorsHelper::CErrorsHelper( IErrorHandler* errorHandler )\n{\n\tCError::Reset();\n\tReset();\n\tSetErrorHandler( errorHandler );\n}\n\nvoid CErrorsHelper::Reset()\n{\n\terrorHandler = nullptr;\n\terrorSeverity = ES_None;\n}\n\nvoid CErrorsHelper::SetErrorHandler( IErrorHandler* _errorHandler )\n{\n\terrorHandler = _errorHandler;\n}\n\nbool CErrorsHelper::HasErrors() const\n{\n\tswitch( ErrorSeverity() ) {\n\t\tcase ES_None:\n\t\tcase ES_Warning:\n\t\t\treturn false;\n\t\tcase ES_Error:\n\t\tcase ES_LinkError:\n\t\tcase ES_FatalError:\n\t\t\treturn true;\n\t}\n\tassert( false );\n\treturn false;\n}\n\nvoid CErrorsHelper::RaiseError( TErrorSeverity severity,\n\tconst std::string& message )\n{\n\tCError::SetSeverity( severity );\n\tCError::SetMessage( message );\n\traiseError();\n\tCError::ResetSeverity();\n\tCError::ResetMessage();\n}\n\nvoid CErrorsHelper::RaiseError( TErrorSeverity severity,\n\tconst std::string& message, const CToken& token )\n{\n\tCError::SetToken( token );\n\tRaiseError( severity, message );\n\tCError::ResetToken();\n}\n\nvoid CErrorsHelper::raiseError()\n{\n\tassert( errorHandler != nullptr );\n\tassert( CError::IsSet() );\n\tconst TErrorSeverity severities[] =\n\t\t{ ES_FatalError, ES_LinkError, ES_Error, ES_Warning, ES_None };\n\tfor( int i = 0; i < sizeof( severities ) \/ sizeof( TErrorSeverity ); i++ ) {\n\t\tif( severities[i] == CError::Severity()\n\t\t\t|| severities[i] == errorSeverity )\n\t\t{\n\t\t\terrorSeverity = severities[i];\n\t\t}\n\t}\n\terrorHandler->Error( *this );\n}\n\n\/\/-----------------------------------------------------------------------------\n\n} \/\/ end of namespace Refal2\nallow print error with position without filename (for stdin)#include \n\nnamespace Refal2 {\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CError\n\nvoid CError::Reset()\n{\n\tResetSeverity();\n\tResetFileName();\n\tResetToken();\n\tResetMessage();\n}\n\nbool CError::IsSet() const\n{\n\treturn ( Severity() != ES_None && !Message().empty() );\n}\n\nvoid CError::ResetSeverity()\n{\n\tseverity = ES_None;\n\tresetCache();\n}\n\nvoid CError::SetSeverity( TErrorSeverity _severity )\n{\n\tassert( _severity != ES_None );\n\tseverity = _severity;\n\tresetCache();\n}\n\nvoid CError::ResetFileName()\n{\n\tfileName.clear();\n\tresetCache();\n}\n\nvoid CError::SetFileName( const std::string& _fileName )\n{\n\tassert( !_fileName.empty() );\n\tfileName = _fileName;\n\tresetCache();\n}\n\nvoid CError::ResetToken()\n{\n\ttoken.type = TT_None;\n\tresetCache();\n}\n\nvoid CError::SetTokenData( int line, int position,\n\tconst std::string& wrongText )\n{\n\ttoken.type = TT_Word;\n\ttoken.line = line;\n\ttoken.position = position;\n\ttoken.word = wrongText;\n}\n\nvoid CError::SetToken( const CToken& _token )\n{\n\tassert( !_token.IsNone() );\n\ttoken = _token;\n\tresetCache();\n}\n\nvoid CError::ResetMessage()\n{\n\tmessage.clear();\n\tresetCache();\n}\n\nvoid CError::SetMessage( const std::string& _message )\n{\n\tassert( !_message.empty() );\n\tmessage = _message;\n\tresetCache();\n}\n\nconst std::string& CError::UserMessage() const\n{\n\tif( userMessage.empty() ) {\n\t\tstd::ostringstream userMessageStream;\n\t\tif( !fileName.empty() ) {\n\t\t\tuserMessageStream << fileName << \":\";\n\t\t}\n\t\tif( !token.IsNone() ) {\n\t\t\tuserMessageStream << token.line << \":\" << token.position << \":\";\n\t\t}\n\t\tif( !fileName.empty() || !token.IsNone() ) {\n\t\t\tuserMessageStream << \" \";\n\t\t}\n\t\tswitch( Severity() ) {\n\t\t\tcase ES_Warning:\n\t\t\t\tuserMessageStream << \"warning\";\n\t\t\t\tbreak;\n\t\t\tcase ES_Error:\n\t\t\t\tuserMessageStream << \"error\";\n\t\t\t\tbreak;\n\t\t\tcase ES_LinkError:\n\t\t\t\tuserMessageStream << \"link error\";\n\t\t\t\tbreak;\n\t\t\tcase ES_FatalError:\n\t\t\t\tuserMessageStream << \"fatal error\";\n\t\t\t\tbreak;\n\t\t\tcase ES_None:\n\t\t\tdefault:\n\t\t\t\tassert( false );\n\t\t\t\tbreak;\n\t\t}\n\t\tassert( !message.empty() );\n\t\tuserMessageStream << \": \" << message << \".\";\n\t\tuserMessage = userMessageStream.str();\n\t}\n\treturn userMessage;\n}\n\n\/\/-----------------------------------------------------------------------------\n\nCErrorsHelper::CErrorsHelper( IErrorHandler* errorHandler )\n{\n\tCError::Reset();\n\tReset();\n\tSetErrorHandler( errorHandler );\n}\n\nvoid CErrorsHelper::Reset()\n{\n\terrorHandler = nullptr;\n\terrorSeverity = ES_None;\n}\n\nvoid CErrorsHelper::SetErrorHandler( IErrorHandler* _errorHandler )\n{\n\terrorHandler = _errorHandler;\n}\n\nbool CErrorsHelper::HasErrors() const\n{\n\tswitch( ErrorSeverity() ) {\n\t\tcase ES_None:\n\t\tcase ES_Warning:\n\t\t\treturn false;\n\t\tcase ES_Error:\n\t\tcase ES_LinkError:\n\t\tcase ES_FatalError:\n\t\t\treturn true;\n\t}\n\tassert( false );\n\treturn false;\n}\n\nvoid CErrorsHelper::RaiseError( TErrorSeverity severity,\n\tconst std::string& message )\n{\n\tCError::SetSeverity( severity );\n\tCError::SetMessage( message );\n\traiseError();\n\tCError::ResetSeverity();\n\tCError::ResetMessage();\n}\n\nvoid CErrorsHelper::RaiseError( TErrorSeverity severity,\n\tconst std::string& message, const CToken& token )\n{\n\tCError::SetToken( token );\n\tRaiseError( severity, message );\n\tCError::ResetToken();\n}\n\nvoid CErrorsHelper::raiseError()\n{\n\tassert( errorHandler != nullptr );\n\tassert( CError::IsSet() );\n\tconst TErrorSeverity severities[] =\n\t\t{ ES_FatalError, ES_LinkError, ES_Error, ES_Warning, ES_None };\n\tfor( int i = 0; i < sizeof( severities ) \/ sizeof( TErrorSeverity ); i++ ) {\n\t\tif( severities[i] == CError::Severity()\n\t\t\t|| severities[i] == errorSeverity )\n\t\t{\n\t\t\terrorSeverity = severities[i];\n\t\t}\n\t}\n\terrorHandler->Error( *this );\n}\n\n\/\/-----------------------------------------------------------------------------\n\n} \/\/ end of namespace Refal2\n<|endoftext|>"} {"text":"\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013 rajendrauppal\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#include \n\n#include \"Exceptions.h\"\n#include \"GcdLcm.h\"\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\n\nint GcdLcm::GCD_Euclidean_Iterative(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\twhile ( n ) {\n\t\tint temp = n;\n\t\tn = m % n;\n\t\tm = temp;\n\t}\n\n\treturn m;\n}\n\nint GcdLcm::GCD_Euclidean_Recursive(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\treturn GCD_Euclidean_Recursive(n, m % n);\n}\n\nint GcdLcm::GCD_AlternateEuclidean_Iterative(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\twhile ( m != n ) {\n\t\tif ( m > n )\n\t\t\tm = m - n;\n\t\telse\n\t\t\tn = n - m;\n\t}\n\n\treturn m;\n}\n\nint GcdLcm::GCD_AlternateEuclidean_Recursive(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\tif ( m == n ) return m;\n\tif ( m > n )\n\t\treturn GCD_AlternateEuclidean_Recursive(m - n, n);\n\telse\n\t\treturn GCD_AlternateEuclidean_Recursive(m, n - m);\n}\n\nint GcdLcm::GCD_Binary_Iterative(int m, int n)\n{\n\treturn 0;\n}\n\nint GcdLcm::GCD_Binary_Recursive(int m, int n)\n{\n\treturn 0;\n}\n\nint GcdLcm::LCM_Iterative(int m, int n)\n{\n\treturn 0;\n}\n\nint GcdLcm::LCM_Recursive(int m, int n)\n{\n\treturn 0;\n}\n\nint GcdLcm::GCD_UsingLCM(int m, int n)\n{\n\treturn 0;\n}\n\n\nint main()\n{\n\tGcdLcm gcdlcm;\n\tint nums[13][2] = {{0,1}, {1,0}, {0,0}, {1,1}, {-1,1}, {1,-1}, {-1,-1}, {1,1}, {2,3}, {10,10}, {121,11}, {24,60}, {36253652,183728732}};\n\tfor ( size_t i = 0; i < 13; ++i ) {\n\t\ttry \n\t\t{\n\t\t\tcout << gcdlcm.GCD_Euclidean_Iterative(nums[i][0], nums[i][1]) << endl;\n\t\t\tcout << gcdlcm.GCD_Euclidean_Recursive(nums[i][0], nums[i][1]) << endl;\n\n\t\t\tcout << gcdlcm.GCD_AlternateEuclidean_Iterative(nums[i][0], nums[i][1]) << endl;\n\t\t\tcout << gcdlcm.GCD_AlternateEuclidean_Recursive(nums[i][0], nums[i][1]) << endl<Implemented Binary GCD algorithm\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013 rajendrauppal\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#include \n\n#include \"Exceptions.h\"\n#include \"GcdLcm.h\"\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\n\nint GcdLcm::GCD_Euclidean_Iterative(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\twhile ( n ) {\n\t\tint temp = n;\n\t\tn = m % n;\n\t\tm = temp;\n\t}\n\n\treturn m;\n}\n\nint GcdLcm::GCD_Euclidean_Recursive(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\treturn GCD_Euclidean_Recursive(n, m % n);\n}\n\nint GcdLcm::GCD_AlternateEuclidean_Iterative(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\twhile ( m != n ) {\n\t\tif ( m > n )\n\t\t\tm = m - n;\n\t\telse\n\t\t\tn = n - m;\n\t}\n\n\treturn m;\n}\n\nint GcdLcm::GCD_AlternateEuclidean_Recursive(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\tif ( m == n ) return m;\n\tif ( m > n )\n\t\treturn GCD_AlternateEuclidean_Recursive(m - n, n);\n\telse\n\t\treturn GCD_AlternateEuclidean_Recursive(m, n - m);\n}\n\nint GcdLcm::GCD_Binary_Iterative(int m, int n)\n{\n\treturn 0;\n}\n\n\/* Binary GCD algorithm (Credit: en.wikipedia.org\/wiki\/Binary_GCD_algorithm)\n-----------------------------------------------\nm\t\tn\t\tgcd\n-----------------------------------------------\neven\teven\t2 * gcd( m\/2, n\/2 )\neven\todd\t\tgcd( m\/2, n )\nodd\t\teven\tgcd( m, n\/2 )\nodd\t\todd\t\tm >= n then gcd( (m - n)\/2, n )\n\t\t\t\tm < n then gcd( (n - m)\/2, m )\n-----------------------------------------------\n*\/\nint GcdLcm::GCD_Binary_Recursive(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\n\tif ( m == n ) return m;\n\n\tbool m_even = ~m & 1;\n\tbool n_even = ~n & 1;\n\t\n\tif ( m_even && n_even ) \n\t\treturn GCD_Binary_Recursive( m >> 1, n >> 1 ) << 1;\n\n\tif ( m_even && !n_even ) \n\t\treturn GCD_Binary_Recursive( m >> 1, n );\n\n\tif ( !m_even && n_even ) \n\t\treturn GCD_Binary_Recursive( m, n >> 1 );\n\n\tif ( m >= n ) \n\t\treturn GCD_Binary_Recursive( (m - n) >> 1, n );\n\telse \n\t\treturn GCD_Binary_Recursive( (n - m) >> 1, m );\n}\n\nint GcdLcm::LCM_Iterative(int m, int n)\n{\n\treturn 0;\n}\n\nint GcdLcm::LCM_Recursive(int m, int n)\n{\n\treturn 0;\n}\n\nint GcdLcm::GCD_UsingLCM(int m, int n)\n{\n\treturn 0;\n}\n\n\nint main()\n{\n\tGcdLcm gcdlcm;\n\tint nums[13][2] = {{0,1}, {1,0}, {0,0}, {1,1}, {-1,1}, {1,-1}, {-1,-1}, {1,1}, {2,3}, {10,10}, {121,11}, {24,60}, {36253652,183728732}};\n\tfor ( size_t i = 0; i < 13; ++i ) {\n\t\ttry \n\t\t{\n\t\t\tcout << gcdlcm.GCD_Euclidean_Iterative(nums[i][0], nums[i][1]) << endl;\n\t\t\tcout << gcdlcm.GCD_Euclidean_Recursive(nums[i][0], nums[i][1]) << endl;\n\n\t\t\tcout << gcdlcm.GCD_AlternateEuclidean_Iterative(nums[i][0], nums[i][1]) << endl;\n\t\t\tcout << gcdlcm.GCD_AlternateEuclidean_Recursive(nums[i][0], nums[i][1]) << endl;\n\n\t\t\tcout << gcdlcm.GCD_Binary_Recursive(nums[i][0], nums[i][1]) << endl;\n\t\t} \n\t\tcatch (CPPExceptions& e) \n\t\t{\n\t\t\tcout << e.message() << endl;\n\t\t}\n\t}\n\n\tcout << \"Press Enter to continue...\" << endl;\n\tcin.get();\n\treturn 0;\n}<|endoftext|>"} {"text":"#include \"GrsApi.h\"\n#include \"amount.h\"\n#include \"chainparams.h\"\n#include \"main.h\"\n#include \"util.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"json\/json_spirit_value.h\"\n#include \"json\/json_spirit_reader_template.h\"\n\n#include \n\nCGrsApi::CGrsApi(const std::string& baseUrl)\n : baseApiUrl(baseUrl)\n{\n curlpp::initialize();\n}\n\nCGrsApi::~CGrsApi()\n{\n curlpp::terminate();\n}\n\n\nCAmount CGrsApi::GetPrice(unsigned int time)\n{\n LogPrintf(\"CGrsApi::GetPrice: time = %d\\n\", time);\n\n \/\/ projected prices for before-the-trading era\n\n if (time >= block_0_t && time < block_128002_t) {\n \/\/ genesis reward zone\n return 656 * USD1 + 35 * USCENT1;\n } else if (time >= block_128002_t && time < block_193536_t) {\n \/\/ decreasing reward zone\n return 10 * USCENT1;\n } else if (time >= block_193536_t && time < Params().LiveFeedSwitchTime()) {\n return 10 * USCENT1;\n }\n\n \/\/ TODO(dmc): check cached price\n\n\n \/\/ get price from the live feed\n while (true) { \/\/TODO(dmc): !!!\n try {\n boost::this_thread::interruption_point();\n unsigned int timestamp = 0; \/\/TODO(dmc): must be 'time'\n CAmount price = GetGrsApiPrice(timestamp);\n LogPrintf(\"GRS price for timestamp: time = %d, price = %d\\n\", time, price);\n return price;\n } catch (const std::runtime_error& e) {\n error(\"Can't get GRS price for timestamp: %s\\n\", e.what());\n } catch (const boost::thread_interrupted& e) {\n LogPrintf(\"CGrsApi::GetPrice thread terminated\\n\");\n throw;\n }\n }\n}\n\nCAmount CGrsApi::GetLatestPrice()\n{\n return 10 * USCENT1; \/\/ STUB: 0.1USD, TODO(dmc): get actual coin price\n}\n\nCAmount CGrsApi::GetGrsApiPrice(unsigned int timestamp)\n{\n LogPrintf(\"Getting GRS price for timestamp: time = %d\\n\", timestamp);\n std::ostringstream reqArgs;\n if (timestamp != 0) {\n reqArgs << timestamp;\n }\n return DoApiPriceRequest(\"price\", reqArgs.str());\n}\n\nCAmount CGrsApi::DoApiPriceRequest(const std::string& reqName,\n const std::string& args)\n{\n CAmount price = 0;\n int apiResponseCode = 200;\n\n std::ostringstream apiUrl;\n apiUrl << baseApiUrl << reqName << \"\/\" << args;\n\n std::ostringstream rawResponse;\n try {\n apiResponseCode = DoApiRequest(apiUrl.str(), rawResponse);\n std::clog << \"GRS API response: \" << rawResponse.str() << std::endl;\n } catch (const curlpp::RuntimeError& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n } catch (const curlpp::LogicError& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n } catch (const std::invalid_argument& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n } catch (const std::domain_error& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n }\n\n if (apiResponseCode != 200) {\n std::ostringstream oss;\n oss << \"apiResponseCode != 200; code = \"\n << apiResponseCode\n << \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\";\n throw std::runtime_error(oss.str());\n }\n\n try {\n json_spirit::Value value;\n json_spirit::read_string(rawResponse.str(), value);\n json_spirit::Object obj(value.get_obj());\n\n bool price_read = false;\n for(json_spirit::Object::size_type i = 0; i != obj.size(); ++i) {\n const json_spirit::Pair& pair = obj[i];\n if (pair.name_ == \"price\") {\n price = pair.value_.get_int();\n price_read = true;\n }\n }\n if (!price_read) {\n throw std::domain_error(\"No price field found\");\n }\n } catch (const std::invalid_argument& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n } catch (const std::domain_error& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n }\n\n return price;\n}\n\nint CGrsApi::DoApiRequest(const std::string& url, std::ostringstream& oss)\n{\n LogPrintf(\"CGrsApi::DoApiRequest: url=%s, oss.str()=%s\\n\", url, oss.str());\n \/\/ std::clog << \"GRS API url: \" << url << std::endl;\n\n curlpp::options::Url reqUrl(url);\n curlpp::Easy request;\n request.setOpt(curlpp::options::NoSignal(false));\n request.setOpt(reqUrl);\n\n curlpp::options::WriteStream ws(&oss);\n request.setOpt(ws);\n request.perform();\n\n return curlpp::infos::ResponseCode::get(request);\n}\n\n\nCDmcSystem::CDmcSystem(const std::string& apiUrl)\n : grsApi(apiUrl)\n{\n genesisReward = 65535 * COIN;\n minReward = 1 * COIN;\n maxReward = 100000 * COIN;\n minTargetPrice = 1 * USD1 + 1 * USCENT1; \/\/ 1.01USD\n}\n\nbool CDmcSystem::CheckBlockReward(const CBlock& block, CAmount nFees, CValidationState& state, CBlockIndex* pindex)\n{\n LogPrintf(\"CDmcSystem::CheckBlockReward: block.nTime=%d, fees=%d, hash=%s, height=%d, time=%d\\n\", block.nTime, nFees, pindex->phashBlock ? pindex->GetBlockHash().ToString() : \"null\", pindex->nHeight, pindex->nTime);\n\n CAmount blockOutput = block.vtx[0].GetValueOut();\n if (!blockOutput || blockOutput <= nFees) {\n return state.DoS(100,\n error(\"CDmcSystem::CheckBlockReward() : coinbase pays zero or <= fees (coinbase=%d, fees=%d)\",\n blockOutput, nFees),\n REJECT_INVALID, \"bad-cb-amount\");\n }\n CAmount blockReward = blockOutput - nFees;\n\n \/\/TODO(dmc): temporary simplification – one GetBlockReward result comparison check\n \/\/ should be enough in the future (the second case of \"if\" construction)\n if (pindex->nTime > Params().LiveFeedSwitchTime()) {\n \/\/ simplified reward checks\n CAmount prevReward = pindex->pprev ? pindex->pprev->nReward : genesisReward;\n CAmount rewDiff = std::abs(blockReward - prevReward);\n if ((rewDiff == 0 || rewDiff == 1 * COIN) &&\n (blockReward >= minReward && blockReward <= maxReward)) {\n return true;\n }\n return state.DoS(100,\n error(\"CDmcSystem::CheckBlockReward() : coinbase pays wrong (actual=%d vs mustbe=%d)\",\n blockOutput, GetBlockReward(pindex) + nFees),\n REJECT_INVALID, \"bad-cb-amount\");\n }\n\n if (blockReward != GetBlockReward(pindex)) {\n return state.DoS(100,\n error(\"CDmcSystem::CheckBlockReward() : coinbase pays wrong reward (actual=%d vs mustbe=%d, fees=%d)\",\n blockReward, GetBlockReward(pindex), nFees),\n REJECT_INVALID, \"bad-cb-amount\");\n }\n return true;\n}\n\nCAmount CDmcSystem::GetBlockReward(const CBlockIndex* pindex)\n{\n LogPrintf(\"CDmcSystem::GetBlockReward: hash=%s, height=%d, time=%d\\n\", pindex->phashBlock ? pindex->GetBlockHash().ToString() : \"null\", pindex->nHeight, pindex->nTime);\n\n CAmount nSubsidy = 1 * COIN;\n\n int nHeight = pindex->nHeight;\n\n if (pindex->nTime > Params().LiveFeedSwitchTime()) {\n CAmount prevReward = pindex->pprev ? pindex->pprev->nReward : genesisReward;\n CAmount reward = prevReward;\n unsigned int price = GetPrice(pindex->nTime);\n CAmount target = GetTargetPrice(prevReward);\n\n if (price < target) {\n reward -= 1 * COIN;\n } else if (price > target) {\n reward += 1 * COIN;\n }\n nSubsidy = std::max(minReward, std::min(reward, maxReward));\n } else {\n if (Params().NetworkID() == CBaseChainParams::MAIN) {\n const int kGenesisRewardZone = 128000;\n const int kGenesisReward = 65535;\n const int kDecreasingRewardZone = kGenesisRewardZone + 1 + kGenesisReward;\n\n if (nHeight >= 0 && nHeight <= kGenesisRewardZone) {\n nSubsidy = kGenesisReward * COIN;\n } else if (nHeight > kGenesisRewardZone && nHeight < kDecreasingRewardZone) {\n nSubsidy = (kDecreasingRewardZone - nHeight) * COIN;\n }\n } else {\n nSubsidy = 1024 * COIN;\n }\n }\n\n return nSubsidy;\n}\n\nCAmount CDmcSystem::GetBlockRewardForNewTip(unsigned int time)\n{\n LogPrintf(\"CDmcSystem::GetBlockRewardForNewTip: time=%d\\n\", time);\n const CBlockIndex* tip = chainActive.Tip();\n\n if (!tip) {\n return genesisReward;\n }\n\n CAmount nSubsidy = 1 * COIN;\n\n int nHeight = tip->nHeight + 1;\n\n if (tip->nTime > Params().LiveFeedSwitchTime()) {\n CAmount prevReward = tip->nReward;\n CAmount reward = prevReward;\n unsigned int price = GetPrice(time);\n CAmount target = GetTargetPrice(prevReward);\n\n if (price < target) {\n reward -= 1 * COIN;\n } else if (price > target) {\n reward += 1 * COIN;\n }\n nSubsidy = std::max(minReward, std::min(reward, maxReward));\n } else {\n if (Params().NetworkID() == CBaseChainParams::MAIN) {\n const int kGenesisRewardZone = 128000;\n const int kGenesisReward = 65535;\n const int kDecreasingRewardZone = kGenesisRewardZone + 1 + kGenesisReward;\n\n if (nHeight >= 0 && nHeight <= kGenesisRewardZone) {\n nSubsidy = kGenesisReward * COIN;\n } else if (nHeight > kGenesisRewardZone && nHeight < kDecreasingRewardZone) {\n nSubsidy = (kDecreasingRewardZone - nHeight) * COIN;\n }\n } else {\n nSubsidy = 1024 * COIN;\n }\n }\n\n LogPrintf(\"CDmcSystem::GetBlockRewardForNewTip: time=%d, nSubsidy=%d\\n\", time, nSubsidy);\n return nSubsidy;\n}\n\n\nCAmount CDmcSystem::GetBlockReward() const\n{\n LOCK(cs_main);\n return chainActive.Tip()->nReward;\n}\n\nCAmount CDmcSystem::GetPrice()\n{\n LOCK(cs_main);\n return grsApi.GetPrice(chainActive.Tip()->nTime);\n}\n\nCAmount CDmcSystem::GetTargetPrice() const\n{\n LOCK(cs_main);\n return GetTargetPrice(chainActive.Tip()->nReward);\n}\n\nCAmount CDmcSystem::GetTotalCoins() const\n{\n LOCK(cs_main);\n return chainActive.Tip()->nChainReward;\n}\n\nCAmount CDmcSystem::GetMarketCap()\n{\n return (GetTotalCoins() \/ COIN) * GetPrice();\n}\n\n\nCAmount CDmcSystem::GetPrice(unsigned int time)\n{\n return grsApi.GetPrice(time);\n}\n\nCAmount CDmcSystem::GetTargetPrice(unsigned int time) const\n{\n \/\/TODO(dmc): temporary simplification\n\/\/ const CBlockIndex* pindex; \/\/ TODO(dmc): get block for time\n\/\/ return GetTargetPrice(pindex->nReward);\n return 10 * USCENT1;\n}\n\n\nCAmount CDmcSystem::GetTargetPrice(CAmount reward) const\n{\n CAmount targetPrice = 1 * USD1 + (reward * USD1) \/ (100 * COIN);\n\n return std::max(minTargetPrice, targetPrice);\n}\nRaise max block reward#include \"GrsApi.h\"\n#include \"amount.h\"\n#include \"chainparams.h\"\n#include \"main.h\"\n#include \"util.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"json\/json_spirit_value.h\"\n#include \"json\/json_spirit_reader_template.h\"\n\n#include \n\nCGrsApi::CGrsApi(const std::string& baseUrl)\n : baseApiUrl(baseUrl)\n{\n curlpp::initialize();\n}\n\nCGrsApi::~CGrsApi()\n{\n curlpp::terminate();\n}\n\n\nCAmount CGrsApi::GetPrice(unsigned int time)\n{\n LogPrintf(\"CGrsApi::GetPrice: time = %d\\n\", time);\n\n \/\/ projected prices for before-the-trading era\n\n if (time >= block_0_t && time < block_128002_t) {\n \/\/ genesis reward zone\n return 656 * USD1 + 35 * USCENT1;\n } else if (time >= block_128002_t && time < block_193536_t) {\n \/\/ decreasing reward zone\n return 10 * USCENT1;\n } else if (time >= block_193536_t && time < Params().LiveFeedSwitchTime()) {\n return 10 * USCENT1;\n }\n\n \/\/ TODO(dmc): check cached price\n\n\n \/\/ get price from the live feed\n while (true) { \/\/TODO(dmc): !!!\n try {\n boost::this_thread::interruption_point();\n unsigned int timestamp = 0; \/\/TODO(dmc): must be 'time'\n CAmount price = GetGrsApiPrice(timestamp);\n LogPrintf(\"GRS price for timestamp: time = %d, price = %d\\n\", time, price);\n return price;\n } catch (const std::runtime_error& e) {\n error(\"Can't get GRS price for timestamp: %s\\n\", e.what());\n } catch (const boost::thread_interrupted& e) {\n LogPrintf(\"CGrsApi::GetPrice thread terminated\\n\");\n throw;\n }\n }\n}\n\nCAmount CGrsApi::GetLatestPrice()\n{\n return 10 * USCENT1; \/\/ STUB: 0.1USD, TODO(dmc): get actual coin price\n}\n\nCAmount CGrsApi::GetGrsApiPrice(unsigned int timestamp)\n{\n LogPrintf(\"Getting GRS price for timestamp: time = %d\\n\", timestamp);\n std::ostringstream reqArgs;\n if (timestamp != 0) {\n reqArgs << timestamp;\n }\n return DoApiPriceRequest(\"price\", reqArgs.str());\n}\n\nCAmount CGrsApi::DoApiPriceRequest(const std::string& reqName,\n const std::string& args)\n{\n CAmount price = 0;\n int apiResponseCode = 200;\n\n std::ostringstream apiUrl;\n apiUrl << baseApiUrl << reqName << \"\/\" << args;\n\n std::ostringstream rawResponse;\n try {\n apiResponseCode = DoApiRequest(apiUrl.str(), rawResponse);\n std::clog << \"GRS API response: \" << rawResponse.str() << std::endl;\n } catch (const curlpp::RuntimeError& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n } catch (const curlpp::LogicError& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n } catch (const std::invalid_argument& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n } catch (const std::domain_error& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n }\n\n if (apiResponseCode != 200) {\n std::ostringstream oss;\n oss << \"apiResponseCode != 200; code = \"\n << apiResponseCode\n << \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\";\n throw std::runtime_error(oss.str());\n }\n\n try {\n json_spirit::Value value;\n json_spirit::read_string(rawResponse.str(), value);\n json_spirit::Object obj(value.get_obj());\n\n bool price_read = false;\n for(json_spirit::Object::size_type i = 0; i != obj.size(); ++i) {\n const json_spirit::Pair& pair = obj[i];\n if (pair.name_ == \"price\") {\n price = pair.value_.get_int();\n price_read = true;\n }\n }\n if (!price_read) {\n throw std::domain_error(\"No price field found\");\n }\n } catch (const std::invalid_argument& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n } catch (const std::domain_error& e) {\n throw std::runtime_error(std::string(e.what())\n + \"; url = '\" + apiUrl.str() + \"'\"\n + \"; response = '\" + rawResponse.str() + \"'\");\n }\n\n return price;\n}\n\nint CGrsApi::DoApiRequest(const std::string& url, std::ostringstream& oss)\n{\n LogPrintf(\"CGrsApi::DoApiRequest: url=%s, oss.str()=%s\\n\", url, oss.str());\n \/\/ std::clog << \"GRS API url: \" << url << std::endl;\n\n curlpp::options::Url reqUrl(url);\n curlpp::Easy request;\n request.setOpt(curlpp::options::NoSignal(false));\n request.setOpt(reqUrl);\n\n curlpp::options::WriteStream ws(&oss);\n request.setOpt(ws);\n request.perform();\n\n return curlpp::infos::ResponseCode::get(request);\n}\n\n\nCDmcSystem::CDmcSystem(const std::string& apiUrl)\n : grsApi(apiUrl)\n{\n genesisReward = 65535 * COIN;\n minReward = 1 * COIN;\n maxReward = 1000000 * COIN;\n minTargetPrice = 1 * USD1 + 1 * USCENT1; \/\/ 1.01USD\n}\n\nbool CDmcSystem::CheckBlockReward(const CBlock& block, CAmount nFees, CValidationState& state, CBlockIndex* pindex)\n{\n LogPrintf(\"CDmcSystem::CheckBlockReward: block.nTime=%d, fees=%d, hash=%s, height=%d, time=%d\\n\", block.nTime, nFees, pindex->phashBlock ? pindex->GetBlockHash().ToString() : \"null\", pindex->nHeight, pindex->nTime);\n\n CAmount blockOutput = block.vtx[0].GetValueOut();\n if (!blockOutput || blockOutput <= nFees) {\n return state.DoS(100,\n error(\"CDmcSystem::CheckBlockReward() : coinbase pays zero or <= fees (coinbase=%d, fees=%d)\",\n blockOutput, nFees),\n REJECT_INVALID, \"bad-cb-amount\");\n }\n CAmount blockReward = blockOutput - nFees;\n\n \/\/TODO(dmc): temporary simplification – one GetBlockReward result comparison check\n \/\/ should be enough in the future (the second case of \"if\" construction)\n if (pindex->nTime > Params().LiveFeedSwitchTime()) {\n \/\/ simplified reward checks\n CAmount prevReward = pindex->pprev ? pindex->pprev->nReward : genesisReward;\n CAmount rewDiff = std::abs(blockReward - prevReward);\n if ((rewDiff == 0 || rewDiff == 1 * COIN) &&\n (blockReward >= minReward && blockReward <= maxReward)) {\n return true;\n }\n return state.DoS(100,\n error(\"CDmcSystem::CheckBlockReward() : coinbase pays wrong (actual=%d vs mustbe=%d)\",\n blockOutput, GetBlockReward(pindex) + nFees),\n REJECT_INVALID, \"bad-cb-amount\");\n }\n\n if (blockReward != GetBlockReward(pindex)) {\n return state.DoS(100,\n error(\"CDmcSystem::CheckBlockReward() : coinbase pays wrong reward (actual=%d vs mustbe=%d, fees=%d)\",\n blockReward, GetBlockReward(pindex), nFees),\n REJECT_INVALID, \"bad-cb-amount\");\n }\n return true;\n}\n\nCAmount CDmcSystem::GetBlockReward(const CBlockIndex* pindex)\n{\n LogPrintf(\"CDmcSystem::GetBlockReward: hash=%s, height=%d, time=%d\\n\", pindex->phashBlock ? pindex->GetBlockHash().ToString() : \"null\", pindex->nHeight, pindex->nTime);\n\n CAmount nSubsidy = 1 * COIN;\n\n int nHeight = pindex->nHeight;\n\n if (pindex->nTime > Params().LiveFeedSwitchTime()) {\n CAmount prevReward = pindex->pprev ? pindex->pprev->nReward : genesisReward;\n CAmount reward = prevReward;\n unsigned int price = GetPrice(pindex->nTime);\n CAmount target = GetTargetPrice(prevReward);\n\n if (price < target) {\n reward -= 1 * COIN;\n } else if (price > target) {\n reward += 1 * COIN;\n }\n nSubsidy = std::max(minReward, std::min(reward, maxReward));\n } else {\n if (Params().NetworkID() == CBaseChainParams::MAIN) {\n const int kGenesisRewardZone = 128000;\n const int kGenesisReward = 65535;\n const int kDecreasingRewardZone = kGenesisRewardZone + 1 + kGenesisReward;\n\n if (nHeight >= 0 && nHeight <= kGenesisRewardZone) {\n nSubsidy = kGenesisReward * COIN;\n } else if (nHeight > kGenesisRewardZone && nHeight < kDecreasingRewardZone) {\n nSubsidy = (kDecreasingRewardZone - nHeight) * COIN;\n }\n } else {\n nSubsidy = 1024 * COIN;\n }\n }\n\n return nSubsidy;\n}\n\nCAmount CDmcSystem::GetBlockRewardForNewTip(unsigned int time)\n{\n LogPrintf(\"CDmcSystem::GetBlockRewardForNewTip: time=%d\\n\", time);\n const CBlockIndex* tip = chainActive.Tip();\n\n if (!tip) {\n return genesisReward;\n }\n\n CAmount nSubsidy = 1 * COIN;\n\n int nHeight = tip->nHeight + 1;\n\n if (tip->nTime > Params().LiveFeedSwitchTime()) {\n CAmount prevReward = tip->nReward;\n CAmount reward = prevReward;\n unsigned int price = GetPrice(time);\n CAmount target = GetTargetPrice(prevReward);\n\n if (price < target) {\n reward -= 1 * COIN;\n } else if (price > target) {\n reward += 1 * COIN;\n }\n nSubsidy = std::max(minReward, std::min(reward, maxReward));\n } else {\n if (Params().NetworkID() == CBaseChainParams::MAIN) {\n const int kGenesisRewardZone = 128000;\n const int kGenesisReward = 65535;\n const int kDecreasingRewardZone = kGenesisRewardZone + 1 + kGenesisReward;\n\n if (nHeight >= 0 && nHeight <= kGenesisRewardZone) {\n nSubsidy = kGenesisReward * COIN;\n } else if (nHeight > kGenesisRewardZone && nHeight < kDecreasingRewardZone) {\n nSubsidy = (kDecreasingRewardZone - nHeight) * COIN;\n }\n } else {\n nSubsidy = 1024 * COIN;\n }\n }\n\n LogPrintf(\"CDmcSystem::GetBlockRewardForNewTip: time=%d, nSubsidy=%d\\n\", time, nSubsidy);\n return nSubsidy;\n}\n\n\nCAmount CDmcSystem::GetBlockReward() const\n{\n LOCK(cs_main);\n return chainActive.Tip()->nReward;\n}\n\nCAmount CDmcSystem::GetPrice()\n{\n LOCK(cs_main);\n return grsApi.GetPrice(chainActive.Tip()->nTime);\n}\n\nCAmount CDmcSystem::GetTargetPrice() const\n{\n LOCK(cs_main);\n return GetTargetPrice(chainActive.Tip()->nReward);\n}\n\nCAmount CDmcSystem::GetTotalCoins() const\n{\n LOCK(cs_main);\n return chainActive.Tip()->nChainReward;\n}\n\nCAmount CDmcSystem::GetMarketCap()\n{\n return (GetTotalCoins() \/ COIN) * GetPrice();\n}\n\n\nCAmount CDmcSystem::GetPrice(unsigned int time)\n{\n return grsApi.GetPrice(time);\n}\n\nCAmount CDmcSystem::GetTargetPrice(unsigned int time) const\n{\n \/\/TODO(dmc): temporary simplification\n\/\/ const CBlockIndex* pindex; \/\/ TODO(dmc): get block for time\n\/\/ return GetTargetPrice(pindex->nReward);\n return 10 * USCENT1;\n}\n\n\nCAmount CDmcSystem::GetTargetPrice(CAmount reward) const\n{\n CAmount targetPrice = 1 * USD1 + (reward * USD1) \/ (100 * COIN);\n\n return std::max(minTargetPrice, targetPrice);\n}\n<|endoftext|>"} {"text":"#include \"InGame.h\"\n#include \n\nInGame::InGame(Configuration& newConfig, std::unique_ptr startInfo) :\n\tconfig(newConfig)\n{\n\tloadGame(startInfo);\n}\n\nInGame::~InGame()\n{\n\tdelete interfacePtr;\n\tdelete networkPtr;\n\tdelete systemPtr;\n}\n\nvoid InGame::run()\n{\n\tsf::RenderWindow& window = config.window;\n\twindow.setFramerateLimit(60);\n\n\twhile (window.isOpen())\n\t{\n\t\t\/\/input & update phase\n\t\tsystemPtr->updateQuadTree();\n\t\tnetworkPtr->update();\n\n\t\tsf::Event event;\n\t\twhile (window.pollEvent(event))\n\t\t{\n\t\t\tif (event.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\n\t\t\tif (event.type == sf::Event::KeyPressed)\n\t\t\t{\n\t\t\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))\n\t\t\t\t\tsystemPtr->interact();\n\t\t\t}\n\n\t\t\tinterfacePtr->updateGUI(event);\n\t\t}\n\n\t\t\/\/handle keyboard input, move character, interact...etc\n\t\thandleKeyboardInput();\n\n\t\t\/\/if this is server, send status update to client\n\t\tif (networkPtr->isServer())\n\t\t{\n\t\t\tserver_sendUpdate();\n\t\t}\n\t\telse \/\/if this is client, send status update to server\n\t\t{\n\t\t\tclient_sendUpdate();\n\t\t}\n\n\t\tconfig.cursor.update();\n\n\t\t\/\/rendering phase\n\t\twindow.clear();\n\t\tinterfacePtr->draw();\n\t\t\/\/window.draw(config.cursor);\n\t\twindow.display();\n\t}\n}\n\nvoid InGame::loadGame(std::unique_ptr& startInfo)\n{\n\t\/\/graphics in loading screen\n\tsf::RenderWindow& window = config.window;\n\ttgui::Gui gui;\n\tgui.setWindow(window);\n\n\tgui.setFont(tgui::Font(config.fontMan.get(\"Carlito-Bold.ttf\")));\n\n\ttgui::Picture::Ptr background = std::make_shared();\n\tbackground->setTexture(config.texMan.get(\"Book.png\"));\n\tbackground->setSize(gui.getSize());\n\tgui.add(background);\n\n\ttgui::ProgressBar::Ptr progressBar = std::make_shared();\n\tgui.add(progressBar);\n\tprogressBar->setPosition(50, 700);\n\tprogressBar->setSize(930, 20);\n\tprogressBar->setMinimum(0);\n\tprogressBar->setMaximum(100);\n\tprogressBar->setText(\"loading...0%\");\n\tunsigned int percent = 0;\n\n\ttgui::Panel::Ptr panel = std::make_shared();\n\tgui.add(panel);\n\tpanel->setSize(820, 200);\n\tpanel->setPosition(100, 450);\n\tpanel->setBackgroundColor(tgui::Color(192, 192, 192, 150));\n\n\ttgui::Label::Ptr tips = std::make_shared();\n\tpanel->add(tips);\n\ttips->setPosition(20, 20);\n\ttips->setTextSize(24);\n\ttips->setText(\"This is testing. Click cross button to leave.\");\n\t\n\t\/\/*************************************************************************\n\t\/\/the render loop\n\tbool loading_complete = false;\t\/\/leave the loop when loading completed\n\tConnection* temp_networkPtr = new Connection;\n\tif (!temp_networkPtr)\n\t{\n\t\tthrow \"Failed to create network module!\";\n\t}\n\n\twhile (window.isOpen() && !loading_complete)\n\t{\n\t\tsf::Event event;\n\t\twhile (window.pollEvent(event))\n\t\t{\n\t\t\tif (event.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\n\t\t\tgui.handleEvent(event);\n\t\t}\n\n\t\tconfig.cursor.update();\n\n\t\t\/\/if still loading, update percent\n\t\tif (percent < 0)\n\t\t{\n\t\t\tif (clock.getElapsedTime() > sf::seconds(0.05))\n\t\t\t{\n\t\t\t\tpercent++;\n\t\t\t\tstd::stringstream ss;\n\t\t\t\tss << percent;\n\t\t\t\tprogressBar->setText(sf::String(\"loading...\") + sf::String(ss.str()) + sf::String(\"%\"));\n\t\t\t\tprogressBar->setValue(percent);\n\t\t\t\tclock.restart();\n\t\t\t}\n\t\t}\n\t\telse\t\/\/else, client: send \"ready\" signal to server for every 5s; server: start anyway\n\t\t{\n\t\t\tprogressBar->setText(sf::String(\"waiting for server...\"));\n\t\t\tloading_complete = waitForStart(startInfo, temp_networkPtr);\n\t\t}\n\n\t\twindow.clear();\n\t\tgui.draw();\n\t\twindow.draw(config.cursor);\n\t\twindow.display();\n\t}\n\tdelete temp_networkPtr;\n\t\/\/*************************************************************************\n\t\/\/if it is server, start server system...\n\tif (startInfo->type == StartInfo::TYPE::Server)\n\t{\n\t\tsystemPtr = new Gameplay::ServerSystem(config, startInfo);\n\t}\n\telse \/\/else it is client, start client system\n\t{\n\t\tsystemPtr = new Gameplay::ClientSystem(config, startInfo);\n\t}\n\n\t\/\/create network and interface which is pointing to the game system\n\tnetworkPtr = new Gameplay::GameNetwork(systemPtr, startInfo);\n\n\tsystemPtr->setNetworkPtr(networkPtr);\n\n\tinterfacePtr = new Gameplay::GameInterface(systemPtr);\n\n\tsystemPtr->setInterfacePtr(interfacePtr);\n\n\tif (startInfo->type == StartInfo::TYPE::Server)\n\t{\n\t\t\/\/send ready signal to every player\n\t\t\/\/...\n\t}\n\telse \/\/if it is a client\n\t{\n\t\t\/\/wait for server's signal\n\t}\n}\n\nbool InGame::waitForStart(std::unique_ptr& startInfoPtr, Connection * connectionPtr)\n{\n\tif (startInfoPtr->type == StartInfo::TYPE::Server)\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\t\/\/if recevied somthing, if that's from server and the signal if \"start\", return true\n\t\tif (!connectionPtr->empty())\n\t\t{\n\t\t\tPackage& package = connectionPtr->front();\n\t\t\tstd::string signal;\n\t\t\tpackage.packet >> signal;\n\t\t\tif (package.ip == startInfoPtr->serverIP && signal == \"start\")\n\t\t\t{\n\t\t\t\tconnectionPtr->pop();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse \/\/else, send \"ready\" signal to server for every 2s\n\t\t{\n\t\t\tif (clock.getElapsedTime() > sf::seconds(2))\n\t\t\t{\n\t\t\t\tsf::Packet packet;\n\t\t\t\tpacket << \"ready\";\n\t\t\t\tconnectionPtr->send(startInfoPtr->serverIP, packet);\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid InGame::handleKeyboardInput()\n{\n\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left))\n\t{\n\t\tsystemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::left);\n\n sf::Packet packet;\n\t\tpacket << config.player_name;\n packet << \"move\";\n packet << \"left\";\n \n\t\tif (networkPtr->isServer())\n networkPtr->boardCast(packet);\n else\n networkPtr->send(networkPtr->getServerIP(), packet);\n\t}\n\telse if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right))\n\t{\n\t\tsystemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::right);\n\n sf::Packet packet;\n\t\tpacket << config.player_name;\n packet << \"move\";\n packet << \"right\";\n \n if (networkPtr->isServer())\n networkPtr->boardCast(packet);\n else\n networkPtr->send(networkPtr->getServerIP(), packet);\n\t}\n\telse if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down))\n\t{\n\t\tsystemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::down);\n sf::Packet packet;\n\t\tpacket << config.player_name;\n packet << \"move\";\n packet << \"down\";\n \n if (networkPtr->isServer())\n networkPtr->boardCast(packet);\n else\n networkPtr->send(networkPtr->getServerIP(), packet);\n\t}\n\telse if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up))\n\t{\n\t\tsystemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::up);\n\n sf::Packet packet;\n\t\tpacket << config.player_name;\n packet << \"move\";\n packet << \"up\";\n if (networkPtr->isServer())\n networkPtr->boardCast(packet);\n else\n networkPtr->send(networkPtr->getServerIP(), packet);\n\t}\n}\n\nvoid InGame::client_sendUpdate()\n{\n\tif (updateClock.getElapsedTime() > sf::seconds(2))\n\t{\n\t\t\/\/update the position\n\t\tsf::Packet packet;\n\t\tpacket << \"setPosition\";\n\t\tfloat x = systemPtr->getPlayerPosition().x;\n\t\tfloat y = systemPtr->getPlayerPosition().y;\n\t\tpacket << x << y;\n\t\tnetworkPtr->send(networkPtr->getServerIP(), packet);\n\t\tupdateClock.restart();\n\t}\n}\n\nvoid InGame::server_sendUpdate()\n{\n\n}\n\nmoving function 2#include \"InGame.h\"\n#include \n\nInGame::InGame(Configuration& newConfig, std::unique_ptr startInfo) :\n\tconfig(newConfig)\n{\n\tloadGame(startInfo);\n}\n\nInGame::~InGame()\n{\n\tdelete interfacePtr;\n\tdelete networkPtr;\n\tdelete systemPtr;\n}\n\nvoid InGame::run()\n{\n\tsf::RenderWindow& window = config.window;\n\twindow.setFramerateLimit(60);\n\n\twhile (window.isOpen())\n\t{\n\t\t\/\/input & update phase\n\t\tsystemPtr->updateQuadTree();\n\t\tnetworkPtr->update();\n\n\t\tsf::Event event;\n\t\twhile (window.pollEvent(event))\n\t\t{\n\t\t\tif (event.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\n\t\t\tif (event.type == sf::Event::KeyPressed)\n\t\t\t{\n\t\t\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))\n\t\t\t\t\tsystemPtr->interact();\n\t\t\t}\n\n\t\t\tinterfacePtr->updateGUI(event);\n\t\t}\n\n\t\t\/\/handle keyboard input, move character, interact...etc\n\t\thandleKeyboardInput();\n\n\t\t\/\/if this is server, send status update to client\n\t\tif (networkPtr->isServer())\n\t\t{\n\t\t\tserver_sendUpdate();\n\t\t}\n\t\telse \/\/if this is client, send status update to server\n\t\t{\n\t\t\tclient_sendUpdate();\n\t\t}\n\n\t\tconfig.cursor.update();\n\n\t\t\/\/rendering phase\n\t\twindow.clear();\n\t\tinterfacePtr->draw();\n\t\t\/\/window.draw(config.cursor);\n\t\twindow.display();\n\t}\n}\n\nvoid InGame::loadGame(std::unique_ptr& startInfo)\n{\n\t\/\/graphics in loading screen\n\tsf::RenderWindow& window = config.window;\n\ttgui::Gui gui;\n\tgui.setWindow(window);\n\n\tgui.setFont(tgui::Font(config.fontMan.get(\"Carlito-Bold.ttf\")));\n\n\ttgui::Picture::Ptr background = std::make_shared();\n\tbackground->setTexture(config.texMan.get(\"Book.png\"));\n\tbackground->setSize(gui.getSize());\n\tgui.add(background);\n\n\ttgui::ProgressBar::Ptr progressBar = std::make_shared();\n\tgui.add(progressBar);\n\tprogressBar->setPosition(50, 700);\n\tprogressBar->setSize(930, 20);\n\tprogressBar->setMinimum(0);\n\tprogressBar->setMaximum(100);\n\tprogressBar->setText(\"loading...0%\");\n\tunsigned int percent = 0;\n\n\ttgui::Panel::Ptr panel = std::make_shared();\n\tgui.add(panel);\n\tpanel->setSize(820, 200);\n\tpanel->setPosition(100, 450);\n\tpanel->setBackgroundColor(tgui::Color(192, 192, 192, 150));\n\n\ttgui::Label::Ptr tips = std::make_shared();\n\tpanel->add(tips);\n\ttips->setPosition(20, 20);\n\ttips->setTextSize(24);\n\ttips->setText(\"This is testing. Click cross button to leave.\");\n\t\n\t\/\/*************************************************************************\n\t\/\/the render loop\n\tbool loading_complete = false;\t\/\/leave the loop when loading completed\n\tConnection* temp_networkPtr = new Connection;\n\tif (!temp_networkPtr)\n\t{\n\t\tthrow \"Failed to create network module!\";\n\t}\n\n\twhile (window.isOpen() && !loading_complete)\n\t{\n\t\tsf::Event event;\n\t\twhile (window.pollEvent(event))\n\t\t{\n\t\t\tif (event.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\n\t\t\tgui.handleEvent(event);\n\t\t}\n\n\t\tconfig.cursor.update();\n\n\t\t\/\/if still loading, update percent\n\t\tif (percent < 0)\n\t\t{\n\t\t\tif (clock.getElapsedTime() > sf::seconds(0.05))\n\t\t\t{\n\t\t\t\tpercent++;\n\t\t\t\tstd::stringstream ss;\n\t\t\t\tss << percent;\n\t\t\t\tprogressBar->setText(sf::String(\"loading...\") + sf::String(ss.str()) + sf::String(\"%\"));\n\t\t\t\tprogressBar->setValue(percent);\n\t\t\t\tclock.restart();\n\t\t\t}\n\t\t}\n\t\telse\t\/\/else, client: send \"ready\" signal to server for every 5s; server: start anyway\n\t\t{\n\t\t\tprogressBar->setText(sf::String(\"waiting for server...\"));\n\t\t\tloading_complete = waitForStart(startInfo, temp_networkPtr);\n\t\t}\n\n\t\twindow.clear();\n\t\tgui.draw();\n\t\twindow.draw(config.cursor);\n\t\twindow.display();\n\t}\n\tdelete temp_networkPtr;\n\t\/\/*************************************************************************\n\t\/\/if it is server, start server system...\n\tif (startInfo->type == StartInfo::TYPE::Server)\n\t{\n\t\tsystemPtr = new Gameplay::ServerSystem(config, startInfo);\n\t}\n\telse \/\/else it is client, start client system\n\t{\n\t\tsystemPtr = new Gameplay::ClientSystem(config, startInfo);\n\t}\n\n\t\/\/create network and interface which is pointing to the game system\n\tnetworkPtr = new Gameplay::GameNetwork(systemPtr, startInfo);\n\n\tsystemPtr->setNetworkPtr(networkPtr);\n\n\tinterfacePtr = new Gameplay::GameInterface(systemPtr);\n\n\tsystemPtr->setInterfacePtr(interfacePtr);\n\n\tif (startInfo->type == StartInfo::TYPE::Server)\n\t{\n\t\t\/\/send ready signal to every player\n\t\t\/\/...\n\t}\n\telse \/\/if it is a client\n\t{\n\t\t\/\/wait for server's signal\n\t}\n}\n\nbool InGame::waitForStart(std::unique_ptr& startInfoPtr, Connection * connectionPtr)\n{\n\tif (startInfoPtr->type == StartInfo::TYPE::Server)\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\t\/\/if recevied somthing, if that's from server and the signal if \"start\", return true\n\t\tif (!connectionPtr->empty())\n\t\t{\n\t\t\tPackage& package = connectionPtr->front();\n\t\t\tstd::string signal;\n\t\t\tpackage.packet >> signal;\n\t\t\tif (package.ip == startInfoPtr->serverIP && signal == \"start\")\n\t\t\t{\n\t\t\t\tconnectionPtr->pop();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse \/\/else, send \"ready\" signal to server for every 2s\n\t\t{\n\t\t\tif (clock.getElapsedTime() > sf::seconds(2))\n\t\t\t{\n\t\t\t\tsf::Packet packet;\n\t\t\t\tpacket << \"ready\";\n\t\t\t\tconnectionPtr->send(startInfoPtr->serverIP, packet);\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid InGame::handleKeyboardInput()\n{\n\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left))\n\t{\n\t\tsystemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::left);\n\n sf::Packet packet;\n packet << \"move\";\n\t\tpacket << config.player_name;\n packet << \"left\";\n \n\t\tif (networkPtr->isServer())\n networkPtr->boardCast(packet);\n else\n networkPtr->send(networkPtr->getServerIP(), packet);\n\t}\n\telse if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right))\n\t{\n\t\tsystemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::right);\n\n sf::Packet packet;\n packet << \"move\";\n\t\tpacket << config.player_name;\n packet << \"right\";\n \n if (networkPtr->isServer())\n networkPtr->boardCast(packet);\n else\n networkPtr->send(networkPtr->getServerIP(), packet);\n\t}\n\telse if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down))\n\t{\n\t\tsystemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::down);\n sf::Packet packet;\n packet << \"move\";\n\t\tpacket << config.player_name;\n packet << \"down\";\n \n if (networkPtr->isServer())\n networkPtr->boardCast(packet);\n else\n networkPtr->send(networkPtr->getServerIP(), packet);\n\t}\n\telse if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up))\n\t{\n\t\tsystemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::up);\n\n sf::Packet packet;\n packet << \"move\";\n\t\tpacket << config.player_name;\n packet << \"up\";\n if (networkPtr->isServer())\n networkPtr->boardCast(packet);\n else\n networkPtr->send(networkPtr->getServerIP(), packet);\n\t}\n}\n\nvoid InGame::client_sendUpdate()\n{\n\tif (updateClock.getElapsedTime() > sf::seconds(2))\n\t{\n\t\t\/\/update the position\n\t\tsf::Packet packet;\n\t\tpacket << \"setPosition\";\n\t\tfloat x = systemPtr->getPlayerPosition().x;\n\t\tfloat y = systemPtr->getPlayerPosition().y;\n\t\tpacket << x << y;\n\t\tnetworkPtr->send(networkPtr->getServerIP(), packet);\n\t\tupdateClock.restart();\n\t}\n}\n\nvoid InGame::server_sendUpdate()\n{\n\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2014 Matteo Agostini \n\n\/\/ This 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\n\/\/ the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (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 library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n\/\/ c++ libs\n#include \n#include \n#include \n#include \n\n\/\/ ROOT libs\n#include \n\n\/\/ m-stats libs\n#include \"MSMath.h\"\n\nnamespace mst {\n\ndouble MSMath::LogGaus(double x, double mean, double sigma) {\n \/\/ sigma must be positive\n if (sigma <= 0.0) {\n std::cerr << \"MSMath::LogGaus >> error: sigma must be positive\\n\";\n return 0;\n }\n const double dx = (x - mean) \/ sigma;\n return -0.5*dx*dx - 0.5*log(2*M_PI) - log(sigma);\n}\n\ndouble MSMath::LogPoisson(double x, double lambda) {\n\n \/\/ If the parameters are negative the Poission probability is not defined\n if (lambda < 0.0 || x < 0.0) {\n std::cerr << \"MSMath::LogPoisson >> error: \"\n << \"function not defined for negative parameters\\n\";\n return std::numeric_limits::quiet_NaN();\n } \n\n \/\/ The expectation must be positive. Empty bins in the PSD should be avoided\n else if (lambda == 0.0) {\n if (x == 0) return 0;\n else return std::numeric_limits::quiet_NaN();\n }\n\n \/\/ Copute Poission probability for positive lambda values\n else {\n if (x == 0) return -lambda;\n else if (lambda < 899) return x*log(lambda)-lambda-TMath::LnGamma(x+1.);\n else return LogGaus(x, lambda, sqrt(lambda));\n }\n}\n\ndouble MSMath::LogExp (double x, double limit, double quantile, double offset) {\n \/\/ the expoential function should be normalized in the range [offset, inf] and\n \/\/ have the quantile corresponding to the desidered probablity at the limit\n \/\/ value.\n \/\/\n \/\/ Starting from the standard exp function normalized betweeen 0 and inf:\n \/\/\n \/\/ f(x) = a*exp(-a*x)\n \/\/\n \/\/ the parameter a is hence fixed by:\n \/\/\n \/\/ int _0 ^limit f(x) dx = quantile\n \/\/ => a = -ln(1-quantile)\/limit\n \/\/\n \/\/ and final the frame must be changed such that 0->offset\n \/\/\n \/\/ => a = -ln(1-quantile)\/(limit-offset)\n \/\/ f(x) = a * exp(-a* (x-offset))\n\n\n \/\/ Check that the quantile is in the range ]0,1[\n if (quantile <= 0.0 && quantile >= 1.0) { \n std::cerr << \"MSMath::Logexp >> error: \"\n << \"quantile must be >0 && <1\\n\";\n return std::numeric_limits::quiet_NaN();\n\n \/\/ Check that the limit is above the offset\n } else if (limit <= offset) {\n std::cerr << \"MSModelPullExp >> error: \"\n << \"the limit must be larger than the offset\\n\";\n return std::numeric_limits::quiet_NaN();\n\n \/\/ Check that the parameter is in the physical range\n } else if (x < offset) {\n std::cerr << \"MSMath::Logexp >> error: \"\n << \"parameter must be larger than the offset\\n\";\n return std::numeric_limits::quiet_NaN();\n\n \/\/ compute LogExp\n } else {\n const double a = -log(1.0-quantile)\/(limit-offset);\n return log(a)-a*(x-offset);\n }\n}\n}\nchanged returned values when the likelhood is not defined to push minuit away\/\/ Copyright (C) 2014 Matteo Agostini \n\n\/\/ This 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\n\/\/ the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (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 library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n\/\/ c++ libs\n#include \n#include \n#include \n#include \n\n\/\/ ROOT libs\n#include \n\n\/\/ m-stats libs\n#include \"MSMath.h\"\n\nnamespace mst {\n\ndouble MSMath::LogGaus(double x, double mean, double sigma) {\n \/\/ sigma must be positive\n if (sigma <= 0.0) {\n std::cerr << \"MSMath::LogGaus >> error: sigma must be positive\\n\";\n return 0;\n }\n const double dx = (x - mean) \/ sigma;\n return -0.5*dx*dx - 0.5*log(2*M_PI) - log(sigma);\n}\n\ndouble MSMath::LogPoisson(double x, double lambda) {\n\n \/\/ If the parameters are negative the Poission probability is not defined\n if (lambda < 0.0 || x < 0.0) {\n std::cerr << \"MSMath::LogPoisson >> error: \"\n << \"function not defined for negative parameters\\n\";\n return -std::numeric_limits::infinity();\n } \n\n \/\/ The expectation must be positive. Empty bins in the PSD should be avoided\n else if (lambda == 0.0) {\n if (x == 0) return 0;\n else return -std::numeric_limits::infinity();\n }\n\n \/\/ Copute Poission probability for positive lambda values\n else {\n if (x == 0) return -lambda;\n else if (lambda < 899) return x*log(lambda)-lambda-TMath::LnGamma(x+1.);\n else return LogGaus(x, lambda, sqrt(lambda));\n }\n}\n\ndouble MSMath::LogExp (double x, double limit, double quantile, double offset) {\n \/\/ the expoential function should be normalized in the range [offset, inf] and\n \/\/ have the quantile corresponding to the desidered probablity at the limit\n \/\/ value.\n \/\/\n \/\/ Starting from the standard exp function normalized betweeen 0 and inf:\n \/\/\n \/\/ f(x) = a*exp(-a*x)\n \/\/\n \/\/ the parameter a is hence fixed by:\n \/\/\n \/\/ int _0 ^limit f(x) dx = quantile\n \/\/ => a = -ln(1-quantile)\/limit\n \/\/\n \/\/ and final the frame must be changed such that 0->offset\n \/\/\n \/\/ => a = -ln(1-quantile)\/(limit-offset)\n \/\/ f(x) = a * exp(-a* (x-offset))\n\n\n \/\/ Check that the quantile is in the range ]0,1[\n if (quantile <= 0.0 && quantile >= 1.0) { \n std::cerr << \"MSMath::Logexp >> error: \"\n << \"quantile must be >0 && <1\\n\";\n return std::numeric_limits::quiet_NaN();\n\n \/\/ Check that the limit is above the offset\n } else if (limit <= offset) {\n std::cerr << \"MSModelPullExp >> error: \"\n << \"the limit must be larger than the offset\\n\";\n return std::numeric_limits::quiet_NaN();\n\n \/\/ Check that the parameter is in the physical range\n } else if (x < offset) {\n std::cerr << \"MSMath::Logexp >> error: \"\n << \"parameter must be larger than the offset\\n\";\n return std::numeric_limits::quiet_NaN();\n\n \/\/ compute LogExp\n } else {\n const double a = -log(1.0-quantile)\/(limit-offset);\n return log(a)-a*(x-offset);\n }\n}\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Matirx.hpp\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#ifndef EIGENJS_MATRIX_HPP\n#define EIGENJS_MATRIX_HPP\n\n#include \n#include \n\n#include \n\n#include \n\n#include \n\nnamespace EigenJS {\n\nclass Matrix : public node::ObjectWrap {\n public:\n static void Init(v8::Handle exports) {\n NanScope();\n\n v8::Local tpl = NanNew(New);\n tpl->SetClassName(NanNew(\"Matrix\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n NODE_SET_PROTOTYPE_METHOD(tpl, \"rows\", rows);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"cols\", cols);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"set\", set);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"get\", get);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"toString\", toString);\n\n NanAssignPersistent(constructor, tpl->GetFunction());\n exports->Set(NanNew(\"Matrix\"), tpl->GetFunction());\n }\n\n static NAN_METHOD(rows) {\n const Matrix* obj = node::ObjectWrap::Unwrap(args.This());\n NanScope();\n\n NanReturnValue(NanNew(obj->matrix_.rows()));\n }\n\n static NAN_METHOD(cols) {\n const Matrix* obj = node::ObjectWrap::Unwrap(args.This());\n NanScope();\n\n NanReturnValue(NanNew(obj->matrix_.cols()));\n }\n\n static NAN_METHOD(set) {\n NanScope();\n\n if (args.Length() == 3 &&\n args[0]->IsNumber() &&\n args[1]->IsNumber() &&\n args[2]->IsNumber()) {\n matrix_type::Index row = args[0]->Uint32Value();\n matrix_type::Index col = args[1]->Uint32Value();\n element_type value = args[2]->NumberValue();\n\n Matrix* obj = node::ObjectWrap::Unwrap(args.This());\n if (is_out_of_range(obj->matrix_, row, col))\n NanReturnUndefined();\n obj->matrix_(row, col) = value;\n }\n\n NanReturnValue(NanNew(args.This()));\n }\n\n static NAN_METHOD(get) {\n const Matrix* obj = node::ObjectWrap::Unwrap(args.This());\n NanScope();\n\n if (args.Length() == 2 &&\n args[0]->IsNumber() &&\n args[1]->IsNumber()) {\n matrix_type::Index row = args[0]->Uint32Value();\n matrix_type::Index col = args[1]->Uint32Value();\n if (is_out_of_range(obj->matrix_, row, col))\n NanReturnUndefined();\n element_type value = obj->matrix_(row, col);\n NanReturnValue(NanNew(value));\n }\n\n NanReturnUndefined();\n }\n\n static NAN_METHOD(toString) {\n const Matrix* obj = node::ObjectWrap::Unwrap(args.This());\n NanScope();\n\n std::ostringstream result;\n result << obj->matrix_;\n\n NanReturnValue(NanNew(result.str().c_str()));\n }\n\n private:\n typedef double element_type;\n typedef Eigen::Matrix<\n element_type\n , Eigen::Dynamic\n , Eigen::Dynamic\n > matrix_type;\n\n Matrix(matrix_type::Index rows, matrix_type::Index cols)\n : matrix_(matrix_type::Zero(rows, cols))\n {}\n ~Matrix() {}\n\n static NAN_METHOD(New) {\n NanScope();\n\n if (args.Length() < 2) {\n NanThrowError(\"Tried creating matrix without rows and columns arguments\");\n NanReturnUndefined();\n }\n\n if (args.IsConstructCall()) {\n matrix_type::Index rows = args[0]->Uint32Value();\n matrix_type::Index columns = args[1]->Uint32Value();\n Matrix* obj = new Matrix(rows, columns);\n obj->Wrap(args.This());\n NanReturnValue(args.This());\n } else {\n v8::Local ctr = NanNew(constructor);\n v8::Local argv[] = {args[0], args[1]};\n NanReturnValue(\n ctr->NewInstance(\n sizeof(argv)\/sizeof(v8::Local)\n , argv\n )\n );\n }\n }\n\n static v8::Persistent constructor;\n\n private:\n static bool is_out_of_range(\n const matrix_type& matrix\n , const matrix_type::Index& row\n , const matrix_type::Index& col) {\n return row < 0 || row >= matrix.rows() || col < 0 || col >= matrix.cols()\n ? NanThrowError(\"Row or column numbers are out of range\"), true\n : false;\n }\n\n private:\n matrix_type matrix_;\n};\n\nv8::Persistent Matrix::constructor;\n\n} \/\/ namespace EigenJS\n\n#endif \/\/ EIGENJS_MATRIX_HPP\nsrc: add 'Matrix.set()' to support Array argument\/\/\n\/\/ Matirx.hpp\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#ifndef EIGENJS_MATRIX_HPP\n#define EIGENJS_MATRIX_HPP\n\n#include \n#include \n\n#include \n\n#include \n\n#include \n\nnamespace EigenJS {\n\nclass Matrix : public node::ObjectWrap {\n public:\n static void Init(v8::Handle exports) {\n NanScope();\n\n v8::Local tpl = NanNew(New);\n tpl->SetClassName(NanNew(\"Matrix\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n NODE_SET_PROTOTYPE_METHOD(tpl, \"rows\", rows);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"cols\", cols);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"set\", set);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"get\", get);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"toString\", toString);\n\n NanAssignPersistent(constructor, tpl->GetFunction());\n exports->Set(NanNew(\"Matrix\"), tpl->GetFunction());\n }\n\n static NAN_METHOD(rows) {\n const Matrix* obj = node::ObjectWrap::Unwrap(args.This());\n NanScope();\n\n NanReturnValue(NanNew(obj->matrix_.rows()));\n }\n\n static NAN_METHOD(cols) {\n const Matrix* obj = node::ObjectWrap::Unwrap(args.This());\n NanScope();\n\n NanReturnValue(NanNew(obj->matrix_.cols()));\n }\n\n static NAN_METHOD(set) {\n Matrix* obj = node::ObjectWrap::Unwrap(args.This());\n NanScope();\n\n if (args.Length() == 1 && args[0]->IsArray()) {\n v8::Local array = args[0].As();\n uint32_t len = array->Length();\n const matrix_type::Index& rows = obj->matrix_.rows();\n\n for (uint32_t i = 0; i < len; ++i) {\n v8::Local elem = array->Get(i);\n obj->matrix_(i \/ rows, i % rows) = elem->NumberValue();\n }\n } else if (\n args.Length() == 3 &&\n args[0]->IsNumber() &&\n args[1]->IsNumber() &&\n args[2]->IsNumber()) {\n matrix_type::Index row = args[0]->Uint32Value();\n matrix_type::Index col = args[1]->Uint32Value();\n element_type value = args[2]->NumberValue();\n\n if (is_out_of_range(obj->matrix_, row, col))\n NanReturnUndefined();\n\n obj->matrix_(row, col) = value;\n }\n\n NanReturnValue(NanNew(args.This()));\n }\n\n static NAN_METHOD(get) {\n const Matrix* obj = node::ObjectWrap::Unwrap(args.This());\n NanScope();\n\n if (args.Length() == 2 &&\n args[0]->IsNumber() &&\n args[1]->IsNumber()) {\n matrix_type::Index row = args[0]->Uint32Value();\n matrix_type::Index col = args[1]->Uint32Value();\n if (is_out_of_range(obj->matrix_, row, col))\n NanReturnUndefined();\n element_type value = obj->matrix_(row, col);\n NanReturnValue(NanNew(value));\n }\n\n NanReturnUndefined();\n }\n\n static NAN_METHOD(toString) {\n const Matrix* obj = node::ObjectWrap::Unwrap(args.This());\n NanScope();\n\n std::ostringstream result;\n result << obj->matrix_;\n\n NanReturnValue(NanNew(result.str().c_str()));\n }\n\n private:\n typedef double element_type;\n typedef Eigen::Matrix<\n element_type\n , Eigen::Dynamic\n , Eigen::Dynamic\n > matrix_type;\n\n Matrix(matrix_type::Index rows, matrix_type::Index cols)\n : matrix_(matrix_type::Zero(rows, cols))\n {}\n ~Matrix() {}\n\n static NAN_METHOD(New) {\n NanScope();\n\n if (args.Length() < 2) {\n NanThrowError(\"Tried creating matrix without rows and columns arguments\");\n NanReturnUndefined();\n }\n\n if (args.IsConstructCall()) {\n matrix_type::Index rows = args[0]->Uint32Value();\n matrix_type::Index columns = args[1]->Uint32Value();\n Matrix* obj = new Matrix(rows, columns);\n obj->Wrap(args.This());\n NanReturnValue(args.This());\n } else {\n v8::Local ctr = NanNew(constructor);\n v8::Local argv[] = {args[0], args[1]};\n NanReturnValue(\n ctr->NewInstance(\n sizeof(argv)\/sizeof(v8::Local)\n , argv\n )\n );\n }\n }\n\n static v8::Persistent constructor;\n\n private:\n static bool is_out_of_range(\n const matrix_type& matrix\n , const matrix_type::Index& row\n , const matrix_type::Index& col) {\n return row < 0 || row >= matrix.rows() || col < 0 || col >= matrix.cols()\n ? NanThrowError(\"Row or column numbers are out of range\"), true\n : false;\n }\n\n private:\n matrix_type matrix_;\n};\n\nv8::Persistent Matrix::constructor;\n\n} \/\/ namespace EigenJS\n\n#endif \/\/ EIGENJS_MATRIX_HPP\n<|endoftext|>"} {"text":"\/\/ [[Rcpp::depends(BH)]]\n\n#include \"Random.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#define Q_GAMMA_THRESHOLD 1E-6\n#define Q_GAMMA_MIN_VALUE 0.0\n\ntypedef boost::random::mt19937 RNGType;\n\/\/typedef boost::random::mt11213b RNGType; \/\/ should be faster\nstatic RNGType rng;\n\nvoid gaps::random::setSeed(uint32_t seed)\n{\n rng.seed(seed);\n}\n\ndouble gaps::random::normal(double mean, double var)\n{\n boost::random::normal_distribution dist(mean, var);\n return dist(rng);\n}\n\nint gaps::random::poisson(double lambda)\n{\n boost::random::poisson_distribution<> dist(lambda);\n return dist(rng);\n}\n\ndouble gaps::random::exponential(double lambda)\n{\n boost::random::exponential_distribution<> dist(lambda);\n return dist(rng);\n}\n\ndouble gaps::random::uniform()\n{\n boost::random::uniform_01 dist(rng); \/\/ could be moved out\n return dist();\n}\n\ndouble gaps::random::uniform(double a, double b)\n{\n if (a == b)\n {\n return a;\n }\n else if (a < b)\n {\n boost::random::uniform_real_distribution<> dist(a,b);\n return dist(rng);\n }\n}\n\nuint64_t gaps::random::uniform64()\n{\n boost::random::uniform_int_distribution dist(0,\n std::numeric_limits::max());\n return dist(rng);\n}\n\nuint64_t gaps::random::uniform64(uint64_t a, uint64_t b)\n{\n if (a == b)\n {\n return a;\n }\n else if (a < b)\n {\n boost::random::uniform_int_distribution dist(a,b);\n return dist(rng);\n }\n}\n\ndouble gaps::random::d_gamma(double d, double shape, double scale)\n{\n boost::math::gamma_distribution<> gam(shape, scale);\n return pdf(gam, d);\n}\n\ndouble gaps::random::p_gamma(double p, double shape, double scale)\n{\n boost::math::gamma_distribution<> gam(shape, scale);\n return cdf(gam, p);\n}\n\ndouble gaps::random::q_gamma(double q, double shape, double scale)\n{\n if (q < Q_GAMMA_THRESHOLD)\n {\n return Q_GAMMA_MIN_VALUE;\n }\n else\n {\n boost::math::gamma_distribution<> gam(shape, scale);\n return quantile(gam, q);\n }\n}\n\ndouble gaps::random::d_norm(double d, double mean, double sd)\n{\n boost::math::normal_distribution<> norm(mean, sd);\n return pdf(norm, d);\n}\n\ndouble gaps::random::q_norm(double q, double mean, double sd)\n{\n boost::math::normal_distribution<> norm(mean, sd);\n return quantile(norm, q);\n}\n\ndouble gaps::random::p_norm(double p, double mean, double sd)\n{\n boost::math::normal_distribution<> norm(mean, sd);\n return cdf(norm, p);\n}\n\ndisable optimization around boost - needed for valgrind\/\/ [[Rcpp::depends(BH)]]\n\n\/\/ needed to run in valgrind\n#pragma GCC push_options\n#pragma GCC optimize (\"O0\")\n\n#include \"Random.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#define Q_GAMMA_THRESHOLD 1E-6\n#define Q_GAMMA_MIN_VALUE 0.0\n\ntypedef boost::random::mt19937 RNGType;\n\/\/typedef boost::random::mt11213b RNGType; \/\/ should be faster\nstatic RNGType rng;\n\nvoid gaps::random::setSeed(uint32_t seed)\n{\n rng.seed(seed);\n}\n\ndouble gaps::random::normal(double mean, double var)\n{\n boost::random::normal_distribution dist(mean, var);\n return dist(rng);\n}\n\nint gaps::random::poisson(double lambda)\n{\n boost::random::poisson_distribution<> dist(lambda);\n return dist(rng);\n}\n\ndouble gaps::random::exponential(double lambda)\n{\n boost::random::exponential_distribution<> dist(lambda);\n return dist(rng);\n}\n\ndouble gaps::random::uniform()\n{\n boost::random::uniform_01 dist(rng); \/\/ could be moved out\n return dist();\n}\n\ndouble gaps::random::uniform(double a, double b)\n{\n if (a == b)\n {\n return a;\n }\n else if (a < b)\n {\n boost::random::uniform_real_distribution<> dist(a,b);\n return dist(rng);\n }\n}\n\nuint64_t gaps::random::uniform64()\n{\n boost::random::uniform_int_distribution dist(0,\n std::numeric_limits::max());\n return dist(rng);\n}\n\nuint64_t gaps::random::uniform64(uint64_t a, uint64_t b)\n{\n if (a == b)\n {\n return a;\n }\n else if (a < b)\n {\n boost::random::uniform_int_distribution dist(a,b);\n return dist(rng);\n }\n}\n\ndouble gaps::random::d_gamma(double d, double shape, double scale)\n{\n boost::math::gamma_distribution<> gam(shape, scale);\n return pdf(gam, d);\n}\n\ndouble gaps::random::p_gamma(double p, double shape, double scale)\n{\n boost::math::gamma_distribution<> gam(shape, scale);\n return cdf(gam, p);\n}\n\ndouble gaps::random::q_gamma(double q, double shape, double scale)\n{\n if (q < Q_GAMMA_THRESHOLD)\n {\n return Q_GAMMA_MIN_VALUE;\n }\n else\n {\n boost::math::gamma_distribution<> gam(shape, scale);\n return quantile(gam, q);\n }\n}\n\ndouble gaps::random::d_norm(double d, double mean, double sd)\n{\n boost::math::normal_distribution<> norm(mean, sd);\n return pdf(norm, d);\n}\n\ndouble gaps::random::q_norm(double q, double mean, double sd)\n{\n boost::math::normal_distribution<> norm(mean, sd);\n return quantile(norm, q);\n}\n\ndouble gaps::random::p_norm(double p, double mean, double sd)\n{\n boost::math::normal_distribution<> norm(mean, sd);\n return cdf(norm, p);\n}\n\n#pragma GCC pop_options<|endoftext|>"} {"text":"#include \n#include \n#include \"SnakeEngine.h\"\n#include \n\nconst int SCREEN_WIDTH = 1920;\nconst int SCREEN_HEIGHT = 1200;\n\n\/\/const int SCREEN_WIDTH = 1366;\n\/\/const int SCREEN_HEIGHT = 768;\n\nconst int SNAKE_GRID_WIDTH = BOARD_WIDTH;\nconst int SNAKE_GRID_HEIGHT = BOARD_HEIGHT;\n\nconst int SNAKE_CELL_W_PX = SCREEN_WIDTH\/SNAKE_GRID_WIDTH;\nconst int SNAKE_CELL_H_PX = SCREEN_HEIGHT\/SNAKE_GRID_HEIGHT;\n\n\/\/ Fixed game logic step\nconst Uint32 TICK_STEP = 60; \/\/ ms\n\nvoid updateRects(std::vector* rectVec, std::vector* snakeVec)\n{\n\tint numRects = rectVec->size();\n\tint numSnakeSquares = snakeVec->size();\n\n\t\/\/ Just fill rectVec with sufficient rectangles at first\n\twhile (numSnakeSquares > numRects) {\n\t\tSDL_Rect fillerRect;\n\t\tfillerRect.w = SNAKE_CELL_W_PX;\n\t\tfillerRect.h = SNAKE_CELL_H_PX;\n\n\t\trectVec->insert(rectVec->begin(), fillerRect);\n\t\tnumRects = rectVec->size();\n\t}\n\n\tint rectVecIndex = 0;\n\tfor (auto& pos : *snakeVec) {\n\t\tint gridX = pos->x;\n\t\tint gridY = pos->y;\n\n\t\tint screenX = gridX*SNAKE_CELL_W_PX;\n\t\tint screenY = gridY*SNAKE_CELL_H_PX;\n\n\t\trectVec->at(rectVecIndex).x = screenX;\n\t\trectVec->at(rectVecIndex).y = screenY;\n\n\t\trectVecIndex++;\n\t}\n}\n\nint main(int arc, char* argv[])\n{\n\t\/\/ Create SnakeEngine object, which is responsible for all game logic\n\tSnakeEngine engine(SnakeEngine::NORTH);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Init a bunch of SDL stuff (graphics and user input)\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ INIT engine\n\tif (SDL_Init(SDL_INIT_EVERYTHING) == -1) {\n\t\tstd::cout << SDL_GetError() << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ Make the window\n\tSDL_Window *screen = nullptr;\n\tscreen = SDL_CreateWindow(\"MaxGFX Extreme\", \n\t\t0,\n\t\t0,\n\t\tSCREEN_WIDTH,\n\t\tSCREEN_HEIGHT,\n\t\tSDL_WINDOW_FULLSCREEN);\n\n\tif (screen == nullptr) {\n\t\tstd::cout << SDL_GetError() << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ Make the renderer\n\tSDL_Renderer *renderer = nullptr;\n\trenderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_ACCELERATED);\n\tif (renderer == nullptr) {\n\t\tstd::cout << SDL_GetError() << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ Make event object to receive input events\n\tSDL_Event event;\n\n\t\/\/ Set background to black\n\tSDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n\tSDL_RenderClear(renderer);\n\n\t\/\/ Create a vector for holding all SDL_Rects needed to draw snake\n\tstd::vector snakeRects;\n\n\t\/\/ Fill it\n\tupdateRects(&snakeRects, engine.getSnakeVector());\n\n\t\/\/ Create a rect for an apple\n\tSDL_Rect appleRect;\n\tappleRect.w = SNAKE_CELL_W_PX;\n\tappleRect.h = SNAKE_CELL_H_PX;\n\tappleRect.x = engine.getAppleX()*SNAKE_CELL_W_PX;\n\tappleRect.y = engine.getAppleY()*SNAKE_CELL_H_PX;\n\n\t\/\/ Remove the cursor and set a delay for the startup\n\tSDL_ShowCursor(0);\n\tSDL_Delay(500);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ GAME LOOP\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tbool running = true;\n\tUint32 lastTick = SDL_GetTicks()-100;\n\tbool doTick = true;\n\twhile (running)\n\t{\n\t\t\/\/ Checks for input events, such as clicking \"X\"\/close on the window or keyboard input\n\t\tif (SDL_PollEvent(&event)) \n\t\t{\n\t\t\tif (event.type == SDL_QUIT)\n\t\t\t{\n\t\t\t\trunning = false;\n\t\t\t}\n\t\t\tif (event.type == SDL_KEYDOWN)\n\t\t\t{\n\t\t\t\tswitch(event.key.keysym.sym) {\n\t\t\t\tcase SDLK_ESCAPE:\n\t\t\t\t\trunning = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_w:\n\t\t\t\t\tengine.setDirection(SnakeEngine::NORTH);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_a:\n\t\t\t\t\tengine.setDirection(SnakeEngine::WEST);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_s:\n\t\t\t\t\tengine.setDirection(SnakeEngine::SOUTH);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_d:\n\t\t\t\t\tengine.setDirection(SnakeEngine::EAST);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t\t\n\t\t\/\/ Game logic\n\t\tif (!doTick) {\n\t\t\tif ((SDL_GetTicks() - lastTick) > TICK_STEP) {\n\t\t\t\tdoTick = true;\n\t\t\t\tlastTick = SDL_GetTicks();\n\t\t\t}\n\t\t}\n\n\t\tif (doTick) {\n\t\t\tengine.tick();\n\t\t\tdoTick = false;\n\n\t\t\tif (engine.hasCrashed()) {\n\t\t\t\trunning = false;\n\t\t\t\tSDL_Delay(1000);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Rendering\n\t\tupdateRects(&snakeRects, engine.getSnakeVector());\n\n\t\tappleRect.x = engine.getAppleX()*SNAKE_CELL_W_PX;\n\t\tappleRect.y = engine.getAppleY()*SNAKE_CELL_H_PX;\n\n\t\t\/\/ Set background to black and clear\n\t\tSDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n\t\tSDL_RenderClear(renderer);\n\n\t\t\/\/ Draw snake\n\t\tSDL_SetRenderDrawColor(renderer, 12, 172, 12, 255);\n\t\tfor (auto& rect : snakeRects) {\n\t\t\tSDL_RenderFillRect(renderer, &rect);\n\t\t}\n\n\t\t\/\/ Draw an apple\n\t\tSDL_SetRenderDrawColor(renderer, 202, 3, 3, 255);\n\t\tSDL_RenderFillRect(renderer, &appleRect);\n\n\t\tSDL_RenderPresent(renderer);\n\t}\n\n\tSDL_DestroyRenderer(renderer);\n\tSDL_DestroyWindow(screen);\n\n\tSDL_Quit();\n\n\treturn 0;\n}No longer needed Source.cpp, now main.cpp<|endoftext|>"} {"text":"\/\/ Vaca - Visual Application Components Abstraction\r\n\/\/ Copyright (c) 2005-2009 David Capello\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\r\n\/\/ are 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\/\/ * Redistributions in binary form must reproduce the above copyright\r\n\/\/ notice, this list of conditions and the following disclaimer in\r\n\/\/ the documentation and\/or other materials provided with the\r\n\/\/ distribution.\r\n\/\/ * Neither the name of the author nor the names of its contributors\r\n\/\/ may be used to endorse or promote products derived from this\r\n\/\/ 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\r\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r\n\/\/ COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\r\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\r\n\/\/ STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r\n\/\/ OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n#include \"Vaca\/System.h\"\r\n#include \"Vaca\/Rect.h\"\r\n#include \"Vaca\/Point.h\"\r\n#include \"Vaca\/Size.h\"\r\n#include \"Vaca\/Color.h\"\r\n#include \"Vaca\/Debug.h\"\r\n#include \"Vaca\/ImageList.h\"\r\n#include \"Vaca\/Mutex.h\"\r\n#include \"Vaca\/ScopedLock.h\"\r\n\r\n#include \r\n\r\nusing namespace Vaca;\r\n\r\n\/\/\/ Returns the parameters in the command line.\r\n\/\/\/ \r\n\/\/\/ @c System::getArgs()[0] is the name of the executable file.\r\n\/\/\/ \r\nstd::vector System::getArgs()\r\n{\r\n \/\/ Convert the command-line to a vector of arguments...\r\n std::vector args;\r\n\r\n Char* cmdline = wcsdup(GetCommandLine());\r\n Char quote;\r\n\r\n for (int i = 0; cmdline[i] != 0; ) {\r\n \/\/ eat spaces\r\n while (cmdline[i] != 0 && iswspace(cmdline[i]))\r\n ++i;\r\n\r\n \/\/ string with quotes?\r\n if (cmdline[i] == '\\\"' || cmdline[i] == '\\'')\r\n quote = cmdline[i++];\r\n else if (cmdline[i] == 0)\r\n break;\r\n else\r\n quote = 0;\r\n\r\n \/\/ read the string\r\n String arg;\r\n \r\n for (; cmdline[i] != 0; ++i) {\r\n \/\/ with quotes\r\n if (quote != 0) {\r\n\tif (cmdline[i] == quote) {\r\n\t ++i;\r\n\t break;\r\n\t}\r\n\telse if (cmdline[i] == '\\\\' && cmdline[i+1] == quote)\r\n\t ++i;\r\n }\r\n \/\/ without quotes\r\n else if (iswspace(cmdline[i]))\r\n\tbreak;\r\n\r\n arg.push_back(cmdline[i]);\r\n }\r\n\r\n args.push_back(arg);\r\n }\r\n\r\n std::free(cmdline);\r\n return args;\r\n}\r\n\r\n\/\/\/ Prints a line in the console.\r\n\/\/\/ \r\nvoid System::println(String line)\r\n{\r\n#ifdef _UNICODE\r\n _putws(line.c_str());\r\n#else\r\n puts(line.c_str());\r\n#endif\r\n}\r\n\r\nvoid System::printf(LPCTSTR fmt, ...)\r\n{\r\n Char buf[1024];\t\t\/\/ TODO: overflow\r\n va_list ap;\r\n\r\n va_start(ap, fmt);\r\n#ifdef UNICODE\r\n vswprintf(buf, fmt, ap);\r\n#else\r\n vsprintf(buf, fmt, ap);\r\n#endif\r\n va_end(ap);\r\n\r\n#ifdef UNICODE\r\n fputws(buf, stdout);\r\n#else\r\n fputs(buf, stdout);\r\n#endif\r\n}\r\n\r\nvoid System::print(String buf)\r\n{\r\n#ifdef UNICODE\r\n fputws(buf.c_str(), stdout);\r\n#else\r\n fputs(buf.c_str(), stdout);\r\n#endif\r\n}\r\n\r\nString System::getCurrentDirectory()\r\n{\r\n Char* buf = new Char[MAX_PATH];\r\n\r\n if (GetCurrentDirectory(MAX_PATH, buf) > 0)\r\n return String(buf);\r\n else\r\n return L\"\";\r\n}\r\n\r\nString System::getWindowsDirectory()\r\n{\r\n Char* buf = new Char[MAX_PATH];\r\n\r\n if (GetWindowsDirectory(buf, MAX_PATH) > 0)\r\n return String(buf);\r\n else\r\n return L\"\";\r\n}\r\n\r\n\/\/\/ \r\n\/\/\/ TODO folderCsidl can't be a virtual folder\r\n\/\/\/ \r\n\/\/\/ CSIDL_ADMINTOOLS\r\n\/\/\/ CSIDL_ALTSTARTUP\r\n\/\/\/ CSIDL_APPDATA\r\n\/\/\/ CSIDL_BITBUCKET\r\n\/\/\/ CSIDL_CDBURN_AREA\r\n\/\/\/ CSIDL_COMMON_ADMINTOOLS\r\n\/\/\/ CSIDL_COMMON_ALTSTARTUP\r\n\/\/\/ CSIDL_COMMON_APPDATA\r\n\/\/\/ CSIDL_COMMON_DESKTOPDIRECTORY\r\n\/\/\/ CSIDL_COMMON_DOCUMENTS\r\n\/\/\/ CSIDL_COMMON_FAVORITES\r\n\/\/\/ CSIDL_COMMON_MUSIC\r\n\/\/\/ CSIDL_COMMON_OEM_LINKS\r\n\/\/\/ CSIDL_COMMON_PICTURES\r\n\/\/\/ CSIDL_COMMON_PROGRAMS\r\n\/\/\/ CSIDL_COMMON_STARTMENU\r\n\/\/\/ CSIDL_COMMON_STARTUP\r\n\/\/\/ CSIDL_COMMON_TEMPLATES\r\n\/\/\/ CSIDL_COMMON_VIDEO\r\n\/\/\/ CSIDL_COMPUTERSNEARME\r\n\/\/\/ CSIDL_CONNECTIONS\r\n\/\/\/ CSIDL_CONTROLS\r\n\/\/\/ CSIDL_COOKIES\r\n\/\/\/ CSIDL_DESKTOP\r\n\/\/\/ CSIDL_DESKTOPDIRECTORY\r\n\/\/\/ CSIDL_DRIVES\r\n\/\/\/ CSIDL_FAVORITES\r\n\/\/\/ CSIDL_FONTS\r\n\/\/\/ CSIDL_HISTORY\r\n\/\/\/ CSIDL_INTERNET\r\n\/\/\/ CSIDL_INTERNET_CACHE\r\n\/\/\/ CSIDL_LOCAL_APPDATA\r\n\/\/\/ CSIDL_MYPICTURES\r\n\/\/\/ CSIDL_NETHOOD\r\n\/\/\/ CSIDL_NETWORK\r\n\/\/\/ CSIDL_PERSONAL\r\n\/\/\/ CSIDL_PRINTERS\r\n\/\/\/ CSIDL_PRINTHOOD\r\n\/\/\/ CSIDL_PROFILE\r\n\/\/\/ CSIDL_PROGRAMS\r\n\/\/\/ CSIDL_PROGRAM_FILES\r\n\/\/\/ CSIDL_PROGRAM_FILESX86\r\n\/\/\/ CSIDL_PROGRAM_FILES_COMMON\r\n\/\/\/ CSIDL_PROGRAM_FILES_COMMONX86\r\n\/\/\/ CSIDL_RECENT\r\n\/\/\/ CSIDL_RESOURCES\r\n\/\/\/ CSIDL_RESOURCES_LOCALIZED\r\n\/\/\/ CSIDL_SENDTO\r\n\/\/\/ CSIDL_STARTMENU\r\n\/\/\/ CSIDL_STARTUP\r\n\/\/\/ CSIDL_SYSTEM\r\n\/\/\/ CSIDL_SYSTEMX86\r\n\/\/\/ CSIDL_TEMPLATES\r\n\/\/\/ CSIDL_WINDOWS\r\n\/\/\/ \r\nString System::getShellFolderPath(int folderCsidl, bool create)\r\n{\r\n Char* buf = new Char[MAX_PATH];\r\n\r\n if (SHGetSpecialFolderPath(NULL, buf, folderCsidl, create))\r\n return String(buf);\r\n else\r\n return L\"\";\r\n}\r\n\r\nImageList System::getImageList(bool smallImage)\r\n{\r\n HIMAGELIST himl;\r\n SHFILEINFO shfi;\r\n\r\n himl = reinterpret_cast\r\n (SHGetFileInfo(L\"\",\r\n\t\t 0, &shfi, sizeof(shfi),\r\n\t\t SHGFI_SYSICONINDEX |\r\n\t\t (smallImage ? SHGFI_SMALLICON:\r\n\t\t\t\t SHGFI_LARGEICON)));\r\n\r\n return ImageList(himl); \/\/ TODO this can't be delete!!!\r\n}\r\n\r\nint System::getFileImageIndex(const String& fileName, bool smallImage)\r\n{\r\n SHFILEINFO shfi;\r\n\r\n SHGetFileInfo(fileName.c_str(), 0, &shfi, sizeof(shfi),\r\n\t\tSHGFI_SYSICONINDEX |\r\n\t\t(smallImage ? SHGFI_SMALLICON:\r\n\t\t\t SHGFI_LARGEICON));\r\n\r\n return shfi.iIcon;\r\n}\r\n\r\n\/\/\/ Returns the screen size.\r\n\/\/\/ \r\nSize System::getScreenSize()\r\n{\r\n return Size(GetSystemMetrics(SM_CXFULLSCREEN),\r\n\t GetSystemMetrics(SM_CYFULLSCREEN));\r\n}\r\n\r\n\/\/\/ Returns the work-area of the screen, it is like the desktop area,\r\n\/\/\/ that is not overlapped by the task-bar.\r\n\/\/\/ \r\n\/\/\/ @warning\r\n\/\/\/ Win32: It is a call to @msdn{SystemParametersInfo} using\r\n\/\/\/ @msdn{SPI_GETWORKAREA}.\r\n\/\/\/ \r\nRect System::getWorkAreaBounds()\r\n{\r\n RECT rc;\r\n\r\n \/\/ returns the work-area rectangle\r\n if (SystemParametersInfo(SPI_GETWORKAREA, 0, reinterpret_cast(&rc), 0))\r\n return Rect(&rc);\r\n \/\/ returns the full-screen rectangle\r\n else\r\n return Rect(Point(0, 0), System::getScreenSize());\r\n}\r\n\r\n\/\/\/ Returns color from the system. It's a wrapper for the Win32's GetSysColor.\r\n\/\/\/ \r\n\/\/\/ @param index\r\n\/\/\/ Can be one of the following values:\r\n\/\/\/ @li COLOR_3DDKSHADOW\r\n\/\/\/ @li COLOR_3DFACE\r\n\/\/\/ @li COLOR_3DHILIGHT\r\n\/\/\/ @li COLOR_3DHIGHLIGHT\r\n\/\/\/ @li COLOR_3DLIGHT\r\n\/\/\/ @li COLOR_BTNHILIGHT\r\n\/\/\/ @li COLOR_3DSHADOW\r\n\/\/\/ @li COLOR_ACTIVEBORDER\r\n\/\/\/ @li COLOR_ACTIVECAPTION\r\n\/\/\/ @li COLOR_APPWORKSPACE\r\n\/\/\/ @li COLOR_BACKGROUND\r\n\/\/\/ @li COLOR_DESKTOP\r\n\/\/\/ @li COLOR_BTNFACE\r\n\/\/\/ @li COLOR_BTNHIGHLIGHT\r\n\/\/\/ @li COLOR_BTNSHADOW\r\n\/\/\/ @li COLOR_BTNTEXT\r\n\/\/\/ @li COLOR_CAPTIONTEXT\r\n\/\/\/ @li COLOR_GRAYTEXT\r\n\/\/\/ @li COLOR_HIGHLIGHT\r\n\/\/\/ @li COLOR_HIGHLIGHTTEXT\r\n\/\/\/ @li COLOR_INACTIVEBORDER\r\n\/\/\/ @li COLOR_INACTIVECAPTION\r\n\/\/\/ @li COLOR_INACTIVECAPTIONTEXT\r\n\/\/\/ @li COLOR_INFOBK\r\n\/\/\/ @li COLOR_INFOTEXT\r\n\/\/\/ @li COLOR_MENU\r\n\/\/\/ @li COLOR_MENUTEXT\r\n\/\/\/ @li COLOR_SCROLLBAR\r\n\/\/\/ @li COLOR_WINDOW\r\n\/\/\/ @li COLOR_WINDOWFRAME\r\n\/\/\/ @li COLOR_WINDOWTEXT\r\n\/\/\/ @li COLOR_HOTLIGHT\r\n\/\/\/ @li COLOR_GRADIENTACTIVECAPTION\r\n\/\/\/ @li COLOR_GRADIENTINACTIVECAPTION\r\n\/\/\/ \r\n\/\/\/ @todo make the index a Enum\r\n\/\/\/ \r\nColor System::getColor(int index)\r\n{\r\n return Color(GetSysColor(index));\r\n}\r\n\r\nbool System::getKeyState(Keys::Type keyCode)\r\n{\r\n \/\/ you can't use getKeyState for modifiers\r\n assert((keyCode & Keys::Modifiers) == 0);\r\n \r\n return (GetKeyState(keyCode) & 0x8000) != 0;\r\n}\r\n\r\n\/\/\/ Returns the cursor position in the screen.\r\n\/\/\/ \r\nPoint System::getCursorPos()\r\n{\r\n POINT pt;\r\n GetCursorPos(&pt);\r\n return Point(pt.x, pt.y);\r\n}\r\n\r\nvoid System::setCursorPos(const Point& pt)\r\n{\r\n SetCursorPos(pt.x, pt.y);\r\n}\r\n\r\nString System::getUserName()\r\n{\r\n Char buf[UNLEN+1];\r\n \/\/ char buf[UNLEN+1];\r\n DWORD len = UNLEN+1;\r\n\r\n if (GetUserName(buf, &len))\r\n return String(buf);\r\n else\r\n return String();\r\n}\r\n\r\n\/\/ Prototypes for Win2000\/XP API\r\n\/\/ typedef BOOLEAN (*GUNEProc)(EXTENDED_NAME_FORMAT NameFormat, LPTSTR lpNameBuffer, PULONG nSize);\r\n\r\nString System::getFriendlyUserName()\r\n{\r\n#if 0\t\t\t\t\/\/ TODO\r\n#if (_WIN32_WINNT >= 0x0500)\r\n HMODULE hSecur32 = GetModuleHandle(L\"SECUR32.DLL\");\r\n if (!hSecur32)\r\n hSecur32 = LoadLibrary(L\"SECUR32.DLL\");\r\n GUNEProc pGUNE = (GUNEProc)GetProcAddress(hSecur32, \"GetUserNameExW\");\r\n\r\n if (pGUNE != NULL) {\r\n Char buf[UNLEN+1];\r\n ULONG len = UNLEN+1;\r\n\r\n if (pGUNE(NameDisplay, buf, &len))\r\n return String(buf);\r\n }\r\n#endif\r\n#endif\r\n return getUserName();\r\n}\r\n\r\n\/\/ int System::getWheelScrollLines()\r\n\/\/ {\r\n\/\/ UINT pulScrollLines = 0;\r\n\/\/ return SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &pulScrollLines, 0);\r\n\/\/ }\r\n\r\nint System::getOS()\r\n{\r\n static Mutex mutex;\r\n static volatile OS::Type cached = OS::Unknown;\r\n\r\n ScopedLock hold(mutex);\r\n\r\n if (cached != OS::Unknown)\r\n return cached;\r\n\r\n OSVERSIONINFOEX osvi;\r\n BOOL bOsVersionInfoEx;\r\n\r\n ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));\r\n osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);\r\n\r\n if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*)&osvi))) {\r\n osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\r\n if (!GetVersionEx((OSVERSIONINFO*)&osvi))\r\n return OS::Unknown;\r\n }\r\n\r\n switch (osvi.dwPlatformId) {\r\n\r\n case VER_PLATFORM_WIN32_NT:\r\n if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)\r\n\treturn cached = OS::WinServer2003;\r\n else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)\r\n\treturn cached = OS::WinXP;\r\n else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)\r\n\treturn cached = OS::Win2K;\r\n else if (osvi.dwMajorVersion <= 4)\r\n\treturn cached = OS::WinNT;\r\n break;\r\n\r\n case VER_PLATFORM_WIN32_WINDOWS:\r\n if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) {\r\n\tif (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')\r\n\t return cached = OS::Win95R2;\r\n\telse\r\n\t return cached = OS::Win95;\r\n } \r\n else if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) {\r\n\tif (osvi.szCSDVersion[1] == 'A')\r\n\t return cached = OS::Win98SE;\r\n\telse\r\n\t return cached = OS::Win98;\r\n }\r\n else if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)\r\n\treturn cached = OS::WinMe;\r\n break;\r\n\r\n case VER_PLATFORM_WIN32s:\r\n return cached = OS::Win32s;\r\n }\r\n\r\n return cached = OS::Unknown;\r\n}\r\n\r\nbool System::isWin95_98_Me()\r\n{\r\n return (getOS() & (OS::Win95 | OS::Win98 | OS::WinMe)) != 0;\r\n}\r\n\r\nbool System::isWinNT_2K_XP()\r\n{\r\n return (getOS() & (OS::WinNT | OS::Win2K | OS::WinXP | OS::WinServer2003)) != 0;\r\n}\r\n\r\nbool System::isWin2K_XP()\r\n{\r\n return (getOS() & (OS::Win2K | OS::WinXP | OS::WinServer2003)) != 0;\r\n}\r\n\r\nbool System::isWinXP()\r\n{\r\n return (getOS() & OS::WinXP) != 0;\r\n}\r\nFixed System::getWorkAreaBounds() documentation.\/\/ Vaca - Visual Application Components Abstraction\r\n\/\/ Copyright (c) 2005-2009 David Capello\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\r\n\/\/ are 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\/\/ * Redistributions in binary form must reproduce the above copyright\r\n\/\/ notice, this list of conditions and the following disclaimer in\r\n\/\/ the documentation and\/or other materials provided with the\r\n\/\/ distribution.\r\n\/\/ * Neither the name of the author nor the names of its contributors\r\n\/\/ may be used to endorse or promote products derived from this\r\n\/\/ 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\r\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r\n\/\/ COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\r\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\r\n\/\/ STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r\n\/\/ OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n#include \"Vaca\/System.h\"\r\n#include \"Vaca\/Rect.h\"\r\n#include \"Vaca\/Point.h\"\r\n#include \"Vaca\/Size.h\"\r\n#include \"Vaca\/Color.h\"\r\n#include \"Vaca\/Debug.h\"\r\n#include \"Vaca\/ImageList.h\"\r\n#include \"Vaca\/Mutex.h\"\r\n#include \"Vaca\/ScopedLock.h\"\r\n\r\n#include \r\n\r\nusing namespace Vaca;\r\n\r\n\/\/\/ Returns the parameters in the command line.\r\n\/\/\/ \r\n\/\/\/ @c System::getArgs()[0] is the name of the executable file.\r\n\/\/\/ \r\nstd::vector System::getArgs()\r\n{\r\n \/\/ Convert the command-line to a vector of arguments...\r\n std::vector args;\r\n\r\n Char* cmdline = wcsdup(GetCommandLine());\r\n Char quote;\r\n\r\n for (int i = 0; cmdline[i] != 0; ) {\r\n \/\/ eat spaces\r\n while (cmdline[i] != 0 && iswspace(cmdline[i]))\r\n ++i;\r\n\r\n \/\/ string with quotes?\r\n if (cmdline[i] == '\\\"' || cmdline[i] == '\\'')\r\n quote = cmdline[i++];\r\n else if (cmdline[i] == 0)\r\n break;\r\n else\r\n quote = 0;\r\n\r\n \/\/ read the string\r\n String arg;\r\n \r\n for (; cmdline[i] != 0; ++i) {\r\n \/\/ with quotes\r\n if (quote != 0) {\r\n\tif (cmdline[i] == quote) {\r\n\t ++i;\r\n\t break;\r\n\t}\r\n\telse if (cmdline[i] == '\\\\' && cmdline[i+1] == quote)\r\n\t ++i;\r\n }\r\n \/\/ without quotes\r\n else if (iswspace(cmdline[i]))\r\n\tbreak;\r\n\r\n arg.push_back(cmdline[i]);\r\n }\r\n\r\n args.push_back(arg);\r\n }\r\n\r\n std::free(cmdline);\r\n return args;\r\n}\r\n\r\n\/\/\/ Prints a line in the console.\r\n\/\/\/ \r\nvoid System::println(String line)\r\n{\r\n#ifdef _UNICODE\r\n _putws(line.c_str());\r\n#else\r\n puts(line.c_str());\r\n#endif\r\n}\r\n\r\nvoid System::printf(LPCTSTR fmt, ...)\r\n{\r\n Char buf[1024];\t\t\/\/ TODO: overflow\r\n va_list ap;\r\n\r\n va_start(ap, fmt);\r\n#ifdef UNICODE\r\n vswprintf(buf, fmt, ap);\r\n#else\r\n vsprintf(buf, fmt, ap);\r\n#endif\r\n va_end(ap);\r\n\r\n#ifdef UNICODE\r\n fputws(buf, stdout);\r\n#else\r\n fputs(buf, stdout);\r\n#endif\r\n}\r\n\r\nvoid System::print(String buf)\r\n{\r\n#ifdef UNICODE\r\n fputws(buf.c_str(), stdout);\r\n#else\r\n fputs(buf.c_str(), stdout);\r\n#endif\r\n}\r\n\r\nString System::getCurrentDirectory()\r\n{\r\n Char* buf = new Char[MAX_PATH];\r\n\r\n if (GetCurrentDirectory(MAX_PATH, buf) > 0)\r\n return String(buf);\r\n else\r\n return L\"\";\r\n}\r\n\r\nString System::getWindowsDirectory()\r\n{\r\n Char* buf = new Char[MAX_PATH];\r\n\r\n if (GetWindowsDirectory(buf, MAX_PATH) > 0)\r\n return String(buf);\r\n else\r\n return L\"\";\r\n}\r\n\r\n\/\/\/ \r\n\/\/\/ TODO folderCsidl can't be a virtual folder\r\n\/\/\/ \r\n\/\/\/ CSIDL_ADMINTOOLS\r\n\/\/\/ CSIDL_ALTSTARTUP\r\n\/\/\/ CSIDL_APPDATA\r\n\/\/\/ CSIDL_BITBUCKET\r\n\/\/\/ CSIDL_CDBURN_AREA\r\n\/\/\/ CSIDL_COMMON_ADMINTOOLS\r\n\/\/\/ CSIDL_COMMON_ALTSTARTUP\r\n\/\/\/ CSIDL_COMMON_APPDATA\r\n\/\/\/ CSIDL_COMMON_DESKTOPDIRECTORY\r\n\/\/\/ CSIDL_COMMON_DOCUMENTS\r\n\/\/\/ CSIDL_COMMON_FAVORITES\r\n\/\/\/ CSIDL_COMMON_MUSIC\r\n\/\/\/ CSIDL_COMMON_OEM_LINKS\r\n\/\/\/ CSIDL_COMMON_PICTURES\r\n\/\/\/ CSIDL_COMMON_PROGRAMS\r\n\/\/\/ CSIDL_COMMON_STARTMENU\r\n\/\/\/ CSIDL_COMMON_STARTUP\r\n\/\/\/ CSIDL_COMMON_TEMPLATES\r\n\/\/\/ CSIDL_COMMON_VIDEO\r\n\/\/\/ CSIDL_COMPUTERSNEARME\r\n\/\/\/ CSIDL_CONNECTIONS\r\n\/\/\/ CSIDL_CONTROLS\r\n\/\/\/ CSIDL_COOKIES\r\n\/\/\/ CSIDL_DESKTOP\r\n\/\/\/ CSIDL_DESKTOPDIRECTORY\r\n\/\/\/ CSIDL_DRIVES\r\n\/\/\/ CSIDL_FAVORITES\r\n\/\/\/ CSIDL_FONTS\r\n\/\/\/ CSIDL_HISTORY\r\n\/\/\/ CSIDL_INTERNET\r\n\/\/\/ CSIDL_INTERNET_CACHE\r\n\/\/\/ CSIDL_LOCAL_APPDATA\r\n\/\/\/ CSIDL_MYPICTURES\r\n\/\/\/ CSIDL_NETHOOD\r\n\/\/\/ CSIDL_NETWORK\r\n\/\/\/ CSIDL_PERSONAL\r\n\/\/\/ CSIDL_PRINTERS\r\n\/\/\/ CSIDL_PRINTHOOD\r\n\/\/\/ CSIDL_PROFILE\r\n\/\/\/ CSIDL_PROGRAMS\r\n\/\/\/ CSIDL_PROGRAM_FILES\r\n\/\/\/ CSIDL_PROGRAM_FILESX86\r\n\/\/\/ CSIDL_PROGRAM_FILES_COMMON\r\n\/\/\/ CSIDL_PROGRAM_FILES_COMMONX86\r\n\/\/\/ CSIDL_RECENT\r\n\/\/\/ CSIDL_RESOURCES\r\n\/\/\/ CSIDL_RESOURCES_LOCALIZED\r\n\/\/\/ CSIDL_SENDTO\r\n\/\/\/ CSIDL_STARTMENU\r\n\/\/\/ CSIDL_STARTUP\r\n\/\/\/ CSIDL_SYSTEM\r\n\/\/\/ CSIDL_SYSTEMX86\r\n\/\/\/ CSIDL_TEMPLATES\r\n\/\/\/ CSIDL_WINDOWS\r\n\/\/\/ \r\nString System::getShellFolderPath(int folderCsidl, bool create)\r\n{\r\n Char* buf = new Char[MAX_PATH];\r\n\r\n if (SHGetSpecialFolderPath(NULL, buf, folderCsidl, create))\r\n return String(buf);\r\n else\r\n return L\"\";\r\n}\r\n\r\nImageList System::getImageList(bool smallImage)\r\n{\r\n HIMAGELIST himl;\r\n SHFILEINFO shfi;\r\n\r\n himl = reinterpret_cast\r\n (SHGetFileInfo(L\"\",\r\n\t\t 0, &shfi, sizeof(shfi),\r\n\t\t SHGFI_SYSICONINDEX |\r\n\t\t (smallImage ? SHGFI_SMALLICON:\r\n\t\t\t\t SHGFI_LARGEICON)));\r\n\r\n return ImageList(himl); \/\/ TODO this can't be delete!!!\r\n}\r\n\r\nint System::getFileImageIndex(const String& fileName, bool smallImage)\r\n{\r\n SHFILEINFO shfi;\r\n\r\n SHGetFileInfo(fileName.c_str(), 0, &shfi, sizeof(shfi),\r\n\t\tSHGFI_SYSICONINDEX |\r\n\t\t(smallImage ? SHGFI_SMALLICON:\r\n\t\t\t SHGFI_LARGEICON));\r\n\r\n return shfi.iIcon;\r\n}\r\n\r\n\/\/\/ Returns the screen size.\r\n\/\/\/ \r\nSize System::getScreenSize()\r\n{\r\n return Size(GetSystemMetrics(SM_CXFULLSCREEN),\r\n\t GetSystemMetrics(SM_CYFULLSCREEN));\r\n}\r\n\r\n\/\/\/ Returns the work-area of the screen, it is like the desktop area,\r\n\/\/\/ that is not overlapped by the task-bar.\r\n\/\/\/ \r\n\/\/\/ @win32\r\n\/\/\/ It is a call to @msdn{SystemParametersInfo} using @msdn{SPI_GETWORKAREA}.\r\n\/\/\/ @endwin32\r\n\/\/\/ \r\nRect System::getWorkAreaBounds()\r\n{\r\n RECT rc;\r\n\r\n \/\/ returns the work-area rectangle\r\n if (SystemParametersInfo(SPI_GETWORKAREA, 0, reinterpret_cast(&rc), 0))\r\n return Rect(&rc);\r\n \/\/ returns the full-screen rectangle\r\n else\r\n return Rect(Point(0, 0), System::getScreenSize());\r\n}\r\n\r\n\/\/\/ Returns color from the system. It's a wrapper for the Win32's GetSysColor.\r\n\/\/\/ \r\n\/\/\/ @param index\r\n\/\/\/ Can be one of the following values:\r\n\/\/\/ @li COLOR_3DDKSHADOW\r\n\/\/\/ @li COLOR_3DFACE\r\n\/\/\/ @li COLOR_3DHILIGHT\r\n\/\/\/ @li COLOR_3DHIGHLIGHT\r\n\/\/\/ @li COLOR_3DLIGHT\r\n\/\/\/ @li COLOR_BTNHILIGHT\r\n\/\/\/ @li COLOR_3DSHADOW\r\n\/\/\/ @li COLOR_ACTIVEBORDER\r\n\/\/\/ @li COLOR_ACTIVECAPTION\r\n\/\/\/ @li COLOR_APPWORKSPACE\r\n\/\/\/ @li COLOR_BACKGROUND\r\n\/\/\/ @li COLOR_DESKTOP\r\n\/\/\/ @li COLOR_BTNFACE\r\n\/\/\/ @li COLOR_BTNHIGHLIGHT\r\n\/\/\/ @li COLOR_BTNSHADOW\r\n\/\/\/ @li COLOR_BTNTEXT\r\n\/\/\/ @li COLOR_CAPTIONTEXT\r\n\/\/\/ @li COLOR_GRAYTEXT\r\n\/\/\/ @li COLOR_HIGHLIGHT\r\n\/\/\/ @li COLOR_HIGHLIGHTTEXT\r\n\/\/\/ @li COLOR_INACTIVEBORDER\r\n\/\/\/ @li COLOR_INACTIVECAPTION\r\n\/\/\/ @li COLOR_INACTIVECAPTIONTEXT\r\n\/\/\/ @li COLOR_INFOBK\r\n\/\/\/ @li COLOR_INFOTEXT\r\n\/\/\/ @li COLOR_MENU\r\n\/\/\/ @li COLOR_MENUTEXT\r\n\/\/\/ @li COLOR_SCROLLBAR\r\n\/\/\/ @li COLOR_WINDOW\r\n\/\/\/ @li COLOR_WINDOWFRAME\r\n\/\/\/ @li COLOR_WINDOWTEXT\r\n\/\/\/ @li COLOR_HOTLIGHT\r\n\/\/\/ @li COLOR_GRADIENTACTIVECAPTION\r\n\/\/\/ @li COLOR_GRADIENTINACTIVECAPTION\r\n\/\/\/ \r\n\/\/\/ @todo make the index a Enum\r\n\/\/\/ \r\nColor System::getColor(int index)\r\n{\r\n return Color(GetSysColor(index));\r\n}\r\n\r\nbool System::getKeyState(Keys::Type keyCode)\r\n{\r\n \/\/ you can't use getKeyState for modifiers\r\n assert((keyCode & Keys::Modifiers) == 0);\r\n \r\n return (GetKeyState(keyCode) & 0x8000) != 0;\r\n}\r\n\r\n\/\/\/ Returns the cursor position in the screen.\r\n\/\/\/ \r\nPoint System::getCursorPos()\r\n{\r\n POINT pt;\r\n GetCursorPos(&pt);\r\n return Point(pt.x, pt.y);\r\n}\r\n\r\nvoid System::setCursorPos(const Point& pt)\r\n{\r\n SetCursorPos(pt.x, pt.y);\r\n}\r\n\r\nString System::getUserName()\r\n{\r\n Char buf[UNLEN+1];\r\n \/\/ char buf[UNLEN+1];\r\n DWORD len = UNLEN+1;\r\n\r\n if (GetUserName(buf, &len))\r\n return String(buf);\r\n else\r\n return String();\r\n}\r\n\r\n\/\/ Prototypes for Win2000\/XP API\r\n\/\/ typedef BOOLEAN (*GUNEProc)(EXTENDED_NAME_FORMAT NameFormat, LPTSTR lpNameBuffer, PULONG nSize);\r\n\r\nString System::getFriendlyUserName()\r\n{\r\n#if 0\t\t\t\t\/\/ TODO\r\n#if (_WIN32_WINNT >= 0x0500)\r\n HMODULE hSecur32 = GetModuleHandle(L\"SECUR32.DLL\");\r\n if (!hSecur32)\r\n hSecur32 = LoadLibrary(L\"SECUR32.DLL\");\r\n GUNEProc pGUNE = (GUNEProc)GetProcAddress(hSecur32, \"GetUserNameExW\");\r\n\r\n if (pGUNE != NULL) {\r\n Char buf[UNLEN+1];\r\n ULONG len = UNLEN+1;\r\n\r\n if (pGUNE(NameDisplay, buf, &len))\r\n return String(buf);\r\n }\r\n#endif\r\n#endif\r\n return getUserName();\r\n}\r\n\r\n\/\/ int System::getWheelScrollLines()\r\n\/\/ {\r\n\/\/ UINT pulScrollLines = 0;\r\n\/\/ return SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &pulScrollLines, 0);\r\n\/\/ }\r\n\r\nint System::getOS()\r\n{\r\n static Mutex mutex;\r\n static volatile OS::Type cached = OS::Unknown;\r\n\r\n ScopedLock hold(mutex);\r\n\r\n if (cached != OS::Unknown)\r\n return cached;\r\n\r\n OSVERSIONINFOEX osvi;\r\n BOOL bOsVersionInfoEx;\r\n\r\n ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));\r\n osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);\r\n\r\n if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*)&osvi))) {\r\n osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\r\n if (!GetVersionEx((OSVERSIONINFO*)&osvi))\r\n return OS::Unknown;\r\n }\r\n\r\n switch (osvi.dwPlatformId) {\r\n\r\n case VER_PLATFORM_WIN32_NT:\r\n if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)\r\n\treturn cached = OS::WinServer2003;\r\n else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)\r\n\treturn cached = OS::WinXP;\r\n else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)\r\n\treturn cached = OS::Win2K;\r\n else if (osvi.dwMajorVersion <= 4)\r\n\treturn cached = OS::WinNT;\r\n break;\r\n\r\n case VER_PLATFORM_WIN32_WINDOWS:\r\n if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) {\r\n\tif (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')\r\n\t return cached = OS::Win95R2;\r\n\telse\r\n\t return cached = OS::Win95;\r\n } \r\n else if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) {\r\n\tif (osvi.szCSDVersion[1] == 'A')\r\n\t return cached = OS::Win98SE;\r\n\telse\r\n\t return cached = OS::Win98;\r\n }\r\n else if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)\r\n\treturn cached = OS::WinMe;\r\n break;\r\n\r\n case VER_PLATFORM_WIN32s:\r\n return cached = OS::Win32s;\r\n }\r\n\r\n return cached = OS::Unknown;\r\n}\r\n\r\nbool System::isWin95_98_Me()\r\n{\r\n return (getOS() & (OS::Win95 | OS::Win98 | OS::WinMe)) != 0;\r\n}\r\n\r\nbool System::isWinNT_2K_XP()\r\n{\r\n return (getOS() & (OS::WinNT | OS::Win2K | OS::WinXP | OS::WinServer2003)) != 0;\r\n}\r\n\r\nbool System::isWin2K_XP()\r\n{\r\n return (getOS() & (OS::Win2K | OS::WinXP | OS::WinServer2003)) != 0;\r\n}\r\n\r\nbool System::isWinXP()\r\n{\r\n return (getOS() & OS::WinXP) != 0;\r\n}\r\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: StorageNativeOutputStream.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: vg $ $Date: 2005-03-23 09:41: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): Ocke Janssen\n *\n *\n ************************************************************************\/\n#if HAVE_CONFIG_H\n#include \n#endif\n\n#include \"StorageNativeOutputStream.h\"\n#include \"uno\/mapping.hxx\"\n#include \"uno\/environment.hxx\"\n#include \"cppuhelper\/bootstrap.hxx\"\n#include \"cppuhelper\/compbase1.hxx\"\n#include \"cppuhelper\/component_context.hxx\"\n\n#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include \n#endif\n#include \"hsqldb\/HStorageAccess.h\"\n#include \"hsqldb\/HStorageMap.hxx\"\n\n#include \"jvmaccess\/virtualmachine.hxx\"\n#include \"com\/sun\/star\/lang\/XSingleComponentFactory.hpp\"\n\n#include \n\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::document;\nusing namespace ::com::sun::star::embed;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\nusing namespace ::connectivity::hsqldb;\n\n#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )\n\/*****************************************************************************\/\n\/* exception macros *\/\n\n#define ThrowException(env, type, msg) { \\\n env->ThrowNew(env->FindClass(type), msg); }\n\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: openStream\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;I)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_openStream\n (JNIEnv * env, jobject obj_this, jstring name, jstring key, jint mode)\n{\n#if OSL_DEBUG_LEVEL > 1\n {\n ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);\n sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\".output\"));\n ::rtl::OString sName = ::rtl::OUStringToOString(sOrgName,RTL_TEXTENCODING_ASCII_US);\n getStreams()[sOrgName] = fopen( sName.getStr(), \"a+\" );\n }\n#endif\n StorageContainer::registerStream(env,name,key,mode);\n}\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: write\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[BII)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3BII\n (JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer, jint off, jint len)\n{\n Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_write(env,obj_this,name,key,buffer,off,len);\n}\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: write\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[B)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3B\n (JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer)\n{\n Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_write(env,obj_this,name,key,buffer,0,env->GetArrayLength(buffer));\n}\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: close\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_close\n (JNIEnv * env, jobject obj_this, jstring key, jstring name)\n{\n ::boost::shared_ptr pHelper = StorageContainer::getRegisteredStream(env,name,key);\n Reference< XOutputStream> xFlush = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();\n if ( xFlush.is() )\n try\n {\n xFlush->flush();\n }\n catch(Exception&)\n {}\n\n#if OSL_DEBUG_LEVEL > 1\n {\n ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);\n sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\".output\"));\n fclose( getStreams()[sOrgName] );\n getStreams().erase(sOrgName);\n }\n#endif\n StorageContainer::revokeStream(env,name,key);\n}\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: write\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;I)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2I\n (JNIEnv * env, jobject obj_this, jstring key, jstring name,jint b)\n{\n Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_writeInt(env,obj_this,name,key,b);\n}\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: flush\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_flush\n (JNIEnv * env, jobject obj_this, jstring key, jstring name)\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: sync\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_sync\n (JNIEnv * env, jobject obj_this, jstring key, jstring name)\n{\n TStorages::mapped_type aStoragePair = StorageContainer::getRegisteredStorage(StorageContainer::jstring2ustring(env,key));\n Reference xTrans(aStoragePair.first.first,UNO_QUERY);\n if ( xTrans.is() )\n {\n try\n {\n TStreamMap::iterator aIter = aStoragePair.second.begin();\n TStreamMap::iterator aEnd = aStoragePair.second.end();\n for (;aIter != aEnd ; ++aIter)\n {\n ::boost::shared_ptr pHelper = aIter->second;\n Reference< XOutputStream> xFlush = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();\n if ( xFlush.is() )\n try\n {\n xFlush->flush();\n }\n catch(Exception&)\n {}\n }\n xTrans->commit();\n }\n catch(Exception& e)\n {\n OSL_ENSURE(0,\"Exception catched! : sync();\");\n StorageContainer::throwJavaException(e,env);\n }\n }\n}\n\/\/ -----------------------------------------------------------------------------\nINTEGRATION: CWS dba28 (1.3.22); FILE MERGED 2005\/03\/23 14:58:43 fs 1.3.22.2: #i45314# implement sync as flush, but *without* commit 2005\/03\/21 12:53:34 fs 1.3.22.1: copying the changes from CWS dba26 herein, since they're needed to fix i45314\/*************************************************************************\n *\n * $RCSfile: StorageNativeOutputStream.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-03-30 11: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): Ocke Janssen\n *\n *\n ************************************************************************\/\n#if HAVE_CONFIG_H\n#include \n#endif\n\n#include \"StorageNativeOutputStream.h\"\n#include \"uno\/mapping.hxx\"\n#include \"uno\/environment.hxx\"\n#include \"cppuhelper\/bootstrap.hxx\"\n#include \"cppuhelper\/compbase1.hxx\"\n#include \"cppuhelper\/component_context.hxx\"\n\n#ifndef CONNECTIVITY_HSQLDB_ACCESSLOG_HXX\n#include \"accesslog.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include \n#endif\n#include \"hsqldb\/HStorageAccess.hxx\"\n#include \"hsqldb\/HStorageMap.hxx\"\n\n#include \"jvmaccess\/virtualmachine.hxx\"\n#include \"com\/sun\/star\/lang\/XSingleComponentFactory.hpp\"\n\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::document;\nusing namespace ::com::sun::star::embed;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\nusing namespace ::connectivity::hsqldb;\n\n#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )\n\/*****************************************************************************\/\n\/* exception macros *\/\n\n#define ThrowException(env, type, msg) { \\\n env->ThrowNew(env->FindClass(type), msg); }\n\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: openStream\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;I)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_openStream\n (JNIEnv * env, jobject obj_this, jstring name, jstring key, jint mode)\n{\n#if OSL_DEBUG_LEVEL > 1\n {\n OperationLogFile( env, name, \"output\" ).logOperation( \"openStream\" );\n LogFile( env, name, \"output\" ).create();\n }\n#endif\n StorageContainer::registerStream(env,name,key,mode);\n}\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: write\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[BII)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3BII\n (JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer, jint off, jint len)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile( env, name, \"output\" ).logOperation( \"write( byte[], int, int )\" );\n\n DataLogFile aDataLog( env, name, \"output\" );\n write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, off, len, &aDataLog );\n#else\n write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, off, len );\n#endif\n}\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: write\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[B)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3B\n (JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile( env, name, \"output\" ).logOperation( \"write( byte[] )\" );\n\n DataLogFile aDataLog( env, name, \"output\" );\n write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, 0, env->GetArrayLength( buffer ), &aDataLog );\n#else\n write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, 0, env->GetArrayLength( buffer ) );\n#endif\n}\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: close\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_close\n (JNIEnv * env, jobject obj_this, jstring key, jstring name)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile aOpLog( env, name, \"output\" );\n aOpLog.logOperation( \"close\" );\n\n LogFile aDataLog( env, name, \"output\" );\n#endif\n\n ::boost::shared_ptr pHelper = StorageContainer::getRegisteredStream(env,name,key);\n Reference< XOutputStream> xFlush = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();\n if ( xFlush.is() )\n try\n {\n xFlush->flush();\n }\n catch(Exception&)\n {}\n\n#if OSL_DEBUG_LEVEL > 1\n aDataLog.close();\n aOpLog.close();\n#endif\n StorageContainer::revokeStream(env,name,key);\n}\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: write\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;I)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2I\n (JNIEnv * env, jobject obj_this, jstring key, jstring name,jint b)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile( env, name, \"output\" ).logOperation( \"write( int )\" );\n\n DataLogFile aDataLog( env, name, \"output\" );\n write_to_storage_stream( env, obj_this, name, key, b, &aDataLog );\n#else\n write_to_storage_stream( env, obj_this, name, key, b );\n#endif\n}\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: flush\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_flush\n (JNIEnv * env, jobject obj_this, jstring key, jstring name)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile( env, name, \"output\" ).logOperation( \"flush\" );\n#endif\n}\n\/\/ -----------------------------------------------------------------------------\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream\n * Method: sync\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_sync\n (JNIEnv * env, jobject obj_this, jstring key, jstring name)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile( env, name, \"output\" ).logOperation( \"sync\" );\n#endif\n ::boost::shared_ptr< StreamHelper > pStream = StorageContainer::getRegisteredStream( env, name, key );\n Reference< XOutputStream > xFlush = pStream.get() ? pStream->getOutputStream() : Reference< XOutputStream>();\n OSL_ENSURE( xFlush.is(), \"StorageNativeOutputStream::sync: could not retrieve an output stream!\" );\n if ( xFlush.is() )\n {\n try\n {\n xFlush->flush();\n }\n catch(Exception&)\n {\n OSL_ENSURE( false, \"StorageNativeOutputStream::sync: could not flush output stream!\" );\n }\n }\n}\n\/\/ -----------------------------------------------------------------------------\n<|endoftext|>"} {"text":"\/*\r\n * Copyright (c) 2008-2009\r\n *\r\n * School of Computing, University of Utah,\r\n * Salt Lake City, UT 84112, USA\r\n *\r\n * and the Gauss Group\r\n * http:\/\/www.cs.utah.edu\/formal_verification\r\n *\r\n * See LICENSE for licensing information\r\n *\/\r\n\r\n\/*\r\n * ISP: MPI Dynamic Verification Tool\r\n *\r\n * File: Transition.hpp\r\n * Description: Implements handling of a single transition in an interleaving\r\n * Contact: isp-dev@cs.utah.edu\r\n *\/\r\n\r\n#ifndef _CB_HPP\r\n#define _CB_HPP\r\n\/*\r\n#include \"Envelope.hpp\"\r\n#include \r\n#include \r\n*\/\r\n\/*\r\n * This implements a single transition\r\n *\/\r\nclass CB {\r\npublic:\r\n int _pid;\r\n int _index;\r\n CB () { }\r\n\r\n CB (int i, int ind) : _pid(i), _index(ind) {\r\n }\r\n CB(const CB& c) : _pid(c._pid), _index(c._index){}\r\n bool operator== (const CB &c) {\r\n return _pid == c._pid && _index == c._index;\r\n }\r\n bool operator!= (const CB &c) {\r\n return !(*this == c);\r\n }\r\n friend bool operator< (const CB &a, const CB &b) {\r\n return a._pid < b._pid || (a._pid == b._pid && a._index < b._index);\r\n }\r\n \/*\r\n CB& operator= (const CB &c) {\r\n this->_pid = c._pid;\r\n this->_index = c._index;\r\n return *this;\r\n }*\/\r\n std::unique_ptr Copy() {\r\n std::unique_ptr ptr(new CB(*this));\r\n return std::move(ptr);\r\n }\r\n};\r\n \r\n#endif\r\nChanged method names to be more consistent.\/*\r\n * Copyright (c) 2008-2009\r\n *\r\n * School of Computing, University of Utah,\r\n * Salt Lake City, UT 84112, USA\r\n *\r\n * and the Gauss Group\r\n * http:\/\/www.cs.utah.edu\/formal_verification\r\n *\r\n * See LICENSE for licensing information\r\n *\/\r\n\r\n\/*\r\n * ISP: MPI Dynamic Verification Tool\r\n *\r\n * File: Transition.hpp\r\n * Description: Implements handling of a single transition in an interleaving\r\n * Contact: isp-dev@cs.utah.edu\r\n *\/\r\n\r\n#ifndef _CB_HPP\r\n#define _CB_HPP\r\n\/*\r\n#include \"Envelope.hpp\"\r\n#include \r\n#include \r\n*\/\r\n\/*\r\n * This implements a single transition\r\n *\/\r\nclass CB {\r\npublic:\r\n int _pid;\r\n int _index;\r\n CB () { }\r\n\r\n CB (int i, int ind) : _pid(i), _index(ind) {\r\n }\r\n CB(const CB& c) : _pid(c._pid), _index(c._index){}\r\n bool operator== (const CB &c) {\r\n return _pid == c._pid && _index == c._index;\r\n }\r\n bool operator!= (const CB &c) {\r\n return !(*this == c);\r\n }\r\n friend bool operator< (const CB &a, const CB &b) {\r\n return a._pid < b._pid || (a._pid == b._pid && a._index < b._index);\r\n }\r\n \/*\r\n CB& operator= (const CB &c) {\r\n this->_pid = c._pid;\r\n this->_index = c._index;\r\n return *this;\r\n }*\/\r\n std::unique_ptr copy() {\r\n std::unique_ptr ptr(new CB(*this));\r\n return std::move(ptr);\r\n }\r\n};\r\n \r\n#endif\r\n<|endoftext|>"} {"text":"#include \"UnrealCVPrivate.h\"\n#include \"ViewMode.h\"\n#include \"BufferVisualizationData.h\"\n\n\/**\nFViewMode is a helper class to tweak render options. Important options are\n\tTonemapper\n\tEyeAdaptation\n\tTemporalAA\n\tMotionBlur\n\tLighting\n\tBloom\n\tColorGrading\n\tGammaCorrection\n\tDepthOfField\n\tLensFlare\n\tVignette\n*\/\n\n\nvoid BasicSetting(FEngineShowFlags& ShowFlags)\n{\n\tShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_All0);\n\tShowFlags.SetRendering(true);\n\tShowFlags.SetStaticMeshes(true);\n\tShowFlags.SetLandscape(true);\n\tShowFlags.SetInstancedFoliage(true);\n\tShowFlags.SetInstancedGrass(true);\n\tShowFlags.SetInstancedStaticMeshes(true);\n\tShowFlags.SetSkeletalMeshes(true);\n}\n\nvoid FViewMode::Lit(FEngineShowFlags& ShowFlags)\n{\n\tBasicSetting(ShowFlags);\n\tShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_Game);\n\tApplyViewMode(VMI_Lit, true, ShowFlags);\n\tShowFlags.SetMaterials(true);\n\tShowFlags.SetLighting(true);\n\tShowFlags.SetPostProcessing(true);\n\t\/\/ ToneMapper needs to be enabled, otherwise the screen will be very dark\n\tShowFlags.SetTonemapper(true);\n\t\/\/ TemporalAA needs to be disabled, otherwise the previous frame might contaminate current frame.\n\t\/\/ Check: https:\/\/answers.unrealengine.com\/questions\/436060\/low-quality-screenshot-after-setting-the-actor-pos.html for detail\n\n\t\/\/ ShowFlags.SetTemporalAA(true);\n\tShowFlags.SetTemporalAA(false);\n\tShowFlags.SetAntiAliasing(true);\n\tShowFlags.SetEyeAdaptation(false); \/\/ Eye adaption is a slow temporal procedure, not useful for image capture\n}\n\nvoid FViewMode::BufferVisualization(FEngineShowFlags& ShowFlags)\n{\n\tApplyViewMode(EViewModeIndex::VMI_VisualizeBuffer, true, ShowFlags); \/\/ This did more than just SetVisualizeBuffer(true);\n\t\/\/ EngineShowFlagOverride()\n\n\t\/\/ From ShowFlags.cpp\n\tShowFlags.SetPostProcessing(true);\n\tShowFlags.SetMaterials(true);\n\tShowFlags.SetVisualizeBuffer(true);\n\n\t\/\/ ToneMapper needs to be disabled\n\tShowFlags.SetTonemapper(false);\n\t\/\/ TemporalAA needs to be disabled, or it will contaminate the following frame\n\tShowFlags.SetTemporalAA(false);\n}\n\n\n\/** ViewMode showing post process *\/\nvoid FViewMode::PostProcess(FEngineShowFlags& ShowFlags)\n{\n\tBasicSetting(ShowFlags);\n\t\/\/ These are minimal setting\n\tShowFlags.SetPostProcessing(true);\n\tShowFlags.SetPostProcessMaterial(true);\n\t\/\/ ShowFlags.SetVertexColors(true); \/\/ This option will change object material to vertex color material, which don't produce surface normal\n\n\tGVertexColorViewMode = EVertexColorViewMode::Color;\n}\n\nvoid FViewMode::Wireframe(FEngineShowFlags& ShowFlags)\n{\n\t\/\/ ApplyViewMode(VMI_Wireframe, true, ShowFlags);\n\tShowFlags.SetPostProcessing(true);\n\tShowFlags.SetWireframe(true);\n}\n\n\nvoid FViewMode::VertexColor(FEngineShowFlags& ShowFlags)\n{\n\tApplyViewMode(VMI_Lit, true, ShowFlags);\n\n\t\/\/ From MeshPaintEdMode.cpp:2942\n\tShowFlags.SetMaterials(false);\n\tShowFlags.SetLighting(false);\n\tShowFlags.SetBSPTriangles(true);\n\tShowFlags.SetVertexColors(true);\n\tShowFlags.SetPostProcessing(false);\n\tShowFlags.SetHMDDistortion(false);\n\tShowFlags.SetTonemapper(false); \/\/ This won't take effect here\n\n\tGVertexColorViewMode = EVertexColorViewMode::Color;\n}\n\nvoid FViewMode::Unlit(FEngineShowFlags& ShowFlags)\n{\n\tApplyViewMode(VMI_Unlit, true, ShowFlags);\n\tShowFlags.SetMaterials(false);\n\tShowFlags.SetVertexColors(false);\n\tShowFlags.SetLightFunctions(false);\n\tShowFlags.SetLighting(false);\n\tShowFlags.SetAtmosphericFog(false);\n}\nEnable materials flag in the ShowFlags, so that the leaves will be accurately displayed in the depth and normal ground truth.#include \"UnrealCVPrivate.h\"\n#include \"ViewMode.h\"\n#include \"BufferVisualizationData.h\"\n\n\/**\nFViewMode is a helper class to tweak render options. Important options are\n\tTonemapper\n\tEyeAdaptation\n\tTemporalAA\n\tMotionBlur\n\tLighting\n\tBloom\n\tColorGrading\n\tGammaCorrection\n\tDepthOfField\n\tLensFlare\n\tVignette\n*\/\n\n\nvoid BasicSetting(FEngineShowFlags& ShowFlags)\n{\n\tShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_All0);\n\tShowFlags.SetRendering(true);\n\tShowFlags.SetStaticMeshes(true);\n\tShowFlags.SetLandscape(true);\n\n\tShowFlags.SetMaterials(true); \/\/ Important for the correctness of tree leaves.\n\n\tShowFlags.SetInstancedFoliage(true);\n\tShowFlags.SetInstancedGrass(true);\n\tShowFlags.SetInstancedStaticMeshes(true);\n\tShowFlags.SetSkeletalMeshes(true);\n\n\t\/\/ ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_Game);\n\t\/\/ ApplyViewMode(EViewModeIndex::VMI_VisualizeBuffer, true, ShowFlags); \/\/ This did more than just SetVisualizeBuffer(true);\n}\n\nvoid FViewMode::Lit(FEngineShowFlags& ShowFlags)\n{\n\tBasicSetting(ShowFlags);\n\tShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_Game);\n\tApplyViewMode(VMI_Lit, true, ShowFlags);\n\tShowFlags.SetMaterials(true);\n\tShowFlags.SetLighting(true);\n\tShowFlags.SetPostProcessing(true);\n\t\/\/ ToneMapper needs to be enabled, otherwise the screen will be very dark\n\tShowFlags.SetTonemapper(true);\n\t\/\/ TemporalAA needs to be disabled, otherwise the previous frame might contaminate current frame.\n\t\/\/ Check: https:\/\/answers.unrealengine.com\/questions\/436060\/low-quality-screenshot-after-setting-the-actor-pos.html for detail\n\n\t\/\/ ShowFlags.SetTemporalAA(true);\n\tShowFlags.SetTemporalAA(false);\n\tShowFlags.SetAntiAliasing(true);\n\tShowFlags.SetEyeAdaptation(false); \/\/ Eye adaption is a slow temporal procedure, not useful for image capture\n}\n\nvoid FViewMode::BufferVisualization(FEngineShowFlags& ShowFlags)\n{\n\tApplyViewMode(EViewModeIndex::VMI_VisualizeBuffer, true, ShowFlags); \/\/ This did more than just SetVisualizeBuffer(true);\n\t\/\/ EngineShowFlagOverride()\n\n\t\/\/ From ShowFlags.cpp\n\tShowFlags.SetPostProcessing(true);\n\tShowFlags.SetMaterials(true);\n\tShowFlags.SetVisualizeBuffer(true);\n\n\t\/\/ ToneMapper needs to be disabled\n\tShowFlags.SetTonemapper(false);\n\t\/\/ TemporalAA needs to be disabled, or it will contaminate the following frame\n\tShowFlags.SetTemporalAA(false);\n}\n\n\n\/** ViewMode showing post process *\/\nvoid FViewMode::PostProcess(FEngineShowFlags& ShowFlags)\n{\n\tBasicSetting(ShowFlags);\n\t\/\/ These are minimal setting\n\tShowFlags.SetPostProcessing(true);\n\tShowFlags.SetPostProcessMaterial(true);\n\t\/\/ ShowFlags.SetVertexColors(true); \/\/ This option will change object material to vertex color material, which don't produce surface normal\n\n\tGVertexColorViewMode = EVertexColorViewMode::Color;\n}\n\nvoid FViewMode::Wireframe(FEngineShowFlags& ShowFlags)\n{\n\t\/\/ ApplyViewMode(VMI_Wireframe, true, ShowFlags);\n\tShowFlags.SetPostProcessing(true);\n\tShowFlags.SetWireframe(true);\n}\n\n\nvoid FViewMode::VertexColor(FEngineShowFlags& ShowFlags)\n{\n\tApplyViewMode(VMI_Lit, true, ShowFlags);\n\n\t\/\/ From MeshPaintEdMode.cpp:2942\n\tShowFlags.SetMaterials(false);\n\tShowFlags.SetLighting(false);\n\tShowFlags.SetBSPTriangles(true);\n\tShowFlags.SetVertexColors(true);\n\tShowFlags.SetPostProcessing(false);\n\tShowFlags.SetHMDDistortion(false);\n\tShowFlags.SetTonemapper(false); \/\/ This won't take effect here\n\n\tGVertexColorViewMode = EVertexColorViewMode::Color;\n}\n\nvoid FViewMode::Unlit(FEngineShowFlags& ShowFlags)\n{\n\tApplyViewMode(VMI_Unlit, true, ShowFlags);\n\tShowFlags.SetMaterials(false);\n\tShowFlags.SetVertexColors(false);\n\tShowFlags.SetLightFunctions(false);\n\tShowFlags.SetLighting(false);\n\tShowFlags.SetAtmosphericFog(false);\n}\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2015-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace asgard {\n\nconst std::size_t UNIX_PATH_MAX = 108;\nconst std::size_t buffer_size = 4096;\n\nstruct driver_connector {\n \/\/Buffer\n char write_buffer[buffer_size];\n char receive_buffer[buffer_size];\n\n \/\/ The socket file descriptor\n int socket_fd;\n\n \/\/ The socket addresses\n struct sockaddr_un client_address;\n struct sockaddr_un server_address;\n};\n\nbool open_driver_connection(driver_connector& driver, const char* client_socket_path, const char* server_socket_path){\n \/\/ Open the socket\n driver.socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0);\n if(driver.socket_fd < 0){\n std::cerr << \"asgard:driversystem: socket() failed\" << std::endl;\n return false;\n }\n\n \/\/ Init the client address\n memset(&driver.client_address, 0, sizeof(struct sockaddr_un));\n driver.client_address.sun_family = AF_UNIX;\n snprintf(driver.client_address.sun_path, UNIX_PATH_MAX, client_socket_path);\n\n \/\/ Unlink the client socket\n unlink(client_socket_path);\n\n \/\/ Bind to client socket\n if(bind(driver.socket_fd, (const struct sockaddr *) &driver.client_address, sizeof(struct sockaddr_un)) < 0){\n std::cerr << \"asgard:driver: bind() failed\" << std::endl;\n return false;\n }\n\n \/\/ Init the server address\n memset(&driver.server_address, 0, sizeof(struct sockaddr_un));\n driver.server_address.sun_family = AF_UNIX;\n snprintf(driver.server_address.sun_path, UNIX_PATH_MAX, server_socket_path);\n\n return true;\n}\n\nint register_source(driver_connector& driver, const std::string& source_name){\n socklen_t address_length = sizeof(struct sockaddr_un);\n\n \/\/ Register the source\n auto nbytes = snprintf(driver.write_buffer, buffer_size, \"REG_SOURCE %s\", source_name.c_str());\n sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));\n\n auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);\n driver.receive_buffer[bytes_received] = '\\0';\n\n auto source_id = atoi(driver.receive_buffer);\n\n std::cout << \"asgard:driver: remote source: \" << source_id << std::endl;\n\n return source_id;\n}\n\nint register_sensor(driver_connector& driver, int source_id, const std::string& type, const std::string& name){\n socklen_t address_length = sizeof(struct sockaddr_un);\n\n \/\/ Register the sensor\n auto nbytes = snprintf(driver.write_buffer, buffer_size, \"REG_SENSOR %d %s %s\", source_id, type.c_str(), name.c_str());\n sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));\n\n auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);\n driver.receive_buffer[bytes_received] = '\\0';\n\n auto sensor_id = atoi(driver.receive_buffer);\n\n std::cout << \"asgard:driver: remote sensor(\" << name << \"):\" << sensor_id << std::endl;\n\n return sensor_id;\n}\n\nvoid send_data(driver_connector& driver, int source_id, int sensor_id, double value){\n \/\/ Send the data\n auto nbytes = snprintf(driver.write_buffer, buffer_size, \"DATA %d %d %.2f\", source_id, sensor_id, value);\n sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));\n}\n\nvoid unregister_sensor(driver_connector& driver, int source_id, int sensor_id){\n \/\/ Unregister the sensor, if necessary\n if(sensor_id >= 0){\n auto nbytes = snprintf(driver.write_buffer, buffer_size, \"UNREG_SENSOR %d %d\", source_id, sensor_id);\n sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));\n }\n}\n\nvoid unregister_source(driver_connector& driver, int source_id){\n \/\/ Unregister the source, if necessary\n if(source_id >= 0){\n auto nbytes = snprintf(driver.write_buffer, buffer_size, \"UNREG_SOURCE %d\", source_id);\n sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));\n }\n}\n\n} \/\/end of namespace asgard\nAdd revoke_root utility\/\/=======================================================================\n\/\/ Copyright (c) 2015-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n#include \n#include \n#include \n\n#include #include \n\n#include \n#include \n#include \n#include \n\nnamespace asgard {\n\nconst std::size_t UNIX_PATH_MAX = 108;\nconst std::size_t buffer_size = 4096;\n\nstruct driver_connector {\n \/\/Buffer\n char write_buffer[buffer_size];\n char receive_buffer[buffer_size];\n\n \/\/ The socket file descriptor\n int socket_fd;\n\n \/\/ The socket addresses\n struct sockaddr_un client_address;\n struct sockaddr_un server_address;\n};\n\nbool open_driver_connection(driver_connector& driver, const char* client_socket_path, const char* server_socket_path){\n \/\/ Open the socket\n driver.socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0);\n if(driver.socket_fd < 0){\n std::cerr << \"asgard:driversystem: socket() failed\" << std::endl;\n return false;\n }\n\n \/\/ Init the client address\n memset(&driver.client_address, 0, sizeof(struct sockaddr_un));\n driver.client_address.sun_family = AF_UNIX;\n snprintf(driver.client_address.sun_path, UNIX_PATH_MAX, client_socket_path);\n\n \/\/ Unlink the client socket\n unlink(client_socket_path);\n\n \/\/ Bind to client socket\n if(bind(driver.socket_fd, (const struct sockaddr *) &driver.client_address, sizeof(struct sockaddr_un)) < 0){\n std::cerr << \"asgard:driver: bind() failed\" << std::endl;\n return false;\n }\n\n \/\/ Init the server address\n memset(&driver.server_address, 0, sizeof(struct sockaddr_un));\n driver.server_address.sun_family = AF_UNIX;\n snprintf(driver.server_address.sun_path, UNIX_PATH_MAX, server_socket_path);\n\n return true;\n}\n\nint register_source(driver_connector& driver, const std::string& source_name){\n socklen_t address_length = sizeof(struct sockaddr_un);\n\n \/\/ Register the source\n auto nbytes = snprintf(driver.write_buffer, buffer_size, \"REG_SOURCE %s\", source_name.c_str());\n sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));\n\n auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);\n driver.receive_buffer[bytes_received] = '\\0';\n\n auto source_id = atoi(driver.receive_buffer);\n\n std::cout << \"asgard:driver: remote source: \" << source_id << std::endl;\n\n return source_id;\n}\n\nint register_sensor(driver_connector& driver, int source_id, const std::string& type, const std::string& name){\n socklen_t address_length = sizeof(struct sockaddr_un);\n\n \/\/ Register the sensor\n auto nbytes = snprintf(driver.write_buffer, buffer_size, \"REG_SENSOR %d %s %s\", source_id, type.c_str(), name.c_str());\n sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));\n\n auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);\n driver.receive_buffer[bytes_received] = '\\0';\n\n auto sensor_id = atoi(driver.receive_buffer);\n\n std::cout << \"asgard:driver: remote sensor(\" << name << \"):\" << sensor_id << std::endl;\n\n return sensor_id;\n}\n\nvoid send_data(driver_connector& driver, int source_id, int sensor_id, double value){\n \/\/ Send the data\n auto nbytes = snprintf(driver.write_buffer, buffer_size, \"DATA %d %d %.2f\", source_id, sensor_id, value);\n sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));\n}\n\nvoid unregister_sensor(driver_connector& driver, int source_id, int sensor_id){\n \/\/ Unregister the sensor, if necessary\n if(sensor_id >= 0){\n auto nbytes = snprintf(driver.write_buffer, buffer_size, \"UNREG_SENSOR %d %d\", source_id, sensor_id);\n sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));\n }\n}\n\nvoid unregister_source(driver_connector& driver, int source_id){\n \/\/ Unregister the source, if necessary\n if(source_id >= 0){\n auto nbytes = snprintf(driver.write_buffer, buffer_size, \"UNREG_SOURCE %d\", source_id);\n sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));\n }\n}\n\nbool revoke_root(){\n if (getuid() == 0) {\n if (setgid(1000) != 0){\n std::cout << \"asgard:dht11: setgid: Unable to drop group privileges: \" << strerror(errno) << std::endl;\n return false;\n }\n\n if (setuid(1000) != 0){\n std::cout << \"asgard:dht11: setgid: Unable to drop user privileges: \" << strerror(errno) << std::endl;\n return false;\n }\n }\n\n if (setuid(0) != -1){\n std::cout << \"asgard:dht11: managed to regain root privileges, exiting...\" << std::endl;\n return false;\n }\n\n return true;\n}\n\n} \/\/end of namespace asgard\n<|endoftext|>"} {"text":"\/*\n * Adplug - Replayer for many OPL2\/OPL3 audio file formats.\n * Copyright (C) 1999 - 2002 Simon Peter , 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 * adplug.cpp - CAdPlug helper class implementation, by Simon Peter \n *\/\n\n\/***** Includes *****\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"adplug.h\"\n#include \"debug.h\"\n\n\/***** Replayer includes *****\/\n\n#include \"hsc.h\"\n#include \"mtk.h\"\n#include \"hsp.h\"\n#include \"s3m.h\"\n#include \"raw.h\"\n#include \"d00.h\"\n#include \"sa2.h\"\n#include \"amd.h\"\n#include \"rad.h\"\n#include \"a2m.h\"\n#include \"mid.h\"\n#include \"imf.h\"\n#include \"sng.h\"\n#include \"ksm.h\"\n#include \"mkj.h\"\n#include \"dfm.h\"\n#include \"lds.h\"\n#include \"bam.h\"\n#include \"fmc.h\"\n#include \"bmf.h\"\n#include \"flash.h\"\n#include \"hyp.h\"\n#include \"psi.h\"\n#include \"rat.h\"\n#include \"hybrid.h\"\n#include \"mad.h\"\n#include \"adtrack.h\"\n\n\/\/ These players use C++ templates, which aren't supported by WATCOM C++\n#ifndef __WATCOMC__\n#include \"u6m.h\"\n#include \"rol.h\"\n#endif\n\n\/***** Defines *****\/\n\n#define VERSION\t\t\"1.3\"\t\t\/\/ AdPlug library version string\n\n\/***** Static variables initializers *****\/\n\nconst unsigned short CPlayer::note_table[12] = {363,385,408,432,458,485,514,544,577,611,647,686};\nconst unsigned char CPlayer::op_table[9] = {0x00, 0x01, 0x02, 0x08, 0x09, 0x0a, 0x10, 0x11, 0x12};\n\n\/***** List of all players that come in the standard AdPlug distribution *****\/\n\n\/\/ WARNING: The order of this list is on purpose! AdPlug tries the players in\n\/\/ this order, which is to be preserved, because some players take precedence\n\/\/ above other players.\n\/\/ The list is terminated with an all-NULL element.\nstatic const struct Players {\n CPlayer *(*factory) (Copl *newopl);\n} allplayers[] = {\n {CmidPlayer::factory}, {CksmPlayer::factory},\n#ifndef __WATCOMC__\n {CrolPlayer::factory},\n#endif\n {CsngPlayer::factory}, {Ca2mLoader::factory}, {CradLoader::factory},\n {CamdLoader::factory}, {Csa2Loader::factory}, {CrawPlayer::factory},\n {Cs3mPlayer::factory}, {CmtkLoader::factory}, {CmkjPlayer::factory},\n {CdfmLoader::factory}, {CbamPlayer::factory}, {CxadbmfPlayer::factory},\n {CxadflashPlayer::factory}, {CxadhypPlayer::factory}, {CxadpsiPlayer::factory},\n {CxadratPlayer::factory}, {CxadhybridPlayer::factory}, {CfmcLoader::factory},\n {CmadLoader::factory},\n#ifndef __WATCOMC__\n {Cu6mPlayer::factory},\n#endif\n {Cd00Player::factory}, {ChspLoader::factory}, {ChscPlayer::factory},\n {CimfPlayer::factory}, {CldsLoader::factory}, {CadtrackLoader::factory},\n {0}\n};\n\n\/***** Public methods *****\/\n\nCPlayer *CAdPlug::factory(const char *fn, Copl *opl)\n{\n\tifstream f(fn, ios::in | ios::binary);\n\n\tif(!f.is_open()) return 0;\n\treturn factory(f,opl,fn);\n}\n\nCPlayer *CAdPlug::factory(istream &f, Copl *opl, const char *fn)\n{\n CPlayer *p;\n unsigned int i;\n\n LogWrite(\"*** CAdPlug::factory(f,opl,\\\"%s\\\") ***\\n\",fn);\n\n for(i=0;allplayers[i].factory;i++) {\n LogWrite(\"Trying: %d\\n\",i);\n if((p = allplayers[i].factory(opl)))\n if(p->load(f,fn)) {\n\tLogWrite(\"got it!\\n\");\n\tLogWrite(\"--- CAdPlug::factory ---\\n\");\n\treturn p;\n } else {\n\tdelete p;\n\tf.seekg(0);\n }\n }\n\n LogWrite(\"End of list!\\n\");\n LogWrite(\"--- CAdPlug::factory ---\\n\");\n return 0;\n}\n\nunsigned long CAdPlug::songlength(CPlayer *p, unsigned int subsong)\n{\n\tfloat\tslength = 0.0f;\n\n\t\/\/ get song length\n\tp->rewind(subsong);\n\twhile(p->update() && slength < 600000)\t\/\/ song length limit: 10 minutes\n\t\tslength += 1000\/p->getrefresh();\n\tp->rewind(subsong);\n\n\treturn (unsigned long)slength;\n}\n\nvoid CAdPlug::seek(CPlayer *p, unsigned long ms)\n{\n\tfloat pos = 0.0f;\n\n\tp->rewind();\n\twhile(pos < ms && p->update())\t\t\/\/ seek to new position\n\t\tpos += 1000\/p->getrefresh();\n}\n\nstd::string CAdPlug::get_version()\n{\n return std::string(VERSION);\n}\n\nvoid CAdPlug::debug_output(std::string filename)\n{\n LogFile(filename.c_str());\n LogWrite(\"CAdPlug::debug_output(\\\"%s\\\"): Redirected.\\n\",filename.c_str());\n}\nCFF loader support\/*\n * Adplug - Replayer for many OPL2\/OPL3 audio file formats.\n * Copyright (C) 1999 - 2002 Simon Peter , 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 * adplug.cpp - CAdPlug helper class implementation, by Simon Peter \n *\/\n\n\/***** Includes *****\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"adplug.h\"\n#include \"debug.h\"\n\n\/***** Replayer includes *****\/\n\n#include \"hsc.h\"\n#include \"mtk.h\"\n#include \"hsp.h\"\n#include \"s3m.h\"\n#include \"raw.h\"\n#include \"d00.h\"\n#include \"sa2.h\"\n#include \"amd.h\"\n#include \"rad.h\"\n#include \"a2m.h\"\n#include \"mid.h\"\n#include \"imf.h\"\n#include \"sng.h\"\n#include \"ksm.h\"\n#include \"mkj.h\"\n#include \"dfm.h\"\n#include \"lds.h\"\n#include \"bam.h\"\n#include \"fmc.h\"\n#include \"bmf.h\"\n#include \"flash.h\"\n#include \"hyp.h\"\n#include \"psi.h\"\n#include \"rat.h\"\n#include \"hybrid.h\"\n#include \"mad.h\"\n#include \"adtrack.h\"\n#include \"cff.h\"\n\n\/\/ These players use C++ templates, which aren't supported by WATCOM C++\n#ifndef __WATCOMC__\n#include \"u6m.h\"\n#include \"rol.h\"\n#endif\n\n\/***** Defines *****\/\n\n#define VERSION\t\t\"1.3\"\t\t\/\/ AdPlug library version string\n\n\/***** Static variables initializers *****\/\n\nconst unsigned short CPlayer::note_table[12] = {363,385,408,432,458,485,514,544,577,611,647,686};\nconst unsigned char CPlayer::op_table[9] = {0x00, 0x01, 0x02, 0x08, 0x09, 0x0a, 0x10, 0x11, 0x12};\n\n\/***** List of all players that come in the standard AdPlug distribution *****\/\n\n\/\/ WARNING: The order of this list is on purpose! AdPlug tries the players in\n\/\/ this order, which is to be preserved, because some players take precedence\n\/\/ above other players.\n\/\/ The list is terminated with an all-NULL element.\nstatic const struct Players {\n CPlayer *(*factory) (Copl *newopl);\n} allplayers[] = {\n {CmidPlayer::factory}, {CksmPlayer::factory},\n#ifndef __WATCOMC__\n {CrolPlayer::factory},\n#endif\n {CsngPlayer::factory}, {Ca2mLoader::factory}, {CradLoader::factory},\n {CamdLoader::factory}, {Csa2Loader::factory}, {CrawPlayer::factory},\n {Cs3mPlayer::factory}, {CmtkLoader::factory}, {CmkjPlayer::factory},\n {CdfmLoader::factory}, {CbamPlayer::factory}, {CxadbmfPlayer::factory},\n {CxadflashPlayer::factory}, {CxadhypPlayer::factory}, {CxadpsiPlayer::factory},\n {CxadratPlayer::factory}, {CxadhybridPlayer::factory}, {CfmcLoader::factory},\n {CmadLoader::factory}, {CcffLoader::factory},\n#ifndef __WATCOMC__\n {Cu6mPlayer::factory},\n#endif\n {Cd00Player::factory}, {ChspLoader::factory}, {ChscPlayer::factory},\n {CimfPlayer::factory}, {CldsLoader::factory}, {CadtrackLoader::factory},\n {0}\n};\n\n\/***** Public methods *****\/\n\nCPlayer *CAdPlug::factory(const char *fn, Copl *opl)\n{\n\tifstream f(fn, ios::in | ios::binary);\n\n\tif(!f.is_open()) return 0;\n\treturn factory(f,opl,fn);\n}\n\nCPlayer *CAdPlug::factory(istream &f, Copl *opl, const char *fn)\n{\n CPlayer *p;\n unsigned int i;\n\n LogWrite(\"*** CAdPlug::factory(f,opl,\\\"%s\\\") ***\\n\",fn);\n\n for(i=0;allplayers[i].factory;i++) {\n LogWrite(\"Trying: %d\\n\",i);\n if((p = allplayers[i].factory(opl)))\n if(p->load(f,fn)) {\n\tLogWrite(\"got it!\\n\");\n\tLogWrite(\"--- CAdPlug::factory ---\\n\");\n\treturn p;\n } else {\n\tdelete p;\n\tf.seekg(0);\n }\n }\n\n LogWrite(\"End of list!\\n\");\n LogWrite(\"--- CAdPlug::factory ---\\n\");\n return 0;\n}\n\nunsigned long CAdPlug::songlength(CPlayer *p, unsigned int subsong)\n{\n\tfloat\tslength = 0.0f;\n\n\t\/\/ get song length\n\tp->rewind(subsong);\n\twhile(p->update() && slength < 600000)\t\/\/ song length limit: 10 minutes\n\t\tslength += 1000\/p->getrefresh();\n\tp->rewind(subsong);\n\n\treturn (unsigned long)slength;\n}\n\nvoid CAdPlug::seek(CPlayer *p, unsigned long ms)\n{\n\tfloat pos = 0.0f;\n\n\tp->rewind();\n\twhile(pos < ms && p->update())\t\t\/\/ seek to new position\n\t\tpos += 1000\/p->getrefresh();\n}\n\nstd::string CAdPlug::get_version()\n{\n return std::string(VERSION);\n}\n\nvoid CAdPlug::debug_output(std::string filename)\n{\n LogFile(filename.c_str());\n LogWrite(\"CAdPlug::debug_output(\\\"%s\\\"): Redirected.\\n\",filename.c_str());\n}\n<|endoftext|>"} {"text":"#include \"GurobiSolver.h\"\n\n#include \n#include \"gurobi_c++.h\"\n\n#include \"Optimization.h\"\n#include \"drake\/common\/drake_assert.h\"\n\nnamespace drake {\nnamespace solvers {\n\nbool GurobiSolver::available() const { return true; }\n\n\/\/ TODO(naveenoid): This is currently largely copy-pasta from the deprecated\n\/\/ Gurobi wrapper in solvers. Utilise sparsity in the constraint matrices,\n\/\/ i.e. Something like :\n\/\/ Eigen::SparseMatrix sparseA(A.sparseView());\n\/\/ sparseA.makeCompressed();\n\/\/ error = GRBaddconstrs(model, A.rows(), sparseA.nonZeros(),\n\/\/ sparseA.InnerIndices(), sparseA.OuterStarts(),\n\/\/ sparseA.Values(),sense, b.data(), NULL);\n\/\/ return(error);\n\ntemplate \nint myGRBaddconstrs(GRBmodel* model, Eigen::MatrixBase const& A,\n Eigen::MatrixBase const& b, char sense,\n double sparseness_threshold = 1e-14) {\n int error = 0, nnz = 0;\n\n std::vector cind(A.cols(), 0);\n std::vector cval(A.cols(), 0.0);\n\n for (size_t i = 0; i < A.rows(); i++) {\n nnz = 0;\n for (size_t j = 0; j < A.cols(); j++) {\n if (std::abs(A(i, j)) > sparseness_threshold) {\n cval[nnz] = A(i, j);\n cind[nnz++] = j;\n }\n }\n error = GRBaddconstr(model, nnz, &cind[0], &cval[0], sense, b(i), NULL);\n if (error) break;\n }\n return error;\n}\n\nSolutionResult GurobiSolver::Solve(OptimizationProblem& prog) const {\n \/\/ We only process quadratic costs and linear \/ bounding box\n \/\/ constraints\n\n GRBenv* env = NULL;\n GRBloadenv(&env, NULL);\n \/\/ Corresponds to no console or file logging.\n GRBsetintparam(env, GRB_INT_PAR_OUTPUTFLAG, 0);\n\n DRAKE_ASSERT(prog.generic_costs().empty());\n DRAKE_ASSERT(prog.generic_constraints().empty());\n\n Eigen::VectorXd solution(prog.num_vars());\n int num_vars = prog.num_vars();\n\n \/\/ bound constraints\n std::vector xlow(num_vars, -std::numeric_limits::infinity());\n std::vector xupp(num_vars, std::numeric_limits::infinity());\n\n for (auto const& binding : prog.bounding_box_constraints()) {\n auto const& c = binding.constraint();\n const Eigen::VectorXd& lower_bound = c->lower_bound();\n const Eigen::VectorXd& upper_bound = c->upper_bound();\n for (const DecisionVariableView& v : binding.variable_list()) {\n for (size_t k = 0; k < v.size(); k++) {\n const int idx = v.index() + k;\n xlow[idx] = std::max(lower_bound(k), xlow[idx]);\n xupp[idx] = std::min(upper_bound(k), xupp[idx]);\n }\n }\n }\n\n int error = 0;\n GRBmodel* model = NULL;\n double sparseness_threshold = 1e-14;\n\n GRBnewmodel(env, &model, \"QP\", num_vars, NULL, &xlow[0], &xupp[0], NULL,\n NULL);\n\n int start_row = 0;\n int num_constraint_vars = 0;\n double individual_quadratic_cost_value = 0.0;\n int row_ind = 0, col_ind = 0;\n\n for (auto const& binding : prog.quadratic_costs()) {\n auto const& c = binding.constraint();\n\n num_constraint_vars = binding.GetNumElements();\n\n Eigen::MatrixXd Q = 0.5 * (c->Q());\n Eigen::VectorXd b = c->b();\n\n \/\/ Check for square matrices\n DRAKE_ASSERT(Q.rows() == Q.cols());\n \/\/ Check for symmetric matrices\n DRAKE_ASSERT(Q.transpose() == Q);\n \/\/ Check for Quadratic and Linear Cost dimensions\n DRAKE_ASSERT(Q.rows() == num_constraint_vars);\n DRAKE_ASSERT(b.cols() == 1);\n DRAKE_ASSERT(b.rows() == num_constraint_vars);\n\n \/\/ adding each Q term (only upper triangular)\n for (size_t i = 0; i < num_constraint_vars; i++) {\n for (size_t j = i; j < num_constraint_vars; j++) {\n if (std::abs(Q(i, j)) > sparseness_threshold) {\n row_ind = i + start_row;\n col_ind = j + start_row;\n \/\/ TODO(naveenoid) : Port to batch addition mode of this function\n \/\/ by utilising the Upper right (or lower left) triangular matrix.\n \/\/ The single element addition method used below is recommended\n \/\/ initiall by Gurobi since it has a low cost\n individual_quadratic_cost_value = Q(i, j);\n error = GRBaddqpterms(model, 1, &row_ind, &col_ind,\n &individual_quadratic_cost_value);\n }\n }\n }\n GRBsetdblattrarray(model, \"Obj\", start_row, num_constraint_vars, b.data());\n start_row = start_row + Q.rows();\n }\n\n \/\/ TODO(naveenoid) : needs test coverage\n for (auto const& binding : prog.linear_equality_constraints()) {\n auto const& c = binding.constraint();\n myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_EQUAL, 1e-18);\n }\n\n for (auto const& binding : prog.linear_constraints()) {\n auto const& c = binding.constraint();\n\n if (c->lower_bound() !=\n -Eigen::MatrixXd::Constant((c->lower_bound()).rows(), 1,\n std::numeric_limits::infinity())) {\n myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_GREATER_EQUAL,\n 1e-18);\n }\n if (c->upper_bound() !=\n Eigen::MatrixXd::Constant((c->upper_bound()).rows(), 1,\n std::numeric_limits::infinity())) {\n myGRBaddconstrs(model, c->A(), c->upper_bound(), GRB_LESS_EQUAL, 1e-18);\n }\n }\n\n SolutionResult result = SolutionResult::kSolutionFound;\n\n error = GRBoptimize(model);\n\n int optimstatus;\n double objval;\n\n if (error) {\n \/\/ TODO(naveenoid) : log error message using GRBgeterrormsg(env)\n result = SolutionResult::kInvalidInput;\n } else {\n error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);\n error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);\n\n if (optimstatus != GRB_OPTIMAL) {\n if (optimstatus == GRB_INF_OR_UNBD) {\n result = SolutionResult::kInfeasibleConstraints;\n } else {\n result = SolutionResult::kUnknownError;\n }\n }\n }\n\n Eigen::VectorXd sol_vector = Eigen::VectorXd::Zero(num_vars);\n\n GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, num_vars, sol_vector.data());\n prog.SetDecisionVariableValues(sol_vector);\n\n prog.SetSolverResult(\"Gurobi\", 0);\n\n GRBfreemodel(model);\n GRBfreeenv(env);\n\n return result;\n}\n\n} \/\/ namespace drake\n} \/\/ namespace solvers\ninitialization of some variables#include \"GurobiSolver.h\"\n\n#include \n#include \"gurobi_c++.h\"\n\n#include \"Optimization.h\"\n#include \"drake\/common\/drake_assert.h\"\n\nnamespace drake {\nnamespace solvers {\n\nbool GurobiSolver::available() const { return true; }\n\n\/\/ TODO(naveenoid): This is currently largely copy-pasta from the deprecated\n\/\/ Gurobi wrapper in solvers. Utilise sparsity in the constraint matrices,\n\/\/ i.e. Something like :\n\/\/ Eigen::SparseMatrix sparseA(A.sparseView());\n\/\/ sparseA.makeCompressed();\n\/\/ error = GRBaddconstrs(model, A.rows(), sparseA.nonZeros(),\n\/\/ sparseA.InnerIndices(), sparseA.OuterStarts(),\n\/\/ sparseA.Values(),sense, b.data(), NULL);\n\/\/ return(error);\n\ntemplate \nint myGRBaddconstrs(GRBmodel* model, Eigen::MatrixBase const& A,\n Eigen::MatrixBase const& b, char sense,\n double sparseness_threshold = 1e-14) {\n int error = 0, nnz = 0;\n\n std::vector cind(A.cols(), 0);\n std::vector cval(A.cols(), 0.0);\n\n for (size_t i = 0; i < A.rows(); i++) {\n nnz = 0;\n for (size_t j = 0; j < A.cols(); j++) {\n if (std::abs(A(i, j)) > sparseness_threshold) {\n cval[nnz] = A(i, j);\n cind[nnz++] = j;\n }\n }\n error = GRBaddconstr(model, nnz, &cind[0], &cval[0], sense, b(i), NULL);\n if (error) break;\n }\n return error;\n}\n\nSolutionResult GurobiSolver::Solve(OptimizationProblem& prog) const {\n \/\/ We only process quadratic costs and linear \/ bounding box\n \/\/ constraints\n\n GRBenv* env = NULL;\n GRBloadenv(&env, NULL);\n \/\/ Corresponds to no console or file logging.\n GRBsetintparam(env, GRB_INT_PAR_OUTPUTFLAG, 0);\n\n DRAKE_ASSERT(prog.generic_costs().empty());\n DRAKE_ASSERT(prog.generic_constraints().empty());\n\n Eigen::VectorXd solution(prog.num_vars());\n int num_vars = prog.num_vars();\n\n \/\/ bound constraints\n std::vector xlow(num_vars, -std::numeric_limits::infinity());\n std::vector xupp(num_vars, std::numeric_limits::infinity());\n\n for (auto const& binding : prog.bounding_box_constraints()) {\n auto const& c = binding.constraint();\n const Eigen::VectorXd& lower_bound = c->lower_bound();\n const Eigen::VectorXd& upper_bound = c->upper_bound();\n for (const DecisionVariableView& v : binding.variable_list()) {\n for (size_t k = 0; k < v.size(); k++) {\n const int idx = v.index() + k;\n xlow[idx] = std::max(lower_bound(k), xlow[idx]);\n xupp[idx] = std::min(upper_bound(k), xupp[idx]);\n }\n }\n }\n\n int error = 0;\n GRBmodel* model = NULL;\n double sparseness_threshold = 1e-14;\n\n GRBnewmodel(env, &model, \"QP\", num_vars, NULL, &xlow[0], &xupp[0], NULL,\n NULL);\n\n int start_row = 0;\n int num_constraint_vars = 0;\n double individual_quadratic_cost_value = 0.0;\n int row_ind = 0, col_ind = 0;\n\n for (auto const& binding : prog.quadratic_costs()) {\n auto const& c = binding.constraint();\n\n num_constraint_vars = binding.GetNumElements();\n\n Eigen::MatrixXd Q = 0.5 * (c->Q());\n Eigen::VectorXd b = c->b();\n\n \/\/ Check for square matrices\n DRAKE_ASSERT(Q.rows() == Q.cols());\n \/\/ Check for symmetric matrices\n DRAKE_ASSERT(Q.transpose() == Q);\n \/\/ Check for Quadratic and Linear Cost dimensions\n DRAKE_ASSERT(Q.rows() == num_constraint_vars);\n DRAKE_ASSERT(b.cols() == 1);\n DRAKE_ASSERT(b.rows() == num_constraint_vars);\n\n \/\/ adding each Q term (only upper triangular)\n for (size_t i = 0; i < num_constraint_vars; i++) {\n for (size_t j = i; j < num_constraint_vars; j++) {\n if (std::abs(Q(i, j)) > sparseness_threshold) {\n row_ind = i + start_row;\n col_ind = j + start_row;\n \/\/ TODO(naveenoid) : Port to batch addition mode of this function\n \/\/ by utilising the Upper right (or lower left) triangular matrix.\n \/\/ The single element addition method used below is recommended\n \/\/ initiall by Gurobi since it has a low cost\n individual_quadratic_cost_value = Q(i, j);\n error = GRBaddqpterms(model, 1, &row_ind, &col_ind,\n &individual_quadratic_cost_value);\n }\n }\n }\n GRBsetdblattrarray(model, \"Obj\", start_row, num_constraint_vars, b.data());\n start_row = start_row + Q.rows();\n }\n\n \/\/ TODO(naveenoid) : needs test coverage\n for (auto const& binding : prog.linear_equality_constraints()) {\n auto const& c = binding.constraint();\n myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_EQUAL, 1e-18);\n }\n\n for (auto const& binding : prog.linear_constraints()) {\n auto const& c = binding.constraint();\n\n if (c->lower_bound() !=\n -Eigen::MatrixXd::Constant((c->lower_bound()).rows(), 1,\n std::numeric_limits::infinity())) {\n myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_GREATER_EQUAL,\n 1e-18);\n }\n if (c->upper_bound() !=\n Eigen::MatrixXd::Constant((c->upper_bound()).rows(), 1,\n std::numeric_limits::infinity())) {\n myGRBaddconstrs(model, c->A(), c->upper_bound(), GRB_LESS_EQUAL, 1e-18);\n }\n }\n\n SolutionResult result = SolutionResult::kSolutionFound;\n\n error = GRBoptimize(model);\n\n int optimstatus = 0;\n double objval = 0.0;\n\n if (error) {\n \/\/ TODO(naveenoid) : log error message using GRBgeterrormsg(env)\n result = SolutionResult::kInvalidInput;\n } else {\n error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);\n error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);\n\n if (optimstatus != GRB_OPTIMAL) {\n if (optimstatus == GRB_INF_OR_UNBD) {\n result = SolutionResult::kInfeasibleConstraints;\n } else {\n result = SolutionResult::kUnknownError;\n }\n }\n }\n\n Eigen::VectorXd sol_vector = Eigen::VectorXd::Zero(num_vars);\n\n GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, num_vars, sol_vector.data());\n prog.SetDecisionVariableValues(sol_vector);\n\n prog.SetSolverResult(\"Gurobi\", 0);\n\n GRBfreemodel(model);\n GRBfreeenv(env);\n\n return result;\n}\n\n} \/\/ namespace drake\n} \/\/ namespace solvers\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"xwalk\/application\/browser\/application_protocols.h\"\n\n#include \n#include \n#include \n\n#include \"base\/files\/file_path.h\"\n#include \"base\/memory\/weak_ptr.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"base\/threading\/worker_pool.h\"\n#include \"base\/threading\/sequenced_worker_pool.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/resource_request_info.h\"\n#include \"url\/url_util.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/http\/http_response_info.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#include \"xwalk\/application\/common\/application_data.h\"\n#include \"xwalk\/application\/common\/application_file_util.h\"\n#include \"xwalk\/application\/common\/application_manifest_constants.h\"\n#include \"xwalk\/application\/common\/application_resource.h\"\n#include \"xwalk\/application\/common\/constants.h\"\n#include \"xwalk\/application\/common\/manifest_handlers\/main_document_handler.h\"\n\nusing content::ResourceRequestInfo;\nusing xwalk::application::ApplicationData;\nusing xwalk::application::MainDocumentInfo;\nnamespace keys = xwalk::application_manifest_keys;\n\nnamespace {\n\nnet::HttpResponseHeaders* BuildHttpHeaders(\n const std::string& mime_type, const std::string& method,\n const base::FilePath& file_path, const base::FilePath& relative_path,\n bool is_authority_match) {\n std::string raw_headers;\n if (method == \"GET\") {\n if (relative_path.empty())\n raw_headers.append(\"HTTP\/1.1 400 Bad Request\");\n else if (!is_authority_match)\n raw_headers.append(\"HTTP\/1.1 403 Forbidden\");\n else if (file_path.empty())\n raw_headers.append(\"HTTP\/1.1 404 Not Found\");\n else\n raw_headers.append(\"HTTP\/1.1 200 OK\");\n } else {\n raw_headers.append(\"HTTP\/1.1 501 Not Implemented\");\n }\n\n raw_headers.append(1, '\\0');\n raw_headers.append(\"Access-Control-Allow-Origin: *\");\n\n if (!mime_type.empty()) {\n raw_headers.append(1, '\\0');\n raw_headers.append(\"Content-Type: \");\n raw_headers.append(mime_type);\n }\n\n raw_headers.append(2, '\\0');\n return new net::HttpResponseHeaders(raw_headers);\n}\n\nclass GeneratedMainDocumentJob: public net::URLRequestSimpleJob {\n public:\n GeneratedMainDocumentJob(\n net::URLRequest* request,\n net::NetworkDelegate* network_delegate,\n const base::FilePath& relative_path,\n const scoped_refptr application)\n : net::URLRequestSimpleJob(request, network_delegate),\n application_(application),\n mime_type_(\"text\/html\"),\n relative_path_(relative_path) {\n }\n\n \/\/ Overridden from URLRequestSimpleJob:\n virtual int GetData(std::string* mime_type,\n std::string* charset,\n std::string* data,\n const net::CompletionCallback& callback) const OVERRIDE {\n *mime_type = mime_type_;\n *charset = \"utf-8\";\n *data = \"\\n\\n\";\n\n MainDocumentInfo* main_info = xwalk::application::ToMainDocumentInfo(\n application_->GetManifestData(keys::kAppMainKey));\n const std::vector& main_scripts = main_info->GetMainScripts();\n for (size_t i = 0; i < main_scripts.size(); ++i) {\n *data += \"