{"text":"\/*\n * DISTRHO Plugin Framework (DPF)\n * Copyright (C) 2012-2019 Filipe Coelho \n *\n * Permission to use, copy, modify, and\/or distribute this software for any purpose with\n * or without fee is hereby granted, provided that the above copyright notice and this\n * permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\n * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN\n * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER\n * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef DISTRHO_PLUGIN_UTILS_HPP_INCLUDED\n#define DISTRHO_PLUGIN_UTILS_HPP_INCLUDED\n\n#include \"DistrhoPlugin.hpp\"\n\nSTART_NAMESPACE_DISTRHO\n\n\/\/ -----------------------------------------------------------------------------------------------------------\n\n\/**\n Handy class to help keep audio buffer in sync with incoming MIDI events.\n To use it, create a local variable (on the stack) and call nextEvent() until it returns false.\n @code\n for (AudioMidiSyncHelper amsh(outputs, frames, midiEvents, midiEventCount); amsh.nextEvent();)\n {\n float* const outL = amsh.outputs[0];\n float* const outR = amsh.outputs[1];\n\n for (uint32_t i=0; i= totalFramesUsed,\n firstEventFrame, totalFramesUsed, false);\n\n midiEventCount = 1;\n while (midiEventCount < remainingMidiEventCount)\n {\n if (midiEvents[midiEventCount].frame == firstEventFrame)\n ++midiEventCount;\n else\n break;\n }\n\n frames = firstEventFrame - totalFramesUsed;\n remainingFrames -= frames;\n remainingMidiEventCount -= midiEventCount;\n totalFramesUsed += frames;\n return true;\n }\n\nprivate:\n \/** @internal *\/\n uint32_t remainingFrames;\n uint32_t remainingMidiEventCount;\n uint32_t totalFramesUsed;\n};\n\n\/\/ -----------------------------------------------------------------------------------------------------------\n\nEND_NAMESPACE_DISTRHO\n\n#endif \/\/ DISTRHO_PLUGIN_UTILS_HPP_INCLUDED\nChange AudioMidiSyncHelper to be a struct\/*\n * DISTRHO Plugin Framework (DPF)\n * Copyright (C) 2012-2019 Filipe Coelho \n *\n * Permission to use, copy, modify, and\/or distribute this software for any purpose with\n * or without fee is hereby granted, provided that the above copyright notice and this\n * permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\n * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN\n * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER\n * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef DISTRHO_PLUGIN_UTILS_HPP_INCLUDED\n#define DISTRHO_PLUGIN_UTILS_HPP_INCLUDED\n\n#include \"DistrhoPlugin.hpp\"\n\nSTART_NAMESPACE_DISTRHO\n\n\/\/ -----------------------------------------------------------------------------------------------------------\n\n\/**\n Handy class to help keep audio buffer in sync with incoming MIDI events.\n To use it, create a local variable (on the stack) and call nextEvent() until it returns false.\n @code\n for (AudioMidiSyncHelper amsh(outputs, frames, midiEvents, midiEventCount); amsh.nextEvent();)\n {\n float* const outL = amsh.outputs[0];\n float* const outR = amsh.outputs[1];\n\n for (uint32_t i=0; i= totalFramesUsed,\n firstEventFrame, totalFramesUsed, false);\n\n midiEventCount = 1;\n while (midiEventCount < remainingMidiEventCount)\n {\n if (midiEvents[midiEventCount].frame == firstEventFrame)\n ++midiEventCount;\n else\n break;\n }\n\n frames = firstEventFrame - totalFramesUsed;\n remainingFrames -= frames;\n remainingMidiEventCount -= midiEventCount;\n totalFramesUsed += frames;\n return true;\n }\n\nprivate:\n \/** @internal *\/\n uint32_t remainingFrames;\n uint32_t remainingMidiEventCount;\n uint32_t totalFramesUsed;\n};\n\n\/\/ -----------------------------------------------------------------------------------------------------------\n\nEND_NAMESPACE_DISTRHO\n\n#endif \/\/ DISTRHO_PLUGIN_UTILS_HPP_INCLUDED\n<|endoftext|>"} {"text":"\/*\r\n * about_dialog.cpp\r\n * PHD Guiding\r\n *\r\n * Created by Sylvain Girard.\r\n * Copyright (c) 2013 Sylvain Girard.\r\n * All rights reserved.\r\n *\r\n * This source code is distributed under the following \"BSD\" license\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * Neither the name of Craig Stark, Stark Labs nor the names of its\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *\/\r\n\r\n#include \"phd.h\"\r\n#include \"about_dialog.h\"\r\n#include \r\n#include \r\n\r\nBEGIN_EVENT_TABLE(AboutDialog, wxDialog)\r\n EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)\r\nEND_EVENT_TABLE()\r\n\r\nAboutDialog::AboutDialog(void) :\r\nwxDialog(pFrame, wxID_ANY, _T(\"About \") APPNAME, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)\r\n{\r\n SetBackgroundColour(*wxWHITE);\r\n\r\n wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);\r\n\r\n #include \"icons\/phd2_64.png.h\"\r\n wxBitmap phd2(wxBITMAP_PNG_FROM_DATA(phd2_64));\r\n wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, phd2);\r\n\r\n wxFileSystem::AddHandler(new wxMemoryFSHandler);\r\n wxMemoryFSHandler::AddFile(\"about.html\", wxString::Format(\r\n \"\"\r\n \"

%s %s<\/h3>\"\r\n \"PHD2 home page - openphdguiding.org<\/a>
\"\r\n \"
PHD2 open source project page<\/a>

\"\r\n \"\"\r\n \"Credits:
\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"
Craig Stark<\/td>\"\r\n \"Bret McKee<\/td>\"\r\n \"<\/tr>\"\r\n \"
Andy Galasso<\/td>\"\r\n \"Bernhard Reutner-Fischer<\/td>\"\r\n \"<\/tr>\"\r\n \"
Stefan Elste<\/td>\"\r\n \"Geoffrey Hausheer<\/td>\"\r\n \"<\/tr>\"\r\n \"
Jared Wellman<\/td>\"\r\n \"John Wainwright<\/td>\"\r\n \"<\/tr>\"\r\n \"
Sylvain Girard<\/td>\"\r\n \"Bruce Waddington<\/td>\"\r\n \"<\/tr>\"\r\n \"
Max Chen<\/td>\"\r\n \"Carsten Przygoda<\/td>\"\r\n \"<\/tr>\"\r\n \"
Hans Lambermont<\/td>\"\r\n \"David Ault<\/td>\"\r\n \"<\/tr>\"\r\n \"
Markus Wieczorek<\/td>\"\r\n \"Linkage<\/td>\"\r\n \"<\/tr>\"\r\n \"
Robin Glover<\/td>\"\r\n \"Patrick Chevalley<\/td>\"\r\n \"<\/tr>\"\r\n \"
Scott Edwards<\/td>\"\r\n \"Eiji Kaneshige<\/td>\"\r\n \"<\/tr>\"\r\n \"
Konstantin Menshikoff   <\/td>\"\r\n \"Jakub Bartas<\/td>\"\r\n \"<\/tr>\"\r\n \"
Javier R<\/td>\"\r\n \"Oleh Malyi<\/td>\"\r\n \"<\/tr>\"\r\n \"
Tsung-Chi Wu<\/td>\"\r\n \"Raffi Enficiaud<\/td>\"\r\n \"<\/tr>\"\r\n \"
Sabin Fota<\/td>\"\r\n \"Dylan O'Donnell<\/td>\"\r\n \"<\/tr>\"\r\n \"
Katsuhiro Kojima<\/td>\"\r\n \"Simon Taylor<\/td>\"\r\n \"<\/tr>\"\r\n \"
Hallgeir Holien<\/td>\"\r\n \"Laurent Schmitz<\/td>\"\r\n \"<\/tr>\"\r\n \"
Atushi Sakauchi<\/td>\"\r\n \"Giorgio Mazzacurati<\/td>\"\r\n \"<\/tr>\"\r\n \"
G\\u00FCnter Scholz<\/td>\"\r\n \"Ray Gralak<\/td>\"\r\n \"<\/tr>\"\r\n \"
Khalefa Algadi<\/td>\"\r\n \"David C. Partridge<\/td>\"\r\n \"<\/tr>\"\r\n \"
Matteo Ghellere<\/td>\"\r\n \"norma<\/td>\"\r\n \"
Edgar D. Klenske<\/td>\"\r\n \"Bernhard Schölkopf<\/td>\"\r\n \"<\/tr>\"\r\n \"
Philipp Hennig<\/td>\"\r\n \"Stephan Wenninger<\/td>\"\r\n \"<\/tr>\"\r\n \"
Wagner Trindade<\/td>\"\r\n \"Cyril Richard<\/td>\"\r\n \"<\/tr>\"\r\n \"<\/table>
\"\r\n \"
\"\r\n \"
\"\r\n \"Copyright 2006-2013 Craig Stark
\"\r\n \"Copyright 2009 Geoffrey Hausheer
\"\r\n \"Copyright 2012-2013 Bret McKee
\"\r\n \"Copyright 2013 Sylvain Girard
\"\r\n \"Copyright 2013-2017 Andy Galasso
\"\r\n \"Copyright 2013-2017 Bruce Waddington
\"\r\n \"Copyright 2014 Hans Lambermont
\"\r\n \"Copyright 2014 Robin Glover
\"\r\n \"Copyright 2014-2017 Max Planck Society
\"\r\n \"
\"\r\n \"
\"\r\n \"The Predictive PEC guide algorithm is based on
\"\r\n \"Gaussian Process Based Predictive Control
for Periodic Error Correction<\/a>\"\r\n \"<\/font>\"\r\n \"<\/body><\/html>\", APPNAME, FULLVER));\r\n wxHtmlWindow *pHtml;\r\n pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(380, 540), wxHW_SCROLLBAR_AUTO);\r\n pHtml->SetBorders(0);\r\n pHtml->LoadPage(\"memory:about.html\");\r\n pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());\r\n\r\n pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));\r\n pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));\r\n\r\n wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);\r\n pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());\r\n pTopLevelSizer->Add(CreateButtonSizer(wxOK), wxSizerFlags(0).Expand().Border(wxALL, 10));\r\n SetSizerAndFit(pTopLevelSizer);\r\n}\r\n\r\nAboutDialog::~AboutDialog(void)\r\n{\r\n wxMemoryFSHandler::RemoveFile(\"about.html\");\r\n}\r\n\r\nvoid AboutDialog::OnLink(wxHtmlLinkEvent & event)\r\n{\r\n wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());\r\n}\r\nadd Mattia Verga to About dialog\/*\r\n * about_dialog.cpp\r\n * PHD Guiding\r\n *\r\n * Created by Sylvain Girard.\r\n * Copyright (c) 2013 Sylvain Girard.\r\n * All rights reserved.\r\n *\r\n * This source code is distributed under the following \"BSD\" license\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * Neither the name of Craig Stark, Stark Labs nor the names of its\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *\/\r\n\r\n#include \"phd.h\"\r\n#include \"about_dialog.h\"\r\n#include \r\n#include \r\n\r\nBEGIN_EVENT_TABLE(AboutDialog, wxDialog)\r\n EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)\r\nEND_EVENT_TABLE()\r\n\r\nAboutDialog::AboutDialog(void) :\r\nwxDialog(pFrame, wxID_ANY, _T(\"About \") APPNAME, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)\r\n{\r\n SetBackgroundColour(*wxWHITE);\r\n\r\n wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);\r\n\r\n #include \"icons\/phd2_64.png.h\"\r\n wxBitmap phd2(wxBITMAP_PNG_FROM_DATA(phd2_64));\r\n wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, phd2);\r\n\r\n wxFileSystem::AddHandler(new wxMemoryFSHandler);\r\n wxMemoryFSHandler::AddFile(\"about.html\", wxString::Format(\r\n \"\"\r\n \"

%s %s<\/h3>\"\r\n \"PHD2 home page - openphdguiding.org<\/a>
\"\r\n \"
PHD2 open source project page<\/a>

\"\r\n \"\"\r\n \"Credits:
\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"\"\r\n \"
Craig Stark<\/td>\"\r\n \"Bret McKee<\/td>\"\r\n \"<\/tr>\"\r\n \"
Andy Galasso<\/td>\"\r\n \"Bernhard Reutner-Fischer<\/td>\"\r\n \"<\/tr>\"\r\n \"
Stefan Elste<\/td>\"\r\n \"Geoffrey Hausheer<\/td>\"\r\n \"<\/tr>\"\r\n \"
Jared Wellman<\/td>\"\r\n \"John Wainwright<\/td>\"\r\n \"<\/tr>\"\r\n \"
Sylvain Girard<\/td>\"\r\n \"Bruce Waddington<\/td>\"\r\n \"<\/tr>\"\r\n \"
Max Chen<\/td>\"\r\n \"Carsten Przygoda<\/td>\"\r\n \"<\/tr>\"\r\n \"
Hans Lambermont<\/td>\"\r\n \"David Ault<\/td>\"\r\n \"<\/tr>\"\r\n \"
Markus Wieczorek<\/td>\"\r\n \"Linkage<\/td>\"\r\n \"<\/tr>\"\r\n \"
Robin Glover<\/td>\"\r\n \"Patrick Chevalley<\/td>\"\r\n \"<\/tr>\"\r\n \"
Scott Edwards<\/td>\"\r\n \"Eiji Kaneshige<\/td>\"\r\n \"<\/tr>\"\r\n \"
Konstantin Menshikoff   <\/td>\"\r\n \"Jakub Bartas<\/td>\"\r\n \"<\/tr>\"\r\n \"
Javier R<\/td>\"\r\n \"Oleh Malyi<\/td>\"\r\n \"<\/tr>\"\r\n \"
Tsung-Chi Wu<\/td>\"\r\n \"Raffi Enficiaud<\/td>\"\r\n \"<\/tr>\"\r\n \"
Sabin Fota<\/td>\"\r\n \"Dylan O'Donnell<\/td>\"\r\n \"<\/tr>\"\r\n \"
Katsuhiro Kojima<\/td>\"\r\n \"Simon Taylor<\/td>\"\r\n \"<\/tr>\"\r\n \"
Hallgeir Holien<\/td>\"\r\n \"Laurent Schmitz<\/td>\"\r\n \"<\/tr>\"\r\n \"
Atushi Sakauchi<\/td>\"\r\n \"Giorgio Mazzacurati<\/td>\"\r\n \"<\/tr>\"\r\n \"
G\\u00FCnter Scholz<\/td>\"\r\n \"Ray Gralak<\/td>\"\r\n \"<\/tr>\"\r\n \"
Khalefa Algadi<\/td>\"\r\n \"David C. Partridge<\/td>\"\r\n \"<\/tr>\"\r\n \"
Matteo Ghellere<\/td>\"\r\n \"norma<\/td>\"\r\n \"
Edgar D. Klenske<\/td>\"\r\n \"Bernhard Schölkopf<\/td>\"\r\n \"<\/tr>\"\r\n \"
Philipp Hennig<\/td>\"\r\n \"Stephan Wenninger<\/td>\"\r\n \"<\/tr>\"\r\n \"
Wagner Trindade<\/td>\"\r\n \"Cyril Richard<\/td>\"\r\n \"<\/tr>\"\r\n \"
Mattia Verga<\/td>\"\r\n \"<\/td>\"\r\n \"<\/tr>\"\r\n \"<\/table>
\"\r\n \"
\"\r\n \"
\"\r\n \"Copyright 2006-2013 Craig Stark
\"\r\n \"Copyright 2009 Geoffrey Hausheer
\"\r\n \"Copyright 2012-2013 Bret McKee
\"\r\n \"Copyright 2013 Sylvain Girard
\"\r\n \"Copyright 2013-2017 Andy Galasso
\"\r\n \"Copyright 2013-2017 Bruce Waddington
\"\r\n \"Copyright 2014 Hans Lambermont
\"\r\n \"Copyright 2014 Robin Glover
\"\r\n \"Copyright 2014-2017 Max Planck Society
\"\r\n \"
\"\r\n \"
\"\r\n \"The Predictive PEC guide algorithm is based on
\"\r\n \"Gaussian Process Based Predictive Control
for Periodic Error Correction<\/a>\"\r\n \"<\/font>\"\r\n \"<\/body><\/html>\", APPNAME, FULLVER));\r\n wxHtmlWindow *pHtml;\r\n pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(380, 540), wxHW_SCROLLBAR_AUTO);\r\n pHtml->SetBorders(0);\r\n pHtml->LoadPage(\"memory:about.html\");\r\n pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());\r\n\r\n pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));\r\n pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));\r\n\r\n wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);\r\n pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());\r\n pTopLevelSizer->Add(CreateButtonSizer(wxOK), wxSizerFlags(0).Expand().Border(wxALL, 10));\r\n SetSizerAndFit(pTopLevelSizer);\r\n}\r\n\r\nAboutDialog::~AboutDialog(void)\r\n{\r\n wxMemoryFSHandler::RemoveFile(\"about.html\");\r\n}\r\n\r\nvoid AboutDialog::OnLink(wxHtmlLinkEvent & event)\r\n{\r\n wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());\r\n}\r\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2001 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Log$\n * Revision 1.6 2002\/02\/01 22:40:44 peiyongz\n * sane_include\n *\n * Revision 1.5 2001\/05\/11 13:24:57 tng\n * Copyright update.\n *\n * Revision 1.4 2001\/05\/03 16:00:03 tng\n * Schema: samples update with schema\n *\n * Revision 1.3 2000\/10\/10 23:55:53 andyh\n * XMLFormatter patch, contributed by Bill Schindler. Fix problems with\n * output to multi-byte encodings.\n *\n * Revision 1.2 2000\/08\/09 22:20:38 jpolast\n * updates for changes to sax2 core functionality.\n *\n * Revision 1.1 2000\/08\/02 19:16:14 jpolast\n * initial checkin of SAX2Print\n *\n *\n *\/\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \"SAX2Print.hpp\"\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local const data\n\/\/\n\/\/ Note: This is the 'safe' way to do these strings. If you compiler supports\n\/\/ L\"\" style strings, and portability is not a concern, you can use\n\/\/ those types constants directly.\n\/\/ ---------------------------------------------------------------------------\nstatic const XMLCh gEndElement[] = { chOpenAngle, chForwardSlash, chNull };\nstatic const XMLCh gEndPI[] = { chQuestion, chCloseAngle, chNull };\nstatic const XMLCh gStartPI[] = { chOpenAngle, chQuestion, chNull };\nstatic const XMLCh gXMLDecl1[] =\n{\n chOpenAngle, chQuestion, chLatin_x, chLatin_m, chLatin_l\n , chSpace, chLatin_v, chLatin_e, chLatin_r, chLatin_s, chLatin_i\n , chLatin_o, chLatin_n, chEqual, chDoubleQuote, chDigit_1, chPeriod\n , chDigit_0, chDoubleQuote, chSpace, chLatin_e, chLatin_n, chLatin_c\n , chLatin_o, chLatin_d, chLatin_i, chLatin_n, chLatin_g, chEqual\n , chDoubleQuote, chNull\n};\n\nstatic const XMLCh gXMLDecl2[] =\n{\n chDoubleQuote, chQuestion, chCloseAngle\n , chLF, chNull\n};\n\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAX2PrintHandlers: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nSAX2PrintHandlers::SAX2PrintHandlers( const char* const encodingName\n , const XMLFormatter::UnRepFlags unRepFlags\n\t\t\t\t\t\t\t\t\t, const bool\t\t\t\t\t expandNamespaces) :\n\n fFormatter\n (\n encodingName\n , this\n , XMLFormatter::NoEscapes\n , unRepFlags\n ),\n\tfExpandNS ( expandNamespaces )\n{\n \/\/\n \/\/ Go ahead and output an XML Decl with our known encoding. This\n \/\/ is not the best answer, but its the best we can do until we\n \/\/ have SAX2 support.\n \/\/\n fFormatter << gXMLDecl1 << fFormatter.getEncodingName() << gXMLDecl2;\n}\n\nSAX2PrintHandlers::~SAX2PrintHandlers()\n{\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAX2PrintHandlers: Overrides of the output formatter target interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAX2PrintHandlers::writeChars(const XMLByte* const toWrite)\n{\n}\n\nvoid SAX2PrintHandlers::writeChars(const XMLByte* const toWrite,\n const unsigned int count,\n XMLFormatter* const formatter)\n{\n \/\/ For this one, just dump them to the standard output\n \/\/ Surprisingly, Solaris was the only platform on which\n \/\/ required the char* cast to print out the string correctly.\n \/\/ Without the cast, it was printing the pointer value in hex.\n \/\/ Quite annoying, considering every other platform printed\n \/\/ the string with the explicit cast to char* below.\n cout.write((char *) toWrite, (int) count);\n\tcout.flush();\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAX2PrintHandlers: Overrides of the SAX ErrorHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAX2PrintHandlers::error(const SAXParseException& e)\n{\n cerr << \"\\nError at file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"\\n Message: \" << StrX(e.getMessage()) << endl;\n}\n\nvoid SAX2PrintHandlers::fatalError(const SAXParseException& e)\n{\n cerr << \"\\nFatal Error at file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"\\n Message: \" << StrX(e.getMessage()) << endl;\n}\n\nvoid SAX2PrintHandlers::warning(const SAXParseException& e)\n{\n cerr << \"\\nWarning at file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"\\n Message: \" << StrX(e.getMessage()) << endl;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAX2PrintHandlers: Overrides of the SAX DTDHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAX2PrintHandlers::unparsedEntityDecl(const XMLCh* const name\n , const XMLCh* const publicId\n , const XMLCh* const systemId\n , const XMLCh* const notationName)\n{\n \/\/ Not used at this time\n}\n\n\nvoid SAX2PrintHandlers::notationDecl(const XMLCh* const name\n , const XMLCh* const publicId\n , const XMLCh* const systemId)\n{\n \/\/ Not used at this time\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAX2PrintHandlers: Overrides of the SAX DocumentHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAX2PrintHandlers::characters(const XMLCh* const chars\n , const unsigned int length)\n{\n fFormatter.formatBuf(chars, length, XMLFormatter::CharEscapes);\n}\n\n\nvoid SAX2PrintHandlers::endDocument()\n{\n}\n\n\nvoid SAX2PrintHandlers::endElement(const XMLCh* const uri,\n\t\t\t\t\t\t\t\t const XMLCh* const localname,\n\t\t\t\t\t\t\t\t const XMLCh* const qname)\n{\n \/\/ No escapes are legal here\n fFormatter << XMLFormatter::NoEscapes << gEndElement ;\n\tif ( fExpandNS )\n\t{\n\t\tif (XMLString::compareIString(uri,XMLUni::fgEmptyString) != 0)\n\t\t\t\tfFormatter << uri << chColon;\n\t\tfFormatter << localname << chCloseAngle;\n\t}\n\telse\n\t\tfFormatter << qname << chCloseAngle;\n}\n\n\nvoid SAX2PrintHandlers::ignorableWhitespace( const XMLCh* const chars\n ,const unsigned int length)\n{\n fFormatter.formatBuf(chars, length, XMLFormatter::NoEscapes);\n}\n\n\nvoid SAX2PrintHandlers::processingInstruction(const XMLCh* const target\n , const XMLCh* const data)\n{\n fFormatter << XMLFormatter::NoEscapes << gStartPI << target;\n if (data)\n fFormatter << chSpace << data;\n fFormatter << XMLFormatter::NoEscapes << gEndPI;\n}\n\n\nvoid SAX2PrintHandlers::startDocument()\n{\n}\n\n\nvoid SAX2PrintHandlers::startElement(const XMLCh* const uri,\n\t\t\t\t\t\t\t\t\tconst XMLCh* const localname,\n\t\t\t\t\t\t\t\t\tconst XMLCh* const qname,\n const Attributes&\t\tattributes)\n{\n \/\/ The name has to be representable without any escapes\n fFormatter << XMLFormatter::NoEscapes << chOpenAngle ;\n\tif ( fExpandNS )\n\t{\n\t\tif (XMLString::compareIString(uri,XMLUni::fgEmptyString) != 0)\n\t\t\t\tfFormatter << uri << chColon;\n\t\tfFormatter << localname ;\n\t}\n\telse\n\t\tfFormatter << qname ;\n\n unsigned int len = attributes.getLength();\n for (unsigned int index = 0; index < len; index++)\n {\n \/\/\n \/\/ Again the name has to be completely representable. But the\n \/\/ attribute can have refs and requires the attribute style\n \/\/ escaping.\n \/\/\n fFormatter << XMLFormatter::NoEscapes << chSpace ;\n\t\tif ( fExpandNS )\n\t\t{\n\t\t\tif (XMLString::compareIString(attributes.getURI(index),XMLUni::fgEmptyString) != 0)\n\t\t\t\tfFormatter << attributes.getURI(index) << chColon;\n\t\t\tfFormatter << attributes.getLocalName(index) ;\n\t\t}\n\t\telse\n\t\t\tfFormatter << attributes.getQName(index) ;\n\n\t\tfFormatter << chEqual << chDoubleQuote\n << XMLFormatter::AttrEscapes\n\t\t << attributes.getValue(index)\n << XMLFormatter::NoEscapes\n << chDoubleQuote;\n }\n fFormatter << chCloseAngle;\n}\nXMLUni::fgEmptyString which is defined as \"EMPTY\" is incorrectly used as an empty string, should use XMLUni::fgZeroLenString instead\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2001 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Log$\n * Revision 1.7 2002\/05\/28 20:24:15 tng\n * XMLUni::fgEmptyString which is defined as \"EMPTY\" is incorrectly used as an empty string, should use XMLUni::fgZeroLenString instead\n *\n * Revision 1.6 2002\/02\/01 22:40:44 peiyongz\n * sane_include\n *\n * Revision 1.5 2001\/05\/11 13:24:57 tng\n * Copyright update.\n *\n * Revision 1.4 2001\/05\/03 16:00:03 tng\n * Schema: samples update with schema\n *\n * Revision 1.3 2000\/10\/10 23:55:53 andyh\n * XMLFormatter patch, contributed by Bill Schindler. Fix problems with\n * output to multi-byte encodings.\n *\n * Revision 1.2 2000\/08\/09 22:20:38 jpolast\n * updates for changes to sax2 core functionality.\n *\n * Revision 1.1 2000\/08\/02 19:16:14 jpolast\n * initial checkin of SAX2Print\n *\n *\n *\/\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \"SAX2Print.hpp\"\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local const data\n\/\/\n\/\/ Note: This is the 'safe' way to do these strings. If you compiler supports\n\/\/ L\"\" style strings, and portability is not a concern, you can use\n\/\/ those types constants directly.\n\/\/ ---------------------------------------------------------------------------\nstatic const XMLCh gEndElement[] = { chOpenAngle, chForwardSlash, chNull };\nstatic const XMLCh gEndPI[] = { chQuestion, chCloseAngle, chNull };\nstatic const XMLCh gStartPI[] = { chOpenAngle, chQuestion, chNull };\nstatic const XMLCh gXMLDecl1[] =\n{\n chOpenAngle, chQuestion, chLatin_x, chLatin_m, chLatin_l\n , chSpace, chLatin_v, chLatin_e, chLatin_r, chLatin_s, chLatin_i\n , chLatin_o, chLatin_n, chEqual, chDoubleQuote, chDigit_1, chPeriod\n , chDigit_0, chDoubleQuote, chSpace, chLatin_e, chLatin_n, chLatin_c\n , chLatin_o, chLatin_d, chLatin_i, chLatin_n, chLatin_g, chEqual\n , chDoubleQuote, chNull\n};\n\nstatic const XMLCh gXMLDecl2[] =\n{\n chDoubleQuote, chQuestion, chCloseAngle\n , chLF, chNull\n};\n\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAX2PrintHandlers: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nSAX2PrintHandlers::SAX2PrintHandlers( const char* const encodingName\n , const XMLFormatter::UnRepFlags unRepFlags\n\t\t\t\t\t\t\t\t\t, const bool\t\t\t\t\t expandNamespaces) :\n\n fFormatter\n (\n encodingName\n , this\n , XMLFormatter::NoEscapes\n , unRepFlags\n ),\n\tfExpandNS ( expandNamespaces )\n{\n \/\/\n \/\/ Go ahead and output an XML Decl with our known encoding. This\n \/\/ is not the best answer, but its the best we can do until we\n \/\/ have SAX2 support.\n \/\/\n fFormatter << gXMLDecl1 << fFormatter.getEncodingName() << gXMLDecl2;\n}\n\nSAX2PrintHandlers::~SAX2PrintHandlers()\n{\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAX2PrintHandlers: Overrides of the output formatter target interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAX2PrintHandlers::writeChars(const XMLByte* const toWrite)\n{\n}\n\nvoid SAX2PrintHandlers::writeChars(const XMLByte* const toWrite,\n const unsigned int count,\n XMLFormatter* const formatter)\n{\n \/\/ For this one, just dump them to the standard output\n \/\/ Surprisingly, Solaris was the only platform on which\n \/\/ required the char* cast to print out the string correctly.\n \/\/ Without the cast, it was printing the pointer value in hex.\n \/\/ Quite annoying, considering every other platform printed\n \/\/ the string with the explicit cast to char* below.\n cout.write((char *) toWrite, (int) count);\n\tcout.flush();\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAX2PrintHandlers: Overrides of the SAX ErrorHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAX2PrintHandlers::error(const SAXParseException& e)\n{\n cerr << \"\\nError at file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"\\n Message: \" << StrX(e.getMessage()) << endl;\n}\n\nvoid SAX2PrintHandlers::fatalError(const SAXParseException& e)\n{\n cerr << \"\\nFatal Error at file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"\\n Message: \" << StrX(e.getMessage()) << endl;\n}\n\nvoid SAX2PrintHandlers::warning(const SAXParseException& e)\n{\n cerr << \"\\nWarning at file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"\\n Message: \" << StrX(e.getMessage()) << endl;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAX2PrintHandlers: Overrides of the SAX DTDHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAX2PrintHandlers::unparsedEntityDecl(const XMLCh* const name\n , const XMLCh* const publicId\n , const XMLCh* const systemId\n , const XMLCh* const notationName)\n{\n \/\/ Not used at this time\n}\n\n\nvoid SAX2PrintHandlers::notationDecl(const XMLCh* const name\n , const XMLCh* const publicId\n , const XMLCh* const systemId)\n{\n \/\/ Not used at this time\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAX2PrintHandlers: Overrides of the SAX DocumentHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAX2PrintHandlers::characters(const XMLCh* const chars\n , const unsigned int length)\n{\n fFormatter.formatBuf(chars, length, XMLFormatter::CharEscapes);\n}\n\n\nvoid SAX2PrintHandlers::endDocument()\n{\n}\n\n\nvoid SAX2PrintHandlers::endElement(const XMLCh* const uri,\n\t\t\t\t\t\t\t\t const XMLCh* const localname,\n\t\t\t\t\t\t\t\t const XMLCh* const qname)\n{\n \/\/ No escapes are legal here\n fFormatter << XMLFormatter::NoEscapes << gEndElement ;\n\tif ( fExpandNS )\n\t{\n\t\tif (XMLString::compareIString(uri,XMLUni::fgZeroLenString) != 0)\n\t\t\t\tfFormatter << uri << chColon;\n\t\tfFormatter << localname << chCloseAngle;\n\t}\n\telse\n\t\tfFormatter << qname << chCloseAngle;\n}\n\n\nvoid SAX2PrintHandlers::ignorableWhitespace( const XMLCh* const chars\n ,const unsigned int length)\n{\n fFormatter.formatBuf(chars, length, XMLFormatter::NoEscapes);\n}\n\n\nvoid SAX2PrintHandlers::processingInstruction(const XMLCh* const target\n , const XMLCh* const data)\n{\n fFormatter << XMLFormatter::NoEscapes << gStartPI << target;\n if (data)\n fFormatter << chSpace << data;\n fFormatter << XMLFormatter::NoEscapes << gEndPI;\n}\n\n\nvoid SAX2PrintHandlers::startDocument()\n{\n}\n\n\nvoid SAX2PrintHandlers::startElement(const XMLCh* const uri,\n\t\t\t\t\t\t\t\t\tconst XMLCh* const localname,\n\t\t\t\t\t\t\t\t\tconst XMLCh* const qname,\n const Attributes&\t\tattributes)\n{\n \/\/ The name has to be representable without any escapes\n fFormatter << XMLFormatter::NoEscapes << chOpenAngle ;\n\tif ( fExpandNS )\n\t{\n\t\tif (XMLString::compareIString(uri,XMLUni::fgZeroLenString) != 0)\n\t\t\t\tfFormatter << uri << chColon;\n\t\tfFormatter << localname ;\n\t}\n\telse\n\t\tfFormatter << qname ;\n\n unsigned int len = attributes.getLength();\n for (unsigned int index = 0; index < len; index++)\n {\n \/\/\n \/\/ Again the name has to be completely representable. But the\n \/\/ attribute can have refs and requires the attribute style\n \/\/ escaping.\n \/\/\n fFormatter << XMLFormatter::NoEscapes << chSpace ;\n\t\tif ( fExpandNS )\n\t\t{\n\t\t\tif (XMLString::compareIString(attributes.getURI(index),XMLUni::fgZeroLenString) != 0)\n\t\t\t\tfFormatter << attributes.getURI(index) << chColon;\n\t\t\tfFormatter << attributes.getLocalName(index) ;\n\t\t}\n\t\telse\n\t\t\tfFormatter << attributes.getQName(index) ;\n\n\t\tfFormatter << chEqual << chDoubleQuote\n << XMLFormatter::AttrEscapes\n\t\t << attributes.getValue(index)\n << XMLFormatter::NoEscapes\n << chDoubleQuote;\n }\n fFormatter << chCloseAngle;\n}\n<|endoftext|>"} {"text":"#include \n#include \"TestRequiringOptions.h\"\n\nint main(int argc, char** argv)\n{\n ::testing::InitGoogleTest(&argc, argv);\n assert(TestRequiringOptions::initFilename(\"Wangscape\/example\/example_options.json\"));\n return RUN_ALL_TESTS();\n}Get the options file from command line args#include \n#include \"TestRequiringOptions.h\"\n\nint main(int argc, char** argv)\n{\n ::testing::InitGoogleTest(&argc, argv);\n std::string filename;\n if (argc < 2)\n filename = std::string(\"Wangscape\/example\/example_options.json\");\n else\n filename = std::string(argv[1]);\n std::cout << \"Using options file at \" << filename << \"\\n\";\n assert(TestRequiringOptions::initFilename(filename));\n return RUN_ALL_TESTS();\n}<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: LayerDialogContent.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 18:33:30 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"LayerDialogContent.hxx\"\n\n#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_\n#include \n#endif\n\n#define ITEMID_COLOR SID_COLOR_TABLE\n\n#include \n#include \n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include \n#endif\n#ifndef _AEITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include \n#endif\n\n#include \"sdattr.hxx\"\n\n#include \"LayerDialog.hrc\"\n#include \"app.hrc\"\n#include \"strings.hrc\"\n#include \"res_bmp.hrc\"\n#include \"sdresid.hxx\"\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"PaneManager.hxx\"\n#include \"ViewShellBase.hxx\"\n#include \"DrawViewShell.hxx\"\n\n\nusing namespace ::com::sun::star;\n\nnamespace sd {\n\n\n\nLayerDialogContent::LayerDialogContent (\n SfxBindings* pInBindings,\n SfxChildWindow *pCW,\n Window* pParent,\n const SdResId& rSdResId,\n ViewShellBase& rBase)\n : SfxDockingWindow (pInBindings, pCW, pParent, rSdResId),\n maLayerTabBar (\n static_cast(\n rBase.GetPaneManager().GetViewShell(PaneManager::PT_CENTER)),\n this,\n SdResId(TB_LAYERS))\n{\n FreeResource();\n\n maLayerTabBar.Show();\n}\n\n\n\n\nLayerDialogContent::~LayerDialogContent (void)\n{\n}\n\n\n\n\nLayerTabBar& LayerDialogContent::GetLayerTabBar (void)\n{\n return maLayerTabBar;\n}\n\n\n\n\nBOOL LayerDialogContent::Close (void)\n{\n return SfxDockingWindow::Close();\n}\n\n\n\n\nvoid LayerDialogContent::Resize (void)\n{\n maLayerTabBar.SetPosSizePixel (\n Point(0,0),\n Size(GetSizePixel().Width(), 17));\n SfxDockingWindow::Resize();\n}\n\n\n} \/\/ end of namespace sd\nINTEGRATION: CWS components1 (1.3.234); FILE MERGED 2006\/09\/25 16:56:15 af 1.3.234.2: RESYNC: (1.3-1.4); FILE MERGED 2006\/08\/22 09:37:29 af 1.3.234.1: #i68075# Transition to new drawing framework.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: LayerDialogContent.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2007-04-03 15:39:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"LayerDialogContent.hxx\"\n\n#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_\n#include \n#endif\n\n#define ITEMID_COLOR SID_COLOR_TABLE\n\n#include \n#include \n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include \n#endif\n#ifndef _AEITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include \n#endif\n\n#include \"sdattr.hxx\"\n\n#include \"LayerDialog.hrc\"\n#include \"app.hrc\"\n#include \"strings.hrc\"\n#include \"res_bmp.hrc\"\n#include \"sdresid.hxx\"\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"ViewShellBase.hxx\"\n#include \"DrawViewShell.hxx\"\n#include \"framework\/FrameworkHelper.hxx\"\n\nusing namespace ::com::sun::star;\n\nnamespace sd {\n\n\n\nLayerDialogContent::LayerDialogContent (\n SfxBindings* pInBindings,\n SfxChildWindow *pCW,\n Window* pParent,\n const SdResId& rSdResId,\n ViewShellBase& rBase)\n : SfxDockingWindow (pInBindings, pCW, pParent, rSdResId),\n maLayerTabBar(\n dynamic_cast(\n framework::FrameworkHelper::Instance(rBase)->GetViewShell(\n framework::FrameworkHelper::msCenterPaneURL).get()),\n this,\n SdResId(TB_LAYERS))\n{\n FreeResource();\n\n maLayerTabBar.Show();\n}\n\n\n\n\nLayerDialogContent::~LayerDialogContent (void)\n{\n}\n\n\n\n\nLayerTabBar& LayerDialogContent::GetLayerTabBar (void)\n{\n return maLayerTabBar;\n}\n\n\n\n\nBOOL LayerDialogContent::Close (void)\n{\n return SfxDockingWindow::Close();\n}\n\n\n\n\nvoid LayerDialogContent::Resize (void)\n{\n maLayerTabBar.SetPosSizePixel (\n Point(0,0),\n Size(GetSizePixel().Width(), 17));\n SfxDockingWindow::Resize();\n}\n\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2009, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Author: Siddharth Choudhary (itzsid@gmail.com)\n *\n *\/\n\n#ifndef PCL_SEARCH_AUTO_TUNED_SEARCH_IMPL\n#define PCL_SEARCH_AUTO_TUNED_SEARCH_IMPL\n\n#include \n#include \n#include \"pcl\/search\/auto.h\"\n#include \"pcl\/search\/kdtree.h\"\n#include \"pcl\/search\/octree.h\"\n#include \"pcl\/search\/organized_neighbor.h\"\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::initSearchDS (int spatial_locator)\n{\n \/\/ specifies the data-structure to be used using spatial_locator flag\n if (spatial_locator == KDTREE)\n \/\/ initialize kdtree\n search_.reset (new KdTree ());\n else if (spatial_locator == ORGANIZED_INDEX)\n search_.reset (new OrganizedNeighbor ());\n else if (spatial_locator == OCTREE)\n search_.reset (new Octree (0.1f));\n else\n PCL_ERROR (\"[pcl::search::AutotunedSearch::initSearchDS] Spatial locator (%d) unknown!\\n\", spatial_locator);\n spatial_loc_ = spatial_locator;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::evaluateSearchMethods (const PointCloudConstPtr& cloud, const int search_type)\n{\n \/\/ Evaluates different search data-structures for the given data and sets it to the ds having minimum time\n\tunsigned int searchIdx;\n while (1)\n {\n searchIdx = rand()%(cloud->width * cloud->height);\n if (cloud->points[searchIdx].z < 100)\n break;\n }\n\n double time_kdtree, time_octree, time_organized_data;\n if (search_type == NEAREST_K_SEARCH)\n {\n unsigned int no_of_neighbors = 20;\n std::vector k_indices;\n k_indices.resize (no_of_neighbors);\n std::vector k_distances;\n k_distances.resize (no_of_neighbors);\n std::cout << \"\\n---------------\\nKDTree\\n---------------\\n\";\n double time1 = getTime ();\n search_.reset (new KdTree ());\n search_->setInputCloud (cloud);\n search_->nearestKSearch (cloud->points[searchIdx], no_of_neighbors, k_indices, k_distances);\n std::cout << \"Neighbors are:\" << std::endl; \n for (int i = 0; i < 20; i++)\n {\n std::cout << k_indices[i] << '\\t'; \n }\n std::cout << std::endl;\n std::cout << \"Number of Neighbors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n\n std::cout << \"\\n---------------\\nOrganizedData\\n---------------\\n\";\n double time2 = getTime ();\n search_.reset (new OrganizedNeighbor());\n search_->setInputCloud (cloud);\n search_->nearestKSearch (cloud->points[searchIdx], no_of_neighbors, k_indices, k_distances);\n std::cout << \"Neighbors are: \" << std::endl;\n for (int i = 0;i < 20; i++)\n {\n std::cout << k_indices[i] << '\\t'; \n }\n std::cout << std::endl;\n std::cout << \"Number of Neigbhors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n\n std::cout << \"\\n---------------\\nOctree\\n---------------\\n\";\n double time3 = getTime ();\n search_.reset (new Octree (0.1f));\n search_->setInputCloud (cloud);\n search_->nearestKSearch (cloud->points[searchIdx], no_of_neighbors, k_indices, k_distances);\n std::cout << \"Neighbors are: \" << std::endl;\n for (int i = 0;i < 20; i++)\n {\n std::cout << k_indices[i] << '\\t'; \n }\n std::cout << std::endl;\n std::cout << \"Number of Neighbors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n std::cout << std::endl;\n std::cout << std::endl;\n\n time_kdtree = time2 - time1;\n time_organized_data = time3 - time2;\n time_octree = getTime () - time3;\n \n std::cout << \"Time Taken: \" << \"KDTree: \" << time_kdtree << '\\t' <<\"OranizedData: \" << time_organized_data << '\\t' << \"Octree: \" << time_octree << '\\t' << std::endl;\n }\n else if (search_type == NEAREST_RADIUS_SEARCH)\n {\n double searchRadius = 1.0 * ((double)rand () \/ (double)RAND_MAX);\n\n std::vector k_indices;\n std::vector k_distances;\n std::cout << \"\\n---------------\\nKDTree\\n---------------\\n\";\n double time1 = getTime ();\n search_.reset (new KdTree ());\n search_->setInputCloud (cloud);\n search_->radiusSearch (cloud->points[searchIdx], searchRadius, k_indices, k_distances);\n std::cout << \"Neighbors are:\" << std::endl;\n\n for(int i = 0;i < 20; ++i)\n {\n std::cout << k_indices[i] << '\\t';\n }\n std::cout << std::endl;\n std::cout << \"Number of Neighbors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n\n std::cout << \"\\n---------------\\nOrganizedData\\n---------------\\n\";\n double time2 = getTime ();\n search_.reset (new OrganizedNeighbor ());\n search_->setInputCloud (cloud);\n search_->radiusSearch (cloud->points[searchIdx], searchRadius, k_indices, k_distances);\n std::cout << \"Neighbors are: \" << std::endl;\n for (int i = 0; i < 20; ++i)\n {\n std::cout << k_indices[i] << '\\t';\n }\n std::cout << std::endl;\n std::cout << \"Number of Neigbhors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n\n std::cout << \"\\n---------------\\nOctree\\n---------------\\n\";\n double time3 = getTime ();\n search_.reset (new Octree (0.1f));\n search_->setInputCloud (cloud);\n search_->radiusSearch (cloud->points[searchIdx], searchRadius, k_indices, k_distances);\n std::cout << \"Neighbors are: \" << std::endl;\n for (int i = 0; i < 20; ++i) \n {\n std::cout << k_indices[i] << '\\t';\n }\n std::cout << std::endl;\n std::cout << \"Number of Neighbors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n std::cout << std::endl;\n std::cout << std::endl;\n\n time_kdtree = time2 - time1;\n time_organized_data = time3 - time2;\n time_octree = getTime () - time3;\n \n std::cout << \"Time Taken: \" << \"KDTree: \" << time_kdtree << '\\t' <<\"OranizedData: \" << time_organized_data << '\\t' << \"Octree: \" << time_octree << '\\t' << std::endl;\t\n }\n else\n {\n PCL_ERROR (\"[pcl::search::AutotunedSearch::evaluateSearchMethods] Only NEAREST_K_SEARCH and NEAREST_RADIUS_SEARCH supported\\n\");\n return (0);\n }\n \/\/ Set the datastructure according to which takes the minimum time\n if (time_kdtree < time_organized_data && time_kdtree < time_octree)\n {\n spatial_loc_ = KDTREE;\n search_.reset (new KdTree ());\n }\n else if (time_octree < time_kdtree && time_octree < time_organized_data)\n {\n spatial_loc_ = OCTREE;\n search_.reset (new Octree (0.1f));\n }\n else if (time_organized_data < time_kdtree && time_organized_data < time_octree)\n {\n spatial_loc_ = OCTREE;\n search_.reset (new OrganizedNeighbor ());\n }\n\/\/ search_->setInputCloud (cloud);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::setInputCloud (const PointCloudConstPtr &cloud, \n const IndicesConstPtr &indices)\n{\n input_ = cloud;\n search_->setInputCloud (cloud, indices);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::setInputCloud (const PointCloudConstPtr& cloud)\n{\n input_ = cloud;\n search_->setInputCloud (cloud);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int \npcl::search::AutotunedSearch::nearestKSearch (const PointT &point,\n int k, \n std::vector &k_indices, \n std::vector &k_sqr_distances) \n{\n return (search_->nearestKSearch (point, k, k_indices, k_sqr_distances));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int \npcl::search::AutotunedSearch::nearestKSearch (const PointCloud &cloud, \n int index, \n int k, \n std::vector &k_indices, \n std::vector &k_sqr_distances) \n{\n return (search_->nearestKSearch (cloud, index, k, k_indices, k_sqr_distances));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int \npcl::search::AutotunedSearch::nearestKSearch (int index, \n int k, \n std::vector &k_indices, \n std::vector &k_sqr_distances)\n{\n return (search_->nearestKSearch (index, k, k_indices, k_sqr_distances));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int\npcl::search::AutotunedSearch::radiusSearch (const PointT &point, \n const double radius, \n std::vector &k_indices, \n std::vector &k_distances, \n int max_nn) const\n{\n return (search_->radiusSearch (point, radius, k_indices, k_distances, max_nn));\n}\n \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int \npcl::search::AutotunedSearch::radiusSearch (const PointCloud &cloud, \n int index, \n double radius,\n std::vector &k_indices, \n std::vector &k_distances,\n int max_nn) \n{\n return (search_->radiusSearch (cloud, index, radius, k_indices, k_distances, max_nn));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int \npcl::search::AutotunedSearch::radiusSearch (int index, \n double radius, \n std::vector &k_indices,\n std::vector &k_distances, \n int max_nn) const\n{\n return (search_->radiusSearch (index, radius, k_indices, k_distances, max_nn));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::approxNearestSearch (const PointCloudConstPtr &cloud_arg, \n int query_index_arg, \n int &result_index_arg,\n float &sqr_distance_arg)\n{\n if(spatial_loc_ == OCTREE)\n search_->approxNearestSearch (cloud_arg, query_index_arg, result_index_arg, sqr_distance_arg);\n else\n PCL_ERROR (\"approxNearestSearch() works only for OCTREE structure\\n\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::approxNearestSearch (const PointT &p_q_arg, \n int &result_index_arg, \n float &sqr_distance_arg)\n{\n if (spatial_loc_ == OCTREE)\n search_->approxNearestSearch (p_q_arg, result_index_arg, sqr_distance_arg);\n else\n PCL_ERROR (\"approxNearestSearch() works only for OCTREE structure\\n\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::approxNearestSearch (int query_index_arg, \n int &result_index_arg, \n float &sqr_distance_arg)\n{\n if (spatial_loc_ == OCTREE)\n search_->approxNearestSearch (query_index_arg, result_index_arg, sqr_distance_arg);\n else\n PCL_ERROR (\"approxNearestSearch() works only for OCTREE structure\\n\");\n}\n\n#define PCL_INSTANTIATE_AutotunedSearch(T) template class PCL_EXPORTS pcl::search::AutotunedSearch;\n\n#endif \/\/#ifndef PCL_SEARCH_AUTO_TUNED_SEARCH_IMPL\nFixing return-statement with a value, in function returning `void'.\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2009, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Author: Siddharth Choudhary (itzsid@gmail.com)\n *\n *\/\n\n#ifndef PCL_SEARCH_AUTO_TUNED_SEARCH_IMPL\n#define PCL_SEARCH_AUTO_TUNED_SEARCH_IMPL\n\n#include \n#include \n#include \"pcl\/search\/auto.h\"\n#include \"pcl\/search\/kdtree.h\"\n#include \"pcl\/search\/octree.h\"\n#include \"pcl\/search\/organized_neighbor.h\"\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::initSearchDS (int spatial_locator)\n{\n \/\/ specifies the data-structure to be used using spatial_locator flag\n if (spatial_locator == KDTREE)\n \/\/ initialize kdtree\n search_.reset (new KdTree ());\n else if (spatial_locator == ORGANIZED_INDEX)\n search_.reset (new OrganizedNeighbor ());\n else if (spatial_locator == OCTREE)\n search_.reset (new Octree (0.1f));\n else\n PCL_ERROR (\"[pcl::search::AutotunedSearch::initSearchDS] Spatial locator (%d) unknown!\\n\", spatial_locator);\n spatial_loc_ = spatial_locator;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::evaluateSearchMethods (const PointCloudConstPtr& cloud, const int search_type)\n{\n \/\/ Evaluates different search data-structures for the given data and sets it to the ds having minimum time\n\tunsigned int searchIdx;\n while (1)\n {\n searchIdx = rand()%(cloud->width * cloud->height);\n if (cloud->points[searchIdx].z < 100)\n break;\n }\n\n double time_kdtree, time_octree, time_organized_data;\n if (search_type == NEAREST_K_SEARCH)\n {\n unsigned int no_of_neighbors = 20;\n std::vector k_indices;\n k_indices.resize (no_of_neighbors);\n std::vector k_distances;\n k_distances.resize (no_of_neighbors);\n std::cout << \"\\n---------------\\nKDTree\\n---------------\\n\";\n double time1 = getTime ();\n search_.reset (new KdTree ());\n search_->setInputCloud (cloud);\n search_->nearestKSearch (cloud->points[searchIdx], no_of_neighbors, k_indices, k_distances);\n std::cout << \"Neighbors are:\" << std::endl; \n for (int i = 0; i < 20; i++)\n {\n std::cout << k_indices[i] << '\\t'; \n }\n std::cout << std::endl;\n std::cout << \"Number of Neighbors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n\n std::cout << \"\\n---------------\\nOrganizedData\\n---------------\\n\";\n double time2 = getTime ();\n search_.reset (new OrganizedNeighbor());\n search_->setInputCloud (cloud);\n search_->nearestKSearch (cloud->points[searchIdx], no_of_neighbors, k_indices, k_distances);\n std::cout << \"Neighbors are: \" << std::endl;\n for (int i = 0;i < 20; i++)\n {\n std::cout << k_indices[i] << '\\t'; \n }\n std::cout << std::endl;\n std::cout << \"Number of Neigbhors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n\n std::cout << \"\\n---------------\\nOctree\\n---------------\\n\";\n double time3 = getTime ();\n search_.reset (new Octree (0.1f));\n search_->setInputCloud (cloud);\n search_->nearestKSearch (cloud->points[searchIdx], no_of_neighbors, k_indices, k_distances);\n std::cout << \"Neighbors are: \" << std::endl;\n for (int i = 0;i < 20; i++)\n {\n std::cout << k_indices[i] << '\\t'; \n }\n std::cout << std::endl;\n std::cout << \"Number of Neighbors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n std::cout << std::endl;\n std::cout << std::endl;\n\n time_kdtree = time2 - time1;\n time_organized_data = time3 - time2;\n time_octree = getTime () - time3;\n \n std::cout << \"Time Taken: \" << \"KDTree: \" << time_kdtree << '\\t' <<\"OranizedData: \" << time_organized_data << '\\t' << \"Octree: \" << time_octree << '\\t' << std::endl;\n }\n else if (search_type == NEAREST_RADIUS_SEARCH)\n {\n double searchRadius = 1.0 * ((double)rand () \/ (double)RAND_MAX);\n\n std::vector k_indices;\n std::vector k_distances;\n std::cout << \"\\n---------------\\nKDTree\\n---------------\\n\";\n double time1 = getTime ();\n search_.reset (new KdTree ());\n search_->setInputCloud (cloud);\n search_->radiusSearch (cloud->points[searchIdx], searchRadius, k_indices, k_distances);\n std::cout << \"Neighbors are:\" << std::endl;\n\n for(int i = 0;i < 20; ++i)\n {\n std::cout << k_indices[i] << '\\t';\n }\n std::cout << std::endl;\n std::cout << \"Number of Neighbors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n\n std::cout << \"\\n---------------\\nOrganizedData\\n---------------\\n\";\n double time2 = getTime ();\n search_.reset (new OrganizedNeighbor ());\n search_->setInputCloud (cloud);\n search_->radiusSearch (cloud->points[searchIdx], searchRadius, k_indices, k_distances);\n std::cout << \"Neighbors are: \" << std::endl;\n for (int i = 0; i < 20; ++i)\n {\n std::cout << k_indices[i] << '\\t';\n }\n std::cout << std::endl;\n std::cout << \"Number of Neigbhors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n\n std::cout << \"\\n---------------\\nOctree\\n---------------\\n\";\n double time3 = getTime ();\n search_.reset (new Octree (0.1f));\n search_->setInputCloud (cloud);\n search_->radiusSearch (cloud->points[searchIdx], searchRadius, k_indices, k_distances);\n std::cout << \"Neighbors are: \" << std::endl;\n for (int i = 0; i < 20; ++i) \n {\n std::cout << k_indices[i] << '\\t';\n }\n std::cout << std::endl;\n std::cout << \"Number of Neighbors: \" << k_indices.size () << std::endl; \n k_indices.clear (); k_distances.clear ();\n std::cout << std::endl;\n std::cout << std::endl;\n\n time_kdtree = time2 - time1;\n time_organized_data = time3 - time2;\n time_octree = getTime () - time3;\n \n std::cout << \"Time Taken: \" << \"KDTree: \" << time_kdtree << '\\t' <<\"OranizedData: \" << time_organized_data << '\\t' << \"Octree: \" << time_octree << '\\t' << std::endl;\t\n }\n else\n {\n PCL_ERROR (\"[pcl::search::AutotunedSearch::evaluateSearchMethods] Only NEAREST_K_SEARCH and NEAREST_RADIUS_SEARCH supported\\n\");\n return;\n }\n \/\/ Set the datastructure according to which takes the minimum time\n if (time_kdtree < time_organized_data && time_kdtree < time_octree)\n {\n spatial_loc_ = KDTREE;\n search_.reset (new KdTree ());\n }\n else if (time_octree < time_kdtree && time_octree < time_organized_data)\n {\n spatial_loc_ = OCTREE;\n search_.reset (new Octree (0.1f));\n }\n else if (time_organized_data < time_kdtree && time_organized_data < time_octree)\n {\n spatial_loc_ = OCTREE;\n search_.reset (new OrganizedNeighbor ());\n }\n\/\/ search_->setInputCloud (cloud);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::setInputCloud (const PointCloudConstPtr &cloud, \n const IndicesConstPtr &indices)\n{\n input_ = cloud;\n search_->setInputCloud (cloud, indices);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::setInputCloud (const PointCloudConstPtr& cloud)\n{\n input_ = cloud;\n search_->setInputCloud (cloud);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int \npcl::search::AutotunedSearch::nearestKSearch (const PointT &point,\n int k, \n std::vector &k_indices, \n std::vector &k_sqr_distances) \n{\n return (search_->nearestKSearch (point, k, k_indices, k_sqr_distances));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int \npcl::search::AutotunedSearch::nearestKSearch (const PointCloud &cloud, \n int index, \n int k, \n std::vector &k_indices, \n std::vector &k_sqr_distances) \n{\n return (search_->nearestKSearch (cloud, index, k, k_indices, k_sqr_distances));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int \npcl::search::AutotunedSearch::nearestKSearch (int index, \n int k, \n std::vector &k_indices, \n std::vector &k_sqr_distances)\n{\n return (search_->nearestKSearch (index, k, k_indices, k_sqr_distances));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int\npcl::search::AutotunedSearch::radiusSearch (const PointT &point, \n const double radius, \n std::vector &k_indices, \n std::vector &k_distances, \n int max_nn) const\n{\n return (search_->radiusSearch (point, radius, k_indices, k_distances, max_nn));\n}\n \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int \npcl::search::AutotunedSearch::radiusSearch (const PointCloud &cloud, \n int index, \n double radius,\n std::vector &k_indices, \n std::vector &k_distances,\n int max_nn) \n{\n return (search_->radiusSearch (cloud, index, radius, k_indices, k_distances, max_nn));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int \npcl::search::AutotunedSearch::radiusSearch (int index, \n double radius, \n std::vector &k_indices,\n std::vector &k_distances, \n int max_nn) const\n{\n return (search_->radiusSearch (index, radius, k_indices, k_distances, max_nn));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::approxNearestSearch (const PointCloudConstPtr &cloud_arg, \n int query_index_arg, \n int &result_index_arg,\n float &sqr_distance_arg)\n{\n if(spatial_loc_ == OCTREE)\n search_->approxNearestSearch (cloud_arg, query_index_arg, result_index_arg, sqr_distance_arg);\n else\n PCL_ERROR (\"approxNearestSearch() works only for OCTREE structure\\n\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::approxNearestSearch (const PointT &p_q_arg, \n int &result_index_arg, \n float &sqr_distance_arg)\n{\n if (spatial_loc_ == OCTREE)\n search_->approxNearestSearch (p_q_arg, result_index_arg, sqr_distance_arg);\n else\n PCL_ERROR (\"approxNearestSearch() works only for OCTREE structure\\n\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void \npcl::search::AutotunedSearch::approxNearestSearch (int query_index_arg, \n int &result_index_arg, \n float &sqr_distance_arg)\n{\n if (spatial_loc_ == OCTREE)\n search_->approxNearestSearch (query_index_arg, result_index_arg, sqr_distance_arg);\n else\n PCL_ERROR (\"approxNearestSearch() works only for OCTREE structure\\n\");\n}\n\n#define PCL_INSTANTIATE_AutotunedSearch(T) template class PCL_EXPORTS pcl::search::AutotunedSearch;\n\n#endif \/\/#ifndef PCL_SEARCH_AUTO_TUNED_SEARCH_IMPL\n<|endoftext|>"} {"text":"\/*\n +----------------------------------------------------------------------+\n | Swoole |\n +----------------------------------------------------------------------+\n | This source file is subject to version 2.0 of the Apache license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.apache.org\/licenses\/LICENSE-2.0.html |\n | If you did not receive a copy of the Apache2.0 license and are unable|\n | to obtain it through the world-wide-web, please send a note to |\n | license@swoole.com so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: Xinyu Zhu |\n | shiguangqi |\n +----------------------------------------------------------------------+\n *\/\n\n#include \"php_swoole.h\"\n\n#ifdef SW_COROUTINE\n#include \"swoole_coroutine.h\"\n\n#define TASK_SLOT \\\n ((int)((ZEND_MM_ALIGNED_SIZE(sizeof(coro_task)) + ZEND_MM_ALIGNED_SIZE(sizeof(zval)) - 1) \/ ZEND_MM_ALIGNED_SIZE(sizeof(zval))))\n#define SWCC(x) sw_current_context->x\n\ncoro_global COROG;\n\n#if PHP_VERSION_ID >= 70200\nstatic inline void sw_vm_stack_init(void)\n{\n uint32_t size = COROG.stack_size;\n zend_vm_stack page = (zend_vm_stack) emalloc(size);\n\n page->top = ZEND_VM_STACK_ELEMENTS(page);\n page->end = (zval*) ((char*) page + size);\n page->prev = NULL;\n\n EG(vm_stack) = page;\n EG(vm_stack)->top++;\n EG(vm_stack_top) = EG(vm_stack)->top;\n EG(vm_stack_end) = EG(vm_stack)->end;\n}\n#else\n#define sw_vm_stack_init zend_vm_stack_init\n#endif\n\nstatic sw_inline void php_coro_save_vm_stack(coro_task *task)\n{\n task->execute_data = EG(current_execute_data);\n task->vm_stack = EG(vm_stack);\n task->vm_stack_top = EG(vm_stack_top);\n task->vm_stack_end = EG(vm_stack_end);\n SW_SAVE_EG_SCOPE(task->scope);\n}\n\nstatic sw_inline coro_task* php_coro_get_current_task()\n{\n coro_task *task = (coro_task *) coroutine_get_current_task();\n if (!task)\n {\n task = &COROG.task;\n }\n php_coro_save_vm_stack(task);\n return task;\n}\n\nstatic sw_inline void php_coro_restore_vm_stack(coro_task *task)\n{\n EG(current_execute_data) = task->execute_data;\n EG(vm_stack) = task->vm_stack;\n EG(vm_stack_top) = task->vm_stack_top;\n EG(vm_stack_end) = task->vm_stack_end;\n SW_SET_EG_SCOPE(task->scope);\n}\n\n\/**\n * The meaning of the task argument in coro switch functions\n *\n * create: origin_task\n * yield: current_task\n * resume: target_task\n * close: current_task\n *\n *\/\n\nstatic sw_inline void php_coro_save_og(coro_task *task)\n{\n task->output_ptr = (zend_output_globals *) emalloc(sizeof(zend_output_globals));\n memcpy(task->output_ptr, SWOG, sizeof(zend_output_globals));\n php_output_activate();\n}\n\nstatic sw_inline void php_coro_restore_og(coro_task *task)\n{\n memcpy(SWOG, task->output_ptr, sizeof(zend_output_globals));\n efree(task->output_ptr);\n task->output_ptr = NULL;\n}\n\nstatic sw_inline void php_coro_og_create(coro_task *task)\n{\n if (OG(handlers).elements)\n {\n php_coro_save_og(task);\n }\n else\n {\n task->output_ptr = NULL;\n }\n}\n\nstatic sw_inline void php_coro_og_yield(coro_task *task)\n{\n if (OG(handlers).elements)\n {\n php_coro_save_og(task);\n }\n else\n {\n task->output_ptr = NULL;\n }\n if (task->origin_task->output_ptr)\n {\n php_coro_restore_og(task->origin_task);\n }\n}\n\nstatic sw_inline void php_coro_og_resume(coro_task *task)\n{\n if (OG(handlers).elements)\n {\n php_coro_save_og(task->origin_task);\n }\n else\n {\n task->origin_task->output_ptr = NULL;\n }\n if (task->output_ptr)\n {\n php_coro_restore_og(task);\n }\n}\n\nstatic sw_inline void php_coro_og_close(coro_task *task)\n{\n if (OG(handlers).elements)\n {\n if (OG(active))\n {\n php_output_end_all();\n }\n php_output_deactivate();\n php_output_activate();\n }\n if (task->output_ptr)\n {\n efree(task->output_ptr);\n task->output_ptr = nullptr;\n }\n}\n\nvoid coro_init(void)\n{\n COROG.max_coro_num = DEFAULT_MAX_CORO_NUM;\n COROG.stack_size = DEFAULT_STACK_SIZE;\n coroutine_set_onYield(internal_coro_yield);\n coroutine_set_onResume(internal_coro_resume);\n coroutine_set_onClose(sw_coro_close);\n}\n\nstatic void php_coro_create(void *arg)\n{\n php_args *php_arg = (php_args *) arg;\n zend_fcall_info_cache *fci_cache = php_arg->fci_cache;\n zval **argv = php_arg->argv;\n int argc = php_arg->argc;\n zval *retval = php_arg->retval;\n coro_task *origin_task = php_arg->origin_task;\n\n int cid = coroutine_get_current_cid();\n int i;\n zend_function *func;\n coro_task *task;\n\n func = fci_cache->function_handler;\n sw_vm_stack_init();\n zend_execute_data *call = (zend_execute_data *) (EG(vm_stack_top));\n\n task = (coro_task *) EG(vm_stack_top);\n EG(vm_stack_top) = (zval *) ((char *) call + TASK_SLOT * sizeof(zval));\n\n call = zend_vm_stack_push_call_frame(\n ZEND_CALL_TOP_FUNCTION | ZEND_CALL_ALLOCATED,\n func, argc,\n fci_cache->called_scope, fci_cache->object\n );\n\n SW_SET_EG_SCOPE(func->common.scope);\n SW_SAVE_EG_SCOPE(task->scope);\n\n for (i = 0; i < argc; ++i)\n {\n zval *target;\n target = ZEND_CALL_ARG(call, i + 1);\n ZVAL_COPY(target, argv[i]);\n }\n call->symbol_table = NULL;\n\n \/\/ EG(current_execute_data) = NULL; \/\/ for backtrace\n if (UNEXPECTED(func->op_array.fn_flags & ZEND_ACC_CLOSURE))\n {\n uint32_t call_info;\n GC_ADDREF(ZEND_CLOSURE_OBJECT(func));\n call_info = ZEND_CALL_CLOSURE;\n ZEND_ADD_CALL_FLAG(call, call_info);\n }\n zend_init_execute_data(call, &func->op_array, retval);\n\n#ifdef SW_LOG_TRACE_OPEN\n task->cid = cid;\n#endif\n task->execute_data = call;\n task->vm_stack = EG(vm_stack);\n task->vm_stack_top = EG(vm_stack_top);\n task->vm_stack_end = EG(vm_stack_end);\n task->origin_task = origin_task;\n task->output_ptr = nullptr;\n task->co = coroutine_get_by_id(cid);\n coroutine_set_task(task->co, (void *) task);\n\n if (SwooleG.hooks[SW_GLOBAL_HOOK_ON_CORO_START])\n {\n swoole_call_hook(SW_GLOBAL_HOOK_ON_CORO_START, task);\n }\n swTraceLog(SW_TRACE_COROUTINE, \"Create coro id: %d, origin cid: %d, coro total count: %d, heap size: %zu\", cid, task->origin_task->cid, COROG.coro_num, zend_memory_usage(0));\n\n php_coro_og_create(origin_task);\n EG(current_execute_data) = task->execute_data;\n zend_execute_ex(EG(current_execute_data));\n\n if (EG(exception))\n {\n zend_exception_error(EG(exception), E_ERROR);\n }\n}\n\nstatic sw_inline void php_coro_yield(coro_task *task)\n{\n swTraceLog(SW_TRACE_COROUTINE,\"php_coro_yield from cid=%d to cid=%d\", task->cid, task->origin_task->cid);\n php_coro_save_vm_stack(task);\n php_coro_restore_vm_stack(task->origin_task);\n php_coro_og_yield(task);\n}\n\nstatic sw_inline void php_coro_resume(coro_task *task)\n{\n task->origin_task = php_coro_get_current_task();\n php_coro_restore_vm_stack(task);\n php_coro_og_resume(task);\n swTraceLog(SW_TRACE_COROUTINE,\"php_coro_resume from cid=%d to cid=%d\", task->origin_task->cid, task->cid);\n}\n\nstatic sw_inline void php_coro_close(coro_task *task)\n{\n php_coro_og_close(task);\n php_coro_yield(task);\n}\n\nvoid internal_coro_resume(void *arg)\n{\n coro_task *task = (coro_task *) arg;\n php_coro_resume(task);\n}\n\nvoid internal_coro_yield(void *arg)\n{\n coro_task *task = (coro_task *) arg;\n php_coro_yield(task);\n}\n\nvoid coro_check(void)\n{\n if (unlikely(!sw_coro_is_in()))\n {\n swoole_php_fatal_error(E_ERROR, \"must be called in the coroutine.\");\n }\n}\n\nvoid coro_destroy(void)\n{\n}\n\nvoid sw_coro_check_bind(const char *name, int bind_cid)\n{\n if (unlikely(bind_cid > 0))\n {\n swString *buffer = SwooleTG.buffer_stack;\n sw_get_debug_print_backtrace(buffer, DEBUG_BACKTRACE_IGNORE_ARGS, 3);\n swoole_error_log(\n SW_LOG_ERROR, SW_ERROR_CO_HAS_BEEN_BOUND,\n \"%s has already been bound to another coroutine #%d, \"\n \"reading or writing of the same socket in multiple coroutines at the same time is not allowed.\\n\"\n \"%.*s\", name, bind_cid, (int) buffer->length, buffer->str\n );\n exit(255);\n }\n}\n\nint sw_coro_create(zend_fcall_info_cache *fci_cache, zval **argv, int argc, zval *retval)\n{\n if (unlikely(COROG.active == 0))\n {\n if (zend_get_module_started(\"xdebug\") == SUCCESS)\n {\n swWarn(\"xdebug do not support coroutine, please notice that it lead to coredump.\");\n }\n COROG.active = 1;\n }\n if (unlikely(COROG.coro_num >= COROG.max_coro_num) )\n {\n swWarn(\"exceed max number of coro_num %d, max_coro_num:%d\", COROG.coro_num, COROG.max_coro_num);\n return CORO_LIMIT;\n }\n\n if (++COROG.coro_num > COROG.peak_coro_num)\n {\n COROG.peak_coro_num = COROG.coro_num;\n }\n\n php_args php_args;\n php_args.fci_cache = fci_cache;\n php_args.argv = argv;\n php_args.argc = argc;\n php_args.retval = retval;\n php_args.origin_task = php_coro_get_current_task();\n\n int cid = coroutine_create(php_coro_create, (void*) &php_args);\n if (unlikely(cid <= 0))\n {\n COROG.coro_num--;\n }\n return cid;\n}\n\nvoid sw_coro_save(zval *return_value, php_context *sw_current_context)\n{\n SWCC(current_coro_return_value_ptr) = return_value;\n SWCC(current_execute_data) = EG(current_execute_data);\n SWCC(current_vm_stack) = EG(vm_stack);\n SWCC(current_vm_stack_top) = EG(vm_stack_top);\n SWCC(current_vm_stack_end) = EG(vm_stack_end);\n SWCC(current_task) = (coro_task *) coroutine_get_current_task();\n}\n\nvoid sw_coro_yield()\n{\n if (unlikely(!sw_coro_is_in()))\n {\n swoole_php_fatal_error(E_ERROR, \"must be called in the coroutine.\");\n }\n coro_task *task = (coro_task *) coroutine_get_current_task();\n php_coro_yield(task);\n coroutine_yield_naked(task->co);\n}\n\nint sw_coro_resume(php_context *sw_current_context, zval *retval, zval *coro_retval)\n{\n coro_task *task = SWCC(current_task);\n php_coro_resume(task);\n if (EG(current_execute_data)->prev_execute_data->opline->result_type != IS_UNUSED && retval)\n {\n ZVAL_COPY(SWCC(current_coro_return_value_ptr), retval);\n }\n\n coroutine_resume_naked(task->co);\n\n if (unlikely(EG(exception)))\n {\n if (retval)\n {\n zval_ptr_dtor(retval);\n }\n zend_exception_error(EG(exception), E_ERROR);\n }\n return CORO_END;\n}\n\nvoid sw_coro_close()\n{\n coro_task *task = (coro_task *) coroutine_get_current_task();\n\n if (SwooleG.hooks[SW_GLOBAL_HOOK_ON_CORO_STOP])\n {\n swoole_call_hook(SW_GLOBAL_HOOK_ON_CORO_STOP, task);\n }\n\n php_coro_close(task);\n efree(task->vm_stack);\n COROG.coro_num--;\n\n swTraceLog(SW_TRACE_COROUTINE, \"coro close cid=%d and %d remained. usage size: %zu. malloc size: %zu\", task->cid, COROG.coro_num, zend_memory_usage(0), zend_memory_usage(1));\n}\n\nint sw_get_current_cid()\n{\n if (unlikely(COROG.active == 0))\n {\n return -1;\n }\n else\n {\n return coroutine_get_current_cid();\n }\n}\n\nvoid sw_coro_set_stack_size(int stack_size)\n{\n coroutine_set_stack_size(stack_size);\n}\n\n#endif\nupdate coro\/*\n +----------------------------------------------------------------------+\n | Swoole |\n +----------------------------------------------------------------------+\n | This source file is subject to version 2.0 of the Apache license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.apache.org\/licenses\/LICENSE-2.0.html |\n | If you did not receive a copy of the Apache2.0 license and are unable|\n | to obtain it through the world-wide-web, please send a note to |\n | license@swoole.com so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: Xinyu Zhu |\n | shiguangqi |\n +----------------------------------------------------------------------+\n *\/\n\n#include \"php_swoole.h\"\n\n#ifdef SW_COROUTINE\n#include \"swoole_coroutine.h\"\n\n#define TASK_SLOT \\\n ((int)((ZEND_MM_ALIGNED_SIZE(sizeof(coro_task)) + ZEND_MM_ALIGNED_SIZE(sizeof(zval)) - 1) \/ ZEND_MM_ALIGNED_SIZE(sizeof(zval))))\n#define SWCC(x) sw_current_context->x\n\ncoro_global COROG;\n\n#if PHP_VERSION_ID >= 70200\nstatic inline void sw_vm_stack_init(void)\n{\n uint32_t size = COROG.stack_size;\n zend_vm_stack page = (zend_vm_stack) emalloc(size);\n\n page->top = ZEND_VM_STACK_ELEMENTS(page);\n page->end = (zval*) ((char*) page + size);\n page->prev = NULL;\n\n EG(vm_stack) = page;\n EG(vm_stack)->top++;\n EG(vm_stack_top) = EG(vm_stack)->top;\n EG(vm_stack_end) = EG(vm_stack)->end;\n}\n#else\n#define sw_vm_stack_init zend_vm_stack_init\n#endif\n\nstatic void sw_vm_stack_destroy(zend_vm_stack stack)\n{\n while (stack != NULL) {\n zend_vm_stack p = stack->prev;\n efree(stack);\n stack = p;\n }\n}\n\n\nstatic sw_inline void php_coro_save_vm_stack(coro_task *task)\n{\n task->execute_data = EG(current_execute_data);\n task->vm_stack = EG(vm_stack);\n task->vm_stack_top = EG(vm_stack_top);\n task->vm_stack_end = EG(vm_stack_end);\n SW_SAVE_EG_SCOPE(task->scope);\n}\n\nstatic sw_inline coro_task* php_coro_get_current_task()\n{\n coro_task *task = (coro_task *) coroutine_get_current_task();\n if (!task)\n {\n task = &COROG.task;\n }\n php_coro_save_vm_stack(task);\n return task;\n}\n\nstatic sw_inline void php_coro_restore_vm_stack(coro_task *task)\n{\n EG(current_execute_data) = task->execute_data;\n EG(vm_stack) = task->vm_stack;\n EG(vm_stack_top) = task->vm_stack_top;\n EG(vm_stack_end) = task->vm_stack_end;\n SW_SET_EG_SCOPE(task->scope);\n}\n\n\/**\n * The meaning of the task argument in coro switch functions\n *\n * create: origin_task\n * yield: current_task\n * resume: target_task\n * close: current_task\n *\n *\/\n\nstatic sw_inline void php_coro_save_og(coro_task *task)\n{\n task->output_ptr = (zend_output_globals *) emalloc(sizeof(zend_output_globals));\n memcpy(task->output_ptr, SWOG, sizeof(zend_output_globals));\n php_output_activate();\n}\n\nstatic sw_inline void php_coro_restore_og(coro_task *task)\n{\n memcpy(SWOG, task->output_ptr, sizeof(zend_output_globals));\n efree(task->output_ptr);\n task->output_ptr = NULL;\n}\n\nstatic sw_inline void php_coro_og_create(coro_task *task)\n{\n if (OG(handlers).elements)\n {\n php_coro_save_og(task);\n }\n else\n {\n task->output_ptr = NULL;\n }\n}\n\nstatic sw_inline void php_coro_og_yield(coro_task *task)\n{\n if (OG(handlers).elements)\n {\n php_coro_save_og(task);\n }\n else\n {\n task->output_ptr = NULL;\n }\n if (task->origin_task->output_ptr)\n {\n php_coro_restore_og(task->origin_task);\n }\n}\n\nstatic sw_inline void php_coro_og_resume(coro_task *task)\n{\n if (OG(handlers).elements)\n {\n php_coro_save_og(task->origin_task);\n }\n else\n {\n task->origin_task->output_ptr = NULL;\n }\n if (task->output_ptr)\n {\n php_coro_restore_og(task);\n }\n}\n\nstatic sw_inline void php_coro_og_close(coro_task *task)\n{\n if (OG(handlers).elements)\n {\n if (OG(active))\n {\n php_output_end_all();\n }\n php_output_deactivate();\n php_output_activate();\n }\n if (task->output_ptr)\n {\n efree(task->output_ptr);\n task->output_ptr = nullptr;\n }\n}\n\nvoid coro_init(void)\n{\n COROG.max_coro_num = DEFAULT_MAX_CORO_NUM;\n COROG.stack_size = DEFAULT_STACK_SIZE;\n coroutine_set_onYield(internal_coro_yield);\n coroutine_set_onResume(internal_coro_resume);\n coroutine_set_onClose(sw_coro_close);\n}\n\nstatic void php_coro_create(void *arg)\n{\n php_args *php_arg = (php_args *) arg;\n zend_fcall_info_cache *fci_cache = php_arg->fci_cache;\n zval **argv = php_arg->argv;\n int argc = php_arg->argc;\n zval *retval = php_arg->retval;\n coro_task *origin_task = php_arg->origin_task;\n\n int cid = coroutine_get_current_cid();\n int i;\n zend_function *func;\n coro_task *task;\n\n func = fci_cache->function_handler;\n sw_vm_stack_init();\n zend_execute_data *call = (zend_execute_data *) (EG(vm_stack_top));\n\n task = (coro_task *) EG(vm_stack_top);\n EG(vm_stack_top) = (zval *) ((char *) call + TASK_SLOT * sizeof(zval));\n\n call = zend_vm_stack_push_call_frame(\n ZEND_CALL_TOP_FUNCTION | ZEND_CALL_ALLOCATED,\n func, argc,\n fci_cache->called_scope, fci_cache->object\n );\n\n SW_SET_EG_SCOPE(func->common.scope);\n SW_SAVE_EG_SCOPE(task->scope);\n\n for (i = 0; i < argc; ++i)\n {\n zval *target;\n target = ZEND_CALL_ARG(call, i + 1);\n ZVAL_COPY(target, argv[i]);\n }\n call->symbol_table = NULL;\n\n \/\/ EG(current_execute_data) = NULL; \/\/ for backtrace\n if (UNEXPECTED(func->op_array.fn_flags & ZEND_ACC_CLOSURE))\n {\n uint32_t call_info;\n GC_ADDREF(ZEND_CLOSURE_OBJECT(func));\n call_info = ZEND_CALL_CLOSURE;\n ZEND_ADD_CALL_FLAG(call, call_info);\n }\n zend_init_execute_data(call, &func->op_array, retval);\n\n#ifdef SW_LOG_TRACE_OPEN\n task->cid = cid;\n#endif\n task->execute_data = call;\n task->vm_stack = EG(vm_stack);\n task->vm_stack_top = EG(vm_stack_top);\n task->vm_stack_end = EG(vm_stack_end);\n task->origin_task = origin_task;\n task->output_ptr = nullptr;\n task->co = coroutine_get_by_id(cid);\n coroutine_set_task(task->co, (void *) task);\n\n if (SwooleG.hooks[SW_GLOBAL_HOOK_ON_CORO_START])\n {\n swoole_call_hook(SW_GLOBAL_HOOK_ON_CORO_START, task);\n }\n swTraceLog(SW_TRACE_COROUTINE, \"Create coro id: %d, origin cid: %d, coro total count: %d, heap size: %zu\", cid, task->origin_task->cid, COROG.coro_num, zend_memory_usage(0));\n\n php_coro_og_create(origin_task);\n EG(current_execute_data) = task->execute_data;\n zend_execute_ex(EG(current_execute_data));\n\n if (EG(exception))\n {\n zend_exception_error(EG(exception), E_ERROR);\n }\n}\n\nstatic sw_inline void php_coro_yield(coro_task *task)\n{\n swTraceLog(SW_TRACE_COROUTINE,\"php_coro_yield from cid=%d to cid=%d\", task->cid, task->origin_task->cid);\n php_coro_save_vm_stack(task);\n php_coro_restore_vm_stack(task->origin_task);\n php_coro_og_yield(task);\n}\n\nstatic sw_inline void php_coro_resume(coro_task *task)\n{\n task->origin_task = php_coro_get_current_task();\n php_coro_restore_vm_stack(task);\n php_coro_og_resume(task);\n swTraceLog(SW_TRACE_COROUTINE,\"php_coro_resume from cid=%d to cid=%d\", task->origin_task->cid, task->cid);\n}\n\nstatic sw_inline void php_coro_close(coro_task *task)\n{\n php_coro_og_close(task);\n php_coro_yield(task);\n}\n\nvoid internal_coro_resume(void *arg)\n{\n coro_task *task = (coro_task *) arg;\n php_coro_resume(task);\n}\n\nvoid internal_coro_yield(void *arg)\n{\n coro_task *task = (coro_task *) arg;\n php_coro_yield(task);\n}\n\nvoid coro_check(void)\n{\n if (unlikely(!sw_coro_is_in()))\n {\n swoole_php_fatal_error(E_ERROR, \"must be called in the coroutine.\");\n }\n}\n\nvoid coro_destroy(void)\n{\n}\n\nvoid sw_coro_check_bind(const char *name, int bind_cid)\n{\n if (unlikely(bind_cid > 0))\n {\n swString *buffer = SwooleTG.buffer_stack;\n sw_get_debug_print_backtrace(buffer, DEBUG_BACKTRACE_IGNORE_ARGS, 3);\n swoole_error_log(\n SW_LOG_ERROR, SW_ERROR_CO_HAS_BEEN_BOUND,\n \"%s has already been bound to another coroutine #%d, \"\n \"reading or writing of the same socket in multiple coroutines at the same time is not allowed.\\n\"\n \"%.*s\", name, bind_cid, (int) buffer->length, buffer->str\n );\n exit(255);\n }\n}\n\nint sw_coro_create(zend_fcall_info_cache *fci_cache, zval **argv, int argc, zval *retval)\n{\n if (unlikely(COROG.active == 0))\n {\n if (zend_get_module_started(\"xdebug\") == SUCCESS)\n {\n swWarn(\"xdebug do not support coroutine, please notice that it lead to coredump.\");\n }\n COROG.active = 1;\n }\n if (unlikely(COROG.coro_num >= COROG.max_coro_num) )\n {\n swWarn(\"exceed max number of coro_num %d, max_coro_num:%d\", COROG.coro_num, COROG.max_coro_num);\n return CORO_LIMIT;\n }\n\n if (++COROG.coro_num > COROG.peak_coro_num)\n {\n COROG.peak_coro_num = COROG.coro_num;\n }\n\n php_args php_args;\n php_args.fci_cache = fci_cache;\n php_args.argv = argv;\n php_args.argc = argc;\n php_args.retval = retval;\n php_args.origin_task = php_coro_get_current_task();\n\n int cid = coroutine_create(php_coro_create, (void*) &php_args);\n if (unlikely(cid <= 0))\n {\n COROG.coro_num--;\n }\n return cid;\n}\n\nvoid sw_coro_save(zval *return_value, php_context *sw_current_context)\n{\n SWCC(current_coro_return_value_ptr) = return_value;\n SWCC(current_execute_data) = EG(current_execute_data);\n SWCC(current_vm_stack) = EG(vm_stack);\n SWCC(current_vm_stack_top) = EG(vm_stack_top);\n SWCC(current_vm_stack_end) = EG(vm_stack_end);\n SWCC(current_task) = (coro_task *) coroutine_get_current_task();\n}\n\nvoid sw_coro_yield()\n{\n if (unlikely(!sw_coro_is_in()))\n {\n swoole_php_fatal_error(E_ERROR, \"must be called in the coroutine.\");\n }\n coro_task *task = (coro_task *) coroutine_get_current_task();\n php_coro_yield(task);\n coroutine_yield_naked(task->co);\n}\n\nint sw_coro_resume(php_context *sw_current_context, zval *retval, zval *coro_retval)\n{\n coro_task *task = SWCC(current_task);\n php_coro_resume(task);\n if (EG(current_execute_data)->prev_execute_data->opline->result_type != IS_UNUSED && retval)\n {\n ZVAL_COPY(SWCC(current_coro_return_value_ptr), retval);\n }\n\n coroutine_resume_naked(task->co);\n\n if (unlikely(EG(exception)))\n {\n if (retval)\n {\n zval_ptr_dtor(retval);\n }\n zend_exception_error(EG(exception), E_ERROR);\n }\n return CORO_END;\n}\n\nvoid sw_coro_close()\n{\n coro_task *task = (coro_task *) coroutine_get_current_task();\n\n if (SwooleG.hooks[SW_GLOBAL_HOOK_ON_CORO_STOP])\n {\n swoole_call_hook(SW_GLOBAL_HOOK_ON_CORO_STOP, task);\n }\n\n php_coro_close(task);\n sw_vm_stack_destroy(task->vm_stack);\n COROG.coro_num--;\n\n swTraceLog(SW_TRACE_COROUTINE, \"coro close cid=%d and %d remained. usage size: %zu. malloc size: %zu\", task->cid, COROG.coro_num, zend_memory_usage(0), zend_memory_usage(1));\n}\n\nint sw_get_current_cid()\n{\n if (unlikely(COROG.active == 0))\n {\n return -1;\n }\n else\n {\n return coroutine_get_current_cid();\n }\n}\n\nvoid sw_coro_set_stack_size(int stack_size)\n{\n coroutine_set_stack_size(stack_size);\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \n\nint main() {\n App app;\n\n client;\n\n requester = client->session()->requester();\n\n\n stream = requester.subscribe(\"\/abc\", func);\n stream.close();\n}\n\n\nvoid callback(ValueUpdate, ResponseStatus)fix compilation error#include \n\nint main() {\n#if 0\n App app;\n\n client;\n\n requester = client->session()->requester();\n\n\n stream = requester.subscribe(\"\/abc\", func);\n stream.close();\n#endif\n}\n\n\n\/\/ void callback(ValueUpdate, ResponseStatus);\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nint main(int argc, const char* argv[])\r\n{\r\n if (argc != 2)\r\n return -1;\r\n\r\n const std::string fname(argv[1]);\r\n\r\n cv::namedWindow(\"CPU\", cv::WINDOW_NORMAL);\r\n cv::namedWindow(\"GPU\", cv::WINDOW_OPENGL);\r\n cv::gpu::setGlDevice();\r\n\r\n cv::Mat frame;\r\n cv::VideoCapture reader(fname);\r\n\r\n cv::gpu::GpuMat d_frame;\r\n cv::gpu::VideoReader_GPU d_reader(fname);\r\n d_reader.dumpFormat(std::cout);\r\n\r\n cv::TickMeter tm;\r\n std::vector cpu_times;\r\n std::vector gpu_times;\r\n\r\n for (;;)\r\n {\r\n tm.reset(); tm.start();\r\n if (!reader.read(frame))\r\n break;\r\n tm.stop();\r\n cpu_times.push_back(tm.getTimeMilli());\r\n\r\n tm.reset(); tm.start();\r\n if (!d_reader.read(d_frame))\r\n break;\r\n tm.stop();\r\n gpu_times.push_back(tm.getTimeMilli());\r\n\r\n cv::imshow(\"CPU\", frame);\r\n cv::imshow(\"GPU\", frame);\r\n\r\n if (cv::waitKey(3) > 0)\r\n break;\r\n }\r\n\r\n if (!cpu_times.empty() && !gpu_times.empty())\r\n {\r\n std::cout << std::endl << \"Results:\" << std::endl;\r\n\r\n std::sort(cpu_times.begin(), cpu_times.end());\r\n std::sort(gpu_times.begin(), gpu_times.end());\r\n\r\n double cpu_avg = std::accumulate(cpu_times.begin(), cpu_times.end(), 0.0) \/ cpu_times.size();\r\n double gpu_avg = std::accumulate(gpu_times.begin(), gpu_times.end(), 0.0) \/ gpu_times.size();\r\n\r\n std::cout << \"CPU : Avg : \" << cpu_avg << \" ms FPS : \" << 1000.0 \/ cpu_avg << std::endl;\r\n std::cout << \"GPU : Avg : \" << gpu_avg << \" ms FPS : \" << 1000.0 \/ gpu_avg << std::endl;\r\n }\r\n\r\n return 0;\r\n}\r\nminor fix in gpu video_writer sample#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nint main(int argc, const char* argv[])\r\n{\r\n if (argc != 2)\r\n return -1;\r\n\r\n const std::string fname(argv[1]);\r\n\r\n cv::namedWindow(\"CPU\", cv::WINDOW_NORMAL);\r\n cv::namedWindow(\"GPU\", cv::WINDOW_OPENGL);\r\n cv::gpu::setGlDevice();\r\n\r\n cv::Mat frame;\r\n cv::VideoCapture reader(fname);\r\n\r\n cv::gpu::GpuMat d_frame;\r\n cv::gpu::VideoReader_GPU d_reader(fname);\r\n d_reader.dumpFormat(std::cout);\r\n\r\n cv::TickMeter tm;\r\n std::vector cpu_times;\r\n std::vector gpu_times;\r\n\r\n for (;;)\r\n {\r\n tm.reset(); tm.start();\r\n if (!reader.read(frame))\r\n break;\r\n tm.stop();\r\n cpu_times.push_back(tm.getTimeMilli());\r\n\r\n tm.reset(); tm.start();\r\n if (!d_reader.read(d_frame))\r\n break;\r\n tm.stop();\r\n gpu_times.push_back(tm.getTimeMilli());\r\n\r\n cv::imshow(\"CPU\", frame);\r\n cv::imshow(\"GPU\", d_frame);\r\n\r\n if (cv::waitKey(3) > 0)\r\n break;\r\n }\r\n\r\n if (!cpu_times.empty() && !gpu_times.empty())\r\n {\r\n std::cout << std::endl << \"Results:\" << std::endl;\r\n\r\n std::sort(cpu_times.begin(), cpu_times.end());\r\n std::sort(gpu_times.begin(), gpu_times.end());\r\n\r\n double cpu_avg = std::accumulate(cpu_times.begin(), cpu_times.end(), 0.0) \/ cpu_times.size();\r\n double gpu_avg = std::accumulate(gpu_times.begin(), gpu_times.end(), 0.0) \/ gpu_times.size();\r\n\r\n std::cout << \"CPU : Avg : \" << cpu_avg << \" ms FPS : \" << 1000.0 \/ cpu_avg << std::endl;\r\n std::cout << \"GPU : Avg : \" << gpu_avg << \" ms FPS : \" << 1000.0 \/ gpu_avg << std::endl;\r\n }\r\n\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: dif.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2003-03-26 18:04:58 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _DIF_HXX\n#define _DIF_HXX\n\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _LIST_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _STRING_HXX \/\/autogen\n#include \n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n\nclass SvStream;\nclass SvNumberFormatter;\nclass ScDocument;\nclass ScPatternAttr;\n\nextern const sal_Unicode pKeyTABLE[];\nextern const sal_Unicode pKeyVECTORS[];\nextern const sal_Unicode pKeyTUPLES[];\nextern const sal_Unicode pKeyDATA[];\nextern const sal_Unicode pKeyBOT[];\nextern const sal_Unicode pKeyEOD[];\nextern const sal_Unicode pKeyTRUE[];\nextern const sal_Unicode pKeyFALSE[];\nextern const sal_Unicode pKeyNA[];\nextern const sal_Unicode pKeyV[];\nextern const sal_Unicode pKey1_0[];\n\n\nenum TOPIC\n{\n T_UNKNOWN,\n T_TABLE, T_VECTORS, T_TUPLES, T_DATA, T_LABEL, T_COMMENT, T_SIZE,\n T_PERIODICITY, T_MAJORSTART, T_MINORSTART, T_TRUELENGTH, T_UINITS,\n T_DISPLAYUNITS,\n T_END\n};\n\nenum DATASET { D_BOT, D_EOD, D_NUMERIC, D_STRING, D_UNKNOWN, D_SYNT_ERROR };\n\n\nclass DifParser\n{\npublic:\n String aData;\n double fVal;\n UINT32 nVector;\n UINT32 nVal;\n UINT32 nNumFormat;\n CharSet eCharSet;\nprivate:\n SvNumberFormatter* pNumFormatter;\n SvStream& rIn;\n BOOL bPlain;\n\n static inline BOOL IsBOT( const sal_Unicode* pRef );\n static inline BOOL IsEOD( const sal_Unicode* pRef );\n static inline BOOL Is1_0( const sal_Unicode* pRef );\npublic:\n DifParser( SvStream&, const UINT32 nOption, ScDocument&, CharSet );\n\n TOPIC GetNextTopic( void );\n\n DATASET GetNextDataset( void );\n\n const sal_Unicode* ScanIntVal( const sal_Unicode* pStart, UINT32& rRet );\n BOOL ScanFloatVal( const sal_Unicode* pStart );\n\n inline BOOL IsNumber( const sal_Unicode cChar );\n inline BOOL IsNumberEnding( const sal_Unicode cChar );\n\n static inline BOOL IsV( const sal_Unicode* pRef );\n\n inline BOOL IsPlain( void ) const;\n};\n\n\ninline BOOL DifParser::IsBOT( const sal_Unicode* pRef )\n{\n return ( pRef[ 0 ] == pKeyBOT[0] &&\n pRef[ 1 ] == pKeyBOT[1] &&\n pRef[ 2 ] == pKeyBOT[2] &&\n pRef[ 3 ] == pKeyBOT[3] );\n}\n\n\ninline BOOL DifParser::IsEOD( const sal_Unicode* pRef )\n{\n return ( pRef[ 0 ] == pKeyEOD[0] &&\n pRef[ 1 ] == pKeyEOD[1] &&\n pRef[ 2 ] == pKeyEOD[2] &&\n pRef[ 3 ] == pKeyEOD[3] );\n}\n\n\ninline BOOL DifParser::Is1_0( const sal_Unicode* pRef )\n{\n return ( pRef[ 0 ] == pKey1_0[0] &&\n pRef[ 1 ] == pKey1_0[1] &&\n pRef[ 2 ] == pKey1_0[2] &&\n pRef[ 3 ] == pKey1_0[3] );\n}\n\n\ninline BOOL DifParser::IsV( const sal_Unicode* pRef )\n{\n return ( pRef[ 0 ] == pKeyV[0] &&\n pRef[ 1 ] == pKeyV[1] );\n}\n\n\ninline BOOL DifParser::IsNumber( const sal_Unicode cChar )\n{\n return ( cChar >= '0' && cChar <= '9' );\n}\n\n\ninline BOOL DifParser::IsNumberEnding( const sal_Unicode cChar )\n{\n return ( cChar == 0x00 );\n}\n\n\ninline BOOL DifParser::IsPlain( void ) const\n{\n return bPlain;\n}\n\n\n\n\nclass DifAttrCache;\nclass ScPatternAttr;\n\n\nclass DifColumn : private List\n{\nprivate:\n friend DifAttrCache;\n struct ENTRY\n {\n UINT32 nNumFormat;\n\n UINT16 nStart;\n UINT16 nEnd;\n };\n\n ENTRY* pAkt;\n\n inline DifColumn( void );\n ~DifColumn();\n void SetLogical( UINT16 nRow );\n void SetNumFormat( UINT16 nRow, const UINT32 nNumFormat );\n void NewEntry( const UINT16 nPos, const UINT32 nNumFormat );\n void Apply( ScDocument&, const UINT16 nCol, const UINT16 nTab, const ScPatternAttr& );\n void Apply( ScDocument &rDoc, const UINT16 nCol, const UINT16 nTab );\npublic: \/\/ geht niemanden etwas an...\n};\n\n\ninline DifColumn::DifColumn( void )\n{\n pAkt = NULL;\n}\n\n\n\n\nclass DifAttrCache\n{\nprivate:\n DifColumn** ppCols;\n BOOL bPlain;\npublic:\n DifAttrCache( const BOOL bPlain );\n ~DifAttrCache();\n inline void SetLogical( const UINT16 nCol, const UINT16 nRow );\n void SetNumFormat( const UINT16 nCol, const UINT16 nRow, const UINT32 nNumFormat );\n void Apply( ScDocument&, UINT16 nTab );\n};\n\n\ninline void DifAttrCache::SetLogical( const UINT16 nCol, const UINT16 nRow )\n{\n DBG_ASSERT( nCol <= MAXCOL, \"-DifAttrCache::SetLogical(): Col zu gross!\" );\n DBG_ASSERT( bPlain, \"*DifAttrCache::SetLogical(): muss Plain sein!\" );\n\n if( !ppCols[ nCol ] )\n ppCols[ nCol ] = new DifColumn;\n ppCols[ nCol ]->SetLogical( nRow );\n}\n\n\n#endif\n\n\nINTEGRATION: CWS ooo20031110 (1.2.166); FILE MERGED 2003\/11\/07 11:00:47 waratah 1.2.166.1: #i21906# add class keyword after friend\/*************************************************************************\n *\n * $RCSfile: dif.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2003-12-01 17:51:58 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _DIF_HXX\n#define _DIF_HXX\n\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _LIST_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _STRING_HXX \/\/autogen\n#include \n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n\nclass SvStream;\nclass SvNumberFormatter;\nclass ScDocument;\nclass ScPatternAttr;\n\nextern const sal_Unicode pKeyTABLE[];\nextern const sal_Unicode pKeyVECTORS[];\nextern const sal_Unicode pKeyTUPLES[];\nextern const sal_Unicode pKeyDATA[];\nextern const sal_Unicode pKeyBOT[];\nextern const sal_Unicode pKeyEOD[];\nextern const sal_Unicode pKeyTRUE[];\nextern const sal_Unicode pKeyFALSE[];\nextern const sal_Unicode pKeyNA[];\nextern const sal_Unicode pKeyV[];\nextern const sal_Unicode pKey1_0[];\n\n\nenum TOPIC\n{\n T_UNKNOWN,\n T_TABLE, T_VECTORS, T_TUPLES, T_DATA, T_LABEL, T_COMMENT, T_SIZE,\n T_PERIODICITY, T_MAJORSTART, T_MINORSTART, T_TRUELENGTH, T_UINITS,\n T_DISPLAYUNITS,\n T_END\n};\n\nenum DATASET { D_BOT, D_EOD, D_NUMERIC, D_STRING, D_UNKNOWN, D_SYNT_ERROR };\n\n\nclass DifParser\n{\npublic:\n String aData;\n double fVal;\n UINT32 nVector;\n UINT32 nVal;\n UINT32 nNumFormat;\n CharSet eCharSet;\nprivate:\n SvNumberFormatter* pNumFormatter;\n SvStream& rIn;\n BOOL bPlain;\n\n static inline BOOL IsBOT( const sal_Unicode* pRef );\n static inline BOOL IsEOD( const sal_Unicode* pRef );\n static inline BOOL Is1_0( const sal_Unicode* pRef );\npublic:\n DifParser( SvStream&, const UINT32 nOption, ScDocument&, CharSet );\n\n TOPIC GetNextTopic( void );\n\n DATASET GetNextDataset( void );\n\n const sal_Unicode* ScanIntVal( const sal_Unicode* pStart, UINT32& rRet );\n BOOL ScanFloatVal( const sal_Unicode* pStart );\n\n inline BOOL IsNumber( const sal_Unicode cChar );\n inline BOOL IsNumberEnding( const sal_Unicode cChar );\n\n static inline BOOL IsV( const sal_Unicode* pRef );\n\n inline BOOL IsPlain( void ) const;\n};\n\n\ninline BOOL DifParser::IsBOT( const sal_Unicode* pRef )\n{\n return ( pRef[ 0 ] == pKeyBOT[0] &&\n pRef[ 1 ] == pKeyBOT[1] &&\n pRef[ 2 ] == pKeyBOT[2] &&\n pRef[ 3 ] == pKeyBOT[3] );\n}\n\n\ninline BOOL DifParser::IsEOD( const sal_Unicode* pRef )\n{\n return ( pRef[ 0 ] == pKeyEOD[0] &&\n pRef[ 1 ] == pKeyEOD[1] &&\n pRef[ 2 ] == pKeyEOD[2] &&\n pRef[ 3 ] == pKeyEOD[3] );\n}\n\n\ninline BOOL DifParser::Is1_0( const sal_Unicode* pRef )\n{\n return ( pRef[ 0 ] == pKey1_0[0] &&\n pRef[ 1 ] == pKey1_0[1] &&\n pRef[ 2 ] == pKey1_0[2] &&\n pRef[ 3 ] == pKey1_0[3] );\n}\n\n\ninline BOOL DifParser::IsV( const sal_Unicode* pRef )\n{\n return ( pRef[ 0 ] == pKeyV[0] &&\n pRef[ 1 ] == pKeyV[1] );\n}\n\n\ninline BOOL DifParser::IsNumber( const sal_Unicode cChar )\n{\n return ( cChar >= '0' && cChar <= '9' );\n}\n\n\ninline BOOL DifParser::IsNumberEnding( const sal_Unicode cChar )\n{\n return ( cChar == 0x00 );\n}\n\n\ninline BOOL DifParser::IsPlain( void ) const\n{\n return bPlain;\n}\n\n\n\n\nclass DifAttrCache;\nclass ScPatternAttr;\n\n\nclass DifColumn : private List\n{\nprivate:\n friend class DifAttrCache;\n struct ENTRY\n {\n UINT32 nNumFormat;\n\n UINT16 nStart;\n UINT16 nEnd;\n };\n\n ENTRY* pAkt;\n\n inline DifColumn( void );\n ~DifColumn();\n void SetLogical( UINT16 nRow );\n void SetNumFormat( UINT16 nRow, const UINT32 nNumFormat );\n void NewEntry( const UINT16 nPos, const UINT32 nNumFormat );\n void Apply( ScDocument&, const UINT16 nCol, const UINT16 nTab, const ScPatternAttr& );\n void Apply( ScDocument &rDoc, const UINT16 nCol, const UINT16 nTab );\npublic: \/\/ geht niemanden etwas an...\n};\n\n\ninline DifColumn::DifColumn( void )\n{\n pAkt = NULL;\n}\n\n\n\n\nclass DifAttrCache\n{\nprivate:\n DifColumn** ppCols;\n BOOL bPlain;\npublic:\n DifAttrCache( const BOOL bPlain );\n ~DifAttrCache();\n inline void SetLogical( const UINT16 nCol, const UINT16 nRow );\n void SetNumFormat( const UINT16 nCol, const UINT16 nRow, const UINT32 nNumFormat );\n void Apply( ScDocument&, UINT16 nTab );\n};\n\n\ninline void DifAttrCache::SetLogical( const UINT16 nCol, const UINT16 nRow )\n{\n DBG_ASSERT( nCol <= MAXCOL, \"-DifAttrCache::SetLogical(): Col zu gross!\" );\n DBG_ASSERT( bPlain, \"*DifAttrCache::SetLogical(): muss Plain sein!\" );\n\n if( !ppCols[ nCol ] )\n ppCols[ nCol ] = new DifColumn;\n ppCols[ nCol ]->SetLogical( nRow );\n}\n\n\n#endif\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cbutton.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:13:59 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/------------------------------------------------------------------\n\n#ifndef SC_CBUTTON_HXX\n#define SC_CBUTTON_HXX\n\n#ifndef _GEN_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _TOOLS_COLOR_HXX\n#include \n#endif\n\nclass Window;\n\n\n\/\/==================================================================\n\nclass ScDDComboBoxButton\n{\npublic:\n ScDDComboBoxButton( Window* pOutputDevice );\n ~ScDDComboBoxButton();\n\n void Draw( const Point& rAt,\n const Size& rSize,\n BOOL bState,\n BOOL bBtnIn = FALSE );\n\n void Draw( const Point& rAt,\n BOOL bState,\n BOOL bBtnIn = FALSE )\n { Draw( rAt, aBtnSize, bState, bBtnIn ); }\n\n void Draw( BOOL bState,\n BOOL bBtnIn = FALSE )\n { Draw( aBtnPos, aBtnSize, bState, bBtnIn ); }\n\n void SetOptSizePixel();\n\n void SetPosPixel( const Point& rNewPos ) { aBtnPos = rNewPos; }\n Point GetPosPixel() const { return aBtnPos; }\n\n void SetSizePixel( const Size& rNewSize ) { aBtnSize = rNewSize; }\n Size GetSizePixel() const { return aBtnSize; }\n\nprivate:\n void ImpDrawArrow( const Rectangle& rRect,\n BOOL bState );\n\nprotected:\n Window* pOut;\n Point aBtnPos;\n Size aBtnSize;\n};\n\n\n#endif \/\/ SC_CBUTTON_HXX\n\n\nINTEGRATION: CWS aw046 (1.4.384); FILE MERGED 2007\/02\/22 17:56:07 nn 1.4.384.1: #i74768# use variable pContentDev to draw content in ScGridWindow::Draw\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cbutton.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2007-06-26 11:50:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/------------------------------------------------------------------\n\n#ifndef SC_CBUTTON_HXX\n#define SC_CBUTTON_HXX\n\n#ifndef _GEN_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _TOOLS_COLOR_HXX\n#include \n#endif\n\nclass OutputDevice;\n\n\n\/\/==================================================================\n\nclass ScDDComboBoxButton\n{\npublic:\n ScDDComboBoxButton( OutputDevice* pOutputDevice );\n ~ScDDComboBoxButton();\n\n void SetOutputDevice( OutputDevice* pOutputDevice );\n\n void Draw( const Point& rAt,\n const Size& rSize,\n BOOL bState,\n BOOL bBtnIn = FALSE );\n\n void Draw( const Point& rAt,\n BOOL bState,\n BOOL bBtnIn = FALSE )\n { Draw( rAt, aBtnSize, bState, bBtnIn ); }\n\n void Draw( BOOL bState,\n BOOL bBtnIn = FALSE )\n { Draw( aBtnPos, aBtnSize, bState, bBtnIn ); }\n\n void SetOptSizePixel();\n\n void SetPosPixel( const Point& rNewPos ) { aBtnPos = rNewPos; }\n Point GetPosPixel() const { return aBtnPos; }\n\n void SetSizePixel( const Size& rNewSize ) { aBtnSize = rNewSize; }\n Size GetSizePixel() const { return aBtnSize; }\n\nprivate:\n void ImpDrawArrow( const Rectangle& rRect,\n BOOL bState );\n\nprotected:\n OutputDevice* pOut;\n Point aBtnPos;\n Size aBtnSize;\n};\n\n\n#endif \/\/ SC_CBUTTON_HXX\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: hdrcont.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 11:34:09 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_HDRCONT_HXX\n#define SC_HDRCONT_HXX\n\n#ifndef _WINDOW_HXX \/\/autogen\n#include \n#endif\n#ifndef _SELENG_HXX \/\/autogen\n#include \n#endif\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\n\n#define HDR_HORIZONTAL 0\n#define HDR_VERTICAL 1\n\n#define HDR_SIZE_OPTIMUM 0xFFFF\n\n\n \/\/ Groesse des Sliders\n#define HDR_SLIDERSIZE 2\n\nclass ScHeaderControl : public Window\n{\nprivate:\n SelectionEngine* pSelEngine;\n Font aNormFont;\n Font aBoldFont;\n BOOL bBoldSet;\n\n USHORT nFlags;\n BOOL bVertical; \/\/ Vertikal = Zeilenheader\n\n long nWidth;\n long nSmallWidth;\n long nBigWidth;\n\n SCCOLROW nSize;\n\n SCCOLROW nMarkStart;\n SCCOLROW nMarkEnd;\n BOOL bMarkRange;\n\n BOOL bDragging; \/\/ Groessen aendern\n SCCOLROW nDragNo;\n long nDragStart;\n long nDragPos;\n BOOL bDragMoved;\n\n BOOL bIgnoreMove;\n\n long GetScrPos( SCCOLROW nEntryNo );\n SCCOLROW GetMousePos( const MouseEvent& rMEvt, BOOL& rBorder );\n\n void ShowDragHelp();\n\n void DoPaint( SCCOLROW nStart, SCCOLROW nEnd );\n\nprotected:\n \/\/ von Window ueberladen\n\n virtual void Paint( const Rectangle& rRect );\n\n virtual void MouseMove( const MouseEvent& rMEvt );\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void Tracking( const TrackingEvent& rTEvt );\n\n virtual void RequestHelp( const HelpEvent& rHEvt );\n\n \/\/ neue Methoden\n\n virtual SCCOLROW GetPos() = 0; \/\/ aktuelle Position (Scrolling)\n virtual USHORT GetEntrySize( SCCOLROW nEntryNo ) = 0; \/\/ Breite \/ Hoehe (Pixel)\n virtual String GetEntryText( SCCOLROW nEntryNo ) = 0;\n\n virtual SCCOLROW GetHiddenCount( SCCOLROW nEntryNo );\n virtual BOOL IsLayoutRTL();\n virtual BOOL IsMirrored();\n\n virtual void SetEntrySize( SCCOLROW nPos, USHORT nNewWidth ) = 0;\n virtual void HideEntries( SCCOLROW nStart, SCCOLROW nEnd ) = 0;\n\n virtual void SetMarking( BOOL bSet );\n virtual void SelectWindow();\n virtual BOOL IsDisabled();\n virtual BOOL ResizeAllowed();\n virtual String GetDragHelp( long nVal );\n\n virtual void DrawInvert( long nDragPos );\n virtual void Command( const CommandEvent& rCEvt );\n\npublic:\n ScHeaderControl( Window* pParent, SelectionEngine* pSelectionEngine,\n SCCOLROW nNewSize, USHORT nNewFlags );\n ~ScHeaderControl();\n\n void SetIgnoreMove(BOOL bSet) { bIgnoreMove = bSet; }\n\n void StopMarking();\n\n void SetMark( BOOL bNewSet, SCCOLROW nNewStart, SCCOLROW nNewEnd );\n\n long GetWidth() const { return nWidth; }\n long GetSmallWidth() const { return nSmallWidth; }\n long GetBigWidth() const { return nBigWidth; }\n void SetWidth( long nNew );\n};\n\n\n\n#endif\n\nINTEGRATION: CWS ooo19126 (1.3.452); FILE MERGED 2005\/09\/05 15:05:28 rt 1.3.452.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hdrcont.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:31:21 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_HDRCONT_HXX\n#define SC_HDRCONT_HXX\n\n#ifndef _WINDOW_HXX \/\/autogen\n#include \n#endif\n#ifndef _SELENG_HXX \/\/autogen\n#include \n#endif\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\n\n#define HDR_HORIZONTAL 0\n#define HDR_VERTICAL 1\n\n#define HDR_SIZE_OPTIMUM 0xFFFF\n\n\n \/\/ Groesse des Sliders\n#define HDR_SLIDERSIZE 2\n\nclass ScHeaderControl : public Window\n{\nprivate:\n SelectionEngine* pSelEngine;\n Font aNormFont;\n Font aBoldFont;\n BOOL bBoldSet;\n\n USHORT nFlags;\n BOOL bVertical; \/\/ Vertikal = Zeilenheader\n\n long nWidth;\n long nSmallWidth;\n long nBigWidth;\n\n SCCOLROW nSize;\n\n SCCOLROW nMarkStart;\n SCCOLROW nMarkEnd;\n BOOL bMarkRange;\n\n BOOL bDragging; \/\/ Groessen aendern\n SCCOLROW nDragNo;\n long nDragStart;\n long nDragPos;\n BOOL bDragMoved;\n\n BOOL bIgnoreMove;\n\n long GetScrPos( SCCOLROW nEntryNo );\n SCCOLROW GetMousePos( const MouseEvent& rMEvt, BOOL& rBorder );\n\n void ShowDragHelp();\n\n void DoPaint( SCCOLROW nStart, SCCOLROW nEnd );\n\nprotected:\n \/\/ von Window ueberladen\n\n virtual void Paint( const Rectangle& rRect );\n\n virtual void MouseMove( const MouseEvent& rMEvt );\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void Tracking( const TrackingEvent& rTEvt );\n\n virtual void RequestHelp( const HelpEvent& rHEvt );\n\n \/\/ neue Methoden\n\n virtual SCCOLROW GetPos() = 0; \/\/ aktuelle Position (Scrolling)\n virtual USHORT GetEntrySize( SCCOLROW nEntryNo ) = 0; \/\/ Breite \/ Hoehe (Pixel)\n virtual String GetEntryText( SCCOLROW nEntryNo ) = 0;\n\n virtual SCCOLROW GetHiddenCount( SCCOLROW nEntryNo );\n virtual BOOL IsLayoutRTL();\n virtual BOOL IsMirrored();\n\n virtual void SetEntrySize( SCCOLROW nPos, USHORT nNewWidth ) = 0;\n virtual void HideEntries( SCCOLROW nStart, SCCOLROW nEnd ) = 0;\n\n virtual void SetMarking( BOOL bSet );\n virtual void SelectWindow();\n virtual BOOL IsDisabled();\n virtual BOOL ResizeAllowed();\n virtual String GetDragHelp( long nVal );\n\n virtual void DrawInvert( long nDragPos );\n virtual void Command( const CommandEvent& rCEvt );\n\npublic:\n ScHeaderControl( Window* pParent, SelectionEngine* pSelectionEngine,\n SCCOLROW nNewSize, USHORT nNewFlags );\n ~ScHeaderControl();\n\n void SetIgnoreMove(BOOL bSet) { bIgnoreMove = bSet; }\n\n void StopMarking();\n\n void SetMark( BOOL bNewSet, SCCOLROW nNewStart, SCCOLROW nNewEnd );\n\n long GetWidth() const { return nWidth; }\n long GetSmallWidth() const { return nSmallWidth; }\n long GetBigWidth() const { return nBigWidth; }\n void SetWidth( long nNew );\n};\n\n\n\n#endif\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sizedev.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:50:46 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_SIZEDEV_HXX\n#define SC_SIZEDEV_HXX\n\n#ifndef _SV_MAPMOD_HXX\n#include \n#endif\n\nclass OutputDevice;\nclass ScDocShell;\n\nclass ScSizeDeviceProvider\n{\n OutputDevice* pDevice;\n BOOL bOwner;\n double nPPTX;\n double nPPTY;\n MapMode aOldMapMode;\n\npublic:\n ScSizeDeviceProvider( ScDocShell* pDocSh );\n ~ScSizeDeviceProvider();\n\n OutputDevice* GetDevice() const { return pDevice; }\n double GetPPTX() const { return nPPTX; }\n double GetPPTY() const { return nPPTY; }\n BOOL IsPrinter() const { return !bOwner; }\n};\n\n#endif\n\nINTEGRATION: CWS changefileheader (1.3.700); FILE MERGED 2008\/04\/01 15:31:00 thb 1.3.700.2: #i85898# Stripping all external header guards 2008\/03\/31 17:15:48 rt 1.3.700.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sizedev.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SC_SIZEDEV_HXX\n#define SC_SIZEDEV_HXX\n\n#include \n\nclass OutputDevice;\nclass ScDocShell;\n\nclass ScSizeDeviceProvider\n{\n OutputDevice* pDevice;\n BOOL bOwner;\n double nPPTX;\n double nPPTY;\n MapMode aOldMapMode;\n\npublic:\n ScSizeDeviceProvider( ScDocShell* pDocSh );\n ~ScSizeDeviceProvider();\n\n OutputDevice* GetDevice() const { return pDevice; }\n double GetPPTX() const { return nPPTX; }\n double GetPPTY() const { return nPPTY; }\n BOOL IsPrinter() const { return !bOwner; }\n};\n\n#endif\n\n<|endoftext|>"} {"text":"\/*!\n * @author Richard Everhart\n * @date July 2017\n *\n * Declarations and template definitions for all tsty library \n * functions\n!*\/\n\n#ifndef TSTY_HPP__\n#define TSTY_HPP__\n\n#include \n#include \n\nnamespace tsty {\n\n\/\/! Rudimentary structure for storing RGB color values.\nstruct Rgb {\n unsigned char r = 0, g = 0, b = 0;\n\n \/\/! Constructor for initializing r, g, b values from a hexadecimal\n explicit Rgb(unsigned int hex);\n\n \/*! \n * Method for acquiring a hexadecimal representation of the rgb color \n * data.\n *\n * @return An unsigned integer that is the hexadecimal representation\n !*\/\n unsigned int hex();\n};\ntypedef Rgb rgb;\n\n\n\/\/! Enum containing flags representing various ANSI-Supported text emphasis\nenum Emphasis {\n NORMAL = 0x000001,\n BOLD = 0x000002,\n FAINT = 0x000004,\n ITALIC = 0x000008,\n UNDERLINE = 0x000010,\n SLOW_BLINK = 0x000020,\n FAST_BLINK = 0x000040,\n NEGATIVE = 0x000080,\n CONCEAL = 0x000100,\n CROSS_OUT = 0x000200,\n FRAKTUR = 0x000400,\n NO_BOLD = 0x000800,\n NO_COLOR = 0x001000,\n NO_ITALIC = 0x002000,\n NO_UNDERLINE = 0x004000,\n POSITIVE = 0x008000,\n REVEAL = 0x010000,\n NO_CROSS_OUT = 0x020000,\n FRAME = 0x040000,\n ENCIRCLE = 0x080000,\n OVERLINE = 0x100000,\n NO_FRAME = 0x200000,\n NO_OVERLINE = 0x400000\n};\ntypedef Emphasis emphasis;\n\n\/*!\n * Sets the current emphasis of all subsequent outputted text to correspond to\n * the emphasis specified by flags.\n *\n * Example usage:\n * @code\n * emphasis(ITALIC | NEGATIVE | FRAME);\n * @endcode\n *\n * @param flags A bit flag specifying the emphasis\n!*\/\nvoid emphasis_on(unsigned int flags);\n\n\/*!\n * Sets the current emphasis of all subsequent outputted text to correspond to\n * the emphasis specified by a variadic list of elements n.\n *\n * Example usage:\n * @code\n * emphasis(ITALIC, NEGATIVE, FRAME);\n * @endcode\n *\n * @param n A variadic list specifying the emphasis\n!*\/\nvoid emphasis_on(Emphasis n...);\n\n\/\/! Turns off any emphasis that may have been set previously using \nvoid emphasis_off();\n\n\/*!\n * Returns a string representing an ANSI escape sequence that may be printed\n * in the future to set the emphasis.\n *\n * Example usage:\n * @code\n * std::string str = ansi_emphasis(ITALIC | BOLD);\n * std::cout << str << \"Styled text!\" << std::endl;\n * @endcode\n *\n * @param flags A bit flag specifying the emphasis\n *\n * @return A string representing an ANSI escape sequence that may be pinted in\n * the future to set the emphasis.\n!*\/\nstd::string ansi_emphasis(unsigned int flags);\n\n\/*!\n * Returns a string representing an ANSI escape sequence that may be printed\n * in the future to set the emphasis.\n *\n * Example usage:\n * @code\n * std::string str = ansi_emphasis(ITALIC, BOLD);\n * std::cout << str << \"Styled text!\" << std::endl;\n * @endcode\n * \n * @param n A variadic list specifying the emphasis\n *\n * @return A string representing an ANSI escape sequence that may be pinted in\n * the future to set the emphasis.\n!*\/\nstd::string ansi_emphasis(Emphasis n...);\n\n}\n\n#endif\nAdded color_on(), color_off() and ansi_color() function declarations.\/*!\n * @author Richard Everhart\n * @date July 2017\n *\n * Declarations and template definitions for all tsty library \n * functions\n!*\/\n\n#ifndef TSTY_HPP__\n#define TSTY_HPP__\n\n#include \n#include \n\nnamespace tsty {\n\n\/\/! Rudimentary structure for storing RGB color values.\nstruct Rgb {\n unsigned char r = 0, g = 0, b = 0;\n\n \/\/! Constructor for initializing r, g, b values from a hexadecimal\n explicit Rgb(unsigned int hex);\n\n \/*! \n * Method for acquiring a hexadecimal representation of the rgb color \n * data.\n *\n * @return An unsigned integer that is the hexadecimal representation\n !*\/\n unsigned int hex();\n};\ntypedef Rgb rgb;\n\n\n\/\/! Enum containing flags representing various ANSI-Supported text emphasis\nenum Emphasis {\n NORMAL = 0x000001,\n BOLD = 0x000002,\n FAINT = 0x000004,\n ITALIC = 0x000008,\n UNDERLINE = 0x000010,\n SLOW_BLINK = 0x000020,\n FAST_BLINK = 0x000040,\n NEGATIVE = 0x000080,\n CONCEAL = 0x000100,\n CROSS_OUT = 0x000200,\n FRAKTUR = 0x000400,\n NO_BOLD = 0x000800,\n NO_COLOR = 0x001000,\n NO_ITALIC = 0x002000,\n NO_UNDERLINE = 0x004000,\n POSITIVE = 0x008000,\n REVEAL = 0x010000,\n NO_CROSS_OUT = 0x020000,\n FRAME = 0x040000,\n ENCIRCLE = 0x080000,\n OVERLINE = 0x100000,\n NO_FRAME = 0x200000,\n NO_OVERLINE = 0x400000\n};\ntypedef Emphasis emphasis;\n\n\/*!\n * Sets the current emphasis of all subsequent outputted text to correspond to\n * the emphasis specified by flags.\n *\n * Example usage:\n * @code\n * emphasis(ITALIC | NEGATIVE | FRAME);\n * @endcode\n *\n * @param flags A bit flag specifying the emphasis\n!*\/\nvoid emphasis_on(unsigned int flags);\n\n\/*!\n * Sets the current emphasis of all subsequent outputted text to correspond to\n * the emphasis specified by a variadic list of elements n.\n *\n * Example usage:\n * @code\n * emphasis(ITALIC, NEGATIVE, FRAME);\n * @endcode\n *\n * @param n A variadic list specifying the emphasis\n!*\/\nvoid emphasis_on(Emphasis n...);\n\n\/\/! Turns off any emphasis that may have been set previously\nvoid emphasis_off();\n\n\/*!\n * Returns a string representing an ANSI escape sequence that may be printed\n * in the future to set the emphasis.\n *\n * Example usage:\n * @code\n * std::string str = ansi_emphasis(ITALIC | BOLD);\n * std::cout << str << \"Styled text!\" << std::endl;\n * @endcode\n *\n * @param flags A bit flag specifying the emphasis\n *\n * @return A string representing an ANSI escape sequence that may be pinted in\n * the future to set the text emphasis.\n!*\/\nstd::string ansi_emphasis(unsigned int flags);\n\n\/*!\n * Returns a string representing an ANSI escape sequence that may be printed\n * in the future to set the emphasis.\n *\n * Example usage:\n * @code\n * std::string str = ansi_emphasis(ITALIC, BOLD);\n * std::cout << str << \"Styled text!\" << std::endl;\n * @endcode\n * \n * @param n A variadic list specifying the emphasis\n *\n * @return A string representing an ANSI escape sequence that may be printed\n * in the future to set the text emphasis.\n!*\/\nstd::string ansi_emphasis(Emphasis n...);\n\n\/*!\n * Sets the background and foreground colors of all subsequent outputted text\n * to correspond to the values specified by fg and bg, respectively.\n * \n * Example usage:\n * @code\n * color_on(rgb(127, 127, 255), rgb(255, 127, 127);\n * @endcode\n *\n * @param fg A rgb color value specifying the desired foreground color\n * @param bg A rgb color value specifying the desired background color\n!*\/\nvoid color_on(rgb fg, rgb bg);\n\n\/\/! Turns off any color that may have been set previously\nvoid color_off();\n\n\/*!\n * Returns a string representing an ANSI escape sequence that may be printed\n * in the future to set the text color.\n * \n * Example usage:\n * @code\n * std::string str = ansi_color(rgb(0, 0, 0), rgb(255, 255, 255));\n * std::cout << str << \"Black text on a white background!\" << std::endl;\n * @endcode\n *\n * @param fg A rgb color value specifying the desired foreground color\n * @param bg A rgb color value specifying the desired background color\n *\n * @return A string representing an ANSI escape sequence that may be printed\n * in the future to set the text color.\n!*\/\nansi_color(rgb fg, rgb bg);\n\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \"fencemodel.h\"\n\nusing namespace troen;\n\nFenceModel::FenceModel(FenceController* fenceController)\n{\n\tm_fenceController = fenceController;\n\tm_rigidBodies = std::vector>();\n}\n\nvoid FenceModel::addFencePart(btVector3 a, btVector3 b)\n{\n\tbtVector3 fenceVector = b - a;\n\t\n\t\/\/ TODO: convert to shared_ptr\n\tbtBoxShape *boxShape = new btBoxShape(btVector3(1, fenceVector.length() \/ 2, getFenceHeight() \/ 2));\n\t\n\tconst btVector3 up = btVector3(0, 0, 1);\n\tconst btVector3 forward = btVector3(0, 1, 0);\n\tconst btScalar angle = fenceVector.angle(forward);\n\n\tbtQuaternion rotationQuat;\n\tif (angle > 0) {\n\t\tbtVector3 axis = fenceVector.cross(-forward).normalized();\n\t\trotationQuat = btQuaternion(axis, angle);\n\t}\n\tbtDefaultMotionState *fenceMotionState = new btDefaultMotionState(btTransform(rotationQuat, (a + b) \/ 2 + btVector3(0, 0, getFenceHeight() \/ 2)));\n\n\tconst btScalar mass = 0;\n\tconst btVector3 fenceInertia(0, 0, 0);\n\t\n\tbtRigidBody::btRigidBodyConstructionInfo m_fenceRigidBodyCI(mass, fenceMotionState, boxShape, fenceInertia);\n\n\tstd::shared_ptr fenceRigidBody = std::make_shared(m_fenceRigidBodyCI);\n\n\tm_rigidBodies.push_back(fenceRigidBody);\n}\n\nbtRigidBody* FenceModel::getLastPart() {\n\treturn m_rigidBodies.back().get();\n}\n\nvoid FenceModel::addFenceMarker(btVector3 a)\n{\n\t\/\/ TODO: convert to shared_ptr\n\tbtBoxShape *boxShape = new btBoxShape(btVector3(0.5, 0.5, getFenceHeight() \/ 2));\n\t\n\tbtDefaultMotionState *fenceMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), a + btVector3(0, 0, getFenceHeight() \/ 4)));\n\n\t\/\/ set mass to zero so that we get a static rigidBody (is this enough?)\n\tbtScalar mass = 0;\n\tbtVector3 fenceInertia(0, 0, 0);\n\t\/\/ boxShape->calculateLocalInertia(mass, fenceInertia);www\n\n\tbtRigidBody::btRigidBodyConstructionInfo m_fenceRigidBodyCI(mass, fenceMotionState, boxShape, fenceInertia);\n\n\tstd::shared_ptr fenceRigidBody = std::make_shared(m_fenceRigidBodyCI);\n\n\tm_rigidBodies.push_back(fenceRigidBody);\n}\n\nfloat FenceModel::getFenceHeight()\n{\n\treturn 20;\n}fixes collision with fence sound, two lines of code got lost in merge#include \"fencemodel.h\"\n\nusing namespace troen;\n\nFenceModel::FenceModel(FenceController* fenceController)\n{\n\tm_fenceController = fenceController;\n\tm_rigidBodies = std::vector>();\n}\n\nvoid FenceModel::addFencePart(btVector3 a, btVector3 b)\n{\n\tbtVector3 fenceVector = b - a;\n\t\n\t\/\/ TODO: convert to shared_ptr\n\tbtBoxShape *boxShape = new btBoxShape(btVector3(1, fenceVector.length() \/ 2, getFenceHeight() \/ 2));\n\t\n\tconst btVector3 up = btVector3(0, 0, 1);\n\tconst btVector3 forward = btVector3(0, 1, 0);\n\tconst btScalar angle = fenceVector.angle(forward);\n\n\tbtQuaternion rotationQuat;\n\tif (angle > 0) {\n\t\tbtVector3 axis = fenceVector.cross(-forward).normalized();\n\t\trotationQuat = btQuaternion(axis, angle);\n\t}\n\tbtDefaultMotionState *fenceMotionState = new btDefaultMotionState(btTransform(rotationQuat, (a + b) \/ 2 + btVector3(0, 0, getFenceHeight() \/ 2)));\n\n\tconst btScalar mass = 0;\n\tconst btVector3 fenceInertia(0, 0, 0);\n\t\n\tbtRigidBody::btRigidBodyConstructionInfo m_fenceRigidBodyCI(mass, fenceMotionState, boxShape, fenceInertia);\n\n\tstd::shared_ptr fenceRigidBody = std::make_shared(m_fenceRigidBodyCI);\n\tfenceRigidBody->setUserPointer(m_fenceController);\n\n\tm_rigidBodies.push_back(fenceRigidBody);\n}\n\nbtRigidBody* FenceModel::getLastPart() {\n\treturn m_rigidBodies.back().get();\n}\n\nvoid FenceModel::addFenceMarker(btVector3 a)\n{\n\t\/\/ TODO: convert to shared_ptr\n\tbtBoxShape *boxShape = new btBoxShape(btVector3(0.5, 0.5, getFenceHeight() \/ 2));\n\t\n\tbtDefaultMotionState *fenceMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), a + btVector3(0, 0, getFenceHeight() \/ 4)));\n\n\t\/\/ set mass to zero so that we get a static rigidBody (is this enough?)\n\tbtScalar mass = 0;\n\tbtVector3 fenceInertia(0, 0, 0);\n\t\/\/ boxShape->calculateLocalInertia(mass, fenceInertia);www\n\n\tbtRigidBody::btRigidBodyConstructionInfo m_fenceRigidBodyCI(mass, fenceMotionState, boxShape, fenceInertia);\n\n\tstd::shared_ptr fenceRigidBody = std::make_shared(m_fenceRigidBodyCI);\n\tfenceRigidBody->setUserPointer(m_fenceController);\n\n\tm_rigidBodies.push_back(fenceRigidBody);\n}\n\nfloat FenceModel::getFenceHeight()\n{\n\treturn 20;\n}<|endoftext|>"} {"text":"#include \"picasso.h\"\n\n\/\/ !! Taken from ctrulib !!\nu32 f32tof24(float vf)\n{\n\tif (!vf) return 0;\n\n\tunion { float f; u32 v; } q;\n\tq.f=vf;\n\n\tu8 s = q.v>>31;\n\tu32 exp = ((q.v>>23) & 0xFF) - 0x40;\n\tu32 man = (q.v>>7) & 0xFFFF;\n\n\tif (exp >= 0)\n\t\treturn man | (exp<<16) | (s<<23);\n\telse\n\t\treturn s<<23;\n}\n\n#ifdef WIN32\nstatic inline void FixMinGWPath(char* buf)\n{\n\tif (buf && *buf == '\/')\n\t{\n\t\tbuf[0] = buf[1];\n\t\tbuf[1] = ':';\n\t}\n}\n#endif\n\nint usage(const char* prog)\n{\n\tfprintf(stderr,\n\t\t\"Usage:\\n\\n\"\n\t\t\"%s shbinFile vshFile [hFile]\\n\", prog);\n\treturn 0;\n}\n\nint main(int argc, char* argv[])\n{\n\tif (argc < 3 || argc > 4)\n\t\treturn usage(argv[0]);\n\n\tchar* shbinFile = argv[1];\n\tchar* vshFile = argv[2];\n\tchar* hFile = argc > 3 ? argv[3] : NULL;\n\n#ifdef WIN32\n\tFixMinGWPath(shbinFile);\n\tFixMinGWPath(vshFile);\n\tFixMinGWPath(hFile);\n#endif\n\n\tchar* sourceCode = StringFromFile(vshFile);\n\tif (!sourceCode)\n\t{\n\t\tfprintf(stderr, \"Cannot open input file!\\n\");\n\t\treturn 1;\n\t}\n\n\tint rc = AssembleString(sourceCode, vshFile);\n\tfree(sourceCode);\n\tif (rc != 0)\n\t\treturn rc;\n\n\tprocTableIter mainIt = g_procTable.find(\"main\");\n\tif (mainIt == g_procTable.end())\n\t{\n\t\tfprintf(stderr, \"Error: main proc not defined\\n\");\n\t\treturn 1;\n\t}\n\n\tFileClass f(shbinFile, \"wb\");\n\n\tif (f.openerror())\n\t{\n\t\tfprintf(stderr, \"Can't open output file!\");\n\t\treturn 1;\n\t}\n\n\tf.WriteWord(0x424C5644); \/\/ DVLB\n\tf.WriteWord(1); \/\/ 1 DVLE\n\tf.WriteWord(3*4 + 0x28); \/\/ offset to DVLE\n\n\tu32 dvlpStart = f.Tell();\n\tu32 shaderSize = g_outputBuf.size();\n\tu32 paramStart = 0x28 + 0x40;\n\n\tf.WriteWord(0x504C5644); \/\/ DVLP\n\tf.WriteWord(0); \/\/ version\n\tf.WriteWord(paramStart); \/\/ offset to shader binary blob\n\tf.WriteWord(shaderSize); \/\/ size of shader binary blob\n\tparamStart += shaderSize*4;\n\tf.WriteWord(paramStart); \/\/ offset to opdesc table\n\tf.WriteWord(g_opdescCount); \/\/ number of opdescs\n\tparamStart += g_opdescCount*8;\n\tf.WriteWord(paramStart); \/\/ offset to symtable (TODO)\n\tf.WriteWord(0); \/\/ ????\n\tf.WriteWord(0); \/\/ ????\n\tf.WriteWord(0); \/\/ ????\n\n\tu32 dvleStart = f.Tell();\n\tparamStart -= dvleStart - dvlpStart;\n\t\n\tf.WriteWord(0x454C5644); \/\/ DVLE\n\tf.WriteHword(0); \/\/ padding?\n\tf.WriteHword(0); \/\/ Vertex shader\n\tf.WriteWord(mainIt->second.first); \/\/ offset to main\n\tf.WriteWord(mainIt->second.first+mainIt->second.second); \/\/ offset to end of main\n\tf.WriteWord(0); \/\/ ???\n\tf.WriteWord(0); \/\/ ???\n\tf.WriteWord(paramStart); \/\/ offset to constant table\n\tf.WriteWord(g_constantCount); \/\/ size of constant table\n\tparamStart += g_constantCount*0x14;\n\tf.WriteWord(paramStart); \/\/ offset to label table (TODO)\n\tf.WriteWord(0); \/\/ size of label table (TODO)\n\tf.WriteWord(paramStart); \/\/ offset to output table\n\tf.WriteWord(g_outputCount); \/\/ size of output table\n\tparamStart += g_outputCount*8;\n\tf.WriteWord(paramStart); \/\/ offset to uniform table\n\tf.WriteWord(g_uniformCount); \/\/ size of uniform table\n\tparamStart += g_uniformCount*8;\n\tf.WriteWord(paramStart); \/\/ offset to symbol table\n\tu32 temp = f.Tell();\n\tf.WriteWord(0); \/\/ size of symbol table\n\n\t\/\/ Write program\n\t\/\/for (u32 p : g_outputBuf)\n\tfor (outputBufIter it = g_outputBuf.begin(); it != g_outputBuf.end(); ++it)\n\t\tf.WriteWord(*it);\n\n\t\/\/ Write opdescs\n\tfor (int i = 0; i < g_opdescCount; i ++)\n\t{\n\t\tf.WriteWord(g_opdescTable[i]);\n\t\tf.WriteWord(0x0000000F); \/\/ unknown\n\t}\n\n\t\/\/ Write constants\n\tfor (int i = 0; i < g_constantCount; i ++)\n\t{\n\t\tConstant& ct = g_constantTable[i];\n\t\tf.WriteHword(0);\n\t\tf.WriteByte(ct.regId-0x20);\n\t\tf.WriteByte(0);\n\t\tfor (int j = 0; j < 4; j ++)\n\t\t\tf.WriteWord(f32tof24(ct.param[j]));\n\t}\n\n\t\/\/ Write outputs\n\tfor (int i = 0; i < g_outputCount; i ++)\n\t\tf.WriteDword(g_outputTable[i]);\n\n\t\/\/ Write uniforms\n\tsize_t sp = 0;\n\tfor (int i = 0; i < g_uniformCount; i ++)\n\t{\n\t\tUniform& u = g_uniformTable[i];\n\t\tsize_t l = strlen(u.name)+1;\n\t\tf.WriteWord(sp); sp += l;\n\t\tf.WriteHword(u.pos-0x20);\n\t\tf.WriteHword(u.pos+u.size-1-0x20);\n\t}\n\n\t\/\/ Write size of symbol table\n\tu32 temp2 = f.Tell();\n\tf.Seek(temp, SEEK_SET);\n\tf.WriteWord(sp);\n\tf.Seek(temp2, SEEK_SET);\n\n\t\/\/ Write symbols\n\tfor (int i = 0; i < g_uniformCount; i ++)\n\t{\n\t\tconst char* u = g_uniformTable[i].name;\n\t\tsize_t l = strlen(u)+1;\n\t\tf.WriteRaw(u, l);\n\t}\n\n\tif (hFile)\n\t{\n\t\tFILE* f2 = fopen(hFile, \"w\");\n\t\tif (!f2)\n\t\t{\n\t\t\tfprintf(stderr, \"Can't open header file!\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tfprintf(f2, \"\/\/ Generated by picasso\\n\");\n\t\tfprintf(f2, \"#pragma once\\n\");\n\t\tfor (int i = 0; i < g_uniformCount; i ++)\n\t\t{\n\t\t\tUniform& u = g_uniformTable[i];\n\t\t\tfprintf(f2, \"#define SHADER_UREG_%s 0x%02X\\n\", u.name, u.pos-0x20);\n\t\t\tfprintf(f2, \"#define SHADER_ULEN_%s %d\\n\", u.name, u.size);\n\t\t}\n\n\t\tfclose(f2);\n\t}\n\n\treturn 0;\n}\nCorrect uniform handling value [pointed out by smea]#include \"picasso.h\"\n\n\/\/ !! Taken from ctrulib !!\nu32 f32tof24(float vf)\n{\n\tif (!vf) return 0;\n\n\tunion { float f; u32 v; } q;\n\tq.f=vf;\n\n\tu8 s = q.v>>31;\n\tu32 exp = ((q.v>>23) & 0xFF) - 0x40;\n\tu32 man = (q.v>>7) & 0xFFFF;\n\n\tif (exp >= 0)\n\t\treturn man | (exp<<16) | (s<<23);\n\telse\n\t\treturn s<<23;\n}\n\n#ifdef WIN32\nstatic inline void FixMinGWPath(char* buf)\n{\n\tif (buf && *buf == '\/')\n\t{\n\t\tbuf[0] = buf[1];\n\t\tbuf[1] = ':';\n\t}\n}\n#endif\n\nint usage(const char* prog)\n{\n\tfprintf(stderr,\n\t\t\"Usage:\\n\\n\"\n\t\t\"%s shbinFile vshFile [hFile]\\n\", prog);\n\treturn 0;\n}\n\nint main(int argc, char* argv[])\n{\n\tif (argc < 3 || argc > 4)\n\t\treturn usage(argv[0]);\n\n\tchar* shbinFile = argv[1];\n\tchar* vshFile = argv[2];\n\tchar* hFile = argc > 3 ? argv[3] : NULL;\n\n#ifdef WIN32\n\tFixMinGWPath(shbinFile);\n\tFixMinGWPath(vshFile);\n\tFixMinGWPath(hFile);\n#endif\n\n\tchar* sourceCode = StringFromFile(vshFile);\n\tif (!sourceCode)\n\t{\n\t\tfprintf(stderr, \"Cannot open input file!\\n\");\n\t\treturn 1;\n\t}\n\n\tint rc = AssembleString(sourceCode, vshFile);\n\tfree(sourceCode);\n\tif (rc != 0)\n\t\treturn rc;\n\n\tprocTableIter mainIt = g_procTable.find(\"main\");\n\tif (mainIt == g_procTable.end())\n\t{\n\t\tfprintf(stderr, \"Error: main proc not defined\\n\");\n\t\treturn 1;\n\t}\n\n\tFileClass f(shbinFile, \"wb\");\n\n\tif (f.openerror())\n\t{\n\t\tfprintf(stderr, \"Can't open output file!\");\n\t\treturn 1;\n\t}\n\n\tf.WriteWord(0x424C5644); \/\/ DVLB\n\tf.WriteWord(1); \/\/ 1 DVLE\n\tf.WriteWord(3*4 + 0x28); \/\/ offset to DVLE\n\n\tu32 dvlpStart = f.Tell();\n\tu32 shaderSize = g_outputBuf.size();\n\tu32 paramStart = 0x28 + 0x40;\n\n\tf.WriteWord(0x504C5644); \/\/ DVLP\n\tf.WriteWord(0); \/\/ version\n\tf.WriteWord(paramStart); \/\/ offset to shader binary blob\n\tf.WriteWord(shaderSize); \/\/ size of shader binary blob\n\tparamStart += shaderSize*4;\n\tf.WriteWord(paramStart); \/\/ offset to opdesc table\n\tf.WriteWord(g_opdescCount); \/\/ number of opdescs\n\tparamStart += g_opdescCount*8;\n\tf.WriteWord(paramStart); \/\/ offset to symtable (TODO)\n\tf.WriteWord(0); \/\/ ????\n\tf.WriteWord(0); \/\/ ????\n\tf.WriteWord(0); \/\/ ????\n\n\tu32 dvleStart = f.Tell();\n\tparamStart -= dvleStart - dvlpStart;\n\t\n\tf.WriteWord(0x454C5644); \/\/ DVLE\n\tf.WriteHword(0); \/\/ padding?\n\tf.WriteHword(0); \/\/ Vertex shader\n\tf.WriteWord(mainIt->second.first); \/\/ offset to main\n\tf.WriteWord(mainIt->second.first+mainIt->second.second); \/\/ offset to end of main\n\tf.WriteWord(0); \/\/ ???\n\tf.WriteWord(0); \/\/ ???\n\tf.WriteWord(paramStart); \/\/ offset to constant table\n\tf.WriteWord(g_constantCount); \/\/ size of constant table\n\tparamStart += g_constantCount*0x14;\n\tf.WriteWord(paramStart); \/\/ offset to label table (TODO)\n\tf.WriteWord(0); \/\/ size of label table (TODO)\n\tf.WriteWord(paramStart); \/\/ offset to output table\n\tf.WriteWord(g_outputCount); \/\/ size of output table\n\tparamStart += g_outputCount*8;\n\tf.WriteWord(paramStart); \/\/ offset to uniform table\n\tf.WriteWord(g_uniformCount); \/\/ size of uniform table\n\tparamStart += g_uniformCount*8;\n\tf.WriteWord(paramStart); \/\/ offset to symbol table\n\tu32 temp = f.Tell();\n\tf.WriteWord(0); \/\/ size of symbol table\n\n\t\/\/ Write program\n\t\/\/for (u32 p : g_outputBuf)\n\tfor (outputBufIter it = g_outputBuf.begin(); it != g_outputBuf.end(); ++it)\n\t\tf.WriteWord(*it);\n\n\t\/\/ Write opdescs\n\tfor (int i = 0; i < g_opdescCount; i ++)\n\t{\n\t\tf.WriteWord(g_opdescTable[i]);\n\t\tf.WriteWord(0x0000000F); \/\/ unknown\n\t}\n\n\t\/\/ Write constants\n\tfor (int i = 0; i < g_constantCount; i ++)\n\t{\n\t\tConstant& ct = g_constantTable[i];\n\t\tf.WriteHword(0);\n\t\tf.WriteByte(ct.regId-0x20);\n\t\tf.WriteByte(0);\n\t\tfor (int j = 0; j < 4; j ++)\n\t\t\tf.WriteWord(f32tof24(ct.param[j]));\n\t}\n\n\t\/\/ Write outputs\n\tfor (int i = 0; i < g_outputCount; i ++)\n\t\tf.WriteDword(g_outputTable[i]);\n\n\t\/\/ Write uniforms\n\tsize_t sp = 0;\n\tfor (int i = 0; i < g_uniformCount; i ++)\n\t{\n\t\tUniform& u = g_uniformTable[i];\n\t\tsize_t l = strlen(u.name)+1;\n\t\tf.WriteWord(sp); sp += l;\n\t\tf.WriteHword(u.pos-0x10);\n\t\tf.WriteHword(u.pos+u.size-1-0x10);\n\t}\n\n\t\/\/ Write size of symbol table\n\tu32 temp2 = f.Tell();\n\tf.Seek(temp, SEEK_SET);\n\tf.WriteWord(sp);\n\tf.Seek(temp2, SEEK_SET);\n\n\t\/\/ Write symbols\n\tfor (int i = 0; i < g_uniformCount; i ++)\n\t{\n\t\tconst char* u = g_uniformTable[i].name;\n\t\tsize_t l = strlen(u)+1;\n\t\tf.WriteRaw(u, l);\n\t}\n\n\tif (hFile)\n\t{\n\t\tFILE* f2 = fopen(hFile, \"w\");\n\t\tif (!f2)\n\t\t{\n\t\t\tfprintf(stderr, \"Can't open header file!\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tfprintf(f2, \"\/\/ Generated by picasso\\n\");\n\t\tfprintf(f2, \"#pragma once\\n\");\n\t\tfor (int i = 0; i < g_uniformCount; i ++)\n\t\t{\n\t\t\tUniform& u = g_uniformTable[i];\n\t\t\tfprintf(f2, \"#define SHADER_UREG_%s 0x%02X\\n\", u.name, u.pos-0x20);\n\t\t\tfprintf(f2, \"#define SHADER_ULEN_%s %d\\n\", u.name, u.size);\n\t\t}\n\n\t\tfclose(f2);\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/@\t{\"targets\":[{\"name\":\"type.hpp\",\"type\":\"include\"}]}\n\n#ifndef TEMPLE_TYPE_HPP\n#define TEMPLE_TYPE_HPP\n\n#include \"error.hpp\"\n#include \n#include \n\nnamespace Temple\n\t{\n\tenum class Type:int\n\t\t{\n\t\t I8=0,I8_ARRAY\n\t\t,I16,I16_ARRAY\n\t\t,I32,I32_ARRAY\n\t\t,I64,I64_ARRAY\n\t\t,FLOAT,FLOAT_ARRAY\n\t\t,DOUBLE,DOUBLE_ARRAY\n\t\t,STRING,STRING_ARRAY\n\t\t,COMPOUND,COMPOUND_ARRAY\n\t\t};\n\n\tinline constexpr Type arraySet(Type t)\n\t\t{return static_cast(static_cast(t) | 1);}\n\n\tinline constexpr Type arrayUnset(Type t)\n\t\t{return static_cast(static_cast(t)&( ~1));}\n\n\tinline constexpr Type next(Type t)\n\t\t{return static_cast(static_cast(t) + 1);}\n\n\tinline constexpr Type step(Type t,int x)\n\t\t{return static_cast(static_cast(t) + x);}\n\n\tinline constexpr Type previous(Type t)\n\t\t{return static_cast(static_cast(t) - 1);}\n\n\n\n\ttemplate\n\tstruct TypeGet:private TypeGet\n\t\t{\n\t\ttypedef typename TypeGet::type BaseType;\n\t\tstatic constexpr auto id=t;\n\t\ttypedef typename StorageModel::template ArrayType type;\n\t\t};\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I8;\n\t\ttypedef int8_t type;\n\t\t};\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I16;\n\t\ttypedef int8_t type;\n\t\t};\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I32;\n\t\ttypedef int32_t type;\n\t\t};\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I64;\n\t\ttypedef int64_t type;\n\t\t};\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::FLOAT;\n\t\ttypedef float type;\n\t\t};\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::DOUBLE;\n\t\ttypedef double type;\n\t\t};\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::STRING;\n\t\ttypedef typename StorageModel::StringType type;\n\t\t};\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::COMPOUND;\n\t\ttypedef void type;\n\t\t};\n\n\n\n\ttemplate\n\tstruct TypeProcess\n\t\t{\n\t\ttemplate\n\t\tstatic void doIt(Type type,Callback& cb,ExceptionHandler& eh)\n\t\t\t{\t\n\t\t\tif(t==type)\n\t\t\t\t{\n\t\t\t\tcb(TypeGet{});\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tstatic constexpr auto t_next=step(t,x);\n\t\t\t\tstatic constexpr bool cont_next=static_cast(t_next) <= static_cast(t_end);\n\t\t\t\tTypeProcess::doIt(type,cb,eh);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\ttemplate\n\tstruct TypeProcess\n\t\t{\n\t\ttemplate\n\t\tstatic void doIt(Type type,Callback& cb,ExceptionHandler& eh)\n\t\t\t{eh.raise(Error(\"Internal error: Type not found.\"));}\n\t\t};\n\n\ttemplate\n\tinline void for_type(Type type,Callback&& cb,ExceptionHandler& eh) \n\t\t{TypeProcess::doIt(type,cb,eh);}\n\n\ttemplate\n\tinline Type type(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tif(str==\"s\")\n\t\t\t{return Type::STRING;}\n\t\tif(str==\"i8\")\n\t\t\t{return Type::I8;}\n\t\tif(str==\"i16\")\n\t\t\t{return Type::I16;}\n\t\tif(str==\"i32\")\n\t\t\t{return Type::I32;}\n\t\tif(str==\"i64\")\n\t\t\t{return Type::I64;}\n\t\tif(str==\"f\")\n\t\t\t{return Type::FLOAT;}\n\t\tif(str==\"d\")\n\t\t\t{return Type::DOUBLE;}\n\t\tif(str==\"\")\n\t\t\t{return Type::COMPOUND;}\n\t\teh.raise(Error(\"The type identifier \",str.c_str(),\" does not correspond to a known type.\"));\n\t\treturn Type::COMPOUND;\n\t\t}\n\n\tinline const char* type(Type type)\n\t\t{\n\t\tswitch(arrayUnset(type))\n\t\t\t{\n\t\t\tcase Type::I8:\n\t\t\t\treturn \"i8\";\n\t\t\tcase Type::I16:\n\t\t\t\treturn \"i16\";\n\t\t\tcase Type::I32:\n\t\t\t\treturn \"i32\";\n\t\t\tcase Type::I64:\n\t\t\t\treturn \"i64\";\n\t\t\tcase Type::FLOAT:\n\t\t\t\treturn \"f\";\n\t\t\tcase Type::DOUBLE:\n\t\t\t\treturn \"d\";\n\t\t\tcase Type::STRING:\n\t\t\t\treturn \"s\";\n\t\t\tcase Type::COMPOUND:\n\t\t\t\treturn \"\";\n\t\t\tdefault:\n\t\t\t\tassert(1!=1);\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\tassert(1!=1);\n\t\treturn nullptr;\n\t\t}\n\t}\n\n#endif\nInverse type map\/\/@\t{\"targets\":[{\"name\":\"type.hpp\",\"type\":\"include\"}]}\n\n#ifndef TEMPLE_TYPE_HPP\n#define TEMPLE_TYPE_HPP\n\n#include \"error.hpp\"\n\/\/#include \"stringconst.hpp\"\n#include \n#include \n\nnamespace Temple\n\t{\n\tenum class Type:int\n\t\t{\n\t\t I8=0,I8_ARRAY\n\t\t,I16,I16_ARRAY\n\t\t,I32,I32_ARRAY\n\t\t,I64,I64_ARRAY\n\t\t,FLOAT,FLOAT_ARRAY\n\t\t,DOUBLE,DOUBLE_ARRAY\n\t\t,STRING,STRING_ARRAY\n\t\t,COMPOUND,COMPOUND_ARRAY\n\t\t};\n\n\tinline constexpr Type arraySet(Type t)\n\t\t{return static_cast(static_cast(t) | 1);}\n\n\tinline constexpr Type arrayUnset(Type t)\n\t\t{return static_cast(static_cast(t)&( ~1));}\n\n\tinline constexpr Type next(Type t)\n\t\t{return static_cast(static_cast(t) + 1);}\n\n\tinline constexpr Type step(Type t,int x)\n\t\t{return static_cast(static_cast(t) + x);}\n\n\tinline constexpr Type previous(Type t)\n\t\t{return static_cast(static_cast(t) - 1);}\n\n\n\n\n\n\ttemplate\n\tstruct TypeGet:private TypeGet\n\t\t{\n\t\ttypedef typename TypeGet::type BaseType;\n\t\tstatic constexpr auto id=t;\n\t\ttypedef typename StorageModel::template ArrayType type;\n\n\n\/*\t\tstatic constexpr auto name_buffer=concat(TypeGet::name,\" array\");\n\t\tstatic constexpr const char* name=name_buffer.begin();*\/\n\t\t};\n\n\ttemplate\n\tstruct IdGet\n\t\t{\n\t\tstatic constexpr auto id=arraySet(IdGet::id);\n\t\ttypedef T type;\n\t\t};\n\n\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I8;\n\t\ttypedef int8_t type;\n\t\t};\n\n\ttemplate\n\tstruct IdGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I8;\n\t\ttypedef int8_t type;\n\t\t};\n\n\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I16;\n\t\ttypedef int8_t type;\n\t\t};\n\n\ttemplate\n\tstruct IdGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I16;\n\t\ttypedef int16_t type;\n\t\t};\n\n\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I32;\n\t\ttypedef int32_t type;\n\t\t};\n\n\ttemplate\n\tstruct IdGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I32;\n\t\ttypedef int32_t type;\n\t\t};\n\n\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I64;\n\t\ttypedef int64_t type;\n\t\t};\n\n\ttemplate\n\tstruct IdGet\n\t\t{\n\t\tstatic constexpr auto id=Type::I64;\n\t\ttypedef int64_t type;\n\t\t};\n\n\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::FLOAT;\n\t\ttypedef float type;\n\t\t};\n\n\ttemplate\n\tstruct IdGet\n\t\t{\n\t\tstatic constexpr auto id=Type::FLOAT;\n\t\ttypedef float type;\n\t\t};\n\n\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::DOUBLE;\n\t\ttypedef double type;\n\t\t};\n\n\ttemplate\n\tstruct IdGet\n\t\t{\n\t\tstatic constexpr auto id=Type::DOUBLE;\n\t\ttypedef double type;\n\t\t};\n\n\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::STRING;\n\t\ttypedef typename StorageModel::StringType type;\n\t\t};\n\n\ttemplate\n\tstruct IdGet\n\t\t{\n\t\tstatic constexpr auto id=Type::STRING;\n\t\ttypedef typename StorageModel::StringType type;\n\t\t};\n\n\n\n\ttemplate\n\tstruct TypeGet\n\t\t{\n\t\tstatic constexpr auto id=Type::COMPOUND;\n\t\ttypedef void type;\n\t\t};\n\n\n\n\ttemplate\n\tstruct TypeProcess\n\t\t{\n\t\ttemplate\n\t\tstatic void doIt(Type type,Callback& cb,ExceptionHandler& eh)\n\t\t\t{\t\n\t\t\tif(t==type)\n\t\t\t\t{\n\t\t\t\tcb(TypeGet{});\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tstatic constexpr auto t_next=step(t,x);\n\t\t\t\tstatic constexpr bool cont_next=static_cast(t_next) <= static_cast(t_end);\n\t\t\t\tTypeProcess::doIt(type,cb,eh);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\ttemplate\n\tstruct TypeProcess\n\t\t{\n\t\ttemplate\n\t\tstatic void doIt(Type type,Callback& cb,ExceptionHandler& eh)\n\t\t\t{eh.raise(Error(\"Internal error: Type not found.\"));}\n\t\t};\n\n\ttemplate\n\tinline void for_type(Type type,Callback&& cb,ExceptionHandler& eh) \n\t\t{TypeProcess::doIt(type,cb,eh);}\n\n\ttemplate\n\tinline Type type(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tif(str==\"s\")\n\t\t\t{return Type::STRING;}\n\t\tif(str==\"i8\")\n\t\t\t{return Type::I8;}\n\t\tif(str==\"i16\")\n\t\t\t{return Type::I16;}\n\t\tif(str==\"i32\")\n\t\t\t{return Type::I32;}\n\t\tif(str==\"i64\")\n\t\t\t{return Type::I64;}\n\t\tif(str==\"f\")\n\t\t\t{return Type::FLOAT;}\n\t\tif(str==\"d\")\n\t\t\t{return Type::DOUBLE;}\n\t\tif(str==\"\")\n\t\t\t{return Type::COMPOUND;}\n\t\teh.raise(Error(\"The type identifier \",str.c_str(),\" does not correspond to a known type.\"));\n\t\treturn Type::COMPOUND;\n\t\t}\n\n\tinline const char* type(Type type)\n\t\t{\n\t\tswitch(arrayUnset(type))\n\t\t\t{\n\t\t\tcase Type::I8:\n\t\t\t\treturn \"i8\";\n\t\t\tcase Type::I16:\n\t\t\t\treturn \"i16\";\n\t\t\tcase Type::I32:\n\t\t\t\treturn \"i32\";\n\t\t\tcase Type::I64:\n\t\t\t\treturn \"i64\";\n\t\t\tcase Type::FLOAT:\n\t\t\t\treturn \"f\";\n\t\t\tcase Type::DOUBLE:\n\t\t\t\treturn \"d\";\n\t\t\tcase Type::STRING:\n\t\t\t\treturn \"s\";\n\t\t\tcase Type::COMPOUND:\n\t\t\t\treturn \"\";\n\t\t\tdefault:\n\t\t\t\tassert(1!=1);\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\tassert(1!=1);\n\t\treturn nullptr;\n\t\t}\n\t}\n\n#endif\n<|endoftext|>"} {"text":"#include \"Game.hpp\"\n#include \"chimera\/core\/device\/JoystickManager.hpp\"\n#include \"chimera\/core\/utils.hpp\"\n#include \"chimera\/render\/scene\/Components.hpp\"\n\nGame::Game(Chimera::Scene& scene) : pCorpoRigido(nullptr), scene(&scene) { SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Constructor Game\"); }\n\nGame::~Game() { SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Destructor Game\"); }\n\nbool Game::onEvent(const SDL_Event& event) {\n using namespace Chimera;\n\n switch (event.type) {\n case SDL_USEREVENT: {\n switch (event.user.code) {\n case Chimera::EVENT_COLLIDE_START: {\n uint32_t* n1 = (uint32_t*)event.user.data1;\n uint32_t* n2 = (uint32_t*)event.user.data2;\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Colisao start: %d -> %d\", *n1, *n2);\n } break;\n case Chimera::EVENT_COLLIDE_ON: {\n uint32_t* n1 = (uint32_t*)event.user.data1;\n uint32_t* n2 = (uint32_t*)event.user.data2;\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Colisao ON: %d -> %d\", *n1, *n2);\n } break;\n case Chimera::EVENT_COLLIDE_OFF: {\n uint32_t* n1 = (uint32_t*)event.user.data1;\n uint32_t* n2 = (uint32_t*)event.user.data2;\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Colisao OFF: %d -> %d\", *n1, *n2);\n } break;\n case Chimera::EVENT_NEW_FPS: {\n uint32_t* pFps = (uint32_t*)event.user.data1;\n fps = *pFps;\n \/\/ glm::vec3 val1 = pCorpoRigido->getPosition();\n \/\/ sPosicaoObj = \"pos:(\" + std::to_string(val1.x) + \",\" + std::to_string(val1.y) + \",\" + std::to_string(val1.z) + \")\";\n } break;\n default:\n break;\n }\n\n } break;\n case SDL_KEYDOWN: {\n switch (event.key.keysym.sym) {\n case SDLK_ESCAPE:\n utilSendEvent(EVENT_FLOW_STOP, nullptr, nullptr);\n break;\n \/\/ case SDLK_F1:\n \/\/ pHUD->setOn(!pHUD->isOn());\n \/\/ break;\n case SDLK_F10:\n utilSendEvent(EVENT_TOGGLE_FULL_SCREEN, nullptr, nullptr);\n break;\n case SDLK_UP:\n pCorpoRigido->applyForce(glm::vec3(10.0, 0.0, 0.0));\n break;\n case SDLK_DOWN:\n pCorpoRigido->applyForce(glm::vec3(-10.0, 0.0, 0.0));\n break;\n case SDLK_LEFT:\n pCorpoRigido->applyForce(glm::vec3(0.0, 10.0, 0.0));\n break;\n case SDLK_RIGHT:\n pCorpoRigido->applyForce(glm::vec3(0.0, -10.0, 0.0));\n break;\n case SDLK_a:\n pCorpoRigido->applyTorc(glm::vec3(0.0, 0.0, 10.0));\n break;\n case SDLK_s:\n pCorpoRigido->applyTorc(glm::vec3(0.0, 0.0, -10.0));\n break;\n default:\n break;\n }\n } break;\n\n case SDL_JOYAXISMOTION:\n case SDL_JOYBUTTONDOWN:\n case SDL_JOYBUTTONUP:\n case SDL_JOYHATMOTION:\n case SDL_JOYBALLMOTION: {\n\n JoystickState* pJoy = JoystickManager::select(event.jball.which);\n\n \/\/ Captura joystick 0 se existir\n if (pJoy != nullptr) {\n\n pJoy->debug();\n\n float propulsaoPrincipal = 3.0f;\n\n crt.yaw = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_X, 32));\n crt.pitch = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_Y, 32));\n crt.roll = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::RIGHT_X, 32));\n\n double throttle = 0;\n crt.throttle = -propulsaoPrincipal * ((1 + JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_TRIGGER))) \/ 2);\n\n if (pJoy->getButtonState((uint8_t)JOY_BUTTON_COD::X) == SDL_PRESSED) {\n \/\/ glm::vec3 posicao = pEmissor->getPosSource();\n \/\/ posicao.x = posicao.x - 0.1f;\n \/\/ pEmissor->setPosSource( posicao );\n }\n\n if (pJoy->getButtonState((uint8_t)JOY_BUTTON_COD::B) == SDL_PRESSED) { \/\/ ( or SDL_RELEASED)\n \/\/ glm::vec3 posicao = pEmissor->getPosSource();\n \/\/ posicao.x = posicao.x + 0.1f;\n \/\/ pEmissor->setPosSource(posicao);\n }\n\n crt.hat = pJoy->getHat(0);\n }\n\n } break;\n\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n case SDL_MOUSEMOTION: {\n } break;\n case SDL_WINDOWEVENT: {\n switch (event.window.event) {\n case SDL_WINDOWEVENT_ENTER:\n utilSendEvent(EVENT_FLOW_RESUME, nullptr, nullptr); \/\/ isPaused = false;\n break;\n case SDL_WINDOWEVENT_LEAVE:\n utilSendEvent(EVENT_FLOW_PAUSE, nullptr, nullptr); \/\/ isPaused = true;\n break;\n }\n } break;\n }\n return true;\n}\n\nvoid Game::onAttach() {\n\n using namespace Chimera;\n \/\/ Localiza objeto como o primario\n TransComponent& tc = scene->getRegistry()->findComponent(\"Zoltan\");\n pCorpoRigido = (Solid*)tc.trans;\n\n lFPS = new Label(\"None\", -500, 280, glm::vec4(1.0, 1.0, 1.0, 1.0));\n Tile* tile = (Tile*)scene->getLayes().getState(\"TileText\");\n tile->add(lFPS);\n\n glClearColor(0.f, 0.f, 0.f, 1.f); \/\/ Initialize clear color\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_CULL_FACE);\n\n glClearDepth(1.0f);\n glDepthFunc(GL_LEQUAL);\n glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n}\n\nvoid Game::onDeatach() {}\n\nvoid Game::onUpdate(const double& ts) {\n\n if (pCorpoRigido)\n scene->setOrigem(pCorpoRigido);\n\n using namespace Chimera;\n\n float propulsaoLRUD = 5.0f;\n float torque = 0.5f;\n\n if (pCorpoRigido) {\n if (crt.hat & (uint8_t)SDL_HAT_UP)\n pCorpoRigido->applyForce(glm::vec3(0.0, 0.0, propulsaoLRUD));\n\n if (crt.hat & (uint8_t)SDL_HAT_DOWN)\n pCorpoRigido->applyForce(glm::vec3(0.0, 0.0, -propulsaoLRUD));\n\n if (crt.hat & (uint8_t)SDL_HAT_RIGHTUP)\n pCorpoRigido->applyForce(glm::vec3(propulsaoLRUD, 0.0, 0.0));\n\n if (crt.hat & (uint8_t)SDL_HAT_LEFTUP)\n pCorpoRigido->applyForce(glm::vec3(-propulsaoLRUD, 0.0, 0.0));\n\n if ((crt.roll != 0.0) || (crt.pitch != 0.0) || (crt.yaw != 0.0) || (crt.throttle != 0.0)) {\n pCorpoRigido->applyForce(glm::vec3(0.0, crt.throttle, 0.0));\n pCorpoRigido->applyTorc(glm::vec3(-torque * crt.pitch, -torque * crt.roll, -torque * crt.yaw));\n }\n }\n\n lFPS->setText(std::string(\"FPS: \") + std::to_string(fps));\n}\n\nvoid Game::onRender() {}Grupo2d funcional junto a texto no models3#include \"Game.hpp\"\n#include \"chimera\/core\/device\/JoystickManager.hpp\"\n#include \"chimera\/core\/utils.hpp\"\n#include \"chimera\/render\/2d\/Group.hpp\"\n#include \"chimera\/render\/2d\/Sprite.hpp\"\n#include \"chimera\/render\/scene\/Components.hpp\"\n\nGame::Game(Chimera::Scene& scene) : pCorpoRigido(nullptr), scene(&scene) { SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Constructor Game\"); }\n\nGame::~Game() { SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Destructor Game\"); }\n\nbool Game::onEvent(const SDL_Event& event) {\n using namespace Chimera;\n\n switch (event.type) {\n case SDL_USEREVENT: {\n switch (event.user.code) {\n case Chimera::EVENT_COLLIDE_START: {\n uint32_t* n1 = (uint32_t*)event.user.data1;\n uint32_t* n2 = (uint32_t*)event.user.data2;\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Colisao start: %d -> %d\", *n1, *n2);\n } break;\n case Chimera::EVENT_COLLIDE_ON: {\n uint32_t* n1 = (uint32_t*)event.user.data1;\n uint32_t* n2 = (uint32_t*)event.user.data2;\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Colisao ON: %d -> %d\", *n1, *n2);\n } break;\n case Chimera::EVENT_COLLIDE_OFF: {\n uint32_t* n1 = (uint32_t*)event.user.data1;\n uint32_t* n2 = (uint32_t*)event.user.data2;\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Colisao OFF: %d -> %d\", *n1, *n2);\n } break;\n case Chimera::EVENT_NEW_FPS: {\n uint32_t* pFps = (uint32_t*)event.user.data1;\n fps = *pFps;\n \/\/ glm::vec3 val1 = pCorpoRigido->getPosition();\n \/\/ sPosicaoObj = \"pos:(\" + std::to_string(val1.x) + \",\" + std::to_string(val1.y) + \",\" + std::to_string(val1.z) + \")\";\n } break;\n default:\n break;\n }\n\n } break;\n case SDL_KEYDOWN: {\n switch (event.key.keysym.sym) {\n case SDLK_ESCAPE:\n utilSendEvent(EVENT_FLOW_STOP, nullptr, nullptr);\n break;\n \/\/ case SDLK_F1:\n \/\/ pHUD->setOn(!pHUD->isOn());\n \/\/ break;\n case SDLK_F10:\n utilSendEvent(EVENT_TOGGLE_FULL_SCREEN, nullptr, nullptr);\n break;\n case SDLK_UP:\n pCorpoRigido->applyForce(glm::vec3(10.0, 0.0, 0.0));\n break;\n case SDLK_DOWN:\n pCorpoRigido->applyForce(glm::vec3(-10.0, 0.0, 0.0));\n break;\n case SDLK_LEFT:\n pCorpoRigido->applyForce(glm::vec3(0.0, 10.0, 0.0));\n break;\n case SDLK_RIGHT:\n pCorpoRigido->applyForce(glm::vec3(0.0, -10.0, 0.0));\n break;\n case SDLK_a:\n pCorpoRigido->applyTorc(glm::vec3(0.0, 0.0, 10.0));\n break;\n case SDLK_s:\n pCorpoRigido->applyTorc(glm::vec3(0.0, 0.0, -10.0));\n break;\n default:\n break;\n }\n } break;\n\n case SDL_JOYAXISMOTION:\n case SDL_JOYBUTTONDOWN:\n case SDL_JOYBUTTONUP:\n case SDL_JOYHATMOTION:\n case SDL_JOYBALLMOTION: {\n\n JoystickState* pJoy = JoystickManager::select(event.jball.which);\n\n \/\/ Captura joystick 0 se existir\n if (pJoy != nullptr) {\n\n pJoy->debug();\n\n float propulsaoPrincipal = 3.0f;\n\n crt.yaw = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_X, 32));\n crt.pitch = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_Y, 32));\n crt.roll = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::RIGHT_X, 32));\n\n double throttle = 0;\n crt.throttle = -propulsaoPrincipal * ((1 + JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_TRIGGER))) \/ 2);\n\n if (pJoy->getButtonState((uint8_t)JOY_BUTTON_COD::X) == SDL_PRESSED) {\n \/\/ glm::vec3 posicao = pEmissor->getPosSource();\n \/\/ posicao.x = posicao.x - 0.1f;\n \/\/ pEmissor->setPosSource( posicao );\n }\n\n if (pJoy->getButtonState((uint8_t)JOY_BUTTON_COD::B) == SDL_PRESSED) { \/\/ ( or SDL_RELEASED)\n \/\/ glm::vec3 posicao = pEmissor->getPosSource();\n \/\/ posicao.x = posicao.x + 0.1f;\n \/\/ pEmissor->setPosSource(posicao);\n }\n\n crt.hat = pJoy->getHat(0);\n }\n\n } break;\n\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n case SDL_MOUSEMOTION: {\n } break;\n case SDL_WINDOWEVENT: {\n switch (event.window.event) {\n case SDL_WINDOWEVENT_ENTER:\n utilSendEvent(EVENT_FLOW_RESUME, nullptr, nullptr); \/\/ isPaused = false;\n break;\n case SDL_WINDOWEVENT_LEAVE:\n utilSendEvent(EVENT_FLOW_PAUSE, nullptr, nullptr); \/\/ isPaused = true;\n break;\n }\n } break;\n }\n return true;\n}\n\nvoid Game::onAttach() {\n\n using namespace Chimera;\n \/\/ Localiza objeto como o primario\n TransComponent& tc = scene->getRegistry()->findComponent(\"Zoltan\");\n pCorpoRigido = (Solid*)tc.trans;\n\n lFPS = new Label(\"None\", 0, 0, glm::vec4(1.0, 1.0, 1.0, 1.0));\n Tile* tile = (Tile*)scene->getLayes().getState(\"TileText\");\n\n Group* group = new Group(glm::translate(glm::mat4(1.0f), glm::vec3(-500.0f, 270.0f, 0.0f)));\n group->add(new Sprite(0.0f, 0.0f, 200.0f, 50.0f, glm::vec4(0, 0, 1, 1)));\n group->add(lFPS);\n tile->add(group);\n \/\/ tile->add(lFPS);\n\n glClearColor(0.f, 0.f, 0.f, 1.f); \/\/ Initialize clear color\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_CULL_FACE);\n\n glClearDepth(1.0f);\n glDepthFunc(GL_LEQUAL);\n glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n}\n\nvoid Game::onDeatach() {}\n\nvoid Game::onUpdate(const double& ts) {\n\n if (pCorpoRigido)\n scene->setOrigem(pCorpoRigido);\n\n using namespace Chimera;\n\n float propulsaoLRUD = 5.0f;\n float torque = 0.5f;\n\n if (pCorpoRigido) {\n if (crt.hat & (uint8_t)SDL_HAT_UP)\n pCorpoRigido->applyForce(glm::vec3(0.0, 0.0, propulsaoLRUD));\n\n if (crt.hat & (uint8_t)SDL_HAT_DOWN)\n pCorpoRigido->applyForce(glm::vec3(0.0, 0.0, -propulsaoLRUD));\n\n if (crt.hat & (uint8_t)SDL_HAT_RIGHTUP)\n pCorpoRigido->applyForce(glm::vec3(propulsaoLRUD, 0.0, 0.0));\n\n if (crt.hat & (uint8_t)SDL_HAT_LEFTUP)\n pCorpoRigido->applyForce(glm::vec3(-propulsaoLRUD, 0.0, 0.0));\n\n if ((crt.roll != 0.0) || (crt.pitch != 0.0) || (crt.yaw != 0.0) || (crt.throttle != 0.0)) {\n pCorpoRigido->applyForce(glm::vec3(0.0, crt.throttle, 0.0));\n pCorpoRigido->applyTorc(glm::vec3(-torque * crt.pitch, -torque * crt.roll, -torque * crt.yaw));\n }\n }\n\n lFPS->setText(std::string(\"FPS: \") + std::to_string(fps));\n}\n\nvoid Game::onRender() {}<|endoftext|>"} {"text":"#include \n#include \nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n cout << \" |\";\n for (int x = 1; x<=12; ++x)\n {\n cout <fixed table.closes #35#include \n#include \nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n cout << \" |\";\n for (int x = 1; x<=12; ++x)\n {\n cout <"} {"text":"#include \"StateSpace.h\"\n\nStateSpace::StateSpace(const unsigned int _angle_max, const unsigned int _velocity_max, PriorityQueue queue ):\n\tangle_max(_angle_max),\n\tvelocity_max(_velocity_max),\n\tspace(_angle_max, std::vector< PriorityQueue > (_velocity_max, PriorityQueue (queue)))\n{}\n\nStateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state)\n{\n\t\/\/throw if the the index is out of bounds\n\tif(robot_state>1)throw std::domain_error(\"action index exceeded\");\n\t\/\/return proxy object to accept second [] operator\n\treturn SubscriptProxy1( robot_state ? space1 : space2 );\n}\n\n\/\/searches state space by state object\nPriorityQueue& StateSpace::operator[](const State & state)\n{\n\t\/\/call the subscript operators with the members of the state object\n\treturn (*this)[state.robot_state][state.theta][state.theta_dot];\n}\nso many comments#include \"StateSpace.h\"\n\nStateSpace::StateSpace(const unsigned int _angle_bins, const unsigned int _velocity_bins, PriorityQueue queue ):\n\tangle_bins(_angle_bins),\n\tvelocity_bins(_velocity_bins),\n\tspace(_angle_max, std::vector< PriorityQueue > (_velocity_max, PriorityQueue (queue)))\n{}\n\nStateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state)\n{\n\t\/\/throw if the the index is out of bounds\n\tif(robot_state>1)throw std::domain_error(\"action index exceeded\");\n\t\/\/return proxy object to accept second [] operator\n\treturn SubscriptProxy1( robot_state ? space1 : space2 );\n}\n\n\/\/searches state space by state object\nPriorityQueue& StateSpace::operator[](const State & state)\n{\n\t\/\/call the subscript operators with the members of the state object\n\treturn (*this)[state.robot_state][state.theta][state.theta_dot];\n}\n<|endoftext|>"} {"text":"\/** \\file crf_analyzer.cpp\n * Implementation of class CRF_Analyzer.\n *\n * \\author Jun Jiang\n * \\version 0.1\n * \\date Mar 2, 2009\n *\/\n\n\n#include \n#include \n#include \n#include \n\n#include \"jma_analyzer.h\"\n#include \"jma_knowledge.h\"\n#include \"tokenizer.h\"\n\n\nnamespace jma\n{\n\n\/**\n * Whether the two MorphemeLists is the same\n * \\param list1 the MorphemeList 1\n * \\param list2 the MorphemeList 2\n *\/\ninline bool isSameMorphemeList( const MorphemeList* list1, const MorphemeList* list2, bool printPOS )\n{\n\t\/\/ if one is zero pointer, return null\n\tif( !list1 || !list2 )\n\t{\n\t\treturn false;\n\t}\n\n\tif( list1->size() != list2->size() )\n\t\treturn false;\n\t\/\/compare one by one\n\tsize_t N = list1->size();\n\tif( printPOS )\n\t{\n\t\tfor( size_t i = 0; i < N; ++i )\n\t\t{\n\t\t\tconst Morpheme& m1 = (*list1)[i];\n\t\t\tconst Morpheme& m2 = (*list2)[i];\n\t\t\tif( m1.lexicon_ != m2.lexicon_ || m1.posCode_ != m2.posCode_\n\t\t\t\t\t|| m1.posStr_ != m2.posStr_ )\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor( size_t i = 0; i < N; ++i )\n\t\t{\n\t\t\tif( (*list1)[i].lexicon_ != (*list2)[i].lexicon_ )\n\t\t\t\treturn false;\n\t\t}\n\t}\n\t\/\/all the elements are the same\n\treturn true;\n}\n\nJMA_Analyzer::JMA_Analyzer()\n : knowledge_(0), tagger_(0)\n{\n}\n\nJMA_Analyzer::~JMA_Analyzer()\n{\n}\n\nvoid JMA_Analyzer::setKnowledge(Knowledge* pKnowledge)\n{\n assert(pKnowledge);\n\n knowledge_ = dynamic_cast(pKnowledge);\n assert(knowledge_);\n tagger_ = knowledge_->getTagger();\n assert(tagger_);\n tagger_->set_lattice_level(1);\n maxPosCateOffset_ = knowledge_->getPOSCatNum() - 1;\n}\n\nint JMA_Analyzer::runWithSentence(Sentence& sentence)\n{\n\tbool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;\n\tint N = (int)getOption(Analyzer::OPTION_TYPE_NBEST);\n\n\t\/\/one best\n\tif(N <= 1)\n\t{\n\t\tconst MeCab::Node* bosNode = tagger_->parseToNode( sentence.getString() );\n\t\tMorphemeList list;\n\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next)\n\t\t{\n\t\t\tstring seg(node->surface, node->length);\n\t\t\tif(knowledge_->isStopWord(seg))\n\t\t\t\tcontinue;\n\t\t\tlist.push_back(Morpheme());\n\t\t\tMorpheme& morp = list.back();\n\t\t\tmorp.lexicon_ = seg;\n\t\t\tif(printPOS)\n\t\t\t{\n\t\t\t\tmorp.posCode_ = (int)node->posid;\n\t\t\t\tmorp.posStr_ = string(node->feature, getPOSOffset(node->feature));\n\t\t\t}\n\t\t}\n\t\tsentence.addList(list, 1.0);\n\t}\n\t\/\/ N-best\n\telse\n\t{\n\t\tdouble totalScore = 0;\n\n\t\tif( !tagger_->parseNBestInit( sentence.getString() ) )\n\t\t{\n\t\t\tcerr << \"[Error] Cannot parseNBestInit on the \" << sentence.getString() << endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tlong base = 0;\n\t\tint i = 0;\n\t\tfor ( ; i < N; )\n\t\t{\n\t\t\tconst MeCab::Node* bosNode = tagger_->nextNode();\n\t\t\tif( !bosNode )\n\t\t\t\tbreak;\n\t\t\tMorphemeList list;\n\t\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next)\n\t\t\t{\n\t\t\t\tstring seg(node->surface, node->length);\n\t\t\t\tif(knowledge_->isStopWord(seg))\n\t\t\t\t\tcontinue;\n\t\t\t\tlist.push_back(Morpheme());\n\t\t\t\tMorpheme& morp = list.back();\n\t\t\t\tmorp.lexicon_ = seg;\n\t\t\t\tif(printPOS)\n\t\t\t\t{\n\t\t\t\t\tmorp.posCode_ = (int)node->posid;\n\t\t\t\t\tmorp.posStr_ = string(node->feature, getPOSOffset(node->feature));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool isDupl = false;\n\t\t\t\/\/check the current result with exits results\n\t\t\tfor( int listOffset = sentence.getListSize() - 1 ; listOffset >= 0; --listOffset )\n\t\t\t{\n\t\t\t\tif( isSameMorphemeList( sentence.getMorphemeList(listOffset), &list, printPOS ) )\n\t\t\t\t{\n\t\t\t\t\tisDupl = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ignore the duplicate results\n\t\t\tif( isDupl )\n\t\t\t\tcontinue;\n\n\t\t\tlong score = tagger_->nextScore();\n\t\t\tif( i == 0 )\n\t\t\t\tbase = score > BASE_NBEST_SCORE ? score - BASE_NBEST_SCORE : 0;\n\n\t\t\tdouble dScore = 1.0 \/ (score - base );\n\t\t\ttotalScore += dScore;\n\t\t\tsentence.addList( list, dScore );\n\t\t\t++i;\n\t\t}\n\n\t\tfor ( int j = 0; j < i; ++j )\n\t\t{\n\t\t\tsentence.setScore(j, sentence.getScore(j) \/ totalScore );\n\t\t}\n\t}\n\n\treturn 1;\n}\n\nconst char* JMA_Analyzer::runWithString(const char* inStr)\n{\n\tbool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;\n\n\tconst MeCab::Node* bosNode = tagger_->parseToNode( inStr );\n\n\tstrBuf_.clear();\n\tif (printPOS) {\n\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next){\n\t\t\tstrBuf_.append(node->surface, node->length).append(posDelimiter_).\n\t\t\t\tappend(node->feature, getPOSOffset(node->feature) ).append(wordDelimiter_);\n\t\t}\n\n\t} else {\n\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next){\n\t\t\tstrBuf_.append(node->surface, node->length).append(wordDelimiter_);\n\t\t}\n\t}\n\n\treturn strBuf_.c_str();\n\n}\n\nint JMA_Analyzer::runWithStream(const char* inFileName, const char* outFileName)\n{\n\tassert(inFileName);\n\tassert(outFileName);\n\n\tbool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;\n\n\tifstream in(inFileName);\n\tif(!in)\n\t{\n\t\tcerr<<\"[Error] The input file \"<parseToNode( line.c_str() );\n\n if (printPOS) {\n\t\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next){\n\t\t\t\tout.write(node->surface, node->length) << posDelimiter_;\n\t\t\t\tout.write(node->feature, getPOSOffset(node->feature) ) << wordDelimiter_;\n\t\t\t}\n\n if (remains)\n out << endl;\n else\n break;\n\n } else {\n\t\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next){\n\t\t\t\tout.write(node->surface, node->length) << wordDelimiter_;\n\t\t\t}\n\n\t\t\tif (remains)\n\t\t\t\tout << endl;\n\t\t\telse\n\t\t\t\tbreak;\n }\n }\n\n in.close();\n out.close();\n return 1;\n}\n\nvoid JMA_Analyzer::splitSentence(const char* paragraph, std::vector& sentences)\n{\n if(! paragraph)\n return;\n\n Sentence result;\n string sentenceStr;\n CTypeTokenizer tokenizer( knowledge_->getCType() );\n tokenizer.assign(paragraph);\n for(const char* p=tokenizer.next(); p; p=tokenizer.next())\n {\n if( knowledge_->isSentenceSeparator(p) )\n {\n sentenceStr += p;\n\n result.setString(sentenceStr.c_str());\n sentences.push_back(result);\n\n sentenceStr.clear();\n }\n \/*\/\/ white-space characters are also used as sentence separator,\n \/\/ but they are ignored in the sentence result\n else if(ctype_->isSpace(p))\n {\n if(! sentenceStr.empty())\n {\n result.setString(sentenceStr.c_str());\n sentences.push_back(result);\n\n sentenceStr.clear();\n }\n }*\/\n else\n {\n sentenceStr += p;\n }\n }\n\n \/\/ in case the last character is not space or sentence separator\n if(! sentenceStr.empty())\n {\n result.setString(sentenceStr.c_str());\n sentences.push_back(result);\n\n sentenceStr.clear();\n }\n}\n\n\nint JMA_Analyzer::getPOSOffset(const char* feature){\n\tif( knowledge_->isOutputFullPOS() )\n\t{\n\t\t\/\/ count for the index of the fourth offset\n\t\tint offset = 0;\n\t\tint commaCount = 0;\n\t\tfor( ; feature[offset]; ++offset )\n\t\t{\n\t\t\tif(feature[offset] == ',')\n\t\t\t{\n\t\t\t\t++commaCount;\n\t\t\t\tif( commaCount > maxPosCateOffset_ )\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn offset;\n\t}\n\n\t \/\/count for the index of the comma that after non-star pos sections\n\tint offset = 0;\n\tint commaCount = 0;\n\tfor( ; feature[offset]; ++offset )\n\t{\n\t\tif(feature[offset] == ',')\n\t\t{\n\t\t\t++commaCount;\n\t\t\tif( commaCount > maxPosCateOffset_ )\n\t\t\t\tbreak;\n\t\t}\n\t\telse if(feature[offset] == '*')\n\t\t{\n\t\t\t\/\/if offset is 0, contains nothing\n\t\t\treturn offset ? offset - 1 : 0 ;\n\t\t}\n\t}\n\n\treturn offset;\n}\n\n} \/\/ namespace jma\ncheck whether a word is stop word in the runWithString and runWithStream\/** \\file crf_analyzer.cpp\n * Implementation of class CRF_Analyzer.\n *\n * \\author Jun Jiang\n * \\version 0.1\n * \\date Mar 2, 2009\n *\/\n\n\n#include \n#include \n#include \n#include \n\n#include \"jma_analyzer.h\"\n#include \"jma_knowledge.h\"\n#include \"tokenizer.h\"\n\n\nnamespace jma\n{\n\n\/**\n * Whether the two MorphemeLists is the same\n * \\param list1 the MorphemeList 1\n * \\param list2 the MorphemeList 2\n *\/\ninline bool isSameMorphemeList( const MorphemeList* list1, const MorphemeList* list2, bool printPOS )\n{\n\t\/\/ if one is zero pointer, return null\n\tif( !list1 || !list2 )\n\t{\n\t\treturn false;\n\t}\n\n\tif( list1->size() != list2->size() )\n\t\treturn false;\n\t\/\/compare one by one\n\tsize_t N = list1->size();\n\tif( printPOS )\n\t{\n\t\tfor( size_t i = 0; i < N; ++i )\n\t\t{\n\t\t\tconst Morpheme& m1 = (*list1)[i];\n\t\t\tconst Morpheme& m2 = (*list2)[i];\n\t\t\tif( m1.lexicon_ != m2.lexicon_ || m1.posCode_ != m2.posCode_\n\t\t\t\t\t|| m1.posStr_ != m2.posStr_ )\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor( size_t i = 0; i < N; ++i )\n\t\t{\n\t\t\tif( (*list1)[i].lexicon_ != (*list2)[i].lexicon_ )\n\t\t\t\treturn false;\n\t\t}\n\t}\n\t\/\/all the elements are the same\n\treturn true;\n}\n\nJMA_Analyzer::JMA_Analyzer()\n : knowledge_(0), tagger_(0)\n{\n}\n\nJMA_Analyzer::~JMA_Analyzer()\n{\n}\n\nvoid JMA_Analyzer::setKnowledge(Knowledge* pKnowledge)\n{\n assert(pKnowledge);\n\n knowledge_ = dynamic_cast(pKnowledge);\n assert(knowledge_);\n tagger_ = knowledge_->getTagger();\n assert(tagger_);\n tagger_->set_lattice_level(1);\n maxPosCateOffset_ = knowledge_->getPOSCatNum() - 1;\n}\n\nint JMA_Analyzer::runWithSentence(Sentence& sentence)\n{\n\tbool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;\n\tint N = (int)getOption(Analyzer::OPTION_TYPE_NBEST);\n\n\t\/\/one best\n\tif(N <= 1)\n\t{\n\t\tconst MeCab::Node* bosNode = tagger_->parseToNode( sentence.getString() );\n\t\tMorphemeList list;\n\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next)\n\t\t{\n\t\t\tstring seg(node->surface, node->length);\n\t\t\tif(knowledge_->isStopWord(seg))\n\t\t\t\tcontinue;\n\t\t\tlist.push_back(Morpheme());\n\t\t\tMorpheme& morp = list.back();\n\t\t\tmorp.lexicon_ = seg;\n\t\t\tif(printPOS)\n\t\t\t{\n\t\t\t\tmorp.posCode_ = (int)node->posid;\n\t\t\t\tmorp.posStr_ = string(node->feature, getPOSOffset(node->feature));\n\t\t\t}\n\t\t}\n\t\tsentence.addList(list, 1.0);\n\t}\n\t\/\/ N-best\n\telse\n\t{\n\t\tdouble totalScore = 0;\n\n\t\tif( !tagger_->parseNBestInit( sentence.getString() ) )\n\t\t{\n\t\t\tcerr << \"[Error] Cannot parseNBestInit on the \" << sentence.getString() << endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tlong base = 0;\n\t\tint i = 0;\n\t\tfor ( ; i < N; )\n\t\t{\n\t\t\tconst MeCab::Node* bosNode = tagger_->nextNode();\n\t\t\tif( !bosNode )\n\t\t\t\tbreak;\n\t\t\tMorphemeList list;\n\t\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next)\n\t\t\t{\n\t\t\t\tstring seg(node->surface, node->length);\n\t\t\t\tif(knowledge_->isStopWord(seg))\n\t\t\t\t\tcontinue;\n\t\t\t\tlist.push_back(Morpheme());\n\t\t\t\tMorpheme& morp = list.back();\n\t\t\t\tmorp.lexicon_ = seg;\n\t\t\t\tif(printPOS)\n\t\t\t\t{\n\t\t\t\t\tmorp.posCode_ = (int)node->posid;\n\t\t\t\t\tmorp.posStr_ = string(node->feature, getPOSOffset(node->feature));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool isDupl = false;\n\t\t\t\/\/check the current result with exits results\n\t\t\tfor( int listOffset = sentence.getListSize() - 1 ; listOffset >= 0; --listOffset )\n\t\t\t{\n\t\t\t\tif( isSameMorphemeList( sentence.getMorphemeList(listOffset), &list, printPOS ) )\n\t\t\t\t{\n\t\t\t\t\tisDupl = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ignore the duplicate results\n\t\t\tif( isDupl )\n\t\t\t\tcontinue;\n\n\t\t\tlong score = tagger_->nextScore();\n\t\t\tif( i == 0 )\n\t\t\t\tbase = score > BASE_NBEST_SCORE ? score - BASE_NBEST_SCORE : 0;\n\n\t\t\tdouble dScore = 1.0 \/ (score - base );\n\t\t\ttotalScore += dScore;\n\t\t\tsentence.addList( list, dScore );\n\t\t\t++i;\n\t\t}\n\n\t\tfor ( int j = 0; j < i; ++j )\n\t\t{\n\t\t\tsentence.setScore(j, sentence.getScore(j) \/ totalScore );\n\t\t}\n\t}\n\n\treturn 1;\n}\n\nconst char* JMA_Analyzer::runWithString(const char* inStr)\n{\n\tbool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;\n\n\tconst MeCab::Node* bosNode = tagger_->parseToNode( inStr );\n\n\tstrBuf_.clear();\n\tif (printPOS) {\n\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next){\n\t\t\tstring seg(node->surface, node->length);\n\t\t\tif(knowledge_->isStopWord(seg))\n\t\t\t\tcontinue;\n\n\t\t\tstrBuf_.append(node->surface, node->length).append(posDelimiter_).\n\t\t\t\tappend(node->feature, getPOSOffset(node->feature) ).append(wordDelimiter_);\n\t\t}\n\n\t} else {\n\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next){\n\t\t\tstring seg(node->surface, node->length);\n\t\t\tif(knowledge_->isStopWord(seg))\n\t\t\t\tcontinue;\n\n\t\t\tstrBuf_.append(node->surface, node->length).append(wordDelimiter_);\n\t\t}\n\t}\n\n\treturn strBuf_.c_str();\n\n}\n\nint JMA_Analyzer::runWithStream(const char* inFileName, const char* outFileName)\n{\n\tassert(inFileName);\n\tassert(outFileName);\n\n\tbool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;\n\n\tifstream in(inFileName);\n\tif(!in)\n\t{\n\t\tcerr<<\"[Error] The input file \"<parseToNode( line.c_str() );\n\n if (printPOS) {\n\t\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next){\n\t\t\t\tstring seg(node->surface, node->length);\n\t\t\t\tif(knowledge_->isStopWord(seg))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tout.write(node->surface, node->length) << posDelimiter_;\n\t\t\t\tout.write(node->feature, getPOSOffset(node->feature) ) << wordDelimiter_;\n\t\t\t}\n\n if (remains)\n out << endl;\n else\n break;\n\n } else {\n\t\t\tfor (const MeCab::Node *node = bosNode->next; node->next; node = node->next){\n\t\t\t\tstring seg(node->surface, node->length);\n\t\t\t\tif(knowledge_->isStopWord(seg))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tout.write(node->surface, node->length) << wordDelimiter_;\n\t\t\t}\n\n\t\t\tif (remains)\n\t\t\t\tout << endl;\n\t\t\telse\n\t\t\t\tbreak;\n }\n }\n\n in.close();\n out.close();\n return 1;\n}\n\nvoid JMA_Analyzer::splitSentence(const char* paragraph, std::vector& sentences)\n{\n if(! paragraph)\n return;\n\n Sentence result;\n string sentenceStr;\n CTypeTokenizer tokenizer( knowledge_->getCType() );\n tokenizer.assign(paragraph);\n for(const char* p=tokenizer.next(); p; p=tokenizer.next())\n {\n if( knowledge_->isSentenceSeparator(p) )\n {\n sentenceStr += p;\n\n result.setString(sentenceStr.c_str());\n sentences.push_back(result);\n\n sentenceStr.clear();\n }\n \/*\/\/ white-space characters are also used as sentence separator,\n \/\/ but they are ignored in the sentence result\n else if(ctype_->isSpace(p))\n {\n if(! sentenceStr.empty())\n {\n result.setString(sentenceStr.c_str());\n sentences.push_back(result);\n\n sentenceStr.clear();\n }\n }*\/\n else\n {\n sentenceStr += p;\n }\n }\n\n \/\/ in case the last character is not space or sentence separator\n if(! sentenceStr.empty())\n {\n result.setString(sentenceStr.c_str());\n sentences.push_back(result);\n\n sentenceStr.clear();\n }\n}\n\n\nint JMA_Analyzer::getPOSOffset(const char* feature){\n\tif( knowledge_->isOutputFullPOS() )\n\t{\n\t\t\/\/ count for the index of the fourth offset\n\t\tint offset = 0;\n\t\tint commaCount = 0;\n\t\tfor( ; feature[offset]; ++offset )\n\t\t{\n\t\t\tif(feature[offset] == ',')\n\t\t\t{\n\t\t\t\t++commaCount;\n\t\t\t\tif( commaCount > maxPosCateOffset_ )\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn offset;\n\t}\n\n\t \/\/count for the index of the comma that after non-star pos sections\n\tint offset = 0;\n\tint commaCount = 0;\n\tfor( ; feature[offset]; ++offset )\n\t{\n\t\tif(feature[offset] == ',')\n\t\t{\n\t\t\t++commaCount;\n\t\t\tif( commaCount > maxPosCateOffset_ )\n\t\t\t\tbreak;\n\t\t}\n\t\telse if(feature[offset] == '*')\n\t\t{\n\t\t\t\/\/if offset is 0, contains nothing\n\t\t\treturn offset ? offset - 1 : 0 ;\n\t\t}\n\t}\n\n\treturn offset;\n}\n\n} \/\/ namespace jma\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: formula.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2004-03-08 11:55:35 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_FORMULA_HXX\n#define SC_FORMULA_HXX\n\n#ifndef SC_ANYREFDG_HXX\n#include \"anyrefdg.hxx\"\n#endif\n\n#ifndef SC_FUNCUTL_HXX\n#include \"funcutl.hxx\"\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\" \/\/ ScAddress\n#endif\n\n#ifndef _STDCTRL_HXX \/\/autogen\n#include \n#endif\n#ifndef _LSTBOX_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SV_GROUP_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SVEDIT_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SV_TABPAGE_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SVSTDARR_STRINGS\n\n#define _SVSTDARR_STRINGS\n#include \n\n#endif\n\n#ifndef _SV_TABCTRL_HXX \/\/autogen\n#include \n#endif\n\n#ifndef SC_PARAWIN_HXX\n#include \"parawin.hxx\"\n#endif\n\n#ifndef _SVTREEBOX_HXX \/\/autogen\n#include \n#endif\n\n#ifndef SC_COMPILER_HXX\n#include \"compiler.hxx\"\n#endif\n\n#ifndef SC_CELL_HXX\n#include \"cell.hxx\"\n#endif\n\n#ifndef SC_FUNCPAGE_HXX\n#include \"funcpage.hxx\"\n#endif\n\n#ifndef SC_STRUCTPG_HXX\n#include \"structpg.hxx\"\n#endif\n\nclass ScViewData;\nclass ScDocument;\nclass ScFuncDesc;\nclass ScInputHandler;\nclass ScDocShell;\n\n\/\/============================================================================\n\nenum ScFormulaDlgMode { SC_FORMDLG_FORMULA, SC_FORMDLG_ARGS, SC_FORMDLG_EDIT };\n\n\/\/============================================================================\n\ntypedef ScTabViewShell* PtrTabViewShell;\n\n\/\/============================================================================\n\n\/\/============================================================================\n\nclass ScFormulaDlg : public ScAnyRefDlg\n{\npublic:\n ScFormulaDlg( SfxBindings* pB, SfxChildWindow* pCW,\n Window* pParent, ScViewData* pViewData );\n ~ScFormulaDlg();\n\n virtual void SetReference( const ScRange& rRef, ScDocument* pRefDoc );\n virtual BOOL IsRefInputMode() const;\n virtual BOOL IsDocAllowed(SfxObjectShell* pDocSh) const;\n virtual void SetActive();\n virtual BOOL Close();\n\nprivate:\n\n TabControl aTabCtrl;\n GroupBox aGbEdit; \/\/! MUST be placed before aScParaWin for initializing\n ScParaWin aScParaWin;\n FixedText aFtHeadLine;\n FixedInfo aFtFuncName;\n FixedInfo aFtFuncDesc;\n\n FixedText aFtEditName;\n \/\/FixedInfo aFtEditDesc;\n\n FixedText aFtResult;\n ValWnd aWndResult;\n\n FixedText aFtFormula;\n ScEditBox aMEFormula;\n\n CheckBox aBtnMatrix;\n HelpButton aBtnHelp;\n CancelButton aBtnCancel;\n\n PushButton aBtnBackward;\n PushButton aBtnForward;\n OKButton aBtnEnd;\n\n ScRefEdit aEdRef;\n ScRefButton aRefBtn;\n\n FixedText aFtFormResult;\n ValWnd aWndFormResult;\n\n ScRefEdit* pTheRefEdit;\n ScRefButton* pTheRefButton;\n ScFuncPage* pScFuncPage;\n ScStructPage* pScStructPage;\n ScFormulaCell* pCell;\n ScCompiler* pComp;\n ScTokenArray* pScTokA;\n String aOldFormula;\n BOOL bStructUpdate;\n MultiLineEdit* pMEdit;\n BOOL bUserMatrixFlag;\n Timer aTimer;\n\n const String aTitle1;\n const String aTitle2;\n const String aTxtEnd;\n const String aTxtOk; \/\/ hinter aBtnEnd\n\n ULONG nOldHelp;\n ULONG nOldUnique;\n ULONG nActivWinId;\n BOOL bIsShutDown;\n\n\n\n Font aFntBold;\n Font aFntLight;\n USHORT nEdFocus;\n\/\/ Selection theCurSel;\n BOOL bEditFlag;\n const ScFuncDesc* pFuncDesc;\n USHORT nArgs;\n String** pArgArr;\n Selection aFuncSel;\n\n static ScDocument* pDoc;\n static ScAddress aCursorPos;\n\nprotected:\n\n virtual long PreNotify( NotifyEvent& rNEvt );\n virtual void RefInputStart( ScRefEdit* pEdit, ScRefButton* pButton = NULL );\n virtual void RefInputDone( BOOL bForced = FALSE );\n ULONG FindFocusWin(Window *pWin);\n void SetFocusWin(Window *pWin,ULONG nUniqueId);\n String RepairFormula(const String& aFormula);\n void SaveLRUEntry(const ScFuncDesc* pFuncDesc);\n void HighlightFunctionParas(const String& aFormula);\n\nprivate:\n\n BOOL IsInputHdl(ScInputHandler* pHdl);\n ScInputHandler* GetNextInputHandler(ScDocShell* pDocShell,PtrTabViewShell* ppViewSh=NULL);\n\n void MakeTree(SvLBoxEntry* pParent,ScToken* pScToken,long Count,\n ScTokenArray* pScTokA,ScCompiler* pComp);\n\n void ClearAllParas();\n void DeleteArgs();\n void FillDialog(BOOL nFlag=TRUE);\n void EditNextFunc( BOOL bForward, xub_StrLen nFStart=NOT_FOUND );\n void EditThisFunc(xub_StrLen nFStart);\n void EditFuncParas(xub_StrLen nEditPos);\n\n\n void UpdateArgInput( USHORT nOffset, USHORT nInput );\n BOOL CalcValue( const String& rStrExp, String& rStrResult );\n BOOL CalcStruct( const String& rStrExp);\n\n void UpdateValues();\n void SaveArg( USHORT nEd );\n void UpdateSelection();\n void DoEnter( BOOL bOk );\n void UpdateFunctionDesc();\n void ResizeArgArr( const ScFuncDesc* pNewFunc );\n void FillListboxes();\n void FillControls();\n\n xub_StrLen GetFunctionPos(xub_StrLen nPos);\n void UpdateTokenArray( const String& rStrExp);\n\n ScRefEdit* GetCurrRefEdit();\n\n DECL_LINK( ScrollHdl, ScParaWin* );\n DECL_LINK( ModifyHdl, ScParaWin* );\n DECL_LINK( FxHdl, ScParaWin* );\n\n DECL_LINK( MatrixHdl, CheckBox *);\n DECL_LINK( FormulaHdl, MultiLineEdit* );\n DECL_LINK( FormulaCursorHdl, ScEditBox*);\n DECL_LINK( BtnHdl, PushButton* );\n DECL_LINK( GetEdFocusHdl, ArgInput* );\n DECL_LINK( GetFxFocusHdl, ArgInput* );\n DECL_LINK( DblClkHdl, ScFuncPage* );\n DECL_LINK( FuncSelHdl, ScFuncPage*);\n DECL_LINK( StructSelHdl, ScStructPage * );\n DECL_LINK( UpdateFocusHdl, Timer*);\n};\n\n\n\n#endif \/\/ SC_CRNRDLG_HXX\n\nINTEGRATION: CWS ooo19126 (1.3.520); FILE MERGED 2005\/09\/05 15:05:22 rt 1.3.520.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: formula.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:26:26 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_FORMULA_HXX\n#define SC_FORMULA_HXX\n\n#ifndef SC_ANYREFDG_HXX\n#include \"anyrefdg.hxx\"\n#endif\n\n#ifndef SC_FUNCUTL_HXX\n#include \"funcutl.hxx\"\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\" \/\/ ScAddress\n#endif\n\n#ifndef _STDCTRL_HXX \/\/autogen\n#include \n#endif\n#ifndef _LSTBOX_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SV_GROUP_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SVEDIT_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SV_TABPAGE_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SVSTDARR_STRINGS\n\n#define _SVSTDARR_STRINGS\n#include \n\n#endif\n\n#ifndef _SV_TABCTRL_HXX \/\/autogen\n#include \n#endif\n\n#ifndef SC_PARAWIN_HXX\n#include \"parawin.hxx\"\n#endif\n\n#ifndef _SVTREEBOX_HXX \/\/autogen\n#include \n#endif\n\n#ifndef SC_COMPILER_HXX\n#include \"compiler.hxx\"\n#endif\n\n#ifndef SC_CELL_HXX\n#include \"cell.hxx\"\n#endif\n\n#ifndef SC_FUNCPAGE_HXX\n#include \"funcpage.hxx\"\n#endif\n\n#ifndef SC_STRUCTPG_HXX\n#include \"structpg.hxx\"\n#endif\n\nclass ScViewData;\nclass ScDocument;\nclass ScFuncDesc;\nclass ScInputHandler;\nclass ScDocShell;\n\n\/\/============================================================================\n\nenum ScFormulaDlgMode { SC_FORMDLG_FORMULA, SC_FORMDLG_ARGS, SC_FORMDLG_EDIT };\n\n\/\/============================================================================\n\ntypedef ScTabViewShell* PtrTabViewShell;\n\n\/\/============================================================================\n\n\/\/============================================================================\n\nclass ScFormulaDlg : public ScAnyRefDlg\n{\npublic:\n ScFormulaDlg( SfxBindings* pB, SfxChildWindow* pCW,\n Window* pParent, ScViewData* pViewData );\n ~ScFormulaDlg();\n\n virtual void SetReference( const ScRange& rRef, ScDocument* pRefDoc );\n virtual BOOL IsRefInputMode() const;\n virtual BOOL IsDocAllowed(SfxObjectShell* pDocSh) const;\n virtual void SetActive();\n virtual BOOL Close();\n\nprivate:\n\n TabControl aTabCtrl;\n GroupBox aGbEdit; \/\/! MUST be placed before aScParaWin for initializing\n ScParaWin aScParaWin;\n FixedText aFtHeadLine;\n FixedInfo aFtFuncName;\n FixedInfo aFtFuncDesc;\n\n FixedText aFtEditName;\n \/\/FixedInfo aFtEditDesc;\n\n FixedText aFtResult;\n ValWnd aWndResult;\n\n FixedText aFtFormula;\n ScEditBox aMEFormula;\n\n CheckBox aBtnMatrix;\n HelpButton aBtnHelp;\n CancelButton aBtnCancel;\n\n PushButton aBtnBackward;\n PushButton aBtnForward;\n OKButton aBtnEnd;\n\n ScRefEdit aEdRef;\n ScRefButton aRefBtn;\n\n FixedText aFtFormResult;\n ValWnd aWndFormResult;\n\n ScRefEdit* pTheRefEdit;\n ScRefButton* pTheRefButton;\n ScFuncPage* pScFuncPage;\n ScStructPage* pScStructPage;\n ScFormulaCell* pCell;\n ScCompiler* pComp;\n ScTokenArray* pScTokA;\n String aOldFormula;\n BOOL bStructUpdate;\n MultiLineEdit* pMEdit;\n BOOL bUserMatrixFlag;\n Timer aTimer;\n\n const String aTitle1;\n const String aTitle2;\n const String aTxtEnd;\n const String aTxtOk; \/\/ hinter aBtnEnd\n\n ULONG nOldHelp;\n ULONG nOldUnique;\n ULONG nActivWinId;\n BOOL bIsShutDown;\n\n\n\n Font aFntBold;\n Font aFntLight;\n USHORT nEdFocus;\n\/\/ Selection theCurSel;\n BOOL bEditFlag;\n const ScFuncDesc* pFuncDesc;\n USHORT nArgs;\n String** pArgArr;\n Selection aFuncSel;\n\n static ScDocument* pDoc;\n static ScAddress aCursorPos;\n\nprotected:\n\n virtual long PreNotify( NotifyEvent& rNEvt );\n virtual void RefInputStart( ScRefEdit* pEdit, ScRefButton* pButton = NULL );\n virtual void RefInputDone( BOOL bForced = FALSE );\n ULONG FindFocusWin(Window *pWin);\n void SetFocusWin(Window *pWin,ULONG nUniqueId);\n String RepairFormula(const String& aFormula);\n void SaveLRUEntry(const ScFuncDesc* pFuncDesc);\n void HighlightFunctionParas(const String& aFormula);\n\nprivate:\n\n BOOL IsInputHdl(ScInputHandler* pHdl);\n ScInputHandler* GetNextInputHandler(ScDocShell* pDocShell,PtrTabViewShell* ppViewSh=NULL);\n\n void MakeTree(SvLBoxEntry* pParent,ScToken* pScToken,long Count,\n ScTokenArray* pScTokA,ScCompiler* pComp);\n\n void ClearAllParas();\n void DeleteArgs();\n void FillDialog(BOOL nFlag=TRUE);\n void EditNextFunc( BOOL bForward, xub_StrLen nFStart=NOT_FOUND );\n void EditThisFunc(xub_StrLen nFStart);\n void EditFuncParas(xub_StrLen nEditPos);\n\n\n void UpdateArgInput( USHORT nOffset, USHORT nInput );\n BOOL CalcValue( const String& rStrExp, String& rStrResult );\n BOOL CalcStruct( const String& rStrExp);\n\n void UpdateValues();\n void SaveArg( USHORT nEd );\n void UpdateSelection();\n void DoEnter( BOOL bOk );\n void UpdateFunctionDesc();\n void ResizeArgArr( const ScFuncDesc* pNewFunc );\n void FillListboxes();\n void FillControls();\n\n xub_StrLen GetFunctionPos(xub_StrLen nPos);\n void UpdateTokenArray( const String& rStrExp);\n\n ScRefEdit* GetCurrRefEdit();\n\n DECL_LINK( ScrollHdl, ScParaWin* );\n DECL_LINK( ModifyHdl, ScParaWin* );\n DECL_LINK( FxHdl, ScParaWin* );\n\n DECL_LINK( MatrixHdl, CheckBox *);\n DECL_LINK( FormulaHdl, MultiLineEdit* );\n DECL_LINK( FormulaCursorHdl, ScEditBox*);\n DECL_LINK( BtnHdl, PushButton* );\n DECL_LINK( GetEdFocusHdl, ArgInput* );\n DECL_LINK( GetFxFocusHdl, ArgInput* );\n DECL_LINK( DblClkHdl, ScFuncPage* );\n DECL_LINK( FuncSelHdl, ScFuncPage*);\n DECL_LINK( StructSelHdl, ScStructPage * );\n DECL_LINK( UpdateFocusHdl, Timer*);\n};\n\n\n\n#endif \/\/ SC_CRNRDLG_HXX\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: gridwin.hxx,v $\n *\n * $Revision: 1.20 $\n *\n * last change: $Author: vg $ $Date: 2005-03-08 15:44:41 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_GRIDWIN_HXX\n#define SC_GRIDWIN_HXX\n\n#ifndef _STRING_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _TRANSFER_HXX\n#include \n#endif\n\n\/\/ nur auf dem MAC Auto-Filter per Popup\n#ifdef MAC\n#define AUTOFILTER_POPUP\n#else\n#undef AUTOFILTER_POPUP\n#endif\n\n#ifndef SC_VIEWUTIL_HXX\n#include \"viewutil.hxx\"\n#endif\n\n#ifndef SC_VIEWDATA_HXX\n#include \"viewdata.hxx\"\n#endif\n\n#ifndef SC_CBUTTON_HXX\n#include \"cbutton.hxx\"\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\nstruct ScTableInfo;\nclass ScViewSelectionEngine;\nclass ScPivot;\nclass ScDPObject;\nclass ScOutputData;\nclass ScFilterListBox;\nclass AutoFilterPopup;\nclass SdrObject;\nclass SdrEditView;\nclass ScNoteMarker;\nclass FloatingWindow;\nclass SdrHdlList;\nclass ScTransferObj;\nstruct SpellCallbackInfo;\n\n \/\/ Maus-Status (nMouseStatus)\n\n#define SC_GM_NONE 0\n#define SC_GM_TABDOWN 1\n#define SC_GM_DBLDOWN 2\n#define SC_GM_FILTER 3\n#define SC_GM_IGNORE 4\n#define SC_GM_WATERUNDO 5\n#define SC_GM_URLDOWN 6\n\n \/\/ Page-Drag-Modus\n\n#define SC_PD_NONE 0\n#define SC_PD_RANGE_L 1\n#define SC_PD_RANGE_R 2\n#define SC_PD_RANGE_T 4\n#define SC_PD_RANGE_B 8\n#define SC_PD_RANGE_TL (SC_PD_RANGE_T|SC_PD_RANGE_L)\n#define SC_PD_RANGE_TR (SC_PD_RANGE_T|SC_PD_RANGE_R)\n#define SC_PD_RANGE_BL (SC_PD_RANGE_B|SC_PD_RANGE_L)\n#define SC_PD_RANGE_BR (SC_PD_RANGE_B|SC_PD_RANGE_R)\n#define SC_PD_BREAK_H 16\n#define SC_PD_BREAK_V 32\n\n\nclass ScHideTextCursor\n{\nprivate:\n ScViewData* pViewData;\n ScSplitPos eWhich;\n\npublic:\n ScHideTextCursor( ScViewData* pData, ScSplitPos eW );\n ~ScHideTextCursor();\n};\n\n\nclass ScGridWindow : public Window, public DropTargetHelper, public DragSourceHelper\n{\n \/\/ ScFilterListBox wird immer fuer Auswahlliste benutzt\n friend class ScFilterListBox;\n#ifdef AUTOFILTER_POPUP\n friend class AutoFilterPopup;\n#endif\n\nprivate:\n ScViewData* pViewData;\n ScSplitPos eWhich;\n ScHSplitPos eHWhich;\n ScVSplitPos eVWhich;\n\n ScNoteMarker* pNoteMarker;\n\n ScFilterListBox* pFilterBox;\n FloatingWindow* pFilterFloat;\n\n USHORT nCursorHideCount;\n\n BOOL bMarking;\n\n USHORT nButtonDown;\n BOOL bEEMouse; \/\/ Edit-Engine hat Maus\n BYTE nMouseStatus;\n BYTE nNestedButtonState; \/\/ track nested button up\/down calls\n\n BOOL bPivotMouse; \/\/ Pivot-D&D (alte Pivottabellen)\n ScPivot* pDragPivot;\n BOOL bPivotColField;\n SCCOL nPivotCol;\n SCCOL nPivotField;\n\n BOOL bDPMouse; \/\/ DataPilot-D&D (neue Pivottabellen)\n long nDPField;\n ScDPObject* pDragDPObj; \/\/! name?\n\n BOOL bRFMouse; \/\/ RangeFinder-Drag\n BOOL bRFSize;\n USHORT nRFIndex;\n SCsCOL nRFAddX;\n SCsROW nRFAddY;\n\n USHORT nPagebreakMouse; \/\/ Pagebreak-Modus Drag\n SCCOLROW nPagebreakBreak;\n SCCOLROW nPagebreakPrev;\n ScRange aPagebreakSource;\n ScRange aPagebreakDrag;\n BOOL bPagebreakDrawn;\n\n BYTE nPageScript;\n\n long nLastClickX;\n long nLastClickY;\n\n BOOL bDragRect;\n SCCOL nDragStartX;\n SCROW nDragStartY;\n SCCOL nDragEndX;\n SCROW nDragEndY;\n\n USHORT nCurrentPointer;\n\n BOOL bIsInScroll;\n BOOL bIsInPaint;\n\n ScDDComboBoxButton aComboButton;\n\n Point aCurMousePos;\n\n USHORT nPaintCount;\n Rectangle aRepaintPixel;\n BOOL bNeedsRepaint;\n\n BOOL bAutoMarkVisible;\n ScAddress aAutoMarkPos;\n\n BOOL bListValButton;\n ScAddress aListValPos;\n\n Rectangle aInvertRect;\n\n DECL_LINK( PopupModeEndHdl, FloatingWindow* );\n DECL_LINK( PopupSpellingHdl, SpellCallbackInfo* );\n\n BOOL TestMouse( const MouseEvent& rMEvt, BOOL bAction );\n\n BOOL DoPageFieldSelection( SCCOL nCol, SCROW nRow );\n void DoPushButton( SCCOL nCol, SCROW nRow, const MouseEvent& rMEvt );\n void PivotMouseMove( const MouseEvent& rMEvt );\n void PivotMouseButtonUp( const MouseEvent& rMEvt );\n BOOL PivotTestMouse( const MouseEvent& rMEvt, BOOL bMove );\n void DoPivotDrop( BOOL bDelete, BOOL bToCols, SCSIZE nDestPos );\n\n void DPMouseMove( const MouseEvent& rMEvt );\n void DPMouseButtonUp( const MouseEvent& rMEvt );\n void DPTestMouse( const MouseEvent& rMEvt, BOOL bMove );\n\n void RFMouseMove( const MouseEvent& rMEvt, BOOL bUp );\n\n void PagebreakMove( const MouseEvent& rMEvt, BOOL bUp );\n\n void UpdateDragRect( BOOL bShowRange, const Rectangle& rPosRect );\n\n BOOL IsAutoFilterActive( SCCOL nCol, SCROW nRow, SCTAB nTab );\n void ExecFilter( ULONG nSel, SCCOL nCol, SCROW nRow,\n const String& aValue );\n void FilterSelect( ULONG nSel );\n\n void ExecDataSelect( SCCOL nCol, SCROW nRow, const String& rStr );\n\n void ExecPageFieldSelect( SCCOL nCol, SCROW nRow, BOOL bHasSelection, const String& rStr );\n\n BOOL HasScenarioButton( const Point& rPosPixel, ScRange& rScenRange );\n\n BOOL DropScroll( const Point& rMousePos );\n\n sal_Int8 AcceptPrivateDrop( const AcceptDropEvent& rEvt );\n sal_Int8 ExecutePrivateDrop( const ExecuteDropEvent& rEvt );\n sal_Int8 DropTransferObj( ScTransferObj* pTransObj, SCCOL nDestPosX, SCROW nDestPosY,\n const Point& rLogicPos, sal_Int8 nDndAction );\n\n void HandleMouseButtonDown( const MouseEvent& rMEvt );\n\n BOOL DrawMouseButtonDown(const MouseEvent& rMEvt);\n BOOL DrawMouseButtonUp(const MouseEvent& rMEvt);\n BOOL DrawMouseMove(const MouseEvent& rMEvt);\n BOOL DrawKeyInput(const KeyEvent& rKEvt);\n BOOL DrawCommand(const CommandEvent& rCEvt);\n BOOL DrawHasMarkedObj();\n void DrawEndAction();\n void DrawMarkDropObj( SdrObject* pObj );\n SdrObject* GetEditObject();\n BOOL IsMyModel(SdrEditView* pSdrView);\n void DrawStartTimer();\n\n void DrawRedraw( ScOutputData& rOutputData, const Rectangle& rDrawingRect,\n ScUpdateMode eMode, ULONG nLayer );\n void DrawSdrGrid( const Rectangle& rDrawingRect );\n BOOL DrawBeforeScroll();\n void DrawAfterScroll(BOOL bVal);\n void OutlinerViewPaint( const Rectangle& rRect );\n void DrawMarks();\n BOOL NeedDrawMarks();\n void DrawComboButton( const Point& rCellPos,\n long nCellSizeX,\n long nCellSizeY,\n BOOL bArrowState,\n BOOL bBtnIn = FALSE );\n Rectangle GetListValButtonRect( const ScAddress& rButtonPos );\n\n void DrawPagePreview( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2 );\n\n BOOL GetEditUrl( const Point& rPos,\n String* pName=0, String* pUrl=0, String* pTarget=0 );\n BOOL GetEditUrlOrError( BOOL bSpellErr, const Point& rPos,\n String* pName=0, String* pUrl=0, String* pTarget=0 );\n\n BOOL HitRangeFinder( const Point& rMouse, BOOL& rCorner, USHORT* pIndex = NULL,\n SCsCOL* pAddX = NULL, SCsROW* pAddY = NULL );\n\n USHORT HitPageBreak( const Point& rMouse, ScRange* pSource = NULL,\n SCCOLROW* pBreak = NULL, SCCOLROW* pPrev = NULL );\n\n#ifdef AUTOFILTER_POPUP\n void DoAutoFilterPopup( SCCOL nCol, SCROW nRow, BOOL bDataSelect );\n#endif\n\n void PasteSelection( const Point& rPosPixel );\n\n void SelectForContextMenu( const Point& rPosPixel );\n\nprotected:\n virtual void Resize( const Size& rSize );\n virtual void Paint( const Rectangle& rRect );\n virtual void KeyInput(const KeyEvent& rKEvt);\n virtual void GetFocus();\n virtual void LoseFocus();\n\n virtual void RequestHelp( const HelpEvent& rEvt );\n virtual void Command( const CommandEvent& rCEvt );\n\n virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );\n virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );\n virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );\n\npublic:\n ScGridWindow( Window* pParent, ScViewData* pData, ScSplitPos eWhichPos );\n ~ScGridWindow();\n\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n virtual void MouseMove( const MouseEvent& rMEvt );\n virtual long PreNotify( NotifyEvent& rNEvt );\n virtual void Tracking( const TrackingEvent& rTEvt );\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();\n\n void FakeButtonUp();\n\n Point GetMousePosPixel() const;\n void UpdateStatusPosSize();\n\n void ClickExtern();\n\n void SetPointer( const Pointer& rPointer );\n\n void MoveMouseStatus( ScGridWindow &rDestWin );\n\n void ScrollPixel( long nDifX, long nDifY );\n void UpdateEditViewPos();\n\n void UpdateFormulas();\n\n void DoAutoFilterMenue( SCCOL nCol, SCROW nRow, BOOL bDataSelect );\n void DoScenarioMenue( const ScRange& rScenRange );\n void DoPageFieldMenue( SCCOL nCol, SCROW nRow );\n\n BOOL HasPageFieldData( SCCOL nCol, SCROW nRow ) const;\n\n void DrawButtons( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,\n ScTableInfo& rTabInfo );\n\n void Draw( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,\n ScUpdateMode eMode = SC_UPDATE_ALL );\n\n void InvertSimple( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,\n BOOL bTestMerge = FALSE, BOOL bRepeat = FALSE );\n\n void DrawDragRect( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,\n BOOL bMarkDrop = TRUE );\n\n void DrawRefMark( SCCOL nRefStartX, SCROW nRefStartY,\n SCCOL nRefEndX, SCROW nRefEndY,\n const Color& rColor, BOOL bHandle );\n\n void CreateAnchorHandle(SdrHdlList& rHdl, const ScAddress& rAddress);\n\n void HideCursor();\n void ShowCursor();\n void DrawCursor();\n void DrawAutoFillMark();\n void UpdateAutoFillMark(BOOL bMarked, const ScRange& rMarkRange);\n\n void UpdateListValPos( BOOL bVisible, const ScAddress& rPos );\n\n BOOL ShowNoteMarker( SCsCOL nPosX, SCsROW nPosY, BOOL bKeyboard );\n void HideNoteMarker();\n\n MapMode GetDrawMapMode( BOOL bForce = FALSE );\n\n void ContinueDrag();\n\n void StopMarking();\n void UpdateInputContext();\n\n void CheckInverted() { if (nPaintCount) bNeedsRepaint = TRUE; }\n\n void DoInvertRect( const Rectangle& rPixel );\n\n void CheckNeedsRepaint();\n};\n\n\n\n#endif\n\nINTEGRATION: CWS ooo19126 (1.20.128); FILE MERGED 2005\/09\/05 15:05:27 rt 1.20.128.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: gridwin.hxx,v $\n *\n * $Revision: 1.21 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:30:53 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_GRIDWIN_HXX\n#define SC_GRIDWIN_HXX\n\n#ifndef _STRING_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _TRANSFER_HXX\n#include \n#endif\n\n\/\/ nur auf dem MAC Auto-Filter per Popup\n#ifdef MAC\n#define AUTOFILTER_POPUP\n#else\n#undef AUTOFILTER_POPUP\n#endif\n\n#ifndef SC_VIEWUTIL_HXX\n#include \"viewutil.hxx\"\n#endif\n\n#ifndef SC_VIEWDATA_HXX\n#include \"viewdata.hxx\"\n#endif\n\n#ifndef SC_CBUTTON_HXX\n#include \"cbutton.hxx\"\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\nstruct ScTableInfo;\nclass ScViewSelectionEngine;\nclass ScPivot;\nclass ScDPObject;\nclass ScOutputData;\nclass ScFilterListBox;\nclass AutoFilterPopup;\nclass SdrObject;\nclass SdrEditView;\nclass ScNoteMarker;\nclass FloatingWindow;\nclass SdrHdlList;\nclass ScTransferObj;\nstruct SpellCallbackInfo;\n\n \/\/ Maus-Status (nMouseStatus)\n\n#define SC_GM_NONE 0\n#define SC_GM_TABDOWN 1\n#define SC_GM_DBLDOWN 2\n#define SC_GM_FILTER 3\n#define SC_GM_IGNORE 4\n#define SC_GM_WATERUNDO 5\n#define SC_GM_URLDOWN 6\n\n \/\/ Page-Drag-Modus\n\n#define SC_PD_NONE 0\n#define SC_PD_RANGE_L 1\n#define SC_PD_RANGE_R 2\n#define SC_PD_RANGE_T 4\n#define SC_PD_RANGE_B 8\n#define SC_PD_RANGE_TL (SC_PD_RANGE_T|SC_PD_RANGE_L)\n#define SC_PD_RANGE_TR (SC_PD_RANGE_T|SC_PD_RANGE_R)\n#define SC_PD_RANGE_BL (SC_PD_RANGE_B|SC_PD_RANGE_L)\n#define SC_PD_RANGE_BR (SC_PD_RANGE_B|SC_PD_RANGE_R)\n#define SC_PD_BREAK_H 16\n#define SC_PD_BREAK_V 32\n\n\nclass ScHideTextCursor\n{\nprivate:\n ScViewData* pViewData;\n ScSplitPos eWhich;\n\npublic:\n ScHideTextCursor( ScViewData* pData, ScSplitPos eW );\n ~ScHideTextCursor();\n};\n\n\nclass ScGridWindow : public Window, public DropTargetHelper, public DragSourceHelper\n{\n \/\/ ScFilterListBox wird immer fuer Auswahlliste benutzt\n friend class ScFilterListBox;\n#ifdef AUTOFILTER_POPUP\n friend class AutoFilterPopup;\n#endif\n\nprivate:\n ScViewData* pViewData;\n ScSplitPos eWhich;\n ScHSplitPos eHWhich;\n ScVSplitPos eVWhich;\n\n ScNoteMarker* pNoteMarker;\n\n ScFilterListBox* pFilterBox;\n FloatingWindow* pFilterFloat;\n\n USHORT nCursorHideCount;\n\n BOOL bMarking;\n\n USHORT nButtonDown;\n BOOL bEEMouse; \/\/ Edit-Engine hat Maus\n BYTE nMouseStatus;\n BYTE nNestedButtonState; \/\/ track nested button up\/down calls\n\n BOOL bPivotMouse; \/\/ Pivot-D&D (alte Pivottabellen)\n ScPivot* pDragPivot;\n BOOL bPivotColField;\n SCCOL nPivotCol;\n SCCOL nPivotField;\n\n BOOL bDPMouse; \/\/ DataPilot-D&D (neue Pivottabellen)\n long nDPField;\n ScDPObject* pDragDPObj; \/\/! name?\n\n BOOL bRFMouse; \/\/ RangeFinder-Drag\n BOOL bRFSize;\n USHORT nRFIndex;\n SCsCOL nRFAddX;\n SCsROW nRFAddY;\n\n USHORT nPagebreakMouse; \/\/ Pagebreak-Modus Drag\n SCCOLROW nPagebreakBreak;\n SCCOLROW nPagebreakPrev;\n ScRange aPagebreakSource;\n ScRange aPagebreakDrag;\n BOOL bPagebreakDrawn;\n\n BYTE nPageScript;\n\n long nLastClickX;\n long nLastClickY;\n\n BOOL bDragRect;\n SCCOL nDragStartX;\n SCROW nDragStartY;\n SCCOL nDragEndX;\n SCROW nDragEndY;\n\n USHORT nCurrentPointer;\n\n BOOL bIsInScroll;\n BOOL bIsInPaint;\n\n ScDDComboBoxButton aComboButton;\n\n Point aCurMousePos;\n\n USHORT nPaintCount;\n Rectangle aRepaintPixel;\n BOOL bNeedsRepaint;\n\n BOOL bAutoMarkVisible;\n ScAddress aAutoMarkPos;\n\n BOOL bListValButton;\n ScAddress aListValPos;\n\n Rectangle aInvertRect;\n\n DECL_LINK( PopupModeEndHdl, FloatingWindow* );\n DECL_LINK( PopupSpellingHdl, SpellCallbackInfo* );\n\n BOOL TestMouse( const MouseEvent& rMEvt, BOOL bAction );\n\n BOOL DoPageFieldSelection( SCCOL nCol, SCROW nRow );\n void DoPushButton( SCCOL nCol, SCROW nRow, const MouseEvent& rMEvt );\n void PivotMouseMove( const MouseEvent& rMEvt );\n void PivotMouseButtonUp( const MouseEvent& rMEvt );\n BOOL PivotTestMouse( const MouseEvent& rMEvt, BOOL bMove );\n void DoPivotDrop( BOOL bDelete, BOOL bToCols, SCSIZE nDestPos );\n\n void DPMouseMove( const MouseEvent& rMEvt );\n void DPMouseButtonUp( const MouseEvent& rMEvt );\n void DPTestMouse( const MouseEvent& rMEvt, BOOL bMove );\n\n void RFMouseMove( const MouseEvent& rMEvt, BOOL bUp );\n\n void PagebreakMove( const MouseEvent& rMEvt, BOOL bUp );\n\n void UpdateDragRect( BOOL bShowRange, const Rectangle& rPosRect );\n\n BOOL IsAutoFilterActive( SCCOL nCol, SCROW nRow, SCTAB nTab );\n void ExecFilter( ULONG nSel, SCCOL nCol, SCROW nRow,\n const String& aValue );\n void FilterSelect( ULONG nSel );\n\n void ExecDataSelect( SCCOL nCol, SCROW nRow, const String& rStr );\n\n void ExecPageFieldSelect( SCCOL nCol, SCROW nRow, BOOL bHasSelection, const String& rStr );\n\n BOOL HasScenarioButton( const Point& rPosPixel, ScRange& rScenRange );\n\n BOOL DropScroll( const Point& rMousePos );\n\n sal_Int8 AcceptPrivateDrop( const AcceptDropEvent& rEvt );\n sal_Int8 ExecutePrivateDrop( const ExecuteDropEvent& rEvt );\n sal_Int8 DropTransferObj( ScTransferObj* pTransObj, SCCOL nDestPosX, SCROW nDestPosY,\n const Point& rLogicPos, sal_Int8 nDndAction );\n\n void HandleMouseButtonDown( const MouseEvent& rMEvt );\n\n BOOL DrawMouseButtonDown(const MouseEvent& rMEvt);\n BOOL DrawMouseButtonUp(const MouseEvent& rMEvt);\n BOOL DrawMouseMove(const MouseEvent& rMEvt);\n BOOL DrawKeyInput(const KeyEvent& rKEvt);\n BOOL DrawCommand(const CommandEvent& rCEvt);\n BOOL DrawHasMarkedObj();\n void DrawEndAction();\n void DrawMarkDropObj( SdrObject* pObj );\n SdrObject* GetEditObject();\n BOOL IsMyModel(SdrEditView* pSdrView);\n void DrawStartTimer();\n\n void DrawRedraw( ScOutputData& rOutputData, const Rectangle& rDrawingRect,\n ScUpdateMode eMode, ULONG nLayer );\n void DrawSdrGrid( const Rectangle& rDrawingRect );\n BOOL DrawBeforeScroll();\n void DrawAfterScroll(BOOL bVal);\n void OutlinerViewPaint( const Rectangle& rRect );\n void DrawMarks();\n BOOL NeedDrawMarks();\n void DrawComboButton( const Point& rCellPos,\n long nCellSizeX,\n long nCellSizeY,\n BOOL bArrowState,\n BOOL bBtnIn = FALSE );\n Rectangle GetListValButtonRect( const ScAddress& rButtonPos );\n\n void DrawPagePreview( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2 );\n\n BOOL GetEditUrl( const Point& rPos,\n String* pName=0, String* pUrl=0, String* pTarget=0 );\n BOOL GetEditUrlOrError( BOOL bSpellErr, const Point& rPos,\n String* pName=0, String* pUrl=0, String* pTarget=0 );\n\n BOOL HitRangeFinder( const Point& rMouse, BOOL& rCorner, USHORT* pIndex = NULL,\n SCsCOL* pAddX = NULL, SCsROW* pAddY = NULL );\n\n USHORT HitPageBreak( const Point& rMouse, ScRange* pSource = NULL,\n SCCOLROW* pBreak = NULL, SCCOLROW* pPrev = NULL );\n\n#ifdef AUTOFILTER_POPUP\n void DoAutoFilterPopup( SCCOL nCol, SCROW nRow, BOOL bDataSelect );\n#endif\n\n void PasteSelection( const Point& rPosPixel );\n\n void SelectForContextMenu( const Point& rPosPixel );\n\nprotected:\n virtual void Resize( const Size& rSize );\n virtual void Paint( const Rectangle& rRect );\n virtual void KeyInput(const KeyEvent& rKEvt);\n virtual void GetFocus();\n virtual void LoseFocus();\n\n virtual void RequestHelp( const HelpEvent& rEvt );\n virtual void Command( const CommandEvent& rCEvt );\n\n virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );\n virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );\n virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );\n\npublic:\n ScGridWindow( Window* pParent, ScViewData* pData, ScSplitPos eWhichPos );\n ~ScGridWindow();\n\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n virtual void MouseMove( const MouseEvent& rMEvt );\n virtual long PreNotify( NotifyEvent& rNEvt );\n virtual void Tracking( const TrackingEvent& rTEvt );\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();\n\n void FakeButtonUp();\n\n Point GetMousePosPixel() const;\n void UpdateStatusPosSize();\n\n void ClickExtern();\n\n void SetPointer( const Pointer& rPointer );\n\n void MoveMouseStatus( ScGridWindow &rDestWin );\n\n void ScrollPixel( long nDifX, long nDifY );\n void UpdateEditViewPos();\n\n void UpdateFormulas();\n\n void DoAutoFilterMenue( SCCOL nCol, SCROW nRow, BOOL bDataSelect );\n void DoScenarioMenue( const ScRange& rScenRange );\n void DoPageFieldMenue( SCCOL nCol, SCROW nRow );\n\n BOOL HasPageFieldData( SCCOL nCol, SCROW nRow ) const;\n\n void DrawButtons( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,\n ScTableInfo& rTabInfo );\n\n void Draw( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,\n ScUpdateMode eMode = SC_UPDATE_ALL );\n\n void InvertSimple( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,\n BOOL bTestMerge = FALSE, BOOL bRepeat = FALSE );\n\n void DrawDragRect( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,\n BOOL bMarkDrop = TRUE );\n\n void DrawRefMark( SCCOL nRefStartX, SCROW nRefStartY,\n SCCOL nRefEndX, SCROW nRefEndY,\n const Color& rColor, BOOL bHandle );\n\n void CreateAnchorHandle(SdrHdlList& rHdl, const ScAddress& rAddress);\n\n void HideCursor();\n void ShowCursor();\n void DrawCursor();\n void DrawAutoFillMark();\n void UpdateAutoFillMark(BOOL bMarked, const ScRange& rMarkRange);\n\n void UpdateListValPos( BOOL bVisible, const ScAddress& rPos );\n\n BOOL ShowNoteMarker( SCsCOL nPosX, SCsROW nPosY, BOOL bKeyboard );\n void HideNoteMarker();\n\n MapMode GetDrawMapMode( BOOL bForce = FALSE );\n\n void ContinueDrag();\n\n void StopMarking();\n void UpdateInputContext();\n\n void CheckInverted() { if (nPaintCount) bNeedsRepaint = TRUE; }\n\n void DoInvertRect( const Rectangle& rPixel );\n\n void CheckNeedsRepaint();\n};\n\n\n\n#endif\n\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ Test running a file in the same directory `cling CurrentDir.C`.\n\/\/ More info in CIFactory.cpp (\"<<< cling interactive line includer >>>\")\n\n\/\/ RUN: cp \"%s\" \"%T\/CurrentDir.C\" && cd %T && %cling -Xclang -verify CurrentDir.C 2>&1 | FileCheck %s\n\/\/ Test testCurrentDir\n\nextern \"C\" {\n int printf(const char*, ...);\n char* getcwd(char *buf, std::size_t size);\n}\n\nvoid CurrentDir() {\n printf(\"Script ran\\n\"); \/\/ CHECK: Script ran\n}\n\/\/expected-no-diagnostics\nRevert \"Simplify; make Windows compatible (cannot delete cwd).\"\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ Test runing a file in the same directory `cling CurrentDir.C`\n\/\/ More info in CIFactory.cpp createCIImpl (line ~850)\n\n\/\/ RUN: cd %S && %cling -Xclang -verify CurrentDir.C 2>&1 | FileCheck %s\n\/\/ RUN: mkdir %T\/Remove && cd %T\/Remove && rm -rf %T\/Remove && %cling -DTEST_CWDRETURN %s -Xclang -verify 2>&1 | FileCheck --check-prefix CHECK --check-prefix CHECKcwd %s\n\/\/ Test testCurrentDir\n\nextern \"C\" {\n int printf(const char*, ...);\n char* getcwd(char *buf, std::size_t size);\n}\n\n#ifdef TEST_CWDRETURN\n \/\/ Make sure include still works\n #include \n #include \n#endif\n\nvoid CurrentDir() {\n #ifdef TEST_CWDRETURN\n char thisDir[1024];\n const char *rslt = getcwd(thisDir, sizeof(thisDir));\n \/\/ Make sure cling reported the error\n \/\/ CHECKcwd: Could not get current working directory: {{.*}}\n\n if (rslt)\n printf(\"Working directory exists\\n\");\n \/\/ CHECK-NOT: Working directory exists\n #endif\n\n printf(\"Script ran\\n\");\n \/\/ CHECK: Script ran\n}\n\n\/\/expected-no-diagnostics\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"GenCF1.h\"\n\n\nCGenCF1::CGenCF1()\n{\n\tt_cnt = 10000;\n\tt_allocated = 10;\n\tInit();\n}\n\n\nCGenCF1::~CGenCF1()\n{\n}\n\nvoid CGenCF1::Generate()\n{\n\tfor (int i = 0; i < t_cnt; i++) {\n\t\tif (i >= t_allocated) ResizeVectors(t_allocated * 2);\n\t\t\/\/TCHAR st[100];\n\t\t\/\/_stprintf_s(st, _T(\"%d\"), rand2());\n\t\t\/\/TRACE(st);\n\t\tif ((i > 0) && (len[i-1][0] > 1) && (coff[i-1][0] < len[i-1][0]-1)) {\n\t\t\tnote[i][0] = note[i - 1][0];\n\t\t\tlen[i][0] = len[i - 1][0];\n\t\t\tcoff[i][0] = coff[i - 1][0] + 1;\n\t\t\tpoff[i][0] = poff[i - 1][0] + 1;\n\t\t}\n\t\telse {\n\t\t\tnote[i][0] = 60 + 12 * rand2() \/ RAND_MAX;\n\t\t\tunsigned int test = RAND_MAX;\n\t\t\tlen[i][0] = 8 * rand2() \/ RAND_MAX;\n\t\t\tcoff[i][0] = 0;\n\t\t\tif (i > 0) poff[i][0] = coff[i - 1][0] + 1;\n\t\t\telse poff[i][0] = 0;\n\t\t}\n\t\t\/\/if (i < t_cnt-1) noff[i][0] = 1;\n\t\t\/\/else noff[i][0] = 0;\n\t\tatt[i][0] = 100;\n\t\ttempo[i][0] = 100;\n\t\tpause[i][0] = 0;\n\t\tt_generated = i+1;\n\t\tif (ng_min > note[i][0]) ng_min = note[i][0];\n\t\tif (ng_max < note[i][0]) ng_max = note[i][0];\n\t\t\/\/CString* st = new CString;\n\t\t\/\/st->Format(\"Note generated %d\", note[i][0]);\n\t\t\/\/::PostMessage(m_hWnd, WM_DEBUG_MSG, 0, (LPARAM)st);\n\t\tif (i % t_send == 0) t_sent = t_generated;\n\t\t\/\/Sleep(1);\n\t\tif (need_exit) return;\n\t}\n\tt_sent = t_generated;\n}\nAdded noff calculation#include \"stdafx.h\"\n#include \"GenCF1.h\"\n\n\nCGenCF1::CGenCF1()\n{\n\tt_cnt = 10000;\n\tt_allocated = 10;\n\tInit();\n}\n\n\nCGenCF1::~CGenCF1()\n{\n}\n\nvoid CGenCF1::Generate()\n{\n\tfor (int i = 0; i < t_cnt; i++) {\n\t\tif (i >= t_allocated) ResizeVectors(t_allocated * 2);\n\t\t\/\/TCHAR st[100];\n\t\t\/\/_stprintf_s(st, _T(\"%d\"), rand2());\n\t\t\/\/TRACE(st);\n\t\tif ((i > 0) && (len[i-1][0] > 1) && (coff[i-1][0] < len[i-1][0]-1)) {\n\t\t\tnote[i][0] = note[i - 1][0];\n\t\t\tlen[i][0] = len[i - 1][0];\n\t\t\tcoff[i][0] = coff[i - 1][0] + 1;\n\t\t\tpoff[i][0] = poff[i - 1][0] + 1;\n\t\t}\n\t\telse {\n\t\t\tnote[i][0] = 60 + 12 * rand2() \/ RAND_MAX;\n\t\t\tlen[i][0] = max(1, 8 * rand2() \/ RAND_MAX);\n\t\t\tcoff[i][0] = 0;\n\t\t\tif (i > 0) poff[i][0] = coff[i - 1][0] + 1;\n\t\t\telse poff[i][0] = 0;\n\t\t\tif (i > 0) {\n\t\t\t\tfor (int x = i - 1; x >= i-len[i-1][0]; x--) {\n\t\t\t\t\tnoff[x][0] = i - x;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/if (i < t_cnt-1) noff[i][0] = 1;\n\t\t\/\/else noff[i][0] = 0;\n\t\tatt[i][0] = 100;\n\t\ttempo[i][0] = 100;\n\t\tpause[i][0] = 0;\n\t\tt_generated = i+1;\n\t\tif (ng_min > note[i][0]) ng_min = note[i][0];\n\t\tif (ng_max < note[i][0]) ng_max = note[i][0];\n\t\t\/\/CString* st = new CString;\n\t\t\/\/st->Format(\"Note generated %d\", note[i][0]);\n\t\t\/\/::PostMessage(m_hWnd, WM_DEBUG_MSG, 0, (LPARAM)st);\n\t\tif (i % t_send == 0) t_sent = t_generated;\n\t\t\/\/Sleep(1);\n\t\tif (need_exit) return;\n\t}\n\tt_sent = t_generated;\n}\n<|endoftext|>"} {"text":"#include \"itkImage.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\n#include \"..\/itkMatrixMath.h\"\n\ntemplate< int dimensionT >\nint Test( void )\n{\n double epsilon = 0.000001;\n\n itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer rndGen\n = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();\n rndGen->Initialize( 1 );\n\n int returnStatus = EXIT_SUCCESS;\n\n for( unsigned int count=0; count<1000; count++ )\n {\n vnl_vector v1(dimensionT);\n for( unsigned int d=0; dGetVariateWithOpenRange();\n }\n vnl_vector v2(dimensionT);\n if( dimensionT == 3 )\n {\n v2 = itk::GetOrthogonalVector( v1 );\n if( dot_product( v1, v2 ) > epsilon )\n {\n std::cerr << count << \" : \";\n std::cerr << \"FAILURE: GetOrthogonalVector: DotProduct = \"\n << v1 << \" .* \" << v2 << \" = \" \n << dot_product( v1, v2 ) << std::endl;\n returnStatus = EXIT_FAILURE;\n }\n \n vnl_vector v3 = itk::GetCrossVector( v1, v2 );\n if( dot_product( v1, v3 ) > epsilon ||\n dot_product( v2, v3 ) > epsilon )\n {\n std::cerr << count << \" : \";\n std::cerr << \"FAILURE: GetCrossVector: DotProduct = \"\n << dot_product( v1, v3 ) << \" and \" \n << dot_product( v2, v3 ) << std::endl;\n returnStatus = EXIT_FAILURE;\n }\n }\n else\n {\n for( unsigned int d=0; dGetVariateWithOpenRange();\n }\n }\n \n v2 = v2.normalize();\n vnl_vector v4 = itk::ComputeLineStep( v1, 0.5, v2 );\n if( vnl_math_abs( itk::ComputeEuclideanDistanceVector( v1, v4 ) - 0.5 )\n > epsilon )\n {\n std::cerr << count << \" : \";\n std::cerr << \"FAILURE: ComputeLineStep = \"\n << v1 << \" + 0.5 * \" << v2 << \" != \" << v4 << std::endl;\n std::cerr << \"FAILURE: ComputeEuclidenDistanceVector = \"\n << itk::ComputeEuclideanDistanceVector( v1, v4 ) << std::endl;\n returnStatus = EXIT_FAILURE;\n }\n\n vnl_matrix m1(dimensionT, dimensionT);\n for( unsigned int r=0; rGetVariateWithOpenRange();\n m1(r,c) = m1(c,r);\n }\n }\n\n vnl_matrix eVects(dimensionT, dimensionT);\n vnl_vector eVals(dimensionT);\n itk::Eigen( m1, eVects, eVals, true );\n for( unsigned int d=0; d epsilon )\n {\n std::cerr << count << \" : \";\n std::cerr << \"FAILURE: Eigen : \"\n << \" v1 * M1 = \" << v1 \n << \" and v1 norm = \" << v1.magnitude()\n << \" != \" << eVals[d] \n << std::endl;\n returnStatus = EXIT_FAILURE;\n }\n }\n }\n \n return returnStatus;\n}\n\nint itkMatrixMathTest(int itkNotUsed(argc), char * itkNotUsed(argv)[])\n{\n\n if( Test<2>() == EXIT_FAILURE || \n Test<3>() == EXIT_FAILURE ||\n Test<4>() == EXIT_FAILURE )\n {\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n\n}\n\nSTYLE: Missing header text\/*=========================================================================\n\nLibrary: TubeTK\n\nCopyright 2010 Kitware Inc. 28 Corporate Drive,\nClifton Park, NY, 12065, USA.\n\nAll rights reserved. \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n=========================================================================*\/\n#include \"itkImage.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\n#include \"..\/itkMatrixMath.h\"\n\ntemplate< int dimensionT >\nint Test( void )\n{\n double epsilon = 0.000001;\n\n itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer rndGen\n = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();\n rndGen->Initialize( 1 );\n\n int returnStatus = EXIT_SUCCESS;\n\n for( unsigned int count=0; count<1000; count++ )\n {\n vnl_vector v1(dimensionT);\n for( unsigned int d=0; dGetVariateWithOpenRange();\n }\n vnl_vector v2(dimensionT);\n if( dimensionT == 3 )\n {\n v2 = itk::GetOrthogonalVector( v1 );\n if( dot_product( v1, v2 ) > epsilon )\n {\n std::cerr << count << \" : \";\n std::cerr << \"FAILURE: GetOrthogonalVector: DotProduct = \"\n << v1 << \" .* \" << v2 << \" = \" \n << dot_product( v1, v2 ) << std::endl;\n returnStatus = EXIT_FAILURE;\n }\n \n vnl_vector v3 = itk::GetCrossVector( v1, v2 );\n if( dot_product( v1, v3 ) > epsilon ||\n dot_product( v2, v3 ) > epsilon )\n {\n std::cerr << count << \" : \";\n std::cerr << \"FAILURE: GetCrossVector: DotProduct = \"\n << dot_product( v1, v3 ) << \" and \" \n << dot_product( v2, v3 ) << std::endl;\n returnStatus = EXIT_FAILURE;\n }\n }\n else\n {\n for( unsigned int d=0; dGetVariateWithOpenRange();\n }\n }\n \n v2 = v2.normalize();\n vnl_vector v4 = itk::ComputeLineStep( v1, 0.5, v2 );\n if( vnl_math_abs( itk::ComputeEuclideanDistanceVector( v1, v4 ) - 0.5 )\n > epsilon )\n {\n std::cerr << count << \" : \";\n std::cerr << \"FAILURE: ComputeLineStep = \"\n << v1 << \" + 0.5 * \" << v2 << \" != \" << v4 << std::endl;\n std::cerr << \"FAILURE: ComputeEuclidenDistanceVector = \"\n << itk::ComputeEuclideanDistanceVector( v1, v4 ) << std::endl;\n returnStatus = EXIT_FAILURE;\n }\n\n vnl_matrix m1(dimensionT, dimensionT);\n for( unsigned int r=0; rGetVariateWithOpenRange();\n m1(r,c) = m1(c,r);\n }\n }\n\n vnl_matrix eVects(dimensionT, dimensionT);\n vnl_vector eVals(dimensionT);\n itk::Eigen( m1, eVects, eVals, true );\n for( unsigned int d=0; d epsilon )\n {\n std::cerr << count << \" : \";\n std::cerr << \"FAILURE: Eigen : \"\n << \" v1 * M1 = \" << v1 \n << \" and v1 norm = \" << v1.magnitude()\n << \" != \" << eVals[d] \n << std::endl;\n returnStatus = EXIT_FAILURE;\n }\n }\n }\n \n return returnStatus;\n}\n\nint itkMatrixMathTest(int itkNotUsed(argc), char * itkNotUsed(argv)[])\n{\n\n if( Test<2>() == EXIT_FAILURE || \n Test<3>() == EXIT_FAILURE ||\n Test<4>() == EXIT_FAILURE )\n {\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n\n}\n\n<|endoftext|>"} {"text":"\/* The goal of these tests is to verify the behavior of all blob commands given\n * the current state is verificationStarted. This state is achieved as a out of\n * verificationPending.\n *\/\n#include \"firmware_handler.hpp\"\n#include \"firmware_unittest.hpp\"\n#include \"status.hpp\"\n#include \"util.hpp\"\n\n#include \n#include \n#include \n\n#include \n\nnamespace ipmi_flash\n{\nnamespace\n{\n\nusing ::testing::Return;\n\n\/*\n * There are the following calls (parameters may vary):\n * canHandleBlob(blob)\n * getBlobIds\n * deleteBlob(blob)\n * stat(blob)\n * stat(session)\n * open(blob)\n * close(session)\n * writemeta(session)\n * write(session)\n * read(session)\n * commit(session)\n *\n * Testing canHandleBlob is uninteresting in this state. Getting the BlobIDs\n * will inform what canHandleBlob will return.\n *\/\n\nclass FirmwareHandlerVerificationStartedTest : public IpmiOnlyFirmwareStaticTest\n{\n protected:\n void getToVerificationStarted(const std::string& blobId)\n {\n auto realHandler = dynamic_cast(handler.get());\n EXPECT_CALL(imageMock, open(blobId)).WillOnce(Return(true));\n EXPECT_TRUE(handler->open(session, flags, blobId));\n EXPECT_EQ(FirmwareBlobHandler::UpdateState::uploadInProgress,\n realHandler->getCurrentState());\n EXPECT_CALL(imageMock, close()).WillRepeatedly(Return());\n handler->close(session);\n EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationPending,\n realHandler->getCurrentState());\n\n EXPECT_TRUE(handler->open(session, flags, verifyBlobId));\n EXPECT_CALL(*verifyMockPtr, triggerVerification())\n .WillOnce(Return(true));\n\n EXPECT_TRUE(handler->commit(session, {}));\n EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationStarted,\n realHandler->getCurrentState());\n }\n\n std::uint16_t session = 1;\n std::uint16_t flags =\n blobs::OpenFlags::write | FirmwareBlobHandler::UpdateFlags::ipmi;\n};\n\n\/*\n * stat(session)\n *\/\nTEST_F(FirmwareHandlerVerificationStartedTest,\n StatOnVerifyBlobIdAfterCommitChecksStateAndReturnsRunning)\n{\n getToVerificationStarted(staticLayoutBlobId);\n EXPECT_CALL(*verifyMockPtr, checkVerificationState())\n .WillOnce(Return(VerifyCheckResponses::running));\n\n blobs::BlobMeta meta, expectedMeta = {};\n expectedMeta.size = 0;\n expectedMeta.blobState = flags | blobs::StateFlags::committing;\n expectedMeta.metadata.push_back(\n static_cast(VerifyCheckResponses::running));\n\n EXPECT_TRUE(handler->stat(session, &meta));\n EXPECT_EQ(expectedMeta, meta);\n}\n\nTEST_F(FirmwareHandlerVerificationStartedTest,\n StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsFailed)\n{\n \/* If the returned state from the verification handler is failed, it sets\n * commit_error and transitions to verificationCompleted.\n *\/\n getToVerificationStarted(staticLayoutBlobId);\n EXPECT_CALL(*verifyMockPtr, checkVerificationState())\n .WillOnce(Return(VerifyCheckResponses::failed));\n\n blobs::BlobMeta meta, expectedMeta = {};\n expectedMeta.size = 0;\n expectedMeta.blobState = flags | blobs::StateFlags::commit_error;\n expectedMeta.metadata.push_back(\n static_cast(VerifyCheckResponses::failed));\n\n auto realHandler = dynamic_cast(handler.get());\n EXPECT_TRUE(handler->stat(session, &meta));\n EXPECT_EQ(expectedMeta, meta);\n\n EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationCompleted,\n realHandler->getCurrentState());\n}\n\nTEST_F(FirmwareHandlerVerificationStartedTest,\n StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsSuccess)\n{\n \/* If the returned state from the verification handler is success, it sets\n * committed and transitions to verificationCompleted.\n *\/\n getToVerificationStarted(staticLayoutBlobId);\n EXPECT_CALL(*verifyMockPtr, checkVerificationState())\n .WillOnce(Return(VerifyCheckResponses::success));\n\n blobs::BlobMeta meta, expectedMeta = {};\n expectedMeta.size = 0;\n expectedMeta.blobState = flags | blobs::StateFlags::committed;\n expectedMeta.metadata.push_back(\n static_cast(VerifyCheckResponses::success));\n\n auto realHandler = dynamic_cast(handler.get());\n EXPECT_TRUE(handler->stat(session, &meta));\n EXPECT_EQ(expectedMeta, meta);\n\n EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationCompleted,\n realHandler->getCurrentState());\n}\n\n\/* TODO: Once verificationCompleted is the state, canHandleBlob should accept\n * updateBlobId.\n *\/\n\n\/* TODO:\n * canHandleBlob(blob)\n *\n * getBlobIds\n *\n * deleteBlob(blob)\n *\/\n\n\/*\n * stat(blob)\n *\/\nTEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveImageReturnsFailure)\n{\n getToVerificationStarted(staticLayoutBlobId);\n ASSERT_TRUE(handler->canHandleBlob(activeImageBlobId));\n\n blobs::BlobMeta meta;\n EXPECT_FALSE(handler->stat(activeImageBlobId, &meta));\n}\n\nTEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveHashReturnsFailure)\n{\n getToVerificationStarted(hashBlobId);\n ASSERT_TRUE(handler->canHandleBlob(activeHashBlobId));\n\n blobs::BlobMeta meta;\n EXPECT_FALSE(handler->stat(activeHashBlobId, &meta));\n}\n\nTEST_F(FirmwareHandlerVerificationStartedTest, StatOnVerifyBlobReturnsFailure)\n{\n \/* the verifyBlobId is available starting at verificationPending. *\/\n getToVerificationStarted(staticLayoutBlobId);\n ASSERT_TRUE(handler->canHandleBlob(verifyBlobId));\n\n blobs::BlobMeta meta;\n EXPECT_FALSE(handler->stat(verifyBlobId, &meta));\n}\n\nTEST_F(FirmwareHandlerVerificationStartedTest, StatOnNormalBlobsReturnsSuccess)\n{\n getToVerificationStarted(staticLayoutBlobId);\n\n blobs::BlobMeta expected;\n expected.blobState = FirmwareBlobHandler::UpdateFlags::ipmi;\n expected.size = 0;\n\n std::vector testBlobs = {staticLayoutBlobId, hashBlobId};\n for (const auto& blob : testBlobs)\n {\n ASSERT_TRUE(handler->canHandleBlob(blob));\n\n blobs::BlobMeta meta = {};\n EXPECT_TRUE(handler->stat(blob, &meta));\n EXPECT_EQ(expected, meta);\n }\n}\n\n\/*\n * writemeta(session)\n *\/\nTEST_F(FirmwareHandlerVerificationStartedTest,\n WriteMetaOnVerifySessionReturnsFailure)\n{\n getToVerificationStarted(staticLayoutBlobId);\n\n std::vector bytes = {0x01, 0x02};\n EXPECT_FALSE(handler->writeMeta(session, 0, bytes));\n}\n\n\/*\n * write(session)\n *\/\nTEST_F(FirmwareHandlerVerificationStartedTest,\n WriteOnVerifySessionReturnsFailure)\n{\n getToVerificationStarted(staticLayoutBlobId);\n\n std::vector bytes = {0x01, 0x02};\n EXPECT_FALSE(handler->write(session, 0, bytes));\n}\n\n\/*\n * open(blob) - there is nothing you can open, this state has an open file.\n *\/\nTEST_F(FirmwareHandlerVerificationStartedTest,\n AttemptToOpenImageFileReturnsFailure)\n{\n \/* Attempt to open a file one normally can open, however, as there is\n * already a file open, this will fail.\n *\/\n getToVerificationStarted(staticLayoutBlobId);\n\n EXPECT_FALSE(handler->open(session + 1, flags, staticLayoutBlobId));\n}\n\n\/*\n * close(session) - close while state if verificationStarted without calling\n * stat first will abort.\n *\n * read(session)\n *\n * commit(session)\n *\/\n\n} \/\/ namespace\n} \/\/ namespace ipmi_flash\ntest: firmware verificationStarted: read\/* The goal of these tests is to verify the behavior of all blob commands given\n * the current state is verificationStarted. This state is achieved as a out of\n * verificationPending.\n *\/\n#include \"firmware_handler.hpp\"\n#include \"firmware_unittest.hpp\"\n#include \"status.hpp\"\n#include \"util.hpp\"\n\n#include \n#include \n#include \n\n#include \n\nnamespace ipmi_flash\n{\nnamespace\n{\n\nusing ::testing::IsEmpty;\nusing ::testing::Return;\n\n\/*\n * There are the following calls (parameters may vary):\n * canHandleBlob(blob)\n * getBlobIds\n * deleteBlob(blob)\n * stat(blob)\n * stat(session)\n * open(blob)\n * close(session)\n * writemeta(session)\n * write(session)\n * read(session)\n * commit(session)\n *\n * Testing canHandleBlob is uninteresting in this state. Getting the BlobIDs\n * will inform what canHandleBlob will return.\n *\/\n\nclass FirmwareHandlerVerificationStartedTest : public IpmiOnlyFirmwareStaticTest\n{\n protected:\n void getToVerificationStarted(const std::string& blobId)\n {\n auto realHandler = dynamic_cast(handler.get());\n EXPECT_CALL(imageMock, open(blobId)).WillOnce(Return(true));\n EXPECT_TRUE(handler->open(session, flags, blobId));\n EXPECT_EQ(FirmwareBlobHandler::UpdateState::uploadInProgress,\n realHandler->getCurrentState());\n EXPECT_CALL(imageMock, close()).WillRepeatedly(Return());\n handler->close(session);\n EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationPending,\n realHandler->getCurrentState());\n\n EXPECT_TRUE(handler->open(session, flags, verifyBlobId));\n EXPECT_CALL(*verifyMockPtr, triggerVerification())\n .WillOnce(Return(true));\n\n EXPECT_TRUE(handler->commit(session, {}));\n EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationStarted,\n realHandler->getCurrentState());\n }\n\n std::uint16_t session = 1;\n std::uint16_t flags =\n blobs::OpenFlags::write | FirmwareBlobHandler::UpdateFlags::ipmi;\n};\n\n\/*\n * stat(session)\n *\/\nTEST_F(FirmwareHandlerVerificationStartedTest,\n StatOnVerifyBlobIdAfterCommitChecksStateAndReturnsRunning)\n{\n getToVerificationStarted(staticLayoutBlobId);\n EXPECT_CALL(*verifyMockPtr, checkVerificationState())\n .WillOnce(Return(VerifyCheckResponses::running));\n\n blobs::BlobMeta meta, expectedMeta = {};\n expectedMeta.size = 0;\n expectedMeta.blobState = flags | blobs::StateFlags::committing;\n expectedMeta.metadata.push_back(\n static_cast(VerifyCheckResponses::running));\n\n EXPECT_TRUE(handler->stat(session, &meta));\n EXPECT_EQ(expectedMeta, meta);\n}\n\nTEST_F(FirmwareHandlerVerificationStartedTest,\n StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsFailed)\n{\n \/* If the returned state from the verification handler is failed, it sets\n * commit_error and transitions to verificationCompleted.\n *\/\n getToVerificationStarted(staticLayoutBlobId);\n EXPECT_CALL(*verifyMockPtr, checkVerificationState())\n .WillOnce(Return(VerifyCheckResponses::failed));\n\n blobs::BlobMeta meta, expectedMeta = {};\n expectedMeta.size = 0;\n expectedMeta.blobState = flags | blobs::StateFlags::commit_error;\n expectedMeta.metadata.push_back(\n static_cast(VerifyCheckResponses::failed));\n\n auto realHandler = dynamic_cast(handler.get());\n EXPECT_TRUE(handler->stat(session, &meta));\n EXPECT_EQ(expectedMeta, meta);\n\n EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationCompleted,\n realHandler->getCurrentState());\n}\n\nTEST_F(FirmwareHandlerVerificationStartedTest,\n StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsSuccess)\n{\n \/* If the returned state from the verification handler is success, it sets\n * committed and transitions to verificationCompleted.\n *\/\n getToVerificationStarted(staticLayoutBlobId);\n EXPECT_CALL(*verifyMockPtr, checkVerificationState())\n .WillOnce(Return(VerifyCheckResponses::success));\n\n blobs::BlobMeta meta, expectedMeta = {};\n expectedMeta.size = 0;\n expectedMeta.blobState = flags | blobs::StateFlags::committed;\n expectedMeta.metadata.push_back(\n static_cast(VerifyCheckResponses::success));\n\n auto realHandler = dynamic_cast(handler.get());\n EXPECT_TRUE(handler->stat(session, &meta));\n EXPECT_EQ(expectedMeta, meta);\n\n EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationCompleted,\n realHandler->getCurrentState());\n}\n\n\/* TODO: Once verificationCompleted is the state, canHandleBlob should accept\n * updateBlobId.\n *\/\n\n\/* TODO:\n * canHandleBlob(blob)\n *\n * getBlobIds\n *\n * deleteBlob(blob)\n *\/\n\n\/*\n * stat(blob)\n *\/\nTEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveImageReturnsFailure)\n{\n getToVerificationStarted(staticLayoutBlobId);\n ASSERT_TRUE(handler->canHandleBlob(activeImageBlobId));\n\n blobs::BlobMeta meta;\n EXPECT_FALSE(handler->stat(activeImageBlobId, &meta));\n}\n\nTEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveHashReturnsFailure)\n{\n getToVerificationStarted(hashBlobId);\n ASSERT_TRUE(handler->canHandleBlob(activeHashBlobId));\n\n blobs::BlobMeta meta;\n EXPECT_FALSE(handler->stat(activeHashBlobId, &meta));\n}\n\nTEST_F(FirmwareHandlerVerificationStartedTest, StatOnVerifyBlobReturnsFailure)\n{\n \/* the verifyBlobId is available starting at verificationPending. *\/\n getToVerificationStarted(staticLayoutBlobId);\n ASSERT_TRUE(handler->canHandleBlob(verifyBlobId));\n\n blobs::BlobMeta meta;\n EXPECT_FALSE(handler->stat(verifyBlobId, &meta));\n}\n\nTEST_F(FirmwareHandlerVerificationStartedTest, StatOnNormalBlobsReturnsSuccess)\n{\n getToVerificationStarted(staticLayoutBlobId);\n\n blobs::BlobMeta expected;\n expected.blobState = FirmwareBlobHandler::UpdateFlags::ipmi;\n expected.size = 0;\n\n std::vector testBlobs = {staticLayoutBlobId, hashBlobId};\n for (const auto& blob : testBlobs)\n {\n ASSERT_TRUE(handler->canHandleBlob(blob));\n\n blobs::BlobMeta meta = {};\n EXPECT_TRUE(handler->stat(blob, &meta));\n EXPECT_EQ(expected, meta);\n }\n}\n\n\/*\n * writemeta(session)\n *\/\nTEST_F(FirmwareHandlerVerificationStartedTest,\n WriteMetaOnVerifySessionReturnsFailure)\n{\n getToVerificationStarted(staticLayoutBlobId);\n\n std::vector bytes = {0x01, 0x02};\n EXPECT_FALSE(handler->writeMeta(session, 0, bytes));\n}\n\n\/*\n * write(session)\n *\/\nTEST_F(FirmwareHandlerVerificationStartedTest,\n WriteOnVerifySessionReturnsFailure)\n{\n getToVerificationStarted(staticLayoutBlobId);\n\n std::vector bytes = {0x01, 0x02};\n EXPECT_FALSE(handler->write(session, 0, bytes));\n}\n\n\/*\n * open(blob) - there is nothing you can open, this state has an open file.\n *\/\nTEST_F(FirmwareHandlerVerificationStartedTest,\n AttemptToOpenImageFileReturnsFailure)\n{\n \/* Attempt to open a file one normally can open, however, as there is\n * already a file open, this will fail.\n *\/\n getToVerificationStarted(staticLayoutBlobId);\n\n EXPECT_FALSE(handler->open(session + 1, flags, staticLayoutBlobId));\n}\n\n\/*\n * read(session)\n *\/\nTEST_F(FirmwareHandlerVerificationStartedTest, ReadOfVerifyBlobReturnsEmpty)\n{\n getToVerificationStarted(staticLayoutBlobId);\n EXPECT_THAT(handler->read(session, 0, 32), IsEmpty());\n}\n\n\/*\n * close(session) - close while state if verificationStarted without calling\n * stat first will abort.\n *\n * commit(session)\n *\/\n\n} \/\/ namespace\n} \/\/ namespace ipmi_flash\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \"mnist_common.h\"\n\nusing namespace af;\n\n\/\/ Get accuracy of the predicted results\nfloat accuracy(const array& predicted, const array& target)\n{\n return 100 * count(predicted == target) \/ target.elements();\n}\n\nvoid naive_bayes_train(array &mu, array &sig2, const array &train_feats, const array &train_classes, int num_classes)\n{\n int feat_len = train_feats.dims(0);\n\n \/\/ Get mean and variance from trianing data\n mu = constant(0, feat_len, num_classes);\n sig2 = constant(0, feat_len, num_classes);\n for (int ii = 0; ii < num_classes; ii++) {\n array idx = where(train_classes == ii);\n array train_feats_ii = train_feats(span, idx);\n\n mu(span, ii) = mean(train_feats_ii, 1);\n\n \/\/ Some pixels are always 0. Add a small variance.\n sig2(span,ii) = var(train_feats_ii, 0, 1) + 0.01;\n }\n\n mu.eval();\n sig2.eval();\n}\n\narray naive_bayes_predict(const array &mu, const array &sig2, const array &test_feats, int num_classes)\n{\n int num_test = test_feats.dims(1);\n\n \/\/ Predict the probabilities for testing data\n \/\/ Using log of probabilities to reduce rounding errors\n array log_probs = constant(1, num_test, num_classes);\n for (int ii = 0; ii < num_classes; ii++) {\n\n \/\/ Tile the current mean and variance to the testing data size\n array Mu = tile(mu (span, ii), 1, num_test);\n array Sig2 = tile(sig2(span, ii), 1, num_test);\n\n array Df = test_feats - Mu;\n array log_P = (-(Df * Df) \/ (2 * Sig2)) - log(sqrt(2 * af::Pi * Sig2));\n\n \/\/ Accumulate the probabilities\n log_probs(span, ii) = sum(log_P).T();\n }\n\n \/\/ Get the location of the maximum value\n array val, idx;\n max(val, idx, log_probs, 1);\n return idx.as(f32);\n}\n\nvoid benchmark_nb(const array &train_feats, const array test_feats,\n const array &train_labels, int num_classes)\n{\n array mu, sig2;\n int iter = 25;\n\n timer::start();\n for (int i = 0; i < iter; i++) {\n naive_bayes_train(mu, sig2, train_feats, train_labels, num_classes);\n }\n af::sync();\n printf(\"Training time: %4.4lf s\\n\", timer::stop() \/ iter);\n\n timer::start();\n for (int i = 0; i < iter; i++) {\n naive_bayes_predict(mu, sig2, test_feats, num_classes);\n }\n af::sync();\n printf(\"Prediction time: %4.4lf s\\n\", timer::stop() \/ iter);\n}\n\nvoid naive_bayes_demo(bool console, int perc)\n{\n array train_images, train_labels;\n array test_images, test_labels;\n int num_train, num_test, num_classes;\n\n \/\/ Load mnist data\n float frac = (float)(perc) \/ 100.0;\n setup_mnist(&num_classes, &num_train, &num_test,\n train_images, test_images,\n train_labels, test_labels, frac);\n\n int feature_length = train_images.elements() \/ num_train;\n array train_feats = moddims(train_images, feature_length, num_train);\n array test_feats = moddims(test_images , feature_length, num_test );\n\n \/\/ Preprocess\n train_feats = train_feats + tile(min(train_feats, 1), 1, num_train);\n test_feats = test_feats + tile(min(test_feats , 1), 1, num_test );\n\n \/\/ Get training parameters\n array mu, sig2;\n naive_bayes_train(mu, sig2, train_feats, train_labels, num_classes);\n\n \/\/ Predict the classes\n array res_labels = naive_bayes_predict(mu, sig2, test_feats, num_classes);\n\n \/\/ Results\n printf(\"Trainng samples: %4d, Testing samples: %4d\\n\", num_train, num_test);\n printf(\"Accuracy on testing data: %2.2f\\n\",\n accuracy(res_labels , test_labels));\n\n benchmark_nb(train_feats, test_feats, train_labels, num_classes);\n\n if (!console) {\n display_results(test_images, res_labels, 20);\n }\n}\n\nint main(int argc, char** argv)\n{\n int device = argc > 1 ? atoi(argv[1]) : 0;\n bool console = argc > 2 ? argv[2][0] == '-' : false;\n int perc = argc > 3 ? atoi(argv[3]) : 60;\n\n try {\n\n af::deviceset(device);\n af::info();\n naive_bayes_demo(console, perc);\n\n } catch (af::exception &ae) {\n std::cout << ae.what() << std::endl;\n }\n\n}\nCleaning up naive bayes#include \n#include \n#include \n#include \n#include \n#include \n#include \"mnist_common.h\"\n\nusing namespace af;\n\n\/\/ Get accuracy of the predicted results\nfloat accuracy(const array& predicted, const array& target)\n{\n return 100 * count(predicted == target) \/ target.elements();\n}\n\nvoid naive_bayes_train(array &mu, array &sig2, const array &train_feats,\n const array &train_classes, int num_classes)\n{\n int feat_len = train_feats.dims(0);\n\n \/\/ Get mean and variance from trianing data\n mu = constant(0, feat_len, num_classes);\n sig2 = constant(0, feat_len, num_classes);\n for (int ii = 0; ii < num_classes; ii++) {\n array idx = where(train_classes == ii);\n array train_feats_ii = train_feats(span, idx);\n\n mu(span, ii) = mean(train_feats_ii, 1);\n\n \/\/ Some pixels are always 0. Add a small variance.\n sig2(span,ii) = var(train_feats_ii, 0, 1) + 0.01;\n }\n\n mu.eval();\n sig2.eval();\n}\n\narray naive_bayes_predict(const array &mu, const array &sig2, const array &test_feats, int num_classes)\n{\n int num_test = test_feats.dims(1);\n\n \/\/ Predict the probabilities for testing data\n \/\/ Using log of probabilities to reduce rounding errors\n array log_probs = constant(1, num_test, num_classes);\n for (int ii = 0; ii < num_classes; ii++) {\n\n \/\/ Tile the current mean and variance to the testing data size\n array Mu = tile(mu (span, ii), 1, num_test);\n array Sig2 = tile(sig2(span, ii), 1, num_test);\n\n array Df = test_feats - Mu;\n array log_P = (-(Df * Df) \/ (2 * Sig2)) - log(sqrt(2 * af::Pi * Sig2));\n\n \/\/ Accumulate the probabilities\n log_probs(span, ii) = sum(log_P).T();\n }\n\n \/\/ Get the location of the maximum value\n array val, idx;\n max(val, idx, log_probs, 1);\n return idx.as(f32);\n}\n\nvoid benchmark_nb(const array &train_feats, const array test_feats,\n const array &train_labels, int num_classes)\n{\n array mu, sig2;\n int iter = 25;\n\n timer::start();\n for (int i = 0; i < iter; i++) {\n naive_bayes_train(mu, sig2, train_feats, train_labels, num_classes);\n }\n af::sync();\n printf(\"Training time: %4.4lf s\\n\", timer::stop() \/ iter);\n\n timer::start();\n for (int i = 0; i < iter; i++) {\n naive_bayes_predict(mu, sig2, test_feats, num_classes);\n }\n af::sync();\n printf(\"Prediction time: %4.4lf s\\n\", timer::stop() \/ iter);\n}\n\nvoid naive_bayes_demo(bool console, int perc)\n{\n array train_images, train_labels;\n array test_images, test_labels;\n int num_train, num_test, num_classes;\n\n \/\/ Load mnist data\n float frac = (float)(perc) \/ 100.0;\n setup_mnist(&num_classes, &num_train, &num_test,\n train_images, test_images,\n train_labels, test_labels, frac);\n\n int feature_length = train_images.elements() \/ num_train;\n array train_feats = moddims(train_images, feature_length, num_train);\n array test_feats = moddims(test_images , feature_length, num_test );\n\n \/\/ Preprocess\n train_feats = train_feats;\n test_feats = test_feats;\n\n \/\/ Get training parameters\n array mu, sig2;\n naive_bayes_train(mu, sig2, train_feats, train_labels, num_classes);\n\n \/\/ Predict the classes\n array res_labels = naive_bayes_predict(mu, sig2, test_feats, num_classes);\n\n \/\/ Results\n printf(\"Trainng samples: %4d, Testing samples: %4d\\n\", num_train, num_test);\n printf(\"Accuracy on testing data: %2.2f\\n\",\n accuracy(res_labels , test_labels));\n\n benchmark_nb(train_feats, test_feats, train_labels, num_classes);\n\n if (!console) {\n display_results(test_images, res_labels, 20);\n }\n}\n\nint main(int argc, char** argv)\n{\n int device = argc > 1 ? atoi(argv[1]) : 0;\n bool console = argc > 2 ? argv[2][0] == '-' : false;\n int perc = argc > 3 ? atoi(argv[3]) : 60;\n\n try {\n\n af::deviceset(device);\n af::info();\n naive_bayes_demo(console, perc);\n\n } catch (af::exception &ae) {\n std::cout << ae.what() << std::endl;\n }\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \t\t\/\/for exit()\n\nint main(int argc, char *argv[])\n{\n\tusing namespace std;\n\tif(argc==1)\t\t\t\/\/quit if no argument\n\t{\n\t\tcerr<<\"Usage: \"<>in)\n\t\t{\n\t\t\tcout<修改了,ex1_16.cpp#include \n#include \n#include \t\t\/\/for exit()\n\nint main(int argc, char *argv[])\n{\n\tusing namespace std;\n\tif(argc==1)\t\t\t\/\/quit if no argument\n\t{\n\t\tcerr<<\"Usage: \"<>in)\n\t\t{\n\t\t\tcout<"} {"text":"\/*\n * Copyright (c) 2009 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \"db\/fiber\/FiberScheduler2.h\"\n\n#include \n#include \n\nusing namespace std;\nusing namespace db::fiber;\nusing namespace db::modest;\nusing namespace db::rt;\n\n#define DEFAULT_STACK_SIZE 0x1000 \/\/ 32k\n\nFiberScheduler2::FiberScheduler2()\n{\n \/\/ add first FiberId\n mFiberIdFreeList.push_back(1);\n}\n\nFiberScheduler2::~FiberScheduler2()\n{\n \/\/ ensure stopped\n FiberScheduler2::stop();\n \n \/\/ delete all fibers\n for(FiberMap::iterator i = mFiberMap.begin(); i != mFiberMap.end(); i++)\n {\n i->second->setState(Fiber2::Dead);\n delete i->second;\n }\n mFiberMap.clear();\n}\n\nvoid FiberScheduler2::start(\n OperationRunner* opRunner, int numOps, size_t fiberStackSize)\n{\n \/\/ save stack size\n mFiberStackSize =\n (fiberStackSize == 0 ? DEFAULT_STACK_SIZE : fiberStackSize);\n \n \/\/ create \"numOps\" Operations\n for(int i = 0; i < numOps; i++)\n {\n \/\/ create Operation\n Operation op(*this);\n mOpList.add(op);\n }\n \n \/\/ queue Operations\n mOpList.queue(opRunner);\n}\n\ninline void FiberScheduler2::stop()\n{\n \/\/ terminate all operations\n mOpList.terminate();\n \n \/\/ delete all thread contexts\n for(ContextList::iterator i = mContextList.begin();\n i != mContextList.end(); i++)\n {\n delete *i;\n }\n mContextList.clear();\n}\n\nbool FiberScheduler2::waitForLastFiberExit(bool stop)\n{\n bool rval = true;\n \n mNoFibersWaitLock.lock();\n {\n \/\/ wait on the no fibers lock until there are no more fibers\n while(rval && !mFiberMap.empty())\n {\n rval = mNoFibersWaitLock.wait();\n }\n }\n mNoFibersWaitLock.unlock();\n \n if(rval && stop)\n {\n \/\/ stop fiber scheduler\n this->stop();\n }\n \n return rval;\n}\n\nFiberId2 FiberScheduler2::addFiber(Fiber2* fiber)\n{\n FiberId2 id;\n \n \/\/ lock scheduler to add fiber\n mScheduleLock.lock();\n {\n \/\/ get available FiberId\n id = mFiberIdFreeList.front();\n mFiberIdFreeList.pop_front();\n \n \/\/ add new id if list is empty\n if(mFiberIdFreeList.empty())\n {\n mFiberIdFreeList.push_back(id + 1);\n }\n \n \/\/ assign id and scheduler to fiber\n fiber->setScheduler(id, this);\n \n \/\/ add fiber to map and queue\n mFiberMap.insert(make_pair(id, fiber));\n mFiberQueue.push_back(fiber);\n \n \/\/ notify that a fiber is available for scheduling\n fiberAvailable();\n }\n mScheduleLock.unlock();\n \n return id;\n}\n\nvoid FiberScheduler2::run()\n{\n \/\/ get and store scheduler context for this thread\n FiberContext* scheduler = new FiberContext();\n mScheduleLock.lock();\n {\n mContextList.push_back(scheduler);\n }\n mScheduleLock.unlock();\n \n \/\/ continue scheduling fibers while this thread is not interrupted\n Thread* t = Thread::currentThread();\n while(!t->isInterrupted())\n {\n \/\/ synchronously get the next fiber to schedule\n Fiber2* fiber = nextFiber();\n \n \/\/ if there is no fiber to schedule\n if(fiber == NULL)\n {\n \/\/ wait until one is available\n waitForFiber();\n }\n \/\/ else a fiber has been found\n else\n {\n if(fiber->getState() == Fiber2::New)\n {\n \/\/ initialize the fiber's context\n if(fiber->getContext()->init(fiber, mFiberStackSize))\n {\n \/\/ set fiber state to running\n fiber->setState(Fiber2::Running);\n }\n else\n {\n \/\/ failed to init fiber, not enough memory, lock to re-queue it\n mScheduleLock.lock();\n {\n mFiberQueue.push_back(fiber);\n }\n mScheduleLock.unlock();\n }\n }\n \n if(fiber->getState() == Fiber2::Running)\n {\n \/\/ swap in the fiber's context\n scheduler->swap(fiber->getContext());\n \n if(fiber->getState() != Fiber2::Sleeping)\n {\n \/\/ lock scheduling while adding fiber back to queue\n mScheduleLock.lock();\n {\n mFiberQueue.push_back(fiber);\n }\n mScheduleLock.unlock();\n \n \/\/ notify that a fiber is available\n fiberAvailable();\n }\n }\n }\n }\n}\n\nvoid FiberScheduler2::yield(Fiber2* fiber)\n{\n \/\/ swap scheduler back in\n fiber->getContext()->swapBack();\n}\n\nvoid FiberScheduler2::sleep(Fiber2* fiber)\n{\n fiber->setState(Fiber2::Sleeping);\n \n \/\/ lock scheduling to insert sleeping fiber entry\n mScheduleLock.lock();\n {\n mSleepingFibers.insert(make_pair(fiber->getId(), fiber)); \n }\n mScheduleLock.unlock();\n \n \/\/ swap scheduler back in\n fiber->getContext()->swapBack();\n}\n\nvoid FiberScheduler2::wakeup(FiberId2 id)\n{\n \/\/ lock scheduling while waking up sleeping fiber\n mScheduleLock.lock();\n {\n \/\/ find the sleeping fiber\n FiberMap::iterator i = mSleepingFibers.find(id);\n if(i != mSleepingFibers.end())\n {\n \/\/ update fiber state, add to queue, remove from sleeping fibers map\n i->second->setState(Fiber2::Running);\n mFiberQueue.push_back(i->second);\n mSleepingFibers.erase(i);\n \n \/\/ notify that a fiber is available\n fiberAvailable();\n }\n }\n mScheduleLock.unlock();\n}\n\nvoid FiberScheduler2::exit(Fiber2* fiber)\n{\n fiber->setState(Fiber2::Exited);\n \n \/\/ load scheduler back in\n fiber->getContext()->loadBack();\n}\n\nFiber2* FiberScheduler2::nextFiber()\n{\n Fiber2* rval = NULL;\n \n \/\/ lock scheduling while iterating over and modifying fiber queue\n mScheduleLock.lock();\n {\n \/\/ look for a fiber that can be scheduled:\n \n \/\/ cycle through fibers not more than once\n FiberId2 cycleEnd = 0;\n for(FiberQueue::iterator i = mFiberQueue.begin();\n rval == NULL && i != mFiberQueue.end() && (*i)->getId() != cycleEnd;)\n {\n \/\/ pop fiber off queue\n Fiber2* fiber = *i;\n i = mFiberQueue.erase(i);\n \n \/\/ check state of fiber\n switch(fiber->getState())\n {\n \/\/ if fiber is new or running, it can be scheduled\n case Fiber2::New:\n case Fiber2::Running:\n rval = fiber;\n break;\n \/\/ exited or dead fibers must be deleted\n case Fiber2::Exited:\n fiber->setState(Fiber2::Dead);\n case Fiber2::Dead:\n \/\/ add fiber ID to free list, remove fiber from scheduler\n mFiberIdFreeList.push_front(fiber->getId());\n mFiberMap.erase(fiber->getId());\n delete fiber;\n fiber = NULL;\n break;\n \/\/ sleeping fibers cannot be scheduled\n case Fiber2::Sleeping:\n break;\n }\n \n \/\/ if current fiber cannot be scheduled\n if(rval == NULL && fiber != NULL)\n {\n \/\/ push fiber onto end of queue\n mFiberQueue.push_back(fiber);\n \n \/\/ ensure current fiber is not checked again\n if(cycleEnd == 0)\n {\n cycleEnd = fiber->getId();\n }\n }\n }\n \n if(mFiberMap.empty())\n {\n \/\/ notify that no fibers are available\n noFibersAvailable();\n }\n }\n mScheduleLock.unlock();\n \n return rval;\n}\n\ninline void FiberScheduler2::fiberAvailable()\n{\n mFiberWaitLock.lock();\n mFiberWaitLock.notifyAll();\n mFiberWaitLock.unlock();\n}\n\ninline void FiberScheduler2::waitForFiber()\n{\n mFiberWaitLock.lock();\n mFiberWaitLock.wait();\n mFiberWaitLock.unlock();\n}\n\ninline void FiberScheduler2::noFibersAvailable()\n{\n mNoFibersWaitLock.lock();\n mNoFibersWaitLock.notifyAll();\n mNoFibersWaitLock.unlock();\n}\nAdded optimizations to handle low memory for fiber stacks.\/*\n * Copyright (c) 2009 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \"db\/fiber\/FiberScheduler2.h\"\n\n#include \n#include \n\nusing namespace std;\nusing namespace db::fiber;\nusing namespace db::modest;\nusing namespace db::rt;\n\n#define DEFAULT_STACK_SIZE 0x1000 \/\/ 32k\n\nFiberScheduler2::FiberScheduler2()\n{\n \/\/ add first FiberId\n mFiberIdFreeList.push_back(1);\n}\n\nFiberScheduler2::~FiberScheduler2()\n{\n \/\/ ensure stopped\n FiberScheduler2::stop();\n \n \/\/ delete all fibers\n for(FiberMap::iterator i = mFiberMap.begin(); i != mFiberMap.end(); i++)\n {\n i->second->setState(Fiber2::Dead);\n delete i->second;\n }\n mFiberMap.clear();\n}\n\nvoid FiberScheduler2::start(\n OperationRunner* opRunner, int numOps, size_t fiberStackSize)\n{\n \/\/ save stack size\n mFiberStackSize =\n (fiberStackSize == 0 ? DEFAULT_STACK_SIZE : fiberStackSize);\n \n \/\/ create \"numOps\" Operations\n for(int i = 0; i < numOps; i++)\n {\n \/\/ create Operation\n Operation op(*this);\n mOpList.add(op);\n }\n \n \/\/ queue Operations\n mOpList.queue(opRunner);\n}\n\ninline void FiberScheduler2::stop()\n{\n \/\/ terminate all operations\n mOpList.terminate();\n \n \/\/ delete all thread contexts\n for(ContextList::iterator i = mContextList.begin();\n i != mContextList.end(); i++)\n {\n delete *i;\n }\n mContextList.clear();\n}\n\nbool FiberScheduler2::waitForLastFiberExit(bool stop)\n{\n bool rval = true;\n \n mNoFibersWaitLock.lock();\n {\n \/\/ wait on the no fibers lock until there are no more fibers\n while(rval && !mFiberMap.empty())\n {\n rval = mNoFibersWaitLock.wait();\n }\n }\n mNoFibersWaitLock.unlock();\n \n if(rval && stop)\n {\n \/\/ stop fiber scheduler\n this->stop();\n }\n \n return rval;\n}\n\nFiberId2 FiberScheduler2::addFiber(Fiber2* fiber)\n{\n FiberId2 id;\n \n \/\/ lock scheduler to add fiber\n mScheduleLock.lock();\n {\n \/\/ get available FiberId\n id = mFiberIdFreeList.front();\n mFiberIdFreeList.pop_front();\n \n \/\/ add new id if list is empty\n if(mFiberIdFreeList.empty())\n {\n mFiberIdFreeList.push_back(id + 1);\n }\n \n \/\/ assign id and scheduler to fiber\n fiber->setScheduler(id, this);\n \n \/\/ add fiber to map and queue\n mFiberMap.insert(make_pair(id, fiber));\n mFiberQueue.push_back(fiber);\n \n \/\/ notify that a fiber is available for scheduling\n fiberAvailable();\n }\n mScheduleLock.unlock();\n \n return id;\n}\n\nvoid FiberScheduler2::run()\n{\n \/\/ get and store scheduler context for this thread\n FiberContext* scheduler = new FiberContext();\n mScheduleLock.lock();\n {\n mContextList.push_back(scheduler);\n }\n mScheduleLock.unlock();\n \n \/\/ continue scheduling fibers while this thread is not interrupted\n bool tryInit = true;\n Thread* t = Thread::currentThread();\n while(!t->isInterrupted())\n {\n \/\/ synchronously get the next fiber to schedule\n Fiber2* fiber = nextFiber();\n \n \/\/ if there is no fiber to schedule\n if(fiber == NULL)\n {\n \/\/ wait until one is available\n waitForFiber();\n }\n \/\/ else a fiber has been found\n else\n {\n if(fiber->getState() == Fiber2::New)\n {\n \/\/ initialize the fiber's context\n if(tryInit && fiber->getContext()->init(fiber, mFiberStackSize))\n {\n \/\/ set fiber state to running\n fiber->setState(Fiber2::Running);\n }\n else\n {\n \/\/ do not try init again until a fiber's stack is reclaimed\n tryInit = false;\n }\n }\n \n if(fiber->getState() != Fiber2::Running)\n {\n \/\/ failed to init fiber, not enough memory, lock to re-queue it\n mScheduleLock.lock();\n {\n mFiberQueue.push_back(fiber);\n }\n mScheduleLock.unlock();\n }\n else\n {\n \/\/ swap in the fiber's context\n scheduler->swap(fiber->getContext());\n \n if(fiber->getState() != Fiber2::Sleeping)\n {\n \/\/ lock scheduling while adding fiber back to queue\n mScheduleLock.lock();\n {\n \/\/ if fiber is running, put it in the back of the queue\n if(fiber->getState() == Fiber2::Running)\n {\n mFiberQueue.push_back(fiber);\n }\n \/\/ fiber is dying, so put it in front for quicker cleanup\n else\n {\n mFiberQueue.push_front(fiber);\n \n \/\/ because fiber's stack memory will be reclaimed, it\n \/\/ is safe to try init on new fibers again\n tryInit = true;\n }\n }\n mScheduleLock.unlock();\n \n \/\/ notify that a fiber is available\n fiberAvailable();\n }\n }\n }\n }\n}\n\nvoid FiberScheduler2::yield(Fiber2* fiber)\n{\n \/\/ swap scheduler back in\n fiber->getContext()->swapBack();\n}\n\nvoid FiberScheduler2::sleep(Fiber2* fiber)\n{\n fiber->setState(Fiber2::Sleeping);\n \n \/\/ lock scheduling to insert sleeping fiber entry\n mScheduleLock.lock();\n {\n mSleepingFibers.insert(make_pair(fiber->getId(), fiber)); \n }\n mScheduleLock.unlock();\n \n \/\/ swap scheduler back in\n fiber->getContext()->swapBack();\n}\n\nvoid FiberScheduler2::wakeup(FiberId2 id)\n{\n \/\/ lock scheduling while waking up sleeping fiber\n mScheduleLock.lock();\n {\n \/\/ find the sleeping fiber\n FiberMap::iterator i = mSleepingFibers.find(id);\n if(i != mSleepingFibers.end())\n {\n \/\/ update fiber state, add to queue, remove from sleeping fibers map\n i->second->setState(Fiber2::Running);\n mFiberQueue.push_back(i->second);\n mSleepingFibers.erase(i);\n \n \/\/ notify that a fiber is available\n fiberAvailable();\n }\n }\n mScheduleLock.unlock();\n}\n\nvoid FiberScheduler2::exit(Fiber2* fiber)\n{\n fiber->setState(Fiber2::Exited);\n \n \/\/ load scheduler back in\n fiber->getContext()->loadBack();\n}\n\nFiber2* FiberScheduler2::nextFiber()\n{\n Fiber2* rval = NULL;\n \n \/\/ lock scheduling while iterating over and modifying fiber queue\n mScheduleLock.lock();\n {\n \/\/ look for a fiber that can be scheduled:\n \n \/\/ cycle through fibers not more than once\n FiberId2 cycleEnd = 0;\n for(FiberQueue::iterator i = mFiberQueue.begin();\n rval == NULL && i != mFiberQueue.end() && (*i)->getId() != cycleEnd;)\n {\n \/\/ pop fiber off queue\n Fiber2* fiber = *i;\n i = mFiberQueue.erase(i);\n \n \/\/ check state of fiber\n switch(fiber->getState())\n {\n \/\/ if fiber is new or running, it can be scheduled\n case Fiber2::New:\n case Fiber2::Running:\n rval = fiber;\n break;\n \/\/ exited or dead fibers must be deleted\n case Fiber2::Exited:\n fiber->setState(Fiber2::Dead);\n case Fiber2::Dead:\n \/\/ add fiber ID to free list, remove fiber from scheduler\n mFiberIdFreeList.push_front(fiber->getId());\n mFiberMap.erase(fiber->getId());\n delete fiber;\n fiber = NULL;\n break;\n \/\/ sleeping fibers cannot be scheduled\n case Fiber2::Sleeping:\n break;\n }\n \n \/\/ if current fiber cannot be scheduled\n if(rval == NULL && fiber != NULL)\n {\n \/\/ push fiber onto end of queue\n mFiberQueue.push_back(fiber);\n \n \/\/ ensure current fiber is not checked again\n if(cycleEnd == 0)\n {\n cycleEnd = fiber->getId();\n }\n }\n }\n \n if(mFiberMap.empty())\n {\n \/\/ notify that no fibers are available\n noFibersAvailable();\n }\n }\n mScheduleLock.unlock();\n \n return rval;\n}\n\ninline void FiberScheduler2::fiberAvailable()\n{\n mFiberWaitLock.lock();\n mFiberWaitLock.notifyAll();\n mFiberWaitLock.unlock();\n}\n\ninline void FiberScheduler2::waitForFiber()\n{\n mFiberWaitLock.lock();\n mFiberWaitLock.wait();\n mFiberWaitLock.unlock();\n}\n\ninline void FiberScheduler2::noFibersAvailable()\n{\n mNoFibersWaitLock.lock();\n mNoFibersWaitLock.notifyAll();\n mNoFibersWaitLock.unlock();\n}\n<|endoftext|>"} {"text":"cppcheck reduce scope of var in toolkit\/...controlmodelcontainerbase.cxx<|endoftext|>"} {"text":"\/\/ Copyright 2016 Benjamin Glatzel\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Precompiled header file\n#include \"stdafx.h\"\n#include \"stdafx_editor.h\"\n\n\/\/ Ui\n#include \"ui_IntrinsicEdPropertyEditorRotation.h\"\n\nIntrinsicEdPropertyEditorRotation::IntrinsicEdPropertyEditorRotation(\n rapidjson::Document* p_Document, rapidjson::Value* p_CurrentProperties,\n rapidjson::Value* p_CurrentProperty, const char* p_PropertyName,\n QWidget* parent)\n : IntrinsicEdPropertyEditorBase(p_Document, p_CurrentProperties,\n p_CurrentProperty, p_PropertyName, parent)\n{\n _ui.setupUi(this);\n updateFromProperty();\n\n QObject::connect(_ui.yaw, SIGNAL(valueChanged(double)), this,\n SLOT(onValueChanged()));\n QObject::connect(_ui.pitch, SIGNAL(valueChanged(double)), this,\n SLOT(onValueChanged()));\n QObject::connect(_ui.roll, SIGNAL(valueChanged(double)), this,\n SLOT(onValueChanged()));\n QObject::connect(_ui.sYaw, SIGNAL(valueChanged(int)), this,\n SLOT(onSliderValueChanged()));\n QObject::connect(_ui.sPitch, SIGNAL(valueChanged(int)), this,\n SLOT(onSliderValueChanged()));\n QObject::connect(_ui.sRoll, SIGNAL(valueChanged(int)), this,\n SLOT(onSliderValueChanged()));\n}\n\nIntrinsicEdPropertyEditorRotation::~IntrinsicEdPropertyEditorRotation() {}\n\nvoid IntrinsicEdPropertyEditorRotation::updateFromProperty()\n{\n _INTR_ASSERT(_property);\n const rapidjson::Value& prop = *_property;\n\n if (prop[\"readOnly\"].GetBool())\n {\n _ui.yaw->setReadOnly(true);\n _ui.pitch->setReadOnly(true);\n _ui.roll->setReadOnly(true);\n _ui.sYaw->setDisabled(true);\n _ui.sPitch->setDisabled(true);\n _ui.sRoll->setDisabled(true);\n }\n\n glm::vec3 euler;\n\n if (strcmp(prop[\"type\"].GetString(), \"quat\") == 0u)\n {\n const glm::quat quat =\n glm::quat(prop[\"values\"][3].GetFloat(), prop[\"values\"][0].GetFloat(),\n prop[\"values\"][1].GetFloat(), prop[\"values\"][2].GetFloat());\n euler = glm::eulerAngles(quat);\n }\n else if (strcmp(prop[\"type\"].GetString(), \"vec3\") == 0u)\n {\n euler =\n glm::vec3(glm::radians(glm::mod(prop[\"values\"][0].GetFloat(), 360.0f)),\n glm::radians(glm::mod(prop[\"values\"][1].GetFloat(), 360.0f)),\n glm::radians(glm::mod(prop[\"values\"][2].GetFloat(), 360.0f)));\n }\n\n bool changed = _ui.yaw->value() != glm::degrees(euler.x) ||\n _ui.pitch->value() != glm::degrees(euler.y) ||\n _ui.roll->value() != glm::degrees(euler.z);\n\n if (changed)\n {\n _ui.yaw->blockSignals(true);\n _ui.pitch->blockSignals(true);\n _ui.roll->blockSignals(true);\n _ui.yaw->setValue(glm::degrees(euler.x));\n _ui.pitch->setValue(glm::degrees(euler.y));\n _ui.roll->setValue(glm::degrees(euler.z));\n _ui.sYaw->setValue(glm::degrees(euler.x));\n _ui.sPitch->setValue(glm::degrees(euler.y));\n _ui.sRoll->setValue(glm::degrees(euler.z));\n _ui.yaw->blockSignals(false);\n _ui.pitch->blockSignals(false);\n _ui.roll->blockSignals(false);\n }\n\n _ui.propertyTitle->setText(_propertyName.c_str());\n}\n\nvoid IntrinsicEdPropertyEditorRotation::onValueChanged()\n{\n _INTR_ASSERT(_property);\n rapidjson::Value& prop = *_property;\n\n _ui.sYaw->setValue(_ui.yaw->value());\n _ui.sPitch->setValue(_ui.pitch->value());\n _ui.sRoll->setValue(_ui.roll->value());\n\n const glm::vec3 euler = glm::vec3(glm::radians(_ui.yaw->value()),\n glm::radians(_ui.pitch->value()),\n glm::radians(_ui.roll->value()));\n\n bool changed = false;\n if (strcmp(prop[\"type\"].GetString(), \"quat\") == 0u)\n {\n const glm::quat quat = glm::quat(euler);\n\n changed = prop[\"values\"][0].GetFloat() != quat.x ||\n prop[\"values\"][1].GetFloat() != quat.y ||\n prop[\"values\"][2].GetFloat() != quat.z ||\n prop[\"values\"][3].GetFloat() != quat.w;\n\n if (changed)\n {\n prop[\"values\"][0].SetFloat(quat.x);\n prop[\"values\"][1].SetFloat(quat.y);\n prop[\"values\"][2].SetFloat(quat.z);\n prop[\"values\"][3].SetFloat(quat.w);\n }\n }\n else if (strcmp(prop[\"type\"].GetString(), \"vec3\") == 0u)\n {\n changed = prop[\"values\"][0].GetFloat() != glm::degrees(euler.x) ||\n prop[\"values\"][1].GetFloat() != glm::degrees(euler.y) ||\n prop[\"values\"][2].GetFloat() != glm::degrees(euler.z);\n\n if (changed)\n {\n prop[\"values\"][0].SetFloat(glm::degrees(euler.x));\n prop[\"values\"][1].SetFloat(glm::degrees(euler.y));\n prop[\"values\"][2].SetFloat(glm::degrees(euler.z));\n }\n }\n\n if (changed)\n emit valueChanged(*_properties);\n}\n\nvoid IntrinsicEdPropertyEditorRotation::onSliderValueChanged()\n{\n _INTR_ASSERT(_property);\n rapidjson::Value& prop = *_property;\n\n _ui.yaw->setValue(_ui.sYaw->value());\n _ui.pitch->setValue(_ui.sPitch->value());\n _ui.roll->setValue(_ui.sRoll->value());\n\n onValueChanged();\n}\nCorrectly block signals from sliders when updating from a property\/\/ Copyright 2016 Benjamin Glatzel\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Precompiled header file\n#include \"stdafx.h\"\n#include \"stdafx_editor.h\"\n\n\/\/ Ui\n#include \"ui_IntrinsicEdPropertyEditorRotation.h\"\n\nIntrinsicEdPropertyEditorRotation::IntrinsicEdPropertyEditorRotation(\n rapidjson::Document* p_Document, rapidjson::Value* p_CurrentProperties,\n rapidjson::Value* p_CurrentProperty, const char* p_PropertyName,\n QWidget* parent)\n : IntrinsicEdPropertyEditorBase(p_Document, p_CurrentProperties,\n p_CurrentProperty, p_PropertyName, parent)\n{\n _ui.setupUi(this);\n updateFromProperty();\n\n QObject::connect(_ui.yaw, SIGNAL(valueChanged(double)), this,\n SLOT(onValueChanged()));\n QObject::connect(_ui.pitch, SIGNAL(valueChanged(double)), this,\n SLOT(onValueChanged()));\n QObject::connect(_ui.roll, SIGNAL(valueChanged(double)), this,\n SLOT(onValueChanged()));\n QObject::connect(_ui.sYaw, SIGNAL(valueChanged(int)), this,\n SLOT(onSliderValueChanged()));\n QObject::connect(_ui.sPitch, SIGNAL(valueChanged(int)), this,\n SLOT(onSliderValueChanged()));\n QObject::connect(_ui.sRoll, SIGNAL(valueChanged(int)), this,\n SLOT(onSliderValueChanged()));\n}\n\nIntrinsicEdPropertyEditorRotation::~IntrinsicEdPropertyEditorRotation() {}\n\nvoid IntrinsicEdPropertyEditorRotation::updateFromProperty()\n{\n _INTR_ASSERT(_property);\n const rapidjson::Value& prop = *_property;\n\n if (prop[\"readOnly\"].GetBool())\n {\n _ui.yaw->setReadOnly(true);\n _ui.pitch->setReadOnly(true);\n _ui.roll->setReadOnly(true);\n _ui.sYaw->setDisabled(true);\n _ui.sPitch->setDisabled(true);\n _ui.sRoll->setDisabled(true);\n }\n\n glm::vec3 euler;\n\n if (strcmp(prop[\"type\"].GetString(), \"quat\") == 0u)\n {\n const glm::quat quat =\n glm::quat(prop[\"values\"][3].GetFloat(), prop[\"values\"][0].GetFloat(),\n prop[\"values\"][1].GetFloat(), prop[\"values\"][2].GetFloat());\n euler = glm::eulerAngles(quat);\n }\n else if (strcmp(prop[\"type\"].GetString(), \"vec3\") == 0u)\n {\n euler =\n glm::vec3(glm::radians(glm::mod(prop[\"values\"][0].GetFloat(), 360.0f)),\n glm::radians(glm::mod(prop[\"values\"][1].GetFloat(), 360.0f)),\n glm::radians(glm::mod(prop[\"values\"][2].GetFloat(), 360.0f)));\n }\n\n bool changed = _ui.yaw->value() != glm::degrees(euler.x) ||\n _ui.pitch->value() != glm::degrees(euler.y) ||\n _ui.roll->value() != glm::degrees(euler.z);\n\n if (changed)\n {\n _ui.yaw->blockSignals(true);\n _ui.pitch->blockSignals(true);\n _ui.roll->blockSignals(true);\n _ui.sYaw->blockSignals(true);\n _ui.sPitch->blockSignals(true);\n _ui.sRoll->blockSignals(true);\n _ui.yaw->setValue(glm::degrees(euler.x));\n _ui.pitch->setValue(glm::degrees(euler.y));\n _ui.roll->setValue(glm::degrees(euler.z));\n _ui.sYaw->setValue(glm::degrees(euler.x));\n _ui.sPitch->setValue(glm::degrees(euler.y));\n _ui.sRoll->setValue(glm::degrees(euler.z));\n _ui.yaw->blockSignals(false);\n _ui.pitch->blockSignals(false);\n _ui.roll->blockSignals(false);\n _ui.sYaw->blockSignals(false);\n _ui.sPitch->blockSignals(false);\n _ui.sRoll->blockSignals(false);\n }\n\n _ui.propertyTitle->setText(_propertyName.c_str());\n}\n\nvoid IntrinsicEdPropertyEditorRotation::onValueChanged()\n{\n _INTR_ASSERT(_property);\n rapidjson::Value& prop = *_property;\n\n _ui.sYaw->setValue(_ui.yaw->value());\n _ui.sPitch->setValue(_ui.pitch->value());\n _ui.sRoll->setValue(_ui.roll->value());\n\n const glm::vec3 euler = glm::vec3(glm::radians(_ui.yaw->value()),\n glm::radians(_ui.pitch->value()),\n glm::radians(_ui.roll->value()));\n\n bool changed = false;\n if (strcmp(prop[\"type\"].GetString(), \"quat\") == 0u)\n {\n const glm::quat quat = glm::quat(euler);\n\n changed = prop[\"values\"][0].GetFloat() != quat.x ||\n prop[\"values\"][1].GetFloat() != quat.y ||\n prop[\"values\"][2].GetFloat() != quat.z ||\n prop[\"values\"][3].GetFloat() != quat.w;\n\n if (changed)\n {\n prop[\"values\"][0].SetFloat(quat.x);\n prop[\"values\"][1].SetFloat(quat.y);\n prop[\"values\"][2].SetFloat(quat.z);\n prop[\"values\"][3].SetFloat(quat.w);\n }\n }\n else if (strcmp(prop[\"type\"].GetString(), \"vec3\") == 0u)\n {\n changed = prop[\"values\"][0].GetFloat() != glm::degrees(euler.x) ||\n prop[\"values\"][1].GetFloat() != glm::degrees(euler.y) ||\n prop[\"values\"][2].GetFloat() != glm::degrees(euler.z);\n\n if (changed)\n {\n prop[\"values\"][0].SetFloat(glm::degrees(euler.x));\n prop[\"values\"][1].SetFloat(glm::degrees(euler.y));\n prop[\"values\"][2].SetFloat(glm::degrees(euler.z));\n }\n }\n\n if (changed)\n emit valueChanged(*_properties);\n}\n\nvoid IntrinsicEdPropertyEditorRotation::onSliderValueChanged()\n{\n _INTR_ASSERT(_property);\n rapidjson::Value& prop = *_property;\n\n _ui.yaw->setValue(_ui.sYaw->value());\n _ui.pitch->setValue(_ui.sPitch->value());\n _ui.roll->setValue(_ui.sRoll->value());\n\n onValueChanged();\n}\n<|endoftext|>"} {"text":"\/*-------------------------------------------------------------------------\n * drawElements Quality Program Tester Core\n * ----------------------------------------\n *\n * Copyright 2014 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief String template class.\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"tcuStringTemplate.hpp\"\n#include \"tcuDefs.hpp\"\n\n#include \n\nusing std::string;\nusing std::map;\nusing std::ostringstream;\n\nnamespace tcu\n{\n\nStringTemplate::StringTemplate (void)\n{\n}\n\nStringTemplate::StringTemplate (const std::string& str)\n{\n\tsetString(str);\n}\n\nStringTemplate::~StringTemplate (void)\n{\n}\n\nvoid StringTemplate::setString (const std::string& str)\n{\n\tm_template = str;\n}\n\nstring StringTemplate::specialize (const map& params) const\n{\n\tostringstream res;\n\n\tsize_t curNdx = 0;\n\tfor (;;)\n\t{\n\t\tsize_t paramNdx = m_template.find(\"${\", curNdx);\n\t\tif (paramNdx != string::npos)\n\t\t{\n\t\t\t\/\/ Append in-between stuff.\n\t\t\tres << m_template.substr(curNdx, paramNdx - curNdx);\n\n\t\t\t\/\/ Find end-of-param.\n\t\t\tsize_t paramEndNdx = m_template.find(\"}\", paramNdx);\n\t\t\tif (paramEndNdx == string::npos)\n\t\t\t\tthrow tcu::InternalError(\"No '}' found in template parameter\", \"\", __FILE__, __LINE__);\n\n\t\t\t\/\/ Parse parameter contents.\n\t\t\tstring\tparamStr\t\t= m_template.substr(paramNdx+2, paramEndNdx-2-paramNdx);\n\t\t\tbool\tparamSingleLine\t= false;\n\t\t\tstring\tparamName;\n\t\t\tsize_t colonNdx = paramStr.find(\":\");\n\t\t\tif (colonNdx != string::npos)\n\t\t\t{\n\t\t\t\tparamName = paramStr.substr(0, colonNdx);\n\t\t\t\tstring flagsStr = paramStr.substr(colonNdx+1);\n\t\t\t\tTCU_CHECK(flagsStr == \"single-line\");\n\t\t\t\tparamSingleLine = true;\n\t\t\t}\n\t\t\telse\n\t\t\t\tparamName = paramStr;\n\n\t\t\t\/\/ Fill in parameter value.\n\t\t\tif (params.find(paramName) != params.end())\n\t\t\t{\n\t\t\t\tconst string& val = (*params.find(paramName)).second;\n\t\t\t\tif (paramSingleLine)\n\t\t\t\t{\n\t\t\t\t\tstring tmp = val;\n\t\t\t\t\tfor (size_t ndx = tmp.find(\"\\n\"); ndx != string::npos; ndx = tmp.find(\"\\n\"))\n\t\t\t\t\t\ttmp = tmp.replace(ndx, 1, \" \");\n\t\t\t\t\tres << tmp;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tres << val;\n\t\t\t}\n\t\t\telse\n\t\t\t\tthrow tcu::InternalError((string(\"Value for parameter '\") + paramName + \"' not found in map\").c_str(), \"\", __FILE__, __LINE__);\n\n\t\t\t\/\/ Skip over template.\n\t\t\tcurNdx = paramEndNdx + 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (curNdx < m_template.length())\n\t\t\t\tres << &m_template[curNdx];\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn res.str();\n}\n\n} \/\/ tcu\nCherry-pick a few tcu::StringTemplate fixes to master\/*-------------------------------------------------------------------------\n * drawElements Quality Program Tester Core\n * ----------------------------------------\n *\n * Copyright 2014 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief String template class.\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"tcuStringTemplate.hpp\"\n#include \"tcuDefs.hpp\"\n\n#include \n\nusing std::string;\nusing std::map;\nusing std::ostringstream;\n\nnamespace tcu\n{\n\nStringTemplate::StringTemplate (void)\n{\n}\n\nStringTemplate::StringTemplate (const std::string& str)\n{\n\tsetString(str);\n}\n\nStringTemplate::~StringTemplate (void)\n{\n}\n\nvoid StringTemplate::setString (const std::string& str)\n{\n\tm_template = str;\n}\n\nstring StringTemplate::specialize (const map& params) const\n{\n\tostringstream res;\n\n\tsize_t curNdx = 0;\n\tfor (;;)\n\t{\n\t\tsize_t paramNdx = m_template.find(\"${\", curNdx);\n\t\tif (paramNdx != string::npos)\n\t\t{\n\t\t\t\/\/ Append in-between stuff.\n\t\t\tres << m_template.substr(curNdx, paramNdx - curNdx);\n\n\t\t\t\/\/ Find end-of-param.\n\t\t\tsize_t paramEndNdx = m_template.find(\"}\", paramNdx);\n\t\t\tif (paramEndNdx == string::npos)\n\t\t\t\tTCU_THROW(InternalError, \"No '}' found in template parameter\");\n\n\t\t\t\/\/ Parse parameter contents.\n\t\t\tstring\tparamStr\t\t= m_template.substr(paramNdx+2, paramEndNdx-2-paramNdx);\n\t\t\tbool\tparamSingleLine\t= false;\n\t\t\tbool\tparamOptional\t= false;\n\t\t\tstring\tparamName;\n\t\t\tsize_t colonNdx = paramStr.find(\":\");\n\t\t\tif (colonNdx != string::npos)\n\t\t\t{\n\t\t\t\tparamName = paramStr.substr(0, colonNdx);\n\t\t\t\tstring flagsStr = paramStr.substr(colonNdx+1);\n\t\t\t\tif (flagsStr == \"single-line\")\n\t\t\t\t{\n\t\t\t\t\tparamSingleLine = true;\n\t\t\t\t}\n\t\t\t\telse if (flagsStr == \"opt\")\n\t\t\t\t{\n\t\t\t\t\tparamOptional = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tTCU_THROW(InternalError, (string(\"Unrecognized flag\") + paramStr).c_str());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\tparamName = paramStr;\n\n\t\t\t\/\/ Fill in parameter value.\n\t\t\tif (params.find(paramName) != params.end())\n\t\t\t{\n\t\t\t\tconst string& val = (*params.find(paramName)).second;\n\t\t\t\tif (paramSingleLine)\n\t\t\t\t{\n\t\t\t\t\tstring tmp = val;\n\t\t\t\t\tfor (size_t ndx = tmp.find(\"\\n\"); ndx != string::npos; ndx = tmp.find(\"\\n\"))\n\t\t\t\t\t\ttmp = tmp.replace(ndx, 1, \" \");\n\t\t\t\t\tres << tmp;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tres << val;\n\t\t\t}\n\t\t\telse if (!paramOptional)\n\t\t\t\tTCU_THROW(InternalError, (string(\"Value for parameter '\") + paramName + \"' not found in map\").c_str());\n\n\t\t\t\/\/ Skip over template.\n\t\t\tcurNdx = paramEndNdx + 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (curNdx < m_template.length())\n\t\t\t\tres << &m_template[curNdx];\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn res.str();\n}\n\n} \/\/ tcu\n<|endoftext|>"} {"text":"\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2017 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\n#include \n#include \n\n#include \"mainwindow.h\"\n\n#include \n\nstatic const QString style = R\"style(\nQWidget {\n \/*font-family: \"Helvetica\";*\/\n}\nQWidget#MainWindow, QTextEdit, QWidget#SyncWidget, QWidget#DownloadArea {\n background-color: rgb(40, 40, 40);\n}\nQTextEdit, QLabel, QComboBox, QCheckBox {\n color: #EDEDED;\n font-size: 12px;\n}\nQLabel {\n font-size: 13px;\n}\nQLabel#Image {\n margin: -10px 0px -5px 0px;\n}\nQTextEdit {\n border-width: 2px 2px 0px 0px;\n border-style: solid;\n background-color: rgb(60, 60, 60);\n}\nQPushButton {\n color:#202020;\n background-color:\n qlineargradient(\n x1: 0, y1: 0, x2: 0, y2: 1,\n stop: 0 white,\n stop: 1 #555555\n );\n border: 1px solid black;\n font-size: 11px;\n min-height: 20px;\n}\nQComboBox { \n background-color: rgb(60, 60, 60);\n min-height: 20px;\n}\nQComboBox:focus, QComboBox:focus QAbstractItemView {\n color: white;\n background-color: rgb(60, 60, 60);\n selection-background-color: rgb(75, 75, 75);\n}\nQCheckBox {\n border: none;\n}\nQCheckBox::indicator {\n width: 12px;\n height: 12px;\n}\nQCheckBox::indicator::unchecked {\n border: 1px solid #5A5A5A;\n background: #A0A0A0;\n}\nQCheckBox::indicator:unchecked:hover {\n border: 1px solid #DDDDDD;\n}\nQCheckBox::indicator::checked {\n border: 1px solid #5A5A5A;\n background: #5AB65A;\n}\nQCheckBox::indicator:checked:hover {\n border: 1px solid #DDDDDD;\n}\nQGroupBox, QScrollArea {\n border: 0px;\n}\nInfoWidget {\n border-width: 1px;\n border-style: solid;\n border-color: #BBBBBB;\n margin: 2px 1px 2px 1px;\n padding: 7.5px;\n}\nInfoWidget QLabel#Name {\n font-size: 17px;\n}\nInfoWidget QLabel#Bytes {\n font-size: 13px;\n font-family: \"Lucida Console\";\n} \nInfoWidget QLabel#MessageLeft, QLabel#MessageCenter, QLabel#MessageRight {\n font-size: 11.5px;\n margin-top: -2px;\n} \nInfoWidget QProgressBar {\n border: 2px solid #BBBBBB;\n border-radius: 5px;\n background: white;\n height: 15px;\n}\nInfoWidget QProgressBar::chunk {\n background: qlineargradient(\n x1: 0, y1: 0.5, x2: 1, y2: 0.5,\n stop: 0 #444444,\n stop: 1 #600000\n );\n}\nQScrollBar {\n border: 1px solid #000000;\n background: #282828;\n width: 15px;\n margin: 16px 0px 16px 0px;\n}\nQScrollBar::handle {\n background: #B0B0B0;\n border: 1px solid #000000;\n border-width: 1px 0px 1px 0px;\n min-height: 20px;\n}\nQScrollBar::add-line, QScrollBar::sub-line {\n background:#B0B0B0;\n border: 1px solid #5A5A5A;\n subcontrol-origin: margin;\n}\nQScrollBar::add-line {\n top: 15px;\n height: 15px;\n}\nQScrollBar::sub-line {\n height: 15px;\n subcontrol-position: top;\n}\nQScrollBar::up-arrow, QScrollBar::down-arrow {\n border: 1px solid #5A5A5A;\n width: 3px;\n height: 3px;\n background-color: #353535;\n}\nQScrollBar::add-page, QScrollBar::sub-page {\n background: none;\n}\n)style\";\n\nint main(int argc, char** argv) {\n QApplication app(argc, argv);\n app.setStyleSheet(style);\n\n\tMainWindow window;\n window.show();\n\n return app.exec();\n}\nChange tab to spaces\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2017 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\n#include \n#include \n\n#include \"mainwindow.h\"\n\n#include \n\nstatic const QString style = R\"style(\nQWidget {\n \/*font-family: \"Helvetica\";*\/\n}\nQWidget#MainWindow, QTextEdit, QWidget#SyncWidget, QWidget#DownloadArea {\n background-color: rgb(40, 40, 40);\n}\nQTextEdit, QLabel, QComboBox, QCheckBox {\n color: #EDEDED;\n font-size: 12px;\n}\nQLabel {\n font-size: 13px;\n}\nQLabel#Image {\n margin: -10px 0px -5px 0px;\n}\nQTextEdit {\n border-width: 2px 2px 0px 0px;\n border-style: solid;\n background-color: rgb(60, 60, 60);\n}\nQPushButton {\n color:#202020;\n background-color:\n qlineargradient(\n x1: 0, y1: 0, x2: 0, y2: 1,\n stop: 0 white,\n stop: 1 #555555\n );\n border: 1px solid black;\n font-size: 11px;\n min-height: 20px;\n}\nQComboBox { \n background-color: rgb(60, 60, 60);\n min-height: 20px;\n}\nQComboBox:focus, QComboBox:focus QAbstractItemView {\n color: white;\n background-color: rgb(60, 60, 60);\n selection-background-color: rgb(75, 75, 75);\n}\nQCheckBox {\n border: none;\n}\nQCheckBox::indicator {\n width: 12px;\n height: 12px;\n}\nQCheckBox::indicator::unchecked {\n border: 1px solid #5A5A5A;\n background: #A0A0A0;\n}\nQCheckBox::indicator:unchecked:hover {\n border: 1px solid #DDDDDD;\n}\nQCheckBox::indicator::checked {\n border: 1px solid #5A5A5A;\n background: #5AB65A;\n}\nQCheckBox::indicator:checked:hover {\n border: 1px solid #DDDDDD;\n}\nQGroupBox, QScrollArea {\n border: 0px;\n}\nInfoWidget {\n border-width: 1px;\n border-style: solid;\n border-color: #BBBBBB;\n margin: 2px 1px 2px 1px;\n padding: 7.5px;\n}\nInfoWidget QLabel#Name {\n font-size: 17px;\n}\nInfoWidget QLabel#Bytes {\n font-size: 13px;\n font-family: \"Lucida Console\";\n} \nInfoWidget QLabel#MessageLeft, QLabel#MessageCenter, QLabel#MessageRight {\n font-size: 11.5px;\n margin-top: -2px;\n} \nInfoWidget QProgressBar {\n border: 2px solid #BBBBBB;\n border-radius: 5px;\n background: white;\n height: 15px;\n}\nInfoWidget QProgressBar::chunk {\n background: qlineargradient(\n x1: 0, y1: 0.5, x2: 1, y2: 0.5,\n stop: 0 #444444,\n stop: 1 #600000\n );\n}\nQScrollBar {\n border: 1px solid #000000;\n background: #282828;\n width: 15px;\n margin: 16px 0px 16px 0px;\n}\nQScrollBar::handle {\n background: #B0B0B0;\n border: 1px solid #000000;\n border-width: 1px 0px 1px 0px;\n min-height: 20px;\n}\nQScrollBar::add-line, QScrollBar::sub-line {\n background:#B0B0B0;\n border: 1px solid #5A5A5A;\n subcontrol-origin: margin;\n}\nQScrollBar::add-line {\n top: 15px;\n height: 15px;\n}\nQScrollBar::sub-line {\n height: 15px;\n subcontrol-position: top;\n}\nQScrollBar::up-arrow, QScrollBar::down-arrow {\n border: 1px solid #5A5A5A;\n width: 3px;\n height: 3px;\n background-color: #353535;\n}\nQScrollBar::add-page, QScrollBar::sub-page {\n background: none;\n}\n)style\";\n\nint main(int argc, char** argv) {\n QApplication app(argc, argv);\n app.setStyleSheet(style);\n\n MainWindow window;\n window.show();\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Containers_Set_inl_\n#define _Stroika_Foundation_Containers_Set_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n\n#include \"Concrete\/Set_Factory.h\"\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Containers {\n\n\n \/*\n ********************************************************************************\n ***************************** Set ***********************************\n ********************************************************************************\n *\/\n template \n inline Set::Set ()\n : inherited (static_cast (Concrete::Set_Factory::mk ()))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n }\n template \n inline Set::Set (const Set& src)\n : inherited (static_cast (src))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n }\n#if qCompilerAndStdLib_Supports_initializer_lists\n template \n inline Set::Set (const std::initializer_list& s)\n : inherited (static_cast (Concrete::Set_Factory::mk ()))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n AddAll (src);\n }\n#endif\n template \n template \n inline Set::Set (const CONTAINER_OF_T& src)\n : inherited (static_cast (Concrete::Set_Factory::mk ()))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n AddAll (src);\n }\n template \n inline Set::Set (const _SharedPtrIRep& rep)\n : inherited (typename inherited::_SharedPtrIRep (rep))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n RequireNotNull (rep);\n }\n template \n template \n inline Set::Set (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)\n : inherited (static_cast (Concrete::Set_Factory::mk ()))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n AddAll (start, end);\n }\n template \n inline Set& Set::operator= (const Set& rhs)\n {\n inherited::operator= (rhs);\n return *this;\n }\n template \n inline const typename Set::_IRep& Set::_GetRep () const\n {\n EnsureMember (&inherited::_GetRep (), _IRep); \/\/ use static_cast cuz more efficient, but validate with assertion\n return *static_cast (&inherited::_GetRep ());\n }\n template \n inline typename Set::_IRep& Set::_GetRep ()\n {\n EnsureMember (&inherited::_GetRep (), _IRep); \/\/ use static_cast cuz more efficient, but validate with assertion\n return *static_cast<_IRep*> (&inherited::_GetRep ());\n }\n template \n inline bool Set::Contains (T item) const\n {\n return _GetRep ().Contains (item);\n }\n template \n inline Memory::Optional Set::Lookup (T item) const\n {\n return _GetRep ().Lookup (item);\n }\n template \n inline void Set::Add (T item)\n {\n _GetRep ().Add (item);\n }\n template \n template \n void Set::AddAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)\n {\n for (auto i = start; i != end; ++i) {\n Add (*i);\n }\n }\n template \n template \n inline void Set::AddAll (const CONTAINER_OF_T& s)\n {\n \/\/ Note - unlike Bag - we dont need to check for this != &s because if we\n \/\/ attempt to add items that already exist, it would do nothing, and not lead to\n \/\/ an infinite loop\n AddAll (std::begin (s), std::end (s));\n }\n template \n inline void Set::Remove (T item)\n {\n _GetRep ().Remove (item);\n }\n template \n inline void Set::Remove (const Iterator& i)\n {\n _GetRep ().Remove (i);\n }\n template \n template \n void Set::RemoveAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)\n {\n for (auto i = start; i != end; ++i) {\n Remove (*i);\n }\n }\n template \n template \n inline void Set::RemoveAll (const CONTAINER_OF_T& s)\n {\n RemoveAll (std::begin (s), std::end (s));\n }\n template \n inline void Set::RemoveAll ()\n {\n _GetRep ().RemoveAll ();\n }\n template \n bool Set::Equals (const Set& rhs) const\n {\n return (_GetRep ().Equals (rhs._GetRep ()));\n }\n template \n inline bool Set::operator== (const Set& rhs) const\n {\n return Equals (rhs);\n }\n template \n inline bool Set::operator!= (const Set& rhs) const\n {\n return (not Equals (rhs));\n }\n template \n inline Set& Set::operator+= (T item)\n {\n Add (item);\n return *this;\n }\n template \n template \n inline Set& Set::operator+= (const CONTAINER_OF_T& items)\n {\n AddAll (items);\n return (*this);\n }\n template \n inline Set& Set::operator-= (T item)\n {\n Remove (item);\n return *this;\n }\n template \n template \n inline Set& Set::operator-= (const CONTAINER_OF_T& items)\n {\n RemoveAll (items);\n return *this;\n }\n template \n inline void Set::clear ()\n {\n RemoveAll ();\n }\n\n\n \/*\n ********************************************************************************\n ************************** Set::_IRep *******************************\n ********************************************************************************\n *\/\n template \n inline Set::_IRep::_IRep ()\n {\n }\n template \n inline Set::_IRep::~_IRep ()\n {\n }\n template \n bool Set::_IRep::_Equals_Reference_Implementation (const _IRep& rhs) const\n {\n if (this == &rhs) {\n return true;\n }\n if (this->GetLength () != rhs.GetLength ()) {\n return false;\n }\n \/\/ Note - no need to iterate over rhs because we checked sizes the same\n for (auto i = this->MakeIterator (); not i.Done (); ++i) {\n if (not rhs.Contains (*i)) {\n return false;\n }\n }\n return true;\n }\n\n\n }\n }\n}\n#endif \/* _Stroika_Foundation_Containers_Set_inl_ *\/\nfixed typo\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Containers_Set_inl_\n#define _Stroika_Foundation_Containers_Set_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n\n#include \"Concrete\/Set_Factory.h\"\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Containers {\n\n\n \/*\n ********************************************************************************\n ***************************** Set ***********************************\n ********************************************************************************\n *\/\n template \n inline Set::Set ()\n : inherited (static_cast (Concrete::Set_Factory::mk ()))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n }\n template \n inline Set::Set (const Set& src)\n : inherited (static_cast (src))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n }\n#if qCompilerAndStdLib_Supports_initializer_lists\n template \n inline Set::Set (const std::initializer_list& src)\n : inherited (static_cast (Concrete::Set_Factory::mk ()))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n AddAll (src);\n }\n#endif\n template \n template \n inline Set::Set (const CONTAINER_OF_T& src)\n : inherited (static_cast (Concrete::Set_Factory::mk ()))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n AddAll (src);\n }\n template \n inline Set::Set (const _SharedPtrIRep& rep)\n : inherited (typename inherited::_SharedPtrIRep (rep))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n RequireNotNull (rep);\n }\n template \n template \n inline Set::Set (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)\n : inherited (static_cast (Concrete::Set_Factory::mk ()))\n {\n AssertMember (&inherited::_GetRep (), _IRep);\n AddAll (start, end);\n }\n template \n inline Set& Set::operator= (const Set& rhs)\n {\n inherited::operator= (rhs);\n return *this;\n }\n template \n inline const typename Set::_IRep& Set::_GetRep () const\n {\n EnsureMember (&inherited::_GetRep (), _IRep); \/\/ use static_cast cuz more efficient, but validate with assertion\n return *static_cast (&inherited::_GetRep ());\n }\n template \n inline typename Set::_IRep& Set::_GetRep ()\n {\n EnsureMember (&inherited::_GetRep (), _IRep); \/\/ use static_cast cuz more efficient, but validate with assertion\n return *static_cast<_IRep*> (&inherited::_GetRep ());\n }\n template \n inline bool Set::Contains (T item) const\n {\n return _GetRep ().Contains (item);\n }\n template \n inline Memory::Optional Set::Lookup (T item) const\n {\n return _GetRep ().Lookup (item);\n }\n template \n inline void Set::Add (T item)\n {\n _GetRep ().Add (item);\n }\n template \n template \n void Set::AddAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)\n {\n for (auto i = start; i != end; ++i) {\n Add (*i);\n }\n }\n template \n template \n inline void Set::AddAll (const CONTAINER_OF_T& s)\n {\n \/\/ Note - unlike Bag - we dont need to check for this != &s because if we\n \/\/ attempt to add items that already exist, it would do nothing, and not lead to\n \/\/ an infinite loop\n AddAll (std::begin (s), std::end (s));\n }\n template \n inline void Set::Remove (T item)\n {\n _GetRep ().Remove (item);\n }\n template \n inline void Set::Remove (const Iterator& i)\n {\n _GetRep ().Remove (i);\n }\n template \n template \n void Set::RemoveAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)\n {\n for (auto i = start; i != end; ++i) {\n Remove (*i);\n }\n }\n template \n template \n inline void Set::RemoveAll (const CONTAINER_OF_T& s)\n {\n RemoveAll (std::begin (s), std::end (s));\n }\n template \n inline void Set::RemoveAll ()\n {\n _GetRep ().RemoveAll ();\n }\n template \n bool Set::Equals (const Set& rhs) const\n {\n return (_GetRep ().Equals (rhs._GetRep ()));\n }\n template \n inline bool Set::operator== (const Set& rhs) const\n {\n return Equals (rhs);\n }\n template \n inline bool Set::operator!= (const Set& rhs) const\n {\n return (not Equals (rhs));\n }\n template \n inline Set& Set::operator+= (T item)\n {\n Add (item);\n return *this;\n }\n template \n template \n inline Set& Set::operator+= (const CONTAINER_OF_T& items)\n {\n AddAll (items);\n return (*this);\n }\n template \n inline Set& Set::operator-= (T item)\n {\n Remove (item);\n return *this;\n }\n template \n template \n inline Set& Set::operator-= (const CONTAINER_OF_T& items)\n {\n RemoveAll (items);\n return *this;\n }\n template \n inline void Set::clear ()\n {\n RemoveAll ();\n }\n\n\n \/*\n ********************************************************************************\n ************************** Set::_IRep *******************************\n ********************************************************************************\n *\/\n template \n inline Set::_IRep::_IRep ()\n {\n }\n template \n inline Set::_IRep::~_IRep ()\n {\n }\n template \n bool Set::_IRep::_Equals_Reference_Implementation (const _IRep& rhs) const\n {\n if (this == &rhs) {\n return true;\n }\n if (this->GetLength () != rhs.GetLength ()) {\n return false;\n }\n \/\/ Note - no need to iterate over rhs because we checked sizes the same\n for (auto i = this->MakeIterator (); not i.Done (); ++i) {\n if (not rhs.Contains (*i)) {\n return false;\n }\n }\n return true;\n }\n\n\n }\n }\n}\n#endif \/* _Stroika_Foundation_Containers_Set_inl_ *\/\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"util.h\"\n\nusing namespace std;\n\nbool show_addresses;\n\nvoid status(string message) {\n cout << \"[+] \" << message << \"\\n\";\n}\n\nvoid header() {\n cout << \"SIC-Disassembler v1.3 by Jay Bosamiya\\n\"\n \"-------------------------------------\\n\\n\";\n}\n\nvoid usage(string progname) {\n cerr << \"Usage: \" << progname << \" input_object_file output_assembly_file [-a]\\n\";\n cerr << \" Options:\\n\";\n cerr << \" -a Show addresses in assembly output\\n\";\n exit(-2);\n}\n\nvoid error(string err) {\n cerr << \"[!] Error: \" << err << \"\\n\";\n}\n\nvoid fatal(string err, int code) {\n error(err);\n exit(code);\n}\n\nbool is_hex_digit(char c) {\n\treturn\n\t\t(c >= 'A' && c <= 'F') ||\n\t\t(c >= '0' && c <= '9');\n}\n\nbool is_hex_string(std::string s) {\n\tbool ret = true;\n\tfor ( const char *c = s.c_str(); *c && ret ; c++ ) {\n\t\tret = ret && is_hex_digit(*c);\n\t}\n\treturn ret;\n}\n\nvoid make_upper_case(std::string &s) {\n\tfor ( string::iterator c = s.begin() ; c != s.end() ; c++ ) {\n\t\tif ( *c >= 'a' && *c <= 'z' ) {\n\t\t\t*c = (*c - 'a') + 'A';\n\t\t}\n\t}\n}\n\nint hexchar2int(char c) {\n\tint ret = -1;\n\tif ( c >= '0' && c <= '9' ) {\n\t\tret = (c-'0');\n\t} else if ( c >= 'A' && c <= 'F' ) {\n\t\tret = (c-'A')+10;\n\t}\n\treturn ret;\n}\n\nint hex2int(string s) {\n\tint ret = 0;\n\tfor ( const char * cc = s.c_str() ; *cc ; cc++ ) {\n\t\tret *= 16;\n\t\tconst char &c = *cc;\n\t\tif ( is_hex_digit(c) ) {\n\t\t\tret += hexchar2int(c);\n\t\t} else {\n\t\t\tfatal(\"Hex values need to be 0-9 or A-F\");\n\t\t}\n\t}\n\treturn ret;\n}\n\nstring byte2hex(int c) {\n\tstring ret = \"\";\n\tif ( c < 0 || c >= 256 ) {\n\t\tfatal(\"Illegal value for byte\");\n\t}\n\tret += (c\/16 < 10)?('0'+c\/16):('A'+c\/16-10);\n\tret += (c%16 < 10)?('0'+c%16):('A'+c%16-10);\n\treturn ret;\n}\n\nstring int2hex(int c, int bytes) {\n\tif ( c < 0 ) {\n\t\treturn int2hex(c&0x7FFFFFFF,bytes);\n\t}\n\tif ( bytes <= 0 ) {\n\t\treturn \"\";\n\t}\n\treturn int2hex(c\/256,bytes-1)+byte2hex(c%256);\n}\n\nstd::string int2str(int c) {\n\tchar ret[20];\n\tsprintf(ret,\"%d\",c);\n\treturn ret;\n}\nUpdate version#include \n#include \n#include \n#include \"util.h\"\n\nusing namespace std;\n\nbool show_addresses;\n\nvoid status(string message) {\n cout << \"[+] \" << message << \"\\n\";\n}\n\nvoid header() {\n cout << \"SIC-Disassembler v1.4 by Jay Bosamiya\\n\"\n \"-------------------------------------\\n\\n\";\n}\n\nvoid usage(string progname) {\n cerr << \"Usage: \" << progname << \" input_object_file output_assembly_file [-a]\\n\";\n cerr << \" Options:\\n\";\n cerr << \" -a Show addresses in assembly output\\n\";\n exit(-2);\n}\n\nvoid error(string err) {\n cerr << \"[!] Error: \" << err << \"\\n\";\n}\n\nvoid fatal(string err, int code) {\n error(err);\n exit(code);\n}\n\nbool is_hex_digit(char c) {\n\treturn\n\t\t(c >= 'A' && c <= 'F') ||\n\t\t(c >= '0' && c <= '9');\n}\n\nbool is_hex_string(std::string s) {\n\tbool ret = true;\n\tfor ( const char *c = s.c_str(); *c && ret ; c++ ) {\n\t\tret = ret && is_hex_digit(*c);\n\t}\n\treturn ret;\n}\n\nvoid make_upper_case(std::string &s) {\n\tfor ( string::iterator c = s.begin() ; c != s.end() ; c++ ) {\n\t\tif ( *c >= 'a' && *c <= 'z' ) {\n\t\t\t*c = (*c - 'a') + 'A';\n\t\t}\n\t}\n}\n\nint hexchar2int(char c) {\n\tint ret = -1;\n\tif ( c >= '0' && c <= '9' ) {\n\t\tret = (c-'0');\n\t} else if ( c >= 'A' && c <= 'F' ) {\n\t\tret = (c-'A')+10;\n\t}\n\treturn ret;\n}\n\nint hex2int(string s) {\n\tint ret = 0;\n\tfor ( const char * cc = s.c_str() ; *cc ; cc++ ) {\n\t\tret *= 16;\n\t\tconst char &c = *cc;\n\t\tif ( is_hex_digit(c) ) {\n\t\t\tret += hexchar2int(c);\n\t\t} else {\n\t\t\tfatal(\"Hex values need to be 0-9 or A-F\");\n\t\t}\n\t}\n\treturn ret;\n}\n\nstring byte2hex(int c) {\n\tstring ret = \"\";\n\tif ( c < 0 || c >= 256 ) {\n\t\tfatal(\"Illegal value for byte\");\n\t}\n\tret += (c\/16 < 10)?('0'+c\/16):('A'+c\/16-10);\n\tret += (c%16 < 10)?('0'+c%16):('A'+c%16-10);\n\treturn ret;\n}\n\nstring int2hex(int c, int bytes) {\n\tif ( c < 0 ) {\n\t\treturn int2hex(c&0x7FFFFFFF,bytes);\n\t}\n\tif ( bytes <= 0 ) {\n\t\treturn \"\";\n\t}\n\treturn int2hex(c\/256,bytes-1)+byte2hex(c%256);\n}\n\nstd::string int2str(int c) {\n\tchar ret[20];\n\tsprintf(ret,\"%d\",c);\n\treturn ret;\n}\n<|endoftext|>"} {"text":"\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"Transient.h\"\n\n\/\/Moose includes\n#include \"Kernel.h\"\n#include \"Factory.h\"\n#include \"SubProblem.h\"\n#include \"ProblemFactory.h\"\n#include \"TimePeriod.h\"\n#include \"TimeScheme.h\"\n\/\/libMesh includes\n#include \"implicit_system.h\"\n#include \"nonlinear_implicit_system.h\"\n#include \"transient_system.h\"\n#include \"numeric_vector.h\"\n#include \"o_string_stream.h\"\n\n\/\/ C++ Includes\n#include \n#include \n#include \n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n std::vector sync_times(1);\n sync_times[0] = -1;\n\n params.addParam(\"start_time\", 0.0, \"The start time of the simulation\");\n params.addParam(\"end_time\", 1.0e30, \"The end time of the simulation\");\n params.addRequiredParam(\"dt\", \"The timestep size between solves\");\n params.addParam(\"dtmin\", 0.0, \"The minimum timestep size in an adaptive run\");\n params.addParam(\"dtmax\", 1.0e30, \"The maximum timestep size in an adaptive run\");\n params.addParam(\"num_steps\", std::numeric_limits::max(), \"The number of timesteps in a transient run\");\n params.addParam (\"n_startup_steps\", 0, \"The number of timesteps during startup\");\n params.addParam(\"trans_ss_check\", false, \"Whether or not to check for steady state conditions\");\n params.addParam(\"ss_check_tol\", 1.0e-08,\"Whenever the relative residual changes by less than this the solution will be considered to be at steady state.\");\n params.addParam(\"ss_tmin\", 0.0, \"Minimum number of timesteps to take before checking for steady state conditions.\");\n params.addParam >(\"sync_times\", sync_times, \"A list of times that will be solved for provided they are within the simulation time\");\n params.addParam >(\"time_t\", \"The values of t\");\n params.addParam >(\"time_dt\", \"The values of dt\");\n params.addParam(\"growth_factor\", 2, \"Maximum ratio of new to previous timestep sizes following a step that required the time step to be cut due to a failed solve. For use with 'time_t' and 'time_dt'.\");\n params.addParam(\"predictor_scale\", \"The scale factor for the predictor (can range from 0 to 1)\");\n\n params.addParam >(\"time_periods\", \"The names of periods\");\n params.addParam >(\"time_period_starts\", \"The start times of time periods\");\n params.addParam >(\"time_period_ends\", \"The end times of time periods\");\n params.addParam(\"use_AB2\", false, \"Whether to use the Adams-Bashforth 2 predictor\");\n params.addParam(\"use_littlef\", false, \"if a function evaluation should be used or time deriv's in predictors\");\n params.addParam(\"abort_on_solve_fail\", false, \"abort if solve not converged rather than cut timestep\");\n return params;\n}\n\nTransient::Transient(const std::string & name, InputParameters parameters) :\n Executioner(name, parameters),\n _problem(*ProblemFactory::instance()->createFEProblem(_mesh)),\n _t_step(_problem.timeStep()),\n _time(_problem.time()),\n _time_old(_problem.timeOld()),\n _input_dt(getParam(\"dt\")),\n _dt(_problem.dt()),\n _dt_old(_problem.dtOld()),\n _prev_dt(-1),\n _reset_dt(false),\n _end_time(getParam(\"end_time\")),\n _dtmin(getParam(\"dtmin\")),\n _dtmax(getParam(\"dtmax\")),\n _num_steps(getParam(\"num_steps\")),\n _n_startup_steps(getParam(\"n_startup_steps\")),\n _trans_ss_check(getParam(\"trans_ss_check\")),\n _ss_check_tol(getParam(\"ss_check_tol\")),\n _ss_tmin(getParam(\"ss_tmin\")),\n _old_time_solution_norm(0.0),\n _converged(true),\n _sync_times(getParam >(\"sync_times\")),\n _remaining_sync_time(true),\n _time_ipol(getParam >(\"time_t\"),\n getParam >(\"time_dt\")),\n _use_time_ipol(_time_ipol.getSampleSize() > 0),\n _growth_factor(getParam(\"growth_factor\")),\n _cutback_occurred(false),\n _abort(getParam(\"abort_on_solve_fail\"))\n{\n _t_step = 0;\n _dt = 0;\n _time = _time_old = getParam(\"start_time\");\n _problem.transient(true);\n if (parameters.isParamValid(\"predictor_scale\"))\n {\n Real predscale(getParam(\"predictor_scale\"));\n if (predscale >= 0.0 and predscale <= 1.0)\n {\n _problem.getNonlinearSystem().setPredictorScale(getParam(\"predictor_scale\"));\n }\n else\n {\n mooseError(\"Input value for predictor_scale = \"<< predscale << \", outside of permissible range (0 to 1)\");\n }\n }\n\n _problem.getTimeScheme()->_use_AB2 = getParam(\"use_AB2\");\n _problem.getTimeScheme()->_use_littlef = getParam(\"use_littlef\");\n if (!_restart_file_base.empty())\n _problem.setRestartFile(_restart_file_base);\n}\n\nTransient::~Transient()\n{\n \/\/ This problem was built by the Factory and needs to be released by this destructor\n delete &_problem;\n}\n\nvoid\nTransient::execute()\n{\n _problem.initialSetup();\n\n preExecute();\n\n \/\/ Start time loop...\n while(keepGoing())\n {\n takeStep();\n if (lastSolveConverged())\n endStep();\n }\n postExecute();\n}\n\nvoid\nTransient::takeStep(Real input_dt)\n{\n if (_converged)\n _problem.copyOldSolutions();\n else\n _problem.restoreSolutions();\n\n _dt_old = _dt;\n if (input_dt == -1.0)\n _dt = computeConstrainedDT();\n else\n _dt = input_dt;\n\n _problem.onTimestepBegin();\n if (_converged)\n {\n \/\/ Update backward material data structures\n _problem.updateMaterials();\n }\n\n \/\/ Increment time\n _time = _time_old + _dt;\n\n std::cout<<\"DT: \"<<_dt< 1)\n\/\/ _dt = _input_dt\/(double)(_n_startup_steps);\n\/\/ else if (_t_step == 1+_n_startup_steps && _n_startup_steps > 1)\n\/\/ _dt = _input_dt;\n\n Real dt_cur = _dt;\n \/\/After startup steps, compute new dt\n if (_t_step > _n_startup_steps)\n dt_cur = computeDT();\n\n \/\/ Don't let the time step size exceed maximum time step size\n if (dt_cur > _dtmax)\n dt_cur = _dtmax;\n\n \/\/ Don't allow time step size to be smaller than minimum time step size\n if (dt_cur < _dtmin)\n dt_cur = _dtmin;\n\n \/\/ Don't let time go beyond simulation end time\n if (_time + dt_cur > _end_time)\n dt_cur = _end_time - _time;\n\n \/\/ Adjust to a sync time if supplied and skipped over\n if (_remaining_sync_time && _time + dt_cur >= *_curr_sync_time_iter)\n {\n dt_cur = *_curr_sync_time_iter - _time;\n if (++_curr_sync_time_iter == _sync_times.end())\n _remaining_sync_time = false;\n\n _prev_dt = _dt;\n\n _reset_dt = true;\n }\n else\n {\n if (_reset_dt)\n {\n if (_use_time_ipol)\n dt_cur = _time_ipol.sample(_time);\n else\n dt_cur = _prev_dt;\n _reset_dt = false;\n }\n }\n\n return dt_cur;\n\n}\n\nReal\nTransient::computeDT()\n{\n if (!lastSolveConverged())\n {\n _cutback_occurred = true;\n \/\/std::cout<<\"Solve failed... cutting timestep\"<= _dtmin)\n return 0.5 * _dt;\n\n else \/\/ (0.5 * _dt < _dtmin)\n return _dtmin;\n }\n\n Real dt = _dt;\n if (_use_time_ipol)\n {\n dt = _time_ipol.sample(_time);\n if (_cutback_occurred &&\n dt > _dt * _growth_factor)\n {\n dt = _dt * _growth_factor;\n }\n }\n\n _cutback_occurred = false;\n return dt;\n}\n\nbool\nTransient::keepGoing()\n{\n \/\/ Check for stop condition based upon steady-state check flag:\n if(_converged && _trans_ss_check == true && _time > _ss_tmin)\n {\n \/\/ Compute new time solution l2_norm\n Real new_time_solution_norm = _problem.getNonlinearSystem().currentSolution()->l2_norm();\n\n \/\/ Compute l2_norm relative error\n Real ss_relerr_norm = fabs(new_time_solution_norm - _old_time_solution_norm)\/new_time_solution_norm;\n\n \/\/ Check current solution relative error norm against steady-state tolerance\n if(ss_relerr_norm < _ss_check_tol)\n {\n std::cout<<\"Steady-State Solution Achieved at time: \"<<_time<_num_steps)\n return false;\n\n if((_time>_end_time) || (fabs(_time-_end_time)<1.e-14))\n return false;\n\n return true;\n}\n\n\nbool\nTransient::lastSolveConverged()\n{\n return _converged;\n}\n\nvoid\nTransient::preExecute()\n{\n \/\/ process time periods\n const std::vector _time_periods = _problem.getTimePeriods();\n for (unsigned int i = 0; i < _time_periods.size(); ++i)\n _sync_times.push_back(_time_periods[i]->start());\n\n const std::vector & time = getParam >(\"time_t\");\n if (_use_time_ipol)\n _sync_times.insert(_sync_times.end(), time.begin()+1, time.end()); \/\/ insert times as sync points except the very first one\n sort(_sync_times.begin(), _sync_times.end());\n _sync_times.erase(std::unique(_sync_times.begin(), _sync_times.end()), _sync_times.end()); \/\/ remove duplicates (needs sorted array)\n\n \/\/ Advance to the first sync time if one is provided in sim time range\n _curr_sync_time_iter = _sync_times.begin();\n while (_remaining_sync_time && *_curr_sync_time_iter <= _time)\n if (++_curr_sync_time_iter == _sync_times.end())\n _remaining_sync_time = false;\n}\nSolutions are copied\/restored in endStep() not at the beginning of the time step (closes #1373)\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"Transient.h\"\n\n\/\/Moose includes\n#include \"Kernel.h\"\n#include \"Factory.h\"\n#include \"SubProblem.h\"\n#include \"ProblemFactory.h\"\n#include \"TimePeriod.h\"\n#include \"TimeScheme.h\"\n\/\/libMesh includes\n#include \"implicit_system.h\"\n#include \"nonlinear_implicit_system.h\"\n#include \"transient_system.h\"\n#include \"numeric_vector.h\"\n#include \"o_string_stream.h\"\n\n\/\/ C++ Includes\n#include \n#include \n#include \n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n std::vector sync_times(1);\n sync_times[0] = -1;\n\n params.addParam(\"start_time\", 0.0, \"The start time of the simulation\");\n params.addParam(\"end_time\", 1.0e30, \"The end time of the simulation\");\n params.addRequiredParam(\"dt\", \"The timestep size between solves\");\n params.addParam(\"dtmin\", 0.0, \"The minimum timestep size in an adaptive run\");\n params.addParam(\"dtmax\", 1.0e30, \"The maximum timestep size in an adaptive run\");\n params.addParam(\"num_steps\", std::numeric_limits::max(), \"The number of timesteps in a transient run\");\n params.addParam (\"n_startup_steps\", 0, \"The number of timesteps during startup\");\n params.addParam(\"trans_ss_check\", false, \"Whether or not to check for steady state conditions\");\n params.addParam(\"ss_check_tol\", 1.0e-08,\"Whenever the relative residual changes by less than this the solution will be considered to be at steady state.\");\n params.addParam(\"ss_tmin\", 0.0, \"Minimum number of timesteps to take before checking for steady state conditions.\");\n params.addParam >(\"sync_times\", sync_times, \"A list of times that will be solved for provided they are within the simulation time\");\n params.addParam >(\"time_t\", \"The values of t\");\n params.addParam >(\"time_dt\", \"The values of dt\");\n params.addParam(\"growth_factor\", 2, \"Maximum ratio of new to previous timestep sizes following a step that required the time step to be cut due to a failed solve. For use with 'time_t' and 'time_dt'.\");\n params.addParam(\"predictor_scale\", \"The scale factor for the predictor (can range from 0 to 1)\");\n\n params.addParam >(\"time_periods\", \"The names of periods\");\n params.addParam >(\"time_period_starts\", \"The start times of time periods\");\n params.addParam >(\"time_period_ends\", \"The end times of time periods\");\n params.addParam(\"use_AB2\", false, \"Whether to use the Adams-Bashforth 2 predictor\");\n params.addParam(\"use_littlef\", false, \"if a function evaluation should be used or time deriv's in predictors\");\n params.addParam(\"abort_on_solve_fail\", false, \"abort if solve not converged rather than cut timestep\");\n return params;\n}\n\nTransient::Transient(const std::string & name, InputParameters parameters) :\n Executioner(name, parameters),\n _problem(*ProblemFactory::instance()->createFEProblem(_mesh)),\n _t_step(_problem.timeStep()),\n _time(_problem.time()),\n _time_old(_problem.timeOld()),\n _input_dt(getParam(\"dt\")),\n _dt(_problem.dt()),\n _dt_old(_problem.dtOld()),\n _prev_dt(-1),\n _reset_dt(false),\n _end_time(getParam(\"end_time\")),\n _dtmin(getParam(\"dtmin\")),\n _dtmax(getParam(\"dtmax\")),\n _num_steps(getParam(\"num_steps\")),\n _n_startup_steps(getParam(\"n_startup_steps\")),\n _trans_ss_check(getParam(\"trans_ss_check\")),\n _ss_check_tol(getParam(\"ss_check_tol\")),\n _ss_tmin(getParam(\"ss_tmin\")),\n _old_time_solution_norm(0.0),\n _converged(true),\n _sync_times(getParam >(\"sync_times\")),\n _remaining_sync_time(true),\n _time_ipol(getParam >(\"time_t\"),\n getParam >(\"time_dt\")),\n _use_time_ipol(_time_ipol.getSampleSize() > 0),\n _growth_factor(getParam(\"growth_factor\")),\n _cutback_occurred(false),\n _abort(getParam(\"abort_on_solve_fail\"))\n{\n _t_step = 0;\n _dt = 0;\n _time = _time_old = getParam(\"start_time\");\n _problem.transient(true);\n if (parameters.isParamValid(\"predictor_scale\"))\n {\n Real predscale(getParam(\"predictor_scale\"));\n if (predscale >= 0.0 and predscale <= 1.0)\n {\n _problem.getNonlinearSystem().setPredictorScale(getParam(\"predictor_scale\"));\n }\n else\n {\n mooseError(\"Input value for predictor_scale = \"<< predscale << \", outside of permissible range (0 to 1)\");\n }\n }\n\n _problem.getTimeScheme()->_use_AB2 = getParam(\"use_AB2\");\n _problem.getTimeScheme()->_use_littlef = getParam(\"use_littlef\");\n if (!_restart_file_base.empty())\n _problem.setRestartFile(_restart_file_base);\n}\n\nTransient::~Transient()\n{\n \/\/ This problem was built by the Factory and needs to be released by this destructor\n delete &_problem;\n}\n\nvoid\nTransient::execute()\n{\n _problem.initialSetup();\n\n preExecute();\n\n \/\/ NOTE: if you remove this line, you will see a subset of tests failing. Those tests might have a wrong answer and might need to be regolded.\n \/\/ The reason is that we actually move the solution back in time before we actually start solving (which I think is wrong). So this call here\n \/\/ is to maintain backward compatibility and so that MOOSE is giving the same answer. However, we might remove this call and regold the test\n \/\/ in the future eventually.\n _problem.copyOldSolutions();\n\n \/\/ Start time loop...\n while(keepGoing())\n {\n takeStep();\n endStep();\n }\n postExecute();\n}\n\nvoid\nTransient::takeStep(Real input_dt)\n{\n _dt_old = _dt;\n if (input_dt == -1.0)\n _dt = computeConstrainedDT();\n else\n _dt = input_dt;\n\n _problem.onTimestepBegin();\n if (_converged)\n {\n \/\/ Update backward material data structures\n _problem.updateMaterials();\n }\n\n \/\/ Increment time\n _time = _time_old + _dt;\n\n std::cout<<\"DT: \"<<_dt< 1)\n\/\/ _dt = _input_dt\/(double)(_n_startup_steps);\n\/\/ else if (_t_step == 1+_n_startup_steps && _n_startup_steps > 1)\n\/\/ _dt = _input_dt;\n\n Real dt_cur = _dt;\n \/\/After startup steps, compute new dt\n if (_t_step > _n_startup_steps)\n dt_cur = computeDT();\n\n \/\/ Don't let the time step size exceed maximum time step size\n if (dt_cur > _dtmax)\n dt_cur = _dtmax;\n\n \/\/ Don't allow time step size to be smaller than minimum time step size\n if (dt_cur < _dtmin)\n dt_cur = _dtmin;\n\n \/\/ Don't let time go beyond simulation end time\n if (_time + dt_cur > _end_time)\n dt_cur = _end_time - _time;\n\n \/\/ Adjust to a sync time if supplied and skipped over\n if (_remaining_sync_time && _time + dt_cur >= *_curr_sync_time_iter)\n {\n dt_cur = *_curr_sync_time_iter - _time;\n if (++_curr_sync_time_iter == _sync_times.end())\n _remaining_sync_time = false;\n\n _prev_dt = _dt;\n\n _reset_dt = true;\n }\n else\n {\n if (_reset_dt)\n {\n if (_use_time_ipol)\n dt_cur = _time_ipol.sample(_time);\n else\n dt_cur = _prev_dt;\n _reset_dt = false;\n }\n }\n\n return dt_cur;\n\n}\n\nReal\nTransient::computeDT()\n{\n if (!lastSolveConverged())\n {\n _cutback_occurred = true;\n \/\/std::cout<<\"Solve failed... cutting timestep\"<= _dtmin)\n return 0.5 * _dt;\n\n else \/\/ (0.5 * _dt < _dtmin)\n return _dtmin;\n }\n\n Real dt = _dt;\n if (_use_time_ipol)\n {\n dt = _time_ipol.sample(_time);\n if (_cutback_occurred &&\n dt > _dt * _growth_factor)\n {\n dt = _dt * _growth_factor;\n }\n }\n\n _cutback_occurred = false;\n return dt;\n}\n\nbool\nTransient::keepGoing()\n{\n \/\/ Check for stop condition based upon steady-state check flag:\n if(_converged && _trans_ss_check == true && _time > _ss_tmin)\n {\n \/\/ Compute new time solution l2_norm\n Real new_time_solution_norm = _problem.getNonlinearSystem().currentSolution()->l2_norm();\n\n \/\/ Compute l2_norm relative error\n Real ss_relerr_norm = fabs(new_time_solution_norm - _old_time_solution_norm)\/new_time_solution_norm;\n\n \/\/ Check current solution relative error norm against steady-state tolerance\n if(ss_relerr_norm < _ss_check_tol)\n {\n std::cout<<\"Steady-State Solution Achieved at time: \"<<_time<_num_steps)\n return false;\n\n if((_time>_end_time) || (fabs(_time-_end_time)<1.e-14))\n return false;\n\n return true;\n}\n\n\nbool\nTransient::lastSolveConverged()\n{\n return _converged;\n}\n\nvoid\nTransient::preExecute()\n{\n \/\/ process time periods\n const std::vector _time_periods = _problem.getTimePeriods();\n for (unsigned int i = 0; i < _time_periods.size(); ++i)\n _sync_times.push_back(_time_periods[i]->start());\n\n const std::vector & time = getParam >(\"time_t\");\n if (_use_time_ipol)\n _sync_times.insert(_sync_times.end(), time.begin()+1, time.end()); \/\/ insert times as sync points except the very first one\n sort(_sync_times.begin(), _sync_times.end());\n _sync_times.erase(std::unique(_sync_times.begin(), _sync_times.end()), _sync_times.end()); \/\/ remove duplicates (needs sorted array)\n\n \/\/ Advance to the first sync time if one is provided in sim time range\n _curr_sync_time_iter = _sync_times.begin();\n while (_remaining_sync_time && *_curr_sync_time_iter <= _time)\n if (++_curr_sync_time_iter == _sync_times.end())\n _remaining_sync_time = false;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#if VENTURA_HAS_ABSOLUTE_PATH_OPERATIONS\n\n#ifdef _WIN32\n#define SILICIUM_TEST_ROOT L\"C:\/\"\n#else\n#define SILICIUM_TEST_ROOT \"\/\"\n#endif\n\nnamespace\n{\n\tventura::absolute_path const absolute_root = *ventura::absolute_path::create(SILICIUM_TEST_ROOT);\n}\n\nBOOST_AUTO_TEST_CASE(get_current_executable_path)\n{\n\tSi::error_or const p = ventura::get_current_executable_path();\n\tBOOST_REQUIRE(!p.is_error());\n\tauto const expected = \"unit_test\"\n#ifdef _WIN32\n\t \".exe\"\n#endif\n\t ;\n\tBOOST_CHECK_EQUAL(expected, p.get().to_boost_path().leaf());\n}\n\nBOOST_AUTO_TEST_CASE(get_current_executable_path_throw)\n{\n\tventura::absolute_path p = ventura::get_current_executable_path(Si::throw_);\n\tauto const expected = \"unit_test\"\n#ifdef _WIN32\n\t \".exe\"\n#endif\n\t ;\n\tBOOST_CHECK_EQUAL(expected, p.to_boost_path().leaf());\n}\n\nBOOST_AUTO_TEST_CASE(get_current_executable_path_variant)\n{\n\tSi::error_or const p = ventura::get_current_executable_path(Si::variant_);\n\tBOOST_REQUIRE(!p.is_error());\n\tauto const expected = \"unit_test\"\n#ifdef _WIN32\n\t \".exe\"\n#endif\n\t ;\n\tBOOST_CHECK_EQUAL(expected, p.get().to_boost_path().leaf());\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_true)\n{\n\tSi::error_or const exists = ventura::file_exists(absolute_root);\n\tBOOST_CHECK(exists.get());\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_true_throw)\n{\n\tbool exists = ventura::file_exists(absolute_root, Si::throw_);\n\tBOOST_CHECK(exists);\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_true_variant)\n{\n\tSi::error_or const exists = ventura::file_exists(absolute_root, Si::variant_);\n\tBOOST_CHECK(exists.get());\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_false)\n{\n\tSi::error_or const exists =\n\t ventura::file_exists(absolute_root \/ *ventura::path_segment::create(\"does-not-exist\"));\n\tBOOST_CHECK(!exists.get());\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_false_throw)\n{\n\tbool exists = ventura::file_exists(absolute_root \/ *ventura::path_segment::create(\"does-not-exist\"), Si::throw_);\n\tBOOST_CHECK(!exists);\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_false_variant)\n{\n\tSi::error_or const exists =\n\t ventura::file_exists(absolute_root \/ *ventura::path_segment::create(\"does-not-exist\"), Si::variant_);\n\tBOOST_CHECK(!exists.get());\n}\n\nBOOST_AUTO_TEST_CASE(test_rename)\n{\n\tventura::absolute_path const from = ventura::temporary_directory().get() \/ ventura::unique_path();\n\tventura::create_file(from).move_value();\n\tventura::absolute_path const to = ventura::temporary_directory().get() \/ ventura::unique_path();\n\tBOOST_CHECK(!ventura::file_exists(to).get());\n\tboost::system::error_code const error = ventura::rename(from, to);\n\tBOOST_CHECK(ventura::file_exists(to).get());\n\tBOOST_CHECK(!error);\n}\n\nBOOST_AUTO_TEST_CASE(test_temporary_directory)\n{\n\tSi::error_or const p = ventura::temporary_directory();\n\tBOOST_REQUIRE(!p.is_error());\n\tBOOST_CHECK(!p.get().empty());\n}\n\nBOOST_AUTO_TEST_CASE(test_temporary_directory_throw)\n{\n\tventura::absolute_path const p = ventura::temporary_directory(Si::throw_);\n\tBOOST_CHECK(!p.empty());\n}\n\nBOOST_AUTO_TEST_CASE(test_temporary_directory_variant)\n{\n\tSi::error_or const p = ventura::temporary_directory(Si::variant_);\n\tBOOST_REQUIRE(!p.is_error());\n\tBOOST_CHECK(!p.get().empty());\n}\n\nBOOST_AUTO_TEST_CASE(test_get_home)\n{\n\tventura::absolute_path const home = ventura::get_home();\n#ifdef _WIN32\n\tBOOST_CHECK(boost::algorithm::starts_with(to_os_string(home), \"C:\/Users\/\"));\n\tBOOST_CHECK(boost::algorithm::ends_with(to_os_string(home), \"\/AppData\/Local\"));\n#elif defined(__linux__)\n\tBOOST_CHECK(boost::algorithm::starts_with(ventura::to_os_string(home), \"\/home\/\"));\n#else\n\t\/\/ OSX\n\tBOOST_CHECK(boost::algorithm::starts_with(to_os_string(home), \"\/Users\/\"));\n#endif\n}\n\nBOOST_AUTO_TEST_CASE(test_copy_recursively)\n{\n\tventura::absolute_path const temp =\n\t ventura::temporary_directory(Si::throw_) \/ ventura::relative_path(\"silicium-test_copy_recursively\");\n\tventura::recreate_directories(temp, Si::throw_);\n\tventura::absolute_path const from = temp \/ ventura::relative_path(\"from\");\n\tventura::absolute_path const to = temp \/ ventura::relative_path(\"to\");\n\tventura::create_directories(from, Si::throw_);\n\tauto const expected = Si::make_c_str_range(\"Hello\");\n\tSi::throw_if_error(ventura::write_file(\n\t Si::native_path_string(to_os_string(from \/ ventura::relative_path(\"file.txt\")).c_str()), expected));\n\tventura::copy_recursively(from, to, nullptr, Si::throw_);\n\tstd::ifstream file((to \/ ventura::relative_path(\"file.txt\")).c_str(), std::ios::binary);\n\tBOOST_REQUIRE(file);\n\tstd::vector const file_content((std::istreambuf_iterator(file)), std::istreambuf_iterator());\n\tBOOST_CHECK_EQUAL_COLLECTIONS(file_content.begin(), file_content.end(), expected.begin(), expected.end());\n}\n#endif\nmore tests for copy_recursively#include \n#include \n#include \n#include \n#include \n\n#if VENTURA_HAS_ABSOLUTE_PATH_OPERATIONS\n\n#ifdef _WIN32\n#define SILICIUM_TEST_ROOT L\"C:\/\"\n#else\n#define SILICIUM_TEST_ROOT \"\/\"\n#endif\n\nnamespace\n{\n\tventura::absolute_path const absolute_root = *ventura::absolute_path::create(SILICIUM_TEST_ROOT);\n}\n\nBOOST_AUTO_TEST_CASE(get_current_executable_path)\n{\n\tSi::error_or const p = ventura::get_current_executable_path();\n\tBOOST_REQUIRE(!p.is_error());\n\tauto const expected = \"unit_test\"\n#ifdef _WIN32\n\t \".exe\"\n#endif\n\t ;\n\tBOOST_CHECK_EQUAL(expected, p.get().to_boost_path().leaf());\n}\n\nBOOST_AUTO_TEST_CASE(get_current_executable_path_throw)\n{\n\tventura::absolute_path p = ventura::get_current_executable_path(Si::throw_);\n\tauto const expected = \"unit_test\"\n#ifdef _WIN32\n\t \".exe\"\n#endif\n\t ;\n\tBOOST_CHECK_EQUAL(expected, p.to_boost_path().leaf());\n}\n\nBOOST_AUTO_TEST_CASE(get_current_executable_path_variant)\n{\n\tSi::error_or const p = ventura::get_current_executable_path(Si::variant_);\n\tBOOST_REQUIRE(!p.is_error());\n\tauto const expected = \"unit_test\"\n#ifdef _WIN32\n\t \".exe\"\n#endif\n\t ;\n\tBOOST_CHECK_EQUAL(expected, p.get().to_boost_path().leaf());\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_true)\n{\n\tSi::error_or const exists = ventura::file_exists(absolute_root);\n\tBOOST_CHECK(exists.get());\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_true_throw)\n{\n\tbool exists = ventura::file_exists(absolute_root, Si::throw_);\n\tBOOST_CHECK(exists);\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_true_variant)\n{\n\tSi::error_or const exists = ventura::file_exists(absolute_root, Si::variant_);\n\tBOOST_CHECK(exists.get());\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_false)\n{\n\tSi::error_or const exists =\n\t ventura::file_exists(absolute_root \/ *ventura::path_segment::create(\"does-not-exist\"));\n\tBOOST_CHECK(!exists.get());\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_false_throw)\n{\n\tbool exists = ventura::file_exists(absolute_root \/ *ventura::path_segment::create(\"does-not-exist\"), Si::throw_);\n\tBOOST_CHECK(!exists);\n}\n\nBOOST_AUTO_TEST_CASE(test_file_exists_false_variant)\n{\n\tSi::error_or const exists =\n\t ventura::file_exists(absolute_root \/ *ventura::path_segment::create(\"does-not-exist\"), Si::variant_);\n\tBOOST_CHECK(!exists.get());\n}\n\nBOOST_AUTO_TEST_CASE(test_rename)\n{\n\tventura::absolute_path const from = ventura::temporary_directory().get() \/ ventura::unique_path();\n\tventura::create_file(from).move_value();\n\tventura::absolute_path const to = ventura::temporary_directory().get() \/ ventura::unique_path();\n\tBOOST_CHECK(!ventura::file_exists(to).get());\n\tboost::system::error_code const error = ventura::rename(from, to);\n\tBOOST_CHECK(ventura::file_exists(to).get());\n\tBOOST_CHECK(!error);\n}\n\nBOOST_AUTO_TEST_CASE(test_temporary_directory)\n{\n\tSi::error_or const p = ventura::temporary_directory();\n\tBOOST_REQUIRE(!p.is_error());\n\tBOOST_CHECK(!p.get().empty());\n}\n\nBOOST_AUTO_TEST_CASE(test_temporary_directory_throw)\n{\n\tventura::absolute_path const p = ventura::temporary_directory(Si::throw_);\n\tBOOST_CHECK(!p.empty());\n}\n\nBOOST_AUTO_TEST_CASE(test_temporary_directory_variant)\n{\n\tSi::error_or const p = ventura::temporary_directory(Si::variant_);\n\tBOOST_REQUIRE(!p.is_error());\n\tBOOST_CHECK(!p.get().empty());\n}\n\nBOOST_AUTO_TEST_CASE(test_get_home)\n{\n\tventura::absolute_path const home = ventura::get_home();\n#ifdef _WIN32\n\tBOOST_CHECK(boost::algorithm::starts_with(to_os_string(home), \"C:\/Users\/\"));\n\tBOOST_CHECK(boost::algorithm::ends_with(to_os_string(home), \"\/AppData\/Local\"));\n#elif defined(__linux__)\n\tBOOST_CHECK(boost::algorithm::starts_with(ventura::to_os_string(home), \"\/home\/\"));\n#else\n\t\/\/ OSX\n\tBOOST_CHECK(boost::algorithm::starts_with(to_os_string(home), \"\/Users\/\"));\n#endif\n}\n\nBOOST_AUTO_TEST_CASE(test_copy_recursively_exists)\n{\n\tventura::absolute_path const temp =\n\t ventura::temporary_directory(Si::throw_) \/ ventura::relative_path(\"silicium-test_copy_recursively\");\n\tventura::recreate_directories(temp, Si::throw_);\n\tventura::absolute_path const from = temp \/ ventura::relative_path(\"from\");\n\tventura::absolute_path const to = temp \/ ventura::relative_path(\"to\");\n\tventura::create_directories(from, Si::throw_);\n\tauto const expected = Si::make_c_str_range(\"Hello\");\n\tSi::throw_if_error(ventura::write_file(\n\t Si::native_path_string(to_os_string(from \/ ventura::relative_path(\"file.txt\")).c_str()), expected));\n\tventura::create_directories(to, Si::throw_);\n\tventura::copy_recursively(from, to, nullptr, Si::throw_);\n\tBOOST_REQUIRE(ventura::file_exists(to).get());\n\tstd::ifstream file((to \/ ventura::relative_path(\"file.txt\")).c_str(), std::ios::binary);\n\tBOOST_REQUIRE(file);\n\tstd::vector const file_content((std::istreambuf_iterator(file)), std::istreambuf_iterator());\n\tBOOST_CHECK_EQUAL_COLLECTIONS(file_content.begin(), file_content.end(), expected.begin(), expected.end());\n}\n\nBOOST_AUTO_TEST_CASE(test_copy_recursively_does_not_exist)\n{\n\tventura::absolute_path const temp =\n\t\tventura::temporary_directory(Si::throw_) \/ ventura::relative_path(\"silicium-test_copy_recursively\");\n\tventura::recreate_directories(temp, Si::throw_);\n\tventura::absolute_path const from = temp \/ ventura::relative_path(\"from\");\n\tventura::absolute_path const to = temp \/ ventura::relative_path(\"to\");\n\tventura::create_directories(from, Si::throw_);\n\tauto const expected = Si::make_c_str_range(\"Hello\");\n\tSi::throw_if_error(ventura::write_file(\n\t\tSi::native_path_string(to_os_string(from \/ ventura::relative_path(\"file.txt\")).c_str()), expected));\n\tBOOST_REQUIRE(!ventura::file_exists(to).get());\n\tventura::copy_recursively(from, to, nullptr, Si::throw_);\n\tBOOST_REQUIRE(ventura::file_exists(to).get());\n\tstd::ifstream file((to \/ ventura::relative_path(\"file.txt\")).c_str(), std::ios::binary);\n\tBOOST_REQUIRE(file);\n\tstd::vector const file_content((std::istreambuf_iterator(file)), std::istreambuf_iterator());\n\tBOOST_CHECK_EQUAL_COLLECTIONS(file_content.begin(), file_content.end(), expected.begin(), expected.end());\n}\n\nBOOST_AUTO_TEST_CASE(test_copy_recursively_parent_does_not_exist)\n{\n\tventura::absolute_path const temp =\n\t\tventura::temporary_directory(Si::throw_) \/ ventura::relative_path(\"silicium-test_copy_recursively\");\n\tventura::recreate_directories(temp, Si::throw_);\n\tventura::absolute_path const from = temp \/ ventura::relative_path(\"from\");\n\tventura::absolute_path const to = temp \/ ventura::relative_path(\"parent\/to\");\n\tventura::create_directories(from, Si::throw_);\n\tauto const expected = Si::make_c_str_range(\"Hello\");\n\tSi::throw_if_error(ventura::write_file(\n\t\tSi::native_path_string(to_os_string(from \/ ventura::relative_path(\"file.txt\")).c_str()), expected));\n\tBOOST_REQUIRE(!ventura::file_exists(to).get());\n\tventura::copy_recursively(from, to, nullptr, Si::throw_);\n\tBOOST_REQUIRE(ventura::file_exists(to).get());\n\tstd::ifstream file((to \/ ventura::relative_path(\"file.txt\")).c_str(), std::ios::binary);\n\tBOOST_REQUIRE(file);\n\tstd::vector const file_content((std::istreambuf_iterator(file)), std::istreambuf_iterator());\n\tBOOST_CHECK_EQUAL_COLLECTIONS(file_content.begin(), file_content.end(), expected.begin(), expected.end());\n}\n#endif\n<|endoftext|>"} {"text":"\/\/******************************************************************************************\n\/\/ File: EX_RGB_NeoPixelBus.h\n\/\/ Authors: Allan (vseven) based on EX_Switch_Dim by Dan G Ogorchock\n\/\/\n\/\/ Summary: EX_RGB_NeoPixelBus is a class which implements the SmartThings \"Color Control\", \"Switch\", and \"Switch Level\" device capabilities.\n\/\/\t\t\t It inherits from the st::Executor class.\n\/\/\n\/\/\t\t\t Create an instance of this class in your sketch's global variable section\n\/\/\t\t\t For Example: st::EX_RGB_NeoPixelBus executor1(\"rgbSwitch1\", PIN_RGB, PIXEL_COUNT);\n\/\/\n\/\/\t\t\t st::EX_RGB_NeoPixelBus() constructor requires the following arguments\n\/\/\t\t\t\t- String &name - REQUIRED - the name of the object - must match the Groovy ST_Anything DeviceType tile name.\n\/\/\t\t\t\t- byte pin - REQUIRED - the Arduino Pin to be used as a digital output for the RGB strip\n\/\/\t\t\t\t- byte count - REQUIRED - the number of programmable pixels in the RGB strip\n\/\/\n\/\/ Change History:\n\/\/\n\/\/ Date Who What\n\/\/ ---- --- ----\n\/\/ 2016-04-30 Dan Ogorchock Original Creation\n\/\/ 2018-08-14 Dan Ogorchock Modified to avoid compiler errors on ESP32 since it currently does not support \"analogWrite()\"\n\/\/ 2017-08-30 Dan Ogorchock Modified comment section above to comply with new Parent\/Child Device Handler requirements\n\/\/ 2017-10-06 Allan (vseven) Modified original code from EX_Switch_Dim to be used for RGB lighting\n\/\/ 2020-08-01 Allan (vseven) Modified the EX_RGB_Dim for use with addressable LED strips using the NeoPixelBus library\n\/\/\n\/\/******************************************************************************************\n#include \"EX_RGB_NeoPixelBus.h\"\n\n#include \"Constants.h\"\n#include \"Everything.h\"\n\n#include \n\nnamespace st\n{\n\n\/\/private\n\tvoid EX_RGB_NeoPixelBus::writeCommandToOutput()\n\t{\n\t\tuint8_t R;\n\t\tuint8_t G;\n\t\tuint8_t B;\n\n\t\tif (st::Executor::debug) {\n\t\t\tSerial.println(\"m_bCurrentState: \" + String(m_bCurrentState));\n\t\t\tSerial.println(\"m_sCurrentHEX: \" + String(m_sCurrentHEX));\n\t\t}\n\n\n\t\tif (m_bCurrentState == HIGH){\n\t\t\t\/\/ Our status is on so get the RGB value from the hex\n\t\t\tString hexstring = m_sCurrentHEX;\n\t\t\tlong number = (long) strtol( &hexstring[1], NULL, 16);\n \t\t\t\/\/ Split them up into r, g, b values\n \t\t\tR = number >> 16;\n \t\t\tG = number >> 8 & 0xFF;\n \t\t\tB = number & 0xFF;\n\t\t} else {\n\t\t\t\/\/ Status is off so turn off LED\n\t\t\tR = 00;\n \t\t\tG = 00;\n \t\t\tB = 00;\n\t\t}\n\t\t\n\t\t\/\/ Any adjustments to the colors can be done here before sending the commands. For example if red is always too bright reduce it:\n\t\t\/\/ R = R * 0.95\n\n\t\t\/\/ Write to our output\n\n\t\tif (st::Executor::debug) {\n\t\t\tSerial.print(F(\"subString R:G:B = \"));\n\t\t\tSerial.println(String(R) + \":\" + String(G) + \":\" + String(B));\n\t\t}\n\n\t\t\/\/ set all pixels to the same color\n\n\t\tRgbColor myColor = RgbColor(R, G, B);\n\n\n\t\tif (st::Executor::debug) {\n\t\t\tSerial.print(F(\"Total number of pixels reported by strip: \"));\n\t\t\tSerial.println(String(m_nStrip.PixelCount()));\n\t\t\t\/\/Serial.print(F(\"Color being sent: \"));\n\t\t\t\/\/Serial.println(String(myColor.r + myColor.g + myColor.b));\n\t\t}\n\n\t\tm_nStrip.ClearTo(myColor);\n\n\t\tif (st::Executor::debug) {\n\t\t\tSerial.println(F(\"All pixels set. Sending show command.\"));\n\t\t}\n\n\t\t\/\/ then display it\n\t\tm_nStrip.Show();\n\t}\n\n\/\/public\n\t\/\/constructor\n\tEX_RGB_NeoPixelBus::EX_RGB_NeoPixelBus(const __FlashStringHelper *name, byte count, byte pin):\n\t\tExecutor(name),\n\t\tm_nStrip(count,pin)\n\t{\n\n\t}\n\n\t\/\/destructor\n\tEX_RGB_NeoPixelBus::~EX_RGB_NeoPixelBus()\n\t{\n\t\n\t}\n\t\n\tvoid EX_RGB_NeoPixelBus::init()\n\t{\n\t\tEverything::sendSmartString(getName() + \" \" + (m_bCurrentState == HIGH ? F(\"on\") : F(\"off\")));\n\t\t\n\t\tif (st::Executor::debug) {\n\t\t\tSerial.println(\"init called. Sending Begin to strip.\");\n\t\t}\n\t\t\/\/ On startup make sure strip is turned off\n \t\tm_nStrip.Begin();\n\t\tm_nStrip.Show();\n\t}\n\n\tvoid EX_RGB_NeoPixelBus::beSmart(const String &str)\n\t{\n\t\tString s=str.substring(str.indexOf(' ')+1);\n\t\tif (st::Executor::debug) {\n\t\t\tSerial.print(F(\"EX_RGB_NeoPixelBus::beSmart s = \"));\n\t\t\tSerial.println(s);\n\t\t}\n\t\tif(s==F(\"on\"))\n\t\t{\n\t\t\tm_bCurrentState=HIGH;\n\t\t}\n\t\telse if(s==F(\"off\"))\n\t\t{\n\t\t\tm_bCurrentState=LOW;\n\t\t}\n\t\telse \/\/must be a set color command\n\t\t{\n\t\t\ts.trim();\n\t\t\tm_sCurrentHEX = s;\n\t\t}\n\n\t\twriteCommandToOutput();\n\n\t\t\/\/Send data to SmartThings\/Hubitat\n\t\tEverything::sendSmartString(getName() + \" \" + (m_bCurrentState == HIGH?F(\"on\"):F(\"off\")));\n\t}\n\t\n\tvoid EX_RGB_NeoPixelBus::refresh()\n\t{\n\t\tEverything::sendSmartString(getName() + \" \" + (m_bCurrentState == HIGH?F(\"on\"):F(\"off\")));\n\t}\n}Delete EX_RGB_NeoPixelBus.cpp<|endoftext|>"} {"text":"\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2016 AliceVision contributors.\n\/\/ Copyright (c) 2012 openMVG contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#pragma once\n\n\/\/#include \"aliceVision\/multiview\/homographyKernelSolver.hpp\"\n\/\/#include \"aliceVision\/robustEstimation\/ACRansac.hpp\"\n\/\/#include \"aliceVision\/robustEstimation\/ACRansacKernelAdaptator.hpp\"\n\/\/#include \"aliceVision\/robustEstimation\/guidedMatching.hpp\"\n\n\/\/#include \"aliceVision\/matching\/IndMatch.hpp\"\n\/\/#include \"aliceVision\/matching\/IndMatchDecorator.hpp\"\n#include \"aliceVision\/sfm\/SfMData.hpp\"\n#include \"aliceVision\/feature\/RegionsPerView.hpp\"\n#include \"aliceVision\/matchingImageCollection\/GeometricFilterMatrix.hpp\"\n\nnamespace aliceVision {\nnamespace matchingImageCollection {\n\n\/\/-- Multiple homography matrices estimation template functor, based on homography growing, used for filter pair of putative correspondences\nstruct GeometricFilterMatrix_HGrowing : public GeometricFilterMatrix\n{\n GeometricFilterMatrix_HGrowing(\n double dPrecision = std::numeric_limits::infinity(),\n size_t iteration = 1024)\n : GeometricFilterMatrix(dPrecision, std::numeric_limits::infinity(), iteration)\n , _maxNbHomographies(10)\n , _minRemainingMatches(20)\n , _similarityTolerance(10)\n , _affinityTolerance(10)\n , _homographyTolerance(5)\n , _minNbPlanarMatches(6)\n , _nbIterations(8)\n , _maxFractionPlanarMatches(0.7)\n {\n _Hs.push_back(Mat3::Identity());\n }\n\/**\n * @brief Given two sets of image points, it estimates the homography matrix\n * relating them using a robust method (like A Contrario Ransac).\n *\/\n template\n EstimationStatus geometricEstimation(\n const sfm::SfMData * sfmData,\n const Regions_or_Features_ProviderT& regionsPerView,\n const Pair pairIndex,\n const matching::MatchesPerDescType & putativeMatchesPerType,\n matching::MatchesPerDescType & out_geometricInliersPerType)\n {\n \n using namespace aliceVision;\n using namespace aliceVision::robustEstimation;\n out_geometricInliersPerType.clear();\n \n \/\/ Get back corresponding view index\n const IndexT iIndex = pairIndex.first;\n const IndexT jIndex = pairIndex.second;\n \n const std::vector descTypes = regionsPerView.getCommonDescTypes(pairIndex);\n if(descTypes.empty())\n return EstimationStatus(false, false);\n \n \/\/ Retrieve all 2D features as undistorted positions into flat arrays\n Mat xI, xJ;\n MatchesPairToMat(pairIndex, putativeMatchesPerType, sfmData, regionsPerView, descTypes, xI, xJ);\n std::cout << \"Pair id. : \" << pairIndex << std::endl;\n std::cout << \"|- xI: \" << xI.rows() << \"x\" << xI.cols() << std::endl;\n std::cout << \"|- xJ: \" << xJ.rows() << \"x\" << xJ.cols() << std::endl;\n std::size_t nbMatches = xI.cols();\n \n \/\/ (?) make a map\n std::vector homographies;\n std::vector> planarMatchesPerH;\n \n for (IndexT iTransform = 0; iTransform < _maxNbHomographies; ++iTransform)\n {\n for (IndexT iMatch = 0; iMatch < nbMatches; ++iMatch)\n {\n \/\/ [TODO] Add 1st improvment\n \n \/\/ Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20) \n std::vector planarMatchesIds;\n Mat3 homographie;\n \n growHomography(xI, xJ, iMatch ,planarMatchesIds, homographie);\n \n if (!planarMatchesIds.empty())\n {\n homographies.push_back(homographie);\n planarMatchesPerH.push_back(planarMatchesIds);\n }\n }\n }\n \n \n \/\/ Check if resection has strong support\n const bool hasStrongSupport = true;\n return EstimationStatus(true, hasStrongSupport);\n }\n \n \/**\n * @brief Geometry_guided_matching\n * @param sfm_data\n * @param regionsPerView\n * @param pairIndex\n * @param dDistanceRatio\n * @param matches\n * @return\n *\/\n bool Geometry_guided_matching\n (\n const sfm::SfMData * sfmData,\n const feature::RegionsPerView & regionsPerView,\n const Pair imageIdsPair,\n const double dDistanceRatio,\n matching::MatchesPerDescType & matches) override\n {\n \n \/* ... *\/\n return matches.getNbAllMatches() != 0;\n }\n\nprivate:\n\n \/\/ Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20) \n \/\/-- See: YASM\/relative_pose.h\n void growHomography(const Mat & featuresI, \n const Mat & featuresJ, \n const IndexT & matchId,\n std::vector & planarMatchesIndices, \n Mat3 & homographie)\n {\n \n planarMatchesIndices.clear();\n homographie = Mat3::Identity();\n \n for (IndexT iRefineStep = 0; iRefineStep < _nbIterations; ++iRefineStep)\n {\n if (iRefineStep == 0)\n {\n computeSimilarityFromMatch();\n }\n else if (iRefineStep <= 4)\n {\n estimateAffinity();\n }\n else\n {\n estimateHomography();\n }\n \n findHomographyInliers();\n \n }\n }\n \n \/**\n * @brief computeSimilarityFromMatch\n * see: alicevision::sfm::computeSimilarity() [sfm\/utils\/alignment.cpp]\n * alicevision::geometry::ACRansac_FindRTS() [geometry\/rigidTransformation3D(_test).hpp]\n *\/ \n void computeSimilarityFromMatch()\n {\n std::cout << \"computeSimilarityFromMatch\" << std::endl;\n }\n \n \/**\n * @brief estimateAffinity\n * see: alicevision::Affine2DFromCorrespondencesLinear() [multiview\/affineSolver(_test).hpp]\n *\/\n void estimateAffinity()\n {\n std::cout << \"estimateAffinity\" << std::endl;\n }\n \n \/**\n * @brief estimateHomography\n * see: by DLT: alicevision::homography::kernel::FourPointSolver::Solve() [multiview\/homographyKernelSolver.hpp]\n * by RANSAC: alicevision::matchingImageCOllection::geometricEstimation() [matchingImageCollection\/GeometricFilterMatrix_H_AC.hpp]\n *\/\n void estimateHomography()\n {\n std::cout << \"estimateHomography\" << std::endl;\n }\n \n \/**\n * @brief findHomographyInliers Test the reprojection error\n *\/\n void findHomographyInliers()\n {\n std::cout << \"findHomographyInliers\" << std::endl;\n }\n \n \/\/-- Stored data\n std::vector _Hs;\n \n \/\/-- Options\n \n std::size_t _maxNbHomographies; \/\/ = MaxHoms\n std::size_t _minRemainingMatches; \/\/ = MinInsNum\n \n \/\/ growHomography function:\n std::size_t _similarityTolerance; \/\/ = SimTol\n std::size_t _affinityTolerance; \/\/ = AffTol\n std::size_t _homographyTolerance; \/\/ = HomTol\n \n std::size_t _minNbPlanarMatches; \/\/ = MinIns\n std::size_t _nbIterations; \/\/ = RefIterNum\n std::size_t _maxFractionPlanarMatches; \/\/ = StopInsFrac\n \n \n};\n\n} \/\/ namespace matchingImageCollection\n} \/\/ namespace aliceVision\n\n\n[Hgrowing] 'computeSimilarityFromMatch' integration\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2016 AliceVision contributors.\n\/\/ Copyright (c) 2012 openMVG contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#pragma once\n\n\/\/#include \"aliceVision\/multiview\/homographyKernelSolver.hpp\"\n\/\/#include \"aliceVision\/robustEstimation\/ACRansac.hpp\"\n\/\/#include \"aliceVision\/robustEstimation\/ACRansacKernelAdaptator.hpp\"\n\/\/#include \"aliceVision\/robustEstimation\/guidedMatching.hpp\"\n\n#include \"aliceVision\/matching\/IndMatch.hpp\"\n\/\/#include \"aliceVision\/matching\/IndMatchDecorator.hpp\"\n#include \"aliceVision\/sfm\/SfMData.hpp\"\n#include \"aliceVision\/feature\/RegionsPerView.hpp\"\n#include \"aliceVision\/matchingImageCollection\/GeometricFilterMatrix.hpp\"\n\nnamespace aliceVision {\nnamespace matchingImageCollection {\n\n\/\/-- Multiple homography matrices estimation template functor, based on homography growing, used for filter pair of putative correspondences\nstruct GeometricFilterMatrix_HGrowing : public GeometricFilterMatrix\n{\n GeometricFilterMatrix_HGrowing(\n double dPrecision = std::numeric_limits::infinity(),\n size_t iteration = 1024)\n : GeometricFilterMatrix(dPrecision, std::numeric_limits::infinity(), iteration)\n , _maxNbHomographies(10)\n , _minRemainingMatches(20)\n , _similarityTolerance(10)\n , _affinityTolerance(10)\n , _homographyTolerance(5)\n , _minNbPlanarMatches(6)\n , _nbIterations(8)\n , _maxFractionPlanarMatches(0.7)\n {\n _Hs.push_back(Mat3::Identity());\n }\n\/**\n * @brief Given two sets of image points, it estimates the homography matrix\n * relating them using a robust method (like A Contrario Ransac).\n *\/\n template\n EstimationStatus geometricEstimation(\n const sfm::SfMData * sfmData,\n const Regions_or_Features_ProviderT& regionsPerView,\n const Pair pairIndex,\n const matching::MatchesPerDescType & putativeMatchesPerType,\n matching::MatchesPerDescType & out_geometricInliersPerType)\n {\n \n using namespace aliceVision;\n using namespace aliceVision::robustEstimation;\n out_geometricInliersPerType.clear();\n \n \/\/ Get back corresponding view index\n const IndexT viewId_I = pairIndex.first;\n const IndexT viewId_J = pairIndex.second;\n \n const std::vector descTypes = regionsPerView.getCommonDescTypes(pairIndex);\n if(descTypes.empty())\n return EstimationStatus(false, false);\n \n \/\/ Retrieve all 2D features as undistorted positions into flat arrays\n Mat xI, xJ;\n MatchesPairToMat(pairIndex, putativeMatchesPerType, sfmData, regionsPerView, descTypes, xI, xJ);\n \n std::cout << \"Pair id. : \" << pairIndex << std::endl;\n std::cout << \"|- putative: \" << putativeMatchesPerType.at(feature::EImageDescriberType::SIFT).size() << std::endl;\n std::cout << \"|- xI: \" << xI.rows() << \"x\" << xI.cols() << std::endl;\n std::cout << \"|- xJ: \" << xJ.rows() << \"x\" << xJ.cols() << std::endl;\n \n const feature::Regions& regionsSIFT_I = regionsPerView.getRegions(viewId_I, descTypes.at(0));\n const feature::Regions& regionsSIFT_J = regionsPerView.getRegions(viewId_J, descTypes.at(0));\n const std::vector allFeaturesI = getSIOPointFeatures(regionsSIFT_I);\n const std::vector allFeaturesJ = getSIOPointFeatures(regionsSIFT_J);\n \n matching::IndMatches putativeMatchesSIFT = putativeMatchesPerType.at(feature::EImageDescriberType::SIFT);\n std::vector putativeFeaturesI, putativeFeaturesJ;\n putativeFeaturesI.reserve(putativeMatchesSIFT.size());\n putativeFeaturesJ.reserve(putativeMatchesSIFT.size());\n \n for (const matching::IndMatch & idMatch : putativeMatchesSIFT)\n {\n putativeFeaturesI.push_back(allFeaturesI.at(idMatch._i));\n putativeFeaturesJ.push_back(allFeaturesJ.at(idMatch._j));\n }\n \n if (viewId_I == 200563944 && viewId_J == 1112206013) \/\/ MATLAB exemple\n {\n std::cout << \"|- #matches: \" << putativeMatchesSIFT.size() << std::endl;\n std::cout << \"|- allFeaturesI : \" << allFeaturesI.size() << std::endl;\n std::cout << \"|- allFeaturesJ : \" << allFeaturesJ.size() << std::endl;\n std::cout << \"|- putativeFeaturesI : \" << putativeFeaturesI.size() << std::endl;\n std::cout << \"|- putativeFeaturesJ : \" << putativeFeaturesJ.size() << std::endl;\n \/\/ std::cout << \"-------\" << std::endl;\n \/\/ std::cout << \"xI : \" << std::endl;\n \/\/ std::cout << xI << std::endl; \n \/\/ std::cout << \"putativeFeaturesI : \" << std::endl;\n \/\/ std::cout << putativeFeaturesI << std::endl;\n \n \n std::size_t nbMatches = putativeMatchesSIFT.size();\n \n \/\/ (?) make a map\n std::vector homographies;\n std::vector> planarMatchesPerH;\n \n for (IndexT iTransform = 0; iTransform < _maxNbHomographies; ++iTransform)\n {\n for (IndexT iMatch = 0; iMatch < nbMatches; ++iMatch)\n {\n \/\/ [TODO] Add 1st improvment\n \n \/\/ Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20) \n std::vector planarMatchesIds;\n Mat3 homographie;\n \n growHomography(putativeFeaturesI, putativeFeaturesJ, iMatch , planarMatchesIds, homographie);\n \n if (!planarMatchesIds.empty())\n {\n homographies.push_back(homographie);\n planarMatchesPerH.push_back(planarMatchesIds);\n }\n }\n }\n }\n \n \n \/\/ Check if resection has strong support\n const bool hasStrongSupport = true;\n return EstimationStatus(true, hasStrongSupport);\n }\n \n \/**\n * @brief Geometry_guided_matching\n * @param sfm_data\n * @param regionsPerView\n * @param pairIndex\n * @param dDistanceRatio\n * @param matches\n * @return\n *\/\n bool Geometry_guided_matching\n (\n const sfm::SfMData * sfmData,\n const feature::RegionsPerView & regionsPerView,\n const Pair imageIdsPair,\n const double dDistanceRatio,\n matching::MatchesPerDescType & matches) override\n {\n \n \/* ... *\/\n return matches.getNbAllMatches() != 0;\n }\n\nprivate:\n\n \/\/ Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20) \n \/\/-- See: YASM\/relative_pose.h\n void growHomography(const std::vector & featuresI, \n const std::vector & featuresJ, \n const IndexT & seedMatchId,\n std::vector & out_planarMatchesIndices, \n Mat3 & out_transformation)\n {\n \n assert(featuresI.size() == featuresJ.size());\n assert(seedMatchId <= featuresI.size());\n \n\/\/ std::cout << \"featuresI = \" << featuresI << std::endl;\n\/\/ std::cout << \"featuresI = \" << featuresI << std::endl;\n \n out_planarMatchesIndices.clear();\n out_transformation = Mat3::Identity();\n \n feature::SIOPointFeature seedFeatureI = featuresI.at(seedMatchId);\n feature::SIOPointFeature seedFeatureJ = featuresJ.at(seedMatchId);\n std::size_t currentTolerance;\n for (IndexT iRefineStep = 0; iRefineStep < _nbIterations; ++iRefineStep)\n {\n if (iRefineStep == 0)\n {\n computeSimilarityFromMatch(seedFeatureI, seedFeatureJ, out_transformation);\n std::cout << \"featI: \" << seedFeatureI << std::endl;\n std::cout << \"featJ: \" << seedFeatureJ << std::endl;\n std::cout << \"S = \" << out_transformation << std::endl;\n getchar();\n currentTolerance = _similarityTolerance;\n }\n else if (iRefineStep <= 4)\n {\n estimateAffinity();\n currentTolerance = _affinityTolerance;\n }\n else\n {\n estimateHomography();\n currentTolerance = _homographyTolerance;\n }\n \n findHomographyInliers();\n \n }\n }\n \n \/**\n * @brief computeSimilarityFromMatch\n * see: alicevision::sfm::computeSimilarity() [sfm\/utils\/alignment.cpp]\n * alicevision::geometry::ACRansac_FindRTS() [geometry\/rigidTransformation3D(_test).hpp]\n *\/ \n\n void computeSimilarityFromMatch(const feature::SIOPointFeature & feat1,\n const feature::SIOPointFeature & feat2,\n Mat3 & S)\n {\n computeSimilarityFromMatch(feat1.coords(), feat1.scale(), feat1.orientation(),\n feat2.coords(), feat2.scale(), feat2.orientation(),\n S);\n }\n\n \/**\n * @brief computeSimilarityFromMatch\n * Source: https:\/\/github.com\/fsrajer\/yasfm\/blob\/master\/YASFM\/relative_pose.cpp#L1649\n * @param coord1\n * @param scale1\n * @param orientation1\n * @param coord2\n * @param scale2\n * @param orientation2\n * @param S\n *\/ \n void computeSimilarityFromMatch(const Vec2f & coord1, double scale1, double orientation1,\n const Vec2f & coord2, double scale2, double orientation2,\n Mat3 & S)\n {\n double c1 = cos(orientation1),\n s1 = sin(orientation1),\n c2 = cos(orientation2),\n s2 = sin(orientation2);\n \n Mat3 A1,A2;\n A1 << scale1*c1,scale1*(-s1),coord1(0),\n scale1*s1,scale1*c1,coord1(1),\n 0,0,1;\n A2 << scale2*c2,scale2*(-s2),coord2(0),\n scale2*s2,scale2*c2,coord2(1),\n 0,0,1;\n \n S = A2*A1.inverse();\n }\n \n \/**\n * @brief estimateAffinity\n * see: alicevision::Affine2DFromCorrespondencesLinear() [multiview\/affineSolver(_test).hpp]\n *\/\n void estimateAffinity()\n {\n\/\/ std::cout << \"estimateAffinity\" << std::endl;\n }\n \n \/**\n * @brief estimateHomography\n * see: by DLT: alicevision::homography::kernel::FourPointSolver::Solve() [multiview\/homographyKernelSolver.hpp]\n * by RANSAC: alicevision::matchingImageCOllection::geometricEstimation() [matchingImageCollection\/GeometricFilterMatrix_H_AC.hpp]\n *\/\n void estimateHomography()\n {\n\/\/ std::cout << \"estimateHomography\" << std::endl;\n }\n \n \/**\n * @brief findHomographyInliers Test the reprojection error\n *\/\n void findHomographyInliers()\n {\n\/\/ std::cout << \"findHomographyInliers\" << std::endl;\n }\n \n \/\/-- Stored data\n std::vector _Hs;\n \n \/\/-- Options\n \n std::size_t _maxNbHomographies; \/\/ = MaxHoms\n std::size_t _minRemainingMatches; \/\/ = MinInsNum\n \n \/\/ growHomography function:\n std::size_t _similarityTolerance; \/\/ = SimTol\n std::size_t _affinityTolerance; \/\/ = AffTol\n std::size_t _homographyTolerance; \/\/ = HomTol\n \n std::size_t _minNbPlanarMatches; \/\/ = MinIns\n std::size_t _nbIterations; \/\/ = RefIterNum\n std::size_t _maxFractionPlanarMatches; \/\/ = StopInsFrac\n \n \n};\n\n} \/\/ namespace matchingImageCollection\n} \/\/ namespace aliceVision\n\n\n<|endoftext|>"} {"text":"\/\/ Application entry point.\n\/\/\n#include \n#include \n\n\nusing namespace std;\n\n\nint main() {\n extern string greeting(); \/\/ greeting.cpp\n std::cout << greeting() << endl;\n return EXIT_SUCCESS;\n}\nadded header to main.cpp\/\/ Application entry point.\n\/\/\n#include \n#include \n#include \n\n\nusing namespace std;\n\n\nint main() {\n extern string greeting(); \/\/ greeting.cpp\n std::cout << greeting() << endl;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2016, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"openthread-core-config.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"cli\/cli_config.h\"\n#include \"common\/code_utils.hpp\"\n#include \"common\/debug.hpp\"\n#include \"common\/logging.hpp\"\n#include \"utils\/uart.h\"\n\n#if OPENTHREAD_POSIX\n#include \n#include \n#endif\n\n\/**\n * @def OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE\n *\n * The size of CLI UART RX buffer in bytes.\n *\n *\/\n#ifndef OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE\n#if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE\n#define OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE 640\n#else\n#define OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE 512\n#endif\n#endif\n\n\/**\n * @def OPENTHREAD_CONFIG_CLI_TX_BUFFER_SIZE\n *\n * The size of CLI message buffer in bytes.\n *\n *\/\n#ifndef OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE\n#define OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE 1024\n#endif\n\n#if OPENTHREAD_CONFIG_DIAG_ENABLE\n#if OPENTHREAD_CONFIG_DIAG_OUTPUT_BUFFER_SIZE > OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE\n#error \"diag output buffer should be smaller than CLI UART tx buffer\"\n#endif\n#if OPENTHREAD_CONFIG_DIAG_CMD_LINE_BUFFER_SIZE > OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE\n#error \"diag command line should be smaller than CLI UART rx buffer\"\n#endif\n#endif\n\n#if OPENTHREAD_CONFIG_CLI_MAX_LINE_LENGTH > OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE\n#error \"command line should be should be smaller than CLI rx buffer\"\n#endif\n\nenum\n{\n kRxBufferSize = OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE,\n kTxBufferSize = OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE,\n};\n\nchar sRxBuffer[kRxBufferSize];\nuint16_t sRxLength;\n\nchar sTxBuffer[kTxBufferSize];\nuint16_t sTxHead;\nuint16_t sTxLength;\n\nuint16_t sSendLength;\n\n#ifdef OT_CLI_UART_LOCK_HDR_FILE\n\n#include OT_CLI_UART_LOCK_HDR_FILE\n\n#else\n\n\/**\n * Macro to acquire an exclusive lock of uart cli output\n * Default implementation does nothing\n *\n *\/\n#ifndef OT_CLI_UART_OUTPUT_LOCK\n#define OT_CLI_UART_OUTPUT_LOCK() \\\n do \\\n { \\\n } while (0)\n#endif\n\n\/**\n * Macro to release the exclusive lock of uart cli output\n * Default implementation does nothing\n *\n *\/\n#ifndef OT_CLI_UART_OUTPUT_UNLOCK\n#define OT_CLI_UART_OUTPUT_UNLOCK() \\\n do \\\n { \\\n } while (0)\n#endif\n\n#endif \/\/ OT_CLI_UART_LOCK_HDR_FILE\n\nstatic int Output(const char *aBuf, uint16_t aBufLength);\nstatic otError ProcessCommand(void);\n\nstatic void ReceiveTask(const uint8_t *aBuf, uint16_t aBufLength)\n{\n static const char sEraseString[] = {'\\b', ' ', '\\b'};\n static const char CRNL[] = {'\\r', '\\n'};\n static const char sCommandPrompt[] = {'>', ' '};\n const uint8_t * end;\n\n end = aBuf + aBufLength;\n\n for (; aBuf < end; aBuf++)\n {\n switch (*aBuf)\n {\n case '\\r':\n case '\\n':\n Output(CRNL, sizeof(CRNL));\n if (sRxLength > 0)\n {\n sRxBuffer[sRxLength] = '\\0';\n IgnoreError(ProcessCommand());\n }\n\n Output(sCommandPrompt, sizeof(sCommandPrompt));\n\n break;\n\n#if OPENTHREAD_POSIX && !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)\n case 0x03: \/\/ ASCII for Ctrl-C\n kill(0, SIGINT);\n break;\n\n case 0x04: \/\/ ASCII for Ctrl-D\n exit(EXIT_SUCCESS);\n break;\n#endif\n\n case '\\b':\n case 127:\n if (sRxLength > 0)\n {\n Output(sEraseString, sizeof(sEraseString));\n sRxBuffer[--sRxLength] = '\\0';\n }\n\n break;\n\n default:\n if (sRxLength < kRxBufferSize - 1)\n {\n Output(reinterpret_cast(aBuf), 1);\n sRxBuffer[sRxLength++] = static_cast(*aBuf);\n }\n\n break;\n }\n }\n}\n\nstatic otError ProcessCommand(void)\n{\n otError error = OT_ERROR_NONE;\n\n while (sRxBuffer[sRxLength - 1] == '\\n' || sRxBuffer[sRxLength - 1] == '\\r')\n {\n sRxBuffer[--sRxLength] = '\\0';\n }\n\n#if OPENTHREAD_CONFIG_LOG_OUTPUT != OPENTHREAD_CONFIG_LOG_OUTPUT_NONE\n \/*\n * Note this is here for this reason:\n *\n * TEXT (command) input ... in a test automation script occurs\n * rapidly and often without gaps between the command and the\n * terminal CR\n *\n * In contrast as a human is typing there is a delay between the\n * last character of a command and the terminal CR which executes\n * a command.\n *\n * During that human induced delay a tasklet may be scheduled and\n * the LOG becomes confusing and it is hard to determine when\n * something happened. Which happened first? the command-CR or\n * the tasklet.\n *\n * Yes, while rare it is a race condition that is hard to debug.\n *\n * Thus this is here to affirmatively LOG exactly when the CLI\n * command is being executed.\n *\/\n#if OPENTHREAD_CONFIG_MULTIPLE_INSTANCE_ENABLE\n \/* TODO: how exactly do we get the instance here? *\/\n#else\n otLogInfoCli(\"execute command: %s\", sRxBuffer);\n#endif\n#endif\n if (sRxLength > 0)\n {\n otCliInputLine(sRxBuffer);\n }\n\n sRxLength = 0;\n\n return error;\n}\n\nstatic void Send(void)\n{\n VerifyOrExit(sSendLength == 0);\n\n if (sTxLength > kTxBufferSize - sTxHead)\n {\n sSendLength = kTxBufferSize - sTxHead;\n }\n else\n {\n sSendLength = sTxLength;\n }\n\n if (sSendLength > 0)\n {\n#if OPENTHREAD_CONFIG_ENABLE_DEBUG_UART\n \/* duplicate the output to the debug uart *\/\n otSysDebugUart_write_bytes(reinterpret_cast(sTxBuffer + sTxHead), sSendLength);\n#endif\n IgnoreError(otPlatUartSend(reinterpret_cast(sTxBuffer + sTxHead), sSendLength));\n }\n\nexit:\n return;\n}\n\nstatic void SendDoneTask(void)\n{\n sTxHead = (sTxHead + sSendLength) % kTxBufferSize;\n sTxLength -= sSendLength;\n sSendLength = 0;\n\n Send();\n}\n\nstatic int Output(const char *aBuf, uint16_t aBufLength)\n{\n OT_CLI_UART_OUTPUT_LOCK();\n uint16_t sent = 0;\n\n while (aBufLength > 0)\n {\n uint16_t remaining = kTxBufferSize - sTxLength;\n uint16_t tail;\n uint16_t sendLength = aBufLength;\n\n if (sendLength > remaining)\n {\n sendLength = remaining;\n }\n\n for (uint16_t i = 0; i < sendLength; i++)\n {\n tail = (sTxHead + sTxLength) % kTxBufferSize;\n sTxBuffer[tail] = *aBuf++;\n aBufLength--;\n sTxLength++;\n }\n\n Send();\n\n sent += sendLength;\n\n if (aBufLength > 0)\n {\n \/\/ More to send, so flush what's waiting now\n otError err = otPlatUartFlush();\n\n if (err == OT_ERROR_NONE)\n {\n \/\/ Flush successful, reset the pointers\n SendDoneTask();\n }\n else\n {\n \/\/ Flush did not succeed, so abort here.\n break;\n }\n }\n }\n\n OT_CLI_UART_OUTPUT_UNLOCK();\n\n return sent;\n}\n\nstatic int CliUartOutput(void *aContext, const char *aFormat, va_list aArguments)\n{\n OT_UNUSED_VARIABLE(aContext);\n\n int rval;\n\n if (sTxLength == 0)\n {\n rval = vsnprintf(sTxBuffer, kTxBufferSize, aFormat, aArguments);\n VerifyOrExit(rval > 0 && rval < kTxBufferSize, otLogWarnPlat(\"Failed to format CLI output `%s`\", aFormat));\n sTxHead = 0;\n sTxLength = static_cast(rval);\n sSendLength = 0;\n }\n else\n {\n va_list retryArguments;\n uint16_t tail = (sTxHead + sTxLength) % kTxBufferSize;\n uint16_t remaining = (sTxHead > tail ? (sTxHead - tail) : (kTxBufferSize - tail));\n\n va_copy(retryArguments, aArguments);\n\n rval = vsnprintf(&sTxBuffer[tail], remaining, aFormat, aArguments);\n\n if (rval < 0)\n {\n otLogWarnPlat(\"Failed to format CLI output `%s`\", aFormat);\n }\n else if (rval < remaining)\n {\n sTxLength += rval;\n }\n else if (rval < kTxBufferSize)\n {\n while (sTxLength != 0)\n {\n otError error;\n\n Send();\n\n error = otPlatUartFlush();\n\n if (error == OT_ERROR_NONE)\n {\n \/\/ Flush successful, reset the pointers\n SendDoneTask();\n }\n else\n {\n \/\/ Flush did not succeed, so abort here.\n otLogWarnPlat(\"Failed to output CLI: %s\", otThreadErrorToString(error));\n ExitNow();\n }\n }\n rval = vsnprintf(sTxBuffer, kTxBufferSize, aFormat, retryArguments);\n OT_ASSERT(rval > 0);\n sTxLength = static_cast(rval);\n sTxHead = 0;\n sSendLength = 0;\n }\n else\n {\n otLogWarnPlat(\"CLI output `%s` truncated\", aFormat);\n }\n\n va_end(retryArguments);\n }\n\n Send();\n\nexit:\n return rval;\n}\n\nvoid otPlatUartReceived(const uint8_t *aBuf, uint16_t aBufLength)\n{\n ReceiveTask(aBuf, aBufLength);\n}\n\nvoid otPlatUartSendDone(void)\n{\n SendDoneTask();\n}\n\nextern \"C\" void otAppCliInit(otInstance *aInstance)\n{\n sRxLength = 0;\n sTxHead = 0;\n sTxLength = 0;\n sSendLength = 0;\n\n IgnoreError(otPlatUartEnable());\n\n otCliInit(aInstance, CliUartOutput, aInstance);\n}\n[cli] fix false alarm when printing empty line (#6499)\/*\n * Copyright (c) 2016, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"openthread-core-config.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"cli\/cli_config.h\"\n#include \"common\/code_utils.hpp\"\n#include \"common\/debug.hpp\"\n#include \"common\/logging.hpp\"\n#include \"utils\/uart.h\"\n\n#if OPENTHREAD_POSIX\n#include \n#include \n#endif\n\n\/**\n * @def OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE\n *\n * The size of CLI UART RX buffer in bytes.\n *\n *\/\n#ifndef OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE\n#if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE\n#define OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE 640\n#else\n#define OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE 512\n#endif\n#endif\n\n\/**\n * @def OPENTHREAD_CONFIG_CLI_TX_BUFFER_SIZE\n *\n * The size of CLI message buffer in bytes.\n *\n *\/\n#ifndef OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE\n#define OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE 1024\n#endif\n\n#if OPENTHREAD_CONFIG_DIAG_ENABLE\n#if OPENTHREAD_CONFIG_DIAG_OUTPUT_BUFFER_SIZE > OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE\n#error \"diag output buffer should be smaller than CLI UART tx buffer\"\n#endif\n#if OPENTHREAD_CONFIG_DIAG_CMD_LINE_BUFFER_SIZE > OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE\n#error \"diag command line should be smaller than CLI UART rx buffer\"\n#endif\n#endif\n\n#if OPENTHREAD_CONFIG_CLI_MAX_LINE_LENGTH > OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE\n#error \"command line should be should be smaller than CLI rx buffer\"\n#endif\n\nenum\n{\n kRxBufferSize = OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE,\n kTxBufferSize = OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE,\n};\n\nchar sRxBuffer[kRxBufferSize];\nuint16_t sRxLength;\n\nchar sTxBuffer[kTxBufferSize];\nuint16_t sTxHead;\nuint16_t sTxLength;\n\nuint16_t sSendLength;\n\n#ifdef OT_CLI_UART_LOCK_HDR_FILE\n\n#include OT_CLI_UART_LOCK_HDR_FILE\n\n#else\n\n\/**\n * Macro to acquire an exclusive lock of uart cli output\n * Default implementation does nothing\n *\n *\/\n#ifndef OT_CLI_UART_OUTPUT_LOCK\n#define OT_CLI_UART_OUTPUT_LOCK() \\\n do \\\n { \\\n } while (0)\n#endif\n\n\/**\n * Macro to release the exclusive lock of uart cli output\n * Default implementation does nothing\n *\n *\/\n#ifndef OT_CLI_UART_OUTPUT_UNLOCK\n#define OT_CLI_UART_OUTPUT_UNLOCK() \\\n do \\\n { \\\n } while (0)\n#endif\n\n#endif \/\/ OT_CLI_UART_LOCK_HDR_FILE\n\nstatic int Output(const char *aBuf, uint16_t aBufLength);\nstatic otError ProcessCommand(void);\n\nstatic void ReceiveTask(const uint8_t *aBuf, uint16_t aBufLength)\n{\n static const char sEraseString[] = {'\\b', ' ', '\\b'};\n static const char CRNL[] = {'\\r', '\\n'};\n static const char sCommandPrompt[] = {'>', ' '};\n const uint8_t * end;\n\n end = aBuf + aBufLength;\n\n for (; aBuf < end; aBuf++)\n {\n switch (*aBuf)\n {\n case '\\r':\n case '\\n':\n Output(CRNL, sizeof(CRNL));\n if (sRxLength > 0)\n {\n sRxBuffer[sRxLength] = '\\0';\n IgnoreError(ProcessCommand());\n }\n\n Output(sCommandPrompt, sizeof(sCommandPrompt));\n\n break;\n\n#if OPENTHREAD_POSIX && !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)\n case 0x03: \/\/ ASCII for Ctrl-C\n kill(0, SIGINT);\n break;\n\n case 0x04: \/\/ ASCII for Ctrl-D\n exit(EXIT_SUCCESS);\n break;\n#endif\n\n case '\\b':\n case 127:\n if (sRxLength > 0)\n {\n Output(sEraseString, sizeof(sEraseString));\n sRxBuffer[--sRxLength] = '\\0';\n }\n\n break;\n\n default:\n if (sRxLength < kRxBufferSize - 1)\n {\n Output(reinterpret_cast(aBuf), 1);\n sRxBuffer[sRxLength++] = static_cast(*aBuf);\n }\n\n break;\n }\n }\n}\n\nstatic otError ProcessCommand(void)\n{\n otError error = OT_ERROR_NONE;\n\n while (sRxBuffer[sRxLength - 1] == '\\n' || sRxBuffer[sRxLength - 1] == '\\r')\n {\n sRxBuffer[--sRxLength] = '\\0';\n }\n\n#if OPENTHREAD_CONFIG_LOG_OUTPUT != OPENTHREAD_CONFIG_LOG_OUTPUT_NONE\n \/*\n * Note this is here for this reason:\n *\n * TEXT (command) input ... in a test automation script occurs\n * rapidly and often without gaps between the command and the\n * terminal CR\n *\n * In contrast as a human is typing there is a delay between the\n * last character of a command and the terminal CR which executes\n * a command.\n *\n * During that human induced delay a tasklet may be scheduled and\n * the LOG becomes confusing and it is hard to determine when\n * something happened. Which happened first? the command-CR or\n * the tasklet.\n *\n * Yes, while rare it is a race condition that is hard to debug.\n *\n * Thus this is here to affirmatively LOG exactly when the CLI\n * command is being executed.\n *\/\n#if OPENTHREAD_CONFIG_MULTIPLE_INSTANCE_ENABLE\n \/* TODO: how exactly do we get the instance here? *\/\n#else\n otLogInfoCli(\"execute command: %s\", sRxBuffer);\n#endif\n#endif\n if (sRxLength > 0)\n {\n otCliInputLine(sRxBuffer);\n }\n\n sRxLength = 0;\n\n return error;\n}\n\nstatic void Send(void)\n{\n VerifyOrExit(sSendLength == 0);\n\n if (sTxLength > kTxBufferSize - sTxHead)\n {\n sSendLength = kTxBufferSize - sTxHead;\n }\n else\n {\n sSendLength = sTxLength;\n }\n\n if (sSendLength > 0)\n {\n#if OPENTHREAD_CONFIG_ENABLE_DEBUG_UART\n \/* duplicate the output to the debug uart *\/\n otSysDebugUart_write_bytes(reinterpret_cast(sTxBuffer + sTxHead), sSendLength);\n#endif\n IgnoreError(otPlatUartSend(reinterpret_cast(sTxBuffer + sTxHead), sSendLength));\n }\n\nexit:\n return;\n}\n\nstatic void SendDoneTask(void)\n{\n sTxHead = (sTxHead + sSendLength) % kTxBufferSize;\n sTxLength -= sSendLength;\n sSendLength = 0;\n\n Send();\n}\n\nstatic int Output(const char *aBuf, uint16_t aBufLength)\n{\n OT_CLI_UART_OUTPUT_LOCK();\n uint16_t sent = 0;\n\n while (aBufLength > 0)\n {\n uint16_t remaining = kTxBufferSize - sTxLength;\n uint16_t tail;\n uint16_t sendLength = aBufLength;\n\n if (sendLength > remaining)\n {\n sendLength = remaining;\n }\n\n for (uint16_t i = 0; i < sendLength; i++)\n {\n tail = (sTxHead + sTxLength) % kTxBufferSize;\n sTxBuffer[tail] = *aBuf++;\n aBufLength--;\n sTxLength++;\n }\n\n Send();\n\n sent += sendLength;\n\n if (aBufLength > 0)\n {\n \/\/ More to send, so flush what's waiting now\n otError err = otPlatUartFlush();\n\n if (err == OT_ERROR_NONE)\n {\n \/\/ Flush successful, reset the pointers\n SendDoneTask();\n }\n else\n {\n \/\/ Flush did not succeed, so abort here.\n break;\n }\n }\n }\n\n OT_CLI_UART_OUTPUT_UNLOCK();\n\n return sent;\n}\n\nstatic int CliUartOutput(void *aContext, const char *aFormat, va_list aArguments)\n{\n OT_UNUSED_VARIABLE(aContext);\n\n int rval;\n\n if (sTxLength == 0)\n {\n rval = vsnprintf(sTxBuffer, kTxBufferSize, aFormat, aArguments);\n VerifyOrExit(rval >= 0 && rval < kTxBufferSize, otLogWarnPlat(\"Failed to format CLI output `%s`\", aFormat));\n sTxHead = 0;\n sTxLength = static_cast(rval);\n sSendLength = 0;\n }\n else\n {\n va_list retryArguments;\n uint16_t tail = (sTxHead + sTxLength) % kTxBufferSize;\n uint16_t remaining = (sTxHead > tail ? (sTxHead - tail) : (kTxBufferSize - tail));\n\n va_copy(retryArguments, aArguments);\n\n rval = vsnprintf(&sTxBuffer[tail], remaining, aFormat, aArguments);\n\n if (rval < 0)\n {\n otLogWarnPlat(\"Failed to format CLI output `%s`\", aFormat);\n }\n else if (rval < remaining)\n {\n sTxLength += rval;\n }\n else if (rval < kTxBufferSize)\n {\n while (sTxLength != 0)\n {\n otError error;\n\n Send();\n\n error = otPlatUartFlush();\n\n if (error == OT_ERROR_NONE)\n {\n \/\/ Flush successful, reset the pointers\n SendDoneTask();\n }\n else\n {\n \/\/ Flush did not succeed, so abort here.\n otLogWarnPlat(\"Failed to output CLI: %s\", otThreadErrorToString(error));\n ExitNow();\n }\n }\n rval = vsnprintf(sTxBuffer, kTxBufferSize, aFormat, retryArguments);\n OT_ASSERT(rval > 0);\n sTxLength = static_cast(rval);\n sTxHead = 0;\n sSendLength = 0;\n }\n else\n {\n otLogWarnPlat(\"CLI output `%s` truncated\", aFormat);\n }\n\n va_end(retryArguments);\n }\n\n Send();\n\nexit:\n return rval;\n}\n\nvoid otPlatUartReceived(const uint8_t *aBuf, uint16_t aBufLength)\n{\n ReceiveTask(aBuf, aBufLength);\n}\n\nvoid otPlatUartSendDone(void)\n{\n SendDoneTask();\n}\n\nextern \"C\" void otAppCliInit(otInstance *aInstance)\n{\n sRxLength = 0;\n sTxHead = 0;\n sTxLength = 0;\n sSendLength = 0;\n\n IgnoreError(otPlatUartEnable());\n\n otCliInit(aInstance, CliUartOutput, aInstance);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \"Channel.h\"\n\n\n\nvoid worker_thread(Channel* data)\n{\n while(true){\n auto Channeldata = data->get();\n if(Channeldata == \"END\"){\n break;\n }\n std::cout << \"Worker says: \" << Channeldata << std::endl;\n }\n std::cout << \"Exiting loop\" << std::endl;\n}\n\nint main()\n{\n Channel* myChan = new Channel;\n\n myChan->put(\"Hello\");\n myChan->put(\"World\");\n\n std::thread worker(worker_thread,myChan);\n\n while (true){\n std::string input;\n std::cin >> input;\n myChan->put(input);\n if(input == \"END\"){\n break;\n }\n }\n\n worker.join();\n}Changed to pass channel by reference#include \n#include \n#include \n#include \n#include \n#include \"Channel.h\"\n\n\n\nvoid worker_thread(Channel& data)\n{\n while(true){\n auto Channeldata = data.get();\n if(Channeldata == \"END\"){\n break;\n }\n std::cout << \"Worker says: \" << Channeldata << std::endl;\n }\n std::cout << \"Exiting loop\" << std::endl;\n}\n\nint main()\n{\n Channel myChan;\n\n myChan.put(\"Hello\");\n myChan.put(\"World\");\n\n std::thread worker(worker_thread,std::ref(myChan));\n\n while (true){\n std::string input;\n std::cin >> input;\n myChan.put(input);\n if(input == \"END\"){\n break;\n }\n }\n\n worker.join();\n}<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2015 The Cryptonote developers\n\/\/ Copyright (c) 2016 The Karbowanec developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"CurrencyAdapter.h\"\n#include \"LoggerAdapter.h\"\n#include \"NodeAdapter.h\"\n#include \"Settings.h\"\n\nnamespace WalletGui {\n\nnamespace {\n\nstd::vector convertStringListToVector(const QStringList& list) {\n std::vector result;\n Q_FOREACH (const QString& item, list) {\n result.push_back(item.toStdString());\n }\n\n return result;\n}\n\n}\n\nclass InProcessNodeInitializer : public QObject {\n Q_OBJECT\n Q_DISABLE_COPY(InProcessNodeInitializer)\n\nQ_SIGNALS:\n void nodeInitCompletedSignal();\n void nodeInitFailedSignal(int _errorCode);\n void nodeDeinitCompletedSignal();\n\npublic:\n InProcessNodeInitializer(QObject* _parent = nullptr) {\n }\n\n ~InProcessNodeInitializer() {\n }\n\n void start(Node** _node, const CryptoNote::Currency* currency, INodeCallback* _callback, Logging::LoggerManager* _loggerManager,\n const CryptoNote::CoreConfig& _coreConfig, const CryptoNote::NetNodeConfig& _netNodeConfig) {\n (*_node) = createInprocessNode(*currency, *_loggerManager, _coreConfig, _netNodeConfig, *_callback);\n try {\n (*_node)->init([this](std::error_code _err) {\n if (_err) {\n Q_EMIT nodeInitFailedSignal(_err.value());\n QCoreApplication::processEvents();\n return;\n }\n\n Q_EMIT nodeInitCompletedSignal();\n QCoreApplication::processEvents();\n });\n } catch (std::runtime_error& err) {\n Q_EMIT nodeInitFailedSignal(CryptoNote::error::INTERNAL_WALLET_ERROR);\n QCoreApplication::processEvents();\n return;\n }\n\n delete *_node;\n *_node = nullptr;\n Q_EMIT nodeDeinitCompletedSignal();\n }\n\n void stop(Node** _node) {\n Q_CHECK_PTR(*_node);\n (*_node)->deinit();\n }\n};\n\nNodeAdapter& NodeAdapter::instance() {\n static NodeAdapter inst;\n return inst;\n}\n\nNodeAdapter::NodeAdapter() : QObject(), m_node(nullptr), m_nodeInitializerThread(), m_nodeInitializer(new InProcessNodeInitializer) {\n m_nodeInitializer->moveToThread(&m_nodeInitializerThread);\n\n qRegisterMetaType(\"CryptoNote::CoreConfig\");\n qRegisterMetaType(\"CryptoNote::NetNodeConfig\");\n\n connect(m_nodeInitializer, &InProcessNodeInitializer::nodeInitCompletedSignal, this, &NodeAdapter::nodeInitCompletedSignal, Qt::QueuedConnection);\n connect(this, &NodeAdapter::initNodeSignal, m_nodeInitializer, &InProcessNodeInitializer::start, Qt::QueuedConnection);\n connect(this, &NodeAdapter::deinitNodeSignal, m_nodeInitializer, &InProcessNodeInitializer::stop, Qt::QueuedConnection);\n}\n\nNodeAdapter::~NodeAdapter() {\n}\n\nquintptr NodeAdapter::getPeerCount() const {\n Q_ASSERT(m_node != nullptr);\n return m_node->getPeerCount();\n}\n\nstd::string NodeAdapter::convertPaymentId(const QString& _paymentIdString) const {\n Q_CHECK_PTR(m_node);\n try {\n return m_node->convertPaymentId(_paymentIdString.toStdString());\n } catch (std::runtime_error& err) {\n }\n return std::string();\n}\n\nQString NodeAdapter::extractPaymentId(const std::string& _extra) const {\n Q_CHECK_PTR(m_node);\n return QString::fromStdString(m_node->extractPaymentId(_extra));\n}\n\nCryptoNote::IWalletLegacy* NodeAdapter::createWallet() const {\n Q_CHECK_PTR(m_node);\n return m_node->createWallet();\n}\n\nbool NodeAdapter::init() {\n Q_ASSERT(m_node == nullptr);\n\n QString connection = Settings::instance().getConnection();\n\n if(connection.compare(\"embedded\") == 0) {\n\n m_node = nullptr;\n return initInProcessNode();\n\n } else if(connection.compare(\"local\") == 0) {\n QUrl localNodeUrl = QUrl::fromUserInput(QString(\"127.0.0.1:%1\").arg(Settings::instance().getCurrentLocalDaemonPort()));\n m_node = createRpcNode(CurrencyAdapter::instance().getCurrency(), *this, localNodeUrl.host().toStdString(), localNodeUrl.port());\n QTimer initTimer;\n initTimer.setInterval(3000);\n initTimer.setSingleShot(true);\n initTimer.start();\n m_node->init([this](std::error_code _err) {\n Q_UNUSED(_err);\n });\n QEventLoop waitLoop;\n connect(&initTimer, &QTimer::timeout, &waitLoop, &QEventLoop::quit);\n connect(this, &NodeAdapter::peerCountUpdatedSignal, &waitLoop, &QEventLoop::quit);\n connect(this, &NodeAdapter::localBlockchainUpdatedSignal, &waitLoop, &QEventLoop::quit);\n waitLoop.exec();\n if (initTimer.isActive()) {\n initTimer.stop();\n Q_EMIT nodeInitCompletedSignal();\n return true;\n }\n\n } else if(connection.compare(\"remote\") == 0) {\n QUrl remoteNodeUrl = QUrl::fromUserInput(Settings::instance().getCurrentRemoteNode());\n m_node = createRpcNode(CurrencyAdapter::instance().getCurrency(), *this, remoteNodeUrl.host().toStdString(), remoteNodeUrl.port());\n QTimer initTimer;\n initTimer.setInterval(3000);\n initTimer.setSingleShot(true);\n initTimer.start();\n m_node->init([this](std::error_code _err) {\n Q_UNUSED(_err);\n });\n QEventLoop waitLoop;\n connect(&initTimer, &QTimer::timeout, &waitLoop, &QEventLoop::quit);\n connect(this, &NodeAdapter::peerCountUpdatedSignal, &waitLoop, &QEventLoop::quit);\n connect(this, &NodeAdapter::localBlockchainUpdatedSignal, &waitLoop, &QEventLoop::quit);\n waitLoop.exec();\n if (initTimer.isActive()) {\n initTimer.stop();\n Q_EMIT nodeInitCompletedSignal();\n return true;\n }\n\n } else {\n QUrl localNodeUrl = QUrl::fromUserInput(QString(\"127.0.0.1:%1\").arg(CryptoNote::RPC_DEFAULT_PORT));\n m_node = createRpcNode(CurrencyAdapter::instance().getCurrency(), *this, localNodeUrl.host().toStdString(), localNodeUrl.port());\n QTimer initTimer;\n initTimer.setInterval(3000);\n initTimer.setSingleShot(true);\n initTimer.start();\n m_node->init([this](std::error_code _err) {\n Q_UNUSED(_err);\n });\n QEventLoop waitLoop;\n connect(&initTimer, &QTimer::timeout, &waitLoop, &QEventLoop::quit);\n connect(this, &NodeAdapter::peerCountUpdatedSignal, &waitLoop, &QEventLoop::quit);\n connect(this, &NodeAdapter::localBlockchainUpdatedSignal, &waitLoop, &QEventLoop::quit);\n waitLoop.exec();\n if (initTimer.isActive()) {\n initTimer.stop();\n Q_EMIT nodeInitCompletedSignal();\n return true;\n }\n delete m_node;\n m_node = nullptr;\n return initInProcessNode();\n }\n\n}\n\nquint64 NodeAdapter::getLastKnownBlockHeight() const {\n Q_CHECK_PTR(m_node);\n return m_node->getLastKnownBlockHeight();\n}\n\nquint64 NodeAdapter::getLastLocalBlockHeight() const {\n Q_CHECK_PTR(m_node);\n return m_node->getLastLocalBlockHeight();\n}\n\nQDateTime NodeAdapter::getLastLocalBlockTimestamp() const {\n Q_CHECK_PTR(m_node);\n return QDateTime::fromTime_t(m_node->getLastLocalBlockTimestamp(), Qt::UTC);\n}\n\nvoid NodeAdapter::peerCountUpdated(Node& _node, size_t _count) {\n Q_UNUSED(_node);\n Q_EMIT peerCountUpdatedSignal(_count);\n}\n\nvoid NodeAdapter::localBlockchainUpdated(Node& _node, uint64_t _height) {\n Q_UNUSED(_node);\n Q_EMIT localBlockchainUpdatedSignal(_height);\n}\n\nvoid NodeAdapter::lastKnownBlockHeightUpdated(Node& _node, uint64_t _height) {\n Q_UNUSED(_node);\n Q_EMIT lastKnownBlockHeightUpdatedSignal(_height);\n}\n\nbool NodeAdapter::initInProcessNode() {\n Q_ASSERT(m_node == nullptr);\n m_nodeInitializerThread.start();\n CryptoNote::CoreConfig coreConfig = makeCoreConfig();\n CryptoNote::NetNodeConfig netNodeConfig = makeNetNodeConfig();\n Q_EMIT initNodeSignal(&m_node, &CurrencyAdapter::instance().getCurrency(), this, &LoggerAdapter::instance().getLoggerManager(), coreConfig, netNodeConfig);\n QEventLoop waitLoop;\n connect(m_nodeInitializer, &InProcessNodeInitializer::nodeInitCompletedSignal, &waitLoop, &QEventLoop::quit);\n connect(m_nodeInitializer, &InProcessNodeInitializer::nodeInitFailedSignal, &waitLoop, &QEventLoop::exit);\n if (waitLoop.exec() != 0) {\n return false;\n }\n\n Q_EMIT localBlockchainUpdatedSignal(getLastLocalBlockHeight());\n Q_EMIT lastKnownBlockHeightUpdatedSignal(getLastKnownBlockHeight());\n return true;\n}\n\nvoid NodeAdapter::deinit() {\n if (m_node != nullptr) {\n if (m_nodeInitializerThread.isRunning()) {\n m_nodeInitializer->stop(&m_node);\n QEventLoop waitLoop;\n connect(m_nodeInitializer, &InProcessNodeInitializer::nodeDeinitCompletedSignal, &waitLoop, &QEventLoop::quit, Qt::QueuedConnection);\n waitLoop.exec();\n m_nodeInitializerThread.quit();\n m_nodeInitializerThread.wait();\n } else {\n delete m_node;\n m_node = nullptr;\n }\n }\n}\n\nCryptoNote::CoreConfig NodeAdapter::makeCoreConfig() const {\n CryptoNote::CoreConfig config;\n boost::program_options::variables_map options;\n boost::any dataDir = std::string(Settings::instance().getDataDir().absolutePath().toLocal8Bit().data());\n options.insert(std::make_pair(\"data-dir\", boost::program_options::variable_value(dataDir, false)));\n config.init(options);\n return config;\n}\n\nCryptoNote::NetNodeConfig NodeAdapter::makeNetNodeConfig() const {\n CryptoNote::NetNodeConfig config;\n boost::program_options::variables_map options;\n boost::any p2pBindIp = Settings::instance().getP2pBindIp().toStdString();\n boost::any p2pBindPort = static_cast(Settings::instance().getP2pBindPort());\n boost::any p2pExternalPort = static_cast(Settings::instance().getP2pExternalPort());\n boost::any p2pAllowLocalIp = Settings::instance().hasAllowLocalIpOption();\n boost::any dataDir = std::string(Settings::instance().getDataDir().absolutePath().toLocal8Bit().data());\n boost::any hideMyPort = Settings::instance().hasHideMyPortOption();\n options.insert(std::make_pair(\"p2p-bind-ip\", boost::program_options::variable_value(p2pBindIp, false)));\n options.insert(std::make_pair(\"p2p-bind-port\", boost::program_options::variable_value(p2pBindPort, false)));\n options.insert(std::make_pair(\"p2p-external-port\", boost::program_options::variable_value(p2pExternalPort, false)));\n options.insert(std::make_pair(\"allow-local-ip\", boost::program_options::variable_value(p2pAllowLocalIp, false)));\n std::vector peerList = convertStringListToVector(Settings::instance().getPeers());\n if (!peerList.empty()) {\n options.insert(std::make_pair(\"add-peer\", boost::program_options::variable_value(peerList, false)));\n }\n\n std::vector priorityNodeList = convertStringListToVector(Settings::instance().getPriorityNodes());\n if (!priorityNodeList.empty()) {\n options.insert(std::make_pair(\"add-priority-node\", boost::program_options::variable_value(priorityNodeList, false)));\n }\n\n std::vector exclusiveNodeList = convertStringListToVector(Settings::instance().getExclusiveNodes());\n if (!exclusiveNodeList.empty()) {\n options.insert(std::make_pair(\"add-exclusive-node\", boost::program_options::variable_value(exclusiveNodeList, false)));\n }\n\n std::vector seedNodeList = convertStringListToVector(Settings::instance().getSeedNodes());\n if (!seedNodeList.empty()) {\n options.insert(std::make_pair(\"seed-node\", boost::program_options::variable_value(seedNodeList, false)));\n }\n\n options.insert(std::make_pair(\"hide-my-port\", boost::program_options::variable_value(hideMyPort, false)));\n options.insert(std::make_pair(\"data-dir\", boost::program_options::variable_value(dataDir, false)));\n int size = options.size();\n config.init(options);\n config.setTestnet(Settings::instance().isTestnet());\n return config;\n}\n\n}\n\n#include \"NodeAdapter.moc\"\nDelete NodeAdapter.cpp<|endoftext|>"} {"text":"#pragma once\n\n#include \"..\/std\/algorithm.hpp\"\n#include \"..\/std\/vector.hpp\"\n#include \"..\/base\/assert.hpp\"\n#include \"..\/base\/swap.hpp\"\n\ntemplate class buffer_vector\n{\nprivate:\n enum { USE_DYNAMIC = N + 1 };\n T m_static[N];\n size_t m_size;\n vector m_dynamic;\n\npublic:\n typedef T value_type;\n typedef T const & const_reference;\n typedef T & reference;\n\n buffer_vector() : m_size(0) {}\n explicit buffer_vector(size_t n, T c = T()) : m_size(0)\n {\n resize(n, c);\n }\n\n void reserve(size_t n)\n {\n if (m_size == USE_DYNAMIC || n > N)\n m_dynamic.reserve(n);\n }\n\n void resize(size_t n, T c = T())\n {\n if (m_size == USE_DYNAMIC)\n m_dynamic.resize(n);\n else\n {\n if (n <= N)\n {\n for (size_t i = m_size; i < n; ++i)\n m_static[i] = c;\n m_size = n;\n }\n else\n {\n m_dynamic.reserve(n);\n size_t const oldSize = m_size;\n SwitchToDynamic();\n m_dynamic.insert(m_dynamic.end(), n - oldSize, c);\n ASSERT_EQUAL(m_dynamic.size(), n, ());\n }\n }\n }\n\n void clear()\n {\n if (m_size == USE_DYNAMIC)\n m_dynamic.clear();\n else\n m_size = 0;\n }\n\n T const * data() const { return m_size == USE_DYNAMIC ? &m_dynamic[0] : &m_static[0]; }\n T * data() { return m_size == USE_DYNAMIC ? &m_dynamic[0] : &m_static[0]; }\n\n T const * begin() const { return data(); }\n T * begin() { return data(); }\n T const * end() const { return data() + size(); }\n T * end() { return data() + size(); }\n\n bool empty() const { return m_size == USE_DYNAMIC ? m_dynamic.empty() : m_size == 0; }\n size_t size() const { return m_size == USE_DYNAMIC ? m_dynamic.size() : m_size; }\n\n T const & front() const\n {\n ASSERT(!empty(), ());\n return *begin();\n }\n T & front()\n {\n ASSERT(!empty(), ());\n return *begin();\n }\n T const & back() const\n {\n ASSERT(!empty(), ());\n return *(end() - 1);\n }\n T & back()\n {\n ASSERT(!empty(), ());\n return *(end() - 1);\n }\n\n T const & operator[](size_t i) const\n {\n ASSERT_LESS(i, size(), ());\n return *(begin() + i);\n }\n T & operator[](size_t i)\n {\n ASSERT_LESS(i, size(), ());\n return *(begin() + i);\n }\n\n void swap(buffer_vector & rhs)\n {\n m_dynamic.swap(rhs.m_dynamic);\n Swap(m_size, rhs.m_size);\n for (size_t i = 0; i < N; ++i)\n Swap(m_static[i], rhs.m_static[i]);\n }\n\n void push_back(T const & t)\n {\n if (m_size == USE_DYNAMIC)\n m_dynamic.push_back(t);\n else\n {\n if (m_size < N)\n m_static[m_size++] = t;\n else\n {\n ASSERT_EQUAL(m_size, N, ());\n m_dynamic.reserve(N + 1);\n SwitchToDynamic();\n m_dynamic.push_back(t);\n ASSERT_EQUAL(m_dynamic.size(), N + 1, ());\n }\n }\n }\n\n void pop_back()\n {\n if (m_size == USE_DYNAMIC)\n m_dynamic.pop_back();\n else\n {\n ASSERT_GREATER(m_size, 0, ());\n --m_size;\n }\n }\n\n template void insert(T const * where, IterT beg, IterT end)\n {\n ptrdiff_t const pos = where - data();\n ASSERT_GREATER_OR_EQUAL(pos, 0, ());\n ASSERT_LESS_OR_EQUAL(pos, size(), ());\n if (m_size == USE_DYNAMIC)\n m_dynamic.insert(m_dynamic.begin() + pos, beg, end);\n else\n {\n size_t const n = end - beg;\n if (m_size + n <= N)\n {\n if (pos != m_size)\n for (ptrdiff_t i = m_size - 1; i >= pos; --i)\n Swap(m_static[i], m_static[i + n]);\n\n m_size += n;\n T * writableWhere = &m_static[0] + pos;\n ASSERT_EQUAL(where, writableWhere, ());\n while (beg != end)\n *(writableWhere++) = *(beg++);\n }\n else\n {\n m_dynamic.reserve(m_size + n);\n SwitchToDynamic();\n m_dynamic.insert(m_dynamic.begin() + pos, beg, end);\n ASSERT_EQUAL(m_dynamic.size(), m_dynamic.capacity(), ());\n }\n }\n }\n\nprivate:\n void SwitchToDynamic()\n {\n ASSERT_NOT_EQUAL(m_size, USE_DYNAMIC, ());\n ASSERT_EQUAL(m_dynamic.size(), 0, ());\n m_dynamic.insert(m_dynamic.end(), m_size, T());\n for (size_t i = 0; i < m_size; ++i)\n Swap(m_static[i], m_dynamic[i]);\n m_size = USE_DYNAMIC;\n }\n};\n\ntemplate \nvoid swap(buffer_vector & r1, buffer_vector & r2) { r1.swap(r2); }\n\ntemplate \ninline string debug_print(buffer_vector const & v)\n{\n return ::my::impl::DebugPrintSequence(v.data(), v.data() + v.size());\n}\nAlmost no-op, fix compilation issue.#pragma once\n\n#include \"..\/std\/algorithm.hpp\"\n#include \"..\/std\/vector.hpp\"\n#include \"..\/base\/assert.hpp\"\n#include \"..\/base\/swap.hpp\"\n\ntemplate class buffer_vector\n{\nprivate:\n enum { USE_DYNAMIC = N + 1 };\n T m_static[N];\n size_t m_size;\n vector m_dynamic;\n\npublic:\n typedef T value_type;\n typedef T const & const_reference;\n typedef T & reference;\n\n buffer_vector() : m_size(0) {}\n explicit buffer_vector(size_t n, T c = T()) : m_size(0)\n {\n resize(n, c);\n }\n\n void reserve(size_t n)\n {\n if (m_size == USE_DYNAMIC || n > N)\n m_dynamic.reserve(n);\n }\n\n void resize(size_t n, T c = T())\n {\n if (m_size == USE_DYNAMIC)\n m_dynamic.resize(n);\n else\n {\n if (n <= N)\n {\n for (size_t i = m_size; i < n; ++i)\n m_static[i] = c;\n m_size = n;\n }\n else\n {\n m_dynamic.reserve(n);\n size_t const oldSize = m_size;\n SwitchToDynamic();\n m_dynamic.insert(m_dynamic.end(), n - oldSize, c);\n ASSERT_EQUAL(m_dynamic.size(), n, ());\n }\n }\n }\n\n void clear()\n {\n if (m_size == USE_DYNAMIC)\n m_dynamic.clear();\n else\n m_size = 0;\n }\n\n T const * data() const { return m_size == USE_DYNAMIC ? &m_dynamic[0] : &m_static[0]; }\n T * data() { return m_size == USE_DYNAMIC ? &m_dynamic[0] : &m_static[0]; }\n\n T const * begin() const { return data(); }\n T * begin() { return data(); }\n T const * end() const { return data() + size(); }\n T * end() { return data() + size(); }\n\n bool empty() const { return m_size == USE_DYNAMIC ? m_dynamic.empty() : m_size == 0; }\n size_t size() const { return m_size == USE_DYNAMIC ? m_dynamic.size() : m_size; }\n\n T const & front() const\n {\n ASSERT(!empty(), ());\n return *begin();\n }\n T & front()\n {\n ASSERT(!empty(), ());\n return *begin();\n }\n T const & back() const\n {\n ASSERT(!empty(), ());\n return *(end() - 1);\n }\n T & back()\n {\n ASSERT(!empty(), ());\n return *(end() - 1);\n }\n\n T const & operator[](size_t i) const\n {\n ASSERT_LESS(i, size(), ());\n return *(begin() + i);\n }\n T & operator[](size_t i)\n {\n ASSERT_LESS(i, size(), ());\n return *(begin() + i);\n }\n\n void swap(buffer_vector & rhs)\n {\n m_dynamic.swap(rhs.m_dynamic);\n Swap(m_size, rhs.m_size);\n for (size_t i = 0; i < N; ++i)\n Swap(m_static[i], rhs.m_static[i]);\n }\n\n void push_back(T const & t)\n {\n if (m_size == USE_DYNAMIC)\n m_dynamic.push_back(t);\n else\n {\n if (m_size < N)\n m_static[m_size++] = t;\n else\n {\n ASSERT_EQUAL(m_size, N, ());\n m_dynamic.reserve(N + 1);\n SwitchToDynamic();\n m_dynamic.push_back(t);\n ASSERT_EQUAL(m_dynamic.size(), N + 1, ());\n }\n }\n }\n\n void pop_back()\n {\n if (m_size == USE_DYNAMIC)\n m_dynamic.pop_back();\n else\n {\n ASSERT_GREATER(m_size, 0, ());\n --m_size;\n }\n }\n\n template void insert(T const * where, IterT beg, IterT end)\n {\n ptrdiff_t const pos = where - data();\n ASSERT_GREATER_OR_EQUAL(pos, 0, ());\n ASSERT_LESS_OR_EQUAL(pos, size(), ());\n if (m_size == USE_DYNAMIC)\n m_dynamic.insert(m_dynamic.begin() + pos, beg, end);\n else\n {\n size_t const n = end - beg;\n if (m_size + n <= N)\n {\n if (pos != m_size)\n for (ptrdiff_t i = m_size - 1; i >= pos; --i)\n Swap(m_static[i], m_static[i + n]);\n\n m_size += n;\n T * writableWhere = &m_static[0] + pos;\n ASSERT_EQUAL(where, writableWhere, ());\n while (beg != end)\n *(writableWhere++) = *(beg++);\n }\n else\n {\n m_dynamic.reserve(m_size + n);\n SwitchToDynamic();\n m_dynamic.insert(m_dynamic.begin() + pos, beg, end);\n ASSERT_EQUAL(m_dynamic.size(), m_dynamic.capacity(), ());\n }\n }\n }\n\nprivate:\n void SwitchToDynamic()\n {\n ASSERT_NOT_EQUAL(m_size, static_cast(USE_DYNAMIC), ());\n ASSERT_EQUAL(m_dynamic.size(), 0, ());\n m_dynamic.insert(m_dynamic.end(), m_size, T());\n for (size_t i = 0; i < m_size; ++i)\n Swap(m_static[i], m_dynamic[i]);\n m_size = USE_DYNAMIC;\n }\n};\n\ntemplate \nvoid swap(buffer_vector & r1, buffer_vector & r2) { r1.swap(r2); }\n\ntemplate \ninline string debug_print(buffer_vector const & v)\n{\n return ::my::impl::DebugPrintSequence(v.data(), v.data() + v.size());\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"base\/get_line.hpp\"\n\n#include \n\nnamespace principia {\nnamespace base {\n\nnamespace {\n\nint constexpr kBufferSize = 100;\n\nstd::string GetLineWithSize(std::size_t const size,\n not_null const stream) {\n char* buffer = new char[size];\n if (!stream->getline(buffer, size).eof() && stream->fail()) {\n stream->clear();\n std::string string_buffer(buffer);\n string_buffer += GetLineWithSize(2 * size, stream);\n return std::move(string_buffer);\n }\n return buffer;\n}\n\n} \/\/ namespace\n\nstd::string GetLine(not_null const stream) {\n return GetLineWithSize(kBufferSize, stream);\n}\n\n} \/\/ namespace base\n} \/\/ namespace principia\nUnique ptr.#pragma once\n\n#include \"base\/get_line.hpp\"\n\n#include \n\nnamespace principia {\nnamespace base {\n\nnamespace {\n\nint constexpr kBufferSize = 200;\n\nstd::string GetLineWithSize(std::size_t const size,\n not_null const stream) {\n std::unique_ptr buffer(new char[size]);\n if (!stream->getline(&buffer[0], size).eof() && stream->fail()) {\n stream->clear();\n std::string string_buffer(buffer.get());\n string_buffer += GetLineWithSize(2 * size, stream);\n return std::move(string_buffer);\n } else {\n std::string string_buffer(buffer.get());\n return std::move(string_buffer);\n }\n}\n\n} \/\/ namespace\n\nstd::string GetLine(not_null const stream) {\n return GetLineWithSize(kBufferSize, stream);\n}\n\n} \/\/ namespace base\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"sixtracklib\/testlib.h\"\n#include \"sixtracklib\/sixtracklib.hpp\"\n\nint main( int argc, char* argv[] )\n{\n namespace st = sixtrack;\n\n using size_t = st::Buffer::size_type;\n using track_job_t = st::TrackJobCpu;\n\n st::Buffer input_pb;\n st::Buffer pb;\n st::Buffer eb;\n\n st::Particles* particles = nullptr;\n\n int NUM_PARTICLES = 0;\n int NUM_TURNS = 10;\n int NUM_TURNS_ELEM_BY_ELEM = 3;\n int OUTPUT_SKIP = 1;\n int track_status = 0;\n\n \/* -------------------------------------------------------------------- *\/\n \/* Read command line parameters *\/\n\n if( argc < 3 )\n {\n std::cout << \"Usage: \" << argv[ 0 ]\n << \" PATH_TO_PARTICLES PATH_TO_BEAM_ELEMENTS\" << std::endl;\n return 0;\n }\n\n if( ( argc >= 3 ) &&\n ( argv[ 1 ] != nullptr ) && ( std::strlen( argv[ 1 ] ) > 0u ) &&\n ( argv[ 2 ] != nullptr ) && ( std::strlen( argv[ 2 ] ) > 0u ) )\n {\n input_pb.readFromFile( argv[ 1 ] );\n eb.readFromFile( argv[ 2 ] );\n\n NUM_PARTICLES = st::Particles::FromBuffer(\n input_pb, 0u )->getNumParticles();\n }\n\n \/* --------------------------------------------------------------------- *\/\n \/* Prepare input and tracking data from run-time parameters: *\/\n\n std::printf(\"%-30s = %10d\\n\",\"NUM_PARTICLES\",NUM_PARTICLES);\n std::printf(\"%-30s = %10d\\n\",\"NUM_TURNS\",NUM_TURNS);\n std::printf(\"%-30s = %10d\\n\",\"NUM_TURNS_ELEM_BY_ELEM\",NUM_TURNS_ELEM_BY_ELEM);\n std::printf(\"%-30s = %10d\\n\",\"OUTPUT_SKIP\", OUTPUT_SKIP);\n\n if( NUM_PARTICLES >= 0 )\n {\n particles = pb.createNew< st::Particles >(\n st::Particles::FromBuffer( input_pb, 0u )->getNumParticles() );\n }\n\n if( ( eb.getNumObjects() > size_t{ 0 } ) &&\n ( NUM_TURNS > NUM_TURNS_ELEM_BY_ELEM ) )\n {\n st::BeamMonitor* beam_monitor = eb.createNew< st::BeamMonitor >();\n beam_monitor->setNumStores( NUM_TURNS - NUM_TURNS_ELEM_BY_ELEM );\n beam_monitor->setStart( NUM_TURNS_ELEM_BY_ELEM );\n beam_monitor->setSkip( OUTPUT_SKIP );\n beam_monitor->setIsRolling( true );\n }\n\n \/* ********************************************************************* *\/\n \/* **** PERFORM TRACKING OPERATIONS ******* *\/\n \/* ********************************************************************* *\/\n\n if( ( particles != nullptr ) && ( NUM_PARTICLES > 0 ) && ( NUM_TURNS > 0 ) )\n {\n \/* Create the track_job *\/\n track_job_t job( pb, eb, nullptr, NUM_TURNS_ELEM_BY_ELEM );\n\n if( NUM_TURNS_ELEM_BY_ELEM > 0 )\n {\n track_status |= st::trackElemByElem( job, NUM_TURNS_ELEM_BY_ELEM );\n }\n\n if( NUM_TURNS > NUM_TURNS_ELEM_BY_ELEM )\n {\n track_status |= st::track( job, NUM_TURNS );\n }\n\n \/* ****************************************************************** *\/\n \/* **** PERFORM OUTPUT OPERATIONS ****** *\/\n \/* ****************************************************************** *\/\n\n \/* NOTE: for the CPU Track Job, collect (currently) performs no\n * operations. Since this *might* change in the future, it's\n * mandated to always call NS(TrackJobCpu_collect)() before\n * accessing the particles, the beam elements or the\n * output buffer *\/\n\n st::collect( job );\n\n if( track_status == 0 )\n {\n st::Buffer* out_buffer = nullptr;\n\n if( job.hasOutputBuffer() )\n {\n out_buffer = job.ptrOutputBuffer();\n }\n\n if( job.hasElemByElemOutput() )\n {\n ::st_ElemByElemConfig const* elem_by_elem_config =\n job.ptrElemByElemConfig();\n\n size_t const out_offset = job.elemByElemOutputBufferOffset();\n\n st_Particles* elem_by_elem_output = st::Particles::FromBuffer(\n *out_buffer, out_offset );\n\n \/* ::st_Particles_print_out(\n elem_by_elem_output->getCApiPtr() ); *\/\n\n ( void )elem_by_elem_config;\n ( void )elem_by_elem_output;\n }\n\n if( job.hasBeamMonitorOutput() )\n {\n st_size_t const bemon_start_index =\n job.beamMonitorsOutputBufferOffset();\n\n st_size_t const bemon_stop_index =\n bemon_start_index + job.numBeamMonitors();\n\n st_size_t ii = bemon_start_index;\n\n for( ; ii < bemon_stop_index ; ++ii )\n {\n st::Particles* out_particles = st::Particles::FromBuffer(\n *out_buffer, ii );\n\n \/* ::st_Particles_print_out(\n out_particles->getCApiPtr() ); *\/\n\n ( void )out_particles;\n }\n }\n }\n }\n\n return 0;\n}\n\n\/* end: examples\/cxx\/track_job_cpu.cpp *\/\nexamples\/cxx: use updated public trackJob API for example#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"sixtracklib\/testlib.h\"\n#include \"sixtracklib\/sixtracklib.hpp\"\n\nint main( int argc, char* argv[] )\n{\n namespace st = sixtrack;\n\n using size_t = st::Buffer::size_type;\n using track_job_t = st::TrackJobCpu;\n\n st::Buffer input_pb;\n st::Buffer pb;\n st::Buffer eb;\n\n st::Particles* particles = nullptr;\n\n int NUM_PARTICLES = 0;\n int NUM_TURNS = 10;\n int NUM_TURNS_ELEM_BY_ELEM = 3;\n int OUTPUT_SKIP = 1;\n int track_status = 0;\n\n \/* -------------------------------------------------------------------- *\/\n \/* Read command line parameters *\/\n\n if( argc < 3 )\n {\n std::cout << \"Usage: \" << argv[ 0 ]\n << \" PATH_TO_PARTICLES PATH_TO_BEAM_ELEMENTS\" << std::endl;\n return 0;\n }\n\n if( ( argc >= 3 ) &&\n ( argv[ 1 ] != nullptr ) && ( std::strlen( argv[ 1 ] ) > 0u ) &&\n ( argv[ 2 ] != nullptr ) && ( std::strlen( argv[ 2 ] ) > 0u ) )\n {\n input_pb.readFromFile( argv[ 1 ] );\n eb.readFromFile( argv[ 2 ] );\n\n NUM_PARTICLES = st::Particles::FromBuffer(\n input_pb, 0u )->getNumParticles();\n }\n\n \/* --------------------------------------------------------------------- *\/\n \/* Prepare input and tracking data from run-time parameters: *\/\n\n std::printf(\"%-30s = %10d\\n\",\"NUM_PARTICLES\",NUM_PARTICLES);\n std::printf(\"%-30s = %10d\\n\",\"NUM_TURNS\",NUM_TURNS);\n std::printf(\"%-30s = %10d\\n\",\"NUM_TURNS_ELEM_BY_ELEM\",NUM_TURNS_ELEM_BY_ELEM);\n std::printf(\"%-30s = %10d\\n\",\"OUTPUT_SKIP\", OUTPUT_SKIP);\n\n if( NUM_PARTICLES >= 0 )\n {\n particles = pb.createNew< st::Particles >(\n st::Particles::FromBuffer( input_pb, 0u )->getNumParticles() );\n }\n\n if( ( eb.getNumObjects() > size_t{ 0 } ) &&\n ( NUM_TURNS > NUM_TURNS_ELEM_BY_ELEM ) )\n {\n st::BeamMonitor* beam_monitor = eb.createNew< st::BeamMonitor >();\n beam_monitor->setNumStores( NUM_TURNS - NUM_TURNS_ELEM_BY_ELEM );\n beam_monitor->setStart( NUM_TURNS_ELEM_BY_ELEM );\n beam_monitor->setSkip( OUTPUT_SKIP );\n beam_monitor->setIsRolling( true );\n }\n\n \/* ********************************************************************* *\/\n \/* **** PERFORM TRACKING OPERATIONS ******* *\/\n \/* ********************************************************************* *\/\n\n if( ( particles != nullptr ) && ( NUM_PARTICLES > 0 ) && ( NUM_TURNS > 0 ) )\n {\n \/* Create the track_job *\/\n track_job_t job( pb, eb, nullptr, NUM_TURNS_ELEM_BY_ELEM );\n\n if( NUM_TURNS_ELEM_BY_ELEM > 0 )\n {\n track_status |= st::trackElemByElem( job, NUM_TURNS_ELEM_BY_ELEM );\n }\n\n if( NUM_TURNS > NUM_TURNS_ELEM_BY_ELEM )\n {\n track_status |= st::trackUntil( job, NUM_TURNS );\n }\n\n \/* ****************************************************************** *\/\n \/* **** PERFORM OUTPUT OPERATIONS ****** *\/\n \/* ****************************************************************** *\/\n\n \/* NOTE: for the CPU Track Job, collect (currently) performs no\n * operations. Since this *might* change in the future, it's\n * mandated to always call NS(TrackJobCpu_collect)() before\n * accessing the particles, the beam elements or the\n * output buffer *\/\n\n st::collect( job );\n\n if( track_status == 0 )\n {\n st::Buffer* out_buffer = nullptr;\n\n if( job.hasOutputBuffer() )\n {\n out_buffer = job.ptrOutputBuffer();\n }\n\n if( job.hasElemByElemOutput() )\n {\n ::st_ElemByElemConfig const* elem_by_elem_config =\n job.ptrElemByElemConfig();\n\n size_t const out_offset = job.elemByElemOutputBufferOffset();\n\n st_Particles* elem_by_elem_output = st::Particles::FromBuffer(\n *out_buffer, out_offset );\n\n \/* ::st_Particles_print_out(\n elem_by_elem_output->getCApiPtr() ); *\/\n\n ( void )elem_by_elem_config;\n ( void )elem_by_elem_output;\n }\n\n if( job.hasBeamMonitorOutput() )\n {\n st_size_t const bemon_start_index =\n job.beamMonitorsOutputBufferOffset();\n\n st_size_t const bemon_stop_index =\n bemon_start_index + job.numBeamMonitors();\n\n st_size_t ii = bemon_start_index;\n\n for( ; ii < bemon_stop_index ; ++ii )\n {\n st::Particles* out_particles = st::Particles::FromBuffer(\n *out_buffer, ii );\n\n \/* ::st_Particles_print_out(\n out_particles->getCApiPtr() ); *\/\n\n ( void )out_particles;\n }\n }\n }\n }\n\n return 0;\n}\n\n\/* end: examples\/cxx\/track_job_cpu.cpp *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: animationcommandnode.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2007-07-17 14:47:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_slideshow.hxx\"\n\n\/\/ must be first\n#include \n#include \n#include \n\n#include \"animationcommandnode.hxx\"\n#include \"delayevent.hxx\"\n#include \"tools.hxx\"\n#include \"nodetools.hxx\"\n\n#include \n\nnamespace slideshow {\nnamespace internal {\n\nvoid AnimationCommandNode::dispose()\n{\n mxCommandNode.clear();\n BaseNode::dispose();\n}\n\nvoid AnimationCommandNode::activate_()\n{\n namespace EffectCommands = com::sun::star::presentation::EffectCommands;\n\n switch( mxCommandNode->getCommand() ) {\n \/\/ the command is user defined\n case EffectCommands::CUSTOM: break;\n \/\/ the command is an ole verb.\n case EffectCommands::VERB: break;\n \/\/ the command starts playing on a media object\n case EffectCommands::PLAY: break;\n \/\/ the command toggles the pause status on a media object\n case EffectCommands::TOGGLEPAUSE: break;\n \/\/ the command stops the animation on a media object\n case EffectCommands::STOP: break;\n \/\/ the command stops all currently running sound effects\n case EffectCommands::STOPAUDIO:\n getContext().mrEventMultiplexer.notifyCommandStopAudio( getSelf() );\n break;\n }\n\n \/\/ deactivate ASAP:\n scheduleDeactivationEvent(\n makeEvent( boost::bind( &AnimationNode::deactivate, getSelf() ) ) );\n}\n\nbool AnimationCommandNode::hasPendingAnimation() const\n{\n return false;\n}\n\n} \/\/ namespace internal\n} \/\/ namespace slideshow\nINTEGRATION: CWS changefileheader (1.8.46); FILE MERGED 2008\/03\/31 14:00:17 rt 1.8.46.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: animationcommandnode.cxx,v $\n * $Revision: 1.9 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_slideshow.hxx\"\n\n\/\/ must be first\n#include \n#include \n#include \n\n#include \"animationcommandnode.hxx\"\n#include \"delayevent.hxx\"\n#include \"tools.hxx\"\n#include \"nodetools.hxx\"\n\n#include \n\nnamespace slideshow {\nnamespace internal {\n\nvoid AnimationCommandNode::dispose()\n{\n mxCommandNode.clear();\n BaseNode::dispose();\n}\n\nvoid AnimationCommandNode::activate_()\n{\n namespace EffectCommands = com::sun::star::presentation::EffectCommands;\n\n switch( mxCommandNode->getCommand() ) {\n \/\/ the command is user defined\n case EffectCommands::CUSTOM: break;\n \/\/ the command is an ole verb.\n case EffectCommands::VERB: break;\n \/\/ the command starts playing on a media object\n case EffectCommands::PLAY: break;\n \/\/ the command toggles the pause status on a media object\n case EffectCommands::TOGGLEPAUSE: break;\n \/\/ the command stops the animation on a media object\n case EffectCommands::STOP: break;\n \/\/ the command stops all currently running sound effects\n case EffectCommands::STOPAUDIO:\n getContext().mrEventMultiplexer.notifyCommandStopAudio( getSelf() );\n break;\n }\n\n \/\/ deactivate ASAP:\n scheduleDeactivationEvent(\n makeEvent( boost::bind( &AnimationNode::deactivate, getSelf() ) ) );\n}\n\nbool AnimationCommandNode::hasPendingAnimation() const\n{\n return false;\n}\n\n} \/\/ namespace internal\n} \/\/ namespace slideshow\n<|endoftext|>"} {"text":"#include \n#include \n#ifndef WIN32\n#include \n#endif\n#include \"InferenceEngineManager.hpp\"\n\nnamespace fast {\n\nbool InferenceEngineManager::m_loaded = false;\nstd::unordered_map> InferenceEngineManager::m_engines;\n\n#ifdef WIN32\n\/\/Returns the last Win32 error, in string format. Returns an empty string if there is no error.\nstd::string GetLastErrorAsString()\n{\n \/\/Get the error message, if any.\n DWORD errorMessageID = ::GetLastError();\n if(errorMessageID == 0)\n return std::string(); \/\/No error message has been recorded\n\n LPSTR messageBuffer = nullptr;\n size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);\n\n std::string message(messageBuffer, size);\n\n \/\/Free the buffer.\n LocalFree(messageBuffer);\n\n return message;\n}\n#endif\n\nstd::vector InferenceEngineManager::getEngineList() {\n loadAll();\n std::vector list;\n for(auto&& engine : m_engines)\n list.push_back(engine.first);\n return list;\n}\n\nvoid InferenceEngineManager::loadAll() {\n if(m_loaded) {\n return;\n }\n std::string prefix = \"InferenceEngine\";\n#ifndef WIN32\n prefix = \"lib\" + prefix;\n#endif\n Reporter::info() << \"Loading inference engines in folder \" << Config::getLibraryPath() << Reporter::end();\n for(auto&& item : getDirectoryList(Config::getLibraryPath(), true, false)) {\n if(item.substr(0, prefix.size()) == prefix) {\n std::string name = item.substr(prefix.size(), item.rfind('.') - prefix.size());\n Reporter::info() << \"Loading inference engine \" << name << \" from shared library \" << item << Reporter::end();\n#ifdef WIN32\n SetErrorMode(SEM_FAILCRITICALERRORS); \/\/ TODO To avoid diaglog box, when not able to load a DLL\n auto handle = LoadLibrary(item.c_str());\n if(!handle) {\n Reporter::warning() << \"Failed to load plugin because \" << GetLastErrorAsString() << Reporter::end();\n continue;\n }\n auto load = (InferenceEngine* (*)())GetProcAddress(handle, \"load\");\n if(!load) {\n FreeLibrary(handle);\n Reporter::warning() << \"Failed to get adress to load function because \" << GetLastErrorAsString() << Reporter::end();\n continue;\n }\n#else\n auto handle = dlopen(item.c_str(), RTLD_LAZY);\n if(!handle) {\n Reporter::warning() << \"Failed to load plugin because \" << dlerror() << Reporter::end();\n continue;\n }\n auto load = (InferenceEngine* (*)())dlsym(handle, \"load\");\n if(!load) {\n dlclose(handle);\n Reporter::warning() << \"Failed to get address of load function because \" << Reporter::end();\/\/ dlerror() << Reporter::end();\n continue;\n }\n#endif\n m_engines[name] = load;\n }\n }\n m_loaded = true;\n}\n\n\nstd::shared_ptr InferenceEngineManager::loadBestAvailableEngine() {\n loadAll();\n if(m_engines.empty())\n throw Exception(\"No inference engines available on the system\");\n\n if(isEngineAvailable(\"TensorFlow\")) {\n \/\/ Default is tensorflow if GPU support is enabled\n auto engine = loadEngine(\"TensorFlow\");\n auto devices = engine->getDeviceList();\n for (auto &&device : devices) {\n if (device.type == InferenceDeviceType::GPU)\n return engine;\n }\n }\n\n if(isEngineAvailable(\"TensorRT\"))\n return loadEngine(\"TensorRT\");\n\n return loadEngine(getEngineList().front());\n}\n\nstd::shared_ptr InferenceEngineManager::loadBestAvailableEngine(ModelFormat modelFormat) {\n loadAll();\n if(m_engines.empty())\n throw Exception(\"No inference engines available on the system\");\n\n if(isEngineAvailable(\"TensorFlow\") && loadEngine(\"TensorFlow\")->isModelFormatSupported(modelFormat)) {\n \/\/ Default is tensorflow if GPU support is enabled\n auto engine = loadEngine(\"TensorFlow\");\n auto devices = engine->getDeviceList();\n for (auto &&device : devices) {\n if (device.type == InferenceDeviceType::GPU)\n return engine;\n }\n }\n\n if(isEngineAvailable(\"TensorRT\") && loadEngine(\"TensorRT\")->isModelFormatSupported(modelFormat))\n return loadEngine(\"TensorRT\");\n\n for(auto name : getEngineList()) {\n auto engine = loadEngine(name);\n if(engine->isModelFormatSupported(modelFormat))\n return engine;\n }\n throw Exception(\"No engine for model format found\");\n}\n\n\n\nbool InferenceEngineManager::isEngineAvailable(std::string name) {\n loadAll();\n return m_engines.count(name) > 0;\n}\n\nstd::shared_ptr InferenceEngineManager::loadEngine(std::string name) {\n loadAll();\n if(m_engines.count(name) == 0)\n throw Exception(\"Inference engine with name \" + name + \" is not available\");\n \/\/ Call the load function which the map stores a handle to\n return std::shared_ptr(m_engines.at(name)());\n}\n\n}Check for AVX2 support before loading TensorFlow#include \n#include \n#ifdef WIN32\n\/\/ For TensorFlow AVX2 check - Taken from https:\/\/docs.microsoft.com\/en-us\/cpp\/intrinsics\/cpuid-cpuidex?view=msvc-160\n#include \n#include \n#include \n#include \n#include \nnamespace fast {\nclass InstructionSet\n{\n \/\/ forward declarations\n class InstructionSet_Internal;\n\npublic:\n \/\/ getters\n static std::string Vendor(void) { return CPU_Rep.vendor_; }\n static std::string Brand(void) { return CPU_Rep.brand_; }\n\n static bool SSE3(void) { return CPU_Rep.f_1_ECX_[0]; }\n static bool PCLMULQDQ(void) { return CPU_Rep.f_1_ECX_[1]; }\n static bool MONITOR(void) { return CPU_Rep.f_1_ECX_[3]; }\n static bool SSSE3(void) { return CPU_Rep.f_1_ECX_[9]; }\n static bool FMA(void) { return CPU_Rep.f_1_ECX_[12]; }\n static bool CMPXCHG16B(void) { return CPU_Rep.f_1_ECX_[13]; }\n static bool SSE41(void) { return CPU_Rep.f_1_ECX_[19]; }\n static bool SSE42(void) { return CPU_Rep.f_1_ECX_[20]; }\n static bool MOVBE(void) { return CPU_Rep.f_1_ECX_[22]; }\n static bool POPCNT(void) { return CPU_Rep.f_1_ECX_[23]; }\n static bool AES(void) { return CPU_Rep.f_1_ECX_[25]; }\n static bool XSAVE(void) { return CPU_Rep.f_1_ECX_[26]; }\n static bool OSXSAVE(void) { return CPU_Rep.f_1_ECX_[27]; }\n static bool AVX(void) { return CPU_Rep.f_1_ECX_[28]; }\n static bool F16C(void) { return CPU_Rep.f_1_ECX_[29]; }\n static bool RDRAND(void) { return CPU_Rep.f_1_ECX_[30]; }\n\n static bool MSR(void) { return CPU_Rep.f_1_EDX_[5]; }\n static bool CX8(void) { return CPU_Rep.f_1_EDX_[8]; }\n static bool SEP(void) { return CPU_Rep.f_1_EDX_[11]; }\n static bool CMOV(void) { return CPU_Rep.f_1_EDX_[15]; }\n static bool CLFSH(void) { return CPU_Rep.f_1_EDX_[19]; }\n static bool MMX(void) { return CPU_Rep.f_1_EDX_[23]; }\n static bool FXSR(void) { return CPU_Rep.f_1_EDX_[24]; }\n static bool SSE(void) { return CPU_Rep.f_1_EDX_[25]; }\n static bool SSE2(void) { return CPU_Rep.f_1_EDX_[26]; }\n\n static bool FSGSBASE(void) { return CPU_Rep.f_7_EBX_[0]; }\n static bool BMI1(void) { return CPU_Rep.f_7_EBX_[3]; }\n static bool HLE(void) { return CPU_Rep.isIntel_ && CPU_Rep.f_7_EBX_[4]; }\n static bool AVX2(void) { return CPU_Rep.f_7_EBX_[5]; }\n static bool BMI2(void) { return CPU_Rep.f_7_EBX_[8]; }\n static bool ERMS(void) { return CPU_Rep.f_7_EBX_[9]; }\n static bool INVPCID(void) { return CPU_Rep.f_7_EBX_[10]; }\n static bool RTM(void) { return CPU_Rep.isIntel_ && CPU_Rep.f_7_EBX_[11]; }\n static bool AVX512F(void) { return CPU_Rep.f_7_EBX_[16]; }\n static bool RDSEED(void) { return CPU_Rep.f_7_EBX_[18]; }\n static bool ADX(void) { return CPU_Rep.f_7_EBX_[19]; }\n static bool AVX512PF(void) { return CPU_Rep.f_7_EBX_[26]; }\n static bool AVX512ER(void) { return CPU_Rep.f_7_EBX_[27]; }\n static bool AVX512CD(void) { return CPU_Rep.f_7_EBX_[28]; }\n static bool SHA(void) { return CPU_Rep.f_7_EBX_[29]; }\n\n static bool PREFETCHWT1(void) { return CPU_Rep.f_7_ECX_[0]; }\n\n static bool LAHF(void) { return CPU_Rep.f_81_ECX_[0]; }\n static bool LZCNT(void) { return CPU_Rep.isIntel_ && CPU_Rep.f_81_ECX_[5]; }\n static bool ABM(void) { return CPU_Rep.isAMD_ && CPU_Rep.f_81_ECX_[5]; }\n static bool SSE4a(void) { return CPU_Rep.isAMD_ && CPU_Rep.f_81_ECX_[6]; }\n static bool XOP(void) { return CPU_Rep.isAMD_ && CPU_Rep.f_81_ECX_[11]; }\n static bool TBM(void) { return CPU_Rep.isAMD_ && CPU_Rep.f_81_ECX_[21]; }\n\n static bool SYSCALL(void) { return CPU_Rep.isIntel_ && CPU_Rep.f_81_EDX_[11]; }\n static bool MMXEXT(void) { return CPU_Rep.isAMD_ && CPU_Rep.f_81_EDX_[22]; }\n static bool RDTSCP(void) { return CPU_Rep.isIntel_ && CPU_Rep.f_81_EDX_[27]; }\n static bool _3DNOWEXT(void) { return CPU_Rep.isAMD_ && CPU_Rep.f_81_EDX_[30]; }\n static bool _3DNOW(void) { return CPU_Rep.isAMD_ && CPU_Rep.f_81_EDX_[31]; }\n\nprivate:\n static const InstructionSet_Internal CPU_Rep;\n\n class InstructionSet_Internal\n {\n public:\n InstructionSet_Internal()\n : nIds_{ 0 },\n nExIds_{ 0 },\n isIntel_{ false },\n isAMD_{ false },\n f_1_ECX_{ 0 },\n f_1_EDX_{ 0 },\n f_7_EBX_{ 0 },\n f_7_ECX_{ 0 },\n f_81_ECX_{ 0 },\n f_81_EDX_{ 0 },\n data_{},\n extdata_{}\n {\n \/\/int cpuInfo[4] = {-1};\n std::array cpui;\n\n \/\/ Calling __cpuid with 0x0 as the function_id argument\n \/\/ gets the number of the highest valid function ID.\n __cpuid(cpui.data(), 0);\n nIds_ = cpui[0];\n\n for (int i = 0; i <= nIds_; ++i)\n {\n __cpuidex(cpui.data(), i, 0);\n data_.push_back(cpui);\n }\n\n \/\/ Capture vendor string\n char vendor[0x20];\n memset(vendor, 0, sizeof(vendor));\n *reinterpret_cast(vendor) = data_[0][1];\n *reinterpret_cast(vendor + 4) = data_[0][3];\n *reinterpret_cast(vendor + 8) = data_[0][2];\n vendor_ = vendor;\n if (vendor_ == \"GenuineIntel\")\n {\n isIntel_ = true;\n }\n else if (vendor_ == \"AuthenticAMD\")\n {\n isAMD_ = true;\n }\n\n \/\/ load bitset with flags for function 0x00000001\n if (nIds_ >= 1)\n {\n f_1_ECX_ = data_[1][2];\n f_1_EDX_ = data_[1][3];\n }\n\n \/\/ load bitset with flags for function 0x00000007\n if (nIds_ >= 7)\n {\n f_7_EBX_ = data_[7][1];\n f_7_ECX_ = data_[7][2];\n }\n\n \/\/ Calling __cpuid with 0x80000000 as the function_id argument\n \/\/ gets the number of the highest valid extended ID.\n __cpuid(cpui.data(), 0x80000000);\n nExIds_ = cpui[0];\n\n char brand[0x40];\n memset(brand, 0, sizeof(brand));\n\n for (int i = 0x80000000; i <= nExIds_; ++i)\n {\n __cpuidex(cpui.data(), i, 0);\n extdata_.push_back(cpui);\n }\n\n \/\/ load bitset with flags for function 0x80000001\n if (nExIds_ >= 0x80000001)\n {\n f_81_ECX_ = extdata_[1][2];\n f_81_EDX_ = extdata_[1][3];\n }\n\n \/\/ Interpret CPU brand string if reported\n if (nExIds_ >= 0x80000004)\n {\n memcpy(brand, extdata_[2].data(), sizeof(cpui));\n memcpy(brand + 16, extdata_[3].data(), sizeof(cpui));\n memcpy(brand + 32, extdata_[4].data(), sizeof(cpui));\n brand_ = brand;\n }\n };\n\n int nIds_;\n int nExIds_;\n std::string vendor_;\n std::string brand_;\n bool isIntel_;\n bool isAMD_;\n std::bitset<32> f_1_ECX_;\n std::bitset<32> f_1_EDX_;\n std::bitset<32> f_7_EBX_;\n std::bitset<32> f_7_ECX_;\n std::bitset<32> f_81_ECX_;\n std::bitset<32> f_81_EDX_;\n std::vector> data_;\n std::vector> extdata_;\n };\n};\n}\n#else\n#include \n#endif\n#include \"InferenceEngineManager.hpp\"\n\nnamespace fast {\n\nbool InferenceEngineManager::m_loaded = false;\nstd::unordered_map> InferenceEngineManager::m_engines;\n\n#ifdef WIN32\n\/\/Returns the last Win32 error, in string format. Returns an empty string if there is no error.\nstd::string GetLastErrorAsString()\n{\n \/\/Get the error message, if any.\n DWORD errorMessageID = ::GetLastError();\n if(errorMessageID == 0)\n return std::string(); \/\/No error message has been recorded\n\n LPSTR messageBuffer = nullptr;\n size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);\n\n std::string message(messageBuffer, size);\n\n \/\/Free the buffer.\n LocalFree(messageBuffer);\n\n return message;\n}\n#endif\n\nstd::vector InferenceEngineManager::getEngineList() {\n loadAll();\n std::vector list;\n for(auto&& engine : m_engines)\n list.push_back(engine.first);\n return list;\n}\n\nvoid InferenceEngineManager::loadAll() {\n if(m_loaded) {\n return;\n }\n std::string prefix = \"InferenceEngine\";\n#ifndef WIN32\n prefix = \"lib\" + prefix;\n#endif\n Reporter::info() << \"Loading inference engines in folder \" << Config::getLibraryPath() << Reporter::end();\n for(auto&& item : getDirectoryList(Config::getLibraryPath(), true, false)) {\n if(item.substr(0, prefix.size()) == prefix) {\n std::string name = item.substr(prefix.size(), item.rfind('.') - prefix.size());\n Reporter::info() << \"Loading inference engine \" << name << \" from shared library \" << item << Reporter::end();\n#ifdef WIN32\n if(name == \"TensorFlow\") {\n if(!InstructionSet::AVX2()) {\n Reporter::warning() << \"You CPU does not support AVX2, unable to load TensorFlow inference engine.\" << Reporter::end();\n continue;\n }\n }\n SetErrorMode(SEM_FAILCRITICALERRORS); \/\/ TODO To avoid diaglog box, when not able to load a DLL\n auto handle = LoadLibrary(item.c_str());\n if(!handle) {\n Reporter::warning() << \"Failed to load plugin because \" << GetLastErrorAsString() << Reporter::end();\n continue;\n }\n auto load = (InferenceEngine* (*)())GetProcAddress(handle, \"load\");\n if(!load) {\n FreeLibrary(handle);\n Reporter::warning() << \"Failed to get adress to load function because \" << GetLastErrorAsString() << Reporter::end();\n continue;\n }\n#else\n if(name == \"TensorFlow\") {\n if(!__builtin_cpu_supports(\"avx2\")) {\n Reporter::warning() << \"You CPU does not support AVX2, unable to load TensorFlow inference engine.\" << Reporter::end();\n continue;\n }\n }\n auto handle = dlopen(item.c_str(), RTLD_LAZY);\n if(!handle) {\n Reporter::warning() << \"Failed to load plugin because \" << dlerror() << Reporter::end();\n continue;\n }\n auto load = (InferenceEngine* (*)())dlsym(handle, \"load\");\n if(!load) {\n dlclose(handle);\n Reporter::warning() << \"Failed to get address of load function because \" << Reporter::end();\/\/ dlerror() << Reporter::end();\n continue;\n }\n#endif\n m_engines[name] = load;\n }\n }\n m_loaded = true;\n}\n\n\nstd::shared_ptr InferenceEngineManager::loadBestAvailableEngine() {\n loadAll();\n if(m_engines.empty())\n throw Exception(\"No inference engines available on the system\");\n\n if(isEngineAvailable(\"TensorFlow\")) {\n \/\/ Default is tensorflow if GPU support is enabled\n auto engine = loadEngine(\"TensorFlow\");\n auto devices = engine->getDeviceList();\n for (auto &&device : devices) {\n if (device.type == InferenceDeviceType::GPU)\n return engine;\n }\n }\n\n if(isEngineAvailable(\"TensorRT\"))\n return loadEngine(\"TensorRT\");\n\n return loadEngine(getEngineList().front());\n}\n\nstd::shared_ptr InferenceEngineManager::loadBestAvailableEngine(ModelFormat modelFormat) {\n loadAll();\n if(m_engines.empty())\n throw Exception(\"No inference engines available on the system\");\n\n if(isEngineAvailable(\"TensorFlow\") && loadEngine(\"TensorFlow\")->isModelFormatSupported(modelFormat)) {\n \/\/ Default is tensorflow if GPU support is enabled\n auto engine = loadEngine(\"TensorFlow\");\n auto devices = engine->getDeviceList();\n for (auto &&device : devices) {\n if (device.type == InferenceDeviceType::GPU)\n return engine;\n }\n }\n\n if(isEngineAvailable(\"TensorRT\") && loadEngine(\"TensorRT\")->isModelFormatSupported(modelFormat))\n return loadEngine(\"TensorRT\");\n\n for(auto name : getEngineList()) {\n auto engine = loadEngine(name);\n if(engine->isModelFormatSupported(modelFormat))\n return engine;\n }\n throw Exception(\"No engine for model format found\");\n}\n\n\n\nbool InferenceEngineManager::isEngineAvailable(std::string name) {\n loadAll();\n return m_engines.count(name) > 0;\n}\n\nstd::shared_ptr InferenceEngineManager::loadEngine(std::string name) {\n loadAll();\n if(m_engines.count(name) == 0)\n throw Exception(\"Inference engine with name \" + name + \" is not available\");\n \/\/ Call the load function which the map stores a handle to\n return std::shared_ptr(m_engines.at(name)());\n}\n\n}<|endoftext|>"} {"text":"#include \"QtVmbViewer.h\"\n#include \n#include \n#include \n\n\/\/ Constructor\nQtVmbViewer::QtVmbViewer( QWidget *parent ) : QWidget( parent ), label( new QLabel ) {\n \/\/ Scale the image label\n label->setScaledContents( true );\n \/\/ Widget layout\n QVBoxLayout* layout = new QVBoxLayout( this );\n layout->addWidget( label );\n layout->setSizeConstraint( QLayout::SetFixedSize );\n \/\/ Create the camera\n camera = new VmbCamera( \"50-0503323406\" );\n \/\/ Connect the camera signal to get the received frame\n connect( camera, &VmbCamera::FrameReceived, this, &QtVmbViewer::GetFrame );\n \/\/ Open the camera\n camera->Open();\n \/\/ Create the image\n image = new QImage( camera->width, camera->height, QImage::Format_Indexed8 );\n \/\/ Create a indexed color table\n image->setColorCount( 256 );\n for( int i = 0; i < 256; i++ ) {\n image->setColor( i, qRgb(i, i, i) );\n }\n \/\/ Start acquisition\n camera->StartCapture();\n}\n\n\/\/ Destructor\nQtVmbViewer::~QtVmbViewer() {\n \/\/ Stop acquisition\n camera->StopCapture();\n \/\/ Close the camera\n camera->Close();\n \/\/ Delete the camera\n delete camera;\n \/\/ Delete the image\n delete image;\n}\n\n\/\/ Image callback\nvoid QtVmbViewer::GetFrame( const VmbFrame_t* frame_pointer ) {\n \/\/ Copy the camera frame to the widget image\n VmbUchar_t* pCursor = image->bits();\n VmbUchar_t* pInBuffer = (VmbUchar_t*)frame_pointer->buffer;\n for( int y=0; yheight; ++y ) {\n pCursor = image->scanLine( y );\n for( int x=0; xwidth; ++x ) {\n *pCursor = *pInBuffer;\n ++pCursor;\n ++pInBuffer;\n }\n }\n \/\/ Set the image to the label\n label->setPixmap( QPixmap::fromImage( *image ) );\n \/\/ Update the widget\n label->update();\n}\n\nCopy the camera frame buffer to the Qt image using memcpy.#include \"QtVmbViewer.h\"\n#include \n#include \n#include \n\n\/\/ Constructor\nQtVmbViewer::QtVmbViewer( QWidget *parent ) : QWidget( parent ), label( new QLabel ) {\n \/\/ Scale the image label\n label->setScaledContents( true );\n \/\/ Widget layout\n QVBoxLayout* layout = new QVBoxLayout( this );\n layout->addWidget( label );\n layout->setSizeConstraint( QLayout::SetFixedSize );\n \/\/ Create the camera\n camera = new VmbCamera( \"50-0503323406\" );\n \/\/ Connect the camera signal to get the received frame\n connect( camera, &VmbCamera::FrameReceived, this, &QtVmbViewer::GetFrame );\n \/\/ Open the camera\n camera->Open();\n \/\/ Create the image\n image = new QImage( camera->width, camera->height, QImage::Format_Indexed8 );\n \/\/ Create a indexed color table\n image->setColorCount( 256 );\n for( int i = 0; i < 256; i++ ) {\n image->setColor( i, qRgb(i, i, i) );\n }\n \/\/ Start acquisition\n camera->StartCapture();\n}\n\n\/\/ Destructor\nQtVmbViewer::~QtVmbViewer() {\n \/\/ Stop acquisition\n camera->StopCapture();\n \/\/ Close the camera\n camera->Close();\n \/\/ Delete the camera\n delete camera;\n \/\/ Delete the image\n delete image;\n}\n\n\/\/ Image callback\nvoid QtVmbViewer::GetFrame( const VmbFrame_t* frame_pointer ) {\n \/\/ Copy the camera frame buffer to the Qt image\n memcpy( image->bits(), frame_pointer->buffer, camera->height*camera->width );\n \/\/ Set the image to the label\n label->setPixmap( QPixmap::fromImage( *image ) );\n \/\/ Update the widget\n label->update();\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n#ifndef LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED\n#define LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED\n\n#include \n#include \/\/ for find_conversion_policy, etc\n#include \/\/ for decorated_type\n#include \/\/ for by_pointer, by_reference, etc\n#include \/\/ for is_nonconst_pointer, is_nonconst_reference, etc\n#include \/\/ for operator new\n\nnamespace luabind { namespace detail\n{\n\ttemplate\n\tstruct char_array\n\t{\n\t\tchar storage[N];\n\t};\n\n\ttemplate\n\tchar_array::type)> indirect_sizeof_test(by_reference);\n\n\ttemplate\n\tchar_array::type)> indirect_sizeof_test(by_const_reference);\n\n\ttemplate\n\tchar_array::type)> indirect_sizeof_test(by_pointer);\n\n\ttemplate\n\tchar_array::type)> indirect_sizeof_test(by_const_pointer);\n\n\ttemplate\n\tchar_array::type)> indirect_sizeof_test(by_value);\n\n\ttemplate\n\tstruct indirect_sizeof\n\t{\n\t\tstatic const int value = sizeof(indirect_sizeof_test(decorated_type()));\n\t};\n\t\n\tnamespace out_value_detail {\n\n\t\ttemplate< int Size >\n\t\tstruct temporary_storage_size {\n\t\t\t\n\t\t\ttemplate< typename T, typename... Args >\n\t\t\tvoid construct(Args&&... args)\n\t\t\t{\n\t\t\t\tnew (&m_storage) T(std::forward(args)...);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tT& get() {\n\t\t\t\treturn *reinterpret_cast(&m_storage);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tconst T& get() const {\n\t\t\t\treturn *reinterpret_cast(&m_storage);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tvoid destroy()\n\t\t\t{\n\t\t\t\tget().~T();\n\t\t\t}\n\n\t\t\ttypename std::aligned_storage::type m_storage;\n\t\t\n\t\t};\n\n\t\ttemplate< typename T >\n\t\tstruct temporary_storage_type {\n\n\t\t\ttemplate< typename... Args >\n\t\t\tvoid construct(Args&&... args)\n\t\t\t{\n\t\t\t\tnew (&m_storage) T(std::forward(args)...);\n\t\t\t}\n\n\t\t\tT& get() {\n\t\t\t\treturn *reinterpret_cast(&m_storage);\n\t\t\t}\n\n\t\t\tconst T& get() const {\n\t\t\t\treturn *reinterpret_cast(&m_storage);\n\t\t\t}\n\n\t\t\tvoid destroy()\n\t\t\t{\n\t\t\t\tget().~T();\n\t\t\t}\n\n\t\t\ttypename std::aligned_storage::type m_storage;\n\n\t\t};\n\n\t}\n\n\t\/\/ See note in out_value_policy about why we're not templating\n\t\/\/ for the parameter type.\n\ttemplate\n\tstruct out_value_converter\n\t{\n\t\tenum { consumed_args = 1 };\n\n template\n\t\tT& to_cpp(lua_State* L, by_reference, int index)\n\t\t{\n\t\t\t\/\/specialized_converter_policy_n<1, Policies, T, lua_to_cpp> converter;\n\t\t\tstorage_.construct(converter_.to_cpp(L, decorated_type(), index));\n\t\t\treturn storage_.get();\n\t\t}\n\n\t\tstatic int match(lua_State* L, by_reference, int index)\n\t\t{\n\t\t\treturn converter_.match(L, decorated_type(), index);\n\t\t}\n\n\t\tvoid converter_postcall(lua_State* L, by_reference, int) \n\t\t{\n\t\t\t\/\/specialized_converter_policy_n<2,Policies,T,cpp_to_lua> converter;\n\t\t\tconverter_.to_lua(L, storage_.get());\n\t\t\tstorage_.destroy();\n\t\t}\n\n\t\tT* to_cpp(lua_State* L, by_pointer, int index)\n\t\t{\n\t\t\tstorage_.construct(converter_.to_cpp(L, decorated_type(), index));\n\t\t\treturn &storage_.get();\n\t\t}\n\n\t\tint match(lua_State* L, by_pointer, int index)\n\t\t{\n\t\t\treturn converter_.match(L, decorated_type(), index);\n\t\t}\n\n\t\ttemplate\n\t\tvoid converter_postcall(lua_State* L, by_pointer, int)\n\t\t{\n\t\t\t\/\/specialized_converter_policy_n<2, Policies, T, cpp_to_lua> converter;\n\t\t\tconverter_.to_lua(L, storage_.get());\n\t\t\tstorage_.destroy();\n\t\t}\n\n\tprivate:\n\t\tspecialized_converter_policy_n<1, Policies, T, lua_to_cpp > converter_;\n\t\tout_value_detail::temporary_storage_type storage_;\n\t};\n\n\ttemplate\n\tstruct out_value_policy\n\t{\n\t\tstruct only_accepts_nonconst_references_or_pointers {};\n\t\tstruct can_only_convert_from_lua_to_cpp {};\n\n\t\ttemplate\n\t\tstruct specialize\n\t\t{\n\t\t\tstatic_assert(std::is_same< Direction, lua_to_cpp >::value, \"Out value policy can only convert from lua to cpp\");\n\t\t\tstatic_assert(meta::or_< is_nonconst_reference, is_nonconst_pointer >::value, \"Out value policy only accepts non const references or pointers\");\n\n\t\t\t\/\/ Note to myself:\n\t\t\t\/\/ Using the size and template members instead of a policy templated for the type seems\n\t\t\t\/\/ to be done to tame template bloat. Need to check if this is worth is.\n\t\t\tusing base_type = typename std::remove_pointer< typename std::remove_reference< T >::type >::type;\n\t\t\ttypedef out_value_converter type;\n\t\t};\n\t};\n\n\ttemplate\n\tstruct pure_out_value_converter\n\t{\n\t\tenum { consumed_args = 0 };\n\n template\n\t\tT& to_cpp(lua_State*, by_reference, int)\n\t\t{\n\t\t\tstorage_.construct();\n\t\t\treturn storage_.get();\n\t\t}\n\n\t\ttemplate\n\t\tstatic int match(lua_State*, by_reference, int)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\n\t\ttemplate\n\t\tvoid converter_postcall(lua_State* L, by_reference, int) \n\t\t{\n\t\t\tspecialized_converter_policy_n<1, Policies, T, cpp_to_lua> converter;\n\t\t\tconverter.to_lua(L, storage_.get());\n\t\t\tstorage_.destroy();\n\t\t}\n\n\t\ttemplate\n\t\tT* to_cpp(lua_State*, by_pointer, int)\n\t\t{\n\t\t\tstorage_.construct();\n\t\t\treturn &storage_.get();\n\t\t}\n\n\t\ttemplate\n\t\tstatic int match(lua_State*, by_pointer, int)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\n\t\ttemplate\n\t\tvoid converter_postcall(lua_State* L, by_pointer, int) \n\t\t{\n\t\t\tspecialized_converter_policy_n<1, Policies, T, cpp_to_lua> converter;\n\t\t\tconverter.to_lua(L, storage_.get());\n\t\t\tstorage_.destroy();\n\t\t}\n\n\tprivate:\n\t\tout_value_detail::temporary_storage_size storage_;\n\t};\n\n\ttemplate\n\tstruct pure_out_value_policy\n\t{\n\t\tstruct only_accepts_nonconst_references_or_pointers {};\n\t\tstruct can_only_convert_from_lua_to_cpp {};\n\n\t\ttemplate\n\t\tstruct specialize\n\t\t{\n\t\t\tstatic_assert(std::is_same< Direction, lua_to_cpp >::value, \"Pure out value policy can only convert from lua to cpp\");\n\t\t\tstatic_assert(meta::or_< is_nonconst_reference, is_nonconst_pointer >::value, \"Pure out value policy only accepts non const references or pointers\");\n\n\t\t\ttypedef pure_out_value_converter::value, Policies> type;\n\t\t};\n\t};\n\t\n}}\n\nnamespace luabind\n{\n\ttemplate\n\tusing out_value = meta::type_list>>;\n\n\ttemplate\n\tusing pure_out_value = meta::type_list>>;\n}\n\n#endif \/\/ LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED\n\nFix out_value_converter compilation.\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n#ifndef LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED\n#define LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED\n\n#include \n#include \/\/ for find_conversion_policy, etc\n#include \/\/ for decorated_type\n#include \/\/ for by_pointer, by_reference, etc\n#include \/\/ for is_nonconst_pointer, is_nonconst_reference, etc\n#include \/\/ for operator new\n\nnamespace luabind { namespace detail\n{\n\ttemplate\n\tstruct char_array\n\t{\n\t\tchar storage[N];\n\t};\n\n\ttemplate\n\tchar_array::type)> indirect_sizeof_test(by_reference);\n\n\ttemplate\n\tchar_array::type)> indirect_sizeof_test(by_const_reference);\n\n\ttemplate\n\tchar_array::type)> indirect_sizeof_test(by_pointer);\n\n\ttemplate\n\tchar_array::type)> indirect_sizeof_test(by_const_pointer);\n\n\ttemplate\n\tchar_array::type)> indirect_sizeof_test(by_value);\n\n\ttemplate\n\tstruct indirect_sizeof\n\t{\n\t\tstatic const int value = sizeof(indirect_sizeof_test(decorated_type()));\n\t};\n\t\n\tnamespace out_value_detail {\n\n\t\ttemplate< int Size >\n\t\tstruct temporary_storage_size {\n\t\t\t\n\t\t\ttemplate< typename T, typename... Args >\n\t\t\tvoid construct(Args&&... args)\n\t\t\t{\n\t\t\t\tnew (&m_storage) T(std::forward(args)...);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tT& get() {\n\t\t\t\treturn *reinterpret_cast(&m_storage);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tconst T& get() const {\n\t\t\t\treturn *reinterpret_cast(&m_storage);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tvoid destroy()\n\t\t\t{\n\t\t\t\tget().~T();\n\t\t\t}\n\n\t\t\ttypename std::aligned_storage::type m_storage;\n\t\t\n\t\t};\n\n\t\ttemplate< typename T >\n\t\tstruct temporary_storage_type {\n\n\t\t\ttemplate< typename... Args >\n\t\t\tvoid construct(Args&&... args)\n\t\t\t{\n\t\t\t\tnew (&m_storage) T(std::forward(args)...);\n\t\t\t}\n\n\t\t\tT& get() {\n\t\t\t\treturn *reinterpret_cast(&m_storage);\n\t\t\t}\n\n\t\t\tconst T& get() const {\n\t\t\t\treturn *reinterpret_cast(&m_storage);\n\t\t\t}\n\n\t\t\tvoid destroy()\n\t\t\t{\n\t\t\t\tget().~T();\n\t\t\t}\n\n\t\t\ttypename std::aligned_storage::type m_storage;\n\n\t\t};\n\n\t}\n\n\t\/\/ See note in out_value_policy about why we're not templating\n\t\/\/ for the parameter type.\n\ttemplate\n\tstruct out_value_converter\n\t{\n\t\tenum { consumed_args = 1 };\n\n template\n\t\tT& to_cpp(lua_State* L, by_reference, int index)\n\t\t{\n\t\t\t\/\/specialized_converter_policy_n<1, Policies, T, lua_to_cpp> converter;\n\t\t\tstorage_.construct(converter_.to_cpp(L, decorated_type(), index));\n\t\t\treturn storage_.get();\n\t\t}\n\n\t\tint match(lua_State* L, by_reference, int index)\n\t\t{\n\t\t\treturn converter_.match(L, decorated_type(), index);\n\t\t}\n\n\t\tvoid converter_postcall(lua_State* L, by_reference, int) \n\t\t{\n\t\t\t\/\/specialized_converter_policy_n<2,Policies,T,cpp_to_lua> converter;\n\t\t\tconverter_.to_lua(L, storage_.get());\n\t\t\tstorage_.destroy();\n\t\t}\n\n\t\tT* to_cpp(lua_State* L, by_pointer, int index)\n\t\t{\n\t\t\tstorage_.construct(converter_.to_cpp(L, decorated_type(), index));\n\t\t\treturn &storage_.get();\n\t\t}\n\n\t\tint match(lua_State* L, by_pointer, int index)\n\t\t{\n\t\t\treturn converter_.match(L, decorated_type(), index);\n\t\t}\n\n\t\ttemplate\n\t\tvoid converter_postcall(lua_State* L, by_pointer, int)\n\t\t{\n\t\t\t\/\/specialized_converter_policy_n<2, Policies, T, cpp_to_lua> converter;\n\t\t\tconverter_.to_lua(L, storage_.get());\n\t\t\tstorage_.destroy();\n\t\t}\n\n\tprivate:\n\t\tspecialized_converter_policy_n<1, Policies, T, lua_to_cpp > converter_;\n\t\tout_value_detail::temporary_storage_type storage_;\n\t};\n\n\ttemplate\n\tstruct out_value_policy\n\t{\n\t\tstruct only_accepts_nonconst_references_or_pointers {};\n\t\tstruct can_only_convert_from_lua_to_cpp {};\n\n\t\ttemplate\n\t\tstruct specialize\n\t\t{\n\t\t\tstatic_assert(std::is_same< Direction, lua_to_cpp >::value, \"Out value policy can only convert from lua to cpp\");\n\t\t\tstatic_assert(meta::or_< is_nonconst_reference, is_nonconst_pointer >::value, \"Out value policy only accepts non const references or pointers\");\n\n\t\t\t\/\/ Note to myself:\n\t\t\t\/\/ Using the size and template members instead of a policy templated for the type seems\n\t\t\t\/\/ to be done to tame template bloat. Need to check if this is worth is.\n\t\t\tusing base_type = typename std::remove_pointer< typename std::remove_reference< T >::type >::type;\n\t\t\ttypedef out_value_converter type;\n\t\t};\n\t};\n\n\ttemplate\n\tstruct pure_out_value_converter\n\t{\n\t\tenum { consumed_args = 0 };\n\n template\n\t\tT& to_cpp(lua_State*, by_reference, int)\n\t\t{\n\t\t\tstorage_.construct();\n\t\t\treturn storage_.get();\n\t\t}\n\n\t\ttemplate\n\t\tstatic int match(lua_State*, by_reference, int)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\n\t\ttemplate\n\t\tvoid converter_postcall(lua_State* L, by_reference, int) \n\t\t{\n\t\t\tspecialized_converter_policy_n<1, Policies, T, cpp_to_lua> converter;\n\t\t\tconverter.to_lua(L, storage_.get());\n\t\t\tstorage_.destroy();\n\t\t}\n\n\t\ttemplate\n\t\tT* to_cpp(lua_State*, by_pointer, int)\n\t\t{\n\t\t\tstorage_.construct();\n\t\t\treturn &storage_.get();\n\t\t}\n\n\t\ttemplate\n\t\tstatic int match(lua_State*, by_pointer, int)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\n\t\ttemplate\n\t\tvoid converter_postcall(lua_State* L, by_pointer, int) \n\t\t{\n\t\t\tspecialized_converter_policy_n<1, Policies, T, cpp_to_lua> converter;\n\t\t\tconverter.to_lua(L, storage_.get());\n\t\t\tstorage_.destroy();\n\t\t}\n\n\tprivate:\n\t\tout_value_detail::temporary_storage_size storage_;\n\t};\n\n\ttemplate\n\tstruct pure_out_value_policy\n\t{\n\t\tstruct only_accepts_nonconst_references_or_pointers {};\n\t\tstruct can_only_convert_from_lua_to_cpp {};\n\n\t\ttemplate\n\t\tstruct specialize\n\t\t{\n\t\t\tstatic_assert(std::is_same< Direction, lua_to_cpp >::value, \"Pure out value policy can only convert from lua to cpp\");\n\t\t\tstatic_assert(meta::or_< is_nonconst_reference, is_nonconst_pointer >::value, \"Pure out value policy only accepts non const references or pointers\");\n\n\t\t\ttypedef pure_out_value_converter::value, Policies> type;\n\t\t};\n\t};\n\t\n}}\n\nnamespace luabind\n{\n\ttemplate\n\tusing out_value = meta::type_list>>;\n\n\ttemplate\n\tusing pure_out_value = meta::type_list>>;\n}\n\n#endif \/\/ LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"media_manager\/audio\/from_mic_to_file_recorder_thread.h\"\n#include \n#include \n#include \n#include \"interfaces\/MOBILE_API.h\"\n#include \"utils\/logger.h\"\n\nnamespace media_manager {\n\nSDL_CREATE_LOG_VARIABLE(\"MediaManager\")\n\nGMainLoop* FromMicToFileRecorderThread::loop = NULL;\n\n\/\/ As per spec, AudioPassThru recording is in monaural\nstatic const int kNumAudioChannels = 1;\n\nFromMicToFileRecorderThread::FromMicToFileRecorderThread(\n const std::string& output_file,\n int32_t duration,\n mobile_apis::SamplingRate::eType sampling_rate,\n mobile_apis::BitsPerSample::eType bits_per_sample,\n mobile_apis::AudioType::eType audio_type)\n : threads::ThreadDelegate()\n , argc_(5)\n , argv_(NULL)\n , oKey_(\"-o\")\n , tKey_(\"-t\")\n , sleepThread_(NULL)\n , outputFileName_(output_file)\n , samplingRate_(sampling_rate)\n , bitsPerSample_(bits_per_sample) {\n SDL_LOG_AUTO_TRACE();\n set_record_duration(duration);\n \/\/ audio_type is not used as we always employ LPCM\n}\n\nFromMicToFileRecorderThread::~FromMicToFileRecorderThread() {\n SDL_LOG_AUTO_TRACE();\n if (sleepThread_) {\n sleepThread_->Stop(threads::Thread::kThreadSoftStop);\n delete sleepThread_->GetDelegate();\n threads::DeleteThread(sleepThread_);\n }\n}\n\nvoid FromMicToFileRecorderThread::set_output_file(\n const std::string& output_file) {\n SDL_LOG_AUTO_TRACE();\n outputFileName_ = output_file;\n}\n\nvoid FromMicToFileRecorderThread::set_record_duration(int32_t duration) {\n SDL_LOG_AUTO_TRACE();\n\n std::stringstream stringStream;\n stringStream << duration \/ 1000;\n durationString_ = stringStream.str();\n}\n\nvoid FromMicToFileRecorderThread::initArgs() {\n SDL_LOG_AUTO_TRACE();\n\n argv_ = new gchar*[argc_];\n\n argv_[0] = new gchar[14];\n argv_[1] = new gchar[3];\n argv_[2] = new gchar[outputFileName_.length() + 1];\n argv_[3] = new gchar[3];\n argv_[4] = new gchar[durationString_.length() + 1];\n\n std::strcpy(argv_[0], \"AudioManager\");\n std::strcpy(argv_[1], oKey_.c_str());\n std::strcpy(argv_[2], outputFileName_.c_str());\n std::strcpy(argv_[3], tKey_.c_str());\n std::strcpy(argv_[4], durationString_.c_str());\n}\n\nvoid FromMicToFileRecorderThread::deinitArgs() {\n SDL_LOG_AUTO_TRACE();\n\n if (argv_) {\n for (int32_t i = 0; i < argc_; ++i) {\n delete[] argv_[i];\n }\n delete[] argv_;\n argv_ = NULL;\n }\n}\n\nvoid FromMicToFileRecorderThread::threadMain() {\n SDL_LOG_AUTO_TRACE();\n\n {\n sync_primitives::AutoLock auto_lock(stopFlagLock_);\n shouldBeStoped_ = false;\n }\n\n initArgs();\n\n GstElement* pipeline;\n GstElement *alsasrc, *audioconvert, *capsfilter, *wavenc, *filesink;\n GstCaps* audiocaps;\n GstBus* bus;\n\n const gchar* device = \"hw:0,0\";\n gchar* outfile = NULL;\n gint duration = -1;\n GOptionContext* context = NULL;\n GError* err = NULL;\n GOptionEntry entries[] = {{\"device\",\n 'd',\n 0,\n G_OPTION_ARG_FILENAME,\n &device,\n \"device file (Default: hw:0,0)\",\n \"SRC\"},\n {\"output\",\n 'o',\n 0,\n G_OPTION_ARG_FILENAME,\n &outfile,\n \"save output of the stream to DEST\",\n \"DEST\"},\n {\"duration\",\n 't',\n 0,\n G_OPTION_ARG_INT,\n &duration,\n \"length of time in seconds to capture\",\n \"int32_t\"},\n {NULL}};\n \/\/ g_option_context_parse() modifies params, so keep argc_ and argv_\n int32_t argc = argc_;\n gchar** argv = new gchar*[argc];\n for (int32_t i = 0; i < argc; ++i) {\n argv[i] = argv_[i];\n }\n\n#ifndef GLIB_VERSION_2_32 \/\/ g_thread_init() does nothing since 2.32\n if (!g_thread_supported()) {\n g_thread_init(NULL);\n }\n#endif\n \/\/ Parse the arguments\n context = g_option_context_new(\"-- M-AUDIO RAW\");\n g_option_context_add_main_entries(context, entries, NULL);\n g_option_context_add_group(context, gst_init_get_option_group());\n if (!g_option_context_parse(context, &argc, &argv, &err)) {\n g_error(\"%s\\n\", err->message);\n }\n\n \/\/ Check for proper arguments\n if (outfile == NULL) {\n g_error(\"Must supply destination (-d FILE)\\n\");\n }\n\n SDL_LOG_TRACE(\"Reading from device: \" << device);\n SDL_LOG_TRACE(\"Saving pipeline output to: \" << outfile);\n SDL_LOG_TRACE(\"Duration set to: \" << duration);\n\n \/\/ Initialize gstreamer and setup the main loop information\n gst_init(&argc, &argv);\n\n delete[] argv;\n argv = NULL;\n\n pipeline = gst_pipeline_new(\"vga2usb-h264\");\n\n \/\/ Set up error handling\n bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));\n gst_bus_add_watch(\n bus,\n reinterpret_cast(recvmsg),\n NULL);\n gst_object_unref(bus);\n\n \/\/ Create all of the elements to be added to the pipeline\n alsasrc = gst_element_factory_make(\"alsasrc\", \"alsasrc0\");\n audioconvert = gst_element_factory_make(\"audioconvert\", \"audioconvert0\");\n capsfilter = gst_element_factory_make(\"capsfilter\", \"filter0\");\n wavenc = gst_element_factory_make(\"wavenc\", \"wavenc0\");\n filesink = gst_element_factory_make(\"filesink\", \"filesink0\");\n\n \/\/ Create a capability to specify audio format. It also downmixes the recorded\n \/\/ audio to monaural.\n std::string caps_string = create_caps_string();\n SDL_LOG_DEBUG(\"Using audio caps: \" << caps_string);\n audiocaps = gst_caps_from_string(caps_string.c_str());\n\n \/\/ Assert that all the elements were created\n if (!alsasrc || !audioconvert || !capsfilter || !wavenc || !filesink ||\n !audiocaps) {\n g_error(\"Failed creating one or more of the pipeline elements.\\n\");\n }\n\n \/\/ Set input and output destinations\n g_object_set(G_OBJECT(alsasrc), \"device\", device, NULL);\n g_object_set(G_OBJECT(filesink), \"location\", outfile, NULL);\n\n \/\/ Add the elements to the pipeline\n gst_bin_add_many(GST_BIN(pipeline),\n alsasrc,\n audioconvert,\n capsfilter,\n wavenc,\n filesink,\n NULL);\n\n \/\/ Link the elements\n gst_element_link_many(\n alsasrc, audioconvert, capsfilter, wavenc, filesink, NULL);\n\n \/\/ set the capability\n g_object_set(G_OBJECT(capsfilter), \"caps\", audiocaps, NULL);\n gst_caps_unref(audiocaps);\n\n gst_element_set_state(pipeline, GST_STATE_PLAYING);\n\n SDL_LOG_TRACE(\"Initializing pipeline ...\");\n while (GST_STATE(pipeline) != GST_STATE_PLAYING) {\n bool shouldBeStoped;\n {\n \/\/ FIXME(dchmerev@luxoft.com):\n sync_primitives::AutoLock auto_lock(stopFlagLock_);\n shouldBeStoped = shouldBeStoped_;\n }\n\n if (shouldBeStoped) {\n gst_element_set_state(pipeline, GST_STATE_NULL);\n gst_object_unref(GST_OBJECT(pipeline));\n g_option_context_free(context);\n\n deinitArgs();\n return;\n }\n }\n SDL_LOG_TRACE(\"Pipeline started ...\\n\");\n\n \/\/ Start up a timer for the pipeline\n if (duration > 0) {\n GstTimeout timeout;\n timeout.pipeline = pipeline;\n timeout.duration = duration;\n\n sleepThread_ =\n threads::CreateThread(\"SleepThread\", new SleepThreadDelegate(timeout));\n sleepThread_->Start();\n }\n\n loop = g_main_loop_new(NULL, FALSE);\n\n g_main_loop_run(loop);\n\n gst_element_set_state(pipeline, GST_STATE_NULL);\n\n SDL_LOG_TRACE(\"Deleting pipeline\\n\");\n gst_object_unref(GST_OBJECT(pipeline));\n g_main_loop_unref(loop);\n g_option_context_free(context);\n\n deinitArgs();\n\n loop = NULL;\n}\n\nstd::string FromMicToFileRecorderThread::create_caps_string() {\n SDL_LOG_AUTO_TRACE();\n\n std::stringstream ss;\n ss << \"audio\/x-raw\";\n\n switch (bitsPerSample_) {\n case mobile_apis::BitsPerSample::BitsPerSample_8_BIT:\n \/\/ format is 8-bit unsigned\n ss << \",format=(string)U8\";\n break;\n case mobile_apis::BitsPerSample::BitsPerSample_16_BIT:\n \/\/ format is 16-bit signed, in little endian\n ss << \",format=(string)S16LE\";\n break;\n default:\n \/\/ do not specify the format; use system default\n break;\n }\n\n switch (samplingRate_) {\n case mobile_apis::SamplingRate::SamplingRate_8KHZ:\n ss << \",rate=8000\";\n break;\n case mobile_apis::SamplingRate::SamplingRate_16KHZ:\n ss << \",rate=16000\";\n break;\n case mobile_apis::SamplingRate::SamplingRate_22KHZ:\n ss << \",rate=22050\";\n break;\n case mobile_apis::SamplingRate::SamplingRate_44KHZ:\n ss << \",rate=44100\";\n break;\n default:\n \/\/ do not specify the sampling rate; use system default\n break;\n }\n\n ss << \",channels=\" << kNumAudioChannels;\n\n return ss.str();\n}\n\nFromMicToFileRecorderThread::SleepThreadDelegate::SleepThreadDelegate(\n GstTimeout timeout)\n : threads::ThreadDelegate(), timeout_(timeout) {}\n\nvoid FromMicToFileRecorderThread::SleepThreadDelegate::threadMain() {\n SDL_LOG_TRACE(\"Sleep for \" << timeout_.duration << \" seconds\");\n\n sleep(timeout_.duration);\n\n if (NULL != loop) {\n if (g_main_loop_is_running(loop)) {\n gst_element_send_event(timeout_.pipeline, gst_event_new_eos());\n }\n }\n}\n\nvoid FromMicToFileRecorderThread::exitThreadMain() {\n SDL_LOG_AUTO_TRACE();\n\n if (NULL != loop) {\n if (g_main_loop_is_running(loop)) {\n SDL_LOG_TRACE(\"Quit loop\\n\");\n g_main_loop_quit(loop);\n }\n }\n\n if (sleepThread_) {\n SDL_LOG_DEBUG(\"Stop sleep thread\\n\");\n sleepThread_->stop();\n }\n\n SDL_LOG_TRACE(\"Set should be stopped flag\\n\");\n sync_primitives::AutoLock auto_lock(stopFlagLock_);\n shouldBeStoped_ = true;\n}\n\n} \/\/ namespace media_manager\nFix thread stop method (#3712)\/*\n * Copyright (c) 2014, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"media_manager\/audio\/from_mic_to_file_recorder_thread.h\"\n#include \n#include \n#include \n#include \"interfaces\/MOBILE_API.h\"\n#include \"utils\/logger.h\"\n\nnamespace media_manager {\n\nSDL_CREATE_LOG_VARIABLE(\"MediaManager\")\n\nGMainLoop* FromMicToFileRecorderThread::loop = NULL;\n\n\/\/ As per spec, AudioPassThru recording is in monaural\nstatic const int kNumAudioChannels = 1;\n\nFromMicToFileRecorderThread::FromMicToFileRecorderThread(\n const std::string& output_file,\n int32_t duration,\n mobile_apis::SamplingRate::eType sampling_rate,\n mobile_apis::BitsPerSample::eType bits_per_sample,\n mobile_apis::AudioType::eType audio_type)\n : threads::ThreadDelegate()\n , argc_(5)\n , argv_(NULL)\n , oKey_(\"-o\")\n , tKey_(\"-t\")\n , sleepThread_(NULL)\n , outputFileName_(output_file)\n , samplingRate_(sampling_rate)\n , bitsPerSample_(bits_per_sample) {\n SDL_LOG_AUTO_TRACE();\n set_record_duration(duration);\n \/\/ audio_type is not used as we always employ LPCM\n}\n\nFromMicToFileRecorderThread::~FromMicToFileRecorderThread() {\n SDL_LOG_AUTO_TRACE();\n if (sleepThread_) {\n sleepThread_->Stop(threads::Thread::kThreadSoftStop);\n delete sleepThread_->GetDelegate();\n threads::DeleteThread(sleepThread_);\n }\n}\n\nvoid FromMicToFileRecorderThread::set_output_file(\n const std::string& output_file) {\n SDL_LOG_AUTO_TRACE();\n outputFileName_ = output_file;\n}\n\nvoid FromMicToFileRecorderThread::set_record_duration(int32_t duration) {\n SDL_LOG_AUTO_TRACE();\n\n std::stringstream stringStream;\n stringStream << duration \/ 1000;\n durationString_ = stringStream.str();\n}\n\nvoid FromMicToFileRecorderThread::initArgs() {\n SDL_LOG_AUTO_TRACE();\n\n argv_ = new gchar*[argc_];\n\n argv_[0] = new gchar[14];\n argv_[1] = new gchar[3];\n argv_[2] = new gchar[outputFileName_.length() + 1];\n argv_[3] = new gchar[3];\n argv_[4] = new gchar[durationString_.length() + 1];\n\n std::strcpy(argv_[0], \"AudioManager\");\n std::strcpy(argv_[1], oKey_.c_str());\n std::strcpy(argv_[2], outputFileName_.c_str());\n std::strcpy(argv_[3], tKey_.c_str());\n std::strcpy(argv_[4], durationString_.c_str());\n}\n\nvoid FromMicToFileRecorderThread::deinitArgs() {\n SDL_LOG_AUTO_TRACE();\n\n if (argv_) {\n for (int32_t i = 0; i < argc_; ++i) {\n delete[] argv_[i];\n }\n delete[] argv_;\n argv_ = NULL;\n }\n}\n\nvoid FromMicToFileRecorderThread::threadMain() {\n SDL_LOG_AUTO_TRACE();\n\n {\n sync_primitives::AutoLock auto_lock(stopFlagLock_);\n shouldBeStoped_ = false;\n }\n\n initArgs();\n\n GstElement* pipeline;\n GstElement *alsasrc, *audioconvert, *capsfilter, *wavenc, *filesink;\n GstCaps* audiocaps;\n GstBus* bus;\n\n const gchar* device = \"hw:0,0\";\n gchar* outfile = NULL;\n gint duration = -1;\n GOptionContext* context = NULL;\n GError* err = NULL;\n GOptionEntry entries[] = {{\"device\",\n 'd',\n 0,\n G_OPTION_ARG_FILENAME,\n &device,\n \"device file (Default: hw:0,0)\",\n \"SRC\"},\n {\"output\",\n 'o',\n 0,\n G_OPTION_ARG_FILENAME,\n &outfile,\n \"save output of the stream to DEST\",\n \"DEST\"},\n {\"duration\",\n 't',\n 0,\n G_OPTION_ARG_INT,\n &duration,\n \"length of time in seconds to capture\",\n \"int32_t\"},\n {NULL}};\n \/\/ g_option_context_parse() modifies params, so keep argc_ and argv_\n int32_t argc = argc_;\n gchar** argv = new gchar*[argc];\n for (int32_t i = 0; i < argc; ++i) {\n argv[i] = argv_[i];\n }\n\n#ifndef GLIB_VERSION_2_32 \/\/ g_thread_init() does nothing since 2.32\n if (!g_thread_supported()) {\n g_thread_init(NULL);\n }\n#endif\n \/\/ Parse the arguments\n context = g_option_context_new(\"-- M-AUDIO RAW\");\n g_option_context_add_main_entries(context, entries, NULL);\n g_option_context_add_group(context, gst_init_get_option_group());\n if (!g_option_context_parse(context, &argc, &argv, &err)) {\n g_error(\"%s\\n\", err->message);\n }\n\n \/\/ Check for proper arguments\n if (outfile == NULL) {\n g_error(\"Must supply destination (-d FILE)\\n\");\n }\n\n SDL_LOG_TRACE(\"Reading from device: \" << device);\n SDL_LOG_TRACE(\"Saving pipeline output to: \" << outfile);\n SDL_LOG_TRACE(\"Duration set to: \" << duration);\n\n \/\/ Initialize gstreamer and setup the main loop information\n gst_init(&argc, &argv);\n\n delete[] argv;\n argv = NULL;\n\n pipeline = gst_pipeline_new(\"vga2usb-h264\");\n\n \/\/ Set up error handling\n bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));\n gst_bus_add_watch(\n bus,\n reinterpret_cast(recvmsg),\n NULL);\n gst_object_unref(bus);\n\n \/\/ Create all of the elements to be added to the pipeline\n alsasrc = gst_element_factory_make(\"alsasrc\", \"alsasrc0\");\n audioconvert = gst_element_factory_make(\"audioconvert\", \"audioconvert0\");\n capsfilter = gst_element_factory_make(\"capsfilter\", \"filter0\");\n wavenc = gst_element_factory_make(\"wavenc\", \"wavenc0\");\n filesink = gst_element_factory_make(\"filesink\", \"filesink0\");\n\n \/\/ Create a capability to specify audio format. It also downmixes the recorded\n \/\/ audio to monaural.\n std::string caps_string = create_caps_string();\n SDL_LOG_DEBUG(\"Using audio caps: \" << caps_string);\n audiocaps = gst_caps_from_string(caps_string.c_str());\n\n \/\/ Assert that all the elements were created\n if (!alsasrc || !audioconvert || !capsfilter || !wavenc || !filesink ||\n !audiocaps) {\n g_error(\"Failed creating one or more of the pipeline elements.\\n\");\n }\n\n \/\/ Set input and output destinations\n g_object_set(G_OBJECT(alsasrc), \"device\", device, NULL);\n g_object_set(G_OBJECT(filesink), \"location\", outfile, NULL);\n\n \/\/ Add the elements to the pipeline\n gst_bin_add_many(GST_BIN(pipeline),\n alsasrc,\n audioconvert,\n capsfilter,\n wavenc,\n filesink,\n NULL);\n\n \/\/ Link the elements\n gst_element_link_many(\n alsasrc, audioconvert, capsfilter, wavenc, filesink, NULL);\n\n \/\/ set the capability\n g_object_set(G_OBJECT(capsfilter), \"caps\", audiocaps, NULL);\n gst_caps_unref(audiocaps);\n\n gst_element_set_state(pipeline, GST_STATE_PLAYING);\n\n SDL_LOG_TRACE(\"Initializing pipeline ...\");\n while (GST_STATE(pipeline) != GST_STATE_PLAYING) {\n bool shouldBeStoped;\n {\n \/\/ FIXME(dchmerev@luxoft.com):\n sync_primitives::AutoLock auto_lock(stopFlagLock_);\n shouldBeStoped = shouldBeStoped_;\n }\n\n if (shouldBeStoped) {\n gst_element_set_state(pipeline, GST_STATE_NULL);\n gst_object_unref(GST_OBJECT(pipeline));\n g_option_context_free(context);\n\n deinitArgs();\n return;\n }\n }\n SDL_LOG_TRACE(\"Pipeline started ...\\n\");\n\n \/\/ Start up a timer for the pipeline\n if (duration > 0) {\n GstTimeout timeout;\n timeout.pipeline = pipeline;\n timeout.duration = duration;\n\n sleepThread_ =\n threads::CreateThread(\"SleepThread\", new SleepThreadDelegate(timeout));\n sleepThread_->Start();\n }\n\n loop = g_main_loop_new(NULL, FALSE);\n\n g_main_loop_run(loop);\n\n gst_element_set_state(pipeline, GST_STATE_NULL);\n\n SDL_LOG_TRACE(\"Deleting pipeline\\n\");\n gst_object_unref(GST_OBJECT(pipeline));\n g_main_loop_unref(loop);\n g_option_context_free(context);\n\n deinitArgs();\n\n loop = NULL;\n}\n\nstd::string FromMicToFileRecorderThread::create_caps_string() {\n SDL_LOG_AUTO_TRACE();\n\n std::stringstream ss;\n ss << \"audio\/x-raw\";\n\n switch (bitsPerSample_) {\n case mobile_apis::BitsPerSample::BitsPerSample_8_BIT:\n \/\/ format is 8-bit unsigned\n ss << \",format=(string)U8\";\n break;\n case mobile_apis::BitsPerSample::BitsPerSample_16_BIT:\n \/\/ format is 16-bit signed, in little endian\n ss << \",format=(string)S16LE\";\n break;\n default:\n \/\/ do not specify the format; use system default\n break;\n }\n\n switch (samplingRate_) {\n case mobile_apis::SamplingRate::SamplingRate_8KHZ:\n ss << \",rate=8000\";\n break;\n case mobile_apis::SamplingRate::SamplingRate_16KHZ:\n ss << \",rate=16000\";\n break;\n case mobile_apis::SamplingRate::SamplingRate_22KHZ:\n ss << \",rate=22050\";\n break;\n case mobile_apis::SamplingRate::SamplingRate_44KHZ:\n ss << \",rate=44100\";\n break;\n default:\n \/\/ do not specify the sampling rate; use system default\n break;\n }\n\n ss << \",channels=\" << kNumAudioChannels;\n\n return ss.str();\n}\n\nFromMicToFileRecorderThread::SleepThreadDelegate::SleepThreadDelegate(\n GstTimeout timeout)\n : threads::ThreadDelegate(), timeout_(timeout) {}\n\nvoid FromMicToFileRecorderThread::SleepThreadDelegate::threadMain() {\n SDL_LOG_TRACE(\"Sleep for \" << timeout_.duration << \" seconds\");\n\n sleep(timeout_.duration);\n\n if (NULL != loop) {\n if (g_main_loop_is_running(loop)) {\n gst_element_send_event(timeout_.pipeline, gst_event_new_eos());\n }\n }\n}\n\nvoid FromMicToFileRecorderThread::exitThreadMain() {\n SDL_LOG_AUTO_TRACE();\n\n if (NULL != loop) {\n if (g_main_loop_is_running(loop)) {\n SDL_LOG_TRACE(\"Quit loop\\n\");\n g_main_loop_quit(loop);\n }\n }\n\n if (sleepThread_) {\n SDL_LOG_DEBUG(\"Stop sleep thread\\n\");\n sleepThread_->Stop(threads::Thread::kThreadStopDelegate);\n }\n\n SDL_LOG_TRACE(\"Set should be stopped flag\\n\");\n sync_primitives::AutoLock auto_lock(stopFlagLock_);\n shouldBeStoped_ = true;\n}\n\n} \/\/ namespace media_manager\n<|endoftext|>"} {"text":"tpcNClsFound -> tpcNClsFoundMin<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: javacompskeleton.cxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: jsc $ $Date: 2005-08-23 08:30:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"skeletonjava.hxx\"\n\nusing namespace ::codemaker::java;\n\nnamespace skeletonmaker { namespace java {\n\nvoid generatePackage(std::ostream & o, const rtl::OString & implname)\n{\n short count=0;\n sal_Int32 index = implname.lastIndexOf('.');\n if (index != -1) {\n o << \"package \" << implname.copy(0, index) << \";\\n\\n\";\n }\n}\n\nvoid generateImports(std::ostream & o,\n const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,\n const rtl::OString & propertyhelper,\n bool serviceobject, bool supportxcomponent)\n{\n o << \"import com.sun.star.uno.XComponentContext;\\n\";\n if (serviceobject) {\n o << \"import com.sun.star.lib.uno.helper.Factory;\\n\";\n o << \"import com.sun.star.lang.XSingleComponentFactory;\\n\";\n o << \"import com.sun.star.registry.XRegistryKey;\\n\";\n }\n\n if (!propertyhelper.equals(\"_\")) {\n if (supportxcomponent)\n o << \"import com.sun.star.lib.uno.helper.ComponentBase;\\n\";\n else\n o << \"import com.sun.star.lib.uno.helper.WeakBase;\\n\";\n }\n if (propertyhelper.getLength() > 0) {\n if (propertyhelper.equals(\"_\")) {\n o << \"import com.sun.star.lib.uno.helper.PropertySet;\\n\";\n o << \"import com.sun.star.beans.PropertyAttribute;\\n\";\n } else {\n o << \"import com.sun.star.uno.Type;\\n\";\n o << \"import com.sun.star.lib.uno.helper.PropertySetMixin;\\n\";\n }\n }\n\n\/\/ std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter = interfaces.begin();\n\/\/ while (iter != interfaces.end()) {\n\/\/ o << \"import \" << ((*iter).getStr()) << \";\\n\";\n\/\/ iter++;\n\/\/ }\n}\n\nvoid generateCompFunctions(std::ostream & o, const rtl::OString & classname)\n{\n o << \" public static XSingleComponentFactory __getComponentFactory(\"\n << \"String sImplementationName ) {\\n\"\n << \" XSingleComponentFactory xFactory = null;\\n\\n\"\n << \" if ( sImplementationName.equals( m_implementationName ) )\\n\"\n << \" xFactory = Factory.createComponentFactory(\"\n << classname << \".class, m_serviceNames);\\n\"\n << \" return xFactory;\\n }\\n\\n\";\n\n o << \" public static boolean __writeRegistryServiceInfo(\"\n << \"XRegistryKey xRegistryKey ) {\\n\"\n << \" return Factory.writeRegistryServiceInfo(m_implementationName,\\n\"\n << \" m_serviceNames,\\n\"\n << \" xRegistryKey);\\n\"\n << \" }\\n\\n\";\n}\n\nvoid generateXServiceInfoBodies(std::ostream& o)\n{\n o << \" \/* com.sun.star.lang.XServiceInfo *\/\\n\";\n o << \" public java.lang.String getImplementationName() {\\n\"\n << \" return m_implementationName;\\n }\\n\\n\";\n\n o << \" public boolean supportsService( java.lang.String sService ) {\\n\"\n << \" int len = m_serviceNames.length;\\n\\n\"\n << \" for( int i=0; i < len; i++) {\\n\"\n << \" if (sService.equals(m_serviceNames[i]))\\n\"\n << \" return true;\\n\"\n << \" }\\n return false;\\n }\\n\\n\";\n\n o << \" public java.lang.String[] getSupportedServiceNames() {\\n\"\n << \" return m_serviceNames;\\n }\\n\\n\";\n}\n\n\nbool checkAttribute(rtl::OStringBuffer& attributeValue, sal_uInt16 attribute) {\n bool cast = false;\n sal_uInt16 attributes[9] = {\n \/* com::sun::star::beans::PropertyValue::MAYBEVOID *\/ 1,\n \/* com::sun::star::beans::PropertyValue::BOUND *\/ 2,\n \/* com::sun::star::beans::PropertyValue::CONSTRAINED *\/ 4,\n \/* com::sun::star::beans::PropertyValue::TRANSIENT *\/ 8,\n \/* com::sun::star::beans::PropertyValue::READONLY *\/ 16,\n \/* com::sun::star::beans::PropertyValue::MAYBEAMBIGIOUS *\/ 32,\n \/* com::sun::star::beans::PropertyValue::MAYBEDEFAULT *\/ 64,\n \/* com::sun::star::beans::PropertyValue::REMOVEABLE *\/ 128,\n \/* com::sun::star::beans::PropertyValue::OPTIONAL *\/ 256 };\n\n for (sal_uInt16 i = 0; i < 9; i++) {\n if (attribute & attributes[i]) {\n if (attributeValue.getLength() > 0) {\n cast |= true;\n attributeValue.append(\"|\");\n }\n switch (attributes[i]) {\n case 1:\n attributeValue.append(\"PropertyAttribute.MAYBEVOID\");\n break;\n case 2:\n attributeValue.append(\"PropertyAttribute.BOUND\");\n break;\n case 4:\n attributeValue.append(\"PropertyAttribute.CONSTRAINED\");\n break;\n case 8:\n attributeValue.append(\"PropertyAttribute.TRANSIENT\");\n break;\n case 16:\n attributeValue.append(\"PropertyAttribute.READONLY\");\n break;\n case 32:\n attributeValue.append(\"PropertyAttribute.MAYBEAMBIGIOUS\");\n break;\n case 64:\n attributeValue.append(\"PropertyAttribute.MAYBEDEFAULT\");\n break;\n case 128:\n attributeValue.append(\"PropertyAttribute.REMOVEABLE\");\n break;\n case 256:\n attributeValue.append(\"PropertyAttribute.OPTIONAL\");\n break;\n }\n }\n }\n if (cast) {\n attributeValue.insert(0, '(');\n attributeValue.append(')');\n }\n\n return cast;\n}\n\nvoid registerProperties(std::ostream& o,\n TypeManager const & manager,\n const StringPairHashMap& properties,\n const rtl::OString& indentation)\n{\n if (!properties.empty()) {\n StringPairHashMap::const_iterator iter =\n properties.begin();\n bool cast = false;\n rtl::OStringBuffer attributeValue;\n while (iter != properties.end()) {\n if (iter->second.second > 0) {\n cast = checkAttribute(attributeValue, iter->second.second);\n } else {\n cast = true;\n attributeValue.append('0');\n }\n\n o << indentation << \"registerProperty(\\\"\" << iter->first\n << \"\\\", \\\"m_\" << iter->first << \"\\\",\\n\"\n << indentation << \" \";\n if (cast)\n o << \"(short)\";\n\n o << attributeValue.makeStringAndClear() << \");\\n\";\n iter++;\n }\n }\n}\n\nvoid generateMethodBodies(std::ostream& o,\n ProgramOptions const & options,\n TypeManager const & manager,\n const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,\n const rtl::OString& indentation)\n{\n std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =\n interfaces.begin();\n codemaker::GeneratedTypeSet generated;\n while (iter != interfaces.end()) {\n if ( (*iter).equals(\"com.sun.star.lang.XServiceInfo\")) {\n generateXServiceInfoBodies(o);\n } else {\n typereg::Reader reader(manager.getTypeReader((*iter).replace('.','\/')));\n printMethods(o, options, manager, reader, generated, \"_\",\n indentation, true);\n }\n iter++;\n }\n}\n\nvoid generateClassDefinition(std::ostream& o,\n ProgramOptions const & options,\n TypeManager const & manager,\n const rtl::OString & classname,\n const std::hash_set< rtl::OString, rtl::OStringHash >& services,\n const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,\n const StringPairHashMap& properties,\n const rtl::OString& propertyhelper, bool supportxcomponent)\n{\n o << \"\\n\\npublic final class \" << classname << \" extends \";\n\n if (!interfaces.empty()) {\n if (propertyhelper.equals(\"_\")) {\n o << \"PropertySet\\n\";\n } else {\n if (supportxcomponent)\n o << \"ComponentBase\\n\";\n else\n o << \"WeakBase\\n\";\n }\n o << \" implements \";\n std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =\n interfaces.begin();\n while (iter != interfaces.end()) {\n o << (*iter);\n iter++;\n if (iter != interfaces.end())\n o << \",\\n \";\n }\n }\n o << \"\\n{\\n\";\n\n o << \" private final XComponentContext m_context;\\n\";\n\n \/\/ check property helper\n if (propertyhelper.getLength() > 1) {\n o << \" private final PropertySetMixin m_prophlp;\";\n }\n\n o << \" private static final java.lang.String m_implementationName = \"\n << classname << \".class.getName();\\n\";\n\n if (!services.empty()) {\n o << \" private static final java.lang.String[] m_serviceNames = {\\n\";\n std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =\n services.begin();\n while (iter != services.end()) {\n o << \" \\\"\" << (*iter).replace('\/','.') << \"\\\"\";\n iter++;\n if (iter != services.end())\n o << \",\\n\";\n else\n o << \" };\\n\";\n }\n }\n o << \"\\n public \" << classname << \"( XComponentContext context ) {\\n\"\n << \" m_context = context;\\n\";\n if (propertyhelper.equals(\"_\")) {\n registerProperties(o, manager, properties, \" \");\n } else {\n if (propertyhelper.getLength() > 1) {\n o << \" m_prophlp = new PropertySetMixin(\\n\"\n << \" m_context, this, new Type(\" << propertyhelper\n << \".class));\\n\";\n }\n }\n o << \" };\\n\\n\";\n\n if (!services.empty())\n generateCompFunctions(o, classname);\n\n generateMethodBodies(o, options, manager, interfaces, \" \");\n\n if (!properties.empty()) {\n StringPairHashMap::const_iterator iter =\n properties.begin();\n while (iter != properties.end()) {\n o << \" protected \";\n printType(o, options, manager, iter->second.first.replace('.','\/'),\n false, false);\n o << \" m_\" << iter->first << \";\\n\";\n iter++;\n }\n }\n\n \/\/ end of class definition\n o << \"}\\n\";\n}\n\nvoid generateSkeleton(ProgramOptions const & options,\n TypeManager const & manager,\n std::vector< rtl::OString > const & types,\n rtl::OString const & delegate)\n{\n std::hash_set< rtl::OString, rtl::OStringHash > interfaces;\n std::hash_set< rtl::OString, rtl::OStringHash > services;\n StringPairHashMap properties;\n bool attributes = false;\n bool serviceobject = false;\n bool supportxcomponent = false;\n\n std::vector< rtl::OString >::const_iterator iter = types.begin();\n while (iter != types.end()) {\n checkType(manager, *iter, interfaces, services, properties, attributes);\n iter++;\n }\n\n \/\/ check if service object or simple UNO object\n if (!services.empty())\n serviceobject = true;\n\n rtl::OString propertyhelper = checkPropertyHelper(manager, services);\n checkDefaultInterfaces(interfaces, services, propertyhelper);\n\n supportxcomponent = checkXComponentSupport(manager, interfaces);\n\n rtl::OString compFileName(createFileNameFromType(\n options.outputpath,\n options.implname.replace('.','\/'),\n \".java\"));\n\n rtl::OString tmpDir = getTempDir(compFileName);\n FileStream file;\n file.createTempFile(tmpDir);\n rtl::OString tmpFileName;\n\n if(!file.isValid())\n {\n rtl::OString message(\"cannot open \");\n message += compFileName + \" for writing\";\n throw CannotDumpException(message);\n } else {\n tmpFileName = file.getName();\n }\n file.close();\n std::ofstream oFile(tmpFileName.getStr(), std::ios_base::binary);\n\n try {\n generatePackage(oFile, options.implname);\n\n generateImports(oFile, interfaces, propertyhelper,\n serviceobject, supportxcomponent);\n\n rtl::OString classname(options.implname);\n sal_Int32 index = 0;\n if ((index = classname.lastIndexOf('.')) > 0)\n classname = classname.copy(index+1);\n\n generateClassDefinition(oFile, options, manager, classname, services,\n interfaces, properties, propertyhelper,\n supportxcomponent);\n\n oFile.close();\n OSL_VERIFY(makeValidTypeFile(compFileName, tmpFileName, sal_False));\n } catch(CannotDumpException& e) {\n\n std::cout << \"ERROR: \" << e.m_message.getStr() << \"\\n\";\n \/\/ remove existing type file if something goes wrong to ensure consistency\n if (fileExists(compFileName))\n removeTypeFile(compFileName);\n\n \/\/ remove tmp file if something goes wrong\n removeTypeFile(tmpFileName);\n }\n}\n\n} }\n\n\n#i52208# formatting\/*************************************************************************\n *\n * $RCSfile: javacompskeleton.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: jsc $ $Date: 2005-08-23 11:23:43 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"skeletonjava.hxx\"\n\nusing namespace ::codemaker::java;\n\nnamespace skeletonmaker { namespace java {\n\nvoid generatePackage(std::ostream & o, const rtl::OString & implname)\n{\n short count=0;\n sal_Int32 index = implname.lastIndexOf('.');\n if (index != -1) {\n o << \"package \" << implname.copy(0, index) << \";\\n\\n\";\n }\n}\n\nvoid generateImports(std::ostream & o,\n const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,\n const rtl::OString & propertyhelper,\n bool serviceobject, bool supportxcomponent)\n{\n o << \"import com.sun.star.uno.XComponentContext;\\n\";\n if (serviceobject) {\n o << \"import com.sun.star.lib.uno.helper.Factory;\\n\";\n o << \"import com.sun.star.lang.XSingleComponentFactory;\\n\";\n o << \"import com.sun.star.registry.XRegistryKey;\\n\";\n }\n\n if (!propertyhelper.equals(\"_\")) {\n if (supportxcomponent)\n o << \"import com.sun.star.lib.uno.helper.ComponentBase;\\n\";\n else\n o << \"import com.sun.star.lib.uno.helper.WeakBase;\\n\";\n }\n if (propertyhelper.getLength() > 0) {\n if (propertyhelper.equals(\"_\")) {\n o << \"import com.sun.star.lib.uno.helper.PropertySet;\\n\";\n o << \"import com.sun.star.beans.PropertyAttribute;\\n\";\n } else {\n o << \"import com.sun.star.uno.Type;\\n\";\n o << \"import com.sun.star.lib.uno.helper.PropertySetMixin;\\n\";\n }\n }\n\n\/\/ std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter = interfaces.begin();\n\/\/ while (iter != interfaces.end()) {\n\/\/ o << \"import \" << ((*iter).getStr()) << \";\\n\";\n\/\/ iter++;\n\/\/ }\n}\n\nvoid generateCompFunctions(std::ostream & o, const rtl::OString & classname)\n{\n o << \" public static XSingleComponentFactory __getComponentFactory(\"\n << \"String sImplementationName ) {\\n\"\n << \" XSingleComponentFactory xFactory = null;\\n\\n\"\n << \" if ( sImplementationName.equals( m_implementationName ) )\\n\"\n << \" xFactory = Factory.createComponentFactory(\"\n << classname << \".class, m_serviceNames);\\n\"\n << \" return xFactory;\\n }\\n\\n\";\n\n o << \" public static boolean __writeRegistryServiceInfo(\"\n << \"XRegistryKey xRegistryKey ) {\\n\"\n << \" return Factory.writeRegistryServiceInfo(m_implementationName,\\n\"\n << \" m_serviceNames,\\n\"\n << \" xRegistryKey);\\n\"\n << \" }\\n\\n\";\n}\n\nvoid generateXServiceInfoBodies(std::ostream& o)\n{\n o << \" \/* com.sun.star.lang.XServiceInfo *\/\\n\";\n o << \" public java.lang.String getImplementationName() {\\n\"\n << \" return m_implementationName;\\n }\\n\\n\";\n\n o << \" public boolean supportsService( java.lang.String sService ) {\\n\"\n << \" int len = m_serviceNames.length;\\n\\n\"\n << \" for( int i=0; i < len; i++) {\\n\"\n << \" if (sService.equals(m_serviceNames[i]))\\n\"\n << \" return true;\\n\"\n << \" }\\n return false;\\n }\\n\\n\";\n\n o << \" public java.lang.String[] getSupportedServiceNames() {\\n\"\n << \" return m_serviceNames;\\n }\\n\\n\";\n}\n\n\nbool checkAttribute(rtl::OStringBuffer& attributeValue, sal_uInt16 attribute) {\n bool cast = false;\n sal_uInt16 attributes[9] = {\n \/* com::sun::star::beans::PropertyValue::MAYBEVOID *\/ 1,\n \/* com::sun::star::beans::PropertyValue::BOUND *\/ 2,\n \/* com::sun::star::beans::PropertyValue::CONSTRAINED *\/ 4,\n \/* com::sun::star::beans::PropertyValue::TRANSIENT *\/ 8,\n \/* com::sun::star::beans::PropertyValue::READONLY *\/ 16,\n \/* com::sun::star::beans::PropertyValue::MAYBEAMBIGIOUS *\/ 32,\n \/* com::sun::star::beans::PropertyValue::MAYBEDEFAULT *\/ 64,\n \/* com::sun::star::beans::PropertyValue::REMOVEABLE *\/ 128,\n \/* com::sun::star::beans::PropertyValue::OPTIONAL *\/ 256 };\n\n for (sal_uInt16 i = 0; i < 9; i++) {\n if (attribute & attributes[i]) {\n if (attributeValue.getLength() > 0) {\n cast |= true;\n attributeValue.append(\"|\");\n }\n switch (attributes[i]) {\n case 1:\n attributeValue.append(\"PropertyAttribute.MAYBEVOID\");\n break;\n case 2:\n attributeValue.append(\"PropertyAttribute.BOUND\");\n break;\n case 4:\n attributeValue.append(\"PropertyAttribute.CONSTRAINED\");\n break;\n case 8:\n attributeValue.append(\"PropertyAttribute.TRANSIENT\");\n break;\n case 16:\n attributeValue.append(\"PropertyAttribute.READONLY\");\n break;\n case 32:\n attributeValue.append(\"PropertyAttribute.MAYBEAMBIGIOUS\");\n break;\n case 64:\n attributeValue.append(\"PropertyAttribute.MAYBEDEFAULT\");\n break;\n case 128:\n attributeValue.append(\"PropertyAttribute.REMOVEABLE\");\n break;\n case 256:\n attributeValue.append(\"PropertyAttribute.OPTIONAL\");\n break;\n }\n }\n }\n if (cast) {\n attributeValue.insert(0, '(');\n attributeValue.append(')');\n }\n\n return cast;\n}\n\nvoid registerProperties(std::ostream& o,\n TypeManager const & manager,\n const StringPairHashMap& properties,\n const rtl::OString& indentation)\n{\n if (!properties.empty()) {\n StringPairHashMap::const_iterator iter =\n properties.begin();\n bool cast = false;\n rtl::OStringBuffer attributeValue;\n while (iter != properties.end()) {\n if (iter->second.second > 0) {\n cast = checkAttribute(attributeValue, iter->second.second);\n } else {\n cast = true;\n attributeValue.append('0');\n }\n\n o << indentation << \"registerProperty(\\\"\" << iter->first\n << \"\\\", \\\"m_\" << iter->first << \"\\\",\\n\"\n << indentation << \" \";\n if (cast)\n o << \"(short)\";\n\n o << attributeValue.makeStringAndClear() << \");\\n\";\n iter++;\n }\n }\n}\n\nvoid generateMethodBodies(std::ostream& o,\n ProgramOptions const & options,\n TypeManager const & manager,\n const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,\n const rtl::OString& indentation)\n{\n std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =\n interfaces.begin();\n codemaker::GeneratedTypeSet generated;\n while (iter != interfaces.end()) {\n if ( (*iter).equals(\"com.sun.star.lang.XServiceInfo\")) {\n generateXServiceInfoBodies(o);\n } else {\n typereg::Reader reader(manager.getTypeReader((*iter).replace('.','\/')));\n printMethods(o, options, manager, reader, generated, \"_\",\n indentation, true);\n }\n iter++;\n }\n}\n\nvoid generateClassDefinition(std::ostream& o,\n ProgramOptions const & options,\n TypeManager const & manager,\n const rtl::OString & classname,\n const std::hash_set< rtl::OString, rtl::OStringHash >& services,\n const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,\n const StringPairHashMap& properties,\n const rtl::OString& propertyhelper, bool supportxcomponent)\n{\n o << \"\\n\\npublic final class \" << classname << \" extends \";\n\n if (!interfaces.empty()) {\n if (propertyhelper.equals(\"_\")) {\n o << \"PropertySet\\n\";\n } else {\n if (supportxcomponent)\n o << \"ComponentBase\\n\";\n else\n o << \"WeakBase\\n\";\n }\n o << \" implements \";\n std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =\n interfaces.begin();\n while (iter != interfaces.end()) {\n o << (*iter);\n iter++;\n if (iter != interfaces.end())\n o << \",\\n \";\n }\n }\n o << \"\\n{\\n\";\n\n o << \" private final XComponentContext m_context;\\n\";\n\n \/\/ check property helper\n if (propertyhelper.getLength() > 1) {\n o << \" private final PropertySetMixin m_prophlp;\\n\";\n }\n\n o << \" private static final java.lang.String m_implementationName = \"\n << classname << \".class.getName();\\n\";\n\n if (!services.empty()) {\n o << \" private static final java.lang.String[] m_serviceNames = {\\n\";\n std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =\n services.begin();\n while (iter != services.end()) {\n o << \" \\\"\" << (*iter).replace('\/','.') << \"\\\"\";\n iter++;\n if (iter != services.end())\n o << \",\\n\";\n else\n o << \" };\\n\";\n }\n }\n o << \"\\n public \" << classname << \"( XComponentContext context ) {\\n\"\n << \" m_context = context;\\n\";\n if (propertyhelper.equals(\"_\")) {\n registerProperties(o, manager, properties, \" \");\n } else {\n if (propertyhelper.getLength() > 1) {\n o << \" m_prophlp = new PropertySetMixin(\\n\"\n << \" m_context, this, new Type(\" << propertyhelper\n << \".class));\\n\";\n }\n }\n o << \" };\\n\\n\";\n\n if (!services.empty())\n generateCompFunctions(o, classname);\n\n generateMethodBodies(o, options, manager, interfaces, \" \");\n\n if (!properties.empty()) {\n StringPairHashMap::const_iterator iter =\n properties.begin();\n while (iter != properties.end()) {\n o << \" protected \";\n printType(o, options, manager, iter->second.first.replace('.','\/'),\n false, false);\n o << \" m_\" << iter->first << \";\\n\";\n iter++;\n }\n }\n\n \/\/ end of class definition\n o << \"}\\n\";\n}\n\nvoid generateSkeleton(ProgramOptions const & options,\n TypeManager const & manager,\n std::vector< rtl::OString > const & types,\n rtl::OString const & delegate)\n{\n std::hash_set< rtl::OString, rtl::OStringHash > interfaces;\n std::hash_set< rtl::OString, rtl::OStringHash > services;\n StringPairHashMap properties;\n bool attributes = false;\n bool serviceobject = false;\n bool supportxcomponent = false;\n\n std::vector< rtl::OString >::const_iterator iter = types.begin();\n while (iter != types.end()) {\n checkType(manager, *iter, interfaces, services, properties, attributes);\n iter++;\n }\n\n \/\/ check if service object or simple UNO object\n if (!services.empty())\n serviceobject = true;\n\n rtl::OString propertyhelper = checkPropertyHelper(manager, services);\n checkDefaultInterfaces(interfaces, services, propertyhelper);\n\n supportxcomponent = checkXComponentSupport(manager, interfaces);\n\n rtl::OString compFileName(createFileNameFromType(\n options.outputpath,\n options.implname.replace('.','\/'),\n \".java\"));\n\n rtl::OString tmpDir = getTempDir(compFileName);\n FileStream file;\n file.createTempFile(tmpDir);\n rtl::OString tmpFileName;\n\n if(!file.isValid())\n {\n rtl::OString message(\"cannot open \");\n message += compFileName + \" for writing\";\n throw CannotDumpException(message);\n } else {\n tmpFileName = file.getName();\n }\n file.close();\n std::ofstream oFile(tmpFileName.getStr(), std::ios_base::binary);\n\n try {\n generatePackage(oFile, options.implname);\n\n generateImports(oFile, interfaces, propertyhelper,\n serviceobject, supportxcomponent);\n\n rtl::OString classname(options.implname);\n sal_Int32 index = 0;\n if ((index = classname.lastIndexOf('.')) > 0)\n classname = classname.copy(index+1);\n\n generateClassDefinition(oFile, options, manager, classname, services,\n interfaces, properties, propertyhelper,\n supportxcomponent);\n\n oFile.close();\n OSL_VERIFY(makeValidTypeFile(compFileName, tmpFileName, sal_False));\n } catch(CannotDumpException& e) {\n\n std::cout << \"ERROR: \" << e.m_message.getStr() << \"\\n\";\n \/\/ remove existing type file if something goes wrong to ensure consistency\n if (fileExists(compFileName))\n removeTypeFile(compFileName);\n\n \/\/ remove tmp file if something goes wrong\n removeTypeFile(tmpFileName);\n }\n}\n\n} }\n\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include \"ProxyRequestContext.h\"\n\n#include \n\n#include \"mcrouter\/config.h\"\n#include \"mcrouter\/McrouterClient.h\"\n#include \"mcrouter\/proxy.h\"\n\nnamespace facebook { namespace memcache { namespace mcrouter {\n\nProxyRequestContext::ProxyRequestContext(\n proxy_t& pr,\n McMsgRef req,\n void (*enqReply)(ProxyRequestContext& preq),\n void* context,\n void (*reqComplete)(ProxyRequestContext& preq))\n : proxy_(pr),\n context_(context),\n enqueueReply_(enqReply),\n reqComplete_(reqComplete),\n logger_(&pr),\n additionalLogger_(&pr) {\n\n static const char* const kInternalGetPrefix = \"__mcrouter__.\";\n\n if (req->op == mc_op_get && !strncmp(req->key.str, kInternalGetPrefix,\n strlen(kInternalGetPrefix))) {\n \/* HACK: for backwards compatibility, convert (get, \"__mcrouter__.key\")\n into (get-service-info, \"key\") *\/\n auto copy = MutableMcMsgRef(mc_msg_dup(req.get()));\n copy->op = mc_op_get_service_info;\n copy->key.str += strlen(kInternalGetPrefix);\n copy->key.len -= strlen(kInternalGetPrefix);\n origReq_ = std::move(copy);\n } else {\n origReq_ = std::move(req);\n }\n\n stat_incr_safe(proxy_.stats, proxy_request_num_outstanding_stat);\n}\n\nProxyRequestContext::~ProxyRequestContext() {\n assert(replied_);\n if (reqComplete_) {\n reqComplete_(*this);\n }\n\n if (processing_) {\n --proxy_.numRequestsProcessing_;\n stat_decr(proxy_.stats, proxy_reqs_processing_stat, 1);\n proxy_.pump();\n }\n\n if (requester_) {\n requester_->decref();\n }\n\n stat_decr_safe(proxy_.stats, proxy_request_num_outstanding_stat);\n}\n\nuint64_t ProxyRequestContext::senderId() const {\n uint64_t id = 0;\n if (requester_) {\n id = requester_->clientId();\n }\n\n return id;\n}\n\nvoid ProxyRequestContext::sendReply(McReply newReply) {\n if (replied_) {\n return;\n }\n reply_ = std::move(newReply);\n replied_ = true;\n\n enqueueReply_(*this);\n\n stat_incr(proxy_.stats, request_replied_stat, 1);\n stat_incr(proxy_.stats, request_replied_count_stat, 1);\n if (mc_res_is_err(reply_->result())) {\n stat_incr(proxy_.stats, request_error_stat, 1);\n stat_incr(proxy_.stats, request_error_count_stat, 1);\n } else {\n stat_incr(proxy_.stats, request_success_stat, 1);\n stat_incr(proxy_.stats, request_success_count_stat, 1);\n }\n}\n\n}}}\nFix embedded mcrouter mode\/*\n * Copyright (c) 2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include \"ProxyRequestContext.h\"\n\n#include \n\n#include \"mcrouter\/config.h\"\n#include \"mcrouter\/McrouterClient.h\"\n#include \"mcrouter\/proxy.h\"\n\nnamespace facebook { namespace memcache { namespace mcrouter {\n\nProxyRequestContext::ProxyRequestContext(\n proxy_t& pr,\n McMsgRef req,\n void (*enqReply)(ProxyRequestContext& preq),\n void* context,\n void (*reqComplete)(ProxyRequestContext& preq))\n : proxy_(pr),\n context_(context),\n enqueueReply_(enqReply),\n reqComplete_(reqComplete),\n logger_(&pr),\n additionalLogger_(&pr) {\n\n static const char* const kInternalGetPrefix = \"__mcrouter__.\";\n\n if (req->op == mc_op_get && !strncmp(req->key.str, kInternalGetPrefix,\n strlen(kInternalGetPrefix))) {\n \/* HACK: for backwards compatibility, convert (get, \"__mcrouter__.key\")\n into (get-service-info, \"key\") *\/\n auto copy = MutableMcMsgRef(mc_msg_dup(req.get()));\n copy->op = mc_op_get_service_info;\n copy->key.str += strlen(kInternalGetPrefix);\n copy->key.len -= strlen(kInternalGetPrefix);\n origReq_ = std::move(copy);\n } else {\n origReq_ = std::move(req);\n }\n\n stat_incr_safe(proxy_.stats, proxy_request_num_outstanding_stat);\n}\n\nProxyRequestContext::~ProxyRequestContext() {\n assert(replied_);\n if (reqComplete_) {\n reqComplete_(*this);\n }\n\n if (processing_) {\n --proxy_.numRequestsProcessing_;\n stat_decr(proxy_.stats, proxy_reqs_processing_stat, 1);\n proxy_.pump();\n }\n\n if (requester_) {\n requester_->decref();\n }\n\n stat_decr_safe(proxy_.stats, proxy_request_num_outstanding_stat);\n}\n\nuint64_t ProxyRequestContext::senderId() const {\n uint64_t id = 0;\n if (requester_) {\n id = requester_->clientId();\n }\n\n return id;\n}\n\nvoid ProxyRequestContext::sendReply(McReply newReply) {\n if (replied_) {\n return;\n }\n reply_ = std::move(newReply);\n replied_ = true;\n\n if (LIKELY(enqueueReply_ != nullptr)) {\n enqueueReply_(*this);\n }\n\n stat_incr(proxy_.stats, request_replied_stat, 1);\n stat_incr(proxy_.stats, request_replied_count_stat, 1);\n if (mc_res_is_err(reply_->result())) {\n stat_incr(proxy_.stats, request_error_stat, 1);\n stat_incr(proxy_.stats, request_error_count_stat, 1);\n } else {\n stat_incr(proxy_.stats, request_success_stat, 1);\n stat_incr(proxy_.stats, request_success_count_stat, 1);\n }\n}\n\n}}}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \/\/ setw, set::precision, ...\n\n\nusing namespace std;\n\n#define EXP\n\n\/\/______________________________________________________________________________\nclass EXP msrOptionsElement\n{\n public:\n\n \/\/ creation from MusicXML\n \/\/ ------------------------------------------------------\n\n protected:\n\n msrOptionsElement (\n string optionsElementShortName,\n string optionsElementLongName,\n string optionsElementDescription);\n\n virtual ~msrOptionsElement();\n\n public:\n\n \/\/ set and get\n \/\/ ------------------------------------------------------\n\n string getOptionsElementShortName () const\n { return fOptionsElementShortName; }\n\n string getOptionsElementLongName () const\n { return fOptionsElementLongName; }\n\n string getOptionsElementDescription () const\n { return fOptionsElementDescription; }\n\n \/\/ services\n \/\/ ------------------------------------------------------\n\n string operator() () const\n { return fOptionsElementDescription; }\n \n \/\/ print\n \/\/ ------------------------------------------------------\n\n virtual void print (ostream& os) const;\n \n protected:\n \n string fOptionsElementShortName;\n string fOptionsElementLongName;\n string fOptionsElementDescription;\n};\n\/\/typedef SMARTP S_msrOptionsElement;\ntypedef msrOptionsElement* S_msrOptionsElement;\nEXP ostream& operator<< (ostream& os, const S_msrOptionsElement& elt);\n\n\nmsrOptionsElement::msrOptionsElement (\n string optionsElementShortName,\n string optionsElementLongName,\n string optionsElementDescription)\n{\n fOptionsElementShortName = optionsElementShortName; \n fOptionsElementLongName = optionsElementLongName; \n fOptionsElementDescription = optionsElementDescription; \n}\n\nmsrOptionsElement::~msrOptionsElement()\n{}\n\nostream& operator<< (ostream& os, const S_msrOptionsElement& elt)\n{\n elt->print (os);\n return os;\n}\n\nvoid msrOptionsElement::print (ostream& os) const\n{\n os << \"??? msrOptionsElement ???\" << endl;\n}\n\n\/\/______________________________________________________________________________\nclass EXP msrOptionsItem : public msrOptionsElement\n{\n public:\n \n msrOptionsItem (\n string optionsItemShortName,\n string optionsItemLongName,\n string optionsItemDescription)\n : msrOptionsElement (\n optionsItemShortName,\n optionsItemLongName,\n optionsItemDescription)\n {\n fOptionsItemHasBeenSelected = false;\n }\n \n void setOptionsItemHasBeenSelected ()\n { fOptionsItemHasBeenSelected = true; }\n \n bool getOptionsItemHasBeenSelected () const\n { return fOptionsItemHasBeenSelected; }\n \n void print (ostream& os) const\n {\n const int fieldWidth = 19;\n \n os <<\n setw(fieldWidth) <<\n \"fOptionsElementShortName\" << \" : \" << fOptionsElementShortName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementLongName\" << \" : \" << fOptionsElementLongName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementDescription\" << \" : \" << fOptionsElementDescription <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsItemHasBeenSelected\" << \" : \" << fOptionsItemHasBeenSelected <<\n endl;\n }\n\n protected:\n \n bool fOptionsItemHasBeenSelected;\n};\ntypedef msrOptionsItem* S_msrOptionsItem;\n\nostream& operator<< (ostream& os, const msrOptionsItem& elt)\n{\n elt.print (os);\n return os;\n}\n\n\/\/______________________________________________________________________________\nclass EXP msrOptionsIntItem : public msrOptionsItem\n{\n public:\n \n msrOptionsIntItem (\n string optionsItemShortName,\n string optionsItemLongName,\n string optionsItemDescription,\n int& optionsIntItemVariable)\n : msrOptionsItem (\n optionsItemShortName,\n optionsItemLongName,\n optionsItemDescription),\n fOptionsIntItemVariable (optionsIntItemVariable)\n {}\n \n void print (ostream& os) const\n {\n const int fieldWidth = 19;\n \n os <<\n setw(fieldWidth) <<\n \"fOptionsElementShortName\" << \" : \" << fOptionsElementShortName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementLongName\" << \" : \" << fOptionsElementLongName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementDescription\" << \" : \" << fOptionsElementDescription <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsItemHasBeenSelected\" << \" : \" << fOptionsItemHasBeenSelected <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsIntItemVariable\" << \" : \" << fOptionsIntItemVariable <<\n endl;\n }\n\n private:\n \n int& fOptionsIntItemVariable;\n};\ntypedef msrOptionsIntItem* S_msrOptionsIntItem;\n\nostream& operator<< (ostream& os, const msrOptionsIntItem& elt)\n{\n elt.print (os);\n return os;\n}\n\n\/\/______________________________________________________________________________\nclass EXP msrOptionsStringItem : public msrOptionsItem\n{\n public:\n \n msrOptionsStringItem (\n string optionsItemShortName,\n string optionsItemLongName,\n string optionsItemDescription,\n string& optionsStringItemVariable)\n : msrOptionsItem (\n optionsItemShortName,\n optionsItemLongName,\n optionsItemDescription),\n fOptionsStringItemVariable (optionsStringItemVariable)\n {}\n \n void print (ostream& os) const\n {\n const int fieldWidth = 19;\n \n os <<\n setw(fieldWidth) <<\n \"fOptionsElementShortName\" << \" : \" << fOptionsElementShortName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementLongName\" << \" : \" << fOptionsElementLongName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementDescription\" << \" : \" << fOptionsElementDescription <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsItemHasBeenSelected\" << \" : \" << fOptionsItemHasBeenSelected <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsStringItemVariable\" << \" : \" << fOptionsStringItemVariable <<\n endl;\n }\n\n private:\n \n string& fOptionsStringItemVariable;\n};\ntypedef msrOptionsStringItem* S_msrOptionsStringItem;\n\nostream& operator<< (ostream& os, const msrOptionsStringItem& elt)\n{\n elt.print (os);\n return os;\n}\n\n\/\/_______________________________________________________________________________\nclass EXP msrOptionsSubGroup : public msrOptionsElement\n{\n public:\n \n msrOptionsSubGroup (\n string optionsSubGroupShortName,\n string optionsSubGroupLongName,\n string optionsSubGroupDescription)\n : msrOptionsElement (\n optionsSubGroupShortName,\n optionsSubGroupLongName,\n optionsSubGroupDescription)\n {}\n \n void appendOptionsItem (\n S_msrOptionsItem optionsItem)\n {\n fOptionsSubGroupItemsList.push_back (\n optionsItem);\n }\n\n void print (ostream& os) const\n {\n const int fieldWidth = 19;\n \n os <<\n setw(fieldWidth) <<\n \"fOptionsElementShortName\" << \" : \" << fOptionsElementShortName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementLongName\" << \" : \" << fOptionsElementLongName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementDescription\" << \" : \" << fOptionsElementDescription <<\n endl;\n \n for (\n list::const_iterator\n i = fOptionsSubGroupItemsList.begin();\n i != fOptionsSubGroupItemsList.end();\n i++) {\n \/\/ print the element\n os << (*i);\n } \/\/ for\n }\n\n private:\n \n list\n fOptionsSubGroupItemsList;\n};\ntypedef msrOptionsSubGroup* S_msrOptionsSubGroup;\n\nostream& operator<< (ostream& os, const msrOptionsSubGroup& elt)\n{\n elt.print (os);\n return os;\n}\n\n\/\/_______________________________________________________________________________\nclass EXP msrOptionsGroup : public msrOptionsElement\n{\n public:\n \n msrOptionsGroup (\n string optionGroupShortName,\n string optionGroupLongName,\n string optionGroupDescription)\n : msrOptionsElement (\n optionGroupShortName,\n optionGroupLongName,\n optionGroupDescription)\n {}\n \n void appendOptionsSubGroup (\n S_msrOptionsSubGroup optionsSubGroup)\n {\n fOptionsGroupSubGroupsList.push_back (\n optionsSubGroup);\n }\n \n void print (ostream& os) const\n {\n const int fieldWidth = 19;\n \n os <<\n setw(fieldWidth) <<\n \"fOptionsElementShortName\" << \" : \" << fOptionsElementShortName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementLongName\" << \" : \" << fOptionsElementLongName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementDescription\" << \" : \" << fOptionsElementDescription <<\n endl;\n \n for (\n list::const_iterator\n i = fOptionsGroupSubGroupsList.begin();\n i != fOptionsGroupSubGroupsList.end();\n i++) {\n \/\/ print the element\n os << (*i);\n } \/\/ for\n }\n\n private:\n\n list\n fOptionsGroupSubGroupsList;\n};\ntypedef msrOptionsGroup* S_msrOptionsGroup;\n\nostream& operator<< (ostream& os, const msrOptionsGroup& elt)\n{\n elt.print (os);\n return os;\n}\n\n\/\/______________________________________________________________________________\nvoid optionError (string errorMessage)\n{\n cerr <<\n endl <<\n endl <<\n \"### ERROR in the options:\" <<\n endl <<\n errorMessage <<\n endl <<\n endl;\n \n exit(99);\n}\n\n\/\/_______________________________________________________________________________\n\/\/ a private variable\nmap pOptionShortNames;\n\nvoid checkOptionUniqueness (\n string optionLongName, string optionShortName)\n{\n if (optionShortName == optionLongName) {\n stringstream s;\n\n s <<\n \"option long name '\" << optionLongName << \"'\" <<\n \" is also used as short name\";\n \n optionError (s.str());\n }\n \n for (\n map::iterator i = pOptionShortNames.begin();\n i != pOptionShortNames.end();\n i++) {\n \n \/\/ is optionLongName in the options names map?\n if ((*i).first == optionLongName) {\n stringstream s;\n \n s <<\n \"option long name '\" << optionLongName << \"'\" <<\n \" is specified more that once\";\n \n optionError (s.str());\n }\n\n \/\/ is optionShortName in the options names map?\n if ((*i).second == optionShortName) {\n if (optionShortName.size ()) {\n stringstream s;\n \n s <<\n \"option short name '\" << optionShortName << \"'\" <<\n \" for option long name '\" << optionLongName << \"'\" <<\n \" is specified more that once\";\n \n optionError (s.str());\n }\n }\n } \/\/ for\n\n \/\/ everything OK, register the option names\n pOptionShortNames [optionLongName] = optionShortName;\n}\n\n\/\/_______________________________________________________________________________\nvoid analyzeOptions (\n int argc,\n char* argv[])\n{\n int n = 0;\n\n S_msrOptionsGroup optionsGroup =\n new msrOptionsGroup (\n \"hog\", \"helpOptionsGroup\", \" help for OptionsGroup\");\n\n S_msrOptionsSubGroup optionsSubGroup =\n new msrOptionsSubGroup (\n \"hosg\", \"helpOptionsSubGroup\", \" help for OptionsSubGroup\");\n\n optionsGroup->\n appendOptionsSubGroup (optionsSubGroup);\n\n int intVariable;\n S_msrOptionsIntItem optionsItem1 =\n new msrOptionsIntItem (\n \"is\", \"il\", \"intVariable\", intVariable);\n optionsSubGroup->\n appendOptionsItem (optionsItem1);\n \n string stringVariable;\n S_msrOptionsStringItem optionsItem2 =\n new msrOptionsStringItem (\n \"ss\", \"sl\", \"stringVariable\", stringVariable);\n optionsSubGroup->\n appendOptionsItem (optionsItem2);\n\n cerr <<\n \"optionsGroup:\" << endl <<\n optionsGroup <<\n endl;\n \n while (true) { \n if (argv [n] == 0)\n break;\n\n string currentElement = string (argv [n]);\n \n \/\/ print current element\n cout <<\n n << \":\" << currentElement <<\n endl;\n\n \/\/ handle current element\n if (currentElement [0] == '-') {\n \/\/ this is an option\n string elementTrailer =\n currentElement.substr (1, string::npos);\n\n \/* JMI\n cout <<\n \"elementTrailer '\" << elementTrailer << \"' is preceded by a dash\" <<\n endl;\n *\/\n\n if (elementTrailer.size ()) {\n if (elementTrailer [0] == '-') {\n \/\/ it is a double-dashed option\n string currentDoubleDashedOption =\n elementTrailer.substr (1, string::npos);\n \n cout <<\n \"'\" << currentDoubleDashedOption << \"' is a double-dashed option\" <<\n endl;\n }\n else {\n \/\/ it is a single-dashed option\n string currentSingleDashedOption =\n elementTrailer; \/\/.substr (1, string::npos);\n \n cout <<\n \"'\" << currentSingleDashedOption << \"' is a single-dashed option\" <<\n endl;\n }\n }\n \n else {\n cout <<\n \"'-' is the minimal single-dashed option\" <<\n endl;\n }\n }\n\n \/\/ next please\n n++;\n } \/\/ while\n}\n\nint main (int argc, char *argv[])\n{\n\/*\n vector vec {\n msrOptionItem (\"1short\", \"1long\", \"descr1\"),\n msrOptionItem (\"2short\", \"1long\", \"descr2\")\n };\n\n int counter = 0;\n cout <<\n \"The contents of 'vec' is:\" <<\n endl << endl;\n for (msrOptionItem i : vec)\n {\n cout <<\n \"Element \" << counter << \":\" <<\n endl <<\n i <<\n endl;\n counter++;\n }\n\nstruct option\n{\n const char *name;\n \/\/ has_arg can't be an enum because some compilers complain about\n \/\/ type mismatches in all the code that assumes it is an int.\n int has_arg;\n int *flag;\n int val;\n};\n*\/\n\n\/*\n vector myLongOptions {\n option (\"1short\", no_argument, &vec [0].fOptionSelected, 1),\n option (\"1long\", no_argument, &vec [0].fOptionSelected, 1),\n \n option (\"2short\", required_argument, &vec [1].fOptionSelected, 1),\n option (\"2long\", required_argument, &vec [1].fOptionSelected, 1),\n \n option (0, 0, 0, 0) \/\/ option trailer\n };\n*\/\n\n\n\/*\n cout << \"Which element should be printed? \";\n \n int n;\n cin >> n;\n\n cout << endl;\n \n if (n < vec.size ())\n cout <<\n \"Element \" << n << \" constains:\" <<\n endl <<\n endl <<\n vec [n] <<\n endl;\n else\n cout <<\n \"Sorry, only elements from 0 to \" << vec.size () - 1 << \" exist\" <<\n endl;\n*\/\n\n analyzeOptions (\n argc, argv);\n\n}\nOptionsTest 4#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \/\/ setw, set::precision, ...\n\n\nusing namespace std;\n\n#define EXP\n\n\/\/______________________________________________________________________________\nclass EXP msrOptionsElement\n{\n public:\n\n \/\/ creation from MusicXML\n \/\/ ------------------------------------------------------\n\n protected:\n\n msrOptionsElement (\n string optionsElementShortName,\n string optionsElementLongName,\n string optionsElementDescription);\n\n virtual ~msrOptionsElement();\n\n public:\n\n \/\/ set and get\n \/\/ ------------------------------------------------------\n\n string getOptionsElementShortName () const\n { return fOptionsElementShortName; }\n\n string getOptionsElementLongName () const\n { return fOptionsElementLongName; }\n\n string getOptionsElementDescription () const\n { return fOptionsElementDescription; }\n\n \/\/ services\n \/\/ ------------------------------------------------------\n\n string operator() () const\n { return fOptionsElementDescription; }\n \n \/\/ print\n \/\/ ------------------------------------------------------\n\n virtual void print (ostream& os) const;\n \n protected:\n \n string fOptionsElementShortName;\n string fOptionsElementLongName;\n string fOptionsElementDescription;\n};\n\/\/typedef SMARTP S_msrOptionsElement;\ntypedef msrOptionsElement* S_msrOptionsElement;\nEXP ostream& operator<< (ostream& os, const S_msrOptionsElement& elt);\n\n\nmsrOptionsElement::msrOptionsElement (\n string optionsElementShortName,\n string optionsElementLongName,\n string optionsElementDescription)\n{\n fOptionsElementShortName = optionsElementShortName; \n fOptionsElementLongName = optionsElementLongName; \n fOptionsElementDescription = optionsElementDescription; \n}\n\nmsrOptionsElement::~msrOptionsElement()\n{}\n\nostream& operator<< (ostream& os, const S_msrOptionsElement& elt)\n{\n elt->print (os);\n return os;\n}\n\nvoid msrOptionsElement::print (ostream& os) const\n{\n os << \"??? msrOptionsElement ???\" << endl;\n}\n\n\/\/______________________________________________________________________________\nclass EXP msrOptionsItem : public msrOptionsElement\n{\n public:\n \n msrOptionsItem (\n string optionsItemShortName,\n string optionsItemLongName,\n string optionsItemDescription)\n : msrOptionsElement (\n optionsItemShortName,\n optionsItemLongName,\n optionsItemDescription)\n {\n fOptionsItemHasBeenSelected = false;\n }\n \n void setOptionsItemHasBeenSelected ()\n { fOptionsItemHasBeenSelected = true; }\n \n bool getOptionsItemHasBeenSelected () const\n { return fOptionsItemHasBeenSelected; }\n \n void print (ostream& os) const\n {\n const int fieldWidth = 19;\n \n os <<\n \"OptionsItem ???:\" <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementShortName\" << \" : \" << fOptionsElementShortName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementLongName\" << \" : \" << fOptionsElementLongName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementDescription\" << \" : \" << fOptionsElementDescription <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsItemHasBeenSelected\" << \" : \" << fOptionsItemHasBeenSelected <<\n endl;\n }\n\n protected:\n \n bool fOptionsItemHasBeenSelected;\n};\ntypedef msrOptionsItem* S_msrOptionsItem;\n\nostream& operator<< (ostream& os, const msrOptionsItem& elt)\n{\n os <<\n \"OptionsItem ???:\" <<\n endl;\n elt.print (os);\n return os;\n}\n\n\/\/______________________________________________________________________________\nclass EXP msrOptionsIntItem : public msrOptionsItem\n{\n public:\n \n msrOptionsIntItem (\n string optionsItemShortName,\n string optionsItemLongName,\n string optionsItemDescription,\n int& optionsIntItemVariable)\n : msrOptionsItem (\n optionsItemShortName,\n optionsItemLongName,\n optionsItemDescription),\n fOptionsIntItemVariable (optionsIntItemVariable)\n {}\n \n void print (ostream& os) const\n {\n const int fieldWidth = 19;\n \n os <<\n \"OptionsIntItem:\" <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementShortName\" << \" : \" << fOptionsElementShortName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementLongName\" << \" : \" << fOptionsElementLongName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementDescription\" << \" : \" << fOptionsElementDescription <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsItemHasBeenSelected\" << \" : \" << fOptionsItemHasBeenSelected <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsIntItemVariable\" << \" : \" << fOptionsIntItemVariable <<\n endl;\n }\n\n private:\n \n int& fOptionsIntItemVariable;\n};\ntypedef msrOptionsIntItem* S_msrOptionsIntItem;\n\nostream& operator<< (ostream& os, const msrOptionsIntItem& elt)\n{\n os <<\n \"OptionsIntItem:\" <<\n endl;\n elt.print (os);\n return os;\n}\n\n\/\/______________________________________________________________________________\nclass EXP msrOptionsStringItem : public msrOptionsItem\n{\n public:\n \n msrOptionsStringItem (\n string optionsItemShortName,\n string optionsItemLongName,\n string optionsItemDescription,\n string& optionsStringItemVariable)\n : msrOptionsItem (\n optionsItemShortName,\n optionsItemLongName,\n optionsItemDescription),\n fOptionsStringItemVariable (optionsStringItemVariable)\n {}\n \n void print (ostream& os) const\n {\n const int fieldWidth = 19;\n \n os <<\n \"OptionsStringItem:\" <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementShortName\" << \" : \" << fOptionsElementShortName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementLongName\" << \" : \" << fOptionsElementLongName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementDescription\" << \" : \" << fOptionsElementDescription <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsItemHasBeenSelected\" << \" : \" << fOptionsItemHasBeenSelected <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsStringItemVariable\" << \" : \" << fOptionsStringItemVariable <<\n endl;\n }\n\n private:\n \n string& fOptionsStringItemVariable;\n};\ntypedef msrOptionsStringItem* S_msrOptionsStringItem;\n\nostream& operator<< (ostream& os, const msrOptionsStringItem& elt)\n{\n os <<\n \"OptionsStringItem:\" <<\n endl;\n elt.print (os);\n return os;\n}\n\n\/\/_______________________________________________________________________________\nclass EXP msrOptionsSubGroup : public msrOptionsElement\n{\n public:\n \n msrOptionsSubGroup (\n string optionsSubGroupShortName,\n string optionsSubGroupLongName,\n string optionsSubGroupDescription)\n : msrOptionsElement (\n optionsSubGroupShortName,\n optionsSubGroupLongName,\n optionsSubGroupDescription)\n {}\n \n void appendOptionsItem (\n S_msrOptionsItem optionsItem)\n {\n fOptionsSubGroupItemsList.push_back (\n optionsItem);\n }\n\n void print (ostream& os) const\n {\n const int fieldWidth = 19;\n \n os <<\n \"OptionsSubGroup:\" <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementShortName\" << \" : \" << fOptionsElementShortName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementLongName\" << \" : \" << fOptionsElementLongName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementDescription\" << \" : \" << fOptionsElementDescription <<\n endl;\n \n for (\n list::const_iterator\n i = fOptionsSubGroupItemsList.begin();\n i != fOptionsSubGroupItemsList.end();\n i++) {\n \/\/ print the element\n os << (*i);\n } \/\/ for\n }\n\n private:\n \n list\n fOptionsSubGroupItemsList;\n};\ntypedef msrOptionsSubGroup* S_msrOptionsSubGroup;\n\nostream& operator<< (ostream& os, const msrOptionsSubGroup& elt)\n{\n os <<\n \"OptionsSubGroup:\" <<\n endl;\n elt.print (os);\n return os;\n}\n\n\/\/_______________________________________________________________________________\nclass EXP msrOptionsGroup : public msrOptionsElement\n{\n public:\n \n msrOptionsGroup (\n string optionGroupShortName,\n string optionGroupLongName,\n string optionGroupDescription)\n : msrOptionsElement (\n optionGroupShortName,\n optionGroupLongName,\n optionGroupDescription)\n {}\n \n void appendOptionsSubGroup (\n S_msrOptionsSubGroup optionsSubGroup)\n {\n fOptionsGroupSubGroupsList.push_back (\n optionsSubGroup);\n }\n \n void print (ostream& os) const\n {\n const int fieldWidth = 19;\n \n os <<\n \"OptionsGroup:\" <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementShortName\" << \" : \" << fOptionsElementShortName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementLongName\" << \" : \" << fOptionsElementLongName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionsElementDescription\" << \" : \" << fOptionsElementDescription <<\n endl;\n \n for (\n list::const_iterator\n i = fOptionsGroupSubGroupsList.begin();\n i != fOptionsGroupSubGroupsList.end();\n i++) {\n \/\/ print the element\n os << (*i);\n } \/\/ for\n }\n\n private:\n\n list\n fOptionsGroupSubGroupsList;\n};\ntypedef msrOptionsGroup* S_msrOptionsGroup;\n\nostream& operator<< (ostream& os, const msrOptionsGroup& elt)\n{\n os <<\n \"OptionsGroup:\" <<\n endl;\n elt.print (os);\n return os;\n}\n\n\/\/______________________________________________________________________________\nvoid optionError (string errorMessage)\n{\n cerr <<\n endl <<\n endl <<\n \"### ERROR in the options:\" <<\n endl <<\n errorMessage <<\n endl <<\n endl;\n \n exit(99);\n}\n\n\/\/_______________________________________________________________________________\n\/\/ a private variable\nmap pOptionShortNames;\n\nvoid checkOptionUniqueness (\n string optionLongName, string optionShortName)\n{\n if (optionShortName == optionLongName) {\n stringstream s;\n\n s <<\n \"option long name '\" << optionLongName << \"'\" <<\n \" is also used as short name\";\n \n optionError (s.str());\n }\n \n for (\n map::iterator i = pOptionShortNames.begin();\n i != pOptionShortNames.end();\n i++) {\n \n \/\/ is optionLongName in the options names map?\n if ((*i).first == optionLongName) {\n stringstream s;\n \n s <<\n \"option long name '\" << optionLongName << \"'\" <<\n \" is specified more that once\";\n \n optionError (s.str());\n }\n\n \/\/ is optionShortName in the options names map?\n if ((*i).second == optionShortName) {\n if (optionShortName.size ()) {\n stringstream s;\n \n s <<\n \"option short name '\" << optionShortName << \"'\" <<\n \" for option long name '\" << optionLongName << \"'\" <<\n \" is specified more that once\";\n \n optionError (s.str());\n }\n }\n } \/\/ for\n\n \/\/ everything OK, register the option names\n pOptionShortNames [optionLongName] = optionShortName;\n}\n\n\/\/_______________________________________________________________________________\nvoid analyzeOptions (\n int argc,\n char* argv[])\n{\n int n = 0;\n\n S_msrOptionsGroup optionsGroup =\n new msrOptionsGroup (\n \"hog\", \"helpOptionsGroup\", \" help for OptionsGroup\");\n\n S_msrOptionsSubGroup optionsSubGroup =\n new msrOptionsSubGroup (\n \"hosg\", \"helpOptionsSubGroup\", \" help for OptionsSubGroup\");\n\n optionsGroup->\n appendOptionsSubGroup (optionsSubGroup);\n\n int intVariable = -3;\n S_msrOptionsIntItem optionsItem1 =\n new msrOptionsIntItem (\n \"is\", \"il\", \"intVariable\", intVariable);\n optionsSubGroup->\n appendOptionsItem (optionsItem1);\n \n string stringVariable = \"a string\";\n S_msrOptionsStringItem optionsItem2 =\n new msrOptionsStringItem (\n \"ss\", \"sl\", \"stringVariable\", stringVariable);\n optionsSubGroup->\n appendOptionsItem (optionsItem2);\n\n cerr <<\n \"optionsItem1:\" << endl <<\n optionsItem1 <<\n endl;\n \n cerr <<\n \"optionsGroup:\" << endl <<\n optionsGroup <<\n endl;\n \n while (true) { \n if (argv [n] == 0)\n break;\n\n string currentElement = string (argv [n]);\n \n \/\/ print current element\n cout <<\n n << \":\" << currentElement <<\n endl;\n\n \/\/ handle current element\n if (currentElement [0] == '-') {\n \/\/ this is an option\n string elementTrailer =\n currentElement.substr (1, string::npos);\n\n \/* JMI\n cout <<\n \"elementTrailer '\" << elementTrailer << \"' is preceded by a dash\" <<\n endl;\n *\/\n\n if (elementTrailer.size ()) {\n if (elementTrailer [0] == '-') {\n \/\/ it is a double-dashed option\n string currentDoubleDashedOption =\n elementTrailer.substr (1, string::npos);\n \n cout <<\n \"'\" << currentDoubleDashedOption << \"' is a double-dashed option\" <<\n endl;\n }\n else {\n \/\/ it is a single-dashed option\n string currentSingleDashedOption =\n elementTrailer; \/\/.substr (1, string::npos);\n \n cout <<\n \"'\" << currentSingleDashedOption << \"' is a single-dashed option\" <<\n endl;\n }\n }\n \n else {\n cout <<\n \"'-' is the minimal single-dashed option\" <<\n endl;\n }\n }\n\n \/\/ next please\n n++;\n } \/\/ while\n}\n\nint main (int argc, char *argv[])\n{\n\/*\n vector vec {\n msrOptionItem (\"1short\", \"1long\", \"descr1\"),\n msrOptionItem (\"2short\", \"1long\", \"descr2\")\n };\n\n int counter = 0;\n cout <<\n \"The contents of 'vec' is:\" <<\n endl << endl;\n for (msrOptionItem i : vec)\n {\n cout <<\n \"Element \" << counter << \":\" <<\n endl <<\n i <<\n endl;\n counter++;\n }\n\nstruct option\n{\n const char *name;\n \/\/ has_arg can't be an enum because some compilers complain about\n \/\/ type mismatches in all the code that assumes it is an int.\n int has_arg;\n int *flag;\n int val;\n};\n*\/\n\n\/*\n vector myLongOptions {\n option (\"1short\", no_argument, &vec [0].fOptionSelected, 1),\n option (\"1long\", no_argument, &vec [0].fOptionSelected, 1),\n \n option (\"2short\", required_argument, &vec [1].fOptionSelected, 1),\n option (\"2long\", required_argument, &vec [1].fOptionSelected, 1),\n \n option (0, 0, 0, 0) \/\/ option trailer\n };\n*\/\n\n\n\/*\n cout << \"Which element should be printed? \";\n \n int n;\n cin >> n;\n\n cout << endl;\n \n if (n < vec.size ())\n cout <<\n \"Element \" << n << \" constains:\" <<\n endl <<\n endl <<\n vec [n] <<\n endl;\n else\n cout <<\n \"Sorry, only elements from 0 to \" << vec.size () - 1 << \" exist\" <<\n endl;\n*\/\n\n analyzeOptions (\n argc, argv);\n\n}\n<|endoftext|>"} {"text":"\/*\nCopyright (C) 2018 Jakob Sinclair\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this program. If not, see .\n*\/\n\n#include \"game.hpp\"\n#include \n#include \n#include \"entity.hpp\"\n#include \"shader.hpp\"\n#include \"input.hpp\"\n#include \"graphics.hpp\"\n#include \"rect2d.hpp\"\n#include \"camera.hpp\"\n#include \"sprite.hpp\"\n#include \"cache.hpp\"\n#include \"luascript.hpp\"\n#include \"iomanager.hpp\"\n\nGame::Game()\n{\n\t;\n}\n\nGame::~Game()\n{\n\t;\n}\n\nbool Game::Init()\n{\n\t\/\/if (Res.CreateModel(\"nanosuit\", \"Model\/nanosuit.obj\") != nullptr)\n\t\/\/\tm_Model = static_cast(Res.GetResource(\"nanosuit\")->Data());\n\n\n\tm_EM.AddEntity(std::make_unique(\"Camera\"));\n\tm_EM.GetEntity(\"Camera\").AddComponent(std::make_unique(1280, 720));\t\n\n\tRes.LoadSample(\"sound.ogg\")->Play();\n\tm_EM.GetSystem().RegisterComponent(std::type_index(typeid(Sprite)));\n\n\tm_EM.AddEntity(std::make_unique(\"Player\"));\n\tauto &sprite = m_EM.GetEntity(\"Player\").AddComponent(std::make_unique(Res.LoadTex(\"sprite.png\"),\n\t 110, 200,\n\t std::vector({25, 29, 135, 229, 150, 29, 260, 229, 287, 29, 397, 229, 438, 29, 548, 229})));\t\n\n\tLuaScript script(\"player.lua\");\n\tint posX = script.Get(\"player.pos.X\");\n\tint posY = script.Get(\"player.pos.Y\");\n\n\tsprite.SetImageSpeed(0.1f);\n\tsprite.SetPos(glm::vec3((float)posX, (float)posY, 0.0f));\n\n\treturn true;\n}\n\nvoid Game::Update(double delta)\n{\n\t\/*\n\tfloat speed = 3.0f * (float)delta;\n\tfloat xoffset = m_Input.GetMousePos().x - m_LastX;\n\tfloat yoffset = m_LastY - m_Input.GetMousePos().y;\n\tm_LastX = m_Input.GetMousePos().x;\n\tm_LastY = m_Input.GetMousePos().y;\n\n\tfloat sensitivity = 0.05f;\n\txoffset *= sensitivity;\n\tyoffset *= sensitivity;\n\tm_Yaw += xoffset;\n\tm_Pitch += yoffset;\n\n\tif (m_Pitch > 89.0f)\n\t\tm_Pitch = 89.0f;\n\telse if (m_Pitch < -89.0f)\n\t\tm_Pitch = -89.0f;\n\n\tglm::vec3 front;\n\tfront.x = cos(glm::radians(m_Pitch)) * cos(glm::radians(m_Yaw));\n\tfront.y = sin(glm::radians(m_Pitch));\n\tfront.z = sin(glm::radians(m_Yaw)) * cos(glm::radians(m_Pitch));\n\tm_Front = glm::normalize(front);\n\t*\/\n\tif (m_EM.GetSystem().GetKey(GLFW_KEY_ESCAPE))\n\t\tm_Quit = true;\n\telse if (m_EM.GetSystem().GetKey(GLFW_KEY_SPACE))\n\t\tRes.LoadSample(\"sound.ogg\")->Play();\n\t\/*if (m_Input.GetKey(GLFW_KEY_W))\n\t\tm_Pos += speed * m_Front;\n\tif (m_Input.GetKey(GLFW_KEY_S))\n\t\tm_Pos -= speed * m_Front;\n\tif (m_Input.GetKey(GLFW_KEY_A))\n\t\tm_Pos -= glm::normalize(glm::cross(m_Front, m_Up)) * speed;\n\tif (m_Input.GetKey(GLFW_KEY_D))\n\t\tm_Pos += glm::normalize(glm::cross(m_Front, m_Up)) * speed;\n\tm_EntityManager.GetCamera()->SetPos(m_Pos);\n\tm_EntityManager.GetCamera()->SetDir(m_Front);*\/\n}Remove all 3D code from 2D demo\/*\nCopyright (C) 2018 Jakob Sinclair\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this program. If not, see .\n*\/\n\n#include \"game.hpp\"\n#include \n#include \n#include \"entity.hpp\"\n#include \"shader.hpp\"\n#include \"input.hpp\"\n#include \"graphics.hpp\"\n#include \"rect2d.hpp\"\n#include \"camera.hpp\"\n#include \"sprite.hpp\"\n#include \"cache.hpp\"\n#include \"luascript.hpp\"\n#include \"iomanager.hpp\"\n\nGame::Game()\n{\n\t;\n}\n\nGame::~Game()\n{\n\t;\n}\n\nbool Game::Init()\n{\n\tm_EM.AddEntity(std::make_unique(\"Camera\"));\n\tm_EM.GetEntity(\"Camera\").AddComponent(std::make_unique(1280, 720));\t\n\n\tRes.LoadSample(\"sound.ogg\")->Play();\n\tm_EM.GetSystem().RegisterComponent(std::type_index(typeid(Sprite)));\n\n\tm_EM.AddEntity(std::make_unique(\"Player\"));\n\tauto &sprite = m_EM.GetEntity(\"Player\").AddComponent(std::make_unique(Res.LoadTex(\"sprite.png\"),\n\t 110, 200,\n\t std::vector({25, 29, 135, 229, 150, 29, 260, 229, 287, 29, 397, 229, 438, 29, 548, 229})));\t\n\n\tLuaScript script(\"player.lua\");\n\tint posX = script.Get(\"player.pos.X\");\n\tint posY = script.Get(\"player.pos.Y\");\n\n\tsprite.SetImageSpeed(0.1f);\n\tsprite.SetPos(glm::vec3((float)posX, (float)posY, 0.0f));\n\n\treturn true;\n}\n\nvoid Game::Update(double delta)\n{\n\tif (m_EM.GetSystem().GetKey(GLFW_KEY_ESCAPE))\n\t\tm_Quit = true;\n\telse if (m_EM.GetSystem().GetKey(GLFW_KEY_SPACE))\n\t\tRes.LoadSample(\"sound.ogg\")->Play();\n}<|endoftext|>"} {"text":" \/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: aboutdialog.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: sj $ $Date: 2007-07-10 16:16:25 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ABOUTDIALOG_HXX\n#include \"aboutdialog.hxx\"\n#endif\n#ifndef OPTIMIZATIONSTATS_HXX\n#include \"optimizationstats.hxx\"\n#endif\n#ifndef _FILEOPEN_DIALOG_HXX_\n#include \"fileopendialog.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_\n#include \n#endif\n\n\/\/ ---------------\n\/\/ - ABOUTDIALOG -\n\/\/ ---------------\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star::ui;\nusing namespace ::com::sun::star::awt;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::frame;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::script;\nusing namespace ::com::sun::star::container;\n\n#define ABOUT_DIALOG_WIDTH 220\n#define ABOUT_DIALOG_HEIGHT 221\n\n\/\/ -----------------------------------------------------------------------------\n\n\nrtl::OUString InsertFixedText( AboutDialog& rAboutDialog, const rtl::OUString& rControlName, const OUString& rLabel,\n sal_Int32 nXPos, sal_Int32 nYPos, sal_Int32 nWidth, sal_Int32 nHeight, sal_Bool bMultiLine, sal_Int16 nTabIndex )\n{\n OUString pNames[] = {\n TKGet( TK_Height ),\n TKGet( TK_Label ),\n TKGet( TK_MultiLine ),\n TKGet( TK_PositionX ),\n TKGet( TK_PositionY ),\n TKGet( TK_Step ),\n TKGet( TK_TabIndex ),\n TKGet( TK_Width ) };\n\n Any pValues[] = {\n Any( nHeight ),\n Any( rLabel ),\n Any( bMultiLine ),\n Any( nXPos ),\n Any( nYPos ),\n Any( (sal_Int16)0 ),\n Any( nTabIndex ),\n Any( nWidth ) };\n\n sal_Int32 nCount = sizeof( pNames ) \/ sizeof( OUString );\n\n Sequence< rtl::OUString > aNames( pNames, nCount );\n Sequence< Any > aValues( pValues, nCount );\n\n rAboutDialog.insertFixedText( rControlName, aNames, aValues );\n return rControlName;\n}\n\nrtl::OUString InsertSeparator( AboutDialog& rAboutDialog, const OUString& rControlName, sal_Int32 nOrientation,\n sal_Int32 nPosX, sal_Int32 nPosY, sal_Int32 nWidth, sal_Int32 nHeight )\n{\n OUString pNames[] = {\n TKGet( TK_Height ),\n TKGet( TK_Orientation ),\n TKGet( TK_PositionX ),\n TKGet( TK_PositionY ),\n TKGet( TK_Step ),\n TKGet( TK_Width ) };\n\n Any pValues[] = {\n Any( nHeight ),\n Any( nOrientation ),\n Any( nPosX ),\n Any( nPosY ),\n Any( sal_Int16( 0 ) ),\n Any( nWidth ) };\n\n sal_Int32 nCount = sizeof( pNames ) \/ sizeof( OUString );\n\n Sequence< rtl::OUString > aNames( pNames, nCount );\n Sequence< Any > aValues( pValues, nCount );\n\n rAboutDialog.insertControlModel( OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.awt.UnoControlFixedLineModel\" ) ),\n rControlName, aNames, aValues );\n return rControlName;\n}\n\nrtl::OUString InsertImage( AboutDialog& rAboutDialog, const OUString& rControlName, const OUString& rURL,\n sal_Int32 nPosX, sal_Int32 nPosY, sal_Int32 nWidth, sal_Int32 nHeight )\n{\n OUString pNames[] = {\n TKGet( TK_Border ),\n TKGet( TK_Height ),\n TKGet( TK_ImageURL ),\n TKGet( TK_PositionX ),\n TKGet( TK_PositionY ),\n TKGet( TK_ScaleImage ),\n TKGet( TK_Width ) };\n\n Any pValues[] = {\n Any( sal_Int16( 1 ) ),\n Any( nHeight ),\n Any( rURL ),\n Any( nPosX ),\n Any( nPosY ),\n Any( sal_True ),\n Any( nWidth ) };\n sal_Int32 nCount = sizeof( pNames ) \/ sizeof( OUString );\n\n Sequence< rtl::OUString > aNames( pNames, nCount );\n Sequence< Any > aValues( pValues, nCount );\n\n rAboutDialog.insertImage( rControlName, aNames, aValues );\n return rControlName;\n}\n\nrtl::OUString InsertButton( AboutDialog& rAboutDialog, const OUString& rControlName, Reference< XActionListener >& xActionListener,\n sal_Int32 nXPos, sal_Int32 nYPos, sal_Int32 nWidth, sal_Int32 nHeight, sal_Int16 nTabIndex, PPPOptimizerTokenEnum nResID )\n{\n OUString pNames[] = {\n TKGet( TK_Enabled ),\n TKGet( TK_Height ),\n TKGet( TK_Label ),\n TKGet( TK_PositionX ),\n TKGet( TK_PositionY ),\n TKGet( TK_PushButtonType ),\n TKGet( TK_Step ),\n TKGet( TK_TabIndex ),\n TKGet( TK_Width ) };\n\n Any pValues[] = {\n Any( sal_True ),\n Any( nHeight ),\n Any( rAboutDialog.getString( nResID ) ),\n Any( nXPos ),\n Any( nYPos ),\n Any( static_cast< sal_Int16 >( PushButtonType_OK ) ),\n Any( (sal_Int16)0 ),\n Any( nTabIndex ),\n Any( nWidth ) };\n\n\n sal_Int32 nCount = sizeof( pNames ) \/ sizeof( OUString );\n\n Sequence< rtl::OUString > aNames( pNames, nCount );\n Sequence< Any > aValues( pValues, nCount );\n\n rAboutDialog.insertButton( rControlName, xActionListener, aNames, aValues );\n return rControlName;\n}\n\nvoid AboutDialog::InitDialog()\n{\n \/\/ setting the dialog properties\n OUString pNames[] = {\n TKGet( TK_Closeable ),\n TKGet( TK_Height ),\n TKGet( TK_Moveable ),\n TKGet( TK_PositionX ),\n TKGet( TK_PositionY ),\n TKGet( TK_Title ),\n TKGet( TK_Width ) };\n\n Any pValues[] = {\n Any( sal_True ),\n Any( sal_Int32( ABOUT_DIALOG_HEIGHT ) ),\n Any( sal_True ),\n Any( sal_Int32( 113 ) ),\n Any( sal_Int32( 42 ) ),\n Any( getString( STR_ABOUT_VERSION ) ),\n Any( sal_Int32( ABOUT_DIALOG_WIDTH ) ) };\n\n sal_Int32 nCount = sizeof( pNames ) \/ sizeof( OUString );\n\n Sequence< rtl::OUString > aNames( pNames, nCount );\n Sequence< Any > aValues( pValues, nCount );\n\n rtl::OUString sBitmapPath( getPath( TK_BitmapPath ) );\n rtl::OUString sBitmap( rtl::OUString::createFromAscii( \"\/aboutlogo.png\" ) );\n rtl::OUString sURL( sBitmapPath += sBitmap );\n\n mxDialogModelMultiPropertySet->setPropertyValues( aNames, aValues );\n\n int nWidth = (int) getMapsFromPixels( 387 );\n\/\/ int nHeight = (int) getMapsFromPixels( 95 );\n\n InsertImage( *this, rtl::OUString( rtl::OUString::createFromAscii( \"aboutimage\" ) ), sURL, 0, 0, ABOUT_DIALOG_WIDTH, 60 );\n InsertFixedText( *this, rtl::OUString( rtl::OUString::createFromAscii( \"fixedtext\" ) ), getString( STR_ABOUT_PRN ), 9, 66, ABOUT_DIALOG_WIDTH - 18, 127, sal_True, 0 );\n InsertSeparator( *this, rtl::OUString( rtl::OUString::createFromAscii( \"separator\" ) ), 0, 0, 196, ABOUT_DIALOG_WIDTH, 8 );\n InsertButton( *this, rtl::OUString( rtl::OUString::createFromAscii( \"button\" ) ), mxActionListener, ( nWidth \/ 2 ) - 25, 204, 50, 14, 1, STR_OK );\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nAboutDialog::AboutDialog( const Reference< XComponentContext > &rxMSF, Reference< XFrame >& rxFrame ) :\n UnoDialog( rxMSF, rxFrame ),\n ConfigurationAccess( rxMSF, NULL ),\n mxMSF( rxMSF ),\n mxFrame( rxFrame ),\n mxActionListener( new AboutActionListener( *this ) )\n{\n Reference< XFrame > xFrame( mxController->getFrame() );\n Reference< XWindow > xContainerWindow( xFrame->getContainerWindow() );\n Reference< XWindowPeer > xWindowPeer( xContainerWindow, UNO_QUERY_THROW );\n createWindowPeer( xWindowPeer );\n\n InitDialog();\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nAboutDialog::~AboutDialog()\n{\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nsal_Bool AboutDialog::execute()\n{\n UnoDialog::execute();\n return mbStatus;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid AboutActionListener::actionPerformed( const ActionEvent& rEvent )\n throw ( com::sun::star::uno::RuntimeException )\n{\n if ( rEvent.ActionCommand == rtl::OUString( rtl::OUString::createFromAscii( \"button\" ) ) )\n {\n mrAboutDialog.endExecute( sal_True );\n }\n}\nvoid AboutActionListener::disposing( const ::com::sun::star::lang::EventObject& \/* Source *\/ )\n throw ( com::sun::star::uno::RuntimeException )\n{\n}\nfixed about image scaling \/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: aboutdialog.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: sj $ $Date: 2007-08-17 15:10:57 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ABOUTDIALOG_HXX\n#include \"aboutdialog.hxx\"\n#endif\n#ifndef OPTIMIZATIONSTATS_HXX\n#include \"optimizationstats.hxx\"\n#endif\n#ifndef _FILEOPEN_DIALOG_HXX_\n#include \"fileopendialog.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_\n#include \n#endif\n\n\/\/ ---------------\n\/\/ - ABOUTDIALOG -\n\/\/ ---------------\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star::ui;\nusing namespace ::com::sun::star::awt;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::frame;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::script;\nusing namespace ::com::sun::star::container;\n\n#define ABOUT_DIALOG_WIDTH 200\n#define ABOUT_DIALOG_HEIGHT 221\n\n\/\/ -----------------------------------------------------------------------------\n\n\nrtl::OUString InsertFixedText( AboutDialog& rAboutDialog, const rtl::OUString& rControlName, const OUString& rLabel,\n sal_Int32 nXPos, sal_Int32 nYPos, sal_Int32 nWidth, sal_Int32 nHeight, sal_Bool bMultiLine, sal_Int16 nTabIndex )\n{\n OUString pNames[] = {\n TKGet( TK_Height ),\n TKGet( TK_Label ),\n TKGet( TK_MultiLine ),\n TKGet( TK_PositionX ),\n TKGet( TK_PositionY ),\n TKGet( TK_Step ),\n TKGet( TK_TabIndex ),\n TKGet( TK_Width ) };\n\n Any pValues[] = {\n Any( nHeight ),\n Any( rLabel ),\n Any( bMultiLine ),\n Any( nXPos ),\n Any( nYPos ),\n Any( (sal_Int16)0 ),\n Any( nTabIndex ),\n Any( nWidth ) };\n\n sal_Int32 nCount = sizeof( pNames ) \/ sizeof( OUString );\n\n Sequence< rtl::OUString > aNames( pNames, nCount );\n Sequence< Any > aValues( pValues, nCount );\n\n rAboutDialog.insertFixedText( rControlName, aNames, aValues );\n return rControlName;\n}\n\nrtl::OUString InsertSeparator( AboutDialog& rAboutDialog, const OUString& rControlName, sal_Int32 nOrientation,\n sal_Int32 nPosX, sal_Int32 nPosY, sal_Int32 nWidth, sal_Int32 nHeight )\n{\n OUString pNames[] = {\n TKGet( TK_Height ),\n TKGet( TK_Orientation ),\n TKGet( TK_PositionX ),\n TKGet( TK_PositionY ),\n TKGet( TK_Step ),\n TKGet( TK_Width ) };\n\n Any pValues[] = {\n Any( nHeight ),\n Any( nOrientation ),\n Any( nPosX ),\n Any( nPosY ),\n Any( sal_Int16( 0 ) ),\n Any( nWidth ) };\n\n sal_Int32 nCount = sizeof( pNames ) \/ sizeof( OUString );\n\n Sequence< rtl::OUString > aNames( pNames, nCount );\n Sequence< Any > aValues( pValues, nCount );\n\n rAboutDialog.insertControlModel( OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.awt.UnoControlFixedLineModel\" ) ),\n rControlName, aNames, aValues );\n return rControlName;\n}\n\nrtl::OUString InsertImage( AboutDialog& rAboutDialog, const OUString& rControlName, const OUString& rURL,\n sal_Int32 nPosX, sal_Int32 nPosY, sal_Int32 nWidth, sal_Int32 nHeight )\n{\n OUString pNames[] = {\n TKGet( TK_Border ),\n TKGet( TK_Height ),\n TKGet( TK_ImageURL ),\n TKGet( TK_PositionX ),\n TKGet( TK_PositionY ),\n TKGet( TK_ScaleImage ),\n TKGet( TK_Width ) };\n\n Any pValues[] = {\n Any( sal_Int16( 1 ) ),\n Any( nHeight ),\n Any( rURL ),\n Any( nPosX ),\n Any( nPosY ),\n Any( sal_False ),\n Any( nWidth ) };\n sal_Int32 nCount = sizeof( pNames ) \/ sizeof( OUString );\n\n Sequence< rtl::OUString > aNames( pNames, nCount );\n Sequence< Any > aValues( pValues, nCount );\n\n rAboutDialog.insertImage( rControlName, aNames, aValues );\n return rControlName;\n}\n\nrtl::OUString InsertButton( AboutDialog& rAboutDialog, const OUString& rControlName, Reference< XActionListener >& xActionListener,\n sal_Int32 nXPos, sal_Int32 nYPos, sal_Int32 nWidth, sal_Int32 nHeight, sal_Int16 nTabIndex, PPPOptimizerTokenEnum nResID )\n{\n OUString pNames[] = {\n TKGet( TK_Enabled ),\n TKGet( TK_Height ),\n TKGet( TK_Label ),\n TKGet( TK_PositionX ),\n TKGet( TK_PositionY ),\n TKGet( TK_PushButtonType ),\n TKGet( TK_Step ),\n TKGet( TK_TabIndex ),\n TKGet( TK_Width ) };\n\n Any pValues[] = {\n Any( sal_True ),\n Any( nHeight ),\n Any( rAboutDialog.getString( nResID ) ),\n Any( nXPos ),\n Any( nYPos ),\n Any( static_cast< sal_Int16 >( PushButtonType_OK ) ),\n Any( (sal_Int16)0 ),\n Any( nTabIndex ),\n Any( nWidth ) };\n\n\n sal_Int32 nCount = sizeof( pNames ) \/ sizeof( OUString );\n\n Sequence< rtl::OUString > aNames( pNames, nCount );\n Sequence< Any > aValues( pValues, nCount );\n\n rAboutDialog.insertButton( rControlName, xActionListener, aNames, aValues );\n return rControlName;\n}\n\nvoid AboutDialog::InitDialog()\n{\n \/\/ setting the dialog properties\n OUString pNames[] = {\n TKGet( TK_Closeable ),\n TKGet( TK_Height ),\n TKGet( TK_Moveable ),\n TKGet( TK_PositionX ),\n TKGet( TK_PositionY ),\n TKGet( TK_Title ),\n TKGet( TK_Width ) };\n\n Any pValues[] = {\n Any( sal_True ),\n Any( sal_Int32( ABOUT_DIALOG_HEIGHT ) ),\n Any( sal_True ),\n Any( sal_Int32( 113 ) ),\n Any( sal_Int32( 42 ) ),\n Any( getString( STR_ABOUT_VERSION ) ),\n Any( sal_Int32( ABOUT_DIALOG_WIDTH ) ) };\n\n sal_Int32 nCount = sizeof( pNames ) \/ sizeof( OUString );\n\n Sequence< rtl::OUString > aNames( pNames, nCount );\n Sequence< Any > aValues( pValues, nCount );\n\n rtl::OUString sBitmapPath( getPath( TK_BitmapPath ) );\n rtl::OUString sBitmap( rtl::OUString::createFromAscii( \"\/aboutlogo.png\" ) );\n rtl::OUString sURL( sBitmapPath += sBitmap );\n\n mxDialogModelMultiPropertySet->setPropertyValues( aNames, aValues );\n sal_Int32 nWidth = getMapsFromPixels( 387 );\n if ( nWidth )\n mxDialogModelPropertySet->setPropertyValue( TKGet( TK_Width ), Any( nWidth ) );\n else\n nWidth = ABOUT_DIALOG_WIDTH;\n\n\/\/ int nHeight = (int) getMapsFromPixels( 95 );\n\n InsertImage( *this, rtl::OUString( rtl::OUString::createFromAscii( \"aboutimage\" ) ), sURL, 0, 0, nWidth, 60 );\n InsertFixedText( *this, rtl::OUString( rtl::OUString::createFromAscii( \"fixedtext\" ) ), getString( STR_ABOUT_PRN ), 9, 66, nWidth - 18, 127, sal_True, 0 );\n InsertSeparator( *this, rtl::OUString( rtl::OUString::createFromAscii( \"separator\" ) ), 0, 0, 196, nWidth, 8 );\n InsertButton( *this, rtl::OUString( rtl::OUString::createFromAscii( \"button\" ) ), mxActionListener, ( nWidth \/ 2 ) - 25, 204, 50, 14, 1, STR_OK );\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nAboutDialog::AboutDialog( const Reference< XComponentContext > &rxMSF, Reference< XFrame >& rxFrame ) :\n UnoDialog( rxMSF, rxFrame ),\n ConfigurationAccess( rxMSF, NULL ),\n mxMSF( rxMSF ),\n mxFrame( rxFrame ),\n mxActionListener( new AboutActionListener( *this ) )\n{\n Reference< XFrame > xFrame( mxController->getFrame() );\n Reference< XWindow > xContainerWindow( xFrame->getContainerWindow() );\n Reference< XWindowPeer > xWindowPeer( xContainerWindow, UNO_QUERY_THROW );\n createWindowPeer( xWindowPeer );\n\n InitDialog();\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nAboutDialog::~AboutDialog()\n{\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nsal_Bool AboutDialog::execute()\n{\n UnoDialog::execute();\n return mbStatus;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid AboutActionListener::actionPerformed( const ActionEvent& rEvent )\n throw ( com::sun::star::uno::RuntimeException )\n{\n if ( rEvent.ActionCommand == rtl::OUString( rtl::OUString::createFromAscii( \"button\" ) ) )\n {\n mrAboutDialog.endExecute( sal_True );\n }\n}\nvoid AboutActionListener::disposing( const ::com::sun::star::lang::EventObject& \/* Source *\/ )\n throw ( com::sun::star::uno::RuntimeException )\n{\n}\n<|endoftext|>"} {"text":"\/* ----------------------------------------------------------------\n Copyright 2016 Cisco Systems\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF 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\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"config.hpp\"\n#include \"catch.hpp\"\n\nusing namespace ydk;\nusing namespace ydktest;\nusing namespace std;\n\nvoid print_data_node(shared_ptr dn);\nvoid print_entity(shared_ptr entity, ydk::path::RootSchemaNode& root);\n\n\/\/ cancel_commit -- issues in netsim\n\/\/TEST_CASE(\"cancel_commit\")\n\/\/{\n\/\/ \/\/ session\n\/\/ path::Repository repo{TEST_HOME};\n\/\/ NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n\/\/ NetconfService ns{};\n\/\/\n\/\/ auto reply = ns.cancel_commit(session);\n\/\/ REQUIRE(reply);\n\/\/}\n\n\/\/ close_session\nTEST_CASE(\"close_session\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n auto reply = ns.close_session(provider);\n REQUIRE(reply);\n}\n\n\/\/ commit\nTEST_CASE(\"commit\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n auto reply = ns.commit(provider);\n REQUIRE(reply);\n}\n\n\/\/ copy_config\nTEST_CASE(\"copy_config\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::candidate;\n DataStore source = DataStore::running;\n\n auto reply = ns.copy_config(provider, target, source);\n REQUIRE(reply);\n}\n\n\/\/ delete_config -- issues in netsim\nTEST_CASE(\"delete_config\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::url;\n\n\/\/ auto reply = ns.delete_config(session, target, \"http:\/\/test\");\n CHECK_THROWS_AS(ns.delete_config(provider, target, \"http:\/\/test\"), YError);\n}\n\n\/\/ discard_changes\nTEST_CASE(\"discard_changes\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n auto reply = ns.discard_changes(provider);\n REQUIRE(reply);\n}\n\nTEST_CASE(\"get_edit_copy_config\")\n{\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::candidate;\n DataStore source = DataStore::running;\n\n \/\/ Build filter\n openconfig_interfaces::Interfaces interfaces_filter{};\n openconfig_bgp::Bgp bgp_filter{};\n vector filter_list{};\n filter_list.push_back(&interfaces_filter);\n filter_list.push_back(&bgp_filter);\n\n \/\/ Read running config\n auto get_config_list = ns.get_config(provider, source, filter_list);\n\n vector copy_config_list{};\n for (auto ent : get_config_list) {\n \t\/\/print_entity(ent, provider.get_session().get_root_schema());\n copy_config_list.push_back(ent.get());\n }\n\n \/\/ Copy config to candidate\n auto result = ns.copy_config(provider, target, copy_config_list);\n REQUIRE(result);\n\n \/\/ Discard changes\n result = ns.discard_changes(provider);\n REQUIRE(result);\n}\n\n\/\/ edit_config, get_config\nTEST_CASE(\"edit_config\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::candidate;\n DataStore source = DataStore::candidate;\n openconfig_bgp::Bgp filter = {};\n openconfig_bgp::Bgp bgp = {};\n bgp.global->config->as = 6500;\n\n auto reply = ns.edit_config(provider, target, bgp);\n REQUIRE(reply);\n\n auto data = ns.get_config(provider, source, filter);\n REQUIRE(data);\n\n auto data_ptr = dynamic_cast(data.get());\n REQUIRE(data_ptr != nullptr);\n REQUIRE(data_ptr->global->config->as == bgp.global->config->as);\n\n reply = ns.discard_changes(provider);\n REQUIRE(reply);\n}\n\nTEST_CASE(\"edit_multiple_config\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::candidate;\n DataStore source = DataStore::candidate;\n\n \/\/ Create 'native' configuration\n ydktest::ydktest_sanity::Native native{};\n native.hostname = \"My Host\";\n native.version = \"0.1.2\";\n\n \/\/ Set the Global AS\n openconfig_bgp::Bgp bgp{};\n bgp.global->config->as = 65051;\n bgp.global->config->router_id = \"10.20.30.40\";\n\n \/\/ Create entity list\n vector edit_list{};\n edit_list.push_back(&native);\n edit_list.push_back(&bgp);\n\n auto reply = ns.edit_config(provider, target, edit_list);\n REQUIRE(reply);\n\n \/\/ Build filter\n ydktest::ydktest_sanity::Native native_filter{};\n openconfig_bgp::Bgp bgp_filter{};\n vector filter_list{};\n filter_list.push_back(&native_filter);\n filter_list.push_back(&bgp_filter);\n\n \/\/ Read current configuration and print it\n auto read_list = ns.get_config(provider, source, filter_list);\n REQUIRE(read_list.size() == 2);\n for (auto item : read_list) {\n string path = item->get_segment_path();\n if (path.find(\"bgp\") != string::npos) {\n auto data_ptr = dynamic_cast(item.get());\n REQUIRE(data_ptr != nullptr);\n REQUIRE(data_ptr->global->config->as == bgp.global->config->as);\n REQUIRE(data_ptr->global->config->router_id == bgp.global->config->router_id);\n }\n if (path.find(\"native\") != string::npos) {\n auto data_ptr = dynamic_cast(item.get());\n REQUIRE(data_ptr != nullptr);\n REQUIRE(data_ptr->hostname == native.hostname);\n REQUIRE(data_ptr->version == native.version);\n }\n }\n\n \/\/ Discard config changes\n reply = ns.discard_changes(provider);\n REQUIRE(reply);\n}\n\n\/\/ get\nTEST_CASE(\"get\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n openconfig_bgp::Bgp filter = {};\n\n auto reply = ns.get(provider, filter);\n REQUIRE(reply);\n}\n\n\/\/ kill_session\nTEST_CASE(\"kill_session\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n int session_id = 3;\n\n\/\/ auto reply = ns.kill_session(session, session_id);\n CHECK_THROWS_AS(ns.kill_session(provider, session_id), YError);\n}\n\n\/\/ lock, unlock\nTEST_CASE(\"lock\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::candidate;\n\n auto reply = ns.lock(provider, target);\n REQUIRE(reply);\n\n reply = ns.unlock(provider, target);\n REQUIRE(reply);\n}\n\n\/\/ validate\nTEST_CASE(\"validate\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore source = DataStore::candidate;\n\n auto reply = ns.validate(provider, source);\n REQUIRE(reply);\n}\n\n\/\/ read device configuration (no filter)\nTEST_CASE(\"ietf_get_config_rpc\")\n{\n path::Repository repo{TEST_HOME};\n ydk::path::NetconfSession session{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n ydk::path::RootSchemaNode& schema = session.get_root_schema();\n\n std::shared_ptr read_rpc { schema.create_rpc(\"ietf-netconf:get-config\") };\n read_rpc->get_input_node().create_datanode(\"source\/running\");\n\n auto read_result = (*read_rpc)(session);\n REQUIRE(read_result != nullptr);\n\n \/\/ Print config\n vector> data_nodes = read_result->get_children();\n for (auto dn : data_nodes) {\n print_data_node(dn);\n }\n}\n\n\/\/ read device configuration and state (no filter)\nTEST_CASE(\"ietf_get_rpc\")\n{\n NetconfServiceProvider provider{\"127.0.0.1\", \"admin\", \"admin\", 12022};\n ydk::path::RootSchemaNode& schema = provider.get_session().get_root_schema();\n\n std::shared_ptr read_rpc { schema.create_rpc(\"ietf-netconf:get\") };\n\n REQUIRE_THROWS_AS((*read_rpc)(provider.get_session()), ydk::YModelError);\n}\n\nTEST_CASE(\"get_config_openconfig_interfaces_and_bgp\")\n{\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n ydk::path::RootSchemaNode& schema = provider.get_session().get_root_schema();\n\n std::shared_ptr read_rpc { schema.create_rpc(\"ietf-netconf:get\") };\n\n \/\/ filter\n openconfig_interfaces::Interfaces interfaces_filter{};\n openconfig_bgp::Bgp bgp_filter{};\n\n std::string filter_string = get_xml_subtree_filter_payload(interfaces_filter, provider);\n filter_string += \"\\n\" + get_xml_subtree_filter_payload(bgp_filter, provider);\n\n read_rpc->get_input_node().create_datanode(\"filter\", filter_string);\n\n auto read_result = (*read_rpc)(provider.get_session());\n REQUIRE(read_result != nullptr);\n\n \/\/ Print config\n vector> data_nodes = read_result->get_children();\n for (auto dn : data_nodes) {\n print_data_node(dn);\n }\n}\nFixed Travis c++ test\/* ----------------------------------------------------------------\n Copyright 2016 Cisco Systems\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF 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\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"config.hpp\"\n#include \"catch.hpp\"\n\nusing namespace ydk;\nusing namespace ydktest;\nusing namespace std;\n\nvoid print_data_node(shared_ptr dn);\nvoid print_entity(shared_ptr entity, ydk::path::RootSchemaNode& root);\n\n\/\/ cancel_commit -- issues in netsim\n\/\/TEST_CASE(\"cancel_commit\")\n\/\/{\n\/\/ \/\/ session\n\/\/ path::Repository repo{TEST_HOME};\n\/\/ NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n\/\/ NetconfService ns{};\n\/\/\n\/\/ auto reply = ns.cancel_commit(session);\n\/\/ REQUIRE(reply);\n\/\/}\n\n\/\/ close_session\nTEST_CASE(\"close_session\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n auto reply = ns.close_session(provider);\n REQUIRE(reply);\n}\n\n\/\/ commit\nTEST_CASE(\"commit\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n auto reply = ns.commit(provider);\n REQUIRE(reply);\n}\n\n\/\/ copy_config\nTEST_CASE(\"copy_config\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::candidate;\n DataStore source = DataStore::running;\n\n auto reply = ns.copy_config(provider, target, source);\n REQUIRE(reply);\n}\n\n\/\/ delete_config -- issues in netsim\nTEST_CASE(\"delete_config\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::url;\n\n\/\/ auto reply = ns.delete_config(session, target, \"http:\/\/test\");\n CHECK_THROWS_AS(ns.delete_config(provider, target, \"http:\/\/test\"), YError);\n}\n\n\/\/ discard_changes\nTEST_CASE(\"discard_changes\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n auto reply = ns.discard_changes(provider);\n REQUIRE(reply);\n}\n\nTEST_CASE(\"get_edit_copy_config\")\n{\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::candidate;\n DataStore source = DataStore::running;\n\n \/\/ Build filter\n openconfig_interfaces::Interfaces interfaces_filter{};\n openconfig_bgp::Bgp bgp_filter{};\n vector filter_list{};\n filter_list.push_back(&interfaces_filter);\n filter_list.push_back(&bgp_filter);\n\n \/\/ Read running config\n auto get_config_list = ns.get_config(provider, source, filter_list);\n\n vector copy_config_list{};\n for (auto ent : get_config_list) {\n \t\/\/print_entity(ent, provider.get_session().get_root_schema());\n copy_config_list.push_back(ent.get());\n }\n\n \/\/ Copy config to candidate\n auto result = ns.copy_config(provider, target, copy_config_list);\n REQUIRE(result);\n\n \/\/ Discard changes\n result = ns.discard_changes(provider);\n REQUIRE(result);\n}\n\n\/\/ edit_config, get_config\nTEST_CASE(\"edit_config\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::candidate;\n DataStore source = DataStore::candidate;\n openconfig_bgp::Bgp filter = {};\n openconfig_bgp::Bgp bgp = {};\n bgp.global->config->as = 6500;\n\n auto reply = ns.edit_config(provider, target, bgp);\n REQUIRE(reply);\n\n auto data = ns.get_config(provider, source, filter);\n REQUIRE(data);\n\n auto data_ptr = dynamic_cast(data.get());\n REQUIRE(data_ptr != nullptr);\n REQUIRE(data_ptr->global->config->as == bgp.global->config->as);\n\n reply = ns.discard_changes(provider);\n REQUIRE(reply);\n}\n\nTEST_CASE(\"edit_multiple_config\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::candidate;\n DataStore source = DataStore::candidate;\n\n \/\/ Create 'native' configuration\n ydktest::ydktest_sanity::Native native{};\n native.hostname = \"My Host\";\n native.version = \"0.1.2\";\n\n \/\/ Set the Global AS\n openconfig_bgp::Bgp bgp{};\n bgp.global->config->as = 65051;\n bgp.global->config->router_id = \"10.20.30.40\";\n\n \/\/ Create entity list\n vector edit_list{};\n edit_list.push_back(&native);\n edit_list.push_back(&bgp);\n\n auto reply = ns.edit_config(provider, target, edit_list);\n REQUIRE(reply);\n\n \/\/ Build filter\n ydktest::ydktest_sanity::Native native_filter{};\n openconfig_bgp::Bgp bgp_filter{};\n vector filter_list{};\n filter_list.push_back(&native_filter);\n filter_list.push_back(&bgp_filter);\n\n \/\/ Read current configuration and print it\n auto read_list = ns.get_config(provider, source, filter_list);\n REQUIRE(read_list.size() == 2);\n for (auto item : read_list) {\n string path = item->get_segment_path();\n if (path.find(\"bgp\") != string::npos) {\n auto data_ptr = dynamic_cast(item.get());\n REQUIRE(data_ptr != nullptr);\n REQUIRE(data_ptr->global->config->as == bgp.global->config->as);\n REQUIRE(data_ptr->global->config->router_id == bgp.global->config->router_id);\n }\n if (path.find(\"native\") != string::npos) {\n auto data_ptr = dynamic_cast(item.get());\n REQUIRE(data_ptr != nullptr);\n REQUIRE(data_ptr->hostname == native.hostname);\n REQUIRE(data_ptr->version == native.version);\n }\n }\n\n \/\/ Discard config changes\n reply = ns.discard_changes(provider);\n REQUIRE(reply);\n}\n\n\/\/ get\nTEST_CASE(\"get\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n openconfig_bgp::Bgp filter = {};\n\n auto reply = ns.get(provider, filter);\n REQUIRE(reply);\n}\n\n\/\/ kill_session\nTEST_CASE(\"kill_session\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n int session_id = 3;\n\n\/\/ auto reply = ns.kill_session(session, session_id);\n CHECK_THROWS_AS(ns.kill_session(provider, session_id), YError);\n}\n\n\/\/ lock, unlock\nTEST_CASE(\"lock\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore target = DataStore::candidate;\n\n auto reply = ns.lock(provider, target);\n REQUIRE(reply);\n\n reply = ns.unlock(provider, target);\n REQUIRE(reply);\n}\n\n\/\/ validate\nTEST_CASE(\"validate\")\n{\n \/\/ session\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n NetconfService ns{};\n\n DataStore source = DataStore::candidate;\n\n auto reply = ns.validate(provider, source);\n REQUIRE(reply);\n}\n\n\/\/ read device configuration (no filter)\nTEST_CASE(\"ietf_get_config_rpc\")\n{\n path::Repository repo{TEST_HOME};\n ydk::path::NetconfSession session{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n ydk::path::RootSchemaNode& schema = session.get_root_schema();\n\n std::shared_ptr read_rpc { schema.create_rpc(\"ietf-netconf:get-config\") };\n read_rpc->get_input_node().create_datanode(\"source\/running\");\n\n auto read_result = (*read_rpc)(session);\n REQUIRE(read_result != nullptr);\n\n \/\/ Print config\n vector> data_nodes = read_result->get_children();\n for (auto dn : data_nodes) {\n print_data_node(dn);\n }\n}\n\n\/\/ read device configuration and state (no filter)\nTEST_CASE(\"ietf_get_rpc\")\n{\n NetconfServiceProvider provider{\"127.0.0.1\", \"admin\", \"admin\", 12022};\n ydk::path::RootSchemaNode& schema = provider.get_session().get_root_schema();\n\n std::shared_ptr read_rpc { schema.create_rpc(\"ietf-netconf:get\") };\n try {\n (*read_rpc)(provider.get_session());\n }\n catch (YModelError ex) {\n cout << \"Exception while executing RPC: \" << ex.what() << endl;\n }\n}\n\nTEST_CASE(\"get_config_openconfig_interfaces_and_bgp\")\n{\n path::Repository repo{TEST_HOME};\n NetconfServiceProvider provider{repo, \"127.0.0.1\", \"admin\", \"admin\", 12022};\n ydk::path::RootSchemaNode& schema = provider.get_session().get_root_schema();\n\n std::shared_ptr read_rpc { schema.create_rpc(\"ietf-netconf:get\") };\n\n \/\/ filter\n openconfig_interfaces::Interfaces interfaces_filter{};\n openconfig_bgp::Bgp bgp_filter{};\n\n std::string filter_string = get_xml_subtree_filter_payload(interfaces_filter, provider);\n filter_string += \"\\n\" + get_xml_subtree_filter_payload(bgp_filter, provider);\n\n read_rpc->get_input_node().create_datanode(\"filter\", filter_string);\n\n auto read_result = (*read_rpc)(provider.get_session());\n REQUIRE(read_result != nullptr);\n\n \/\/ Print config\n vector> data_nodes = read_result->get_children();\n for (auto dn : data_nodes) {\n print_data_node(dn);\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visomics\n\n Copyright (c) Kitware, Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n=========================================================================*\/\n\n\/\/ Qt includes\n#include \n#include \n#include \n#include \n\n\/\/ Visomics includes\n#include \"voDataObject.h\"\n#include \"voKMeansClusteringDynView.h\"\n#include \"voUtils.h\"\n\n\/\/ VTK includes\n#include \n#include \n\n\/\/ --------------------------------------------------------------------------\nclass voKMeansClusteringDynViewPrivate\n{\npublic:\n voKMeansClusteringDynViewPrivate();\n};\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voKMeansClusteringDynViewPrivate methods\n\n\/\/ --------------------------------------------------------------------------\nvoKMeansClusteringDynViewPrivate::voKMeansClusteringDynViewPrivate()\n{\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voKMeansClusteringDynView methods\n\n\/\/ --------------------------------------------------------------------------\nvoKMeansClusteringDynView::voKMeansClusteringDynView(QWidget * newParent):\n Superclass(newParent), d_ptr(new voKMeansClusteringDynViewPrivate)\n{\n}\n\n\/\/ --------------------------------------------------------------------------\nvoKMeansClusteringDynView::~voKMeansClusteringDynView()\n{\n}\n\nnamespace\n{\n\n\/\/ --------------------------------------------------------------------------\nQScriptValue scriptValueFromCluster(QScriptEngine* scriptEngine, vtkTable * clusterTable, int clusterId)\n{\n QScriptValue clusterChildren = scriptEngine->newArray();\n quint32 childCount = 0;\n for(vtkIdType cid = 1; cid < clusterTable->GetNumberOfColumns() ; ++cid)\n {\n vtkIntArray * currentColumn = vtkIntArray::SafeDownCast(clusterTable->GetColumn(cid));\n int currentValue = currentColumn->GetValue(0);\n if (currentValue == clusterId)\n {\n QScriptValue clusterChild = scriptEngine->newObject();\n clusterChild.setProperty(\"name\", QScriptValue(currentColumn->GetName()));\n clusterChildren.setProperty(childCount, clusterChild);\n ++childCount;\n }\n }\n return clusterChildren;\n}\n\n\/\/ --------------------------------------------------------------------------\nQScriptValue scriptValueFromClusters(QScriptEngine* scriptEngine, vtkTable * clusterTable, quint32 kmeansCenters)\n{\n QScriptValue array = scriptEngine->newArray();\n QScriptValueList::const_iterator it;\n for (quint32 i = 0; i < kmeansCenters; ++i)\n {\n QScriptValue cluster = scriptEngine->newObject();\n cluster.setProperty(\"name\", QScriptValue(QString(\"Cluster %1\").arg(i + 1)));\n cluster.setProperty(\"children\", scriptValueFromCluster(scriptEngine, clusterTable, i + 1));\n array.setProperty(i, cluster);\n }\n return array;\n}\n\n} \/\/ end of anonymous namespace\n\n\/\/ --------------------------------------------------------------------------\nQString voKMeansClusteringDynView::stringify(const voDataObject& dataObject)\n{\n vtkTable * table = vtkTable::SafeDownCast(dataObject.dataAsVTKDataObject());\n if (!table)\n {\n qCritical() << \"voKMeansClusteringDynView - Failed to setDataObject - vtkTable data is expected !\";\n return QString();\n }\n\n bool ok = false;\n int kmeansCenters = dataObject.property(\"kmeans_centers\").toInt(&ok);\n if (!ok)\n {\n qCritical() << \"voKMeansClusteringDynView - Failed to setDataObject - 'kmeans_center' property is expected !\";\n return QString();\n }\n\n QScriptEngine scriptEngine;\n QScriptValue object = scriptEngine.newObject();\n object.setProperty(\"name\", QScriptValue(\"Clusters\"));\n object.setProperty(\"children\", scriptValueFromClusters(&scriptEngine, table, kmeansCenters));\n\n return voUtils::stringify(&scriptEngine, object);\n}\nCast to vtkAbstractArray rather than vtkIntArray\/*=========================================================================\n\n Program: Visomics\n\n Copyright (c) Kitware, Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n=========================================================================*\/\n\n\/\/ Qt includes\n#include \n#include \n#include \n#include \n\n\/\/ Visomics includes\n#include \"voDataObject.h\"\n#include \"voKMeansClusteringDynView.h\"\n#include \"voUtils.h\"\n\n\/\/ VTK includes\n#include \n#include \n\n\/\/ --------------------------------------------------------------------------\nclass voKMeansClusteringDynViewPrivate\n{\npublic:\n voKMeansClusteringDynViewPrivate();\n};\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voKMeansClusteringDynViewPrivate methods\n\n\/\/ --------------------------------------------------------------------------\nvoKMeansClusteringDynViewPrivate::voKMeansClusteringDynViewPrivate()\n{\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voKMeansClusteringDynView methods\n\n\/\/ --------------------------------------------------------------------------\nvoKMeansClusteringDynView::voKMeansClusteringDynView(QWidget * newParent):\n Superclass(newParent), d_ptr(new voKMeansClusteringDynViewPrivate)\n{\n}\n\n\/\/ --------------------------------------------------------------------------\nvoKMeansClusteringDynView::~voKMeansClusteringDynView()\n{\n}\n\nnamespace\n{\n\n\/\/ --------------------------------------------------------------------------\nQScriptValue scriptValueFromCluster(QScriptEngine* scriptEngine, vtkTable * clusterTable, int clusterId)\n{\n QScriptValue clusterChildren = scriptEngine->newArray();\n quint32 childCount = 0;\n\n for(vtkIdType cid = 1; cid < clusterTable->GetNumberOfColumns() ; ++cid)\n {\n\n vtkAbstractArray * currentColumn = vtkAbstractArray::SafeDownCast(clusterTable->GetColumn(cid));\n int currentValue = currentColumn->GetVariantValue(0).ToInt();\n if (currentValue == clusterId)\n {\n QScriptValue clusterChild = scriptEngine->newObject();\n clusterChild.setProperty(\"name\", QScriptValue(currentColumn->GetName()));\n clusterChildren.setProperty(childCount, clusterChild);\n ++childCount;\n }\n }\n return clusterChildren;\n}\n\n\/\/ --------------------------------------------------------------------------\nQScriptValue scriptValueFromClusters(QScriptEngine* scriptEngine, vtkTable * clusterTable, quint32 kmeansCenters)\n{\n QScriptValue array = scriptEngine->newArray();\n QScriptValueList::const_iterator it;\n for (quint32 i = 0; i < kmeansCenters; ++i)\n {\n QScriptValue cluster = scriptEngine->newObject();\n cluster.setProperty(\"name\", QScriptValue(QString(\"Cluster %1\").arg(i + 1)));\n cluster.setProperty(\"children\", scriptValueFromCluster(scriptEngine, clusterTable, i + 1));\n array.setProperty(i, cluster);\n }\n return array;\n}\n\n} \/\/ end of anonymous namespace\n\n\/\/ --------------------------------------------------------------------------\nQString voKMeansClusteringDynView::stringify(const voDataObject& dataObject)\n{\n vtkTable * table = vtkTable::SafeDownCast(dataObject.dataAsVTKDataObject());\n if (!table)\n {\n qCritical() << \"voKMeansClusteringDynView - Failed to setDataObject - vtkTable data is expected !\";\n return QString();\n }\n\n bool ok = false;\n int kmeansCenters = dataObject.property(\"kmeans_centers\").toInt(&ok);\n if (!ok)\n {\n qCritical() << \"voKMeansClusteringDynView - Failed to setDataObject - 'kmeans_center' property is expected !\";\n return QString();\n }\n\n QScriptEngine scriptEngine;\n QScriptValue object = scriptEngine.newObject();\n object.setProperty(\"name\", QScriptValue(\"Clusters\"));\n object.setProperty(\"children\", scriptValueFromClusters(&scriptEngine, table, kmeansCenters));\n\n return voUtils::stringify(&scriptEngine, object);\n}\n<|endoftext|>"} {"text":"#include \"chs.hpp\"\n\nCHS::CHS()\n{\ncylinder=0,head=0,sector=0,\nspt=63,tpc=255;\n}\n\nCHS::CHS(int c,int h,int s)\n{\ncylinder=c,head=h,sector=s,\n\nspt=63,tpc=255;\n}\n\nCHS::CHS(long long lba)\n{\nspt=63,tpc=255;\ncalc(lba);\n\n}\n\n\nvoid CHS::calc(long long lba)\n{\nlong long temp;\n\ncylinder =lba \/ (tpc * spt);\ntemp = lba % (tpc * spt);\nhead = temp \/ spt;\nsector = temp % spt + 1;\n\n}\n\n\nbool CHS::SetCylinder(long long cylinder)\n{\n this->cylinder=cylinder;\n return true;\n}\n\nbool CHS::SetHead(unsigned int head)\n{\n if(head>tpc) return false;\n this->head=head;\n return true;\n}\n\nbool CHS::SetSector(unsigned int sector)\n{\n if(head>spt) return false;\n this->sector=sector;\n return true;\n}\n\n\nunsigned long CHS::GetCylinder()\n{\n return this->cylinder;\n}\nunsigned int CHS::GetHead()\n{\n return this->head;\n}\nunsigned int CHS::GetSector()\n{\n return this->sector;\n}\n\n\nbool CHS::SetGeometry(int spt,int tpc)\n{\n this->spt=spt;\n this->tpc=tpc;\nreturn true;\n}\n\nint CHS::GetSPT() { return spt; }\nint CHS::GetTPC() { return tpc; }\n\nvoid CHS::SetSPT(int spt)\n{\nlong long old_lba=ToLBA();\nthis->spt=spt;\ncalc(old_lba);\n}\nvoid CHS::SetTPC(int tpc)\n{\nlong long old_lba=ToLBA();\nthis->tpc=tpc;\n calc(old_lba);\n\n}\n\n\nlong long CHS::ToLBA()\n{\n return ( ( cylinder * tpc + head ) * spt ) + sector - 1;\n}\n\n\n\n\n\n\nCHS &CHS::operator =(long long lba)\n{\nunsigned long temp;\n\ncylinder =lba \/ (tpc * spt);\ntemp = lba % (tpc * spt);\nhead = temp \/ spt;\nsector = temp % spt + 1;\n\nreturn *this;\n}\n\nbool CHS::operator ==(CHS &chs)\n{\nif(this->ToLBA()==chs.ToLBA())\n return true;\n\nreturn false;\n}\n\n\n\nCHS &CHS::operator ++()\n{\nunsigned long temp;\nlong long lba=this->ToLBA()+1;\n\ncylinder =lba \/ (tpc * spt);\ntemp = lba % (tpc * spt);\nhead = temp \/ spt;\nsector = temp % spt + 1;\n\nreturn *this;\n}\n\nCHS &CHS::operator ++(int)\n{\nCHS ret=*this;\n\nunsigned long temp;\nlong long lba=this->ToLBA()+1;\n\ncylinder =lba \/ (tpc * spt);\ntemp = lba % (tpc * spt);\nhead = temp \/ spt;\nsector = temp % spt + 1;\n\nreturn ret;\n}\n\nAdded MBR_CHS CHS::ToMbrChs() function#include \"chs.hpp\"\n#include \"definitions.h\"\n\nCHS::CHS()\n{\ncylinder=0,head=0,sector=0,\nspt=63,tpc=255;\n}\n\nCHS::CHS(int c,int h,int s)\n{\ncylinder=c,head=h,sector=s,\n\nspt=63,tpc=255;\n}\n\nCHS::CHS(long long lba)\n{\nspt=63,tpc=255;\ncalc(lba);\n\n}\n\n\nvoid CHS::calc(long long lba)\n{\nlong long temp;\n\ncylinder =lba \/ (tpc * spt);\ntemp = lba % (tpc * spt);\nhead = temp \/ spt;\nsector = temp % spt + 1;\n\n}\n\n\nbool CHS::SetCylinder(long long cylinder)\n{\n this->cylinder=cylinder;\n return true;\n}\n\nbool CHS::SetHead(unsigned int head)\n{\n if(head>tpc) return false;\n this->head=head;\n return true;\n}\n\nbool CHS::SetSector(unsigned int sector)\n{\n if(head>spt) return false;\n this->sector=sector;\n return true;\n}\n\n\nunsigned long CHS::GetCylinder()\n{\n return this->cylinder;\n}\nunsigned int CHS::GetHead()\n{\n return this->head;\n}\nunsigned int CHS::GetSector()\n{\n return this->sector;\n}\n\n\nbool CHS::SetGeometry(int spt,int tpc)\n{\n this->spt=spt;\n this->tpc=tpc;\nreturn true;\n}\n\nint CHS::GetSPT() { return spt; }\nint CHS::GetTPC() { return tpc; }\n\nvoid CHS::SetSPT(int spt)\n{\nlong long old_lba=ToLBA();\nthis->spt=spt;\ncalc(old_lba);\n}\nvoid CHS::SetTPC(int tpc)\n{\nlong long old_lba=ToLBA();\nthis->tpc=tpc;\n calc(old_lba);\n\n}\n\n\nlong long CHS::ToLBA()\n{\n return ( ( cylinder * tpc + head ) * spt ) + sector - 1;\n}\n\n\nMBR_CHS CHS::ToMbrChs()\n{\n MBR_CHS chs= {0};\n\n if(ToLBA()>=CHS_LIMIT)\n {\n chs.cylinder_bits=1023>>8;\n chs.cylinder=1023&0xFF;\n\n chs.head=254;\n chs.sector=63;\n return chs;\n }\n\n unsigned cylinder,head,sector,temp=0;\n\n cylinder =ToLBA()\/ (tpc * spt);\n temp = ToLBA() % (tpc * spt);\n head = temp \/ spt;\n sector = temp % spt + 1;\n\n chs.cylinder_bits=cylinder>>8;\n chs.cylinder=cylinder&0xFF;\n\n chs.head=head;\n chs.sector=sector;\n\n return chs;\n}\n\n\n\nCHS &CHS::operator =(long long lba)\n{\nunsigned long temp;\n\ncylinder =lba \/ (tpc * spt);\ntemp = lba % (tpc * spt);\nhead = temp \/ spt;\nsector = temp % spt + 1;\n\nreturn *this;\n}\n\nbool CHS::operator ==(CHS &chs)\n{\nif(this->ToLBA()==chs.ToLBA())\n return true;\n\nreturn false;\n}\n\n\n\nCHS &CHS::operator ++()\n{\nunsigned long temp;\nlong long lba=this->ToLBA()+1;\n\ncylinder =lba \/ (tpc * spt);\ntemp = lba % (tpc * spt);\nhead = temp \/ spt;\nsector = temp % spt + 1;\n\nreturn *this;\n}\n\nCHS &CHS::operator ++(int)\n{\nCHS ret=*this;\n\nunsigned long temp;\nlong long lba=this->ToLBA()+1;\n\ncylinder =lba \/ (tpc * spt);\ntemp = lba % (tpc * spt);\nhead = temp \/ spt;\nsector = temp % spt + 1;\n\nreturn ret;\n}\n\n<|endoftext|>"} {"text":"\/*\n* This file is part of PyMesh.\n*\n* PyMesh is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* PyMesh is distributed in the hope that it 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 Foobar. If not, see .\n*\n*\/\n\n\n#ifndef PYMESHPLUGIN_HH\n#define PYMESHPLUGIN_HH\n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n\n#include \"PyMeshToolbox.hh\"\n\n\nclass PyMeshPlugin : public QObject, BaseInterface, ToolboxInterface, LoadSaveInterface, LoggingInterface, BackupInterface, ProcessInterface, ScriptInterface, RPCInterface\n{\n Q_OBJECT\n Q_INTERFACES(BaseInterface)\n Q_INTERFACES(ToolboxInterface)\n Q_INTERFACES(LoadSaveInterface)\n Q_INTERFACES(LoggingInterface)\n Q_INTERFACES(BackupInterface)\n Q_INTERFACES(ProcessInterface)\n Q_INTERFACES(ScriptInterface)\n Q_INTERFACES(RPCInterface)\n Q_PLUGIN_METADATA(IID \"org.OpenFlipper.Plugins.Plugin-PyMesh\")\n\nQ_SIGNALS:\n\n \/\/ Base Interface\n void updatedObject(int _identifier, const UpdateType& _type);\n\n \/\/ Toolbox Interface\n void addToolbox(QString _name, QWidget* _widget , QIcon* _icon);\n\n \/\/ Load-Save Interface\n void addEmptyObject(DataType _type, int& _id);\n void deleteObject(int _id);\n\n \/\/ Logging Interface\n void log(Logtype _type, QString _message);\n void log(QString _message);\n\n \/\/ Process Interface\n void setJobDescription(QString _jobId, QString _text);\n void startJob(QString _jobId, QString _description, int _min, int _max, bool _blocking = false);\n void finishJob(QString _jobId);\n\n \/\/ Script Interface\n void getAvailableFunctions(QStringList& _functions);\n void getDescription(QString _function, QString& _description, QStringList& _parameters, QStringList& _descriptions);\n\n \/\/ Backup Interface\n void createBackup(int _objectid, QString _name, UpdateType _type = UPDATE_ALL);\n\npublic Q_SLOTS:\n\n bool runPyScriptFile(const QString& _filename, bool _clearPrevious);\n void runPyScriptFileAsync(const QString& _filename, bool _clearPrevious);\n\n bool runPyScript(const QString& _script, bool _clearPrevious);\n void runPyScriptAsync(const QString& _script, bool _clearPrevious);\n\n void convertPropsPyToCpp(const IdList& _list);\n\n void resetInterpreter();\n\npublic:\n\n \/\/ Python callback functions\n void pyOutput(const char* w);\n void pyError(const char* w); \n void* createTriMesh();\n void* createPolyMesh();\n\n\n PyMeshPlugin();\n ~PyMeshPlugin();\n\n QString name(){return QString(\"PyMesh\");}\n QString description(){return QString(\"Run OpenMesh Python Scripts and shows the resulting mesh.\");}\n\nprivate:\n\n pybind11::module main_module_;\n PyObject* global_dict_clean_ = nullptr; \/\/clean global dict. used for reset. do not change\n\n PyMeshToolbox* toolbox_ = nullptr;\n std::vector createdObjects_;\n\n QWidget* scriptingFunctionsPresenter_ = nullptr;\n\n void initPython();\n \/\/\/ Run Python Script. Does not update any object. save to call from another thread\n bool runPyScript_internal(const QString& _script, bool _clearPrevious);\n \/\/\/ Does not update all objects, save to call from another thread\n void convertPropsPyToCpp_internal(const IdList& _list);\n\nprivate Q_SLOTS:\n\n void initializePlugin();\n\n void pluginsInitialized();\n\n void slotRunScript();\n\n void slotSelectFile();\n\n void canceledJob(QString _job);\n\n void runPyScriptFinished();\n\n void noguiSupported() {};\n\n void showScriptingFunctions();\n\npublic Q_SLOTS:\n QString version(){ return QString(\"1.0\"); }\n};\n\n\n#endif \/\/PYMESHPLUGIN_HH\nincreased version number\/*\n* This file is part of PyMesh.\n*\n* PyMesh is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* PyMesh is distributed in the hope that it 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 Foobar. If not, see .\n*\n*\/\n\n\n#ifndef PYMESHPLUGIN_HH\n#define PYMESHPLUGIN_HH\n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n\n#include \"PyMeshToolbox.hh\"\n\n\nclass PyMeshPlugin : public QObject, BaseInterface, ToolboxInterface, LoadSaveInterface, LoggingInterface, BackupInterface, ProcessInterface, ScriptInterface, RPCInterface\n{\n Q_OBJECT\n Q_INTERFACES(BaseInterface)\n Q_INTERFACES(ToolboxInterface)\n Q_INTERFACES(LoadSaveInterface)\n Q_INTERFACES(LoggingInterface)\n Q_INTERFACES(BackupInterface)\n Q_INTERFACES(ProcessInterface)\n Q_INTERFACES(ScriptInterface)\n Q_INTERFACES(RPCInterface)\n Q_PLUGIN_METADATA(IID \"org.OpenFlipper.Plugins.Plugin-PyMesh\")\n\nQ_SIGNALS:\n\n \/\/ Base Interface\n void updatedObject(int _identifier, const UpdateType& _type);\n\n \/\/ Toolbox Interface\n void addToolbox(QString _name, QWidget* _widget , QIcon* _icon);\n\n \/\/ Load-Save Interface\n void addEmptyObject(DataType _type, int& _id);\n void deleteObject(int _id);\n\n \/\/ Logging Interface\n void log(Logtype _type, QString _message);\n void log(QString _message);\n\n \/\/ Process Interface\n void setJobDescription(QString _jobId, QString _text);\n void startJob(QString _jobId, QString _description, int _min, int _max, bool _blocking = false);\n void finishJob(QString _jobId);\n\n \/\/ Script Interface\n void getAvailableFunctions(QStringList& _functions);\n void getDescription(QString _function, QString& _description, QStringList& _parameters, QStringList& _descriptions);\n\n \/\/ Backup Interface\n void createBackup(int _objectid, QString _name, UpdateType _type = UPDATE_ALL);\n\npublic Q_SLOTS:\n\n bool runPyScriptFile(const QString& _filename, bool _clearPrevious);\n void runPyScriptFileAsync(const QString& _filename, bool _clearPrevious);\n\n bool runPyScript(const QString& _script, bool _clearPrevious);\n void runPyScriptAsync(const QString& _script, bool _clearPrevious);\n\n void convertPropsPyToCpp(const IdList& _list);\n\n void resetInterpreter();\n\npublic:\n\n \/\/ Python callback functions\n void pyOutput(const char* w);\n void pyError(const char* w); \n void* createTriMesh();\n void* createPolyMesh();\n\n\n PyMeshPlugin();\n ~PyMeshPlugin();\n\n QString name(){return QString(\"PyMesh\");}\n QString description(){return QString(\"Run OpenMesh Python Scripts and shows the resulting mesh.\");}\n\nprivate:\n\n pybind11::module main_module_;\n PyObject* global_dict_clean_ = nullptr; \/\/clean global dict. used for reset. do not change\n\n PyMeshToolbox* toolbox_ = nullptr;\n std::vector createdObjects_;\n\n QWidget* scriptingFunctionsPresenter_ = nullptr;\n\n void initPython();\n \/\/\/ Run Python Script. Does not update any object. save to call from another thread\n bool runPyScript_internal(const QString& _script, bool _clearPrevious);\n \/\/\/ Does not update all objects, save to call from another thread\n void convertPropsPyToCpp_internal(const IdList& _list);\n\nprivate Q_SLOTS:\n\n void initializePlugin();\n\n void pluginsInitialized();\n\n void slotRunScript();\n\n void slotSelectFile();\n\n void canceledJob(QString _job);\n\n void runPyScriptFinished();\n\n void noguiSupported() {};\n\n void showScriptingFunctions();\n\npublic Q_SLOTS:\n QString version(){ return QString(\"2.0\"); }\n};\n\n\n#endif \/\/PYMESHPLUGIN_HH\n<|endoftext|>"} {"text":"#include \"Scene.h\"\n\nScene::Scene(void)\n{\n\tview_matrix = glm::lookAt(glm::vec3(0.f, 0.f, 0.f), glm::vec3(0.f, 0.f, -1.f), glm::vec3(0.f, 1.f, 0.f));\n\tmemset(&KeyStates, 0, sizeof(KeyStates));\n\tbbo = new BulletBufferObject(this, 50);\n\tthis->debug = false;\n\tthis->game = true;\n\tthis->score = 0;\n}\n\nScene::~Scene(void)\n{\n\tif (player != 0) delete player;\n\tfor (unsigned int i = 0; i < objects.size(); i++){\n\t\tif (objects[i] != 0) delete objects[i];\n\t}\n\n}\nvoid Scene::Init(GLuint *texture){\n\tthis->texture = texture;\n\n\t\/\/ Init Player\n\tthis->player = new Player(this, this->texture[0], 0.0f, 0.0f);\n\n\t\/\/ Init Objects\t\n\tAddObstacle(new Obstacle(this, this->texture[2], 15.0, 15.0, 7.00));\n\tAddObstacle(new Obstacle(this, this->texture[2], -12.0, -17.0, 9.00));\n\tAddObstacle(new Obstacle(this, this->texture[2], 12.0, -6.0, 5.00));\n\tAddObstacle(new Obstacle(this, this->texture[2], -16.0, 15.0, 6.00));\n\n\t\/\/ Init Zombies\n\tfor (unsigned int i = 0; i < ZOMBIE_AMOUNT; ++i) AddZombie(new Zombie(this, this->texture[1]));\n\n\t\/\/Init PowerUps\n\tfor (unsigned int i = 0; i < POWERUP_AMOUNT; ++i) AddPowerUp(new PowerUp(this));\n\n\tPrintPlayerData();\n\n}\n\nvoid Scene::PrintResult()\n{\n\tsystem(\"cls\");\n\tcout << \"---------- RESULT ----------\" << endl;\n\tcout << \"Score: \" << player->score << endl << endl;\n\tcout << \"Type [R] to restart game\" << endl << endl;\n}\n\nvoid Scene::PrintPlayerData()\n{\n\n}\nstring Scene::GetPlayerData()\n{\n\treturn player->GetPlayerData();\n}\n\nvoid Scene::Update(double delta_time)\n{\n\tDisplayData();\n\tif (this->game){\n\t\tCheckVictoryCondition();\n\t\tbbo->Update(delta_time);\n\t\tfor (unsigned int i = 0; i < objects.size(); i++)\n\t\t{\n\t\t\tobjects[i]->Update(delta_time);\n\t\t}\n\n\t\tif (KeyStates['w'] || KeyStates['W']) player->Move(glm::vec2(0, 0.3), delta_time);\n\t\tif (KeyStates['s'] || KeyStates['S']) player->Move(glm::vec2(0, -0.3), delta_time);\n\t\tif (KeyStates['a'] || KeyStates['A']) player->Move(glm::vec2(-0.3, 0), delta_time);\n\t\tif (KeyStates['d'] || KeyStates['D']) player->Move(glm::vec2(0.3, 0), delta_time);\n\n\t\tplayer->Update(delta_time);\n\t}\n\tif ((KeyStates['r'] || KeyStates['R']) && !game) Restart();\n\tif (KeyStates[27]) exit(0); \/\/ESC key quits the game\n}\n\nbool Scene::CheckVictoryCondition(void)\n{\n\tif(player->immortality_duration > 0)\n\t\treturn game;\n\n\tfor (unsigned int i = 0; iGetObjectPosition(), zombies[i]->GetObjectPosition()) < 2)\n\t\t{\n\t\t\tif(player->lifes > 0)\n\t\t\t{\n\t\t\t\tplayer->Respawn();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthis->game = false;\n\t\t\t\tPrintResult();\n\t\t\t}\n\t\t}\n\t}\n\n\treturn game;\n}\n\nvoid Scene::Restart(void){\n\tthis->game = true;\n\tthis->debug = true;\n\tfor (unsigned int i = 0; i < zombies.size(); i++)\n\t{\n\t\tzombies[i]->RandomPosition();\t\n\t\tzombies[i]->aggressive = false;\n\t}\n\tthis->debug = false;\n\tplayer->Reset();\n\tfor(unsigned int i = 0; i < powerups.size(); i++)\n\t{\n\t\tpowerups[i]->Respawn();\n\t}\n\tPrintPlayerData();\n}\n\nstring NumberWithSpaces(int n, int m)\n{\n\tstringstream ss;\n\tss << n;\n\n\tstring s = ss.str();\n\n\twhile(s.size() < m)\n\t\ts = \" \" + s;\n\n\treturn s;\n}\n\nvoid Scene::Draw(void)\n{\n\tplayer->Draw();\n\tbbo->Draw();\n\tfor(unsigned int i = 0; i < objects.size(); i++)\n\t{\n\t\tobjects[i]->Draw();\n\t}\n\t\n\tstring rail_info = (player->current_weapon == Player::WEAPON_TYPE::RAIL ? \"-> \" : \" \");\n\trail_info += \"Railgun [\" + NumberWithSpaces(player->rail_lvl, 1) + \"] [\" + NumberWithSpaces(player->rail_ammo, 4) + \"]\";\n\n\tif(player->current_weapon == Player::WEAPON_TYPE::RAIL)\n\t\tglColor3f(1.0f, 1.0f, 1.0f);\n\telse\n\t\tglColor3f(0.2f, 0.2f, 1.0f);\n\tglRasterPos2f(0.35f, -0.94f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)rail_info.c_str());\n\n\tstring machine_info = (player->current_weapon == Player::WEAPON_TYPE::MACHINE ? \"-> \" : \" \");\n\tmachine_info += \"Machine gun [\" + NumberWithSpaces(player->machine_lvl, 1) + \"] [\" + NumberWithSpaces(player->machine_ammo, 4) + \"]\";\n\n\tif(player->current_weapon == Player::WEAPON_TYPE::MACHINE)\n\t\tglColor3f(1.0f, 1.0f, 1.0f);\n\telse\n\t\tglColor3f(0.2f, 0.2f, 1.0f);\n\tglRasterPos2f(0.35f, -0.98f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)machine_info.c_str());\n\n\tstring lifes_info = \"Lifes: \" + NumberWithSpaces(player->lifes, 3);\n\tglColor3f(1.0f, 0.1f, 0.1f);\n\tglRasterPos2f(-0.99f, -0.90f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)lifes_info.c_str());\n\n\tstring score_info = \"Score: \" + NumberWithSpaces(player->score, 3);\n\tglColor3f(0.3f, 0.8f, 0.8f);\n\tglRasterPos2f(-0.99f, -0.94f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)score_info.c_str());\n\n\tstring cash_info = \"Cash: \" + NumberWithSpaces(player->cash, 3);\n\tglColor3f(0.2f, 1.0f, 0.2f);\n\tglRasterPos2f(-0.99f, -0.98f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)cash_info.c_str());\n\n\tstring info = \"Press [q] to switch weapon\";\n\tglColor3f(0.5f, 0.5f, 0.5f);\n\tglRasterPos2f(0.30f, 0.96f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)info.c_str());\n\n\tinfo = \"Press [e] to upgrade weapon\";\n\tglColor3f(0.5f, 0.5f, 0.5f);\n\tglRasterPos2f(0.30f, 0.92f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)info.c_str());\n}\n\nvoid Scene::PlayerRotate(glm::vec2 heading)\n{\n\tplayer->Rotate(heading);\n\t\n}\n\nvoid Scene::PlayerShoot(glm::vec2 aim)\n{\n\tplayer->Shoot(aim);\n}\n\nvoid Scene::KeyState(unsigned char key, bool tf)\n{\n\tKeyStates[key] = tf;\n\n\tif(key == 'q' && tf)\n\t{\n\t\tif(player->current_weapon == Player::WEAPON_TYPE::RAIL)\n\t\t\tplayer->current_weapon = Player::WEAPON_TYPE::MACHINE;\n\t\telse\n\t\t\tplayer->current_weapon = Player::WEAPON_TYPE::RAIL;\n\n\t\tPrintPlayerData();\n\t}\n\telse if(key == 'e' && tf)\n\t{\n\t\tif(player->current_weapon == Player::WEAPON_TYPE::MACHINE)\n\t\t\tplayer->UpgradeWeapon(Player::WEAPON_TYPE::MACHINE);\n\t\telse\n\t\t\tplayer->UpgradeWeapon(Player::WEAPON_TYPE::RAIL);\n\t}\n}\n\nvoid Scene::AddObject(GameEntity *entity)\n{\n\tobjects.push_back(entity);\n}\nvoid Scene::AddZombie(Zombie *entity)\n{\n\tzombies.push_back(entity);\n\tobjects.push_back(entity);\n}\nvoid Scene::AddObstacle(Obstacle *entity)\n{\n\tobstacles.push_back(entity);\n\tobjects.push_back(entity);\n}\n\nvoid Scene::AddPowerUp(PowerUp *entity)\n{\n\tpowerups.push_back(entity);\n\tobjects.push_back(entity);\n}\n\nostream& operator<<(ostream &o, const Scene &gw)\n{\n\to << \"---------------- SCENE ---------------\" << \"\\n\";\n\n\to << \"--------------------------------------\" << endl;\n\treturn o;\n}\n\nvoid Scene::DisplayData()\n{\n\tstring str;\n\tstringstream ss;\n\n\tss << \"Lifes: \" << player->lifes << endl;\n\tstr = \"\";\n\tss >> str;\n\n\t\/\/glRasterPos2i(0, 0);\n\t\/\/glColor3f(1, 0, 0);\n\t\/\/glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24, (const unsigned char*)\"Dzialaj\");\n\n\n\n\n}\nInstruction for Quitting the game#include \"Scene.h\"\n\nScene::Scene(void)\n{\n\tview_matrix = glm::lookAt(glm::vec3(0.f, 0.f, 0.f), glm::vec3(0.f, 0.f, -1.f), glm::vec3(0.f, 1.f, 0.f));\n\tmemset(&KeyStates, 0, sizeof(KeyStates));\n\tbbo = new BulletBufferObject(this, 50);\n\tthis->debug = false;\n\tthis->game = true;\n\tthis->score = 0;\n}\n\nScene::~Scene(void)\n{\n\tif (player != 0) delete player;\n\tfor (unsigned int i = 0; i < objects.size(); i++){\n\t\tif (objects[i] != 0) delete objects[i];\n\t}\n\n}\nvoid Scene::Init(GLuint *texture){\n\tthis->texture = texture;\n\n\t\/\/ Init Player\n\tthis->player = new Player(this, this->texture[0], 0.0f, 0.0f);\n\n\t\/\/ Init Objects\t\n\tAddObstacle(new Obstacle(this, this->texture[2], 15.0, 15.0, 7.00));\n\tAddObstacle(new Obstacle(this, this->texture[2], -12.0, -17.0, 9.00));\n\tAddObstacle(new Obstacle(this, this->texture[2], 12.0, -6.0, 5.00));\n\tAddObstacle(new Obstacle(this, this->texture[2], -16.0, 15.0, 6.00));\n\n\t\/\/ Init Zombies\n\tfor (unsigned int i = 0; i < ZOMBIE_AMOUNT; ++i) AddZombie(new Zombie(this, this->texture[1]));\n\n\t\/\/Init PowerUps\n\tfor (unsigned int i = 0; i < POWERUP_AMOUNT; ++i) AddPowerUp(new PowerUp(this));\n\n\tPrintPlayerData();\n\n}\n\nvoid Scene::PrintResult()\n{\n\tsystem(\"cls\");\n\tcout << \"---------- RESULT ----------\" << endl;\n\tcout << \"Score: \" << player->score << endl << endl;\n\tcout << \"Type [R] to restart game\" << endl << endl;\n}\n\nvoid Scene::PrintPlayerData()\n{\n\n}\nstring Scene::GetPlayerData()\n{\n\treturn player->GetPlayerData();\n}\n\nvoid Scene::Update(double delta_time)\n{\n\tDisplayData();\n\tif (this->game){\n\t\tCheckVictoryCondition();\n\t\tbbo->Update(delta_time);\n\t\tfor (unsigned int i = 0; i < objects.size(); i++)\n\t\t{\n\t\t\tobjects[i]->Update(delta_time);\n\t\t}\n\n\t\tif (KeyStates['w'] || KeyStates['W']) player->Move(glm::vec2(0, 0.3), delta_time);\n\t\tif (KeyStates['s'] || KeyStates['S']) player->Move(glm::vec2(0, -0.3), delta_time);\n\t\tif (KeyStates['a'] || KeyStates['A']) player->Move(glm::vec2(-0.3, 0), delta_time);\n\t\tif (KeyStates['d'] || KeyStates['D']) player->Move(glm::vec2(0.3, 0), delta_time);\n\n\t\tplayer->Update(delta_time);\n\t}\n\tif ((KeyStates['r'] || KeyStates['R']) && !game) Restart();\n\tif (KeyStates[27]) exit(0); \/\/ESC key quits the game\n}\n\nbool Scene::CheckVictoryCondition(void)\n{\n\tif(player->immortality_duration > 0)\n\t\treturn game;\n\n\tfor (unsigned int i = 0; iGetObjectPosition(), zombies[i]->GetObjectPosition()) < 2)\n\t\t{\n\t\t\tif(player->lifes > 0)\n\t\t\t{\n\t\t\t\tplayer->Respawn();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthis->game = false;\n\t\t\t\tPrintResult();\n\t\t\t}\n\t\t}\n\t}\n\n\treturn game;\n}\n\nvoid Scene::Restart(void){\n\tthis->game = true;\n\tthis->debug = true;\n\tfor (unsigned int i = 0; i < zombies.size(); i++)\n\t{\n\t\tzombies[i]->RandomPosition();\t\n\t\tzombies[i]->aggressive = false;\n\t}\n\tthis->debug = false;\n\tplayer->Reset();\n\tfor(unsigned int i = 0; i < powerups.size(); i++)\n\t{\n\t\tpowerups[i]->Respawn();\n\t}\n\tPrintPlayerData();\n}\n\nstring NumberWithSpaces(int n, int m)\n{\n\tstringstream ss;\n\tss << n;\n\n\tstring s = ss.str();\n\n\twhile(s.size() < m)\n\t\ts = \" \" + s;\n\n\treturn s;\n}\n\nvoid Scene::Draw(void)\n{\n\tplayer->Draw();\n\tbbo->Draw();\n\tfor(unsigned int i = 0; i < objects.size(); i++)\n\t{\n\t\tobjects[i]->Draw();\n\t}\n\t\n\tstring rail_info = (player->current_weapon == Player::WEAPON_TYPE::RAIL ? \"-> \" : \" \");\n\trail_info += \"Railgun [\" + NumberWithSpaces(player->rail_lvl, 1) + \"] [\" + NumberWithSpaces(player->rail_ammo, 4) + \"]\";\n\n\tif(player->current_weapon == Player::WEAPON_TYPE::RAIL)\n\t\tglColor3f(1.0f, 1.0f, 1.0f);\n\telse\n\t\tglColor3f(0.2f, 0.2f, 1.0f);\n\tglRasterPos2f(0.35f, -0.94f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)rail_info.c_str());\n\n\tstring machine_info = (player->current_weapon == Player::WEAPON_TYPE::MACHINE ? \"-> \" : \" \");\n\tmachine_info += \"Machine gun [\" + NumberWithSpaces(player->machine_lvl, 1) + \"] [\" + NumberWithSpaces(player->machine_ammo, 4) + \"]\";\n\n\tif(player->current_weapon == Player::WEAPON_TYPE::MACHINE)\n\t\tglColor3f(1.0f, 1.0f, 1.0f);\n\telse\n\t\tglColor3f(0.2f, 0.2f, 1.0f);\n\tglRasterPos2f(0.35f, -0.98f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)machine_info.c_str());\n\n\tstring lifes_info = \"Lifes: \" + NumberWithSpaces(player->lifes, 3);\n\tglColor3f(1.0f, 0.1f, 0.1f);\n\tglRasterPos2f(-0.99f, -0.90f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)lifes_info.c_str());\n\n\tstring score_info = \"Score: \" + NumberWithSpaces(player->score, 3);\n\tglColor3f(0.3f, 0.8f, 0.8f);\n\tglRasterPos2f(-0.99f, -0.94f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)score_info.c_str());\n\n\tstring cash_info = \"Cash: \" + NumberWithSpaces(player->cash, 3);\n\tglColor3f(0.2f, 1.0f, 0.2f);\n\tglRasterPos2f(-0.99f, -0.98f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)cash_info.c_str());\n\n\tstring info = \"Press [ESC] to quit\";\n\tglColor3f(0.5f, 0.5f, 0.5f);\n\tglRasterPos2f(-0.95f, 0.96f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)info.c_str());\n\n\tinfo = \"Press [q] to switch weapon\";\n\tglColor3f(0.5f, 0.5f, 0.5f);\n\tglRasterPos2f(0.30f, 0.96f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)info.c_str());\n\n\tinfo = \"Press [e] to upgrade weapon\";\n\tglColor3f(0.5f, 0.5f, 0.5f);\n\tglRasterPos2f(0.30f, 0.92f);\n\tglutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)info.c_str());\n}\n\nvoid Scene::PlayerRotate(glm::vec2 heading)\n{\n\tplayer->Rotate(heading);\n\t\n}\n\nvoid Scene::PlayerShoot(glm::vec2 aim)\n{\n\tplayer->Shoot(aim);\n}\n\nvoid Scene::KeyState(unsigned char key, bool tf)\n{\n\tKeyStates[key] = tf;\n\n\tif(key == 'q' && tf)\n\t{\n\t\tif(player->current_weapon == Player::WEAPON_TYPE::RAIL)\n\t\t\tplayer->current_weapon = Player::WEAPON_TYPE::MACHINE;\n\t\telse\n\t\t\tplayer->current_weapon = Player::WEAPON_TYPE::RAIL;\n\n\t\tPrintPlayerData();\n\t}\n\telse if(key == 'e' && tf)\n\t{\n\t\tif(player->current_weapon == Player::WEAPON_TYPE::MACHINE)\n\t\t\tplayer->UpgradeWeapon(Player::WEAPON_TYPE::MACHINE);\n\t\telse\n\t\t\tplayer->UpgradeWeapon(Player::WEAPON_TYPE::RAIL);\n\t}\n}\n\nvoid Scene::AddObject(GameEntity *entity)\n{\n\tobjects.push_back(entity);\n}\nvoid Scene::AddZombie(Zombie *entity)\n{\n\tzombies.push_back(entity);\n\tobjects.push_back(entity);\n}\nvoid Scene::AddObstacle(Obstacle *entity)\n{\n\tobstacles.push_back(entity);\n\tobjects.push_back(entity);\n}\n\nvoid Scene::AddPowerUp(PowerUp *entity)\n{\n\tpowerups.push_back(entity);\n\tobjects.push_back(entity);\n}\n\nostream& operator<<(ostream &o, const Scene &gw)\n{\n\to << \"---------------- SCENE ---------------\" << \"\\n\";\n\n\to << \"--------------------------------------\" << endl;\n\treturn o;\n}\n\nvoid Scene::DisplayData()\n{\n\tstring str;\n\tstringstream ss;\n\n\tss << \"Lifes: \" << player->lifes << endl;\n\tstr = \"\";\n\tss >> str;\n\n\t\/\/glRasterPos2i(0, 0);\n\t\/\/glColor3f(1, 0, 0);\n\t\/\/glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24, (const unsigned char*)\"Dzialaj\");\n\n\n\n\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n \nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n \nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n \n=========================================================================*\/\n\n\n#include \"mitkManualSegmentationToSurfaceFilter.h\"\n#include \n#include \"mitkDataTreeNodeFactory.h\"\n#include \n#include \n\n#include \n\/**\n* Test class for ManualSegmentationToSurfaceFilter and ImageToSurface\n* 1. Read an image\n* 2. Create a surface\n* 3. Create a Surface with all image processing facillities\n*\/\nint mitkManualSegmentationToSurfaceFilterTest(int argc, char* argv[])\n{\n \n if(argc==0)\n {\n std::cout<<\"no file specified [FAILED]\"<SetFileName( fileIn.c_str() );\n factory->Update();\n\n if(factory->GetNumberOfOutputs()<1)\n {\n std::cout<<\"file could not be loaded [FAILED]\"<GetOutput( 0 );\n image = dynamic_cast(node->GetData());\n if(image.IsNull())\n {\n std::cout<<\"file not an image - test will not be applied [PASSED]\"<::Pointer writer = mitk::SurfaceVtkWriter::New();\n if (filter.IsNull())\n {\n std::cout<<\"Instantiat SurfaceVtkWirter: [FAILED]\"<GlobalWarningDisplayOn();\n writer->SetFileName(fileOut.c_str());\n writer->GetVtkWriter()->SetFileTypeToBinary(); \n \n }\n \n std::cout << \"Create surface with default settings: \";\n if (image->GetDimension()==3)\n {\n filter->SetInput(image);\n filter->Update();\n writer->SetInput(filter->GetOutput());\n writer->Write();\n\n if( writer->GetNumberOfInputs() < 1 )\n {\n std::cout<<\"[FAILED]\"<Delete();\n return EXIT_FAILURE;\n }\n else\n {\n std::cout<<\"[PASSED]\"<MedianFilter3DOn();\n filter->SetGaussianStandardDeviation(1.5);\n filter->InterpolationOn();\n filter->UseGaussianImageSmoothOn();\n filter->SetThreshold( 1 ); \/\/if( Gauss ) --> TH manipulated for vtkMarchingCube\n filter->SetDecimate( mitk::ImageToSurfaceFilter::DecimatePro );\n filter->SetTargetReduction(0.05f);\n filter->SmoothOn();\n\n \/\/filter->Update();\n writer->SetInput( filter->GetOutput() );\n if( writer->GetNumberOfInputs() < 1 )\n {\n std::cout<<\"[FAILED]\"<Write();\n }\n }\n else\n {\n std::cout<<\"Image not suitable for filter: Dimension!=3\"<COMP: exception handling for writing\/*=========================================================================\n \nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n \nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n \n=========================================================================*\/\n\n\n#include \"mitkManualSegmentationToSurfaceFilter.h\"\n#include \n#include \"mitkDataTreeNodeFactory.h\"\n#include \n#include \n\n#include \n\/**\n* Test class for ManualSegmentationToSurfaceFilter and ImageToSurface\n* 1. Read an image\n* 2. Create a surface\n* 3. Create a Surface with all image processing facillities\n*\/\nint mitkManualSegmentationToSurfaceFilterTest(int argc, char* argv[])\n{\n \n if(argc==0)\n {\n std::cout<<\"no file specified [FAILED]\"<SetFileName( fileIn.c_str() );\n factory->Update();\n\n if(factory->GetNumberOfOutputs()<1)\n {\n std::cout<<\"file could not be loaded [FAILED]\"<GetOutput( 0 );\n image = dynamic_cast(node->GetData());\n if(image.IsNull())\n {\n std::cout<<\"file not an image - test will not be applied [PASSED]\"<::Pointer writer = mitk::SurfaceVtkWriter::New();\n if (filter.IsNull())\n {\n std::cout<<\"Instantiat SurfaceVtkWirter: [FAILED]\"<GlobalWarningDisplayOn();\n writer->SetFileName(fileOut.c_str());\n writer->GetVtkWriter()->SetFileTypeToBinary(); \n \n }\n \n std::cout << \"Create surface with default settings: \";\n if (image->GetDimension()==3)\n {\n filter->SetInput(image);\n filter->Update();\n writer->SetInput(filter->GetOutput());\n writer->Write();\n\n if( writer->GetNumberOfInputs() < 1 )\n {\n std::cout<<\"[FAILED]\"<Delete();\n return EXIT_FAILURE;\n }\n else\n {\n std::cout<<\"[PASSED]\"<MedianFilter3DOn();\n filter->SetGaussianStandardDeviation(1.5);\n filter->InterpolationOn();\n filter->UseGaussianImageSmoothOn();\n filter->SetThreshold( 1 ); \/\/if( Gauss ) --> TH manipulated for vtkMarchingCube\n filter->SetDecimate( mitk::ImageToSurfaceFilter::DecimatePro );\n filter->SetTargetReduction(0.05f);\n filter->SmoothOn();\n\n \/\/filter->Update();\n writer->SetInput( filter->GetOutput() );\n if( writer->GetNumberOfInputs() < 1 )\n {\n std::cout<<\"[FAILED]\"<Write();\n }\n catch( itk::ExceptionObject e)\n {\n std::cout<<\"caught exception: \"<"} {"text":"\/\/ Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include \n#include \"gtest\/gtest.h\"\n\n#include \n#include \n\nusing namespace RosettaStone;\nusing namespace SimpleTasks;\nusing namespace TestUtils;\n\nTEST(DamageTask, GetTaskID)\n{\n const DamageTask damage(EntityType::ENEMIES, 2);\n EXPECT_EQ(damage.GetTaskID(), +TaskID::DAMAGE);\n}\n\nTEST(DamageTask, Run)\n{\n GameConfig config;\n config.startPlayer = PlayerType::PLAYER1;\n Game game(config);\n\n Player& player1 = game.GetPlayer1();\n\n std::vector cards;\n cards.reserve(5);\n\n const std::string name = \"test\";\n for (std::size_t i = 0; i < 5; ++i)\n {\n const auto id = static_cast(i + 0x30);\n cards.emplace_back(GenerateMinionCard(name + id, 1, 1));\n PlayMinionCard(player1, cards[i]);\n }\n\n DamageTask damage(EntityType::FRIENDS, 1);\n TaskStatus result = damage.Run(player1);\n\n EXPECT_EQ(result, TaskStatus::COMPLETE);\n EXPECT_EQ(player1.GetField().GetNumOfMinions(), 0u);\n}\ntest: Add code to test spell power\/\/ Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include \n#include \"gtest\/gtest.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace RosettaStone;\nusing namespace SimpleTasks;\nusing namespace TestUtils;\n\nTEST(DamageTask, GetTaskID)\n{\n const DamageTask damage(EntityType::ENEMIES, 2);\n EXPECT_EQ(damage.GetTaskID(), +TaskID::DAMAGE);\n}\n\nTEST(DamageTask, Run)\n{\n GameConfig config;\n config.startPlayer = PlayerType::PLAYER1;\n Game game(config);\n\n Player& player1 = game.GetPlayer1();\n\n std::vector cards;\n cards.reserve(5);\n\n const std::string name = \"test\";\n for (std::size_t i = 0; i < 5; ++i)\n {\n const auto id = static_cast(i + 0x30);\n cards.emplace_back(GenerateMinionCard(name + id, 1, 1));\n PlayMinionCard(player1, cards[i]);\n }\n\n DamageTask damage(EntityType::FRIENDS, 1);\n TaskStatus result = damage.Run(player1);\n\n EXPECT_EQ(result, TaskStatus::COMPLETE);\n EXPECT_EQ(player1.GetField().GetNumOfMinions(), 0u);\n}\n\nTEST(DamageTask, SpellPower)\n{\n GameConfig config;\n config.startPlayer = PlayerType::PLAYER1;\n Game game(config);\n\n Player& player1 = game.GetPlayer1();\n\n std::vector cards;\n cards.reserve(5);\n\n const std::string name = \"test\";\n for (std::size_t i = 0; i < 5; ++i)\n {\n const auto id = static_cast(i + 0x30);\n cards.emplace_back(GenerateMinionCard(name + id, 1, 5));\n PlayMinionCard(player1, cards[i]);\n }\n\n DamageTask damage1(EntityType::FRIENDS, 1, true);\n damage1.SetSource(player1.GetField().GetMinion(0));\n TaskStatus result = damage1.Run(player1);\n\n EXPECT_EQ(result, TaskStatus::COMPLETE);\n for (std::size_t i = 0; i < 5; ++i)\n {\n EXPECT_EQ(player1.GetField().GetMinion(i)->health, 4);\n }\n\n player1.currentSpellPower = 1;\n\n DamageTask damage2(EntityType::FRIENDS, 1, true);\n damage2.SetSource(player1.GetField().GetMinion(0));\n result = damage2.Run(player1);\n\n EXPECT_EQ(result, TaskStatus::COMPLETE);\n for (std::size_t i = 0; i < 5; ++i)\n {\n EXPECT_EQ(player1.GetField().GetMinion(i)->health, 2);\n }\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"serialDriver.c\"\n#include \/\/ std::stringstream\n\nclass serialListener{\n\tpublic:\n\tros::NodeHandle handle;\n\tros::Publisher arduino;\n\tstd_msgs::String serialmsg;\n\tstd::stringstream read;\n\n\tint checklastln(const char* toCheck , int maxLength){\n\t\tfor(int i=0;i(\"\/tawi\/arduino\/serial\",100);\n\t}\n};\n\n\nint main (int argc, char **argv){\n\tros::init(argc, argv, \"serialListener\");\n\tserialListener serial;\n\tros::Rate hz(5);\n\twhile(ros::ok()){\n\t\tserial.poll();\n\t\tros::spinOnce();\t\n\t\thz.sleep();\n\t}\n}\nTrying to clarify serialListener.poll#include \n#include \n#include \n#include \"serialDriver.c\"\n#include \/\/ std::stringstream\n\nclass serialListener{\n\tpublic:\n\tros::NodeHandle handle;\n\tros::Publisher arduino;\n\tstd_msgs::String serialmsg;\n\tstd::stringstream read;\n\n\tint checklastln(const char* toCheck , int maxLength){\n\t\tfor(int i=0;i(\"\/tawi\/arduino\/serial\",100);\n\t}\n};\n\n\nint main (int argc, char **argv){\n\tros::init(argc, argv, \"serialListener\");\n\tserialListener serial;\n\tros::Rate hz(5);\n\twhile(ros::ok()){\n\t\tserial.poll();\n\t\tros::spinOnce();\t\n\t\thz.sleep();\n\t}\n}\n<|endoftext|>"} {"text":"#include \"mitkImageBackground2D.h\"\n\/\/ MITK includes\n#include \"mitkVtkLayerController.h\"\n#include \"mitkVtkRenderWindow.h\"\n#include \"mitkRenderWindow.h\"\n\n\/\/ VTK includes\n#include \"vtkSystemIncludes.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkMapper.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkImageActor.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkImageImport.h\"\n#include \"vtkCommand.h\"\n#include \"vtkCamera.h\"\n\n#include \n\n\/\/ VTK CALLBACK for automatic resize of the video\nclass vtkVideoSizeCallback : public vtkCommand\n{\npublic:\n static vtkVideoSizeCallback *New(){ return new vtkVideoSizeCallback; }\n \n vtkRenderer * m_ImageRenderer;\n int m_ImageWidth, m_ImageHeight;\n\n void SetVtkVideoRenderer(vtkRenderer* r)\n {\n m_ImageRenderer = r;\n }\n void SetVideoDimensions(int x, int y)\n {\n m_ImageWidth = x; m_ImageHeight = y;\n }\n\n virtual void Execute(vtkObject* \/*caller*\/, unsigned long, void*)\n {\n \/\/vtkRenderWindow * RenderWindow = reinterpret_cast(caller);\n \/\/m_ImageRenderer->ResetCameraClippingRange();\n }\n};\n\nmitk::ImageBackground2D::ImageBackground2D()\n{\n m_ImageWidth = 720;\n m_ImageHeight = 576;\n m_ImageScalarComponents = 3;\n m_ParallelScale = 0;\n m_RenderWindow = NULL;\n \n m_Actor = vtkImageActor::New();\n m_ImageRenderer = vtkRenderer::New();\n m_VtkImageImport = vtkImageImport::New();\n \n m_ImageData = 0;\n\n InitVtkImageImport();\n}\n\nvoid mitk::ImageBackground2D::InitVtkImageImport()\n{ \n m_VtkImageImport->SetDataScalarTypeToUnsignedChar();\n m_VtkImageImport->SetNumberOfScalarComponents(m_ImageScalarComponents);\n m_VtkImageImport->SetWholeExtent(0,m_ImageWidth-1,0,m_ImageHeight-1,0,1-1);\n m_VtkImageImport->SetDataExtentToWholeExtent(); \n}\n\nmitk::ImageBackground2D::~ImageBackground2D()\n{\n if ( m_RenderWindow != NULL )\n if ( this->IsEnabled() )\n this->Disable();\n if ( m_Actor!=NULL )\n m_Actor->Delete();\n if ( m_ImageRenderer != NULL )\n m_ImageRenderer->Delete();\n if ( m_VtkImageImport != NULL)\n m_VtkImageImport->Delete();\n}\n\/**\n * Sets the renderwindow, in which the Video background\n * will be shown. Make sure, you have called this function\n * before calling Enable()\n *\/\nvoid mitk::ImageBackground2D::SetRenderWindow( const mitk::RenderWindow* renderWindow )\n{\n m_RenderWindow = renderWindow;\n\n \/*m_SizeCallback = vtkVideoSizeCallback::New();\n m_RenderWindow->GetVtkRenderWindow()->AddObserver(vtkCommand::ModifiedEvent,m_SizeCallback);*\/\n \n}\n\nvoid mitk::ImageBackground2D::SetParallelScale(int scale)\n{\n m_ParallelScale = scale;\n m_ImageRenderer->GetActiveCamera()->SetParallelScale(m_ParallelScale);\n}\nint mitk::ImageBackground2D::GetParallelScale()\n{\n \/\/ TODO someone who knows this, check if double->int could cause problems\n return static_cast(m_ImageRenderer->GetActiveCamera()->GetParallelScale());\n}\n\/**\n * Enables drawing of the color Video background.\n * If you want to disable it, call the Disable() function.\n *\/\nvoid mitk::ImageBackground2D::Enable()\n{\n m_ImageRenderer = vtkRenderer::New();\n \n unsigned char * c = 0;\n Update(c);\n m_Actor->SetInput(m_VtkImageImport->GetOutput());\n \n m_ImageRenderer->AddActor2D(m_Actor);\n m_ImageRenderer->ResetCamera();\n m_ImageRenderer->InteractiveOff();\n m_ImageRenderer->GetActiveCamera()->ParallelProjectionOn();\n if(m_ParallelScale == 0)\n m_ImageRenderer->GetActiveCamera()->SetParallelScale(m_ImageHeight\/2);\n \n \/\/m_SizeCallback->SetVtkVideoRenderer(m_ImageRenderer);\n \/\/m_SizeCallback->SetVideoDimensions(m_ImageWidth, m_ImageHeight);\n m_RenderWindow->GetVtkLayerController()->InsertBackgroundRenderer(m_ImageRenderer,true); \n}\n\n\/**\n * Disables drawing of the color Video background.\n * If you want to enable it, call the Enable() function.\n *\/\nvoid mitk::ImageBackground2D::Disable()\n{\n if ( this->IsEnabled() )\n m_RenderWindow->GetVtkLayerController()->RemoveRenderer(m_ImageRenderer); \n}\n\/**\n * Checks, if the Video background is currently\n * enabled (visible)\n *\/\nbool mitk::ImageBackground2D::IsEnabled()\n{\n if ( m_RenderWindow->GetVtkLayerController()->IsRendererInserted(m_ImageRenderer) )\n return true;\n else\n return false; \n}\n\nvoid mitk::ImageBackground2D::Update(unsigned char * datapointer)\n{\n if(!IsEnabled())\n return;\n\n if(!datapointer)\n {\/\/ no valid image pointer provided -> initialize black image\n m_ImageData = new unsigned char[m_ImageHeight*m_ImageWidth*m_ImageScalarComponents];\n unsigned char* b = m_ImageData;\n for ( int textCounter = 0; textCounter < (m_ImageHeight*m_ImageWidth*m_ImageScalarComponents); textCounter++ )\n *b++ = 0;\n }\n \n m_VtkImageImport->SetImportVoidPointer(m_ImageData);\n m_VtkImageImport->Modified();\n m_VtkImageImport->Update();\n m_RenderWindow->GetVtkRenderWindow()->Render();\n \n}\n\n#ifdef OPEN_CV\n\nvoid mitk::ImageBackground2D::Update(IplImage * image)\n{\n if(!image || !IsEnabled())\n return;\n \n \n if(image->roi == NULL)\n {\n if(image->height != m_ImageHeight || image->width != m_ImageWidth || image->nChannels != m_ImageScalarComponents)\n { \/\/ image parameters changed, update data array \n m_ImageHeight = image->height;\n m_ImageWidth = image->width;\n m_ImageScalarComponents = image->nChannels;\n \n if(m_ImageData != 0)\n { \n delete m_ImageData;\n m_ImageData = 0;\n }\n }\n if(m_ImageData == 0)\n m_ImageData = new unsigned char[m_ImageWidth*m_ImageHeight*m_ImageScalarComponents];\n\n }\n else\n {\n if(image->roi->height != m_ImageHeight|| image->roi->width != m_ImageWidth || image->nChannels != m_ImageScalarComponents)\n {\n\n }\n }\n\n InitVtkImageImport();\n\n int column, row;\n unsigned char* tex = m_ImageData;\n char* data = image->imageData;\n \n if(image->nChannels == 1 && image->origin == 1)\n { \/\/ flip image\n unsigned char g;\n for (column = 0; column < m_ImageHeight; column++)\n {\n for (row = 0; row < m_ImageWidth; row++)\n {\n g = *data++;\n *tex++ = g;\n }\n }\n }\n else if(image->nChannels == 3 && image->origin == 1)\n { \/\/ flip image, change color channels\n unsigned char r, g, b;\n for (column = 0; column < m_ImageHeight; column++)\n {\n for (row = 0; row < m_ImageWidth; row++)\n { \/\/change r with b\n b = *data++;\n g = *data++;\n r = *data++;\n *tex++ = r;\n *tex++ = g;\n *tex++ = b;\n }\n }\n }\n else\n std::cout << \"opencv image not supported in mitkimagebackround2d.cpp\" << std::endl;\n\n m_VtkImageImport->SetImportVoidPointer(m_ImageData);\n m_VtkImageImport->Modified();\n m_VtkImageImport->Update();\n m_RenderWindow->GetVtkRenderWindow()->Render();\n}\n#endif\nCHG: removed opencv dependency#include \"mitkImageBackground2D.h\"\n\/\/ MITK includes\n#include \"mitkVtkLayerController.h\"\n#include \"mitkVtkRenderWindow.h\"\n#include \"mitkRenderWindow.h\"\n\n\/\/ VTK includes\n#include \"vtkSystemIncludes.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkMapper.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkImageActor.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkImageImport.h\"\n#include \"vtkCommand.h\"\n#include \"vtkCamera.h\"\n\n#include \n\n\/\/ VTK CALLBACK for automatic resize of the video\nclass vtkVideoSizeCallback : public vtkCommand\n{\npublic:\n static vtkVideoSizeCallback *New(){ return new vtkVideoSizeCallback; }\n \n vtkRenderer * m_ImageRenderer;\n int m_ImageWidth, m_ImageHeight;\n\n void SetVtkVideoRenderer(vtkRenderer* r)\n {\n m_ImageRenderer = r;\n }\n void SetVideoDimensions(int x, int y)\n {\n m_ImageWidth = x; m_ImageHeight = y;\n }\n\n virtual void Execute(vtkObject* \/*caller*\/, unsigned long, void*)\n {\n \/\/vtkRenderWindow * RenderWindow = reinterpret_cast(caller);\n \/\/m_ImageRenderer->ResetCameraClippingRange();\n }\n};\n\nmitk::ImageBackground2D::ImageBackground2D()\n{\n m_ImageWidth = 720;\n m_ImageHeight = 576;\n m_ImageScalarComponents = 3;\n m_ParallelScale = 0;\n m_RenderWindow = NULL;\n \n m_Actor = vtkImageActor::New();\n m_ImageRenderer = vtkRenderer::New();\n m_VtkImageImport = vtkImageImport::New();\n \n m_ImageData = 0;\n\n InitVtkImageImport();\n}\n\nvoid mitk::ImageBackground2D::InitVtkImageImport()\n{ \n m_VtkImageImport->SetDataScalarTypeToUnsignedChar();\n m_VtkImageImport->SetNumberOfScalarComponents(m_ImageScalarComponents);\n m_VtkImageImport->SetWholeExtent(0,m_ImageWidth-1,0,m_ImageHeight-1,0,1-1);\n m_VtkImageImport->SetDataExtentToWholeExtent(); \n}\n\nmitk::ImageBackground2D::~ImageBackground2D()\n{\n if ( m_RenderWindow != NULL )\n if ( this->IsEnabled() )\n this->Disable();\n if ( m_Actor!=NULL )\n m_Actor->Delete();\n if ( m_ImageRenderer != NULL )\n m_ImageRenderer->Delete();\n if ( m_VtkImageImport != NULL)\n m_VtkImageImport->Delete();\n}\n\/**\n * Sets the renderwindow, in which the Video background\n * will be shown. Make sure, you have called this function\n * before calling Enable()\n *\/\nvoid mitk::ImageBackground2D::SetRenderWindow( const mitk::RenderWindow* renderWindow )\n{\n m_RenderWindow = renderWindow;\n\n \/*m_SizeCallback = vtkVideoSizeCallback::New();\n m_RenderWindow->GetVtkRenderWindow()->AddObserver(vtkCommand::ModifiedEvent,m_SizeCallback);*\/\n \n}\n\nvoid mitk::ImageBackground2D::SetParallelScale(int scale)\n{\n m_ParallelScale = scale;\n m_ImageRenderer->GetActiveCamera()->SetParallelScale(m_ParallelScale);\n}\nint mitk::ImageBackground2D::GetParallelScale()\n{\n \/\/ TODO someone who knows this, check if double->int could cause problems\n return static_cast(m_ImageRenderer->GetActiveCamera()->GetParallelScale());\n}\n\/**\n * Enables drawing of the color Video background.\n * If you want to disable it, call the Disable() function.\n *\/\nvoid mitk::ImageBackground2D::Enable()\n{\n m_ImageRenderer = vtkRenderer::New();\n \n unsigned char * c = 0;\n Update(c);\n m_Actor->SetInput(m_VtkImageImport->GetOutput());\n \n m_ImageRenderer->AddActor2D(m_Actor);\n m_ImageRenderer->ResetCamera();\n m_ImageRenderer->InteractiveOff();\n m_ImageRenderer->GetActiveCamera()->ParallelProjectionOn();\n if(m_ParallelScale == 0)\n m_ImageRenderer->GetActiveCamera()->SetParallelScale(m_ImageHeight\/2);\n \n \/\/m_SizeCallback->SetVtkVideoRenderer(m_ImageRenderer);\n \/\/m_SizeCallback->SetVideoDimensions(m_ImageWidth, m_ImageHeight);\n m_RenderWindow->GetVtkLayerController()->InsertBackgroundRenderer(m_ImageRenderer,true); \n}\n\n\/**\n * Disables drawing of the color Video background.\n * If you want to enable it, call the Enable() function.\n *\/\nvoid mitk::ImageBackground2D::Disable()\n{\n if ( this->IsEnabled() )\n m_RenderWindow->GetVtkLayerController()->RemoveRenderer(m_ImageRenderer); \n}\n\/**\n * Checks, if the Video background is currently\n * enabled (visible)\n *\/\nbool mitk::ImageBackground2D::IsEnabled()\n{\n if ( m_RenderWindow->GetVtkLayerController()->IsRendererInserted(m_ImageRenderer) )\n return true;\n else\n return false; \n}\n\nvoid mitk::ImageBackground2D::Update(unsigned char * datapointer)\n{\n if(!IsEnabled())\n return;\n\n if(!datapointer)\n {\/\/ no valid image pointer provided -> initialize black image\n m_ImageData = new unsigned char[m_ImageHeight*m_ImageWidth*m_ImageScalarComponents];\n unsigned char* b = m_ImageData;\n for ( int textCounter = 0; textCounter < (m_ImageHeight*m_ImageWidth*m_ImageScalarComponents); textCounter++ )\n *b++ = 0;\n }\n \n m_VtkImageImport->SetImportVoidPointer(m_ImageData);\n m_VtkImageImport->Modified();\n m_VtkImageImport->Update();\n m_RenderWindow->GetVtkRenderWindow()->Render();\n \n}\n\n\n<|endoftext|>"} {"text":"Implement tutorial 02<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ Read in data files\nvoid readData(const std::vector & simulationScenarios,\n const std::vector & simulationParameters,\n const std::vector & simulationOutputs,\n const std::vector & experimentScenarios,\n const std::vector & experimentOutputs) {\n FILE * fp_in = fopen(\"gp\/scalar\/dakota_pstudy.dat\", \"r\");\n unsigned int i, id, size = 512;\n double k_tmasl, k_tmoml, k_tnrgl, k_xkwlx, k_cd, pressure;\n char line[size];\n\n double mins[] = {0.95, 0.9, 0.9, 0.9, 0.9};\n double maxs[] = {1.05, 1.1, 1.1, 1.1, 1.1};\n\n double meansim = 0;\n double m2sim = 0;\n\n \/\/ First line is a header, so we ignore it\n fgets(line, size, fp_in);\n\n i = 0;\n while (fscanf(fp_in, \"%d %lf %lf %lf %lf %lf %lf\\n\", &id, &k_tmasl, &k_tmoml,\n &k_tnrgl, &k_xkwlx, &k_cd, &pressure) != EOF) {\n (*(simulationScenarios[i]))[0] = 0.5;\n\n (*(simulationParameters[i]))[0] = (k_tmasl - mins[0]) \/ (maxs[0] - mins[0]);\n (*(simulationParameters[i]))[1] = (k_tmoml - mins[1]) \/ (maxs[1] - mins[1]);\n (*(simulationParameters[i]))[2] = (k_tnrgl - mins[2]) \/ (maxs[2] - mins[2]);\n (*(simulationParameters[i]))[3] = (k_xkwlx - mins[3]) \/ (maxs[3] - mins[3]);\n (*(simulationParameters[i]))[4] = (k_cd - mins[4]) \/ (maxs[4] - mins[4]);\n\n (*(simulationOutputs[i]))[0] = pressure;\n i++;\n\n double delta = pressure - meansim;\n meansim += delta \/ i;\n m2sim += delta * (pressure - meansim);\n }\n\n double stdsim = m2sim \/ (double)(i - 1);\n\n for (unsigned int j = 0; j < i; j++) {\n (*(simulationOutputs[j]))[0] -= meansim;\n (*(simulationOutputs[j]))[0] \/= stdsim;\n }\n\n fclose(fp_in); \/\/ Done with simulation data\n\n \/\/ Read in experimental data\n fp_in = fopen(\"gp\/scalar\/ctf_dat.txt\", \"r\");\n i = 0;\n while (fscanf(fp_in, \"%lf\\n\", &pressure) != EOF) {\n (*(experimentOutputs[i]))[0] = pressure;\n i++;\n }\n\n for (unsigned int j = 0; j < i; j++) {\n (*(experimentOutputs[j]))[0] -= meansim;\n (*(experimentOutputs[j]))[0] \/= stdsim;\n }\n\n fclose(fp_in);\n}\n\nint main(int argc, char ** argv) {\n \/\/ Step 0: Set up some variables\n unsigned int numExperiments = 10; \/\/ Number of experiments\n unsigned int numUncertainVars = 5; \/\/ Number of things to calibrate\n unsigned int numSimulations = 50; \/\/ Number of simulations\n unsigned int numConfigVars = 1; \/\/ Dimension of configuration space\n unsigned int numEta = 1; \/\/ Number of responses the model is returning\n unsigned int experimentSize = 1; \/\/ Size of each experiment\n\n MPI_Init(&argc, &argv);\n\n \/\/ Step 1: Set up QUESO environment\n QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], \"\", NULL);\n\n \/\/ Step 2: Set up prior for calibration parameters\n QUESO::VectorSpace paramSpace(env,\n \"param_\", numUncertainVars, NULL);\n\n \/\/ Parameter (theta) bounds:\n \/\/ descriptors 'k_tmasl' 'k_xkle' 'k_xkwew' 'k_xkwlx' 'k_cd'\n \/\/ upper_bounds 1.05 1.1 1.1 1.1 1.1\n \/\/ lower_bounds 0.95 0.9 0.9 0.9 0.9\n QUESO::GslVector paramMins(paramSpace.zeroVector());\n QUESO::GslVector paramMaxs(paramSpace.zeroVector());\n\n paramMins.cwSet(0.9);\n paramMaxs.cwSet(1.1);\n\n paramMins[0] = 0.95;\n paramMaxs[0] = 1.05;\n\n QUESO::BoxSubset paramDomain(\"param_\",\n paramSpace, paramMins, paramMaxs);\n\n QUESO::UniformVectorRV priorRv(\"prior_\",\n paramDomain);\n\n \/\/ Step 3: Instantiate the 'scenario' and 'output' spaces for simulation\n QUESO::VectorSpace configSpace(env,\n \"scenario_\", numConfigVars, NULL);\n\n QUESO::VectorSpace nEtaSpace(env,\n \"output_\", numEta, NULL);\n\n \/\/ Step 4: Instantiate the 'output' space for the experiments\n QUESO::VectorSpace experimentSpace(env,\n \"experimentspace_\", experimentSize, NULL);\n\n QUESO::VectorSpace totalExperimentSpace(env,\n \"experimentspace_\", experimentSize * numExperiments, NULL);\n\n \/\/ Step 5: Instantiate the Gaussian process emulator object\n \/\/\n \/\/ Regarding simulation scenario input values, QUESO should standardise them\n \/\/ so that they exist inside a hypercube.\n \/\/\n \/\/ Regarding simulation output data, QUESO should transform it so that the\n \/\/ mean is zero and the variance is one.\n \/\/\n \/\/ Regarding experimental scenario input values, QUESO should standardize\n \/\/ them so that they exist inside a hypercube.\n \/\/\n \/\/ Regarding experimental data, QUESO should transformed it so that it has\n \/\/ zero mean and variance one.\n\n \/\/ GaussianProcessEmulator stores all the information about our simulation\n \/\/ data and experimental data. It also stores default information about the\n \/\/ hyperparameter distributions.\n QUESO::GaussianProcessFactory\n gpFactory(\"gp_\",\n priorRv,\n configSpace,\n paramSpace,\n nEtaSpace,\n experimentSpace,\n numSimulations,\n numExperiments);\n\n \/\/ std::vector containing all the points in scenario space where we have\n \/\/ simulations\n std::vector simulationScenarios(numSimulations,\n (QUESO::GslVector *) NULL);\n\n \/\/ std::vector containing all the points in parameter space where we have\n \/\/ simulations\n std::vector paramVecs(numSimulations,\n (QUESO::GslVector *) NULL);\n\n \/\/ std::vector containing all the simulation output data\n std::vector outputVecs(numSimulations,\n (QUESO::GslVector *) NULL);\n\n \/\/ std::vector containing all the points in scenario space where we have\n \/\/ experiments\n std::vector experimentScenarios(numExperiments,\n (QUESO::GslVector *) NULL);\n\n \/\/ std::vector containing all the experimental output data\n std::vector experimentVecs(numExperiments,\n (QUESO::GslVector *) NULL);\n\n \/\/ The experimental output data observation error covariance matrix\n QUESO::GslMatrix experimentMat(totalExperimentSpace.zeroVector());\n\n \/\/ Instantiate each of the simulation points\/outputs\n for (unsigned int i = 0; i < numSimulations; i++) {\n simulationScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); \/\/ 'x_{i+1}^*' in paper\n paramVecs [i] = new QUESO::GslVector(paramSpace.zeroVector()); \/\/ 't_{i+1}^*' in paper\n outputVecs [i] = new QUESO::GslVector(nEtaSpace.zeroVector()); \/\/ 'eta_{i+1}' in paper\n }\n\n for (unsigned int i = 0; i < numExperiments; i++) {\n experimentScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); \/\/ 'x_{i+1}' in paper\n experimentVecs[i] = new QUESO::GslVector(experimentSpace.zeroVector());\n }\n\n readExpData(experimentScenarios, experimentVecs);\n readSimData(simulationScenarios, paramVecs, outputVecs);\n\n for (unsigned int i = 0; i < numExperiments; i++) {\n experimentMat(i, i) = 0.025 * 0.025;\n }\n\n \/\/ Add simulation and experimental data\n gpFactory.addSimulations(simulationScenarios, paramVecs, outputVecs);\n gpFactory.addExperiments(experimentScenarios, experimentVecs, &experimentMat);\n\n QUESO::GenericVectorRV postRv(\n \"post_\",\n gpFactory.prior().imageSet().vectorSpace());\n QUESO::StatisticalInverseProblem ip(\"\",\n NULL, gpFactory, postRv);\n\n QUESO::GslVector paramInitials(\n gpFactory.prior().imageSet().vectorSpace().zeroVector());\n\n \/\/ Initial condition of the chain\n \/\/ for (unsigned int i = 0; i < paramInitials.sizeLocal(); i++) {\n \/\/ paramInitials[i] = 0.95;\n \/\/ }\n\n \/\/ 'Best' initial conditions (from cobra report) are:\n paramInitials[0] = 1.05; \/\/ k_tmasl\n paramInitials[1] = 0.9; \/\/ k_tmoml\n paramInitials[2] = 0.9888; \/\/ k_tnrgl\n paramInitials[3] = 0.995; \/\/ k_xkwlx\n paramInitials[4] = 1.0178; \/\/ k_cd\n paramInitials[5] = 0.0; \/\/ Emulator mean\n\n for (unsigned int i = 6; i < 15; i++) {\n paramInitials[i] = 0.01;\n }\n\n QUESO::GslMatrix proposalCovMatrix(\n gpFactory.prior().imageSet().vectorSpace().zeroVector());\n for (unsigned int i = 0; i < proposalCovMatrix.numRowsLocal(); i++) {\n proposalCovMatrix(i, i) = 0.01;\n }\n std::cout << \"got here 25\" << std::endl;\n\n ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix);\n std::cout << \"got here 26\" << std::endl;\n\n MPI_Finalize();\n std::cout << \"got here 27\" << std::endl;\n\n return 0;\n}\nUpdate params for standardised data#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ Read in data files\nvoid readData(const std::vector & simulationScenarios,\n const std::vector & simulationParameters,\n const std::vector & simulationOutputs,\n const std::vector & experimentScenarios,\n const std::vector & experimentOutputs) {\n FILE * fp_in = fopen(\"gp\/scalar\/dakota_pstudy.dat\", \"r\");\n unsigned int i, id, size = 512;\n double k_tmasl, k_tmoml, k_tnrgl, k_xkwlx, k_cd, pressure;\n char line[size];\n\n double mins[] = {0.95, 0.9, 0.9, 0.9, 0.9};\n double maxs[] = {1.05, 1.1, 1.1, 1.1, 1.1};\n\n double meansim = 0;\n double m2sim = 0;\n\n \/\/ First line is a header, so we ignore it\n fgets(line, size, fp_in);\n\n i = 0;\n while (fscanf(fp_in, \"%d %lf %lf %lf %lf %lf %lf\\n\", &id, &k_tmasl, &k_tmoml,\n &k_tnrgl, &k_xkwlx, &k_cd, &pressure) != EOF) {\n (*(simulationScenarios[i]))[0] = 0.5;\n\n (*(simulationParameters[i]))[0] = (k_tmasl - mins[0]) \/ (maxs[0] - mins[0]);\n (*(simulationParameters[i]))[1] = (k_tmoml - mins[1]) \/ (maxs[1] - mins[1]);\n (*(simulationParameters[i]))[2] = (k_tnrgl - mins[2]) \/ (maxs[2] - mins[2]);\n (*(simulationParameters[i]))[3] = (k_xkwlx - mins[3]) \/ (maxs[3] - mins[3]);\n (*(simulationParameters[i]))[4] = (k_cd - mins[4]) \/ (maxs[4] - mins[4]);\n\n (*(simulationOutputs[i]))[0] = pressure;\n i++;\n\n double delta = pressure - meansim;\n meansim += delta \/ i;\n m2sim += delta * (pressure - meansim);\n }\n\n double stdsim = m2sim \/ (double)(i - 1);\n\n for (unsigned int j = 0; j < i; j++) {\n (*(simulationOutputs[j]))[0] -= meansim;\n (*(simulationOutputs[j]))[0] \/= stdsim;\n }\n\n fclose(fp_in); \/\/ Done with simulation data\n\n \/\/ Read in experimental data\n fp_in = fopen(\"gp\/scalar\/ctf_dat.txt\", \"r\");\n i = 0;\n while (fscanf(fp_in, \"%lf\\n\", &pressure) != EOF) {\n (*(experimentOutputs[i]))[0] = pressure;\n i++;\n }\n\n for (unsigned int j = 0; j < i; j++) {\n (*(experimentOutputs[j]))[0] -= meansim;\n (*(experimentOutputs[j]))[0] \/= stdsim;\n }\n\n fclose(fp_in);\n}\n\nint main(int argc, char ** argv) {\n \/\/ Step 0: Set up some variables\n unsigned int numExperiments = 10; \/\/ Number of experiments\n unsigned int numUncertainVars = 5; \/\/ Number of things to calibrate\n unsigned int numSimulations = 50; \/\/ Number of simulations\n unsigned int numConfigVars = 1; \/\/ Dimension of configuration space\n unsigned int numEta = 1; \/\/ Number of responses the model is returning\n unsigned int experimentSize = 1; \/\/ Size of each experiment\n\n MPI_Init(&argc, &argv);\n\n \/\/ Step 1: Set up QUESO environment\n QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], \"\", NULL);\n\n \/\/ Step 2: Set up prior for calibration parameters\n QUESO::VectorSpace paramSpace(env,\n \"param_\", numUncertainVars, NULL);\n\n \/\/ Parameter (theta) bounds:\n \/\/ descriptors 'k_tmasl' 'k_xkle' 'k_xkwew' 'k_xkwlx' 'k_cd'\n \/\/ upper_bounds 1.05 1.1 1.1 1.1 1.1\n \/\/ lower_bounds 0.95 0.9 0.9 0.9 0.9\n QUESO::GslVector paramMins(paramSpace.zeroVector());\n QUESO::GslVector paramMaxs(paramSpace.zeroVector());\n\n paramMins.cwSet(0.0);\n paramMaxs.cwSet(1.0);\n\n QUESO::BoxSubset paramDomain(\"param_\",\n paramSpace, paramMins, paramMaxs);\n\n QUESO::UniformVectorRV priorRv(\"prior_\",\n paramDomain);\n\n \/\/ Step 3: Instantiate the 'scenario' and 'output' spaces for simulation\n QUESO::VectorSpace configSpace(env,\n \"scenario_\", numConfigVars, NULL);\n\n QUESO::VectorSpace nEtaSpace(env,\n \"output_\", numEta, NULL);\n\n \/\/ Step 4: Instantiate the 'output' space for the experiments\n QUESO::VectorSpace experimentSpace(env,\n \"experimentspace_\", experimentSize, NULL);\n\n QUESO::VectorSpace totalExperimentSpace(env,\n \"experimentspace_\", experimentSize * numExperiments, NULL);\n\n \/\/ Step 5: Instantiate the Gaussian process emulator object\n \/\/\n \/\/ Regarding simulation scenario input values, QUESO should standardise them\n \/\/ so that they exist inside a hypercube.\n \/\/\n \/\/ Regarding simulation output data, QUESO should transform it so that the\n \/\/ mean is zero and the variance is one.\n \/\/\n \/\/ Regarding experimental scenario input values, QUESO should standardize\n \/\/ them so that they exist inside a hypercube.\n \/\/\n \/\/ Regarding experimental data, QUESO should transformed it so that it has\n \/\/ zero mean and variance one.\n\n \/\/ GaussianProcessEmulator stores all the information about our simulation\n \/\/ data and experimental data. It also stores default information about the\n \/\/ hyperparameter distributions.\n QUESO::GaussianProcessFactory\n gpFactory(\"gp_\",\n priorRv,\n configSpace,\n paramSpace,\n nEtaSpace,\n experimentSpace,\n numSimulations,\n numExperiments);\n\n \/\/ std::vector containing all the points in scenario space where we have\n \/\/ simulations\n std::vector simulationScenarios(numSimulations,\n (QUESO::GslVector *) NULL);\n\n \/\/ std::vector containing all the points in parameter space where we have\n \/\/ simulations\n std::vector paramVecs(numSimulations,\n (QUESO::GslVector *) NULL);\n\n \/\/ std::vector containing all the simulation output data\n std::vector outputVecs(numSimulations,\n (QUESO::GslVector *) NULL);\n\n \/\/ std::vector containing all the points in scenario space where we have\n \/\/ experiments\n std::vector experimentScenarios(numExperiments,\n (QUESO::GslVector *) NULL);\n\n \/\/ std::vector containing all the experimental output data\n std::vector experimentVecs(numExperiments,\n (QUESO::GslVector *) NULL);\n\n \/\/ The experimental output data observation error covariance matrix\n QUESO::GslMatrix experimentMat(totalExperimentSpace.zeroVector());\n\n \/\/ Instantiate each of the simulation points\/outputs\n for (unsigned int i = 0; i < numSimulations; i++) {\n simulationScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); \/\/ 'x_{i+1}^*' in paper\n paramVecs [i] = new QUESO::GslVector(paramSpace.zeroVector()); \/\/ 't_{i+1}^*' in paper\n outputVecs [i] = new QUESO::GslVector(nEtaSpace.zeroVector()); \/\/ 'eta_{i+1}' in paper\n }\n\n for (unsigned int i = 0; i < numExperiments; i++) {\n experimentScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); \/\/ 'x_{i+1}' in paper\n experimentVecs[i] = new QUESO::GslVector(experimentSpace.zeroVector());\n }\n\n readData(simulationScenarios,\n paramVecs,\n outputVecs,\n experimentScenarios,\n experimentVecs);\n\n for (unsigned int i = 0; i < numExperiments; i++) {\n experimentMat(i, i) = 1.0;\n }\n\n \/\/ Add simulation and experimental data\n gpFactory.addSimulations(simulationScenarios, paramVecs, outputVecs);\n gpFactory.addExperiments(experimentScenarios, experimentVecs, &experimentMat);\n\n QUESO::GenericVectorRV postRv(\n \"post_\",\n gpFactory.prior().imageSet().vectorSpace());\n QUESO::StatisticalInverseProblem ip(\"\",\n NULL, gpFactory, postRv);\n\n QUESO::GslVector paramInitials(\n gpFactory.prior().imageSet().vectorSpace().zeroVector());\n\n \/\/ Initial condition of the chain\n \/\/ for (unsigned int i = 0; i < paramInitials.sizeLocal(); i++) {\n \/\/ paramInitials[i] = 0.95;\n \/\/ }\n\n \/\/ 'Best' initial conditions (from cobra report) are:\n paramInitials[0] = 1.05; \/\/ k_tmasl\n paramInitials[1] = 0.9; \/\/ k_tmoml\n paramInitials[2] = 0.9888; \/\/ k_tnrgl\n paramInitials[3] = 0.995; \/\/ k_xkwlx\n paramInitials[4] = 1.0178; \/\/ k_cd\n paramInitials[5] = 0.0; \/\/ Emulator mean\n\n for (unsigned int i = 6; i < 15; i++) {\n paramInitials[i] = 0.01;\n }\n\n QUESO::GslMatrix proposalCovMatrix(\n gpFactory.prior().imageSet().vectorSpace().zeroVector());\n for (unsigned int i = 0; i < proposalCovMatrix.numRowsLocal(); i++) {\n proposalCovMatrix(i, i) = 0.01;\n }\n std::cout << \"got here 25\" << std::endl;\n\n ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix);\n std::cout << \"got here 26\" << std::endl;\n\n MPI_Finalize();\n std::cout << \"got here 27\" << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/** @file multiGrid_example.cpp\n\n @brief Provides an examples for the multigrid solver.\n\n This file is part of the G+Smo library.\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 Author(s): C. Hofreither, S. Takacs\n*\/\n\n#include \n\nusing namespace gismo;\n\nint main(int argc, char *argv[])\n{\n \/************** Define command line options *************\/\n\n std::string geometry(\"domain2d\/yeti_mp2.xml\");\n index_t refinements = 3;\n index_t degree = 2;\n bool dg = false;\n index_t levels = -1;\n index_t cycles = 1;\n index_t presmooth = 1;\n index_t postsmooth = 1;\n std::string smoother(\"GaussSeidel\");\n real_t damping = -1;\n real_t scaling = 0.12;\n real_t tolerance = 1.e-8;\n index_t maxIterations = 100;\n bool plot = false;\n std::string boundary_conditions(\"d\");\n\n gsCmdLine cmd(\"Solves a PDE with an isogeometric discretization using a multigrid solver.\");\n cmd.addString(\"g\", \"Geometry\", \"Geometry file\", geometry);\n cmd.addInt (\"r\", \"Refinements\", \"Number of uniform h-refinement steps to perform before solving\", refinements);\n cmd.addInt (\"p\", \"Degree\", \"Degree of the B-spline discretization space\", degree);\n cmd.addSwitch(\"\", \"DG\", \"Use a discontinuous Galerkin discretization\", dg);\n cmd.addInt (\"l\", \"MG.Levels\", \"Number of levels to use for multigrid iteration\", levels);\n cmd.addInt (\"c\", \"MG.Cycles\", \"Number of multi-grid cycles\", cycles);\n cmd.addInt (\"\", \"MG.Presmooth\", \"Number of pre-smoothing steps\", presmooth);\n cmd.addInt (\"\", \"MG.Postsmooth\", \"Number of post-smoothing steps\", postsmooth);\n cmd.addString(\"s\", \"MG.Smoother\", \"Smoothing method\", smoother);\n cmd.addReal (\"\", \"MG.Damping\", \"Damping factor for the smoother\", damping);\n cmd.addReal (\"\", \"MG.Scaling\", \"Scaling factor for the subspace corrected mass smoother\", scaling);\n cmd.addReal (\"t\", \"CG.Tolerance\", \"Stopping criterion for cg\", tolerance);\n cmd.addInt (\"\", \"CG.MaxIterations\", \"Stopping criterion for cg\", maxIterations);\n cmd.addString(\"b\", \"BoundaryConditions\", \"Boundary conditions\", boundary_conditions);\n cmd.addSwitch(\"\", \"Plot\", \"Plot the result with Paraview\", plot);\n\n try { cmd.getValues(argc,argv); } catch (int rv) { return rv; }\n\n gsOptionList opt = cmd.getOptionList();\n\n \/\/ Default case is levels:=refinements, so replace invalid default accordingly\n if (levels <0) { levels = refinements; opt.setInt( \"MG.Levels\", levels ); }\n \/\/ The smoothers know their defaults, so remove the invalid default\n if (damping<0) { opt.remove( \"MG.Damping\" ); }\n\n \/\/ Define assembler options\n opt.remove( \"DG\" );\n opt.addInt( \"Ass.InterfaceStrategy\", \"\", (index_t)( dg ? iFace::dg : iFace::conforming ) );\n opt.addInt( \"Ass.DirichletStrategy\", \"\", (index_t) dirichlet::elimination );\n\n if ( ! gsFileManager::fileExists(geometry) )\n {\n gsInfo << \"Geometry file could not be found.\\n\";\n gsInfo << \"I was searching in the current directory and in: \" << gsFileManager::getSearchPaths() << \"\\n\";\n return EXIT_FAILURE;\n }\n\n gsInfo << \"Run multiGrid_example with options:\\n\" << opt << std::endl;\n\n \/******************* Define geometry ********************\/\n\n gsInfo << \"Define geometry... \" << std::flush;\n\n gsMultiPatch<>::uPtr mpPtr = gsReadFile<>(geometry);\n if (!mpPtr)\n {\n gsInfo << \"No geometry found in file \" << geometry << \".\\n\";\n return EXIT_FAILURE;\n }\n gsMultiPatch<>& mp = *mpPtr;\n\n gsInfo << \"done.\\n\";\n\n \/************** Define boundary conditions **************\/\n\n gsInfo << \"Define boundary conditions... \" << std::flush;\n\n gsConstantFunction<> one(1.0, mp.geoDim());\n\n gsBoundaryConditions<> bc;\n {\n const index_t len = boundary_conditions.length();\n index_t i = 0;\n for (gsMultiPatch<>::const_biterator it = mp.bBegin(); it < mp.bEnd(); ++it)\n {\n char b_local;\n if ( len == 1 )\n b_local = boundary_conditions[0];\n else if ( i < len )\n b_local = boundary_conditions[i];\n else\n {\n gsInfo << \"\\nNot enough boundary conditions given.\\n\";\n return EXIT_FAILURE;\n }\n\n if ( b_local == 'd' )\n bc.addCondition( *it, condition_type::dirichlet, &one );\n else if ( b_local == 'n' )\n bc.addCondition( *it, condition_type::neumann, &one );\n else\n {\n gsInfo << \"\\nInvalid boundary condition given; only 'd' (Dirichlet) and 'n' (Neumann) are supported.\\n\";\n return EXIT_FAILURE;\n }\n\n ++i;\n }\n if ( len > i )\n gsInfo << \"\\nToo much boundary conditions have been specified. Ingnoring the remaining ones.\\n\";\n gsInfo << \"done. \"< mb(mp);\n\n for ( size_t i = 0; i < mb.nBases(); ++ i )\n mb[i].setDegreePreservingMultiplicity(degree);\n\n for ( index_t i = 0; i < refinements; ++i )\n mb.uniformRefine();\n\n gsInfo << \"done.\\n\";\n\n \/********* Setup assembler and assemble matrix **********\/\n\n gsInfo << \"Setup assembler and assemble matrix... \" << std::flush;\n\n gsPoissonAssembler<> assembler(\n mp,\n mb,\n bc,\n gsConstantFunction<>(1,mp.geoDim()),\n (dirichlet::strategy) opt.getInt(\"Ass.DirichletStrategy\"),\n (iFace::strategy) opt.getInt(\"Ass.InterfaceStrategy\")\n );\n assembler.assemble();\n\n gsInfo << \"done.\\n\";\n\n \/**************** Setup solver and solve ****************\/\n\n gsInfo << \"Setup solver and solve... \" << std::flush;\n\n std::vector< gsSparseMatrix > transferMatrices;\n std::vector< gsMultiBasis > multiBases; \/\/ only needed for subspace corrected mass smoother\n\n gsGridHierarchy<>::buildByCoarsening(give(mb), bc, opt.getGroup(\"MG\"))\n .moveMultiBasesTo(multiBases)\n .moveTransferMatricesTo(transferMatrices)\n .clear();\n\n gsMultiGridOp<>::Ptr mg = gsMultiGridOp<>::make( assembler.matrix(), transferMatrices );\n mg->setOptions( opt.getGroup(\"MG\") );\n\n for (index_t i = 1; i < mg->numLevels(); ++i)\n {\n gsPreconditionerOp<>::Ptr smootherOp;\n if ( opt.getString(\"MG.Smoother\") == \"Richardson\" )\n smootherOp = makeRichardsonOp(mg->matrix(i));\n else if ( opt.getString(\"MG.Smoother\") == \"Jacobi\" )\n smootherOp = makeJacobiOp(mg->matrix(i));\n else if ( opt.getString(\"MG.Smoother\") == \"GaussSeidel\" )\n smootherOp = makeGaussSeidelOp(mg->matrix(i));\n else if ( opt.getString(\"MG.Smoother\") == \"SubspaceCorrectedMassSmoother\" )\n {\n if (multiBases[i].nBases() != 1)\n {\n gsInfo << \"The chosen smoother only works for single-patch geometries.\\n\\n\";\n return EXIT_FAILURE;\n }\n smootherOp = gsPreconditionerFromOp<>::make(\n mg->underlyingOp(i),\n gsPatchPreconditionersCreator<>::subspaceCorrectedMassSmootherOp(multiBases[i][0],bc,opt.getGroup(\"Ass\"),scaling)\n );\n }\n else\n {\n gsInfo << \"The chosen smoother is unknown.\\n\\nKnown are:\\n Richardson\\n Jacobi\\n GaussSeidel\"\n \"\\n SubspaceCorrectedMassSmoother\\n\\n\";\n return EXIT_FAILURE;\n }\n smootherOp->setOptions( opt.getGroup(\"MG\") );\n mg->setSmoother(i, smootherOp);\n }\n\n gsMatrix<> x, errorHistory;\n x.setRandom( assembler.matrix().rows(), 1 );\n\n gsConjugateGradient<>( assembler.matrix(), mg )\n .setOptions( opt.getGroup(\"CG\") )\n .solveDetailed( assembler.rhs(), x, errorHistory );\n\n gsInfo << \"done.\\n\\n\";\n\n \/******************** Print end Exit ********************\/\n\n const index_t iter = errorHistory.rows()-1;\n const bool success = errorHistory(iter,0) < tolerance;\n if (success)\n gsInfo << \"Reached desired tolerance after \" << iter << \" iterates:\\n\";\n else\n gsInfo << \"Did not reach desired tolerance after \" << iter << \" iterates:\\n\";\n\n if (errorHistory.rows() < 20)\n gsInfo << errorHistory.transpose() << \"\\n\\n\";\n else\n gsInfo << errorHistory.topRows(5).transpose() << \" ... \" << errorHistory.bottomRows(5).transpose() << \"\\n\\n\";\n\n if (plot)\n {\n \/\/ Construct the solution as a scalar field\n gsMultiPatch<> mpsol;\n assembler.constructSolution(x, mpsol);\n gsField<> sol( assembler.patches(), mpsol );\n\n \/\/ Write approximate and exact solution to paraview files\n gsInfo << \"Plotting in Paraview.\\n\";\n gsWriteParaview<>(sol, \"multiGrid_result\", 1000);\n gsFileManager::open(\"multiGrid_result.pvd\");\n }\n else\n {\n gsInfo << \"Done. No output created, re-run with --Plot to get a ParaView \"\n \"file containing the solution.\\n\";\n }\n return success ? EXIT_SUCCESS : EXIT_FAILURE;\n};\nMore options in multiGrid_example (#279)\/** @file multiGrid_example.cpp\n\n @brief Provides an examples for the multigrid solver.\n\n This file is part of the G+Smo library.\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 Author(s): C. Hofreither, S. Takacs\n*\/\n\n#include \n\nusing namespace gismo;\n\nint main(int argc, char *argv[])\n{\n \/************** Define command line options *************\/\n\n std::string geometry(\"domain2d\/yeti_mp2.xml\");\n index_t refinements = 3;\n index_t degree = 2;\n bool dg = false;\n index_t levels = -1;\n index_t cycles = 1;\n index_t presmooth = 1;\n index_t postsmooth = 1;\n bool extrasmooth = false;\n std::string smoother(\"GaussSeidel\");\n real_t damping = -1;\n real_t scaling = 0.12;\n real_t tolerance = 1.e-8;\n index_t maxIterations = 100;\n bool plot = false;\n std::string boundary_conditions(\"d\");\n\n gsCmdLine cmd(\"Solves a PDE with an isogeometric discretization using a multigrid solver.\");\n cmd.addString(\"g\", \"Geometry\", \"Geometry file\", geometry);\n cmd.addInt (\"r\", \"Refinements\", \"Number of uniform h-refinement steps to perform before solving\", refinements);\n cmd.addInt (\"p\", \"Degree\", \"Degree of the B-spline discretization space\", degree);\n cmd.addSwitch(\"\", \"DG\", \"Use a discontinuous Galerkin discretization\", dg);\n cmd.addInt (\"l\", \"MG.Levels\", \"Number of levels to use for multigrid iteration\", levels);\n cmd.addInt (\"c\", \"MG.Cycles\", \"Number of multi-grid cycles\", cycles);\n cmd.addInt (\"\", \"MG.Presmooth\", \"Number of pre-smoothing steps\", presmooth);\n cmd.addInt (\"\", \"MG.Postsmooth\", \"Number of post-smoothing steps\", postsmooth);\n cmd.addSwitch(\"\", \"MG.Extrasmooth\", \"Doubles the number of smoothing steps for each coarser level\", extrasmooth);\n cmd.addString(\"s\", \"MG.Smoother\", \"Smoothing method\", smoother);\n cmd.addReal (\"\", \"MG.Damping\", \"Damping factor for the smoother\", damping);\n cmd.addReal (\"\", \"MG.Scaling\", \"Scaling factor for the subspace corrected mass smoother\", scaling);\n cmd.addReal (\"t\", \"CG.Tolerance\", \"Stopping criterion for cg\", tolerance);\n cmd.addInt (\"\", \"CG.MaxIterations\", \"Stopping criterion for cg\", maxIterations);\n cmd.addString(\"b\", \"BoundaryConditions\", \"Boundary conditions\", boundary_conditions);\n cmd.addSwitch(\"\", \"Plot\", \"Plot the result with Paraview\", plot);\n\n try { cmd.getValues(argc,argv); } catch (int rv) { return rv; }\n\n gsOptionList opt = cmd.getOptionList();\n\n \/\/ Default case is levels:=refinements, so replace invalid default accordingly\n if (levels <0) { levels = refinements; opt.setInt( \"MG.Levels\", levels ); }\n \/\/ The smoothers know their defaults, so remove the invalid default\n if (damping<0) { opt.remove( \"MG.Damping\" ); }\n\n \/\/ Define assembler options\n opt.remove( \"DG\" );\n opt.addInt( \"MG.InterfaceStrategy\", \"\", (index_t)( dg ? iFace::dg : iFace::conforming ) );\n opt.addInt( \"MG.DirichletStrategy\", \"\", (index_t) dirichlet::elimination );\n\n if ( ! gsFileManager::fileExists(geometry) )\n {\n gsInfo << \"Geometry file could not be found.\\n\";\n gsInfo << \"I was searching in the current directory and in: \" << gsFileManager::getSearchPaths() << \"\\n\";\n return EXIT_FAILURE;\n }\n\n gsInfo << \"Run multiGrid_example with options:\\n\" << opt << std::endl;\n\n \/******************* Define geometry ********************\/\n\n gsInfo << \"Define geometry... \" << std::flush;\n\n gsMultiPatch<>::uPtr mpPtr = gsReadFile<>(geometry);\n if (!mpPtr)\n {\n gsInfo << \"No geometry found in file \" << geometry << \".\\n\";\n return EXIT_FAILURE;\n }\n gsMultiPatch<>& mp = *mpPtr;\n\n gsInfo << \"done.\\n\";\n\n \/************** Define boundary conditions **************\/\n\n gsInfo << \"Define boundary conditions... \" << std::flush;\n\n gsConstantFunction<> one(1.0, mp.geoDim());\n\n gsBoundaryConditions<> bc;\n {\n const index_t len = boundary_conditions.length();\n index_t i = 0;\n for (gsMultiPatch<>::const_biterator it = mp.bBegin(); it < mp.bEnd(); ++it)\n {\n char b_local;\n if ( len == 1 )\n b_local = boundary_conditions[0];\n else if ( i < len )\n b_local = boundary_conditions[i];\n else\n {\n gsInfo << \"\\nNot enough boundary conditions given.\\n\";\n return EXIT_FAILURE;\n }\n\n if ( b_local == 'd' )\n bc.addCondition( *it, condition_type::dirichlet, &one );\n else if ( b_local == 'n' )\n bc.addCondition( *it, condition_type::neumann, &one );\n else\n {\n gsInfo << \"\\nInvalid boundary condition given; only 'd' (Dirichlet) and 'n' (Neumann) are supported.\\n\";\n return EXIT_FAILURE;\n }\n\n ++i;\n }\n if ( len > i )\n gsInfo << \"\\nToo much boundary conditions have been specified. Ingnoring the remaining ones.\\n\";\n gsInfo << \"done. \"< mb(mp);\n\n for ( size_t i = 0; i < mb.nBases(); ++ i )\n mb[i].setDegreePreservingMultiplicity(degree);\n\n for ( index_t i = 0; i < refinements; ++i )\n mb.uniformRefine();\n\n gsInfo << \"done.\\n\";\n\n \/********* Setup assembler and assemble matrix **********\/\n\n gsInfo << \"Setup assembler and assemble matrix... \" << std::flush;\n\n gsPoissonAssembler<> assembler(\n mp,\n mb,\n bc,\n gsConstantFunction<>(1,mp.geoDim()),\n (dirichlet::strategy) opt.getInt(\"MG.DirichletStrategy\"),\n (iFace::strategy) opt.getInt(\"MG.InterfaceStrategy\")\n );\n assembler.assemble();\n\n gsInfo << \"done.\\n\";\n\n \/**************** Setup solver and solve ****************\/\n\n gsInfo << \"Setup solver and solve... \" << std::flush;\n\n std::vector< gsSparseMatrix > transferMatrices;\n std::vector< gsMultiBasis > multiBases; \/\/ only needed for subspace corrected mass smoother\n\n gsGridHierarchy<>::buildByCoarsening(give(mb), bc, opt.getGroup(\"MG\"))\n .moveMultiBasesTo(multiBases)\n .moveTransferMatricesTo(transferMatrices)\n .clear();\n\n gsMultiGridOp<>::Ptr mg = gsMultiGridOp<>::make( assembler.matrix(), transferMatrices );\n mg->setOptions( opt.getGroup(\"MG\") );\n\n for (index_t i = 1; i < mg->numLevels(); ++i)\n {\n gsPreconditionerOp<>::Ptr smootherOp;\n if ( smoother == \"Richardson\" || smoother == \"r\" )\n smootherOp = makeRichardsonOp(mg->matrix(i));\n else if ( smoother == \"Jacobi\" || smoother == \"j\" )\n smootherOp = makeJacobiOp(mg->matrix(i));\n else if ( smoother == \"GaussSeidel\" || smoother == \"gs\" )\n smootherOp = makeGaussSeidelOp(mg->matrix(i));\n else if ( smoother == \"SubspaceCorrectedMassSmoother\" || smoother == \"scms\" || smoother == \"Hybrid\" || smoother == \"hyb\" )\n {\n if (multiBases[i].nBases() != 1)\n {\n gsInfo << \"The chosen smoother only works for single-patch geometries.\\n\\n\";\n return EXIT_FAILURE;\n }\n smootherOp = gsPreconditionerFromOp<>::make(\n mg->underlyingOp(i),\n gsPatchPreconditionersCreator<>::subspaceCorrectedMassSmootherOp(multiBases[i][0],bc,opt.getGroup(\"Ass\"),scaling)\n );\n\n if ( smoother == \"Hybrid\" || smoother == \"hyb\" )\n smootherOp = gsCompositePrecOp<>::make( makeGaussSeidelOp(mg->matrix(i)), smootherOp );\n }\n else\n {\n gsInfo << \"The chosen smoother is unknown.\\n\\nKnown are:\\n Richardson (r)\\n Jacobi (j)\\n GaussSeidel (gs)\"\n \"\\n SubspaceCorrectedMassSmoother (scms)\\n Hybrid (hyb)\\n\\n\";\n return EXIT_FAILURE;\n }\n smootherOp->setOptions( opt.getGroup(\"MG\") );\n \/\/ Handle the extra-smooth option. On the finest grid level, there is nothing to handle.\n if (extrasmooth && i < mg->numLevels()-1 )\n {\n smootherOp->setNumOfSweeps( 1 << (mg->numLevels()-1-i) );\n smootherOp = gsPreconditionerFromOp<>::make(mg->underlyingOp(i),smootherOp);\n }\n mg->setSmoother(i, smootherOp);\n }\n\n gsMatrix<> x, errorHistory;\n x.setRandom( assembler.matrix().rows(), 1 );\n\n gsConjugateGradient<>( assembler.matrix(), mg )\n .setOptions( opt.getGroup(\"CG\") )\n .solveDetailed( assembler.rhs(), x, errorHistory );\n\n gsInfo << \"done.\\n\\n\";\n\n \/******************** Print end Exit ********************\/\n\n const index_t iter = errorHistory.rows()-1;\n const bool success = errorHistory(iter,0) < tolerance;\n if (success)\n gsInfo << \"Reached desired tolerance after \" << iter << \" iterates:\\n\";\n else\n gsInfo << \"Did not reach desired tolerance after \" << iter << \" iterates:\\n\";\n\n if (errorHistory.rows() < 20)\n gsInfo << errorHistory.transpose() << \"\\n\\n\";\n else\n gsInfo << errorHistory.topRows(5).transpose() << \" ... \" << errorHistory.bottomRows(5).transpose() << \"\\n\\n\";\n\n if (plot)\n {\n \/\/ Construct the solution as a scalar field\n gsMultiPatch<> mpsol;\n assembler.constructSolution(x, mpsol);\n gsField<> sol( assembler.patches(), mpsol );\n\n \/\/ Write approximate and exact solution to paraview files\n gsInfo << \"Plotting in Paraview.\\n\";\n gsWriteParaview<>(sol, \"multiGrid_result\", 1000);\n gsFileManager::open(\"multiGrid_result.pvd\");\n }\n else\n {\n gsInfo << \"Done. No output created, re-run with --Plot to get a ParaView \"\n \"file containing the solution.\\n\";\n }\n return success ? EXIT_SUCCESS : EXIT_FAILURE;\n};\n<|endoftext|>"} {"text":"#include \"kalman_filter.h\"\n#include \nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing namespace std;\n\/\/ Please note that the Eigen library does not initialize \n\/\/ VectorXd or MatrixXd objects with zeros upon creation.\n\nKalmanFilter::KalmanFilter() {\n cout<<\"Kalman Filter constructor running\\n\"< 0.0001){\n rho_dot = (x_(0)*x_(2) + x_(1)*x_(3))\/rho;\n }\n else{\n rho_dot = 0; \n }\n\n z_pred << rho, phi, rho_dot;\n \n VectorXd y = z - z_pred;\n \n \/\/Normalize residual phi to be between -pi to pi\n y(2) = atan2(sin(y(2)), cos(y(2)));\n \n MatrixXd Ht = H_.transpose();\n MatrixXd S = H_ * P_ * Ht + R_;\n MatrixXd Si = S.inverse();\n MatrixXd PHt = P_ * Ht;\n MatrixXd K = PHt * Si;\n\n \/\/new estimate\n x_ = x_ + (K * y);\n long x_size = x_.size();\n MatrixXd I = MatrixXd::Identity(x_size, x_size);\n P_ = (I - K * H_) * P_; \n}\nfix: pass variables with references and add missing headers#include \"kalman_filter.h\"\n#include \n#include \n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing namespace std;\n\/\/ Please note that the Eigen library does not initialize \n\/\/ VectorXd or MatrixXd objects with zeros upon creation.\n\nKalmanFilter::KalmanFilter() {\n \/\/cout<<\"Kalman Filter constructor running...\\n\"< 0.0001){\n rho_dot = (x_(0)*x_(2) + x_(1)*x_(3))\/rho;\n }\n else{\n rho_dot = 0; \n }\n\n z_pred << rho, phi, rho_dot;\n \n VectorXd y = z - z_pred;\n \n \/\/Normalize residual phi to be between -pi to pi\n y(2) = atan2(sin(y(2)), cos(y(2)));\n \n MatrixXd Ht = H_.transpose();\n MatrixXd S = H_ * P_ * Ht + R_;\n MatrixXd Si = S.inverse();\n MatrixXd PHt = P_ * Ht;\n MatrixXd K = PHt * Si;\n\n \/\/new estimate\n x_ = x_ + (K * y);\n long x_size = x_.size();\n MatrixXd I = MatrixXd::Identity(x_size, x_size);\n P_ = (I - K * H_) * P_; \n}\n<|endoftext|>"} {"text":"\/\/=============================================================================\n\/\/ ■ ASM76\/ASM76.cpp\n\/\/-----------------------------------------------------------------------------\n\/\/ 全局变量与实用函数。\n\/\/=============================================================================\n\n#include \"ASM76.hpp\"\n\nnamespace ASM76 {\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 全局变量\n\t\/\/-------------------------------------------------------------------------\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 初始化\n\t\/\/-------------------------------------------------------------------------\n\tvoid init() {\n\t\tprintf(\"Init ASM76 environment\\n\");\n\t\t\/\/ nothing to do here now\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 结束处理\n\t\/\/-------------------------------------------------------------------------\n\tvoid terminate() {\n\t\tprintf(\"Terminate ASM76 environment\\n\");\n\t}\n}\nOptimize printf -> puts — just one useless step\/\/=============================================================================\n\/\/ ■ ASM76\/ASM76.cpp\n\/\/-----------------------------------------------------------------------------\n\/\/ 全局变量与实用函数。\n\/\/=============================================================================\n\n#include \"ASM76.hpp\"\n\nnamespace ASM76 {\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 全局变量\n\t\/\/-------------------------------------------------------------------------\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 初始化\n\t\/\/-------------------------------------------------------------------------\n\tvoid init() {\n\t\tputs(\"Init ASM76 environment\");\n\t\t\/\/ nothing to do here now\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 结束处理\n\t\/\/-------------------------------------------------------------------------\n\tvoid terminate() {\n\t\tputs(\"Terminate ASM76 environment\");\n\t}\n}\n<|endoftext|>"} {"text":"#include \n#include \"details\/pass\/build-ast-to-ir\/scope.h\"\n#include \"details\/utils\/check-for-valid-identifier-name.h\"\n\nusing namespace Yuni;\n\n\n\n\nnamespace Nany\n{\nnamespace IR\n{\nnamespace Producer\n{\n\n\n\tbool Scope::visitASTExprIn(const AST::Node& node, LVID& localvar, ShortString128& elementname)\n\t{\n\t\t\/\/ lvid representing the input container\n\t\tAST::Node* container = nullptr;\n\t\tAST::Node* predicate = nullptr;\n\n\t\tfor (auto& childptr: node.children)\n\t\t{\n\t\t\tauto& child = *childptr;\n\t\t\tswitch (child.rule)\n\t\t\t{\n\t\t\t\tcase AST::rgInVars:\n\t\t\t\t{\n\t\t\t\t\tif (unlikely(child.children.size() != 1))\n\t\t\t\t\t\treturn error(child) << \"only one cursor name is allowed in views\";\n\t\t\t\t\tauto& identifier = child.firstChild();\n\t\t\t\t\tif (unlikely(identifier.rule != AST::rgIdentifier))\n\t\t\t\t\t\treturn ICE(identifier) << \"identifier expected\";\n\n\t\t\t\t\tif (unlikely(not checkForValidIdentifierName(context.report, child, identifier.text, false)))\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\telementname = identifier.text;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase AST::rgInContainer:\n\t\t\t\t{\n\t\t\t\t\tif (unlikely(child.children.size() != 1))\n\t\t\t\t\t\treturn ICE(child) << \"invalid expression\";\n\n\t\t\t\t\tcontainer = &child.firstChild();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase AST::rgInPredicate:\n\t\t\t\t{\n\t\t\t\t\tif (unlikely(child.children.size() != 1))\n\t\t\t\t\t\treturn ICE(child) << \"invalid predicate expr\";\n\t\t\t\t\tauto& expr = child.firstChild();\n\t\t\t\t\tif (unlikely(expr.rule != AST::rgExpr))\n\t\t\t\t\t\treturn ICE(expr) << \"invalid node type for predicate\";\n\n\t\t\t\t\twarning(expr) << \"predicates in views are not fully implemented\";\n\t\t\t\t\tpredicate = &expr;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn ICEUnexpectedNode(child, \"[expr\/in]\");\n\t\t\t}\n\t\t}\n\n\t\tif (unlikely(!container))\n\t\t\treturn ICE(node) << \"invalid view container expr\";\n\n\t\tif (!context.reuse.inset.node)\n\t\t\tcontext.prepareReuseForIn();\n\n\t\tcontext.reuse.inset.container->children.clear();\n\t\tcontext.reuse.inset.container->children.push_back(container);\n\t\tcontext.reuse.inset.viewname->text = \"^view^default\";\n\n\t\tif (elementname.empty())\n\t\t\telementname << \"%vr\" << nextvar();\n\t\tcontext.reuse.inset.elementname->text = elementname;\n\n\t\tif (!predicate)\n\t\t\tpredicate = AST::Node::Ptr::WeakPointer(context.reuse.inset.premadeAlwaysTrue);\n\t\tcontext.reuse.inset.predicate->children.clear();\n\t\tcontext.reuse.inset.predicate->children.push_back(predicate);\n\n\t\temitDebugpos(node);\n\t\treturn visitASTExpr(*context.reuse.inset.node, localvar);\n\t}\n\n\n\tbool Scope::visitASTExprIn(const AST::Node& node, LVID& localvar)\n\t{\n\t\t\/\/ Name of the target ref for each element in the container (ignored here)\n\t\tShortString128 elementname;\n\t\treturn visitASTExprIn(node, localvar, elementname);\n\t}\n\n\n\n\n} \/\/ namespace Producer\n} \/\/ namespace IR\n} \/\/ namespace Nany\nremoved warning 'predicates in views are not fully implemented'#include \n#include \"details\/pass\/build-ast-to-ir\/scope.h\"\n#include \"details\/utils\/check-for-valid-identifier-name.h\"\n\nusing namespace Yuni;\n\n\n\n\nnamespace Nany\n{\nnamespace IR\n{\nnamespace Producer\n{\n\n\n\tbool Scope::visitASTExprIn(const AST::Node& node, LVID& localvar, ShortString128& elementname)\n\t{\n\t\t\/\/ lvid representing the input container\n\t\tAST::Node* container = nullptr;\n\t\tAST::Node* predicate = nullptr;\n\n\t\tfor (auto& childptr: node.children)\n\t\t{\n\t\t\tauto& child = *childptr;\n\t\t\tswitch (child.rule)\n\t\t\t{\n\t\t\t\tcase AST::rgInVars:\n\t\t\t\t{\n\t\t\t\t\tif (unlikely(child.children.size() != 1))\n\t\t\t\t\t\treturn error(child) << \"only one cursor name is allowed in views\";\n\t\t\t\t\tauto& identifier = child.firstChild();\n\t\t\t\t\tif (unlikely(identifier.rule != AST::rgIdentifier))\n\t\t\t\t\t\treturn ICE(identifier) << \"identifier expected\";\n\n\t\t\t\t\tif (unlikely(not checkForValidIdentifierName(context.report, child, identifier.text, false)))\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\telementname = identifier.text;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase AST::rgInContainer:\n\t\t\t\t{\n\t\t\t\t\tif (unlikely(child.children.size() != 1))\n\t\t\t\t\t\treturn ICE(child) << \"invalid expression\";\n\n\t\t\t\t\tcontainer = &child.firstChild();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase AST::rgInPredicate:\n\t\t\t\t{\n\t\t\t\t\tif (unlikely(child.children.size() != 1))\n\t\t\t\t\t\treturn ICE(child) << \"invalid predicate expr\";\n\t\t\t\t\tauto& expr = child.firstChild();\n\t\t\t\t\tif (unlikely(expr.rule != AST::rgExpr))\n\t\t\t\t\t\treturn ICE(expr) << \"invalid node type for predicate\";\n\n\t\t\t\t\tpredicate = &expr;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn ICEUnexpectedNode(child, \"[expr\/in]\");\n\t\t\t}\n\t\t}\n\n\t\tif (unlikely(!container))\n\t\t\treturn ICE(node) << \"invalid view container expr\";\n\n\t\tif (!context.reuse.inset.node)\n\t\t\tcontext.prepareReuseForIn();\n\n\t\tcontext.reuse.inset.container->children.clear();\n\t\tcontext.reuse.inset.container->children.push_back(container);\n\t\tcontext.reuse.inset.viewname->text = \"^view^default\";\n\n\t\tif (elementname.empty())\n\t\t\telementname << \"%vr\" << nextvar();\n\t\tcontext.reuse.inset.elementname->text = elementname;\n\n\t\tif (!predicate)\n\t\t\tpredicate = AST::Node::Ptr::WeakPointer(context.reuse.inset.premadeAlwaysTrue);\n\t\tcontext.reuse.inset.predicate->children.clear();\n\t\tcontext.reuse.inset.predicate->children.push_back(predicate);\n\n\t\temitDebugpos(node);\n\t\treturn visitASTExpr(*context.reuse.inset.node, localvar);\n\t}\n\n\n\tbool Scope::visitASTExprIn(const AST::Node& node, LVID& localvar)\n\t{\n\t\t\/\/ Name of the target ref for each element in the container (ignored here)\n\t\tShortString128 elementname;\n\t\treturn visitASTExprIn(node, localvar, elementname);\n\t}\n\n\n\n\n} \/\/ namespace Producer\n} \/\/ namespace IR\n} \/\/ namespace Nany\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2020-present ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n#include \"service\/raft\/raft_sys_table_storage.hh\"\n\n#include \"cql3\/untyped_result_set.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"utils\/UUID.hh\"\n\n#include \"serializer.hh\"\n#include \"idl\/raft.dist.hh\"\n#include \"serializer_impl.hh\"\n#include \"idl\/raft.dist.impl.hh\"\n\n#include \"cql3\/statements\/batch_statement.hh\"\n#include \"cql3\/statements\/modification_statement.hh\"\n#include \"cql3\/query_processor.hh\"\n\n#include \n#include \n\nnamespace service {\n\nraft_sys_table_storage::raft_sys_table_storage(cql3::query_processor& qp, raft::group_id gid)\n : _group_id(std::move(gid))\n , _qp(qp)\n , _dummy_query_state(service::client_state::for_internal_calls(), empty_service_permit())\n , _pending_op_fut(make_ready_future<>())\n{\n static const auto store_cql = format(\"INSERT INTO system.{} (group_id, term, \\\"index\\\", data) VALUES (?, ?, ?, ?)\",\n db::system_keyspace::RAFT);\n auto prepared_stmt_ptr = _qp.prepare_internal(store_cql);\n shared_ptr cql_stmt = prepared_stmt_ptr->statement;\n _store_entry_stmt = dynamic_pointer_cast(cql_stmt);\n}\n\nfuture<> raft_sys_table_storage::store_term_and_vote(raft::term_t term, raft::server_id vote) {\n return execute_with_linearization_point([this, term, vote] {\n static const auto store_cql = format(\"INSERT INTO system.{} (group_id, vote_term, vote) VALUES (?, ?, ?)\",\n db::system_keyspace::RAFT);\n return _qp.execute_internal(\n store_cql,\n {_group_id.id, int64_t(term), vote.id}).discard_result();\n });\n}\n\nfuture> raft_sys_table_storage::load_term_and_vote() {\n static const auto load_cql = format(\"SELECT vote_term, vote FROM system.{} WHERE group_id = ?\", db::system_keyspace::RAFT);\n ::shared_ptr rs = co_await _qp.execute_internal(load_cql, {_group_id.id});\n if (rs->empty()) {\n co_return std::pair(raft::term_t(), raft::server_id());\n }\n const auto& static_row = rs->one();\n raft::term_t vote_term = raft::term_t(static_row.get_or(\"vote_term\", raft::term_t{}));\n raft::server_id vote{static_row.get_or(\"vote\", raft::server_id{}.id)};\n co_return std::pair(vote_term, vote);\n}\n\nfuture raft_sys_table_storage::load_log() {\n static const auto load_cql = format(\"SELECT term, \\\"index\\\", data FROM system.{} WHERE group_id = ?\", db::system_keyspace::RAFT);\n ::shared_ptr rs = co_await _qp.execute_internal(load_cql, {_group_id.id});\n\n raft::log_entries log;\n for (const cql3::untyped_result_set_row& row : *rs) {\n if (!row.has(\"data\")) {\n \/\/ The partition only contains static cells, the log\n \/\/ is empty.\n break;\n }\n raft::term_t term = raft::term_t(row.get_as(\"term\"));\n raft::index_t idx = raft::index_t(row.get_as(\"index\"));\n auto raw_data = row.get_blob(\"data\");\n auto in = ser::as_input_stream(raw_data);\n using data_variant_type = decltype(raft::log_entry::data);\n data_variant_type data = ser::deserialize(in, boost::type());\n\n log.emplace_back(make_lw_shared(\n raft::log_entry{.term = term, .idx = idx, .data = std::move(data)}));\n\n co_await make_ready_future<>();\n }\n co_return log;\n}\n\nfuture raft_sys_table_storage::load_snapshot() {\n static const auto load_id_cql = format(\"SELECT snapshot_id FROM system.{} WHERE group_id = ?\", db::system_keyspace::RAFT);\n ::shared_ptr id_rs = co_await _qp.execute_internal(load_id_cql, {_group_id.id});\n if (id_rs->empty() || !id_rs->one().has(\"snapshot_id\")) {\n co_return raft::snapshot();\n }\n const auto& id_row = id_rs->one(); \/\/ should be only one row since snapshot_id column is static\n utils::UUID snapshot_id = id_row.get_as(\"snapshot_id\");\n\n static const auto load_snp_info_cql = format(\"SELECT idx, term, config FROM system.{} WHERE group_id = ? AND id = ?\",\n db::system_keyspace::RAFT_SNAPSHOTS);\n ::shared_ptr snp_rs = co_await _qp.execute_internal(load_snp_info_cql, {_group_id.id, snapshot_id});\n const auto& snp_row = snp_rs->one(); \/\/ should be only one matching row for a given snapshot id\n auto snp_cfg = snp_row.get_blob(\"config\");\n auto in = ser::as_input_stream(snp_cfg);\n\n raft::snapshot s{\n .idx = raft::index_t(snp_row.get_as(\"idx\")),\n .term = raft::term_t(snp_row.get_as(\"term\")),\n .config = ser::deserialize(in, boost::type()),\n .id = raft::snapshot_id(snapshot_id)};\n co_return s;\n}\n\nfuture<> raft_sys_table_storage::store_snapshot(const raft::snapshot& snap, size_t preserve_log_entries) {\n \/\/ TODO: check that snap.idx refers to an already persisted entry\n return execute_with_linearization_point([this, &snap, preserve_log_entries] () -> future<> {\n static const auto store_snp_cql = format(\"INSERT INTO system.{} (group_id, id, idx, term, config) VALUES (?, ?, ?, ?, ?)\",\n db::system_keyspace::RAFT_SNAPSHOTS);\n co_await _qp.execute_internal(\n store_snp_cql,\n {_group_id.id, snap.id.id, int64_t(snap.idx), int64_t(snap.term), data_value(ser::serialize_to_buffer(snap.config))}\n );\n \/\/ Also update the latest snapshot id in `system.raft` table\n static const auto store_latest_id_cql = format(\"INSERT INTO system.{} (group_id, snapshot_id) VALUES (?, ?)\",\n db::system_keyspace::RAFT);\n co_await _qp.execute_internal(\n store_latest_id_cql,\n {_group_id.id, snap.id.id}\n );\n if (preserve_log_entries > snap.idx) {\n co_return;\n }\n \/\/ TODO: make truncation and snapshot update in `system.raft` atomic\n co_await truncate_log_tail(raft::index_t(static_cast(snap.idx) - static_cast(preserve_log_entries)));\n });\n}\n\nfuture<> raft_sys_table_storage::do_store_log_entries(const std::vector& entries) {\n if (entries.empty()) {\n co_return;\n }\n std::vector batch_stmts;\n \/\/ statement values that can be allocated at once (one contiguous allocation)\n std::vector> stmt_values;\n \/\/ fragmented storage for log_entries data\n std::vector stmt_data_views;\n \/\/ statement value views -- required for `query_options` to consume `fragmented_temporary_buffer::view`\n std::vector> stmt_value_views;\n const size_t entries_size = entries.size();\n batch_stmts.reserve(entries_size);\n stmt_values.reserve(entries_size);\n stmt_data_views.reserve(entries_size);\n stmt_value_views.reserve(entries_size);\n\n for (const raft::log_entry_ptr& eptr : entries) {\n batch_stmts.emplace_back(cql3::statements::batch_statement::single_statement(_store_entry_stmt, false));\n\n auto data_tmp_buf = fragmented_temporary_buffer::allocate_to_fit(ser::get_sizeof(eptr->data));\n auto data_out_str = data_tmp_buf.get_ostream();\n ser::serialize(data_out_str, eptr->data);\n\n \/\/ don't include serialized \"data\" here since it will require to linearize the stream\n std::vector single_stmt_values = {\n cql3::raw_value::make_value(timeuuid_type->decompose(_group_id.id)),\n cql3::raw_value::make_value(long_type->decompose(int64_t(eptr->term))),\n cql3::raw_value::make_value(long_type->decompose(int64_t(eptr->idx)))\n };\n stmt_values.emplace_back(std::move(single_stmt_values));\n stmt_data_views.emplace_back(std::move(data_tmp_buf));\n\n \/\/ allocate value views\n std::vector value_views;\n value_views.reserve(4); \/\/ 4 is the number of required values for the insertion query \n for (const cql3::raw_value& raw : stmt_values.back()) {\n value_views.push_back(raw.to_view());\n }\n value_views.emplace_back(\n cql3::raw_value_view::make_value(\n fragmented_temporary_buffer::view(stmt_data_views.back())));\n stmt_value_views.emplace_back(std::move(value_views));\n\n co_await make_ready_future<>();\n }\n\n auto batch_options = cql3::query_options::make_batch_options(\n cql3::query_options(\n cql3::default_cql_config,\n db::consistency_level::ONE,\n std::nullopt,\n std::vector{},\n false,\n cql3::query_options::specific_options::DEFAULT,\n cql_serialization_format::latest()),\n std::move(stmt_value_views));\n\n cql3::statements::batch_statement batch(\n cql3::statements::batch_statement::type::UNLOGGED,\n std::move(batch_stmts),\n cql3::attributes::none(),\n _qp.get_cql_stats());\n\n co_await batch.execute(_qp, _dummy_query_state, batch_options);\n}\n\nfuture<> raft_sys_table_storage::store_log_entries(const std::vector& entries) {\n return execute_with_linearization_point([this, &entries] {\n return do_store_log_entries(entries);\n });\n}\n\nfuture<> raft_sys_table_storage::truncate_log(raft::index_t idx) {\n return execute_with_linearization_point([this, idx] {\n static const auto truncate_cql = format(\"DELETE FROM system.{} WHERE group_id = ? AND \\\"index\\\" >= ?\",\n db::system_keyspace::RAFT); \n return _qp.execute_internal(truncate_cql, {_group_id.id, int64_t(idx)}).discard_result();\n });\n}\n\nfuture<> raft_sys_table_storage::abort() {\n \/\/ wait for pending write requests to complete.\n \/\/ TODO: should we wait for all kinds of requests?\n return std::move(_pending_op_fut);\n}\n\nfuture<> raft_sys_table_storage::truncate_log_tail(raft::index_t idx) {\n static const auto truncate_cql = format(\"DELETE FROM system.{} WHERE group_id = ? AND \\\"index\\\" <= ?\", db::system_keyspace::RAFT);\n return _qp.execute_internal(truncate_cql, {_group_id.id, int64_t(idx)}).discard_result();\n}\n\nfuture<> raft_sys_table_storage::execute_with_linearization_point(std::function()> f) {\n promise<> task_promise;\n auto pending_fut = std::exchange(_pending_op_fut, task_promise.get_future());\n co_await std::move(pending_fut);\n try {\n co_await f();\n task_promise.set_value();\n } catch (...) {\n task_promise.set_exception(std::current_exception());\n throw;\n }\n}\n\n} \/\/ end of namespace service\nraft: raft_sys_table_storage: fix broken `load_snapshot` and `load_term_and_vote`\/*\n * Copyright (C) 2020-present ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n#include \"service\/raft\/raft_sys_table_storage.hh\"\n\n#include \"cql3\/untyped_result_set.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"utils\/UUID.hh\"\n\n#include \"serializer.hh\"\n#include \"idl\/raft.dist.hh\"\n#include \"serializer_impl.hh\"\n#include \"idl\/raft.dist.impl.hh\"\n\n#include \"cql3\/statements\/batch_statement.hh\"\n#include \"cql3\/statements\/modification_statement.hh\"\n#include \"cql3\/query_processor.hh\"\n\n#include \n#include \n\nnamespace service {\n\nraft_sys_table_storage::raft_sys_table_storage(cql3::query_processor& qp, raft::group_id gid)\n : _group_id(std::move(gid))\n , _qp(qp)\n , _dummy_query_state(service::client_state::for_internal_calls(), empty_service_permit())\n , _pending_op_fut(make_ready_future<>())\n{\n static const auto store_cql = format(\"INSERT INTO system.{} (group_id, term, \\\"index\\\", data) VALUES (?, ?, ?, ?)\",\n db::system_keyspace::RAFT);\n auto prepared_stmt_ptr = _qp.prepare_internal(store_cql);\n shared_ptr cql_stmt = prepared_stmt_ptr->statement;\n _store_entry_stmt = dynamic_pointer_cast(cql_stmt);\n}\n\nfuture<> raft_sys_table_storage::store_term_and_vote(raft::term_t term, raft::server_id vote) {\n return execute_with_linearization_point([this, term, vote] {\n static const auto store_cql = format(\"INSERT INTO system.{} (group_id, vote_term, vote) VALUES (?, ?, ?)\",\n db::system_keyspace::RAFT);\n return _qp.execute_internal(\n store_cql,\n {_group_id.id, int64_t(term), vote.id}).discard_result();\n });\n}\n\nfuture> raft_sys_table_storage::load_term_and_vote() {\n static const auto load_cql = format(\"SELECT vote_term, vote FROM system.{} WHERE group_id = ? LIMIT 1\", db::system_keyspace::RAFT);\n ::shared_ptr rs = co_await _qp.execute_internal(load_cql, {_group_id.id});\n if (rs->empty()) {\n co_return std::pair(raft::term_t(), raft::server_id());\n }\n const auto& static_row = rs->one();\n raft::term_t vote_term = raft::term_t(static_row.get_or(\"vote_term\", raft::term_t{}));\n raft::server_id vote{static_row.get_or(\"vote\", raft::server_id{}.id)};\n co_return std::pair(vote_term, vote);\n}\n\nfuture raft_sys_table_storage::load_log() {\n static const auto load_cql = format(\"SELECT term, \\\"index\\\", data FROM system.{} WHERE group_id = ?\", db::system_keyspace::RAFT);\n ::shared_ptr rs = co_await _qp.execute_internal(load_cql, {_group_id.id});\n\n raft::log_entries log;\n for (const cql3::untyped_result_set_row& row : *rs) {\n if (!row.has(\"data\")) {\n \/\/ The partition only contains static cells, the log\n \/\/ is empty.\n break;\n }\n raft::term_t term = raft::term_t(row.get_as(\"term\"));\n raft::index_t idx = raft::index_t(row.get_as(\"index\"));\n auto raw_data = row.get_blob(\"data\");\n auto in = ser::as_input_stream(raw_data);\n using data_variant_type = decltype(raft::log_entry::data);\n data_variant_type data = ser::deserialize(in, boost::type());\n\n log.emplace_back(make_lw_shared(\n raft::log_entry{.term = term, .idx = idx, .data = std::move(data)}));\n\n co_await make_ready_future<>();\n }\n co_return log;\n}\n\nfuture raft_sys_table_storage::load_snapshot() {\n static const auto load_id_cql = format(\"SELECT snapshot_id FROM system.{} WHERE group_id = ? LIMIT 1\", db::system_keyspace::RAFT);\n ::shared_ptr id_rs = co_await _qp.execute_internal(load_id_cql, {_group_id.id});\n if (id_rs->empty() || !id_rs->one().has(\"snapshot_id\")) {\n co_return raft::snapshot();\n }\n const auto& id_row = id_rs->one(); \/\/ should be only one row since snapshot_id column is static\n utils::UUID snapshot_id = id_row.get_as(\"snapshot_id\");\n\n static const auto load_snp_info_cql = format(\"SELECT idx, term, config FROM system.{} WHERE group_id = ? AND id = ?\",\n db::system_keyspace::RAFT_SNAPSHOTS);\n ::shared_ptr snp_rs = co_await _qp.execute_internal(load_snp_info_cql, {_group_id.id, snapshot_id});\n const auto& snp_row = snp_rs->one(); \/\/ should be only one matching row for a given snapshot id\n auto snp_cfg = snp_row.get_blob(\"config\");\n auto in = ser::as_input_stream(snp_cfg);\n\n raft::snapshot s{\n .idx = raft::index_t(snp_row.get_as(\"idx\")),\n .term = raft::term_t(snp_row.get_as(\"term\")),\n .config = ser::deserialize(in, boost::type()),\n .id = raft::snapshot_id(snapshot_id)};\n co_return s;\n}\n\nfuture<> raft_sys_table_storage::store_snapshot(const raft::snapshot& snap, size_t preserve_log_entries) {\n \/\/ TODO: check that snap.idx refers to an already persisted entry\n return execute_with_linearization_point([this, &snap, preserve_log_entries] () -> future<> {\n static const auto store_snp_cql = format(\"INSERT INTO system.{} (group_id, id, idx, term, config) VALUES (?, ?, ?, ?, ?)\",\n db::system_keyspace::RAFT_SNAPSHOTS);\n co_await _qp.execute_internal(\n store_snp_cql,\n {_group_id.id, snap.id.id, int64_t(snap.idx), int64_t(snap.term), data_value(ser::serialize_to_buffer(snap.config))}\n );\n \/\/ Also update the latest snapshot id in `system.raft` table\n static const auto store_latest_id_cql = format(\"INSERT INTO system.{} (group_id, snapshot_id) VALUES (?, ?)\",\n db::system_keyspace::RAFT);\n co_await _qp.execute_internal(\n store_latest_id_cql,\n {_group_id.id, snap.id.id}\n );\n if (preserve_log_entries > snap.idx) {\n co_return;\n }\n \/\/ TODO: make truncation and snapshot update in `system.raft` atomic\n co_await truncate_log_tail(raft::index_t(static_cast(snap.idx) - static_cast(preserve_log_entries)));\n });\n}\n\nfuture<> raft_sys_table_storage::do_store_log_entries(const std::vector& entries) {\n if (entries.empty()) {\n co_return;\n }\n std::vector batch_stmts;\n \/\/ statement values that can be allocated at once (one contiguous allocation)\n std::vector> stmt_values;\n \/\/ fragmented storage for log_entries data\n std::vector stmt_data_views;\n \/\/ statement value views -- required for `query_options` to consume `fragmented_temporary_buffer::view`\n std::vector> stmt_value_views;\n const size_t entries_size = entries.size();\n batch_stmts.reserve(entries_size);\n stmt_values.reserve(entries_size);\n stmt_data_views.reserve(entries_size);\n stmt_value_views.reserve(entries_size);\n\n for (const raft::log_entry_ptr& eptr : entries) {\n batch_stmts.emplace_back(cql3::statements::batch_statement::single_statement(_store_entry_stmt, false));\n\n auto data_tmp_buf = fragmented_temporary_buffer::allocate_to_fit(ser::get_sizeof(eptr->data));\n auto data_out_str = data_tmp_buf.get_ostream();\n ser::serialize(data_out_str, eptr->data);\n\n \/\/ don't include serialized \"data\" here since it will require to linearize the stream\n std::vector single_stmt_values = {\n cql3::raw_value::make_value(timeuuid_type->decompose(_group_id.id)),\n cql3::raw_value::make_value(long_type->decompose(int64_t(eptr->term))),\n cql3::raw_value::make_value(long_type->decompose(int64_t(eptr->idx)))\n };\n stmt_values.emplace_back(std::move(single_stmt_values));\n stmt_data_views.emplace_back(std::move(data_tmp_buf));\n\n \/\/ allocate value views\n std::vector value_views;\n value_views.reserve(4); \/\/ 4 is the number of required values for the insertion query \n for (const cql3::raw_value& raw : stmt_values.back()) {\n value_views.push_back(raw.to_view());\n }\n value_views.emplace_back(\n cql3::raw_value_view::make_value(\n fragmented_temporary_buffer::view(stmt_data_views.back())));\n stmt_value_views.emplace_back(std::move(value_views));\n\n co_await make_ready_future<>();\n }\n\n auto batch_options = cql3::query_options::make_batch_options(\n cql3::query_options(\n cql3::default_cql_config,\n db::consistency_level::ONE,\n std::nullopt,\n std::vector{},\n false,\n cql3::query_options::specific_options::DEFAULT,\n cql_serialization_format::latest()),\n std::move(stmt_value_views));\n\n cql3::statements::batch_statement batch(\n cql3::statements::batch_statement::type::UNLOGGED,\n std::move(batch_stmts),\n cql3::attributes::none(),\n _qp.get_cql_stats());\n\n co_await batch.execute(_qp, _dummy_query_state, batch_options);\n}\n\nfuture<> raft_sys_table_storage::store_log_entries(const std::vector& entries) {\n return execute_with_linearization_point([this, &entries] {\n return do_store_log_entries(entries);\n });\n}\n\nfuture<> raft_sys_table_storage::truncate_log(raft::index_t idx) {\n return execute_with_linearization_point([this, idx] {\n static const auto truncate_cql = format(\"DELETE FROM system.{} WHERE group_id = ? AND \\\"index\\\" >= ?\",\n db::system_keyspace::RAFT); \n return _qp.execute_internal(truncate_cql, {_group_id.id, int64_t(idx)}).discard_result();\n });\n}\n\nfuture<> raft_sys_table_storage::abort() {\n \/\/ wait for pending write requests to complete.\n \/\/ TODO: should we wait for all kinds of requests?\n return std::move(_pending_op_fut);\n}\n\nfuture<> raft_sys_table_storage::truncate_log_tail(raft::index_t idx) {\n static const auto truncate_cql = format(\"DELETE FROM system.{} WHERE group_id = ? AND \\\"index\\\" <= ?\", db::system_keyspace::RAFT);\n return _qp.execute_internal(truncate_cql, {_group_id.id, int64_t(idx)}).discard_result();\n}\n\nfuture<> raft_sys_table_storage::execute_with_linearization_point(std::function()> f) {\n promise<> task_promise;\n auto pending_fut = std::exchange(_pending_op_fut, task_promise.get_future());\n co_await std::move(pending_fut);\n try {\n co_await f();\n task_promise.set_value();\n } catch (...) {\n task_promise.set_exception(std::current_exception());\n throw;\n }\n}\n\n} \/\/ end of namespace service\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2012, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\/\n\n#ifndef PCL_FEATURES_IMPL_SHOT_LRF_OMP_H_\n#define PCL_FEATURES_IMPL_SHOT_LRF_OMP_H_\n\n#include \n#include \n#include \n\ntemplate\nvoid\npcl::SHOTLocalReferenceFrameEstimationOMP::computeFeature (PointCloudOut &output)\n{\n \/\/check whether used with search radius or search k-neighbors\n if (this->getKSearch () != 0)\n {\n PCL_ERROR(\n \"[pcl::%s::computeFeature] Error! Search method set to k-neighborhood. Call setKSearch(0) and setRadiusSearch( radius ) to use this class.\\n\",\n getClassName().c_str ());\n return;\n }\n tree_->setSortedResults (true);\n\n#pragma omp parallel for num_threads(threads_)\n for (size_t i = 0; i < indices_->size (); ++i)\n {\n \/\/ point result\n Eigen::Matrix3f rf;\n PointOutT& output_rf = output[i];\n\n \/\/output_rf.confidence = getLocalRF ((*indices_)[i], rf);\n \/\/if (output_rf.confidence == std::numeric_limits::max ())\n\n std::vector n_indices;\n std::vector n_sqr_distances;\n searchForNeighbors ((*indices_)[i], search_parameter_, n_indices, n_sqr_distances);\n if (getLocalRF ((*indices_)[i], rf) == std::numeric_limits::max ())\n {\n output.is_dense = false;\n }\n\n output_rf.x_axis.getNormalVector3fMap () = rf.row (0);\n output_rf.y_axis.getNormalVector3fMap () = rf.row (1);\n output_rf.z_axis.getNormalVector3fMap () = rf.row (2);\n }\n\n}\n\ntemplate\nvoid\npcl::SHOTLocalReferenceFrameEstimationOMP::computeFeatureEigen (pcl::PointCloud &output)\n{\n \/\/check whether used with search radius or search k-neighbors\n if (this->getKSearch () != 0)\n {\n PCL_ERROR(\n \"[pcl::%s::computeFeatureEigen] Error! Search method set to k-neighborhood. Call setKSearch(0) and setRadiusSearch( radius ) to use this class.\\n\",\n getClassName().c_str ());\n return;\n }\n tree_->setSortedResults (true);\n\n \/\/ Set up the output channels\n output.channels[\"shot_lrf\"].name = \"shot_lrf\";\n output.channels[\"shot_lrf\"].offset = 0;\n output.channels[\"shot_lrf\"].size = 4;\n output.channels[\"shot_lrf\"].count = 9;\n output.channels[\"shot_lrf\"].datatype = sensor_msgs::PointField::FLOAT32;\n\n \/\/output.points.resize (indices_->size (), 10);\n output.points.resize (indices_->size (), 9);\n\n#pragma omp parallel for num_threads(threads_)\n for (size_t i = 0; i < indices_->size (); ++i)\n {\n \/\/ point result\n Eigen::Matrix3f rf;\n\n \/\/output.points (i, 9) = getLocalRF ((*indices_)[i], rf);\n \/\/if (output.points (i, 9) == std::numeric_limits::max ())\n if (getLocalRF ((*indices_)[i], rf) == std::numeric_limits::max ())\n {\n output.is_dense = false;\n }\n\n output.points.block<1, 3> (i, 0) = rf.row (0);\n output.points.block<1, 3> (i, 3) = rf.row (1);\n output.points.block<1, 3> (i, 6) = rf.row (2);\n }\n\n}\n\n#define PCL_INSTANTIATE_SHOTLocalReferenceFrameEstimationOMP(T,OutT) template class PCL_EXPORTS pcl::SHOTLocalReferenceFrameEstimationOMP;\n\n#endif \/\/ PCL_FEATURES_IMPL_SHOT_LRF_H_\nAdded check to ensure that num_threads is a positive integer, otherwise omp raises an out of memory error. This should fix the test errors for features. However, does not fix the compilation issue in Windows. Visual Studio compiler has a bug:\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2012, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\/\n\n#ifndef PCL_FEATURES_IMPL_SHOT_LRF_OMP_H_\n#define PCL_FEATURES_IMPL_SHOT_LRF_OMP_H_\n\n#include \n#include \n#include \n\ntemplate\nvoid\npcl::SHOTLocalReferenceFrameEstimationOMP::computeFeature (PointCloudOut &output)\n{\n if (threads_ < 0)\n threads_ = 1;\n\n \/\/check whether used with search radius or search k-neighbors\n if (this->getKSearch () != 0)\n {\n PCL_ERROR(\n \"[pcl::%s::computeFeature] Error! Search method set to k-neighborhood. Call setKSearch(0) and setRadiusSearch( radius ) to use this class.\\n\",\n getClassName().c_str ());\n return;\n }\n tree_->setSortedResults (true);\n\n#pragma omp parallel for num_threads(threads_)\n for (size_t i = 0; i < indices_->size (); ++i)\n {\n \/\/ point result\n Eigen::Matrix3f rf;\n PointOutT& output_rf = output[i];\n\n \/\/output_rf.confidence = getLocalRF ((*indices_)[i], rf);\n \/\/if (output_rf.confidence == std::numeric_limits::max ())\n\n std::vector n_indices;\n std::vector n_sqr_distances;\n searchForNeighbors ((*indices_)[i], search_parameter_, n_indices, n_sqr_distances);\n if (getLocalRF ((*indices_)[i], rf) == std::numeric_limits::max ())\n {\n output.is_dense = false;\n }\n\n output_rf.x_axis.getNormalVector3fMap () = rf.row (0);\n output_rf.y_axis.getNormalVector3fMap () = rf.row (1);\n output_rf.z_axis.getNormalVector3fMap () = rf.row (2);\n }\n\n}\n\ntemplate\nvoid\npcl::SHOTLocalReferenceFrameEstimationOMP::computeFeatureEigen (pcl::PointCloud &output)\n{\n if (threads_ < 0)\n threads_ = 1;\n\n \/\/check whether used with search radius or search k-neighbors\n if (this->getKSearch () != 0)\n {\n PCL_ERROR(\n \"[pcl::%s::computeFeatureEigen] Error! Search method set to k-neighborhood. Call setKSearch(0) and setRadiusSearch( radius ) to use this class.\\n\",\n getClassName().c_str ());\n return;\n }\n tree_->setSortedResults (true);\n\n \/\/ Set up the output channels\n output.channels[\"shot_lrf\"].name = \"shot_lrf\";\n output.channels[\"shot_lrf\"].offset = 0;\n output.channels[\"shot_lrf\"].size = 4;\n output.channels[\"shot_lrf\"].count = 9;\n output.channels[\"shot_lrf\"].datatype = sensor_msgs::PointField::FLOAT32;\n\n \/\/output.points.resize (indices_->size (), 10);\n output.points.resize (indices_->size (), 9);\n\n#pragma omp parallel for num_threads(threads_)\n for (size_t i = 0; i < indices_->size (); ++i)\n {\n \/\/ point result\n Eigen::Matrix3f rf;\n\n \/\/output.points (i, 9) = getLocalRF ((*indices_)[i], rf);\n \/\/if (output.points (i, 9) == std::numeric_limits::max ())\n if (getLocalRF ((*indices_)[i], rf) == std::numeric_limits::max ())\n {\n output.is_dense = false;\n }\n\n output.points.block<1, 3> (i, 0) = rf.row (0);\n output.points.block<1, 3> (i, 3) = rf.row (1);\n output.points.block<1, 3> (i, 6) = rf.row (2);\n }\n\n}\n\n#define PCL_INSTANTIATE_SHOTLocalReferenceFrameEstimationOMP(T,OutT) template class PCL_EXPORTS pcl::SHOTLocalReferenceFrameEstimationOMP;\n\n#endif \/\/ PCL_FEATURES_IMPL_SHOT_LRF_H_\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: filedlg.cxx,v $\n *\n * $Revision: 1.18 $\n *\n * last change: $Author: kz $ $Date: 2008-03-07 16:26:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_TEMPLATEDESCRIPTION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_\n#include \n#endif\n\n#ifndef _SV_MSGBOX_HXX\n#include \n#endif\n#ifndef _SAL_TYPES_H_\n#include \n#endif\n#ifndef _URLOBJ_HXX\n#include \n#endif\n\n#ifndef _VOS_THREAD_HXX_\n#include \n#endif\n#ifndef _VOS_MUTEX_HXX_\n#include \n#endif\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n\n#ifndef _FILEDLGHELPER_HXX\n#include \n#endif\n\n#include \n\n#include \n#include \"filedlg.hxx\"\n#include \"sdresid.hxx\"\n#include \"strings.hrc\"\n\n\n\n\/\/-----------------------------------------------------------------------------\n\nnamespace css = ::com::sun::star;\n\n\n\/\/ --------------------------------------------------------------------\n\/\/ ----------- SdFileDialog_Imp ---------------------------\n\/\/ --------------------------------------------------------------------\nclass SdFileDialog_Imp : public sfx2::FileDialogHelper\n{\nprivate:\n#if defined __SUNPRO_CC\n using sfx2::FileDialogHelper::Execute;\n#endif\n\n friend class SdExportFileDialog;\n friend class SdOpenSoundFileDialog;\n\n css::uno::Reference< css::ui::dialogs::XFilePickerControlAccess > mxControlAccess;\n\n css::uno::Reference< css::media::XPlayer > mxPlayer;\n ULONG mnPlaySoundEvent;\n BOOL mbUsableSelection;\n BOOL mbLabelPlaying;\n\n void CheckSelectionState();\n\n DECL_LINK( PlayMusicHdl, void * );\n\n Timer maUpdateTimer;\n\n DECL_LINK( IsMusicStoppedHdl, void * );\n\npublic:\n SdFileDialog_Imp( const short nDialogType, sal_Bool bUsableSelection );\n ~SdFileDialog_Imp();\n\n ErrCode Execute();\n\n \/\/ overwritten from FileDialogHelper, to receive user feedback\n virtual void SAL_CALL ControlStateChanged( const css::ui::dialogs::FilePickerEvent& aEvent );\n\n sal_Bool SelectionBoxState() const;\n};\n\n\/\/ ------------------------------------------------------------------------\nvoid SAL_CALL SdFileDialog_Imp::ControlStateChanged( const css::ui::dialogs::FilePickerEvent& aEvent )\n{\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n switch( aEvent.ElementId )\n {\n case css::ui::dialogs::CommonFilePickerElementIds::LISTBOX_FILTER:\n CheckSelectionState();\n break;\n\n case css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY:\n if( mxControlAccess.is() )\n {\n if( mnPlaySoundEvent )\n Application::RemoveUserEvent( mnPlaySoundEvent );\n\n mnPlaySoundEvent = Application::PostUserEvent( LINK( this, SdFileDialog_Imp, PlayMusicHdl ) );\n }\n break;\n }\n}\n\n\/\/ ------------------------------------------------------------------------\nIMPL_LINK( SdFileDialog_Imp, PlayMusicHdl, void *, EMPTYARG )\n{\n maUpdateTimer.Stop();\n mnPlaySoundEvent = 0;\n\n if (mxPlayer.is())\n {\n if (mxPlayer->isPlaying())\n mxPlayer->stop();\n mxPlayer.clear();\n }\n\n if( mbLabelPlaying )\n {\n try\n {\n mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,\n String( SdResId( STR_PLAY ) ) );\n\n mbLabelPlaying = FALSE;\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot access play button\" );\n#endif\n }\n }\n else\n {\n rtl::OUString aUrl( GetPath() );\n if ( aUrl.getLength() )\n {\n try\n {\n mxPlayer.set( avmedia::MediaWindow::createPlayer( aUrl ), css::uno::UNO_QUERY_THROW );\n mxPlayer->start();\n maUpdateTimer.SetTimeout( 100 );\n maUpdateTimer.Start();\n }\n catch( css::uno::Exception& e )\n {\n (void)e;\n mxPlayer.clear();\n }\n\n if (mxPlayer.is())\n {\n try\n {\n mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,\n String( SdResId( STR_STOP ) ) );\n\n mbLabelPlaying = TRUE;\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot access play button\" );\n#endif\n }\n }\n }\n }\n\n return 0;\n}\n\n\/\/ ------------------------------------------------------------------------\nIMPL_LINK( SdFileDialog_Imp, IsMusicStoppedHdl, void *, EMPTYARG )\n{\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n if (\n mxPlayer.is() && mxPlayer->isPlaying() &&\n mxPlayer->getMediaTime() < mxPlayer->getDuration()\n )\n {\n maUpdateTimer.Start();\n return 0L;\n }\n\n\n if( mxControlAccess.is() )\n {\n try\n {\n mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,\n String( SdResId( STR_PLAY ) ) );\n mbLabelPlaying = FALSE;\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot access play button\" );\n#endif\n }\n }\n\n return( 0L );\n}\n\n\/\/ check whether to disable the \"selection\" checkbox\nvoid SdFileDialog_Imp::CheckSelectionState()\n{\n if( mbUsableSelection && mxControlAccess.is() )\n {\n String aCurrFilter( GetCurrentFilter() );\n\n try\n {\n if( !aCurrFilter.Len() || ( aCurrFilter == String( SdResId( STR_EXPORT_HTML_NAME ) ) ) )\n mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, FALSE );\n else\n mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, TRUE );\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot access \\\"selection\\\" checkbox\" );\n#endif\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nSdFileDialog_Imp::SdFileDialog_Imp( const short nDialogType,\n sal_Bool bUsableSelection ) :\n FileDialogHelper( nDialogType, 0 ),\n mnPlaySoundEvent( 0 ),\n mbUsableSelection( bUsableSelection ),\n mbLabelPlaying(FALSE)\n{\n maUpdateTimer.SetTimeoutHdl(LINK(this, SdFileDialog_Imp, IsMusicStoppedHdl));\n\n css::uno::Reference < ::com::sun::star::ui::dialogs::XFilePicker > xFileDlg = GetFilePicker();\n\n \/\/ get the control access\n mxControlAccess = css::uno::Reference< css::ui::dialogs::XFilePickerControlAccess > ( xFileDlg, css::uno::UNO_QUERY );\n\n if( mxControlAccess.is() )\n {\n if( nDialogType ==\n css::ui::dialogs::TemplateDescription::FILEOPEN_PLAY )\n {\n try\n {\n mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,\n String( SdResId( STR_PLAY ) ) );\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot set play button label\" );\n#endif\n }\n }\n else if( mbUsableSelection != sal_True )\n {\n try\n {\n mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, FALSE );\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot disable selection checkbox\" );\n#endif\n }\n }\n }\n}\n\n\n\/\/ ------------------------------------------------------------------------\nSdFileDialog_Imp::~SdFileDialog_Imp()\n{\n if( mnPlaySoundEvent )\n Application::RemoveUserEvent( mnPlaySoundEvent );\n}\n\n\/\/ ------------------------------------------------------------------------\nErrCode SdFileDialog_Imp::Execute()\n{\n \/\/ make sure selection checkbox is disabled if\n \/\/ HTML is current filter!\n CheckSelectionState();\n return FileDialogHelper::Execute();\n}\n\n\/\/ ------------------------------------------------------------------------\nsal_Bool SdFileDialog_Imp::SelectionBoxState() const\n{\n if ( !mbUsableSelection || !mxControlAccess.is() )\n return sal_False;\n\n sal_Bool bState(0);\n try\n {\n mxControlAccess->getValue( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0 ) >>= bState;\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot access \\\"selection\\\" checkbox\" );\n#endif\n }\n\n return bState;\n}\n\n\n\/\/ --------------------------------------------------------------------\n\/\/ ----------- SdExportFileDialog ---------------------------\n\/\/ --------------------------------------------------------------------\n\n\/\/ these are simple forwarders\nSdExportFileDialog::SdExportFileDialog(BOOL bHaveCheckbox) :\n mpImpl( new SdFileDialog_Imp( css::ui::dialogs::TemplateDescription::FILESAVE_AUTOEXTENSION_SELECTION,\n bHaveCheckbox ) )\n{\n \/\/ setup filter\n const String aHTMLFilter( SdResId( STR_EXPORT_HTML_NAME ) );\n GraphicFilter* pFilter = GetGrfFilter();\n const USHORT nFilterCount = pFilter->GetExportFormatCount();\n\n \/\/ add HTML filter\n mpImpl->AddFilter( aHTMLFilter, String( SdResId( STR_EXPORT_HTML_FILTER ) ) );\n\n \/\/ add other graphic filters\n for ( USHORT i = 0; i < nFilterCount; i++ )\n {\n mpImpl->AddFilter( pFilter->GetExportFormatName( i ),\n pFilter->GetExportWildcard( i ) );\n }\n\n \/\/ set dialog title\n mpImpl->SetTitle( String( SdResId( STR_EXPORT_DIALOG_TITLE ) ) );\n}\n\n\/\/ ------------------------------------------------------------------------\nSdExportFileDialog::~SdExportFileDialog()\n{\n}\n\n\/\/ ------------------------------------------------------------------------\nErrCode SdExportFileDialog::Execute()\n{\n return mpImpl->Execute();\n}\n\nString SdExportFileDialog::GetPath() const\n{\n return mpImpl->GetPath();\n}\n\n\/\/ ------------------------------------------------------------------------\nvoid SdExportFileDialog::SetPath( const String& rPath )\n{\n mpImpl->SetDisplayDirectory( rPath );\n}\n\n\/\/ ------------------------------------------------------------------------\nString SdExportFileDialog::ReqCurrentFilter() const\n{\n return mpImpl->GetCurrentFilter();\n}\n\n\/\/ ------------------------------------------------------------------------\nBOOL SdExportFileDialog::IsExportSelection() const\n{\n return mpImpl->SelectionBoxState();\n}\n\n\n\/\/ --------------------------------------------------------------------\n\/\/ ----------- SdOpenSoundFileDialog -----------------------\n\/\/ --------------------------------------------------------------------\n\n\/\/ these are simple forwarders\nSdOpenSoundFileDialog::SdOpenSoundFileDialog() :\n mpImpl(\n new SdFileDialog_Imp(\n css::ui::dialogs::TemplateDescription::FILEOPEN_PLAY, sal_False ) )\n{\n String aDescr;\n aDescr = String(SdResId(STR_ALL_FILES));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.*\" ) ) );\n\n \/\/ setup filter\n#if defined UNX\n aDescr = String(SdResId(STR_AU_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.au;*.snd\" ) ) );\n aDescr = String(SdResId(STR_VOC_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.voc\" ) ) );\n aDescr = String(SdResId(STR_WAV_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.wav\" ) ) );\n aDescr = String(SdResId(STR_AIFF_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.aiff\" ) ) );\n aDescr = String(SdResId(STR_SVX_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.svx\" ) ) );\n#else\n aDescr = String(SdResId(STR_WAV_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.wav;*.mp3;*.ogg\" ) ) );\n aDescr = String(SdResId(STR_MIDI_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.mid\" ) ) );\n#endif\n}\n\n\/\/ ------------------------------------------------------------------------\nSdOpenSoundFileDialog::~SdOpenSoundFileDialog()\n{\n}\n\n\/\/ ------------------------------------------------------------------------\nErrCode SdOpenSoundFileDialog::Execute()\n{\n return mpImpl->Execute();\n}\n\n\/\/ ------------------------------------------------------------------------\nString SdOpenSoundFileDialog::GetPath() const\n{\n return mpImpl->GetPath();\n}\n\n\/\/ ------------------------------------------------------------------------\nvoid SdOpenSoundFileDialog::SetPath( const String& rPath )\n{\n mpImpl->SetDisplayDirectory( rPath );\n}\nINTEGRATION: CWS changefileheader (1.18.24); FILE MERGED 2008\/04\/01 15:34:19 thb 1.18.24.3: #i85898# Stripping all external header guards 2008\/04\/01 12:38:41 thb 1.18.24.2: #i85898# Stripping all external header guards 2008\/03\/31 13:57:45 rt 1.18.24.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: filedlg.cxx,v $\n * $Revision: 1.19 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \"filedlg.hxx\"\n#include \"sdresid.hxx\"\n#include \"strings.hrc\"\n\n\n\n\/\/-----------------------------------------------------------------------------\n\nnamespace css = ::com::sun::star;\n\n\n\/\/ --------------------------------------------------------------------\n\/\/ ----------- SdFileDialog_Imp ---------------------------\n\/\/ --------------------------------------------------------------------\nclass SdFileDialog_Imp : public sfx2::FileDialogHelper\n{\nprivate:\n#if defined __SUNPRO_CC\n using sfx2::FileDialogHelper::Execute;\n#endif\n\n friend class SdExportFileDialog;\n friend class SdOpenSoundFileDialog;\n\n css::uno::Reference< css::ui::dialogs::XFilePickerControlAccess > mxControlAccess;\n\n css::uno::Reference< css::media::XPlayer > mxPlayer;\n ULONG mnPlaySoundEvent;\n BOOL mbUsableSelection;\n BOOL mbLabelPlaying;\n\n void CheckSelectionState();\n\n DECL_LINK( PlayMusicHdl, void * );\n\n Timer maUpdateTimer;\n\n DECL_LINK( IsMusicStoppedHdl, void * );\n\npublic:\n SdFileDialog_Imp( const short nDialogType, sal_Bool bUsableSelection );\n ~SdFileDialog_Imp();\n\n ErrCode Execute();\n\n \/\/ overwritten from FileDialogHelper, to receive user feedback\n virtual void SAL_CALL ControlStateChanged( const css::ui::dialogs::FilePickerEvent& aEvent );\n\n sal_Bool SelectionBoxState() const;\n};\n\n\/\/ ------------------------------------------------------------------------\nvoid SAL_CALL SdFileDialog_Imp::ControlStateChanged( const css::ui::dialogs::FilePickerEvent& aEvent )\n{\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n switch( aEvent.ElementId )\n {\n case css::ui::dialogs::CommonFilePickerElementIds::LISTBOX_FILTER:\n CheckSelectionState();\n break;\n\n case css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY:\n if( mxControlAccess.is() )\n {\n if( mnPlaySoundEvent )\n Application::RemoveUserEvent( mnPlaySoundEvent );\n\n mnPlaySoundEvent = Application::PostUserEvent( LINK( this, SdFileDialog_Imp, PlayMusicHdl ) );\n }\n break;\n }\n}\n\n\/\/ ------------------------------------------------------------------------\nIMPL_LINK( SdFileDialog_Imp, PlayMusicHdl, void *, EMPTYARG )\n{\n maUpdateTimer.Stop();\n mnPlaySoundEvent = 0;\n\n if (mxPlayer.is())\n {\n if (mxPlayer->isPlaying())\n mxPlayer->stop();\n mxPlayer.clear();\n }\n\n if( mbLabelPlaying )\n {\n try\n {\n mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,\n String( SdResId( STR_PLAY ) ) );\n\n mbLabelPlaying = FALSE;\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot access play button\" );\n#endif\n }\n }\n else\n {\n rtl::OUString aUrl( GetPath() );\n if ( aUrl.getLength() )\n {\n try\n {\n mxPlayer.set( avmedia::MediaWindow::createPlayer( aUrl ), css::uno::UNO_QUERY_THROW );\n mxPlayer->start();\n maUpdateTimer.SetTimeout( 100 );\n maUpdateTimer.Start();\n }\n catch( css::uno::Exception& e )\n {\n (void)e;\n mxPlayer.clear();\n }\n\n if (mxPlayer.is())\n {\n try\n {\n mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,\n String( SdResId( STR_STOP ) ) );\n\n mbLabelPlaying = TRUE;\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot access play button\" );\n#endif\n }\n }\n }\n }\n\n return 0;\n}\n\n\/\/ ------------------------------------------------------------------------\nIMPL_LINK( SdFileDialog_Imp, IsMusicStoppedHdl, void *, EMPTYARG )\n{\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n\n if (\n mxPlayer.is() && mxPlayer->isPlaying() &&\n mxPlayer->getMediaTime() < mxPlayer->getDuration()\n )\n {\n maUpdateTimer.Start();\n return 0L;\n }\n\n\n if( mxControlAccess.is() )\n {\n try\n {\n mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,\n String( SdResId( STR_PLAY ) ) );\n mbLabelPlaying = FALSE;\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot access play button\" );\n#endif\n }\n }\n\n return( 0L );\n}\n\n\/\/ check whether to disable the \"selection\" checkbox\nvoid SdFileDialog_Imp::CheckSelectionState()\n{\n if( mbUsableSelection && mxControlAccess.is() )\n {\n String aCurrFilter( GetCurrentFilter() );\n\n try\n {\n if( !aCurrFilter.Len() || ( aCurrFilter == String( SdResId( STR_EXPORT_HTML_NAME ) ) ) )\n mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, FALSE );\n else\n mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, TRUE );\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot access \\\"selection\\\" checkbox\" );\n#endif\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nSdFileDialog_Imp::SdFileDialog_Imp( const short nDialogType,\n sal_Bool bUsableSelection ) :\n FileDialogHelper( nDialogType, 0 ),\n mnPlaySoundEvent( 0 ),\n mbUsableSelection( bUsableSelection ),\n mbLabelPlaying(FALSE)\n{\n maUpdateTimer.SetTimeoutHdl(LINK(this, SdFileDialog_Imp, IsMusicStoppedHdl));\n\n css::uno::Reference < ::com::sun::star::ui::dialogs::XFilePicker > xFileDlg = GetFilePicker();\n\n \/\/ get the control access\n mxControlAccess = css::uno::Reference< css::ui::dialogs::XFilePickerControlAccess > ( xFileDlg, css::uno::UNO_QUERY );\n\n if( mxControlAccess.is() )\n {\n if( nDialogType ==\n css::ui::dialogs::TemplateDescription::FILEOPEN_PLAY )\n {\n try\n {\n mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,\n String( SdResId( STR_PLAY ) ) );\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot set play button label\" );\n#endif\n }\n }\n else if( mbUsableSelection != sal_True )\n {\n try\n {\n mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, FALSE );\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot disable selection checkbox\" );\n#endif\n }\n }\n }\n}\n\n\n\/\/ ------------------------------------------------------------------------\nSdFileDialog_Imp::~SdFileDialog_Imp()\n{\n if( mnPlaySoundEvent )\n Application::RemoveUserEvent( mnPlaySoundEvent );\n}\n\n\/\/ ------------------------------------------------------------------------\nErrCode SdFileDialog_Imp::Execute()\n{\n \/\/ make sure selection checkbox is disabled if\n \/\/ HTML is current filter!\n CheckSelectionState();\n return FileDialogHelper::Execute();\n}\n\n\/\/ ------------------------------------------------------------------------\nsal_Bool SdFileDialog_Imp::SelectionBoxState() const\n{\n if ( !mbUsableSelection || !mxControlAccess.is() )\n return sal_False;\n\n sal_Bool bState(0);\n try\n {\n mxControlAccess->getValue( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0 ) >>= bState;\n }\n catch( css::lang::IllegalArgumentException )\n {\n#ifdef DBG_UTIL\n DBG_ERROR( \"Cannot access \\\"selection\\\" checkbox\" );\n#endif\n }\n\n return bState;\n}\n\n\n\/\/ --------------------------------------------------------------------\n\/\/ ----------- SdExportFileDialog ---------------------------\n\/\/ --------------------------------------------------------------------\n\n\/\/ these are simple forwarders\nSdExportFileDialog::SdExportFileDialog(BOOL bHaveCheckbox) :\n mpImpl( new SdFileDialog_Imp( css::ui::dialogs::TemplateDescription::FILESAVE_AUTOEXTENSION_SELECTION,\n bHaveCheckbox ) )\n{\n \/\/ setup filter\n const String aHTMLFilter( SdResId( STR_EXPORT_HTML_NAME ) );\n GraphicFilter* pFilter = GetGrfFilter();\n const USHORT nFilterCount = pFilter->GetExportFormatCount();\n\n \/\/ add HTML filter\n mpImpl->AddFilter( aHTMLFilter, String( SdResId( STR_EXPORT_HTML_FILTER ) ) );\n\n \/\/ add other graphic filters\n for ( USHORT i = 0; i < nFilterCount; i++ )\n {\n mpImpl->AddFilter( pFilter->GetExportFormatName( i ),\n pFilter->GetExportWildcard( i ) );\n }\n\n \/\/ set dialog title\n mpImpl->SetTitle( String( SdResId( STR_EXPORT_DIALOG_TITLE ) ) );\n}\n\n\/\/ ------------------------------------------------------------------------\nSdExportFileDialog::~SdExportFileDialog()\n{\n}\n\n\/\/ ------------------------------------------------------------------------\nErrCode SdExportFileDialog::Execute()\n{\n return mpImpl->Execute();\n}\n\nString SdExportFileDialog::GetPath() const\n{\n return mpImpl->GetPath();\n}\n\n\/\/ ------------------------------------------------------------------------\nvoid SdExportFileDialog::SetPath( const String& rPath )\n{\n mpImpl->SetDisplayDirectory( rPath );\n}\n\n\/\/ ------------------------------------------------------------------------\nString SdExportFileDialog::ReqCurrentFilter() const\n{\n return mpImpl->GetCurrentFilter();\n}\n\n\/\/ ------------------------------------------------------------------------\nBOOL SdExportFileDialog::IsExportSelection() const\n{\n return mpImpl->SelectionBoxState();\n}\n\n\n\/\/ --------------------------------------------------------------------\n\/\/ ----------- SdOpenSoundFileDialog -----------------------\n\/\/ --------------------------------------------------------------------\n\n\/\/ these are simple forwarders\nSdOpenSoundFileDialog::SdOpenSoundFileDialog() :\n mpImpl(\n new SdFileDialog_Imp(\n css::ui::dialogs::TemplateDescription::FILEOPEN_PLAY, sal_False ) )\n{\n String aDescr;\n aDescr = String(SdResId(STR_ALL_FILES));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.*\" ) ) );\n\n \/\/ setup filter\n#if defined UNX\n aDescr = String(SdResId(STR_AU_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.au;*.snd\" ) ) );\n aDescr = String(SdResId(STR_VOC_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.voc\" ) ) );\n aDescr = String(SdResId(STR_WAV_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.wav\" ) ) );\n aDescr = String(SdResId(STR_AIFF_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.aiff\" ) ) );\n aDescr = String(SdResId(STR_SVX_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.svx\" ) ) );\n#else\n aDescr = String(SdResId(STR_WAV_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.wav;*.mp3;*.ogg\" ) ) );\n aDescr = String(SdResId(STR_MIDI_FILE));\n mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"*.mid\" ) ) );\n#endif\n}\n\n\/\/ ------------------------------------------------------------------------\nSdOpenSoundFileDialog::~SdOpenSoundFileDialog()\n{\n}\n\n\/\/ ------------------------------------------------------------------------\nErrCode SdOpenSoundFileDialog::Execute()\n{\n return mpImpl->Execute();\n}\n\n\/\/ ------------------------------------------------------------------------\nString SdOpenSoundFileDialog::GetPath() const\n{\n return mpImpl->GetPath();\n}\n\n\/\/ ------------------------------------------------------------------------\nvoid SdOpenSoundFileDialog::SetPath( const String& rPath )\n{\n mpImpl->SetDisplayDirectory( rPath );\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: docprev.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: kz $ $Date: 2008-04-03 14:00:46 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SD_DOCPREV_HXX_\n#define _SD_DOCPREV_HXX_\n\n#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_\n#include \n#endif\n\n#ifndef _SV_WINDOW_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SV_GEN_HXX \/\/autogen\n#include \n#endif\n\n#include \n\n#ifndef _SFXLSTNER_HXX\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_COLORCFG_HXX\n#include \n#endif\n\n#ifndef _SD_FADEDEF_H\n#include \"fadedef.h\"\n#endif\n#ifndef INCLUDED_SDDLLAPI_H\n#include \"sddllapi.h\"\n#endif\n\nnamespace sd {\n class SlideShow;\n}\n\nclass GDIMetaFile;\n\nclass SD_DLLPUBLIC SdDocPreviewWin : public Control, public SfxListener\n{\nprotected:\n GDIMetaFile* pMetaFile;\n BOOL bInEffect;\n Link aClickHdl;\n SfxObjectShell* mpObj;\n sal_uInt16 mnShowPage;\n Color maDocumentColor;\n rtl::Reference< sd::SlideShow > mxSlideShow;\n\n virtual void Paint( const Rectangle& rRect );\n static void CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint );\n void ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev );\n\n static const int FRAME;\n\n svtools::ColorConfig maColorConfig;\n\n virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);\n\n void updateViewSettings();\n\npublic:\n SdDocPreviewWin( Window* pParent, const ResId& rResId );\n SdDocPreviewWin( Window* pParent );\n ~SdDocPreviewWin();\n void SetObjectShell( SfxObjectShell* pObj, sal_uInt16 nShowPage = 0 );\n void SetGDIFile( GDIMetaFile* pFile );\n virtual void Resize();\n void startPreview();\n\n virtual long Notify( NotifyEvent& rNEvt );\n\n void SetClickHdl( const Link& rLink ) { aClickHdl = rLink; }\n const Link& GetClickHdl() const { return aClickHdl; }\n\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n\n};\n\n#endif\n\nINTEGRATION: CWS changefileheader (1.8.624); FILE MERGED 2008\/04\/01 15:35:22 thb 1.8.624.3: #i85898# Stripping all external header guards 2008\/04\/01 12:39:03 thb 1.8.624.2: #i85898# Stripping all external header guards 2008\/03\/31 13:58:13 rt 1.8.624.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: docprev.hxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SD_DOCPREV_HXX_\n#define _SD_DOCPREV_HXX_\n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \"fadedef.h\"\n#include \"sddllapi.h\"\n\nnamespace sd {\n class SlideShow;\n}\n\nclass GDIMetaFile;\n\nclass SD_DLLPUBLIC SdDocPreviewWin : public Control, public SfxListener\n{\nprotected:\n GDIMetaFile* pMetaFile;\n BOOL bInEffect;\n Link aClickHdl;\n SfxObjectShell* mpObj;\n sal_uInt16 mnShowPage;\n Color maDocumentColor;\n rtl::Reference< sd::SlideShow > mxSlideShow;\n\n virtual void Paint( const Rectangle& rRect );\n static void CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint );\n void ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev );\n\n static const int FRAME;\n\n svtools::ColorConfig maColorConfig;\n\n virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);\n\n void updateViewSettings();\n\npublic:\n SdDocPreviewWin( Window* pParent, const ResId& rResId );\n SdDocPreviewWin( Window* pParent );\n ~SdDocPreviewWin();\n void SetObjectShell( SfxObjectShell* pObj, sal_uInt16 nShowPage = 0 );\n void SetGDIFile( GDIMetaFile* pFile );\n virtual void Resize();\n void startPreview();\n\n virtual long Notify( NotifyEvent& rNEvt );\n\n void SetClickHdl( const Link& rLink ) { aClickHdl = rLink; }\n const Link& GetClickHdl() const { return aClickHdl; }\n\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n\n};\n\n#endif\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \"StateSpace.h\"\n#include \"PriorityQueue.h\"\n#include \"State.h\"\n#include \"encoder.h\"\n#include \"CreateModule.h\"\n\n\/**\n * @brief Gives a std::string representation of a primitive type\n * \n * @param x Primitive type such as int, double, long\n * @return std::string conversion of param x\n *\/\ntemplate std::string to_string(T x) {\n\treturn static_cast((std::ostringstream() << std::dec << x)).str();\n}\n\n\/\/function to calculate a temperature for the select action function as a function of time\ndouble temperature();\n\n\/\/function to select next action\nint * selectAction(PriorityQueue& a_queue);\n\n\/\/function to update a q value\nvoid updateQ(StateSpace & space, int * action, State & new_state, State & old_state, double alpha, double gamma);\n\nint main()\n{\t\n\t\/\/ STUFF WE DONT UNDERSTAND, AND DONT NEED TO\n\t\/\/__________________________________________________________________________________________\n\t\/\/__________________________________________________________________________________________\n\t\/\/ Libraries to load\n\tstd::string bodyLibName = \"bodyinfo\";\n\tstd::string movementLibName = \"movementtools\";\n\t\n\t\/\/ Name of camera module in library\n\tstd::string bodyModuleName = \"BodyInfo\";\n\tstd::string movementModuleName = \"MovementTools\";\n\n\t\/\/ Set broker name, ip and port, finding first available port from 54000\n\tconst std::string brokerName = \"MotionTimingBroker\";\n\tint brokerPort = qi::os::findAvailablePort(54000);\n\tconst std::string brokerIp = \"0.0.0.0\";\n\t\n\t\/\/ Default parent port and ip\n\tint pport = 9559;\n\tstd::string pip = \"127.0.0.1\";\n\t\n\t\/\/ Need this for SOAP serialisation of floats to work\n\tsetlocale(LC_NUMERIC, \"C\");\n\n\t\/\/ Create a broker\n\tboost::shared_ptr broker;\n\ttry\n\t{\n\t\tbroker = AL::ALBroker::createBroker(\n\t\t\t\tbrokerName,\n\t\t\t\tbrokerIp,\n\t\t\t\tbrokerPort,\n\t\t\t\tpip,\n\t\t\t\tpport,\n\t\t\t\t0);\n\t}\n\t\/\/ Throw error and quit if a broker could not be created\n\tcatch(...)\n\t{\n\t\tstd::cerr << \"Failed to connect broker to: \"\n\t\t\t << pip\n\t\t\t << \":\"\n\t\t\t << pport\n\t\t\t << std::endl;\n\t\tAL::ALBrokerManager::getInstance()->killAllBroker();\n\t\tAL::ALBrokerManager::kill();\n\n\t\treturn 1;\n\t}\n\n\t\/\/ Add the broker to NAOqi\n\tAL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());\n\tAL::ALBrokerManager::getInstance()->addBroker(broker);\n\n\tCreateModule(movementLibName, movementModuleName, broker, false, true);\n\tCreateModule(bodyLibName, bodyModuleName, broker, false, true);\n\t\n\tAL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);\n\tAL::ALProxy movementToolsProxy(movementModuleName, pip, pport);\n\tAL::ALMotionProxy motion(pip, pport);\n\t\/\/__________________________________________________________________________________________\n\t\/\/__________________________________________________________________________________________\n\t\/\/END OF STUFF WE DONT UNDERSTAND, BREATHE NOW\n\t\n\t\/\/learning factor\n\tconst double alpha=0.5;\n\t\/\/discount factor\n\tconst double gamma=0.5;\n\t\n\t\/\/seed rng\n\tstd::srand(std::time(NULL));\n\t\n\tint action_forwards = FORWARD;\n\tint* p_action_forwards = &action_forwards;\n\tint action_backwards = BACKWARD;\n\tint* p_action_backwards = &action_backwards;\n\tint* chosen_action = &action_forwards;\n\t\n\t\/\/create a priority queue to copy to all the state space priority queues\n\tPriorityQueue initiator_queue(MAX);\n\tinitiator_queue.enqueueWithPriority(p_action_forwards,0);\n\tinitiator_queue.enqueueWithPriority(p_action_backwards,0);\n\t\n\t\/\/create encoder\n\tEncoder encoder();\n\tencoder.calibrate();\n\t\n\t\/\/create the state space\n\tStateSpace space(initiator_queue);\n\tspace.setAngle(100);\n\tspace.setVelocity(50);\n\t\n\t\/\/state objects\n\tState current_state(0,0,FORWARD);\n\tState old_state(0,0,FORWARD);\n\t\n\twhile(true)\n\t{\n\t\tcurrent_state.theta= M_PI * encoder.GetAngle()\/180;\n\t\tcurrent_state.theta_dot=(current_state.theta - old_state.theta)\/700; \/\/Needs actual time\n\t\tcurrent_state.robot_state=*chosen_action;\n\t\t\n\t\tupdateQ(space, chosen_action, old_state, current_state, alpha, gamma);\n\t\t\n\t\told_state=current_state;\n\t\t\n\t\tchosen_action=selectAction(space[current_state]);\n\t\t\n\t\t(*chosen_action)?movementToolsProxy.callVoid(\"swingForwards\"):movementToolsProxy.callVoid(\"swingBackwards\");\n\t}\n\t\n\treturn 1;\n}\n\ndouble temperature()\n{\n\treturn std::time(NULL);\n}\n\n\/\/function is fed with a priority queue of action-values \n\/\/generates Boltzmann distribution of these action-values\n\/\/and selects an action based on probabilities \nint * selectAction(PriorityQueue& a_queue)\n{\t\n\ttypedef PriorityQueue PQ;\n\ttypedef std::vector< std::pair > Vec_Pair;\n\ttypedef std::pair Pair;\n\t\n\tdouble sum= 0;\n\tint i = 0;\n\t\n\tint size = a_queue.getSize();\n\tVec_Pair action_vec(size);\n\t\n\t\/\/Calculate partition function by iterating over action-values\n\tfor(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)\n\t{\n\t\tsum += std::exp((iter->second)\/temperature());\n\t}\n\t\/\/Calculate boltzmann factors for action-values\n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t it->first = a_queue[i].first;\n\t it->second = std::exp(a_queue[i].second \/temperature()) \/ sum;\n\t ++i;\n\t}\n\t\n\t\/\/calculate cumulative probability distribution \n\tfor(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)\n\t{\n\t it1->second += it2->second;\n\t}\n\t\n\t\/\/generate RN between 0 and 1\n\tdouble rand_num = static_cast(rand()\/ (RAND_MAX));\n\t\n\t\/\/select action based on probability \n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t\t\/\/if RN falls within cumulative probability bin return the corresponding action\n\t\tif(rand_num < it->second)return &(it->first);\n\t}\n \t\n\treturn NULL; \/\/note that this line should never be reached\n}\n\nvoid updateQ(StateSpace & space, int * action, State & new_state, State & old_state, double alpha, double gamma)\n{\n \/\/oldQ value reference\n double oldQ = space[old_state].search(action).second;\n \n \/\/reward given to current state \n double R = new_state.getReward();\n \n \/\/optimal Q value for new state i.e. first element \n double maxQ = space[current_state].peekFront().second;\n \n \/\/new Q value determined by Q learning algorithm\n double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);\n \n \/\/ change priority of action to new Q value\n space[old_state].changePriority(action, newQ);\n}\n\nUpdate Main.cpp#include \n#include \n#include \n#include \n#include \n#include \"StateSpace.h\"\n#include \"PriorityQueue.h\"\n#include \"State.h\"\n#include \"encoder.h\"\n#include \"CreateModule.h\"\n\n\/**\n * @brief Gives a std::string representation of a primitive type\n * \n * @param x Primitive type such as int, double, long\n * @return std::string conversion of param x\n *\/\ntemplate std::string to_string(T x) {\n\treturn static_cast((std::ostringstream() << std::dec << x)).str();\n}\n\n\/\/function to calculate a temperature for the select action function as a function of time\ndouble temperature();\n\n\/\/function to select next action\nint * selectAction(PriorityQueue& a_queue);\n\n\/\/function to update a q value\nvoid updateQ(StateSpace & space, int * action, State & new_state, State & old_state, double alpha, double gamma);\n\nint main()\n{\t\n\t\/\/ STUFF WE DONT UNDERSTAND, AND DONT NEED TO\n\t\/\/__________________________________________________________________________________________\n\t\/\/__________________________________________________________________________________________\n\t\/\/ Libraries to load\n\tstd::string bodyLibName = \"bodyinfo\";\n\tstd::string movementLibName = \"movementtools\";\n\t\n\t\/\/ Name of camera module in library\n\tstd::string bodyModuleName = \"BodyInfo\";\n\tstd::string movementModuleName = \"MovementTools\";\n\n\t\/\/ Set broker name, ip and port, finding first available port from 54000\n\tconst std::string brokerName = \"MotionTimingBroker\";\n\tint brokerPort = qi::os::findAvailablePort(54000);\n\tconst std::string brokerIp = \"0.0.0.0\";\n\t\n\t\/\/ Default parent port and ip\n\tint pport = 9559;\n\tstd::string pip = \"127.0.0.1\";\n\t\n\t\/\/ Need this for SOAP serialisation of floats to work\n\tsetlocale(LC_NUMERIC, \"C\");\n\n\t\/\/ Create a broker\n\tboost::shared_ptr broker;\n\ttry\n\t{\n\t\tbroker = AL::ALBroker::createBroker(\n\t\t\t\tbrokerName,\n\t\t\t\tbrokerIp,\n\t\t\t\tbrokerPort,\n\t\t\t\tpip,\n\t\t\t\tpport,\n\t\t\t\t0);\n\t}\n\t\/\/ Throw error and quit if a broker could not be created\n\tcatch(...)\n\t{\n\t\tstd::cerr << \"Failed to connect broker to: \"\n\t\t\t << pip\n\t\t\t << \":\"\n\t\t\t << pport\n\t\t\t << std::endl;\n\t\tAL::ALBrokerManager::getInstance()->killAllBroker();\n\t\tAL::ALBrokerManager::kill();\n\n\t\treturn 1;\n\t}\n\n\t\/\/ Add the broker to NAOqi\n\tAL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());\n\tAL::ALBrokerManager::getInstance()->addBroker(broker);\n\n\tCreateModule(movementLibName, movementModuleName, broker, false, true);\n\tCreateModule(bodyLibName, bodyModuleName, broker, false, true);\n\t\n\tAL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);\n\tAL::ALProxy movementToolsProxy(movementModuleName, pip, pport);\n\tAL::ALMotionProxy motion(pip, pport);\n\t\/\/__________________________________________________________________________________________\n\t\/\/__________________________________________________________________________________________\n\t\/\/END OF STUFF WE DONT UNDERSTAND, BREATHE NOW\n\t\n\t\/\/learning factor\n\tconst double alpha=0.5;\n\t\/\/discount factor\n\tconst double gamma=0.5;\n\t\n\t\/\/seed rng\n\tstd::srand(std::time(NULL));\n\t\n\tint action_forwards = FORWARD;\n\tint* p_action_forwards = &action_forwards;\n\tint action_backwards = BACKWARD;\n\tint* p_action_backwards = &action_backwards;\n\tint* chosen_action = &action_forwards;\n\t\n\t\/\/create a priority queue to copy to all the state space priority queues\n\tPriorityQueue initiator_queue(MAX);\n\tinitiator_queue.enqueueWithPriority(p_action_forwards,0);\n\tinitiator_queue.enqueueWithPriority(p_action_backwards,0);\n\t\n\t\/\/create encoder\n\tEncoder encoder();\n\tencoder.calibrate();\n\t\n\t\/\/create the state space\n\tStateSpace space(initiator_queue);\n\tspace.setAngleBins(100);\n\tspace.setVelocityBins(50);\n\t\n\t\/\/state objects\n\tState current_state(0,0,FORWARD);\n\tState old_state(0,0,FORWARD);\n\t\n\twhile(true)\n\t{\n\t\tcurrent_state.theta= M_PI * encoder.GetAngle()\/180;\n\t\tcurrent_state.theta_dot=(current_state.theta - old_state.theta)\/700; \/\/Needs actual time\n\t\tcurrent_state.robot_state=*chosen_action;\n\t\t\n\t\tupdateQ(space, chosen_action, old_state, current_state, alpha, gamma);\n\t\t\n\t\told_state=current_state;\n\t\t\n\t\tchosen_action=selectAction(space[current_state]);\n\t\t\n\t\t(*chosen_action)?movementToolsProxy.callVoid(\"swingForwards\"):movementToolsProxy.callVoid(\"swingBackwards\");\n\t}\n\t\n\treturn 1;\n}\n\ndouble temperature()\n{\n\treturn std::time(NULL);\n}\n\n\/\/function is fed with a priority queue of action-values \n\/\/generates Boltzmann distribution of these action-values\n\/\/and selects an action based on probabilities \nint * selectAction(PriorityQueue& a_queue)\n{\t\n\ttypedef PriorityQueue PQ;\n\ttypedef std::vector< std::pair > Vec_Pair;\n\ttypedef std::pair Pair;\n\t\n\tdouble sum= 0;\n\tint i = 0;\n\t\n\tint size = a_queue.getSize();\n\tVec_Pair action_vec(size);\n\t\n\t\/\/Calculate partition function by iterating over action-values\n\tfor(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)\n\t{\n\t\tsum += std::exp((iter->second)\/temperature());\n\t}\n\t\/\/Calculate boltzmann factors for action-values\n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t it->first = a_queue[i].first;\n\t it->second = std::exp(a_queue[i].second \/temperature()) \/ sum;\n\t ++i;\n\t}\n\t\n\t\/\/calculate cumulative probability distribution \n\tfor(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)\n\t{\n\t it1->second += it2->second;\n\t}\n\t\n\t\/\/generate RN between 0 and 1\n\tdouble rand_num = static_cast(rand()\/ (RAND_MAX));\n\t\n\t\/\/select action based on probability \n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t\t\/\/if RN falls within cumulative probability bin return the corresponding action\n\t\tif(rand_num < it->second)return &(it->first);\n\t}\n \t\n\treturn NULL; \/\/note that this line should never be reached\n}\n\nvoid updateQ(StateSpace & space, int * action, State & new_state, State & old_state, double alpha, double gamma)\n{\n \/\/oldQ value reference\n double oldQ = space[old_state].search(action).second;\n \n \/\/reward given to current state \n double R = new_state.getReward();\n \n \/\/optimal Q value for new state i.e. first element \n double maxQ = space[current_state].peekFront().second;\n \n \/\/new Q value determined by Q learning algorithm\n double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);\n \n \/\/ change priority of action to new Q value\n space[old_state].changePriority(action, newQ);\n}\n\n<|endoftext|>"} {"text":"\/*\nUselessMine\n Copyright (C) 2014 Vladimir \"allejo\" Jimenez\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n*\/\n\n#include \n#include \n\n#include \"bzfsAPI.h\"\n#include \"bztoolkit\/bzToolkitAPI.h\"\n\n\/\/ Define plugin name\nconst std::string PLUGIN_NAME = \"Useless Mine\";\n\n\/\/ Define plugin version numbering\nconst int MAJOR = 1;\nconst int MINOR = 0;\nconst int REV = 0;\nconst int BUILD = 8;\n\nclass UselessMine : public bz_Plugin, public bz_CustomSlashCommandHandler\n{\npublic:\n virtual const char* Name ();\n virtual void Init (const char* config);\n virtual void Event (bz_EventData *eventData);\n virtual void Cleanup (void);\n\n virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);\n\n virtual int getMineCount ();\n virtual void initializeMessages (void),\n removeAllMines(int playerID),\n removeMine (int mineIndex),\n setMine (int owner, float pos[3], bz_eTeamType team);\n\n \/\/ The information each mine will contain\n struct Mine\n {\n int owner, victim; \/\/ The owner of the mine and the victim, respectively\n\n float x, y, z; \/\/ The coordinates of where the mine was placed\n\n bz_eTeamType team; \/\/ The team of the owner\n\n bool detonated; \/\/ Whether or not the mine has been detonated; to prepare it for removal from play\n\n Mine (int _owner, float _pos[3], bz_eTeamType _team) :\n owner(_owner),\n victim(-1),\n x(_pos[0]),\n y(_pos[1]),\n z(_pos[2]),\n team(_team),\n detonated(false)\n {}\n };\n\n std::vector activeMines; \/\/ A vector that will store all of the mines that are in play\n std::vector deathMessages; \/\/ A vector that will store all of the witty death messages\n\n double bzdb_SpawnSafetyTime, \/\/ The BZDB variable that will store the amount of seconds a player has before a mine is detonated\n playerSpawnTime[256]; \/\/ The time of a player's last spawn time used to calculate their safety from detonation\n};\n\nBZ_PLUGIN(UselessMine)\n\nconst char* UselessMine::Name (void)\n{\n static std::string pluginBuild = \"\";\n\n if (!pluginBuild.size())\n {\n std::ostringstream pluginBuildStream;\n\n pluginBuildStream << PLUGIN_NAME << \" \" << MAJOR << \".\" << MINOR << \".\" << REV << \" (\" << BUILD << \")\";\n pluginBuild = pluginBuildStream.str();\n }\n\n return pluginBuild.c_str();\n}\n\nvoid UselessMine::Init (const char* commandLine)\n{\n \/\/ Register our events with Register()\n Register(bz_eFlagGrabbedEvent);\n Register(bz_ePlayerDieEvent);\n Register(bz_ePlayerPartEvent);\n Register(bz_ePlayerSpawnEvent);\n Register(bz_ePlayerUpdateEvent);\n\n \/\/ Register our custom slash commands\n bz_registerCustomSlashCommand(\"mine\", this);\n\n \/\/ Initialize all of the witty death messages\n initializeMessages();\n\n \/\/ Set some custom BZDB variables\n bzdb_SpawnSafetyTime = bztk_registerCustomDoubleBZDB(\"_mineSafetyTime\", 5.0);\n}\n\nvoid UselessMine::Cleanup (void)\n{\n Flush(); \/\/ Clean up all the events\n\n \/\/ Clean up our custom slash commands\n bz_removeCustomSlashCommand(\"mine\");\n}\n\nvoid UselessMine::Event (bz_EventData *eventData)\n{\n switch (eventData->eventType)\n {\n case bz_eFlagGrabbedEvent: \/\/ This event is called each time a flag is grabbed by a player\n {\n bz_FlagGrabbedEventData_V1* flagGrabData = (bz_FlagGrabbedEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - The player that grabbed the flag\n \/\/ (int) flagID - The flag ID that was grabbed\n \/\/ (bz_ApiString) flagType - The flag abbreviation of the flag that was grabbed\n \/\/ (float[3]) pos - The position at which the flag was grabbed\n \/\/ (double) eventTime - This value is the local server time of the event.\n\n \/\/ If the user grabbed the Useless flag, let them know they can place a mine\n if (strcmp(flagGrabData->flagType, \"US\") == 0)\n {\n bz_sendTextMessage(BZ_SERVER, flagGrabData->playerID, \"You grabbed a Useless flag! Type \/mine at any time to set a useless mine!\");\n }\n }\n break;\n\n\n case bz_ePlayerDieEvent: \/\/ This event is called each time a tank is killed.\n {\n bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - ID of the player who was killed.\n \/\/ (bz_eTeamType) team - The team the killed player was on.\n \/\/ (int) killerID - The owner of the shot that killed the player, or BZ_SERVER for server side kills\n \/\/ (bz_eTeamType) killerTeam - The team the owner of the shot was on.\n \/\/ (bz_ApiString) flagKilledWith - The flag name the owner of the shot had when the shot was fired.\n \/\/ (int) shotID - The shot ID that killed the player, if the player was not killed by a shot, the id will be -1.\n \/\/ (bz_PlayerUpdateState) state - The state record for the killed player at the time of the event\n \/\/ (double) eventTime - Time of the event on the server.\n\n int playerID = dieData->playerID;\n\n \/\/ Loop through all the mines in play\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Create a local variable for easy access\n Mine &detonatedMine = activeMines.at(i);\n\n \/\/ Check if the mine has already been detonated\n if (detonatedMine.detonated)\n {\n \/\/ Check if the victim killed is the player who just died\n if (detonatedMine.victim == playerID)\n {\n \/\/ Check if the player who just died was killed by the server\n if (dieData->killerID == 253)\n {\n \/\/ The random number used to fetch a random taunting death message\n int randomNumber = rand() % deathMessages.size();\n\n \/\/ Get the callsigns of the players\n const char* owner = bz_getPlayerCallsign(detonatedMine.owner);\n const char* victim = bz_getPlayerCallsign(detonatedMine.victim);\n\n \/\/ Attribute the kill to the mine owner\n dieData->killerID = detonatedMine.owner;\n\n \/\/ This mine has been detonated and we're done with the information that we need\n removeMine(i);\n\n bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, deathMessages.at(randomNumber).c_str(), owner, victim);\n break;\n }\n }\n }\n }\n }\n break;\n\n case bz_ePlayerPartEvent: \/\/ This event is called each time a player leaves a game\n {\n bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - The player ID that is leaving\n \/\/ (bz_BasePlayerRecord*) record - The player record for the leaving player\n \/\/ (bz_ApiString) reason - The reason for leaving, such as a kick or a ban\n \/\/ (double) eventTime - Time of event.\n\n int playerID = partData->playerID;\n\n removeAllMines(playerID);\n }\n break;\n\n case bz_ePlayerSpawnEvent: \/\/ This event is called each time a playing tank is being spawned into the world\n {\n bz_PlayerSpawnEventData_V1* spawnData = (bz_PlayerSpawnEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - ID of the player who was added to the world.\n \/\/ (bz_eTeamType) team - The team the player is a member of.\n \/\/ (bz_PlayerUpdateState) state - The state record for the spawning player\n \/\/ (double) eventTime - Time local server time for the event.\n\n int playerID = spawnData->playerID;\n\n \/\/ Save the time the player spawned last\n playerSpawnTime[playerID] = bz_getCurrentTime();\n }\n break;\n\n case bz_ePlayerUpdateEvent: \/\/ This event is called each time a player sends an update to the server\n {\n bz_PlayerUpdateEventData_V1* updateData = (bz_PlayerUpdateEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - ID of the player that sent the update\n \/\/ (float[3]) pos - The player's current position\n \/\/ (float[3]) velocity - The player's current velocity\n \/\/ (float) azimuth - The direction the player is facing\n \/\/ (float) angvel - The player's angular velocity\n \/\/ (int) phydrv - The physics driver the player is on\n \/\/ (double) eventTime - The current server time\n\n int playerID = updateData->playerID;\n\n \/\/ Loop through all of the players\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Make an easy access mine\n Mine ¤tMine = activeMines.at(i);\n\n \/\/ If the mine owner is not the player triggering the mine (so no self kills) and the player is a rogue or does is an enemy team relative to the mine owner\n if (currentMine.owner != playerID && (bz_getPlayerTeam(playerID) == eRogueTeam || bz_getPlayerTeam(playerID) != currentMine.team))\n {\n \/\/ Make easy to access variables\n float playerPos[3] = {updateData->state.pos[0], updateData->state.pos[1], updateData->state.pos[2]};\n double shockRange = bz_getBZDBDouble(\"_shockOutRadius\") * 0.75;\n\n \/\/ Check if the player is in the detonation range\n if ((playerPos[0] > currentMine.x - shockRange && playerPos[0] < currentMine.x + shockRange) &&\n (playerPos[1] > currentMine.y - shockRange && playerPos[1] < currentMine.y + shockRange) &&\n (playerPos[2] > currentMine.z - shockRange && playerPos[2] < currentMine.z + shockRange) &&\n playerSpawnTime[playerID] + bzdb_SpawnSafetyTime <= bz_getCurrentTime() && !currentMine.detonated)\n {\n \/\/ Check that the mine owner exists and is not an observer\n if (bztk_isValidPlayerID(currentMine.owner) && bz_getPlayerTeam(currentMine.owner) != eObservers)\n {\n \/\/ Get the current mine position\n float minePos[3] = {currentMine.x, currentMine.y, currentMine.z};\n\n \/\/ Save who detonated the mine and mark it as detonated\n currentMine.victim = playerID;\n currentMine.detonated = true;\n\n \/\/ BOOM!\n bz_fireWorldWep(\"SW\", 2.0, BZ_SERVER, minePos, 0, 0, 0, currentMine.team);\n }\n \/\/ Just in case the player doesn't exist or is an observer, then remove the mine because it shouldn't be there\n else\n {\n removeMine(i);\n }\n\n break;\n }\n }\n }\n }\n break;\n\n default: break;\n }\n}\n\nbool UselessMine::SlashCommand(int playerID, bz_ApiString command, bz_ApiString \/*message*\/, bz_APIStringList *params)\n{\n if (command == \"mine\")\n {\n std::shared_ptr playerRecord(bz_getPlayerByIndex(playerID));\n\n \/\/ If the player is not an observer, they let them proceed to the next check\n if (playerRecord->team != eObservers)\n {\n \/\/ Check if the player has the Useless flag\n if (playerRecord->currentFlag == \"USeless (+US)\")\n {\n \/\/ Store their current position\n float currentPosition[3] = {playerRecord->lastKnownState.pos[0], playerRecord->lastKnownState.pos[1], playerRecord->lastKnownState.pos[2]};\n\n setMine(playerID, currentPosition, playerRecord->team);\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"You can't place a mine without the Useless flag!\");\n }\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"Silly observer, you can't place a mine.\");\n }\n\n return true;\n }\n}\n\n\/\/ A shortcut to get the amount of mines that are in play\nint UselessMine::getMineCount()\n{\n return activeMines.size();\n}\n\n\/\/ In order to keep things organized, this function is where you can specify all the witty death messages you want to be available\nvoid UselessMine::initializeMessages()\n{\n deathMessages.push_back(\"%s was killed by %s's mine.\");\n deathMessages.push_back(\"%s was owned by %s's mine.\");\n deathMessages.push_back(\"%s was obliterated by %s's mine.\");\n deathMessages.push_back(\"%s's tank disintegrated from %s's mine.\");\n deathMessages.push_back(\"%s was permanently blinded by the bright light from %s's mine.\");\n deathMessages.push_back(\"%s was sent shooting into the stars by %s's mine.\");\n deathMessages.push_back(\"%s was never heard from again thanks to %s's mine.\");\n deathMessages.push_back(\"We salute %s for taking an atrocious hit from %s's mine.\");\n deathMessages.push_back(\"%s's mine left %s's tank parts scattered all over.\");\n deathMessages.push_back(\"%s thought %s's mine was a shiny brand new car.\");\n deathMessages.push_back(\"%s was bombarded by many concussive attacks from %s's mine.\");\n deathMessages.push_back(\"%s was ignited by %s's mine.\");\n deathMessages.push_back(\"%s's mine bursted %s's tank to bite-size flaming pieces.\");\n deathMessages.push_back(\"%s took a nosedive into %s's mine.\");\n deathMessages.push_back(\"%s fell face first into %s's mine.\");\n deathMessages.push_back(\"I knew %s would be clumsy enough to run into %s's mine.\");\n deathMessages.push_back(\"%s killed %s with a mine. No surprise there.\");\n deathMessages.push_back(\"DID YOU SEE THAT? %s did total carnage to %s's tank with that one little mine.\");\n deathMessages.push_back(\"%s purposely ran into %s's mine.\");\n deathMessages.push_back(\"I ascertain that %s has been ruptured by a mine created from the heavens with the name dubbed %s.\");\n}\n\nvoid UselessMine::removeAllMines(int playerID)\n{\n \/\/ Go through all of the mines\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Quick access mine\n Mine ¤tMine = activeMines.at(i);\n\n \/\/ If the mine belongs to the player, remove it\n if (currentMine.owner == playerID)\n {\n removeMine(i);\n }\n }\n}\n\n\/\/ A shortcut to remove a mine from play\nvoid UselessMine::removeMine(int mineIndex)\n{\n activeMines.erase(activeMines.begin() + mineIndex);\n}\n\n\/\/ A shortcut to set a mine\nvoid UselessMine::setMine(int owner, float pos[3], bz_eTeamType team)\n{\n \/\/ Remove their flag because it's going to be a US flag\n bz_removePlayerFlag(owner);\n\n \/\/ Push the new mine\n Mine newMine(owner, pos, team);\n activeMines.push_back(newMine);\n}Silly me. Fix order of mine owner and victim in death messages\/*\nUselessMine\n Copyright (C) 2014 Vladimir \"allejo\" Jimenez\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n*\/\n\n#include \n#include \n\n#include \"bzfsAPI.h\"\n#include \"bztoolkit\/bzToolkitAPI.h\"\n\n\/\/ Define plugin name\nconst std::string PLUGIN_NAME = \"Useless Mine\";\n\n\/\/ Define plugin version numbering\nconst int MAJOR = 1;\nconst int MINOR = 0;\nconst int REV = 0;\nconst int BUILD = 8;\n\nclass UselessMine : public bz_Plugin, public bz_CustomSlashCommandHandler\n{\npublic:\n virtual const char* Name ();\n virtual void Init (const char* config);\n virtual void Event (bz_EventData *eventData);\n virtual void Cleanup (void);\n\n virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);\n\n virtual int getMineCount ();\n virtual void initializeMessages (void),\n removeAllMines(int playerID),\n removeMine (int mineIndex),\n setMine (int owner, float pos[3], bz_eTeamType team);\n\n \/\/ The information each mine will contain\n struct Mine\n {\n int owner, victim; \/\/ The owner of the mine and the victim, respectively\n\n float x, y, z; \/\/ The coordinates of where the mine was placed\n\n bz_eTeamType team; \/\/ The team of the owner\n\n bool detonated; \/\/ Whether or not the mine has been detonated; to prepare it for removal from play\n\n Mine (int _owner, float _pos[3], bz_eTeamType _team) :\n owner(_owner),\n victim(-1),\n x(_pos[0]),\n y(_pos[1]),\n z(_pos[2]),\n team(_team),\n detonated(false)\n {}\n };\n\n std::vector activeMines; \/\/ A vector that will store all of the mines that are in play\n std::vector deathMessages; \/\/ A vector that will store all of the witty death messages\n\n double bzdb_SpawnSafetyTime, \/\/ The BZDB variable that will store the amount of seconds a player has before a mine is detonated\n playerSpawnTime[256]; \/\/ The time of a player's last spawn time used to calculate their safety from detonation\n};\n\nBZ_PLUGIN(UselessMine)\n\nconst char* UselessMine::Name (void)\n{\n static std::string pluginBuild = \"\";\n\n if (!pluginBuild.size())\n {\n std::ostringstream pluginBuildStream;\n\n pluginBuildStream << PLUGIN_NAME << \" \" << MAJOR << \".\" << MINOR << \".\" << REV << \" (\" << BUILD << \")\";\n pluginBuild = pluginBuildStream.str();\n }\n\n return pluginBuild.c_str();\n}\n\nvoid UselessMine::Init (const char* commandLine)\n{\n \/\/ Register our events with Register()\n Register(bz_eFlagGrabbedEvent);\n Register(bz_ePlayerDieEvent);\n Register(bz_ePlayerPartEvent);\n Register(bz_ePlayerSpawnEvent);\n Register(bz_ePlayerUpdateEvent);\n\n \/\/ Register our custom slash commands\n bz_registerCustomSlashCommand(\"mine\", this);\n\n \/\/ Initialize all of the witty death messages\n initializeMessages();\n\n \/\/ Set some custom BZDB variables\n bzdb_SpawnSafetyTime = bztk_registerCustomDoubleBZDB(\"_mineSafetyTime\", 5.0);\n}\n\nvoid UselessMine::Cleanup (void)\n{\n Flush(); \/\/ Clean up all the events\n\n \/\/ Clean up our custom slash commands\n bz_removeCustomSlashCommand(\"mine\");\n}\n\nvoid UselessMine::Event (bz_EventData *eventData)\n{\n switch (eventData->eventType)\n {\n case bz_eFlagGrabbedEvent: \/\/ This event is called each time a flag is grabbed by a player\n {\n bz_FlagGrabbedEventData_V1* flagGrabData = (bz_FlagGrabbedEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - The player that grabbed the flag\n \/\/ (int) flagID - The flag ID that was grabbed\n \/\/ (bz_ApiString) flagType - The flag abbreviation of the flag that was grabbed\n \/\/ (float[3]) pos - The position at which the flag was grabbed\n \/\/ (double) eventTime - This value is the local server time of the event.\n\n \/\/ If the user grabbed the Useless flag, let them know they can place a mine\n if (strcmp(flagGrabData->flagType, \"US\") == 0)\n {\n bz_sendTextMessage(BZ_SERVER, flagGrabData->playerID, \"You grabbed a Useless flag! Type \/mine at any time to set a useless mine!\");\n }\n }\n break;\n\n\n case bz_ePlayerDieEvent: \/\/ This event is called each time a tank is killed.\n {\n bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - ID of the player who was killed.\n \/\/ (bz_eTeamType) team - The team the killed player was on.\n \/\/ (int) killerID - The owner of the shot that killed the player, or BZ_SERVER for server side kills\n \/\/ (bz_eTeamType) killerTeam - The team the owner of the shot was on.\n \/\/ (bz_ApiString) flagKilledWith - The flag name the owner of the shot had when the shot was fired.\n \/\/ (int) shotID - The shot ID that killed the player, if the player was not killed by a shot, the id will be -1.\n \/\/ (bz_PlayerUpdateState) state - The state record for the killed player at the time of the event\n \/\/ (double) eventTime - Time of the event on the server.\n\n int playerID = dieData->playerID;\n\n \/\/ Loop through all the mines in play\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Create a local variable for easy access\n Mine &detonatedMine = activeMines.at(i);\n\n \/\/ Check if the mine has already been detonated\n if (detonatedMine.detonated)\n {\n \/\/ Check if the victim killed is the player who just died\n if (detonatedMine.victim == playerID)\n {\n \/\/ Check if the player who just died was killed by the server\n if (dieData->killerID == 253)\n {\n \/\/ The random number used to fetch a random taunting death message\n int randomNumber = rand() % deathMessages.size();\n\n \/\/ Get the callsigns of the players\n const char* owner = bz_getPlayerCallsign(detonatedMine.owner);\n const char* victim = bz_getPlayerCallsign(detonatedMine.victim);\n\n \/\/ Attribute the kill to the mine owner\n dieData->killerID = detonatedMine.owner;\n\n \/\/ This mine has been detonated and we're done with the information that we need\n removeMine(i);\n\n bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, deathMessages.at(randomNumber).c_str(), victim, owner);\n break;\n }\n }\n }\n }\n }\n break;\n\n case bz_ePlayerPartEvent: \/\/ This event is called each time a player leaves a game\n {\n bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - The player ID that is leaving\n \/\/ (bz_BasePlayerRecord*) record - The player record for the leaving player\n \/\/ (bz_ApiString) reason - The reason for leaving, such as a kick or a ban\n \/\/ (double) eventTime - Time of event.\n\n int playerID = partData->playerID;\n\n removeAllMines(playerID);\n }\n break;\n\n case bz_ePlayerSpawnEvent: \/\/ This event is called each time a playing tank is being spawned into the world\n {\n bz_PlayerSpawnEventData_V1* spawnData = (bz_PlayerSpawnEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - ID of the player who was added to the world.\n \/\/ (bz_eTeamType) team - The team the player is a member of.\n \/\/ (bz_PlayerUpdateState) state - The state record for the spawning player\n \/\/ (double) eventTime - Time local server time for the event.\n\n int playerID = spawnData->playerID;\n\n \/\/ Save the time the player spawned last\n playerSpawnTime[playerID] = bz_getCurrentTime();\n }\n break;\n\n case bz_ePlayerUpdateEvent: \/\/ This event is called each time a player sends an update to the server\n {\n bz_PlayerUpdateEventData_V1* updateData = (bz_PlayerUpdateEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - ID of the player that sent the update\n \/\/ (float[3]) pos - The player's current position\n \/\/ (float[3]) velocity - The player's current velocity\n \/\/ (float) azimuth - The direction the player is facing\n \/\/ (float) angvel - The player's angular velocity\n \/\/ (int) phydrv - The physics driver the player is on\n \/\/ (double) eventTime - The current server time\n\n int playerID = updateData->playerID;\n\n \/\/ Loop through all of the players\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Make an easy access mine\n Mine ¤tMine = activeMines.at(i);\n\n \/\/ If the mine owner is not the player triggering the mine (so no self kills) and the player is a rogue or does is an enemy team relative to the mine owner\n if (currentMine.owner != playerID && (bz_getPlayerTeam(playerID) == eRogueTeam || bz_getPlayerTeam(playerID) != currentMine.team))\n {\n \/\/ Make easy to access variables\n float playerPos[3] = {updateData->state.pos[0], updateData->state.pos[1], updateData->state.pos[2]};\n double shockRange = bz_getBZDBDouble(\"_shockOutRadius\") * 0.75;\n\n \/\/ Check if the player is in the detonation range\n if ((playerPos[0] > currentMine.x - shockRange && playerPos[0] < currentMine.x + shockRange) &&\n (playerPos[1] > currentMine.y - shockRange && playerPos[1] < currentMine.y + shockRange) &&\n (playerPos[2] > currentMine.z - shockRange && playerPos[2] < currentMine.z + shockRange) &&\n playerSpawnTime[playerID] + bzdb_SpawnSafetyTime <= bz_getCurrentTime() && !currentMine.detonated)\n {\n \/\/ Check that the mine owner exists and is not an observer\n if (bztk_isValidPlayerID(currentMine.owner) && bz_getPlayerTeam(currentMine.owner) != eObservers)\n {\n \/\/ Get the current mine position\n float minePos[3] = {currentMine.x, currentMine.y, currentMine.z};\n\n \/\/ Save who detonated the mine and mark it as detonated\n currentMine.victim = playerID;\n currentMine.detonated = true;\n\n \/\/ BOOM!\n bz_fireWorldWep(\"SW\", 2.0, BZ_SERVER, minePos, 0, 0, 0, currentMine.team);\n }\n \/\/ Just in case the player doesn't exist or is an observer, then remove the mine because it shouldn't be there\n else\n {\n removeMine(i);\n }\n\n break;\n }\n }\n }\n }\n break;\n\n default: break;\n }\n}\n\nbool UselessMine::SlashCommand(int playerID, bz_ApiString command, bz_ApiString \/*message*\/, bz_APIStringList *params)\n{\n if (command == \"mine\")\n {\n std::shared_ptr playerRecord(bz_getPlayerByIndex(playerID));\n\n \/\/ If the player is not an observer, they let them proceed to the next check\n if (playerRecord->team != eObservers)\n {\n \/\/ Check if the player has the Useless flag\n if (playerRecord->currentFlag == \"USeless (+US)\")\n {\n \/\/ Store their current position\n float currentPosition[3] = {playerRecord->lastKnownState.pos[0], playerRecord->lastKnownState.pos[1], playerRecord->lastKnownState.pos[2]};\n\n setMine(playerID, currentPosition, playerRecord->team);\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"You can't place a mine without the Useless flag!\");\n }\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"Silly observer, you can't place a mine.\");\n }\n\n return true;\n }\n}\n\n\/\/ A shortcut to get the amount of mines that are in play\nint UselessMine::getMineCount()\n{\n return activeMines.size();\n}\n\n\/\/ In order to keep things organized, this function is where you can specify all the witty death messages you want to be available\nvoid UselessMine::initializeMessages()\n{\n deathMessages.push_back(\"%s was killed by %s's mine.\");\n deathMessages.push_back(\"%s was owned by %s's mine.\");\n deathMessages.push_back(\"%s was obliterated by %s's mine.\");\n deathMessages.push_back(\"%s's tank disintegrated from %s's mine.\");\n deathMessages.push_back(\"%s was permanently blinded by the bright light from %s's mine.\");\n deathMessages.push_back(\"%s was sent shooting into the stars by %s's mine.\");\n deathMessages.push_back(\"%s was never heard from again thanks to %s's mine.\");\n deathMessages.push_back(\"We salute %s for taking an atrocious hit from %s's mine.\");\n deathMessages.push_back(\"%s's mine left %s's tank parts scattered all over.\");\n deathMessages.push_back(\"%s thought %s's mine was a shiny brand new car.\");\n deathMessages.push_back(\"%s was bombarded by many concussive attacks from %s's mine.\");\n deathMessages.push_back(\"%s was ignited by %s's mine.\");\n deathMessages.push_back(\"%s's mine bursted %s's tank to bite-size flaming pieces.\");\n deathMessages.push_back(\"%s took a nosedive into %s's mine.\");\n deathMessages.push_back(\"%s fell face first into %s's mine.\");\n deathMessages.push_back(\"I knew %s would be clumsy enough to run into %s's mine.\");\n deathMessages.push_back(\"%s killed %s with a mine. No surprise there.\");\n deathMessages.push_back(\"DID YOU SEE THAT? %s did total carnage to %s's tank with that one little mine.\");\n deathMessages.push_back(\"%s purposely ran into %s's mine.\");\n deathMessages.push_back(\"I ascertain that %s has been ruptured by a mine created from the heavens with the name dubbed %s.\");\n}\n\nvoid UselessMine::removeAllMines(int playerID)\n{\n \/\/ Go through all of the mines\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Quick access mine\n Mine ¤tMine = activeMines.at(i);\n\n \/\/ If the mine belongs to the player, remove it\n if (currentMine.owner == playerID)\n {\n removeMine(i);\n }\n }\n}\n\n\/\/ A shortcut to remove a mine from play\nvoid UselessMine::removeMine(int mineIndex)\n{\n activeMines.erase(activeMines.begin() + mineIndex);\n}\n\n\/\/ A shortcut to set a mine\nvoid UselessMine::setMine(int owner, float pos[3], bz_eTeamType team)\n{\n \/\/ Remove their flag because it's going to be a US flag\n bz_removePlayerFlag(owner);\n\n \/\/ Push the new mine\n Mine newMine(owner, pos, team);\n activeMines.push_back(newMine);\n}<|endoftext|>"} {"text":"\/\/\n\/\/ AliEveHLTZMQeventManager\n\/\/\n\/\/ blame: Mikolaj Krzewicki, mikolaj.krzewicki@cern.ch\n\/\/\n\/\/\n\n#include \"AliEveHLTZMQeventManager.h\"\n\n#include \"AliEveConfigManager.h\"\n#include \"AliCDBManager.h\"\n#include \"AliGRPPreprocessor.h\"\n#include \n#include \n#include \n\n#include \"AliHLTComponent.h\"\n#include \"AliHLTMessage.h\"\n\n#include \"AliOnlineReconstructionUtil.h\"\n\n#ifdef ZMQ\n#include \"zmq.h\"\n#endif\n\n\nusing namespace std;\n\nAliEveHLTZMQeventManager::AliEveHLTZMQeventManager(Int_t ev, bool storageManager) :\n AliEveEventManager(\"HLT\",ev,false),\n fEventListenerThreadHLT(0),\n fCurrentRun(-1),\n fZMQContext(NULL),\n fZMQeventQueue(NULL),\n fHLTPublisherAddress(\"tcp:\/\/localhost:60201\")\n{\n#ifdef ZMQ\n fIsOpen=kTRUE;\n \/\/get the address of the HLT proxy from the environment\n if (gSystem->Getenv(\"HLT_ZMQ_proxy\")) \n fHLTPublisherAddress=gSystem->Getenv(\"HLT_ZMQ_proxy\");\n \/\/single ZMQ context for inter thread comm. etc.\n fZMQContext = zmq_ctx_new();\n \/\/single ZMQ socket for gathering the events form various listening threads\n \/\/must be bound before threads can connect\n fZMQeventQueue = zmq_socket(fZMQContext, ZMQ_PULL);\n zmq_bind(fZMQeventQueue, \"inproc:\/\/fCurrentEvent\");\n\n cout<<\"ZMQ FOUND. Starting subscriber threads.\"<Run();\n#endif\n \n AliEveEventManager::SetMaster(this);\n}\n\nAliEveHLTZMQeventManager::~AliEveHLTZMQeventManager()\n{\n#ifdef ZMQ\n if (fZMQeventQueue)\n {\n int lingerValue = 0;\n int rc = zmq_setsockopt(fZMQeventQueue, ZMQ_LINGER, &lingerValue, sizeof(int));\n if (rc<0) printf(\"error setting linger on fZMQeventQueue\\n\");\n rc = zmq_close(fZMQeventQueue);\n if (rc<0) printf(\"error closing socket fZMQeventQueue\\n\");\n }\n\n printf(\"trying to destroy fZMQContext\\n\");\n if (fZMQContext) zmq_ctx_destroy(fZMQContext);\n printf(\"destroyed fZMQContext\\n\");\n#endif\n\n if(fEventListenerThreadHLT)\n {\n fEventListenerThreadHLT->Join();\n fEventListenerThreadHLT->Kill();\n delete fEventListenerThreadHLT;\n cout<<\"HLT listener thread killed and deleted\"<SetRun(runNo);\n }\n}\n\nvoid AliEveHLTZMQeventManager::GotoEvent(Int_t \/*event*\/)\n{\n static const TEveException kEH(\"AliEveEventManager::GotoEvent \");\n \n if (fAutoLoadTimerRunning){throw (kEH + \"Event auto-load timer is running.\");}\n \n NextEvent();\n gEve->Redraw3D(kFALSE, kTRUE); \/\/ Enforce drop of all logicals.\n \n return;\n \n}\n\nvoid AliEveHLTZMQeventManager::NextEvent()\n{\n static const TEveException kEH(\"AliEveEventManager::NextEvent \");\n \/\/read event from queue\n if (fAutoLoadTimerRunning){throw (kEH + \"Event auto-load timer is running.\");}\n\n#ifdef ZMQ\n \/\/init some stuff\n int rc = 0;\n AliESDEvent* esdObject = NULL;\n char topic[kAliHLTComponentDataTypeTopicSize+1]; memset(topic, 0, sizeof(topic));\n memset(topic, 0, kAliHLTComponentDataTypeTopicSize);\n zmq_msg_t message;\n rc = zmq_msg_init(&message);\n int64_t more = 0;\n size_t more_size = sizeof(more);\n\n \/\/try to receive a new topic+message from the queue\n int topicSize = zmq_recv(fZMQeventQueue, &topic, kAliHLTComponentDataTypeTopicSize, ZMQ_DONTWAIT);\n int errnoTopic = errno;\n rc = zmq_getsockopt(fZMQeventQueue, ZMQ_RCVMORE, &more, &more_size);\n if (more) rc = zmq_msg_recv(&message, fZMQeventQueue, ZMQ_DONTWAIT);\n\n \/\/decode the message into an AliESDEvent,\n \/\/for HLT messages AliHLTMessage needs to be used\n if( topicSize > 0 \/*&& errnoTopic != EAGAIN*\/ && zmq_msg_size(&message) > 0 )\n {\n if (Topicncmp(topic, \"ALIESDV0HLT\", topicSize, 11))\n {\n printf(\"trying to decode %s with AliHLTMessage\\n\", topic);\n AliHLTMessage msg(zmq_msg_data(&message), zmq_msg_size(&message));\n TClass* objclass = msg.GetClass();\n esdObject = static_cast(msg.ReadObject(AliESDEvent::Class()));\n }\n else if (Topicncmp(topic, \"ALIESDV0POR\", topicSize, 11))\n {\n printf(\"trying to decode %s with TBufferFile\\n\", topic);\n TBufferFile *mess = new TBufferFile(TBuffer::kRead,\n zmq_msg_size(&message)+sizeof(UInt_t),\n zmq_msg_data(&message));\n mess->InitMap();\n mess->ReadClass();\/\/ get first the class stored in message\n mess->SetBufferOffset(sizeof(UInt_t) + sizeof(kMESS_OBJECT));\n mess->ResetMap();\n esdObject = (AliESDEvent*)(mess->ReadObjectAny(AliESDEvent::Class()));\n } \n else\n {\n printf(\"Don't know what to do with %s\\n\",topic);\n }\n }\n if (esdObject) \n {\n printf(\"setting new event\\n\");\n esdObject->GetStdContent();\n DestroyElements();\n int runNumber = esdObject->GetRunNumber();\n InitOCDB(runNumber);\n\n \/\/replace the ESD\n delete fESD;\n fESD = esdObject;\n fHasEvent=kTRUE;\n \n AfterNewEventLoaded();\n }\n else\n {\n cout<<\"No new event is avaliable.\"<ProcessEvents();\n}\n\ncleanup includes\/\/\n\/\/ AliEveHLTZMQeventManager\n\/\/\n\/\/ blame: Mikolaj Krzewicki, mikolaj.krzewicki@cern.ch\n\/\/\n\/\/\n\n#include \"AliEveHLTZMQeventManager.h\"\n\n#include \"AliEveConfigManager.h\"\n#include \"AliCDBManager.h\"\n#include \"AliGRPPreprocessor.h\"\n#include \n#include \n#include \n\n#include \"AliHLTComponent.h\"\n#include \"AliHLTMessage.h\"\n\n#ifdef ZMQ\n#include \"zmq.h\"\n#endif\n\n\nusing namespace std;\n\nAliEveHLTZMQeventManager::AliEveHLTZMQeventManager(Int_t ev, bool storageManager) :\n AliEveEventManager(\"HLT\",ev,false),\n fEventListenerThreadHLT(0),\n fCurrentRun(-1),\n fZMQContext(NULL),\n fZMQeventQueue(NULL),\n fHLTPublisherAddress(\"tcp:\/\/localhost:60201\")\n{\n#ifdef ZMQ\n fIsOpen=kTRUE;\n \/\/get the address of the HLT proxy from the environment\n if (gSystem->Getenv(\"HLT_ZMQ_proxy\")) \n fHLTPublisherAddress=gSystem->Getenv(\"HLT_ZMQ_proxy\");\n \/\/single ZMQ context for inter thread comm. etc.\n fZMQContext = zmq_ctx_new();\n \/\/single ZMQ socket for gathering the events form various listening threads\n \/\/must be bound before threads can connect\n fZMQeventQueue = zmq_socket(fZMQContext, ZMQ_PULL);\n zmq_bind(fZMQeventQueue, \"inproc:\/\/fCurrentEvent\");\n\n cout<<\"ZMQ FOUND. Starting subscriber threads.\"<Run();\n#endif\n \n AliEveEventManager::SetMaster(this);\n}\n\nAliEveHLTZMQeventManager::~AliEveHLTZMQeventManager()\n{\n#ifdef ZMQ\n if (fZMQeventQueue)\n {\n int lingerValue = 0;\n int rc = zmq_setsockopt(fZMQeventQueue, ZMQ_LINGER, &lingerValue, sizeof(int));\n if (rc<0) printf(\"error setting linger on fZMQeventQueue\\n\");\n rc = zmq_close(fZMQeventQueue);\n if (rc<0) printf(\"error closing socket fZMQeventQueue\\n\");\n }\n\n printf(\"trying to destroy fZMQContext\\n\");\n if (fZMQContext) zmq_ctx_destroy(fZMQContext);\n printf(\"destroyed fZMQContext\\n\");\n#endif\n\n if(fEventListenerThreadHLT)\n {\n fEventListenerThreadHLT->Join();\n fEventListenerThreadHLT->Kill();\n delete fEventListenerThreadHLT;\n cout<<\"HLT listener thread killed and deleted\"<SetRun(runNo);\n }\n}\n\nvoid AliEveHLTZMQeventManager::GotoEvent(Int_t \/*event*\/)\n{\n static const TEveException kEH(\"AliEveEventManager::GotoEvent \");\n \n if (fAutoLoadTimerRunning){throw (kEH + \"Event auto-load timer is running.\");}\n \n NextEvent();\n gEve->Redraw3D(kFALSE, kTRUE); \/\/ Enforce drop of all logicals.\n \n return;\n \n}\n\nvoid AliEveHLTZMQeventManager::NextEvent()\n{\n static const TEveException kEH(\"AliEveEventManager::NextEvent \");\n \/\/read event from queue\n if (fAutoLoadTimerRunning){throw (kEH + \"Event auto-load timer is running.\");}\n\n#ifdef ZMQ\n \/\/init some stuff\n int rc = 0;\n AliESDEvent* esdObject = NULL;\n char topic[kAliHLTComponentDataTypeTopicSize+1]; memset(topic, 0, sizeof(topic));\n memset(topic, 0, kAliHLTComponentDataTypeTopicSize);\n zmq_msg_t message;\n rc = zmq_msg_init(&message);\n int64_t more = 0;\n size_t more_size = sizeof(more);\n\n \/\/try to receive a new topic+message from the queue\n int topicSize = zmq_recv(fZMQeventQueue, &topic, kAliHLTComponentDataTypeTopicSize, ZMQ_DONTWAIT);\n int errnoTopic = errno;\n rc = zmq_getsockopt(fZMQeventQueue, ZMQ_RCVMORE, &more, &more_size);\n if (more) rc = zmq_msg_recv(&message, fZMQeventQueue, ZMQ_DONTWAIT);\n\n \/\/decode the message into an AliESDEvent,\n \/\/for HLT messages AliHLTMessage needs to be used\n if( topicSize > 0 \/*&& errnoTopic != EAGAIN*\/ && zmq_msg_size(&message) > 0 )\n {\n if (Topicncmp(topic, \"ALIESDV0HLT\", topicSize, 11))\n {\n printf(\"trying to decode %s with AliHLTMessage\\n\", topic);\n AliHLTMessage msg(zmq_msg_data(&message), zmq_msg_size(&message));\n TClass* objclass = msg.GetClass();\n esdObject = static_cast(msg.ReadObject(AliESDEvent::Class()));\n }\n else if (Topicncmp(topic, \"ALIESDV0POR\", topicSize, 11))\n {\n printf(\"trying to decode %s with TBufferFile\\n\", topic);\n TBufferFile *mess = new TBufferFile(TBuffer::kRead,\n zmq_msg_size(&message)+sizeof(UInt_t),\n zmq_msg_data(&message));\n mess->InitMap();\n mess->ReadClass();\/\/ get first the class stored in message\n mess->SetBufferOffset(sizeof(UInt_t) + sizeof(kMESS_OBJECT));\n mess->ResetMap();\n esdObject = (AliESDEvent*)(mess->ReadObjectAny(AliESDEvent::Class()));\n } \n else\n {\n printf(\"Don't know what to do with %s\\n\",topic);\n }\n }\n if (esdObject) \n {\n printf(\"setting new event\\n\");\n esdObject->GetStdContent();\n DestroyElements();\n int runNumber = esdObject->GetRunNumber();\n InitOCDB(runNumber);\n\n \/\/replace the ESD\n delete fESD;\n fESD = esdObject;\n fHasEvent=kTRUE;\n \n AfterNewEventLoaded();\n }\n else\n {\n cout<<\"No new event is avaliable.\"<ProcessEvents();\n}\n\n<|endoftext|>"} {"text":"\/* RoboticsLab, Copyright 2008-2010 SimLab Co., Ltd. All rights reserved.\r\n*\r\n* This library is commercial and cannot be redistributed, and\/or modified\r\n* WITHOUT ANY ALLOWANCE OR PERMISSION OF SimLab Co., LTD.\r\n*\/\r\n#include \"hybrid_automaton\/include\/hybrid_automaton_manager\/AbstractHybridAutomatonManager.h\"\r\n#include \"hybrid_automaton\/include\/hybrid_automaton_manager\/AbstractHybridAutomatonManagerCmd.h\"\r\n\r\n#include \"ros_bridge\\include\\msgs\\String.h\"\r\n#include \"ros_bridge\\include\\msgs\\Transform.h\"\r\n\r\n#include \r\n\r\nunsigned __stdcall deserializeHybridAutomaton(void *udata)\r\n{\r\n\tDeserializingThreadArguments* thread_args = static_cast(udata);\r\n\tHybridAutomaton* ha = NULL;\r\n\ttry {\r\n\t\tha = XMLDeserializer::createHybridAutomaton(thread_args->_string, thread_args->_sys, thread_args->_dT);\r\n\t\t\/\/std::cout << \"--------------- recieving hybrid automaton ------------------\" << std::endl;\r\n\t\t\/\/std::cout << ha->toStringXML() << std::endl;\r\n\t}\r\n\tcatch(std::string e)\r\n\t{\r\n\t\tstd::cerr << \"[deserializeHybridAutomaton] ERROR while deserializing hybrid automaton!\" << std::endl;\r\n\t\tstd::cerr << e << std::endl;\r\n\r\n\t\tdelete ha;\r\n\t\tdelete thread_args;\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tWaitForSingleObject(*(thread_args->_deserialize_mutex), INFINITE);\r\n\tif(thread_args->_noQueue)\r\n\t{\r\n\t\tfor(size_t i=0;i_deserialized_hybrid_automatons->size();i++)\r\n\t\t{\r\n\t\t\tdelete thread_args->_deserialized_hybrid_automatons->at(i);\r\n\t\t}\r\n\t\tthread_args->_deserialized_hybrid_automatons->clear();\t\r\n\t}\r\n\r\n\tthread_args->_deserialized_hybrid_automatons->push_back(ha);\r\n\tReleaseMutex(*(thread_args->_deserialize_mutex));\r\n\t\r\n\tdelete thread_args;\r\n\r\n\treturn 0;\r\n}\r\n\r\nAbstractHybridAutomatonManager::AbstractHybridAutomatonManager(rDC rdc) \r\n:rControlAlgorithm(rdc)\r\n, _sys(NULL)\r\n, _blackboard(NULL)\r\n, _activeMotionBehaviour(NULL)\r\n, _dof(0)\r\n, _servo_on(false)\r\n, _hybrid_automaton(NULL)\r\n, _qdot_filter(NULL)\r\n, _noQueue(false)\r\n{\r\n\t_deserialize_mutex = CreateMutex(0, FALSE, 0);\r\n\tif( !_deserialize_mutex ) {\r\n\t\tthrow(std::string(\"[AbstractHybridAutomatonManager::HybridAutomatonManager] ERROR: Mutex was not created (_deserialize_mutex)!\"));\r\n\t}\r\n}\r\n\r\nAbstractHybridAutomatonManager::~AbstractHybridAutomatonManager()\r\n{\r\n\tif(_activeMotionBehaviour)\r\n\t\tdelete _activeMotionBehaviour;\r\n\r\n\tif(_blackboard)\r\n\t{\r\n\t\tdelete _blackboard;\r\n\t\t_blackboard = NULL;\r\n\t}\r\n\r\n\tif(_qdot_filter)\r\n\t{\r\n\t\tdelete _qdot_filter;\r\n\t}\t\r\n\r\n\tFREE_SYSTEMS();\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::init(int mode)\r\n{\r\n\t_sys = LOAD_SYSTEM(_path, _aml, _T0, _q0);\r\n\tassert(_sys);\r\n\r\n\t\/\/Find the robot device. This device is used to read position and write torques\r\n\t\/\/to the robot\r\n\t_robot = findDevice(_T(\"ROBOT\"));\r\n\tRASSERT(_robot != INVALID_RHANDLE);\r\n\r\n\trxDevice* ft_sensor = (rxDevice*)findDevice(_T(\"FT_SENSOR\"));\r\n\tif (ft_sensor)\r\n\t\t_sys->addDevice(ft_sensor);\r\n\r\n\t_dof = _sys->jointDOF() + _sys->earthDOF() + _sys->constraintDOF();\r\n\r\n\t\/\/Initialize variables\r\n\t_q.resize(_dof);\r\n\t_qOld.resize(_dof);\r\n\t_qdot.resize(_dof);\r\n\t_torque.resize(_dof);\r\n\r\n\t_q.zero();\r\n\t_qOld.zero();\r\n\t_torque.zero();\r\n\t_qdot.zero();\r\n\r\n\t_qdot_filter = new rxFilteredDerivative(this->_dT, 10.0*this->_dT, this->_sys->jdof());\r\n\r\n\t_activeMotionBehaviour = new MotionBehaviour(new Milestone(), new Milestone(), _sys);\r\n\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::activateBlackboard(std::string &rlab_host, int rlab_port, std::string &ros_host, int ros_port)\r\n{\r\n\t_blackboard = RTBlackBoard::getInstance(rlab_host, rlab_port, ros_host, ros_port);\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::setHybridAutomaton(const std::string& _new_hybrid_automaton_str)\r\n{\r\n\tDeserializingThreadArguments* thread_args = new DeserializingThreadArguments();\r\n\tthread_args->_sys = this->_sys;\r\n\tthread_args->_string = _new_hybrid_automaton_str;\r\n\tthread_args->_dT = this->_dT;\r\n\tthread_args->_noQueue = this->_noQueue;\r\n\tthread_args->_deserialize_mutex = &(this->_deserialize_mutex);\r\n\tthread_args->_deserialized_hybrid_automatons = &(this->_deserialized_hybrid_automatons);\r\n\r\n\tif (_beginthreadex(NULL, 0, deserializeHybridAutomaton, (void*)thread_args, 0, NULL) == 0)\r\n\t{\r\n\t\tstd::cerr << \"[AbstractHybridAutomatonManager::updateHybridAutomaton] Error creating thread to deserialize xml string!\" << std::endl;\r\n\t}\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::setHybridAutomaton(HybridAutomaton* _new_hybrid_automaton)\r\n{\r\n\tWaitForSingleObject(_deserialize_mutex, INFINITE);\r\n\tthis->_deserialized_hybrid_automatons.push_back(_new_hybrid_automaton);\r\n\tReleaseMutex(_deserialize_mutex);\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::update(const rTime& t)\r\n{\r\n\tthis->updateHybridAutomaton();\r\n\r\n\tthis->updateMotionBehaviour(t);\r\n\r\n\tif (_activeMotionBehaviour)\r\n\t{\r\n\t\tMilestone* currentMilestone = (Milestone*)(_activeMotionBehaviour->getChild());\r\n\t\tcurrentMilestone->update(t);\r\n\t}\r\n\r\n\trControlAlgorithm::update(t);\r\n\r\n\tthis->updateBlackboard();\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::updateHybridAutomaton()\r\n{\r\n\tif (_blackboard && _blackboard->isUpdated(\"update_hybrid_automaton\"))\r\n\t{\r\n\t\trlab::String* ha_xml = dynamic_cast(_blackboard->getData(\"update_hybrid_automaton\"));\r\n\t\ttry\r\n\t\t{\r\n\t\t\tDeserializingThreadArguments* thread_args = new DeserializingThreadArguments();\r\n\t\t\tthread_args->_sys = this->_sys;\r\n\t\t\tthread_args->_string = ha_xml->get();\r\n\t\t\tthread_args->_dT = this->_dT;\r\n\t\t\tthread_args->_noQueue= this->_noQueue;\r\n\t\t\tthread_args->_deserialize_mutex = &(this->_deserialize_mutex);\r\n\t\t\tthread_args->_deserialized_hybrid_automatons = &(this->_deserialized_hybrid_automatons);\r\n\r\n\t\t\tif (_beginthreadex(NULL, 0, deserializeHybridAutomaton, (void*)thread_args, 0, NULL) == 0)\r\n\t\t\t{\r\n\t\t\t\tstd::cerr << \"[AbstractHybridAutomatonManager::updateHybridAutomaton] Error creating thread to deserialize xml string!\" << std::endl;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch(::std::string e)\r\n\t\t{\r\n\t\t\tstd::cout << \"[AbstractHybridAutomatonManager::updateHybridAutomaton] Error caught: \" << std::endl;\r\n\t\t\t::std::cout << e << ::std::endl;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::updateBlackboard()\r\n{\r\n\tif(!_blackboard)\r\n\t\treturn;\r\n\r\n\t_blackboard->setJointState(\"\/joint_states\", _sys->q(), _sys->qdot(), _torque);\r\n\r\n\tHTransform relative_transform;\r\n\trxBody* end_effector = _sys->getUCSBody(_T(\"EE\"), relative_transform);\r\n\tHTransform absolute_transform = end_effector->T() * relative_transform;\r\n\t_blackboard->setTransform(\"ee\", absolute_transform, \"base_link\");\r\n\t\r\n\t_blackboard->step();\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::setNominalSystem(const TCHAR* path, const TCHAR* aml, const HTransform& T0, const dVector& q0)\r\n{\r\n\tthis->_path = path;\r\n\tthis->_aml = aml;\r\n\tthis->_T0 = T0;\r\n\tthis->_q0 = q0;\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::setPeriod(const rTime& dT)\r\n{\r\n\tthis->_dT = dT;\r\n}\r\n\r\n\r\nvoid AbstractHybridAutomatonManager::_readDevices()\r\n{\t\r\n\t_qOld = _q;\r\n\r\n\tint r = readDeviceValue(_robot, &_q[0], sizeof(double) * _q.size(), 0);\r\n\tassert (r == sizeof(double) * _q.size());\r\n\r\n}\r\n\r\n\r\nvoid AbstractHybridAutomatonManager::_writeDevices()\r\n{\r\n\tint w = writeDeviceValue(_robot, &_torque[0], sizeof(double) * _torque.size());\r\n\tassert(w == sizeof(double)*_torque.size());\r\n}\r\n\r\n\r\nvoid AbstractHybridAutomatonManager::_reflect()\r\n{\r\n\t_sys->q(_q);\r\n\t_sys->qdot(_qdot);\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::_compute(const double& t)\r\n{\r\n\tif (_servo_on)\r\n\t{\r\n\t\t_torque = _activeMotionBehaviour->update(t);\r\n\t}\r\n\telse \r\n\t{\r\n\t\t_torque.zero();\r\n\t}\r\n\r\n\tsetTorque(_torque);\r\n}\r\n\r\n\r\n\r\nvoid AbstractHybridAutomatonManager::_estimate()\r\n{\r\n\tthis->_qdot_filter->compute(this->_q, this->_qdot);\r\n}\r\n\r\nint AbstractHybridAutomatonManager::command(const short& cmd, const int& arg)\r\n{\r\n\tswitch (cmd)\r\n\t{\r\n\tcase SERVO_ON:\r\n\t\t{\r\n\t\t\t_servo_on = !_servo_on;\r\n\r\n\t\t\tif(_servo_on)\r\n\t\t\t\tthis->_qdot_filter->initialize(this->_q);\r\n\r\n\t\t\tstd::cout << \"[AbstractHybridAutomatonManager::command] Servo ON: \" << _servo_on << std::endl;\r\n\t\t}\r\n\t\tbreak;\r\n\t\t\r\n\tcase BLACKBOARD_ON:\r\n\t\t{\r\n\t\t\tstd::map domain_names;\r\n\t\t\tdomain_names[URI_LOCAL] = \"\";\r\n\t\t\tdomain_names[URI_BOTTOM_1]\t= \"130.149.238.178\";\r\n\t\t\tdomain_names[URI_BOTTOM_2]\t= \"130.149.238.179\";\r\n\t\t\tdomain_names[URI_BOTTOM_3]\t= \"130.149.238.180\";\r\n\t\t\tdomain_names[URI_LOHENGRIN] = \"130.149.238.186\";\r\n\t\t\tdomain_names[URI_HASMA]\t\t= \"130.149.238.184\";\r\n\t\t\tdomain_names[URI_LEIBNIZ]\t= \"130.149.238.185\";\r\n domain_names[URI_POSEIDON]\t= \"130.149.238.193\";\r\n\t\t\tdomain_names[URI_FIRSTMM]\t= \"130.149.238.220\";\r\n\t\t\tdomain_names[URI_SHOEFER]\t= \"130.149.238.182\";\r\n\t\t\tdomain_names[URI_TOP_1A]\t= \"130.149.238.188\";\r\n\t\t\tdomain_names[URI_TOP_1B]\t= \"130.149.238.189\";\r\n\t\t\tdomain_names[URI_ARIS]\t\t= \"130.149.238.194\";\r\n\t\t\tdomain_names[URI_ANGEL]\t\t= \"130.149.238.149\";\r\n\t\t\tint bit_code = arg;\r\n\t\t\t\r\n\t\t\tint port = bit_code >> 16;\r\n\t\t\tbit_code &= ~(port << 16);\r\n\t\t\t\r\n\t\t\tint local_host = bit_code >> 8;\r\n\t\t\tbit_code &= ~(local_host << 8);\r\n\r\n\t\t\tint remote_host = bit_code;\r\n\t\t\t\r\n\t\t\tstd::cout << \"Enabled BlackBoard. Establishing connection between \" << domain_names[local_host] << \":\" << port << \" and \" << domain_names[remote_host] << \":\" << port << \".\" << std::endl;\t\r\n\t\t\t\r\n\t\t\tif (local_host != URI_LOCAL && domain_names[local_host].empty() ||\r\n\t\t\t\tremote_host != URI_LOCAL && domain_names[remote_host].empty())\r\n\t\t\t{\r\n\t\t\t\tstd::cout << \"WARNING! Unknown host: \" << local_host << \" or \" << remote_host << \"! (Will only establish unconnected BlackBoard)\" << std::endl;\r\n\t\t\t}\r\n\r\n\t\t\tactivateBlackboard(domain_names[local_host], port, domain_names[remote_host], port);\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\nvoid AbstractHybridAutomatonManager::datanames(vector& names, int channel)\r\n{\r\n\tswitch (channel) {\r\n\t\tcase PLOT_TORQUE: names.push_back(_T(\"Torque\"));\r\n\t\tcase PLOT_Q: names.push_back(_T(\"Q\"));\r\n\t\tcase PLOT_VELOCITY: names.push_back(_T(\"Velocity\"));\r\n\t\tcase PLOT_EEFRAME: names.push_back(_T(\"EEPosition\"));\r\n\t}\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::collect(vector& data, int channel)\r\n{\r\n\tif (channel == PLOT_TORQUE)\r\n\t{\r\n\t\tfor(int i = 0; i < _dof; ++i)\r\n\t\t\tdata.push_back(_torque[i]);\r\n\t}\r\n\telse if (channel == PLOT_Q)\r\n\t{\r\n\t\tfor(int i = 0; i < _dof; ++i)\r\n\t\t\tdata.push_back(_sys->q()[i]);\r\n\t}\r\n\telse if (channel == PLOT_VELOCITY)\r\n\t{\r\n\t\tfor(int i = 0; i < _dof; ++i)\r\n\t\t\tdata.push_back(_sys->qdot()[i]);\r\n\t}\t\r\n\telse if (channel == PLOT_EEFRAME)\r\n\t{\r\n\t\tHTransform relative_transform;\r\n\t\trxBody* end_effector = _sys->getUCSBody(_T(\"EE\"), relative_transform);\r\n\t\tHTransform absolute_transform = end_effector->T() * relative_transform;\r\n\t\tfor(int i = 0; i < 3; ++i)\r\n\t\t\tdata.push_back(absolute_transform.r(i));\r\n\t}\t\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::onSetInterestFrame(const TCHAR* name, const HTransform& T)\r\n{\r\n}\r\n\r\n\/*\r\nrControlAlgorithm* CreateControlAlgorithm(rDC& rdc)\r\n{\r\n\treturn new AbstractHybridAutomatonManager(rdc);\r\n}\r\n*\/Commented FREE_SYSTEMS out. Gave always a run-time exception.\/* RoboticsLab, Copyright 2008-2010 SimLab Co., Ltd. All rights reserved.\r\n*\r\n* This library is commercial and cannot be redistributed, and\/or modified\r\n* WITHOUT ANY ALLOWANCE OR PERMISSION OF SimLab Co., LTD.\r\n*\/\r\n#include \"hybrid_automaton\/include\/hybrid_automaton_manager\/AbstractHybridAutomatonManager.h\"\r\n#include \"hybrid_automaton\/include\/hybrid_automaton_manager\/AbstractHybridAutomatonManagerCmd.h\"\r\n\r\n#include \"ros_bridge\\include\\msgs\\String.h\"\r\n#include \"ros_bridge\\include\\msgs\\Transform.h\"\r\n\r\n#include \r\n\r\nunsigned __stdcall deserializeHybridAutomaton(void *udata)\r\n{\r\n\tDeserializingThreadArguments* thread_args = static_cast(udata);\r\n\tHybridAutomaton* ha = NULL;\r\n\ttry {\r\n\t\tha = XMLDeserializer::createHybridAutomaton(thread_args->_string, thread_args->_sys, thread_args->_dT);\r\n\t\t\/\/std::cout << \"--------------- recieving hybrid automaton ------------------\" << std::endl;\r\n\t\t\/\/std::cout << ha->toStringXML() << std::endl;\r\n\t}\r\n\tcatch(std::string e)\r\n\t{\r\n\t\tstd::cerr << \"[deserializeHybridAutomaton] ERROR while deserializing hybrid automaton!\" << std::endl;\r\n\t\tstd::cerr << e << std::endl;\r\n\r\n\t\tdelete ha;\r\n\t\tdelete thread_args;\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tWaitForSingleObject(*(thread_args->_deserialize_mutex), INFINITE);\r\n\tif(thread_args->_noQueue)\r\n\t{\r\n\t\tfor(size_t i=0;i_deserialized_hybrid_automatons->size();i++)\r\n\t\t{\r\n\t\t\tdelete thread_args->_deserialized_hybrid_automatons->at(i);\r\n\t\t}\r\n\t\tthread_args->_deserialized_hybrid_automatons->clear();\t\r\n\t}\r\n\r\n\tthread_args->_deserialized_hybrid_automatons->push_back(ha);\r\n\tReleaseMutex(*(thread_args->_deserialize_mutex));\r\n\t\r\n\tdelete thread_args;\r\n\r\n\treturn 0;\r\n}\r\n\r\nAbstractHybridAutomatonManager::AbstractHybridAutomatonManager(rDC rdc) \r\n:rControlAlgorithm(rdc)\r\n, _sys(NULL)\r\n, _blackboard(NULL)\r\n, _activeMotionBehaviour(NULL)\r\n, _dof(0)\r\n, _servo_on(false)\r\n, _hybrid_automaton(NULL)\r\n, _qdot_filter(NULL)\r\n, _noQueue(false)\r\n{\r\n\t_deserialize_mutex = CreateMutex(0, FALSE, 0);\r\n\tif( !_deserialize_mutex ) {\r\n\t\tthrow(std::string(\"[AbstractHybridAutomatonManager::HybridAutomatonManager] ERROR: Mutex was not created (_deserialize_mutex)!\"));\r\n\t}\r\n}\r\n\r\nAbstractHybridAutomatonManager::~AbstractHybridAutomatonManager()\r\n{\r\n\tif(_activeMotionBehaviour)\r\n\t\tdelete _activeMotionBehaviour;\r\n\r\n\tif(_blackboard)\r\n\t{\r\n\t\tdelete _blackboard;\r\n\t\t_blackboard = NULL;\r\n\t}\r\n\r\n\tif(_qdot_filter)\r\n\t{\r\n\t\tdelete _qdot_filter;\r\n\t}\t\r\n\r\n\t\/*\r\n\tFREE_SYSTEMS();\r\n\t*\/\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::init(int mode)\r\n{\r\n\t_sys = LOAD_SYSTEM(_path, _aml, _T0, _q0);\r\n\tassert(_sys);\r\n\r\n\t\/\/Find the robot device. This device is used to read position and write torques\r\n\t\/\/to the robot\r\n\t_robot = findDevice(_T(\"ROBOT\"));\r\n\tRASSERT(_robot != INVALID_RHANDLE);\r\n\r\n\trxDevice* ft_sensor = (rxDevice*)findDevice(_T(\"FT_SENSOR\"));\r\n\tif (ft_sensor)\r\n\t\t_sys->addDevice(ft_sensor);\r\n\r\n\t_dof = _sys->jointDOF() + _sys->earthDOF() + _sys->constraintDOF();\r\n\r\n\t\/\/Initialize variables\r\n\t_q.resize(_dof);\r\n\t_qOld.resize(_dof);\r\n\t_qdot.resize(_dof);\r\n\t_torque.resize(_dof);\r\n\r\n\t_q.zero();\r\n\t_qOld.zero();\r\n\t_torque.zero();\r\n\t_qdot.zero();\r\n\r\n\t_qdot_filter = new rxFilteredDerivative(this->_dT, 10.0*this->_dT, this->_sys->jdof());\r\n\r\n\t_activeMotionBehaviour = new MotionBehaviour(new Milestone(), new Milestone(), _sys);\r\n\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::activateBlackboard(std::string &rlab_host, int rlab_port, std::string &ros_host, int ros_port)\r\n{\r\n\t_blackboard = RTBlackBoard::getInstance(rlab_host, rlab_port, ros_host, ros_port);\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::setHybridAutomaton(const std::string& _new_hybrid_automaton_str)\r\n{\r\n\tDeserializingThreadArguments* thread_args = new DeserializingThreadArguments();\r\n\tthread_args->_sys = this->_sys;\r\n\tthread_args->_string = _new_hybrid_automaton_str;\r\n\tthread_args->_dT = this->_dT;\r\n\tthread_args->_noQueue = this->_noQueue;\r\n\tthread_args->_deserialize_mutex = &(this->_deserialize_mutex);\r\n\tthread_args->_deserialized_hybrid_automatons = &(this->_deserialized_hybrid_automatons);\r\n\r\n\tif (_beginthreadex(NULL, 0, deserializeHybridAutomaton, (void*)thread_args, 0, NULL) == 0)\r\n\t{\r\n\t\tstd::cerr << \"[AbstractHybridAutomatonManager::updateHybridAutomaton] Error creating thread to deserialize xml string!\" << std::endl;\r\n\t}\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::setHybridAutomaton(HybridAutomaton* _new_hybrid_automaton)\r\n{\r\n\tWaitForSingleObject(_deserialize_mutex, INFINITE);\r\n\tthis->_deserialized_hybrid_automatons.push_back(_new_hybrid_automaton);\r\n\tReleaseMutex(_deserialize_mutex);\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::update(const rTime& t)\r\n{\r\n\tthis->updateHybridAutomaton();\r\n\r\n\tthis->updateMotionBehaviour(t);\r\n\r\n\tif (_activeMotionBehaviour)\r\n\t{\r\n\t\tMilestone* currentMilestone = (Milestone*)(_activeMotionBehaviour->getChild());\r\n\t\tcurrentMilestone->update(t);\r\n\t}\r\n\r\n\trControlAlgorithm::update(t);\r\n\r\n\tthis->updateBlackboard();\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::updateHybridAutomaton()\r\n{\r\n\tif (_blackboard && _blackboard->isUpdated(\"update_hybrid_automaton\"))\r\n\t{\r\n\t\trlab::String* ha_xml = dynamic_cast(_blackboard->getData(\"update_hybrid_automaton\"));\r\n\t\ttry\r\n\t\t{\r\n\t\t\tDeserializingThreadArguments* thread_args = new DeserializingThreadArguments();\r\n\t\t\tthread_args->_sys = this->_sys;\r\n\t\t\tthread_args->_string = ha_xml->get();\r\n\t\t\tthread_args->_dT = this->_dT;\r\n\t\t\tthread_args->_noQueue= this->_noQueue;\r\n\t\t\tthread_args->_deserialize_mutex = &(this->_deserialize_mutex);\r\n\t\t\tthread_args->_deserialized_hybrid_automatons = &(this->_deserialized_hybrid_automatons);\r\n\r\n\t\t\tif (_beginthreadex(NULL, 0, deserializeHybridAutomaton, (void*)thread_args, 0, NULL) == 0)\r\n\t\t\t{\r\n\t\t\t\tstd::cerr << \"[AbstractHybridAutomatonManager::updateHybridAutomaton] Error creating thread to deserialize xml string!\" << std::endl;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch(::std::string e)\r\n\t\t{\r\n\t\t\tstd::cout << \"[AbstractHybridAutomatonManager::updateHybridAutomaton] Error caught: \" << std::endl;\r\n\t\t\t::std::cout << e << ::std::endl;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::updateBlackboard()\r\n{\r\n\tif(!_blackboard)\r\n\t\treturn;\r\n\r\n\t_blackboard->setJointState(\"\/joint_states\", _sys->q(), _sys->qdot(), _torque);\r\n\r\n\tHTransform relative_transform;\r\n\trxBody* end_effector = _sys->getUCSBody(_T(\"EE\"), relative_transform);\r\n\tHTransform absolute_transform = end_effector->T() * relative_transform;\r\n\t_blackboard->setTransform(\"ee\", absolute_transform, \"base_link\");\r\n\t\r\n\t_blackboard->step();\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::setNominalSystem(const TCHAR* path, const TCHAR* aml, const HTransform& T0, const dVector& q0)\r\n{\r\n\tthis->_path = path;\r\n\tthis->_aml = aml;\r\n\tthis->_T0 = T0;\r\n\tthis->_q0 = q0;\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::setPeriod(const rTime& dT)\r\n{\r\n\tthis->_dT = dT;\r\n}\r\n\r\n\r\nvoid AbstractHybridAutomatonManager::_readDevices()\r\n{\t\r\n\t_qOld = _q;\r\n\r\n\tint r = readDeviceValue(_robot, &_q[0], sizeof(double) * _q.size(), 0);\r\n\tassert (r == sizeof(double) * _q.size());\r\n\r\n}\r\n\r\n\r\nvoid AbstractHybridAutomatonManager::_writeDevices()\r\n{\r\n\tint w = writeDeviceValue(_robot, &_torque[0], sizeof(double) * _torque.size());\r\n\tassert(w == sizeof(double)*_torque.size());\r\n}\r\n\r\n\r\nvoid AbstractHybridAutomatonManager::_reflect()\r\n{\r\n\t_sys->q(_q);\r\n\t_sys->qdot(_qdot);\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::_compute(const double& t)\r\n{\r\n\tif (_servo_on)\r\n\t{\r\n\t\t_torque = _activeMotionBehaviour->update(t);\r\n\t}\r\n\telse \r\n\t{\r\n\t\t_torque.zero();\r\n\t}\r\n\r\n\tsetTorque(_torque);\r\n}\r\n\r\n\r\n\r\nvoid AbstractHybridAutomatonManager::_estimate()\r\n{\r\n\tthis->_qdot_filter->compute(this->_q, this->_qdot);\r\n}\r\n\r\nint AbstractHybridAutomatonManager::command(const short& cmd, const int& arg)\r\n{\r\n\tswitch (cmd)\r\n\t{\r\n\tcase SERVO_ON:\r\n\t\t{\r\n\t\t\t_servo_on = !_servo_on;\r\n\r\n\t\t\tif(_servo_on)\r\n\t\t\t\tthis->_qdot_filter->initialize(this->_q);\r\n\r\n\t\t\tstd::cout << \"[AbstractHybridAutomatonManager::command] Servo ON: \" << _servo_on << std::endl;\r\n\t\t}\r\n\t\tbreak;\r\n\t\t\r\n\tcase BLACKBOARD_ON:\r\n\t\t{\r\n\t\t\tstd::map domain_names;\r\n\t\t\tdomain_names[URI_LOCAL] = \"\";\r\n\t\t\tdomain_names[URI_BOTTOM_1]\t= \"130.149.238.178\";\r\n\t\t\tdomain_names[URI_BOTTOM_2]\t= \"130.149.238.179\";\r\n\t\t\tdomain_names[URI_BOTTOM_3]\t= \"130.149.238.180\";\r\n\t\t\tdomain_names[URI_LOHENGRIN] = \"130.149.238.186\";\r\n\t\t\tdomain_names[URI_HASMA]\t\t= \"130.149.238.184\";\r\n\t\t\tdomain_names[URI_LEIBNIZ]\t= \"130.149.238.185\";\r\n domain_names[URI_POSEIDON]\t= \"130.149.238.193\";\r\n\t\t\tdomain_names[URI_FIRSTMM]\t= \"130.149.238.220\";\r\n\t\t\tdomain_names[URI_SHOEFER]\t= \"130.149.238.182\";\r\n\t\t\tdomain_names[URI_TOP_1A]\t= \"130.149.238.188\";\r\n\t\t\tdomain_names[URI_TOP_1B]\t= \"130.149.238.189\";\r\n\t\t\tdomain_names[URI_ARIS]\t\t= \"130.149.238.194\";\r\n\t\t\tdomain_names[URI_ANGEL]\t\t= \"130.149.238.149\";\r\n\t\t\tint bit_code = arg;\r\n\t\t\t\r\n\t\t\tint port = bit_code >> 16;\r\n\t\t\tbit_code &= ~(port << 16);\r\n\t\t\t\r\n\t\t\tint local_host = bit_code >> 8;\r\n\t\t\tbit_code &= ~(local_host << 8);\r\n\r\n\t\t\tint remote_host = bit_code;\r\n\t\t\t\r\n\t\t\tstd::cout << \"Enabled BlackBoard. Establishing connection between \" << domain_names[local_host] << \":\" << port << \" and \" << domain_names[remote_host] << \":\" << port << \".\" << std::endl;\t\r\n\t\t\t\r\n\t\t\tif (local_host != URI_LOCAL && domain_names[local_host].empty() ||\r\n\t\t\t\tremote_host != URI_LOCAL && domain_names[remote_host].empty())\r\n\t\t\t{\r\n\t\t\t\tstd::cout << \"WARNING! Unknown host: \" << local_host << \" or \" << remote_host << \"! (Will only establish unconnected BlackBoard)\" << std::endl;\r\n\t\t\t}\r\n\r\n\t\t\tactivateBlackboard(domain_names[local_host], port, domain_names[remote_host], port);\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\nvoid AbstractHybridAutomatonManager::datanames(vector& names, int channel)\r\n{\r\n\tswitch (channel) {\r\n\t\tcase PLOT_TORQUE: names.push_back(_T(\"Torque\"));\r\n\t\tcase PLOT_Q: names.push_back(_T(\"Q\"));\r\n\t\tcase PLOT_VELOCITY: names.push_back(_T(\"Velocity\"));\r\n\t\tcase PLOT_EEFRAME: names.push_back(_T(\"EEPosition\"));\r\n\t}\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::collect(vector& data, int channel)\r\n{\r\n\tif (channel == PLOT_TORQUE)\r\n\t{\r\n\t\tfor(int i = 0; i < _dof; ++i)\r\n\t\t\tdata.push_back(_torque[i]);\r\n\t}\r\n\telse if (channel == PLOT_Q)\r\n\t{\r\n\t\tfor(int i = 0; i < _dof; ++i)\r\n\t\t\tdata.push_back(_sys->q()[i]);\r\n\t}\r\n\telse if (channel == PLOT_VELOCITY)\r\n\t{\r\n\t\tfor(int i = 0; i < _dof; ++i)\r\n\t\t\tdata.push_back(_sys->qdot()[i]);\r\n\t}\t\r\n\telse if (channel == PLOT_EEFRAME)\r\n\t{\r\n\t\tHTransform relative_transform;\r\n\t\trxBody* end_effector = _sys->getUCSBody(_T(\"EE\"), relative_transform);\r\n\t\tHTransform absolute_transform = end_effector->T() * relative_transform;\r\n\t\tfor(int i = 0; i < 3; ++i)\r\n\t\t\tdata.push_back(absolute_transform.r(i));\r\n\t}\t\r\n}\r\n\r\nvoid AbstractHybridAutomatonManager::onSetInterestFrame(const TCHAR* name, const HTransform& T)\r\n{\r\n}\r\n\r\n\/*\r\nrControlAlgorithm* CreateControlAlgorithm(rDC& rdc)\r\n{\r\n\treturn new AbstractHybridAutomatonManager(rdc);\r\n}\r\n*\/<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/customize\/p9_xip_customize.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef _P9_XIP_CUSTOMIZE_\n#define _P9_XIP_CUSTOMIZE_\n\n#include \n\ntypedef fapi2::ReturnCode (*p9_xip_customize_FP_t) (\n const fapi2::Target& i_proc_target,\n void* io_image,\n uint32_t& io_imageSize,\n void* io_ringSectionBuf,\n uint32_t& io_ringSectionBufSize,\n uint8_t i_sysPhase,\n uint8_t i_modeBuild,\n void* io_ringBuf1,\n uint32_t i_ringBufSize1,\n void* io_ringBuf2,\n uint32_t i_ringBufSize2,\n uint32_t& io_bootCoreMask);\n\nextern \"C\"\n{\n\/\/\/ @brief p9_xip_customize used to customize the SBE\/CME\/SGPE images with\n\/\/\/ mailbox attributes, VPD rings and other stuff.\n\/\/\/\n\/\/\/ @param[in] i_proc_target => P9 proc chip target\n\/\/\/ @param[in\/out] io_image => Pointer to an in-memory image\n\/\/\/ HB_SBE:\n\/\/\/ In: SBE image\n\/\/\/ Out: Seeprom image\n\/\/\/ RT_{CME,SGPE}:\n\/\/\/ In: HW image\n\/\/\/ Out: HW image\n\/\/\/ @param[in\/out] io_imageSize => Size of image\n\/\/\/ HB_SBE:\n\/\/\/ In: MAX_SEEPROM_IMAGE_SIZE\n\/\/\/ Out: Final size\n\/\/\/ RT_{CME,SGPE}:\n\/\/\/ In: Size of HW image\n\/\/\/ Out: Unchanged\n\/\/\/ @param[in\/out] io_ringSectionBuf => Pointer to an in-memory ring section\n\/\/\/ buffer\n\/\/\/ HB_SBE:\n\/\/\/ Used as temporary image work buffer\n\/\/\/ In: Undefined\n\/\/\/ Out: Undefined\n\/\/\/ RT_{CME,SGPE}:\n\/\/\/ In: Undefined\n\/\/\/ Out: Updated .rings section\n\/\/\/ @param[in\/out] io_ringSectionBufSize => In: Size of ring section buffer\n\/\/\/ HB_SBE:\n\/\/\/ In: MAX_SEEPROM_IMAGE_SIZE\n\/\/\/ Out: Unchanged\n\/\/\/ RT_{CME,SGPE}:\n\/\/\/ In: MAX_SEEPROM_IMAGE_SIZE\n\/\/\/ Out: Final size\n\/\/\/ @param[in] i_sysPhase => ={HB_SBE, RT_CME, RT_SGPE}\n\/\/\/ @param[in] i_modeBuild => ={IPL, REBUILD}\n\/\/\/ @param[in\/out] io_ringBuf1 => Caller supplied in-memory buffer\n\/\/\/ for uncompressed VPD rings in\n\/\/\/ @param[in] i_ringBufSize1 => Max size of VPD ring buffer\n\/\/\/ (Should equal MAX_RING_BUF_SIZE)\n\/\/\/ @param[in\/out] io_ringBuf2 => Caller supplied in-memory buffer\n\/\/\/ for uncompressed overlay rings\n\/\/\/ @param[in] i_ringBufSize2 => Max size of overlay ring buffer\n\/\/\/ (Should equal MAX_RING_BUF_SIZE)\n\/\/\/ @param[in\/out] io_bootCoreMask => In: Mask of the desired boot cores\n\/\/\/ Out: Actual boot cores\n\/\/\/ (Only used in HB_SBE sysPhase)\n\/\/\/ (Bits(8:31) = EC00:EC23)\n\/\/\/\n\/\/\/ @return FAPI_RC_SUCCESS if the customization was successful\n\/\/\/\n fapi2::ReturnCode p9_xip_customize (\n const fapi2::Target& i_proc_target,\n void* io_image,\n uint32_t& io_imageSize,\n void* io_ringSectionBuf,\n uint32_t& io_ringSectionBufSize,\n uint8_t i_sysPhase,\n uint8_t i_modeBuild,\n void* io_ringBuf1,\n uint32_t i_ringBufSize1,\n void* io_ringBuf2,\n uint32_t i_ringBufSize2,\n uint32_t& io_bootCoreMask);\n\n}\n#endif\nxip_customize: Four fixes for relieving Seeprom space constraint.\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/customize\/p9_xip_customize.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef _P9_XIP_CUSTOMIZE_\n#define _P9_XIP_CUSTOMIZE_\n\n#include \n\ntypedef fapi2::ReturnCode (*p9_xip_customize_FP_t) (\n const fapi2::Target& i_proc_target,\n void* io_image,\n uint32_t& io_imageSize,\n void* io_ringSectionBuf,\n uint32_t& io_ringSectionBufSize,\n uint8_t i_sysPhase,\n uint8_t i_modeBuild,\n void* io_ringBuf1,\n uint32_t i_ringBufSize1,\n void* io_ringBuf2,\n uint32_t i_ringBufSize2,\n uint32_t& io_bootCoreMask);\n\nextern \"C\"\n{\n\/\/\/ @brief p9_xip_customize used to customize the SBE\/CME\/SGPE images with\n\/\/\/ mailbox attributes, VPD rings and other stuff.\n\/\/\/\n\/\/\/ @param[in] i_proc_target => P9 proc chip target\n\/\/\/ @param[in\/out] io_image => Pointer to an in-memory image\n\/\/\/ HB_SBE:\n\/\/\/ In: SBE image\n\/\/\/ Out: Seeprom image\n\/\/\/ RT_{CME,SGPE}:\n\/\/\/ In: HW image\n\/\/\/ Out: HW image\n\/\/\/ @param[in\/out] io_imageSize => Size of image\n\/\/\/ HB_SBE:\n\/\/\/ In: >=MAX_SBE_SEEPROM_SIZE\n\/\/\/ Out: Final size\n\/\/\/ RT_{CME,SGPE}:\n\/\/\/ In: Size of HW image\n\/\/\/ Out: Unchanged\n\/\/\/ @param[in\/out] io_ringSectionBuf => Pointer to an in-memory ring section\n\/\/\/ buffer\n\/\/\/ HB_SBE:\n\/\/\/ Used as temporary image work buffer\n\/\/\/ In: Undefined\n\/\/\/ Out: Undefined\n\/\/\/ RT_{CME,SGPE}:\n\/\/\/ In: Undefined\n\/\/\/ Out: Updated .rings section\n\/\/\/ @param[in\/out] io_ringSectionBufSize => In: Size of ring section buffer\n\/\/\/ HB_SBE:\n\/\/\/ In: Input value of io_imageSize\n\/\/\/ Out: Final size\n\/\/\/ RT_{CME,SGPE}:\n\/\/\/ In: >=MAX_SBE_SEEPROM_SIZE\n\/\/\/ Out: Final size\n\/\/\/ @param[in] i_sysPhase => ={HB_SBE, RT_CME, RT_SGPE}\n\/\/\/ @param[in] i_modeBuild => ={IPL, REBUILD}\n\/\/\/ @param[in\/out] io_ringBuf1 => Caller supplied in-memory buffer\n\/\/\/ for uncompressed VPD rings in\n\/\/\/ @param[in] i_ringBufSize1 => Max size of VPD ring buffer\n\/\/\/ (Should equal MAX_RING_BUF_SIZE)\n\/\/\/ @param[in\/out] io_ringBuf2 => Caller supplied in-memory buffer\n\/\/\/ for uncompressed overlay rings\n\/\/\/ @param[in] i_ringBufSize2 => Max size of overlay ring buffer\n\/\/\/ (Should equal MAX_RING_BUF_SIZE)\n\/\/\/ @param[in\/out] io_bootCoreMask => In: Mask of the desired boot cores\n\/\/\/ Out: Actual boot cores\n\/\/\/ (Only used in HB_SBE sysPhase)\n\/\/\/ (Bits(8:31) = EC00:EC23)\n\/\/\/\n\/\/\/ @return FAPI_RC_SUCCESS if the customization was successful\n\/\/\/\n fapi2::ReturnCode p9_xip_customize (\n const fapi2::Target& i_proc_target,\n void* io_image,\n uint32_t& io_imageSize,\n void* io_ringSectionBuf,\n uint32_t& io_ringSectionBufSize,\n uint8_t i_sysPhase,\n uint8_t i_modeBuild,\n void* io_ringBuf1,\n uint32_t i_ringBufSize1,\n void* io_ringBuf2,\n uint32_t i_ringBufSize2,\n uint32_t& io_bootCoreMask);\n\n}\n#endif\n<|endoftext|>"} {"text":"\/*\n*\n* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U\n*\n* This file is part of Orion Context Broker.\n*\n* Orion Context Broker is free software: you can redistribute it and\/or\n* modify it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* Orion Context Broker is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero\n* General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with Orion Context Broker. If not, see http:\/\/www.gnu.org\/licenses\/.\n*\n* For those usages not covered by this license please contact with\n* fermin at tid dot es\n*\n* Author: Ken Zangelin\n*\/\n#include \n#include \n\n#include \"logMsg\/logMsg.h\"\n#include \"logMsg\/traceLevels.h\"\n\n#include \"convenience\/UpdateContextElementResponse.h\"\n#include \"convenienceMap\/mapPutIndividualContextEntityAttribute.h\"\n#include \"ngsi\/ParseData.h\"\n#include \"rest\/ConnectionInfo.h\"\n#include \"serviceRoutines\/putIndividualContextEntityAttribute.h\"\n\n\n\n\/* ****************************************************************************\n*\n* putIndividualContextEntityAttribute -\n*\/\nstd::string putIndividualContextEntityAttribute(ConnectionInfo* ciP, int components, std::vector compV, ParseData* parseDataP)\n{\n std::string answer;\n std::string entityId = compV[2];\n std::string attributeName = compV[4];\n StatusCode response;\n\n LM_T(LmtConvenience, (\"CONVENIENCE: got a 'PUT' request for entityId '%s'\", entityId.c_str()));\n ciP->httpStatusCode = mapPutIndividualContextEntityAttribute(entityId, attributeName, &parseDataP->upcar.res, &response);\n answer = response.render(ciP->outFormat, \"\");\n response.release();\n\n return answer;\n}\nChange author\/*\n*\n* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U\n*\n* This file is part of Orion Context Broker.\n*\n* Orion Context Broker is free software: you can redistribute it and\/or\n* modify it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* Orion Context Broker is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero\n* General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with Orion Context Broker. If not, see http:\/\/www.gnu.org\/licenses\/.\n*\n* For those usages not covered by this license please contact with\n* fermin at tid dot es\n*\n* Author: TID Developer\n*\/\n#include \n#include \n\n#include \"logMsg\/logMsg.h\"\n#include \"logMsg\/traceLevels.h\"\n\n#include \"convenience\/UpdateContextElementResponse.h\"\n#include \"convenienceMap\/mapPutIndividualContextEntityAttribute.h\"\n#include \"ngsi\/ParseData.h\"\n#include \"rest\/ConnectionInfo.h\"\n#include \"serviceRoutines\/putIndividualContextEntityAttribute.h\"\n\n\n\n\/* ****************************************************************************\n*\n* putIndividualContextEntityAttribute -\n*\/\nstd::string putIndividualContextEntityAttribute(ConnectionInfo* ciP, int components, std::vector compV, ParseData* parseDataP)\n{\n std::string answer;\n std::string entityId = compV[2];\n std::string attributeName = compV[4];\n StatusCode response;\n\n LM_T(LmtConvenience, (\"CONVENIENCE: got a 'PUT' request for entityId '%s'\", entityId.c_str()));\n ciP->httpStatusCode = mapPutIndividualContextEntityAttribute(entityId, attributeName, &parseDataP->upcar.res, &response);\n answer = response.render(ciP->outFormat, \"\");\n response.release();\n\n return answer;\n}\n<|endoftext|>"} {"text":"\/*\n\tThis file is part of cpp-ethereum.\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/** @file ClientModel.cpp\n * @author Yann yann@ethdev.com\n * @author Arkadiy Paronyan arkadiy@ethdev.com\n * @date 2015\n * Ethereum IDE client.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"AppContext.h\"\n#include \"DebuggingStateWrapper.h\"\n#include \"QContractDefinition.h\"\n#include \"QVariableDeclaration.h\"\n#include \"ContractCallDataEncoder.h\"\n#include \"CodeModel.h\"\n#include \"ClientModel.h\"\n#include \"QEther.h\"\n#include \"Web3Server.h\"\n#include \"ClientModel.h\"\n\nusing namespace dev;\nusing namespace dev::eth;\nusing namespace dev::mix;\n\nClientModel::ClientModel(AppContext* _context):\n\tm_context(_context), m_running(false), m_qWebThree(nullptr)\n{\n\tqRegisterMetaType(\"QBigInt*\");\n\tqRegisterMetaType(\"QEther*\");\n\tqRegisterMetaType(\"QVariableDefinition*\");\n\tqRegisterMetaType(\"QVariableDefinitionList*\");\n\tqRegisterMetaType>(\"QList\");\n\tqRegisterMetaType>(\"QList\");\n\tqRegisterMetaType(\"QVariableDeclaration*\");\n\tqRegisterMetaType(\"AssemblyDebuggerData\");\n\n\tconnect(this, &ClientModel::dataAvailable, this, &ClientModel::showDebugger, Qt::QueuedConnection);\n\tm_client.reset(new MixClient());\n\n\tm_qWebThree = new QWebThree(this);\n\tm_qWebThreeConnector.reset(new QWebThreeConnector());\n\tm_qWebThreeConnector->setQWeb(m_qWebThree);\n\tm_web3Server.reset(new Web3Server(*m_qWebThreeConnector.get(), std::vector { m_client->userAccount() }, m_client.get()));\n\tconnect(m_qWebThree, &QWebThree::response, this, &ClientModel::apiResponse);\n\n\t_context->appEngine()->rootContext()->setContextProperty(\"clientModel\", this);\n}\n\nClientModel::~ClientModel()\n{\n}\n\nvoid ClientModel::apiRequest(QString const& _message)\n{\n\t(void)_message;\n\/\/\tm_qWebThree->postMessage(_message);\n}\n\nQString ClientModel::contractAddress() const\n{\n\tQString address = QString::fromStdString(dev::toJS(m_client->lastContractAddress()));\n\treturn address;\n}\n\nvoid ClientModel::debugDeployment()\n{\n\texecuteSequence(std::vector(), 10000000 * ether);\n}\n\nvoid ClientModel::debugState(QVariantMap _state)\n{\n\tu256 balance = (qvariant_cast(_state.value(\"balance\")))->toU256Wei();\n\tQVariantList transactions = _state.value(\"transactions\").toList();\n\n\tstd::vector transactionSequence;\n\tTransactionSettings constructorTr;\n\tfor (auto const& t: transactions)\n\t{\n\t\tQVariantMap transaction = t.toMap();\n\t\tQString functionId = transaction.value(\"functionId\").toString();\n\t\tu256 gas = (qvariant_cast(transaction.value(\"gas\")))->toU256Wei();\n\t\tu256 value = (qvariant_cast(transaction.value(\"value\")))->toU256Wei();\n\t\tu256 gasPrice = (qvariant_cast(transaction.value(\"gasPrice\")))->toU256Wei();\n\t\tQVariantMap params = transaction.value(\"parameters\").toMap();\n\t\tTransactionSettings transactionSettings(functionId, value, gas, gasPrice);\n\n\t\tfor (auto p = params.cbegin(); p != params.cend(); ++p)\n\t\t{\n\t\t\tQBigInt* param = qvariant_cast(p.value());\n\t\t\ttransactionSettings.parameterValues.insert(std::make_pair(p.key(), boost::get(param->internalValue())));\n\t\t}\n\n\t\tif (transaction.value(\"executeConstructor\").toBool())\n\t\t\tconstructorTr = transactionSettings;\n\t\telse\n\t\t\ttransactionSequence.push_back(transactionSettings);\n\t}\n\texecuteSequence(transactionSequence, balance, constructorTr);\n}\n\nvoid ClientModel::executeSequence(std::vector const& _sequence, u256 _balance, TransactionSettings const& ctrTransaction)\n{\n\tif (m_running)\n\t\tthrow (std::logic_error(\"debugging already running\"));\n\tauto compilerRes = m_context->codeModel()->code();\n\tstd::shared_ptr contractDef = compilerRes->sharedContract();\n\tm_running = true;\n\n\temit runStarted();\n\temit stateChanged();\n\n\t\/\/run sequence\n\tQtConcurrent::run([=]()\n\t{\n\t\ttry\n\t\t{\n\t\t\tbytes contractCode = compilerRes->bytes();\n\t\t\tstd::vector transactonData;\n\t\t\tQFunctionDefinition* f = nullptr;\n\t\t\tContractCallDataEncoder c;\n\t\t\t\/\/encode data for all transactions\n\t\t\tfor (auto const& t: _sequence)\n\t\t\t{\n\t\t\t\tf = nullptr;\n\t\t\t\tfor (int tf = 0; tf < contractDef->functionsList().size(); tf++)\n\t\t\t\t{\n\t\t\t\t\tif (contractDef->functionsList().at(tf)->name() == t.functionId)\n\t\t\t\t\t{\n\t\t\t\t\t\tf = contractDef->functionsList().at(tf);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!f)\n\t\t\t\t\tthrow std::runtime_error(\"function \" + t.functionId.toStdString() + \" not found\");\n\n\t\t\t\tc.encode(f);\n\t\t\t\tfor (int p = 0; p < f->parametersList().size(); p++)\n\t\t\t\t{\n\t\t\t\t\tQVariableDeclaration* var = (QVariableDeclaration*)f->parametersList().at(p);\n\t\t\t\t\tu256 value = 0;\n\t\t\t\t\tauto v = t.parameterValues.find(var->name());\n\t\t\t\t\tif (v != t.parameterValues.cend())\n\t\t\t\t\t\tvalue = v->second;\n\t\t\t\t\tc.encode(var, value);\n\t\t\t\t}\n\t\t\t\ttransactonData.emplace_back(c.encodedData());\n\t\t\t}\n\n\t\t\t\/\/run contract creation first\n\t\t\tm_client->resetState(_balance);\n\t\t\tExecutionResult debuggingContent = deployContract(contractCode, ctrTransaction);\n\t\t\tAddress address = debuggingContent.contractAddress;\n\t\t\tfor (unsigned i = 0; i < _sequence.size(); ++i)\n\t\t\t\tdebuggingContent = callContract(address, transactonData.at(i), _sequence.at(i));\n\n\t\t\tQList returnParameters;\n\n\t\t\tif (f)\n\t\t\t\treturnParameters = c.decode(f->returnParameters(), debuggingContent.returnValue);\n\n\t\t\t\/\/we need to wrap states in a QObject before sending to QML.\n\t\t\tQList wStates;\n\t\t\tfor (unsigned i = 0; i < debuggingContent.machineStates.size(); i++)\n\t\t\t{\n\t\t\t\tQPointer s(new DebuggingStateWrapper(debuggingContent.executionCode, debuggingContent.executionData.toBytes()));\n\t\t\t\ts->setState(debuggingContent.machineStates[i]);\n\t\t\t\twStates.append(s);\n\t\t\t}\n\t\t\t\/\/collect states for last transaction\n\t\t\tAssemblyDebuggerData code = DebuggingStateWrapper::getHumanReadableCode(debuggingContent.executionCode);\n\t\t\temit dataAvailable(returnParameters, wStates, code);\n\t\t\temit runComplete();\n\t\t}\n\t\tcatch(boost::exception const&)\n\t\t{\n\t\t\temit runFailed(QString::fromStdString(boost::current_exception_diagnostic_information()));\n\t\t}\n\n\t\tcatch(std::exception const& e)\n\t\t{\n\t\t\temit runFailed(e.what());\n\t\t}\n\t\tm_running = false;\n\t\temit stateChanged();\n\t});\n}\n\nvoid ClientModel::showDebugger(QList const& _returnParam, QList const& _wStates, AssemblyDebuggerData const& _code)\n{\n\tm_context->appEngine()->rootContext()->setContextProperty(\"debugStates\", QVariant::fromValue(_wStates));\n\tm_context->appEngine()->rootContext()->setContextProperty(\"humanReadableExecutionCode\", QVariant::fromValue(std::get<0>(_code)));\n\tm_context->appEngine()->rootContext()->setContextProperty(\"bytesCodeMapping\", QVariant::fromValue(std::get<1>(_code)));\n\tm_context->appEngine()->rootContext()->setContextProperty(\"contractCallReturnParameters\", QVariant::fromValue(new QVariableDefinitionList(_returnParam)));\n\tshowDebuggerWindow();\n}\n\nvoid ClientModel::showDebugError(QString const& _error)\n{\n\t\/\/TODO: change that to a signal\n\tm_context->displayMessageDialog(tr(\"Debugger\"), _error);\n}\n\nExecutionResult ClientModel::deployContract(bytes const& _code, TransactionSettings const& _ctrTransaction)\n{\n\tAddress newAddress;\n\tif (!ctrTransaction.isEmpty())\n\t\tnewAddress = m_client->transact(m_client->userAccount().secret(), _ctrTransaction.value, _code, _ctrTransaction.gas, _ctrTransaction.gasPrice);\n\telse\n\t{\n\t\tu256 gasPrice = 10000000000000;\n\t\tu256 gas = 125000;\n\t\tu256 amount = 100;\n\t\tnewAddress = m_client->transact(m_client->userAccount().secret(), amount, _code, gas, gasPrice);\n\t}\n\n\tAddress lastAddress = m_client->lastContractAddress();\n\tExecutionResult r = m_client->lastExecutionResult();\n\tif (newAddress != lastAddress)\n\t\tcontractAddressChanged();\n\treturn r;\n}\n\nExecutionResult ClientModel::callContract(Address const& _contract, bytes const& _data, TransactionSettings const& _tr)\n{\n\tm_client->transact(m_client->userAccount().secret(), _tr.value, _contract, _data, _tr.gas, _tr.gasPrice);\n\tExecutionResult r = m_client->lastExecutionResult();\n\tr.contractAddress = _contract;\n\treturn r;\n}\n - Coding Standards\/*\n\tThis file is part of cpp-ethereum.\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/** @file ClientModel.cpp\n * @author Yann yann@ethdev.com\n * @author Arkadiy Paronyan arkadiy@ethdev.com\n * @date 2015\n * Ethereum IDE client.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"AppContext.h\"\n#include \"DebuggingStateWrapper.h\"\n#include \"QContractDefinition.h\"\n#include \"QVariableDeclaration.h\"\n#include \"ContractCallDataEncoder.h\"\n#include \"CodeModel.h\"\n#include \"ClientModel.h\"\n#include \"QEther.h\"\n#include \"Web3Server.h\"\n#include \"ClientModel.h\"\n\nusing namespace dev;\nusing namespace dev::eth;\nusing namespace dev::mix;\n\nClientModel::ClientModel(AppContext* _context):\n\tm_context(_context), m_running(false), m_qWebThree(nullptr)\n{\n\tqRegisterMetaType(\"QBigInt*\");\n\tqRegisterMetaType(\"QEther*\");\n\tqRegisterMetaType(\"QVariableDefinition*\");\n\tqRegisterMetaType(\"QVariableDefinitionList*\");\n\tqRegisterMetaType>(\"QList\");\n\tqRegisterMetaType>(\"QList\");\n\tqRegisterMetaType(\"QVariableDeclaration*\");\n\tqRegisterMetaType(\"AssemblyDebuggerData\");\n\n\tconnect(this, &ClientModel::dataAvailable, this, &ClientModel::showDebugger, Qt::QueuedConnection);\n\tm_client.reset(new MixClient());\n\n\tm_qWebThree = new QWebThree(this);\n\tm_qWebThreeConnector.reset(new QWebThreeConnector());\n\tm_qWebThreeConnector->setQWeb(m_qWebThree);\n\tm_web3Server.reset(new Web3Server(*m_qWebThreeConnector.get(), std::vector { m_client->userAccount() }, m_client.get()));\n\tconnect(m_qWebThree, &QWebThree::response, this, &ClientModel::apiResponse);\n\n\t_context->appEngine()->rootContext()->setContextProperty(\"clientModel\", this);\n}\n\nClientModel::~ClientModel()\n{\n}\n\nvoid ClientModel::apiRequest(QString const& _message)\n{\n\t(void)_message;\n\/\/\tm_qWebThree->postMessage(_message);\n}\n\nQString ClientModel::contractAddress() const\n{\n\tQString address = QString::fromStdString(dev::toJS(m_client->lastContractAddress()));\n\treturn address;\n}\n\nvoid ClientModel::debugDeployment()\n{\n\texecuteSequence(std::vector(), 10000000 * ether);\n}\n\nvoid ClientModel::debugState(QVariantMap _state)\n{\n\tu256 balance = (qvariant_cast(_state.value(\"balance\")))->toU256Wei();\n\tQVariantList transactions = _state.value(\"transactions\").toList();\n\n\tstd::vector transactionSequence;\n\tTransactionSettings constructorTr;\n\tfor (auto const& t: transactions)\n\t{\n\t\tQVariantMap transaction = t.toMap();\n\t\tQString functionId = transaction.value(\"functionId\").toString();\n\t\tu256 gas = (qvariant_cast(transaction.value(\"gas\")))->toU256Wei();\n\t\tu256 value = (qvariant_cast(transaction.value(\"value\")))->toU256Wei();\n\t\tu256 gasPrice = (qvariant_cast(transaction.value(\"gasPrice\")))->toU256Wei();\n\t\tQVariantMap params = transaction.value(\"parameters\").toMap();\n\t\tTransactionSettings transactionSettings(functionId, value, gas, gasPrice);\n\n\t\tfor (auto p = params.cbegin(); p != params.cend(); ++p)\n\t\t{\n\t\t\tQBigInt* param = qvariant_cast(p.value());\n\t\t\ttransactionSettings.parameterValues.insert(std::make_pair(p.key(), boost::get(param->internalValue())));\n\t\t}\n\n\t\tif (transaction.value(\"executeConstructor\").toBool())\n\t\t\tconstructorTr = transactionSettings;\n\t\telse\n\t\t\ttransactionSequence.push_back(transactionSettings);\n\t}\n\texecuteSequence(transactionSequence, balance, constructorTr);\n}\n\nvoid ClientModel::executeSequence(std::vector const& _sequence, u256 _balance, TransactionSettings const& ctrTransaction)\n{\n\tif (m_running)\n\t\tthrow (std::logic_error(\"debugging already running\"));\n\tauto compilerRes = m_context->codeModel()->code();\n\tstd::shared_ptr contractDef = compilerRes->sharedContract();\n\tm_running = true;\n\n\temit runStarted();\n\temit stateChanged();\n\n\t\/\/run sequence\n\tQtConcurrent::run([=]()\n\t{\n\t\ttry\n\t\t{\n\t\t\tbytes contractCode = compilerRes->bytes();\n\t\t\tstd::vector transactonData;\n\t\t\tQFunctionDefinition* f = nullptr;\n\t\t\tContractCallDataEncoder c;\n\t\t\t\/\/encode data for all transactions\n\t\t\tfor (auto const& t: _sequence)\n\t\t\t{\n\t\t\t\tf = nullptr;\n\t\t\t\tfor (int tf = 0; tf < contractDef->functionsList().size(); tf++)\n\t\t\t\t{\n\t\t\t\t\tif (contractDef->functionsList().at(tf)->name() == t.functionId)\n\t\t\t\t\t{\n\t\t\t\t\t\tf = contractDef->functionsList().at(tf);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!f)\n\t\t\t\t\tthrow std::runtime_error(\"function \" + t.functionId.toStdString() + \" not found\");\n\n\t\t\t\tc.encode(f);\n\t\t\t\tfor (int p = 0; p < f->parametersList().size(); p++)\n\t\t\t\t{\n\t\t\t\t\tQVariableDeclaration* var = (QVariableDeclaration*)f->parametersList().at(p);\n\t\t\t\t\tu256 value = 0;\n\t\t\t\t\tauto v = t.parameterValues.find(var->name());\n\t\t\t\t\tif (v != t.parameterValues.cend())\n\t\t\t\t\t\tvalue = v->second;\n\t\t\t\t\tc.encode(var, value);\n\t\t\t\t}\n\t\t\t\ttransactonData.emplace_back(c.encodedData());\n\t\t\t}\n\n\t\t\t\/\/run contract creation first\n\t\t\tm_client->resetState(_balance);\n\t\t\tExecutionResult debuggingContent = deployContract(contractCode, ctrTransaction);\n\t\t\tAddress address = debuggingContent.contractAddress;\n\t\t\tfor (unsigned i = 0; i < _sequence.size(); ++i)\n\t\t\t\tdebuggingContent = callContract(address, transactonData.at(i), _sequence.at(i));\n\n\t\t\tQList returnParameters;\n\n\t\t\tif (f)\n\t\t\t\treturnParameters = c.decode(f->returnParameters(), debuggingContent.returnValue);\n\n\t\t\t\/\/we need to wrap states in a QObject before sending to QML.\n\t\t\tQList wStates;\n\t\t\tfor (unsigned i = 0; i < debuggingContent.machineStates.size(); i++)\n\t\t\t{\n\t\t\t\tQPointer s(new DebuggingStateWrapper(debuggingContent.executionCode, debuggingContent.executionData.toBytes()));\n\t\t\t\ts->setState(debuggingContent.machineStates[i]);\n\t\t\t\twStates.append(s);\n\t\t\t}\n\t\t\t\/\/collect states for last transaction\n\t\t\tAssemblyDebuggerData code = DebuggingStateWrapper::getHumanReadableCode(debuggingContent.executionCode);\n\t\t\temit dataAvailable(returnParameters, wStates, code);\n\t\t\temit runComplete();\n\t\t}\n\t\tcatch(boost::exception const&)\n\t\t{\n\t\t\temit runFailed(QString::fromStdString(boost::current_exception_diagnostic_information()));\n\t\t}\n\n\t\tcatch(std::exception const& e)\n\t\t{\n\t\t\temit runFailed(e.what());\n\t\t}\n\t\tm_running = false;\n\t\temit stateChanged();\n\t});\n}\n\nvoid ClientModel::showDebugger(QList const& _returnParam, QList const& _wStates, AssemblyDebuggerData const& _code)\n{\n\tm_context->appEngine()->rootContext()->setContextProperty(\"debugStates\", QVariant::fromValue(_wStates));\n\tm_context->appEngine()->rootContext()->setContextProperty(\"humanReadableExecutionCode\", QVariant::fromValue(std::get<0>(_code)));\n\tm_context->appEngine()->rootContext()->setContextProperty(\"bytesCodeMapping\", QVariant::fromValue(std::get<1>(_code)));\n\tm_context->appEngine()->rootContext()->setContextProperty(\"contractCallReturnParameters\", QVariant::fromValue(new QVariableDefinitionList(_returnParam)));\n\tshowDebuggerWindow();\n}\n\nvoid ClientModel::showDebugError(QString const& _error)\n{\n\t\/\/TODO: change that to a signal\n\tm_context->displayMessageDialog(tr(\"Debugger\"), _error);\n}\n\nExecutionResult ClientModel::deployContract(bytes const& _code, TransactionSettings const& _ctrTransaction)\n{\n\tAddress newAddress;\n\tif (!_ctrTransaction.isEmpty())\n\t\tnewAddress = m_client->transact(m_client->userAccount().secret(), _ctrTransaction.value, _code, _ctrTransaction.gas, _ctrTransaction.gasPrice);\n\telse\n\t{\n\t\tu256 gasPrice = 10000000000000;\n\t\tu256 gas = 125000;\n\t\tu256 amount = 100;\n\t\tnewAddress = m_client->transact(m_client->userAccount().secret(), amount, _code, gas, gasPrice);\n\t}\n\n\tAddress lastAddress = m_client->lastContractAddress();\n\tExecutionResult r = m_client->lastExecutionResult();\n\tif (newAddress != lastAddress)\n\t\tcontractAddressChanged();\n\treturn r;\n}\n\nExecutionResult ClientModel::callContract(Address const& _contract, bytes const& _data, TransactionSettings const& _tr)\n{\n\tm_client->transact(m_client->userAccount().secret(), _tr.value, _contract, _data, _tr.gas, _tr.gasPrice);\n\tExecutionResult r = m_client->lastExecutionResult();\n\tr.contractAddress = _contract;\n\treturn r;\n}\n<|endoftext|>"} {"text":"#include \"SphericalProjectionSurface.h\"\n#include \"utils\/Const.h\"\n\nnamespace carto {\n \n SphericalProjectionSurface::SphericalProjectionSurface() {\n }\n\n MapPos SphericalProjectionSurface::calculateMapPos(const cglib::vec3& pos) const {\n return SphericalToInternal(pos * (1.0 \/ SPHERE_SIZE));\n }\n\n MapVec SphericalProjectionSurface::calculateMapVec(const cglib::vec3& pos, const cglib::vec3& vec) const {\n cglib::vec3 xyzPos = pos * (1.0 \/ SPHERE_SIZE);\n cglib::mat3x3 xyzFrame = LocalFrame(xyzPos);\n double scale = std::sqrt(xyzPos(0) * xyzPos(0) + xyzPos(1) * xyzPos(1)) \/ Const::PI;\n cglib::vec3 mapVec = cglib::transform(vec, cglib::transpose(xyzFrame));\n return MapVec(mapVec(0) * scale, mapVec(1) * scale, mapVec(2) * scale);\n }\n\n cglib::vec3 SphericalProjectionSurface::calculatePosition(const MapPos& mapPos) const {\n return InternalToSpherical(mapPos) * SPHERE_SIZE;\n }\n\n cglib::vec3 SphericalProjectionSurface::calculateNormal(const MapPos& mapPos) const {\n return InternalToSpherical(mapPos);\n }\n\n cglib::vec3 SphericalProjectionSurface::calculateVector(const MapPos& mapPos, const MapVec& mapVec) const {\n cglib::vec3 xyzPos = InternalToSpherical(mapPos);\n cglib::mat3x3 xyzFrame = LocalFrame(xyzPos);\n double scale = Const::PI \/ std::sqrt(xyzPos(0) * xyzPos(0) + xyzPos(1) * xyzPos(1));\n return cglib::transform(cglib::vec3(mapVec.getX() * scale, mapVec.getY() * scale, mapVec.getZ() * scale), xyzFrame);\n }\n\n void SphericalProjectionSurface::tesselateSegment(const MapPos& mapPos0, const MapPos& mapPos1, std::vector& mapPoses) const {\n \/\/ TODO: make it faster, non-recursive\n MapPos mapPosM;\n if (SplitSegment(mapPos0, mapPos1, mapPosM)) {\n tesselateSegment(mapPos0, mapPosM, mapPoses);\n tesselateSegment(mapPosM, mapPos1, mapPoses);\n return;\n }\n\n mapPoses.push_back(mapPos0);\n mapPoses.push_back(mapPos1);\n }\n\n void SphericalProjectionSurface::tesselateTriangle(unsigned int i0, unsigned int i1, unsigned int i2, std::vector& indices, std::vector& mapPoses) const {\n const MapPos& mapPos0 = mapPoses.at(i0);\n const MapPos& mapPos1 = mapPoses.at(i1);\n const MapPos& mapPos2 = mapPoses.at(i2);\n \n \/\/ TODO: make it faster, non-recursive\n MapPos mapPosM;\n if (SplitSegment(mapPos0, mapPos1, mapPosM)) {\n unsigned int iM = static_cast(mapPoses.size());\n mapPoses.push_back(mapPosM);\n tesselateTriangle(i2, i0, iM, indices, mapPoses);\n tesselateTriangle(i1, i2, iM, indices, mapPoses);\n return;\n } else if (SplitSegment(mapPos0, mapPos2, mapPosM)) {\n unsigned int iM = static_cast(mapPoses.size());\n mapPoses.push_back(mapPosM);\n tesselateTriangle(i0, i1, iM, indices, mapPoses);\n tesselateTriangle(i1, i2, iM, indices, mapPoses);\n return;\n } else if (SplitSegment(mapPos1, mapPos2, mapPosM)) {\n unsigned int iM = static_cast(mapPoses.size());\n mapPoses.push_back(mapPosM);\n tesselateTriangle(i0, i1, iM, indices, mapPoses);\n tesselateTriangle(i2, i0, iM, indices, mapPoses);\n return;\n }\n\n indices.push_back(i0);\n indices.push_back(i1);\n indices.push_back(i2);\n }\n\n double SphericalProjectionSurface::calculateDistance(const cglib::vec3 pos0, const cglib::vec3& pos1) const {\n double dot = cglib::dot_product(cglib::unit(pos0), cglib::unit(pos1));\n double angle = std::acos(std::min(1.0, std::max(-1.0, dot)));\n if (angle < PLANAR_APPROX_ANGLE) {\n cglib::vec3 delta = cglib::unit(pos0) - cglib::unit(pos1);\n return cglib::length(delta) * Const::WORLD_SIZE;\n }\n return angle * Const::WORLD_SIZE;\n }\n\n cglib::vec3 SphericalProjectionSurface::calculateNearestPoint(const cglib::vec3& pos, double height) const {\n return cglib::unit(pos) * (SPHERE_SIZE + height);\n }\n \n cglib::vec3 SphericalProjectionSurface::calculateNearestPoint(const cglib::ray3& ray, double height, double& t) const {\n if (calculateHitPoint(ray, height, t)) {\n return ray(t);\n }\n t = -cglib::dot_product(ray.origin, ray.direction) \/ cglib::norm(ray.direction);\n return cglib::unit(ray(t)) * (SPHERE_SIZE + height);\n }\n\n bool SphericalProjectionSurface::calculateHitPoint(const cglib::ray3& ray, double height, double& t) const {\n double a = cglib::norm(ray.direction);\n double b = 2.0 * cglib::dot_product(ray.direction, ray.origin);\n double c = cglib::norm(ray.origin) - (SPHERE_SIZE + height) * (SPHERE_SIZE + height);\n double d = b * b - 4.0 * a * c;\n if (d < 0.0) {\n return false;\n }\n t = (-b - std::sqrt(d)) \/ (2.0 * a);\n return true;\n }\n\n cglib::mat4x4 SphericalProjectionSurface::calculateLocalFrameMatrix(const cglib::vec3& pos) const {\n cglib::mat3x3 localFrameMat3 = LocalFrame(pos * (1.0 \/ SPHERE_SIZE));\n cglib::mat4x4 localFrameMat4 = cglib::mat4x4::identity();\n for (int i = 0; i < 3; i++) {\n cglib::vec3 dir = cglib::unit(cglib::col_vector(localFrameMat3, i));\n for (int j = 0; j < 3; j++) {\n localFrameMat4(j, i) = dir(j) * SPHERE_SIZE \/ Const::EARTH_RADIUS;\n }\n localFrameMat4(i, 3) = pos(i);\n }\n return localFrameMat4;\n }\n\n cglib::mat4x4 SphericalProjectionSurface::calculateTranslateMatrix(const cglib::vec3& pos0, const cglib::vec3& pos1, double t) const {\n double scale = (1 - t) + (cglib::length(pos1) \/ cglib::length(pos0)) * t;\n cglib::mat4x4 scaleMat = cglib::scale4_matrix(cglib::vec3(scale, scale, scale));\n\n double dot = cglib::dot_product(cglib::unit(pos0), cglib::unit(pos1));\n double angle = std::acos(std::min(1.0, std::max(-1.0, dot)));\n cglib::vec3 axis = cglib::vector_product(cglib::unit(pos0), cglib::unit(pos1));\n if (cglib::length(axis) > 0) {\n if (angle < PLANAR_APPROX_ANGLE) { \/\/ less than 10m\n return cglib::translate4_matrix((cglib::unit(pos1) - cglib::unit(pos0)) * (SPHERE_SIZE * t)) * scaleMat;\n }\n return cglib::rotate4_matrix(axis, angle * t) * scaleMat;\n }\n return scaleMat;\n }\n\n bool SphericalProjectionSurface::SplitSegment(const MapPos& mapPos0, const MapPos& mapPos1, MapPos& mapPosM) {\n cglib::vec3 pos0 = cglib::unit(InternalToSpherical(mapPos0));\n cglib::vec3 pos1 = cglib::unit(InternalToSpherical(mapPos1));\n double dot = cglib::dot_product(pos0, pos1);\n if (dot <= -1) {\n return false; \/\/ exactly on the opposite side, no way to split\n }\n double angle = std::acos(std::min(1.0, std::max(-1.0, dot)));\n if (angle * Const::EARTH_RADIUS < SEGMENT_SPLIT_THRESHOLD) {\n return false;\n }\n mapPosM = SphericalToInternal(cglib::unit(pos0 + pos1));\n return true;\n }\n\n MapPos SphericalProjectionSurface::SphericalToInternal(const cglib::vec3& pos) {\n double scale = Const::WORLD_SIZE \/ (2 * Const::PI);\n double length = cglib::length(pos);\n double x1 = pos(0) != 0 || pos(1) != 0 ? std::atan2(pos(1), pos(0)) : 0;\n double y1 = std::atanh(std::max(-1.0, std::min(1.0, pos(2) \/ length)));\n double z1 = length - 1.0;\n return MapPos(x1 * scale, y1 * scale, z1 * scale);\n }\n\n cglib::vec3 SphericalProjectionSurface::InternalToSpherical(const MapPos& mapPos) {\n double scale = 2 * Const::PI \/ Const::WORLD_SIZE;\n double x1 = mapPos.getX() * scale;\n double y1 = mapPos.getY() * scale;\n double z1 = mapPos.getZ() * scale;\n double rz = std::tanh(y1);\n double ss = std::sqrt(std::max(0.0, 1.0 - rz * rz));\n double rx = ss * std::cos(x1);\n double ry = ss * std::sin(x1);\n return cglib::vec3(rx, ry, rz) * (1.0 + z1);\n }\n\n cglib::mat3x3 SphericalProjectionSurface::LocalFrame(const cglib::vec3& pos) {\n double x = pos(0);\n double y = pos(1);\n double z = pos(2);\n \n double dx_du = -y;\n double dy_du = x;\n double dz_du = 0;\n\n double dx_dv = -z * x;\n double dy_dv = -z * y;\n double dz_dv = x * x + y * y;\n\n double dx_dh = x;\n double dy_dh = y;\n double dz_dh = z;\n\n return cglib::mat3x3 { { dx_du, dx_dv, dx_dh }, { dy_du, dy_dv, dy_dh }, { dz_du, dz_dv, dz_dh } };\n }\n\n const double SphericalProjectionSurface::SPHERE_SIZE = Const::WORLD_SIZE \/ Const::PI;\n\n const double SphericalProjectionSurface::PLANAR_APPROX_ANGLE = 1.0e-6;\n\n const double SphericalProjectionSurface::SEGMENT_SPLIT_THRESHOLD = Const::EARTH_CIRCUMFERENCE \/ 120.0;\n \n}\nFix Z coordinate handling in SphericalProjectionSurface#include \"SphericalProjectionSurface.h\"\n#include \"utils\/Const.h\"\n\nnamespace carto {\n \n SphericalProjectionSurface::SphericalProjectionSurface() {\n }\n\n MapPos SphericalProjectionSurface::calculateMapPos(const cglib::vec3& pos) const {\n return SphericalToInternal(pos * (1.0 \/ SPHERE_SIZE));\n }\n\n MapVec SphericalProjectionSurface::calculateMapVec(const cglib::vec3& pos, const cglib::vec3& vec) const {\n cglib::vec3 xyzPos = pos * (1.0 \/ SPHERE_SIZE);\n cglib::mat3x3 xyzFrame = LocalFrame(xyzPos);\n double scale = std::sqrt(xyzPos(0) * xyzPos(0) + xyzPos(1) * xyzPos(1)) \/ Const::PI;\n cglib::vec3 mapVec = cglib::transform(vec, cglib::transpose(xyzFrame));\n return MapVec(mapVec(0) * scale, mapVec(1) * scale, mapVec(2) * scale);\n }\n\n cglib::vec3 SphericalProjectionSurface::calculatePosition(const MapPos& mapPos) const {\n return InternalToSpherical(mapPos) * SPHERE_SIZE;\n }\n\n cglib::vec3 SphericalProjectionSurface::calculateNormal(const MapPos& mapPos) const {\n return InternalToSpherical(mapPos);\n }\n\n cglib::vec3 SphericalProjectionSurface::calculateVector(const MapPos& mapPos, const MapVec& mapVec) const {\n cglib::vec3 xyzPos = InternalToSpherical(mapPos);\n cglib::mat3x3 xyzFrame = LocalFrame(xyzPos);\n double scale = Const::PI \/ std::sqrt(xyzPos(0) * xyzPos(0) + xyzPos(1) * xyzPos(1));\n return cglib::transform(cglib::vec3(mapVec.getX() * scale, mapVec.getY() * scale, mapVec.getZ() * scale), xyzFrame);\n }\n\n void SphericalProjectionSurface::tesselateSegment(const MapPos& mapPos0, const MapPos& mapPos1, std::vector& mapPoses) const {\n \/\/ TODO: make it faster, non-recursive\n MapPos mapPosM;\n if (SplitSegment(mapPos0, mapPos1, mapPosM)) {\n tesselateSegment(mapPos0, mapPosM, mapPoses);\n tesselateSegment(mapPosM, mapPos1, mapPoses);\n return;\n }\n\n mapPoses.push_back(mapPos0);\n mapPoses.push_back(mapPos1);\n }\n\n void SphericalProjectionSurface::tesselateTriangle(unsigned int i0, unsigned int i1, unsigned int i2, std::vector& indices, std::vector& mapPoses) const {\n const MapPos& mapPos0 = mapPoses.at(i0);\n const MapPos& mapPos1 = mapPoses.at(i1);\n const MapPos& mapPos2 = mapPoses.at(i2);\n \n \/\/ TODO: make it faster, non-recursive\n MapPos mapPosM;\n if (SplitSegment(mapPos0, mapPos1, mapPosM)) {\n unsigned int iM = static_cast(mapPoses.size());\n mapPoses.push_back(mapPosM);\n tesselateTriangle(i2, i0, iM, indices, mapPoses);\n tesselateTriangle(i1, i2, iM, indices, mapPoses);\n return;\n } else if (SplitSegment(mapPos0, mapPos2, mapPosM)) {\n unsigned int iM = static_cast(mapPoses.size());\n mapPoses.push_back(mapPosM);\n tesselateTriangle(i0, i1, iM, indices, mapPoses);\n tesselateTriangle(i1, i2, iM, indices, mapPoses);\n return;\n } else if (SplitSegment(mapPos1, mapPos2, mapPosM)) {\n unsigned int iM = static_cast(mapPoses.size());\n mapPoses.push_back(mapPosM);\n tesselateTriangle(i0, i1, iM, indices, mapPoses);\n tesselateTriangle(i2, i0, iM, indices, mapPoses);\n return;\n }\n\n indices.push_back(i0);\n indices.push_back(i1);\n indices.push_back(i2);\n }\n\n double SphericalProjectionSurface::calculateDistance(const cglib::vec3 pos0, const cglib::vec3& pos1) const {\n double dot = cglib::dot_product(cglib::unit(pos0), cglib::unit(pos1));\n double angle = std::acos(std::min(1.0, std::max(-1.0, dot)));\n if (angle < PLANAR_APPROX_ANGLE) {\n cglib::vec3 delta = cglib::unit(pos0) - cglib::unit(pos1);\n return cglib::length(delta) * Const::WORLD_SIZE;\n }\n return angle * Const::WORLD_SIZE;\n }\n\n cglib::vec3 SphericalProjectionSurface::calculateNearestPoint(const cglib::vec3& pos, double height) const {\n return cglib::unit(pos) * (SPHERE_SIZE + height);\n }\n \n cglib::vec3 SphericalProjectionSurface::calculateNearestPoint(const cglib::ray3& ray, double height, double& t) const {\n if (calculateHitPoint(ray, height, t)) {\n return ray(t);\n }\n t = -cglib::dot_product(ray.origin, ray.direction) \/ cglib::norm(ray.direction);\n return cglib::unit(ray(t)) * (SPHERE_SIZE + height);\n }\n\n bool SphericalProjectionSurface::calculateHitPoint(const cglib::ray3& ray, double height, double& t) const {\n double a = cglib::norm(ray.direction);\n double b = 2.0 * cglib::dot_product(ray.direction, ray.origin);\n double c = cglib::norm(ray.origin) - (SPHERE_SIZE + height) * (SPHERE_SIZE + height);\n double d = b * b - 4.0 * a * c;\n if (d < 0.0) {\n return false;\n }\n t = (-b - std::sqrt(d)) \/ (2.0 * a);\n return true;\n }\n\n cglib::mat4x4 SphericalProjectionSurface::calculateLocalFrameMatrix(const cglib::vec3& pos) const {\n cglib::mat3x3 localFrameMat3 = LocalFrame(pos * (1.0 \/ SPHERE_SIZE));\n cglib::mat4x4 localFrameMat4 = cglib::mat4x4::identity();\n for (int i = 0; i < 3; i++) {\n cglib::vec3 dir = cglib::unit(cglib::col_vector(localFrameMat3, i));\n for (int j = 0; j < 3; j++) {\n localFrameMat4(j, i) = dir(j) * SPHERE_SIZE \/ Const::EARTH_RADIUS;\n }\n localFrameMat4(i, 3) = pos(i);\n }\n return localFrameMat4;\n }\n\n cglib::mat4x4 SphericalProjectionSurface::calculateTranslateMatrix(const cglib::vec3& pos0, const cglib::vec3& pos1, double t) const {\n double scale = (1 - t) + (cglib::length(pos1) \/ cglib::length(pos0)) * t;\n cglib::mat4x4 scaleMat = cglib::scale4_matrix(cglib::vec3(scale, scale, scale));\n\n double dot = cglib::dot_product(cglib::unit(pos0), cglib::unit(pos1));\n double angle = std::acos(std::min(1.0, std::max(-1.0, dot)));\n cglib::vec3 axis = cglib::vector_product(cglib::unit(pos0), cglib::unit(pos1));\n if (cglib::length(axis) > 0) {\n if (angle < PLANAR_APPROX_ANGLE) { \/\/ less than 10m\n return cglib::translate4_matrix((cglib::unit(pos1) - cglib::unit(pos0)) * (SPHERE_SIZE * t)) * scaleMat;\n }\n return cglib::rotate4_matrix(axis, angle * t) * scaleMat;\n }\n return scaleMat;\n }\n\n bool SphericalProjectionSurface::SplitSegment(const MapPos& mapPos0, const MapPos& mapPos1, MapPos& mapPosM) {\n cglib::vec3 pos0 = cglib::unit(InternalToSpherical(mapPos0));\n cglib::vec3 pos1 = cglib::unit(InternalToSpherical(mapPos1));\n double dot = cglib::dot_product(pos0, pos1);\n if (dot <= -1) {\n return false; \/\/ exactly on the opposite side, no way to split\n }\n double angle = std::acos(std::min(1.0, std::max(-1.0, dot)));\n if (angle * Const::EARTH_RADIUS < SEGMENT_SPLIT_THRESHOLD) {\n return false;\n }\n mapPosM = SphericalToInternal(cglib::unit(pos0 + pos1));\n return true;\n }\n\n MapPos SphericalProjectionSurface::SphericalToInternal(const cglib::vec3& pos) {\n double scale = Const::WORLD_SIZE \/ (2 * Const::PI);\n double len = cglib::length(pos);\n double rz = pos(2) \/ len;\n double ss = std::sqrt(std::max(0.0, 1.0 - rz * rz));\n double x1 = pos(0) != 0 || pos(1) != 0 ? std::atan2(pos(1), pos(0)) : 0;\n double y1 = std::atanh(std::max(-1.0, std::min(1.0, rz)));\n double z1 = (len - 1.0) \/ ss;\n return MapPos(x1 * scale, y1 * scale, z1 * scale);\n }\n\n cglib::vec3 SphericalProjectionSurface::InternalToSpherical(const MapPos& mapPos) {\n double scale = 2 * Const::PI \/ Const::WORLD_SIZE;\n double x1 = mapPos.getX() * scale;\n double y1 = mapPos.getY() * scale;\n double z1 = mapPos.getZ() * scale;\n double rz = std::tanh(y1);\n double ss = std::sqrt(std::max(0.0, 1.0 - rz * rz));\n double rx = ss * std::cos(x1);\n double ry = ss * std::sin(x1);\n double len = 1.0 + z1 * ss;\n return cglib::vec3(rx, ry, rz) * len;\n }\n\n cglib::mat3x3 SphericalProjectionSurface::LocalFrame(const cglib::vec3& pos) {\n double x = pos(0);\n double y = pos(1);\n double z = pos(2);\n \n double dx_du = -y;\n double dy_du = x;\n double dz_du = 0;\n\n double dx_dv = -z * x;\n double dy_dv = -z * y;\n double dz_dv = x * x + y * y;\n\n double dx_dh = x;\n double dy_dh = y;\n double dz_dh = z;\n\n return cglib::mat3x3 { { dx_du, dx_dv, dx_dh }, { dy_du, dy_dv, dy_dh }, { dz_du, dz_dv, dz_dh } };\n }\n\n const double SphericalProjectionSurface::SPHERE_SIZE = Const::WORLD_SIZE \/ Const::PI;\n\n const double SphericalProjectionSurface::PLANAR_APPROX_ANGLE = 1.0e-6;\n\n const double SphericalProjectionSurface::SEGMENT_SPLIT_THRESHOLD = Const::EARTH_CIRCUMFERENCE \/ 120.0;\n \n}\n<|endoftext|>"} {"text":"#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n#include \"mtrace.h\"\n#include \"amd64.h\"\n#include \"uspinlock.h\"\n#include \"pthread.h\"\n\nenum { readaccess = 0 };\nenum { verbose = 0 };\nenum { npg = 1 };\n\nvoid*\nthr(void *arg)\n{\n u64 tid = (u64)arg;\n\n for (int i = 0; i < 1000000; i++) {\n if (verbose && ((i % 100) == 0))\n fprintf(1, \"%d: %d ops\\n\", tid, i);\n\n volatile char *p = (char*) (0x40000UL + tid * npg * 4096);\n if (map((void *) p, npg * 4096) < 0) {\n fprintf(1, \"%d: map failed\\n\", tid);\n exit();\n }\n\n if (readaccess) {\n for (int j = 0; j < npg * 4096; j++)\n\tp[j] = '\\0';\n }\n\n if (unmap((void *) p, npg * 4096) < 0) {\n fprintf(1, \"%d: unmap failed\\n\", tid);\n exit();\n }\n }\n return 0;\n}\n\nint\nmain(int ac, char **av)\n{\n mtenable(\"xv6-mapbench\");\n\n if (ac != 2) {\n fprintf(1, \"usage: %s nthreads\\n\", av[0]);\n exit();\n }\n\n int nthread = atoi(av[1]);\n\n \/\/ fprintf(1, \"mapbench[%d]: start esp %x, nthread=%d\\n\", getpid(), rrsp(), nthread);\n\n for(u64 i = 0; i < nthread; i++) {\n pthread_t tid;\n pthread_create(&tid, 0, thr, (void*) i);\n if (0) fprintf(1, \"mapbench[%d]: child %d\\n\", getpid(), tid);\n }\n\n for(int i = 0; i < nthread; i++)\n wait();\n\n \/\/ fprintf(1, \"mapbench[%d]: done\\n\", getpid());\n mtdisable(\"xv6-mapbench\");\n \/\/ halt();\n exit();\n}\nget rid of mtenable\/mtdisable in mapbench#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n#include \"amd64.h\"\n#include \"uspinlock.h\"\n#include \"pthread.h\"\n\nenum { readaccess = 0 };\nenum { verbose = 0 };\nenum { npg = 1 };\n\nvoid*\nthr(void *arg)\n{\n u64 tid = (u64)arg;\n\n for (int i = 0; i < 1000000; i++) {\n if (verbose && ((i % 100) == 0))\n fprintf(1, \"%d: %d ops\\n\", tid, i);\n\n volatile char *p = (char*) (0x40000UL + tid * npg * 4096);\n if (map((void *) p, npg * 4096) < 0) {\n fprintf(1, \"%d: map failed\\n\", tid);\n exit();\n }\n\n if (readaccess) {\n for (int j = 0; j < npg * 4096; j++)\n\tp[j] = '\\0';\n }\n\n if (unmap((void *) p, npg * 4096) < 0) {\n fprintf(1, \"%d: unmap failed\\n\", tid);\n exit();\n }\n }\n return 0;\n}\n\nint\nmain(int ac, char **av)\n{\n if (ac != 2) {\n fprintf(1, \"usage: %s nthreads\\n\", av[0]);\n exit();\n }\n\n int nthread = atoi(av[1]);\n\n \/\/ fprintf(1, \"mapbench[%d]: start esp %x, nthread=%d\\n\", getpid(), rrsp(), nthread);\n\n for(u64 i = 0; i < nthread; i++) {\n pthread_t tid;\n pthread_create(&tid, 0, thr, (void*) i);\n if (0) fprintf(1, \"mapbench[%d]: child %d\\n\", getpid(), tid);\n }\n\n for(int i = 0; i < nthread; i++)\n wait();\n\n \/\/ fprintf(1, \"mapbench[%d]: done\\n\", getpid());\n \/\/ halt();\n exit();\n}\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2016 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"UseAnalysisGroupings.h\"\n\n#include \"ModelBase\/src\/nodes\/Reference.h\"\n\nnamespace CodeReview\n{\n\nbool const UseAnalysisGroupings::ONLY_CONSIDER_CHANGES = true;\n\nUseAnalysisGroupings::DiffFrameInfo UseAnalysisGroupings::computeDiffFrameDependenciesAndPresentations\n\t\t(VersionControlUI::DiffFrame* diffFrame)\n{\n\tauto oldNode = diffFrame->oldVersionNode();\n\tauto newNode = diffFrame->newVersionNode();\n\n\tif (!oldNode && !newNode)\n\t\treturn {};\n\n\tQList stack;\n\tif (oldNode)\n\t\tstack << oldNode;\n\tif (newNode)\n\t\tstack << newNode;\n\n\tDiffFrameInfo diffFrameInfo;\n\n\twhile (!stack.isEmpty())\n\t{\n\t\tauto top = stack.takeLast();\n\t\tif (top)\n\t\t{\n\n\t\t\tif (auto referenceNode = DCast(top))\n\t\t\t{\n\t\t\t\tif (referenceNode->isResolved())\n\t\t\t\t\tdiffFrameInfo.refersTo_.insert(referenceNode->target());\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstack.append(top->children());\n\t\t\t\tdiffFrameInfo.shows_.insert(top);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ remove ids which are shown by this DiffFrame from the dependencies\n\tdiffFrameInfo.refersTo_.subtract(diffFrameInfo.shows_);\n\n\treturn diffFrameInfo;\n}\n\n\nQList> UseAnalysisGroupings::useAnalysisGrouping(QList\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t diffFrames)\n{\n\tQList> result;\n\n\tQHash diffFrameToInfo;\n\tQHash*> groupLists;\n\n\tfor (auto diffFrame : diffFrames)\n\t{\n\t\tauto info = computeDiffFrameDependenciesAndPresentations(diffFrame);\n\n\t\tdiffFrameToInfo.insert(diffFrame, info);\n\t}\n\n\tfor (auto diffFrame : diffFrames)\n\t{\n\t\tbool dependsOnOther = false;\n\n\t\tfor (auto otherDiffFrame : diffFrames)\n\t\t{\n\t\t\tif (diffFrame == otherDiffFrame) continue;\n\n\t\t\tif (dependsOn(diffFrameToInfo.value(diffFrame), otherDiffFrame, diffFrameToInfo.value(otherDiffFrame)))\n\t\t\t{\n\t\t\t\tdependsOnOther = true;\n\t\t\t\tauto iter = groupLists.find(otherDiffFrame);\n\t\t\t\tif (iter != groupLists.end())\n\t\t\t\t{\n\t\t\t\t\titer.value()->append(diffFrame);\n\t\t\t\t\tgroupLists.insert(diffFrame, iter.value());\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tresult.append(QList{});\n\t\t\t\t\tresult.last().append(diffFrame);\n\t\t\t\t\tresult.last().append(otherDiffFrame);\n\t\t\t\t\tgroupLists.insert(diffFrame, &result.last());\n\t\t\t\t\tgroupLists.insert(otherDiffFrame, &result.last());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!dependsOnOther && !groupLists.contains(diffFrame))\n\t\t{\n\t\t\tresult.append(QList{});\n\t\t\tresult.last().append(diffFrame);\n\t\t\tgroupLists.insert(diffFrame, &result.last());\n\t\t}\n\t}\n\treturn result;\n}\n\nbool UseAnalysisGroupings::dependsOn(DiffFrameInfo infoA,\n\t\t\t\t\t\t\t\t\t\t\t\tVersionControlUI::DiffFrame* frameB, DiffFrameInfo infoB)\n{\n\tif (ONLY_CONSIDER_CHANGES)\n\t{\n\t\tfor (auto referal : infoA.refersTo_)\n\t\t{\n\t\t\tfor (auto changesOld : frameB->oldChangedNodes())\n\t\t\t\tif (changesOld->isSameOrAncestorOf(referal))\n\t\t\t\t\treturn true;\n\t\t\tfor (auto changesNew : frameB->newChangedNodes())\n\t\t\t\tif (changesNew->isSameOrAncestorOf(referal))\n\t\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tauto refers = infoA.refersTo_;\n\t\tauto shows = infoB.shows_;\n\t\treturn !refers.intersect(shows).isEmpty();\n\t}\n}\n\n}\nFix condition for dependsOn function\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2016 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"UseAnalysisGroupings.h\"\n\n#include \"ModelBase\/src\/nodes\/Reference.h\"\n\nnamespace CodeReview\n{\n\nbool const UseAnalysisGroupings::ONLY_CONSIDER_CHANGES = true;\n\nUseAnalysisGroupings::DiffFrameInfo UseAnalysisGroupings::computeDiffFrameDependenciesAndPresentations\n\t\t(VersionControlUI::DiffFrame* diffFrame)\n{\n\tauto oldNode = diffFrame->oldVersionNode();\n\tauto newNode = diffFrame->newVersionNode();\n\n\tif (!oldNode && !newNode)\n\t\treturn {};\n\n\tQList stack;\n\tif (oldNode)\n\t\tstack << oldNode;\n\tif (newNode)\n\t\tstack << newNode;\n\n\tDiffFrameInfo diffFrameInfo;\n\n\twhile (!stack.isEmpty())\n\t{\n\t\tauto top = stack.takeLast();\n\t\tif (top)\n\t\t{\n\n\t\t\tif (auto referenceNode = DCast(top))\n\t\t\t{\n\t\t\t\tif (referenceNode->isResolved())\n\t\t\t\t\tdiffFrameInfo.refersTo_.insert(referenceNode->target());\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstack.append(top->children());\n\t\t\t\tdiffFrameInfo.shows_.insert(top);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ remove ids which are shown by this DiffFrame from the dependencies\n\tdiffFrameInfo.refersTo_.subtract(diffFrameInfo.shows_);\n\n\treturn diffFrameInfo;\n}\n\n\nQList> UseAnalysisGroupings::useAnalysisGrouping(QList\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t diffFrames)\n{\n\tQList> result;\n\n\tQHash diffFrameToInfo;\n\tQHash*> groupLists;\n\n\tfor (auto diffFrame : diffFrames)\n\t{\n\t\tauto info = computeDiffFrameDependenciesAndPresentations(diffFrame);\n\n\t\tdiffFrameToInfo.insert(diffFrame, info);\n\t}\n\n\tfor (auto diffFrame : diffFrames)\n\t{\n\t\tbool dependsOnOther = false;\n\n\t\tfor (auto otherDiffFrame : diffFrames)\n\t\t{\n\t\t\tif (diffFrame == otherDiffFrame) continue;\n\n\t\t\tif (dependsOn(diffFrameToInfo.value(diffFrame), otherDiffFrame, diffFrameToInfo.value(otherDiffFrame)))\n\t\t\t{\n\t\t\t\tdependsOnOther = true;\n\t\t\t\tauto iter = groupLists.find(otherDiffFrame);\n\t\t\t\tif (iter != groupLists.end())\n\t\t\t\t{\n\t\t\t\t\titer.value()->append(diffFrame);\n\t\t\t\t\tgroupLists.insert(diffFrame, iter.value());\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tresult.append(QList{});\n\t\t\t\t\tresult.last().append(diffFrame);\n\t\t\t\t\tresult.last().append(otherDiffFrame);\n\t\t\t\t\tgroupLists.insert(diffFrame, &result.last());\n\t\t\t\t\tgroupLists.insert(otherDiffFrame, &result.last());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!dependsOnOther && !groupLists.contains(diffFrame))\n\t\t{\n\t\t\tresult.append(QList{});\n\t\t\tresult.last().append(diffFrame);\n\t\t\tgroupLists.insert(diffFrame, &result.last());\n\t\t}\n\t}\n\treturn result;\n}\n\nbool UseAnalysisGroupings::dependsOn(DiffFrameInfo infoA,\n\t\t\t\t\t\t\t\t\t\t\t\tVersionControlUI::DiffFrame* frameB, DiffFrameInfo infoB)\n{\n\tif (ONLY_CONSIDER_CHANGES)\n\t{\n\t\tfor (auto referal : infoA.refersTo_)\n\t\t{\n\t\t\tfor (auto changesOld : frameB->oldChangedNodes())\n\t\t\t\tif (changesOld->isSameOrAncestorOf(referal) || referal->isSameOrAncestorOf(changesOld))\n\t\t\t\t\treturn true;\n\t\t\tfor (auto changesNew : frameB->newChangedNodes())\n\t\t\t\tif (changesNew->isSameOrAncestorOf(referal) || referal->isSameOrAncestorOf(changesNew))\n\t\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tauto refers = infoA.refersTo_;\n\t\tauto shows = infoB.shows_;\n\t\treturn !refers.intersect(shows).isEmpty();\n\t}\n}\n\n}\n<|endoftext|>"} {"text":"\/*\r\n* This is an open source non-commercial project. Dear PVS-Studio, please check it.\r\n* PVS-Studio Static Code Analyzer for C, C++ and C#: http:\/\/www.viva64.com\r\n*\/\r\n\/\/ Google Test library\r\n#include \r\n\r\n\/\/ uArchSim modules\r\n#include \"..\/cow_string.h\"\r\n\r\nTEST( Cow_String, Copy_Check)\r\n{\r\n CowString a {\"Hello\"};\r\n CowString b = a;\r\n ASSERT_EQ( a, b);\r\n ASSERT_EQ( static_cast(a).data(), static_cast(b).data());\r\n\r\n b += \" World!\";\r\n ASSERT_EQ( a, \"Hello\");\r\n ASSERT_EQ( b, \"Hello World!\");\r\n ASSERT_NE( a, b);\r\n ASSERT_NE( static_cast(a).data(), static_cast(b).data());\r\n}\r\n\r\nTEST( Cow_String, Assignment_Check)\r\n{\r\n CowString a {\"Hello\"};\r\n CowString b = a;\r\n ASSERT_EQ( a, b);\r\n ASSERT_EQ( static_cast(a).data(), static_cast(b).data());\r\n\r\n a = \"Goodbye!\";\r\n ASSERT_EQ( a, \"Goodbye!\");\r\n ASSERT_EQ( b, \"Hello\");\r\n ASSERT_NE( a, b);\r\n ASSERT_NE( static_cast(a).data(), static_cast(b).data());\r\n}\r\n\r\nTEST( Cow_String, Empty_String)\r\n{\r\n CowString a;\r\n ASSERT_EQ( a, \"\");\r\n CowString b = a;\r\n ASSERT_EQ( b, \"\");\r\n\r\n a = \"Hello!\";\r\n ASSERT_EQ( a, \"Hello!\");\r\n ASSERT_EQ( b, \"\");\r\n ASSERT_NE( a, b);\r\n \r\n b = \"Goodbye!\";\r\n ASSERT_EQ( b, \"Goodbye!\");\r\n ASSERT_NE( a, b);\r\n\r\n CowString c;\r\n ASSERT_EQ( c, \"\");\r\n c += \"World!\";\r\n ASSERT_EQ( c, \"World!\");\r\n}\r\n\r\nint main( int argc, char* argv[])\r\n{\r\n ::testing::InitGoogleTest( &argc, argv);\r\n ::testing::FLAGS_gtest_death_test_style = \"threadsafe\";\r\n return RUN_ALL_TESTS();\r\n}\r\nUpdate unit_test.cpp\/*\r\n* This is an open source non-commercial project. Dear PVS-Studio, please check it.\r\n* PVS-Studio Static Code Analyzer for C, C++ and C#: http:\/\/www.viva64.com\r\n*\/\r\n\/\/ Google Test library\r\n#include \r\n\r\n\/\/ uArchSim modules\r\n#include \"..\/cow_string.h\"\r\n\r\nTEST( Cow_String, Copy_Check)\r\n{\r\n CowString a {\"Hello\"};\r\n CowString b = a;\r\n ASSERT_EQ( a, b);\r\n ASSERT_EQ( static_cast(a).data(), static_cast(b).data());\r\n\r\n b += \" World!\";\r\n ASSERT_EQ( a, \"Hello\");\r\n ASSERT_EQ( b, \"Hello World!\");\r\n ASSERT_NE( a, b);\r\n ASSERT_NE( static_cast(a).data(), static_cast(b).data());\r\n}\r\n\r\nTEST( Cow_String, Assignment_Check)\r\n{\r\n CowString a {\"Hello\"};\r\n CowString b = a;\r\n ASSERT_EQ( a, b);\r\n ASSERT_EQ( static_cast(a).data(), static_cast(b).data());\r\n\r\n a = \"Goodbye!\";\r\n ASSERT_EQ( a, \"Goodbye!\");\r\n ASSERT_EQ( b, \"Hello\");\r\n ASSERT_NE( a, b);\r\n ASSERT_NE( static_cast(a).data(), static_cast(b).data());\r\n}\r\n\r\nTEST( Cow_String, Empty_String)\r\n{\r\n CowString a;\r\n ASSERT_EQ( a, \"\");\r\n CowString b = a;\r\n ASSERT_EQ( b, \"\");\r\n\r\n a = \"Hello!\";\r\n ASSERT_EQ( a, \"Hello!\");\r\n ASSERT_EQ( b, \"\");\r\n ASSERT_NE( a, b);\r\n \r\n b = \"Goodbye!\";\r\n ASSERT_EQ( b, \"Goodbye!\");\r\n ASSERT_NE( a, b);\r\n\r\n CowString c;\r\n CowString d = c;\r\n ASSERT_EQ( c, \"\");\r\n c += \"World!\";\r\n ASSERT_EQ( c, \"World!\");\r\n ASSERT_EQ( d, \"\");\r\n}\r\n\r\nint main( int argc, char* argv[])\r\n{\r\n ::testing::InitGoogleTest( &argc, argv);\r\n ::testing::FLAGS_gtest_death_test_style = \"threadsafe\";\r\n return RUN_ALL_TESTS();\r\n}\r\n<|endoftext|>"} {"text":"#include \"ConfigTypes.h\"\n\n\/*\nvoid ConfigSet::set(string name, string value){\n Strings[name] = value;\n}\n\nvoid ConfigSet::set( string name, std::map > value ){\n\tPairs[name] = value;\n}\n\nvoid ConfigSet::set( string name, std::vector < int > value ){\n\tVectors[name] = value;\n}\n\nstring ConfigSet::get(string name){\n std::map < string, string>::iterator iter = Strings.find( name );\n if( iter != Strings.end() )\n return iter->second;\n return \"\";\n}\n*\/\nCleanup<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTreeDifferenceFilter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkTreeDifferenceFilter.h\"\n\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMath.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTree.h\"\n\nvtkStandardNewMacro(vtkTreeDifferenceFilter);\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::vtkTreeDifferenceFilter()\n{\n this->SetNumberOfInputPorts(2);\n this->SetNumberOfOutputPorts(1);\n\n this->IdArrayName = 0;\n this->ComparisonArrayName = 0;\n this->OutputArrayName = 0;\n this->ComparisonArrayIsVertexData = false;\n}\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::~vtkTreeDifferenceFilter()\n{\n \/\/ release memory\n this->SetIdArrayName(0);\n this->SetComparisonArrayName(0);\n this->SetOutputArrayName(0);\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::FillInputPortInformation(int port, vtkInformation *info)\n{\n if(port == 0)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n }\n else if(port == 1)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);\n }\n\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::RequestData(\n vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector)\n{\n vtkInformation* tree1_info = inputVector[0]->GetInformationObject(0);\n vtkTree* tree1 = vtkTree::SafeDownCast(\n tree1_info->Get(vtkDataObject::DATA_OBJECT()));\n\n \/\/ Copy the structure into the output.\n vtkTree* outputTree = vtkTree::GetData(outputVector);\n\n vtkInformation* tree2_info = inputVector[1]->GetInformationObject(0);\n if(!tree2_info)\n {\n \/\/ If no second tree provided, we're done\n outputTree->CheckedShallowCopy(tree1);\n return 0;\n }\n\n vtkTree* tree2 = vtkTree::SafeDownCast(\n tree2_info->Get(vtkDataObject::DATA_OBJECT()));\n\n if (this->IdArrayName != 0)\n {\n if (!this->GenerateMapping(tree1, tree2))\n {\n return 0;\n }\n }\n else\n {\n this->VertexMap.clear();\n for (vtkIdType vertex = 0; vertex < tree1->GetNumberOfVertices(); ++vertex)\n {\n this->VertexMap[vertex] = vertex;\n }\n\n this->EdgeMap.clear();\n for (vtkIdType edge = 0; edge < tree1->GetNumberOfEdges(); ++edge)\n {\n this->VertexMap[edge] = edge;\n }\n }\n\n this->ComputeDifference(tree1, tree2);\n\n if (!outputTree->CheckedShallowCopy(tree1))\n {\n vtkErrorMacro(<<\"Invalid tree structure.\");\n return 0;\n }\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nbool vtkTreeDifferenceFilter::GenerateMapping(vtkTree *tree1, vtkTree *tree2)\n{\n this->VertexMap.clear();\n this->VertexMap.assign(tree1->GetNumberOfVertices(), -1);\n\n this->EdgeMap.clear();\n this->EdgeMap.assign(tree1->GetNumberOfEdges(), -1);\n\n vtkStringArray *nodeNames1 = vtkStringArray::SafeDownCast(\n tree1->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames1 == NULL)\n {\n vtkErrorMacro(\"tree #1's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkStringArray *nodeNames2 = vtkStringArray::SafeDownCast(\n tree2->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames2 == NULL)\n {\n vtkErrorMacro(\"tree #2's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkIdType root1 = tree1->GetRoot();\n vtkIdType root2 = tree2->GetRoot();\n\n vtkIdType edgeId1 = -1;\n vtkIdType edgeId2 = -1;\n\n \/\/ iterate over the vertex names for tree #1, finding the corresponding\n \/\/ vertex in tree #2.\n for (vtkIdType vertexItr = 0; vertexItr < nodeNames1->GetNumberOfTuples();\n ++vertexItr)\n {\n vtkIdType vertexId1 = vertexItr;\n std::string nodeName = nodeNames1->GetValue(vertexId1);\n if (nodeName.compare(\"\") == 0)\n {\n continue;\n }\n\n \/\/ record this correspondence in the maps\n vtkIdType vertexId2 = nodeNames2->LookupValue(nodeName);\n if (vertexId2 == -1)\n {\n vtkWarningMacro(\"tree #2 does not contain a vertex named \" << nodeName);\n continue;\n }\n this->VertexMap[vertexId1] = vertexId2;\n\n if (vertexId1 == root1 || vertexId2 == root2)\n {\n continue;\n }\n\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n\n \/\/ descend the tree until we reach the root, mapping parent vertices to\n \/\/ each other along the way.\n while (tree1->GetParent(vertexId1) != root1 &&\n tree2->GetParent(vertexId2) != root2)\n {\n vertexId1 = tree1->GetParent(vertexId1);\n vertexId2 = tree2->GetParent(vertexId2);\n if (this->VertexMap[vertexId1] == -1)\n {\n this->VertexMap[vertexId1] = vertexId2;\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n }\n }\n }\n\n return true;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkTreeDifferenceFilter::ComputeDifference(vtkTree *tree1, vtkTree *tree2)\n{\n if (this->ComparisonArrayName == 0)\n {\n vtkErrorMacro(\"ComparisonArrayName has not been set.\");\n return;\n }\n\n vtkDataSetAttributes *treeData1, *treeData2;\n const char *dataName;\n if (this->ComparisonArrayIsVertexData)\n {\n treeData1 = tree1->GetVertexData();\n treeData2 = tree2->GetVertexData();\n dataName = \"VertexData\";\n }\n else\n {\n treeData1 = tree1->GetEdgeData();\n treeData2 = tree2->GetEdgeData();\n dataName = \"EdgeData\";\n }\n\n vtkDoubleArray *arrayToCompare1 = vtkDoubleArray::SafeDownCast(\n treeData1->GetAbstractArray(this->ComparisonArrayName));\n if (arrayToCompare1 == NULL)\n {\n vtkErrorMacro(\"tree #1's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->IdArrayName);\n return;\n }\n\n vtkDoubleArray *arrayToCompare2 = vtkDoubleArray::SafeDownCast(\n treeData2->GetAbstractArray(this->ComparisonArrayName));\n if (arrayToCompare2 == NULL)\n {\n vtkErrorMacro(\"tree #2's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->IdArrayName);\n return;\n }\n\n vtkNew resultArray;\n resultArray->SetNumberOfValues(arrayToCompare1->GetNumberOfTuples());\n resultArray->FillComponent(0, vtkMath::Nan());\n\n if (this->OutputArrayName == 0)\n {\n resultArray->SetName(\"difference\");\n }\n else\n {\n resultArray->SetName(this->OutputArrayName);\n }\n\n vtkIdType treeId2;\n for (vtkIdType treeId1 = 0; treeId1 < arrayToCompare1->GetNumberOfTuples();\n ++treeId1)\n {\n treeId2 = this->EdgeMap[treeId1];\n double result =\n arrayToCompare1->GetValue(treeId1) - arrayToCompare2->GetValue(treeId2);\n resultArray->SetValue(treeId1, result);\n }\n\n treeData1->AddArray(resultArray.GetPointer());\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkTreeDifferenceFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n}\nFix some logic errors\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTreeDifferenceFilter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkTreeDifferenceFilter.h\"\n\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMath.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTree.h\"\n\nvtkStandardNewMacro(vtkTreeDifferenceFilter);\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::vtkTreeDifferenceFilter()\n{\n this->SetNumberOfInputPorts(2);\n this->SetNumberOfOutputPorts(1);\n\n this->IdArrayName = 0;\n this->ComparisonArrayName = 0;\n this->OutputArrayName = 0;\n this->ComparisonArrayIsVertexData = false;\n}\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::~vtkTreeDifferenceFilter()\n{\n \/\/ release memory\n this->SetIdArrayName(0);\n this->SetComparisonArrayName(0);\n this->SetOutputArrayName(0);\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::FillInputPortInformation(int port, vtkInformation *info)\n{\n if(port == 0)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n }\n else if(port == 1)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);\n }\n\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::RequestData(\n vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector)\n{\n vtkInformation* tree1_info = inputVector[0]->GetInformationObject(0);\n vtkTree* tree1 = vtkTree::SafeDownCast(\n tree1_info->Get(vtkDataObject::DATA_OBJECT()));\n\n \/\/ Copy the structure into the output.\n vtkTree* outputTree = vtkTree::GetData(outputVector);\n\n vtkInformation* tree2_info = inputVector[1]->GetInformationObject(0);\n if(!tree2_info)\n {\n \/\/ If no second tree provided, we're done\n outputTree->CheckedShallowCopy(tree1);\n return 0;\n }\n\n vtkTree* tree2 = vtkTree::SafeDownCast(\n tree2_info->Get(vtkDataObject::DATA_OBJECT()));\n\n if (this->IdArrayName != 0)\n {\n if (!this->GenerateMapping(tree1, tree2))\n {\n return 0;\n }\n }\n else\n {\n this->VertexMap.clear();\n for (vtkIdType vertex = 0; vertex < tree1->GetNumberOfVertices(); ++vertex)\n {\n this->VertexMap[vertex] = vertex;\n }\n\n this->EdgeMap.clear();\n for (vtkIdType edge = 0; edge < tree1->GetNumberOfEdges(); ++edge)\n {\n this->EdgeMap[edge] = edge;\n }\n }\n\n this->ComputeDifference(tree1, tree2);\n\n if (!outputTree->CheckedShallowCopy(tree1))\n {\n vtkErrorMacro(<<\"Invalid tree structure.\");\n return 0;\n }\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nbool vtkTreeDifferenceFilter::GenerateMapping(vtkTree *tree1, vtkTree *tree2)\n{\n this->VertexMap.clear();\n this->VertexMap.assign(tree1->GetNumberOfVertices(), -1);\n\n this->EdgeMap.clear();\n this->EdgeMap.assign(tree1->GetNumberOfEdges(), -1);\n\n vtkStringArray *nodeNames1 = vtkStringArray::SafeDownCast(\n tree1->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames1 == NULL)\n {\n vtkErrorMacro(\"tree #1's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkStringArray *nodeNames2 = vtkStringArray::SafeDownCast(\n tree2->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames2 == NULL)\n {\n vtkErrorMacro(\"tree #2's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkIdType root1 = tree1->GetRoot();\n vtkIdType root2 = tree2->GetRoot();\n\n vtkIdType edgeId1 = -1;\n vtkIdType edgeId2 = -1;\n\n \/\/ iterate over the vertex names for tree #1, finding the corresponding\n \/\/ vertex in tree #2.\n for (vtkIdType vertexItr = 0; vertexItr < nodeNames1->GetNumberOfTuples();\n ++vertexItr)\n {\n vtkIdType vertexId1 = vertexItr;\n std::string nodeName = nodeNames1->GetValue(vertexId1);\n if (nodeName.compare(\"\") == 0)\n {\n continue;\n }\n\n \/\/ record this correspondence in the maps\n vtkIdType vertexId2 = nodeNames2->LookupValue(nodeName);\n if (vertexId2 == -1)\n {\n vtkWarningMacro(\"tree #2 does not contain a vertex named \" << nodeName);\n continue;\n }\n this->VertexMap[vertexId1] = vertexId2;\n\n if (vertexId1 == root1 || vertexId2 == root2)\n {\n continue;\n }\n\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n\n \/\/ descend the tree until we reach the root, mapping parent vertices to\n \/\/ each other along the way.\n while (tree1->GetParent(vertexId1) != root1 &&\n tree2->GetParent(vertexId2) != root2)\n {\n vertexId1 = tree1->GetParent(vertexId1);\n vertexId2 = tree2->GetParent(vertexId2);\n if (this->VertexMap[vertexId1] == -1)\n {\n this->VertexMap[vertexId1] = vertexId2;\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n }\n }\n }\n\n return true;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkTreeDifferenceFilter::ComputeDifference(vtkTree *tree1, vtkTree *tree2)\n{\n if (this->ComparisonArrayName == 0)\n {\n vtkErrorMacro(\"ComparisonArrayName has not been set.\");\n return;\n }\n\n vtkDataSetAttributes *treeData1, *treeData2;\n const char *dataName;\n if (this->ComparisonArrayIsVertexData)\n {\n treeData1 = tree1->GetVertexData();\n treeData2 = tree2->GetVertexData();\n dataName = \"VertexData\";\n }\n else\n {\n treeData1 = tree1->GetEdgeData();\n treeData2 = tree2->GetEdgeData();\n dataName = \"EdgeData\";\n }\n\n vtkDoubleArray *arrayToCompare1 = vtkDoubleArray::SafeDownCast(\n treeData1->GetAbstractArray(this->ComparisonArrayName));\n if (arrayToCompare1 == NULL)\n {\n vtkErrorMacro(\"tree #1's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->IdArrayName);\n return;\n }\n\n vtkDoubleArray *arrayToCompare2 = vtkDoubleArray::SafeDownCast(\n treeData2->GetAbstractArray(this->ComparisonArrayName));\n if (arrayToCompare2 == NULL)\n {\n vtkErrorMacro(\"tree #2's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->IdArrayName);\n return;\n }\n\n vtkNew resultArray;\n resultArray->SetNumberOfValues(arrayToCompare1->GetNumberOfTuples());\n resultArray->FillComponent(0, vtkMath::Nan());\n\n if (this->OutputArrayName == 0)\n {\n resultArray->SetName(\"difference\");\n }\n else\n {\n resultArray->SetName(this->OutputArrayName);\n }\n\n vtkIdType treeId2;\n for (vtkIdType treeId1 = 0; treeId1 < arrayToCompare1->GetNumberOfTuples();\n ++treeId1)\n {\n if (this->ComparisonArrayIsVertexData)\n {\n treeId2 = this->VertexMap[treeId1];\n }\n else\n {\n treeId2 = this->EdgeMap[treeId1];\n }\n double result =\n arrayToCompare1->GetValue(treeId1) - arrayToCompare2->GetValue(treeId2);\n resultArray->SetValue(treeId1, result);\n }\n\n treeData1->AddArray(resultArray.GetPointer());\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkTreeDifferenceFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#define\tEPOLL_EVENT_COUNT\t128\n\nstruct EventPollState {\n\tint ep_;\n};\n\nEventPoll::EventPoll(void)\n: log_(\"\/event\/poll\"),\n read_poll_(),\n write_poll_(),\n state_(new EventPollState())\n{\n\tstate_->ep_ = epoll_create(EPOLL_EVENT_COUNT);\n\tASSERT(state_->ep_ != -1);\n}\n\nEventPoll::~EventPoll()\n{\n\tASSERT(read_poll_.empty());\n\tASSERT(write_poll_.empty());\n\n\tif (state_ != NULL) {\n\t\tif (state_->ep_ != -1) {\n\t\t\tclose(state_->ep_);\n\t\t\tstate_->ep_ = -1;\n\t\t}\n\t\tdelete state_;\n\t\tstate_ = NULL;\n\t}\n}\n\nAction *\nEventPoll::poll(const Type& type, int fd, EventCallback *cb)\n{\n\tASSERT(fd != -1);\n\n\tEventPoll::PollHandler *poll_handler;\n\tstruct epoll_event eev;\n\tbool unique = true;\n\teev.data.fd = fd;\n\tswitch (type) {\n\tcase EventPoll::Readable:\n\t\tASSERT(read_poll_.find(fd) == read_poll_.end());\n\t\tunique = write_poll_.find(fd) == write_poll_.end();\n\t\tpoll_handler = &read_poll_[fd];\n\t\teev.events = EPOLLIN | (unique ? 0 : EPOLLOUT);\n\t\tbreak;\n\tcase EventPoll::Writable:\n\t\tASSERT(write_poll_.find(fd) == write_poll_.end());\n\t\tunique = read_poll_.find(fd) == read_poll_.end();\n\t\tpoll_handler = &write_poll_[fd];\n\t\teev.events = EPOLLOUT | (unique ? 0 : EPOLLIN);\n\t\tbreak;\n\tdefault:\n\t\tNOTREACHED();\n\t}\n\tint rv = ::epoll_ctl(state_->ep_, unique ? EPOLL_CTL_ADD : EPOLL_CTL_MOD, fd, &eev);\n\tif (rv == -1)\n\t\tHALT(log_) << \"Could not add event to epoll.\";\n\tASSERT(rv == 0);\n\tASSERT(poll_handler->action_ == NULL);\n\tpoll_handler->callback_ = cb;\n\tAction *a = new EventPoll::PollAction(this, type, fd);\n\treturn (a);\n}\n\nvoid\nEventPoll::cancel(const Type& type, int fd)\n{\n\tEventPoll::PollHandler *poll_handler;\n\n\tstruct epoll_event eev;\n\tbool unique = true;\n\teev.data.fd = fd;\n\tswitch (type) {\n\tcase EventPoll::Readable:\n\t\tASSERT(read_poll_.find(fd) != read_poll_.end());\n\t\tunique = write_poll_.find(fd) == write_poll_.end();\n\t\tpoll_handler = &read_poll_[fd];\n\t\tpoll_handler->cancel();\n\t\tread_poll_.erase(fd);\n\t\teev.events = unique ? 0 : EPOLLOUT;\n\t\tbreak;\n\tcase EventPoll::Writable:\n\t\tASSERT(write_poll_.find(fd) != write_poll_.end());\n\t\tunique = read_poll_.find(fd) == read_poll_.end();\n\t\tpoll_handler = &write_poll_[fd];\n\t\tpoll_handler->cancel();\n\t\twrite_poll_.erase(fd);\n\t\teev.events = unique ? 0 : EPOLLIN;\n\t\tbreak;\n\t}\n\tint rv = ::epoll_ctl(state_->ep_, unique ? EPOLL_CTL_DEL : EPOLL_CTL_MOD, fd, &eev);\n\tif (rv == -1)\n\t\tHALT(log_) << \"Could not delete event from epoll.\";\n\tASSERT(rv == 0);\n}\n\nvoid\nEventPoll::wait(int ms)\n{\n\tstruct timespec ts;\n\n\tts.tv_sec = ms \/ 1000;\n\tts.tv_nsec = (ms % 1000) * 1000000;\n\n\tif (idle()) {\n\t\tif (ms != -1) {\n\t\t\tint rv;\n\n\t\t\trv = nanosleep(&ts, NULL);\n\t\t\tASSERT(rv != -1);\n\t\t}\n\t\treturn;\n\t}\n\n\tstruct epoll_event eev[EPOLL_EVENT_COUNT];\n\tint evcnt = ::epoll_wait(state_->ep_, eev, EPOLL_EVENT_COUNT, ms);\n\tif (evcnt == -1) {\n\t\tif (errno == EINTR) {\n\t\t\tINFO(log_) << \"Received interrupt, ceasing polling until stop handlers have run.\";\n\t\t\treturn;\n\t\t}\n\t\tHALT(log_) << \"Could not poll epoll.\";\n\t}\n\n\tint i;\n\tfor (i = 0; i < evcnt; i++) {\n\t\tstruct epoll_event *ev = &eev[i];\n\t\tEventPoll::PollHandler *poll_handler;\n\t\tif ((ev->events & EPOLLIN) != 0) {\n\t\t\tASSERT(read_poll_.find(ev->data.fd) != read_poll_.end());\n\t\t\tpoll_handler = &read_poll_[ev->data.fd];\n\t\t\tpoll_handler->callback(Event::Done);\n\t\t}\n\n\t\tif ((ev->events & EPOLLOUT) != 0) {\n\t\t\tASSERT(write_poll_.find(ev->data.fd) != write_poll_.end());\n\t\t\tpoll_handler = &write_poll_[ev->data.fd];\n\t\t\tpoll_handler->callback(Event::Done);\n\t\t}\n\n\t\tif ((ev->events & EPOLLIN) == 0 && (ev->events & EPOLLOUT) == 0) {\n\t\t\tif (read_poll_.find(ev->data.fd) != read_poll_.end()) {\n\t\t\t\tpoll_handler = &read_poll_[ev->data.fd];\n\t\t\t} else if (write_poll_.find(ev->data.fd) != write_poll_.end()) {\n\t\t\t\tpoll_handler = &write_poll_[ev->data.fd];\n\t\t\t} else {\n\t\t\t\tHALT(log_) << \"Unexpected poll fd.\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ((ev->events & EPOLLERR) != 0) {\n\t\t\t\tpoll_handler->callback(Event::Error);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ((ev->events & EPOLLHUP) != 0) {\n\t\t\t\tpoll_handler->callback(Event::EOS);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tHALT(log_) << \"Unexpected poll events: \" << ev->events;\n\t\t}\n\t}\n}\nIgnore hangup on write polls.#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#define\tEPOLL_EVENT_COUNT\t128\n\nstruct EventPollState {\n\tint ep_;\n};\n\nEventPoll::EventPoll(void)\n: log_(\"\/event\/poll\"),\n read_poll_(),\n write_poll_(),\n state_(new EventPollState())\n{\n\tstate_->ep_ = epoll_create(EPOLL_EVENT_COUNT);\n\tASSERT(state_->ep_ != -1);\n}\n\nEventPoll::~EventPoll()\n{\n\tASSERT(read_poll_.empty());\n\tASSERT(write_poll_.empty());\n\n\tif (state_ != NULL) {\n\t\tif (state_->ep_ != -1) {\n\t\t\tclose(state_->ep_);\n\t\t\tstate_->ep_ = -1;\n\t\t}\n\t\tdelete state_;\n\t\tstate_ = NULL;\n\t}\n}\n\nAction *\nEventPoll::poll(const Type& type, int fd, EventCallback *cb)\n{\n\tASSERT(fd != -1);\n\n\tEventPoll::PollHandler *poll_handler;\n\tstruct epoll_event eev;\n\tbool unique = true;\n\teev.data.fd = fd;\n\tswitch (type) {\n\tcase EventPoll::Readable:\n\t\tASSERT(read_poll_.find(fd) == read_poll_.end());\n\t\tunique = write_poll_.find(fd) == write_poll_.end();\n\t\tpoll_handler = &read_poll_[fd];\n\t\teev.events = EPOLLIN | (unique ? 0 : EPOLLOUT);\n\t\tbreak;\n\tcase EventPoll::Writable:\n\t\tASSERT(write_poll_.find(fd) == write_poll_.end());\n\t\tunique = read_poll_.find(fd) == read_poll_.end();\n\t\tpoll_handler = &write_poll_[fd];\n\t\teev.events = EPOLLOUT | (unique ? 0 : EPOLLIN);\n\t\tbreak;\n\tdefault:\n\t\tNOTREACHED();\n\t}\n\tint rv = ::epoll_ctl(state_->ep_, unique ? EPOLL_CTL_ADD : EPOLL_CTL_MOD, fd, &eev);\n\tif (rv == -1)\n\t\tHALT(log_) << \"Could not add event to epoll.\";\n\tASSERT(rv == 0);\n\tASSERT(poll_handler->action_ == NULL);\n\tpoll_handler->callback_ = cb;\n\tAction *a = new EventPoll::PollAction(this, type, fd);\n\treturn (a);\n}\n\nvoid\nEventPoll::cancel(const Type& type, int fd)\n{\n\tEventPoll::PollHandler *poll_handler;\n\n\tstruct epoll_event eev;\n\tbool unique = true;\n\teev.data.fd = fd;\n\tswitch (type) {\n\tcase EventPoll::Readable:\n\t\tASSERT(read_poll_.find(fd) != read_poll_.end());\n\t\tunique = write_poll_.find(fd) == write_poll_.end();\n\t\tpoll_handler = &read_poll_[fd];\n\t\tpoll_handler->cancel();\n\t\tread_poll_.erase(fd);\n\t\teev.events = unique ? 0 : EPOLLOUT;\n\t\tbreak;\n\tcase EventPoll::Writable:\n\t\tASSERT(write_poll_.find(fd) != write_poll_.end());\n\t\tunique = read_poll_.find(fd) == read_poll_.end();\n\t\tpoll_handler = &write_poll_[fd];\n\t\tpoll_handler->cancel();\n\t\twrite_poll_.erase(fd);\n\t\teev.events = unique ? 0 : EPOLLIN;\n\t\tbreak;\n\t}\n\tint rv = ::epoll_ctl(state_->ep_, unique ? EPOLL_CTL_DEL : EPOLL_CTL_MOD, fd, &eev);\n\tif (rv == -1)\n\t\tHALT(log_) << \"Could not delete event from epoll.\";\n\tASSERT(rv == 0);\n}\n\nvoid\nEventPoll::wait(int ms)\n{\n\tstruct timespec ts;\n\n\tts.tv_sec = ms \/ 1000;\n\tts.tv_nsec = (ms % 1000) * 1000000;\n\n\tif (idle()) {\n\t\tif (ms != -1) {\n\t\t\tint rv;\n\n\t\t\trv = nanosleep(&ts, NULL);\n\t\t\tASSERT(rv != -1);\n\t\t}\n\t\treturn;\n\t}\n\n\tstruct epoll_event eev[EPOLL_EVENT_COUNT];\n\tint evcnt = ::epoll_wait(state_->ep_, eev, EPOLL_EVENT_COUNT, ms);\n\tif (evcnt == -1) {\n\t\tif (errno == EINTR) {\n\t\t\tINFO(log_) << \"Received interrupt, ceasing polling until stop handlers have run.\";\n\t\t\treturn;\n\t\t}\n\t\tHALT(log_) << \"Could not poll epoll.\";\n\t}\n\n\tint i;\n\tfor (i = 0; i < evcnt; i++) {\n\t\tstruct epoll_event *ev = &eev[i];\n\t\tEventPoll::PollHandler *poll_handler;\n\t\tif ((ev->events & EPOLLIN) != 0) {\n\t\t\tASSERT(read_poll_.find(ev->data.fd) != read_poll_.end());\n\t\t\tpoll_handler = &read_poll_[ev->data.fd];\n\t\t\tpoll_handler->callback(Event::Done);\n\t\t}\n\n\t\tif ((ev->events & EPOLLOUT) != 0) {\n\t\t\tASSERT(write_poll_.find(ev->data.fd) != write_poll_.end());\n\t\t\tpoll_handler = &write_poll_[ev->data.fd];\n\t\t\tpoll_handler->callback(Event::Done);\n\t\t}\n\n\t\tif ((ev->events & EPOLLIN) == 0 && (ev->events & EPOLLOUT) == 0) {\n\t\t\tif (read_poll_.find(ev->data.fd) != read_poll_.end()) {\n\t\t\t\tpoll_handler = &read_poll_[ev->data.fd];\n\t\t\t} else if (write_poll_.find(ev->data.fd) != write_poll_.end()) {\n\t\t\t\tpoll_handler = &write_poll_[ev->data.fd];\n\n\t\t\t\tif ((ev->events & (EPOLLERR | EPOLLHUP)) == EPOLLHUP) {\n\t\t\t\t\tDEBUG(log_) << \"Got EPOLLHUP on write poll.\";\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tHALT(log_) << \"Unexpected poll fd.\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ((ev->events & EPOLLERR) != 0) {\n\t\t\t\tpoll_handler->callback(Event::Error);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ((ev->events & EPOLLHUP) != 0) {\n\t\t\t\tpoll_handler->callback(Event::EOS);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tHALT(log_) << \"Unexpected poll events: \" << ev->events;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2016, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#include \"session.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nvoid LSession::stopall(){\n stopping = true;\n for(int i=0; istate()!=QProcess::NotRunning){ PROCS[i]->kill(); }\n }\n QCoreApplication::processEvents();\n for(int i=0; istate()!=QProcess::NotRunning){ PROCS[i]->terminate(); }\n }\n QCoreApplication::exit(0);\n}\n\nvoid LSession::procFinished(){\n \/\/Go through and check the status on all the procs to determine which one finished\n int stopped = 0;\n \/\/qDebug() << \"Got Process Stopped Signal:\";\n for(int i=0; istate()==QProcess::NotRunning){\n \/\/qDebug() << \" - Stopped:\" << PROCS[i]->objectName();\n stopped++;\n if(!stopping){\n \/\/See if this process is the main desktop binary\n if(PROCS[i]->objectName()==\"runtime\"){\n qDebug() << \"Got Desktop Process Finished:\" << PROCS[i]->exitCode();\n \/\/if(PROCS[i]->exitCode()==787){ PROCS[i]->start(QIODevice::ReadOnly); } \/\/special internal restart code\n \/\/else{\n stopall(); \/\/}\n }else if(PROCS[i]->objectName()==\"wm\" && wmfails<2){ wmfails++; PROCS[i]->start(QIODevice::ReadOnly); wmTimer->start(); } \/\/restart the WM\n \/\/if(PROCS[i]->program().section(\"\/\",-1) == \"lumina-desktop\"){ stopall(); } \/\/start closing down everything\n \/\/else{ PROCS[i]->start(QIODevice::ReadOnly); } \/\/restart the process\n \/\/break;\n }\n }\n }\n \/\/qDebug() << \" - Final Count:\" << stopped << stopping;\n if(stopping || stopped==PROCS.length()){\n \/\/Note about compton: It does not like running multiple sessions under the *same user*\n \/\/ (even on different displays). Run a blanket killall on it when closing down so that\n \/\/ any other Lumina sessions will automatically restart compton on that specific display\n QProcess::execute(\"killall compton\");\n QCoreApplication::exit(0);\n }else{\n \/\/Make sure we restart the process as needed\n for(int i=0; istate()==QProcess::NotRunning){\n \/\/runtime\/wm processes have special restart rules above\n if(PROCS[i]->objectName()!=\"runtime\" && PROCS[i]->objectName()!=\"wm\"){\n PROCS[i]->start(QIODevice::ReadOnly);\n }\n }\n }\n }\n}\n\nvoid LSession::startProcess(QString ID, QString command, QStringList watchfiles){\n QString dir = QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/logs\";\n QString display = QString(getenv(\"DISPLAY\")).section(\":\",1,1);\n if(!QFile::exists(dir)){ QDir tmp(dir); tmp.mkpath(dir); }\n QString logfile = dir+\"\/\"+ID+\"_\"+display+\".log\";\n if(QFile::exists(logfile+\".old\")){ QFile::remove(logfile+\".old\"); }\n if(QFile::exists(logfile)){ QFile::rename(logfile,logfile+\".old\"); }\n\n LProcess *proc = new LProcess(ID, watchfiles);\n proc->setProcessChannelMode(QProcess::MergedChannels);\n proc->setProcessEnvironment( QProcessEnvironment::systemEnvironment() );\n proc->setStandardOutputFile(logfile);\n proc->setObjectName(ID);\n if(ID==\"runtime\"){\n \/\/Bypass for a hidden dbus file requirement for Qt itself (Qt 5.5.1+?)\n if(!QFile::exists(\"\/etc\/machine-id\") && !QFile::exists(\"\/var\/db\/dbus\/machine-id\")){\n if(LUtils::isValidBinary(\"dbus-uuidgen\") && LUtils::runCmd(\"dbus-uuidgen --ensure\") ){ } \/\/good - the UUID was created successfully\n else if(LUtils::isValidBinary(\"dbus-launch\")){ command.prepend(\"dbus-launch --exit-with-session \"); }\n else{\n \/\/create a simple DBUS UUID and put it in the universal-fallback location (OS-independent)\n \/\/ TO-DO - root vs user level permissions issue?\n qDebug() << \"Could not find '\/etc\/machine-id' or '\/var\/db\/dbus\/machine-id': Qt will most likely crash. \\nPlease run 'dbus-uuidgen --ensure' with root permissions to generate this file if Lumina does not start properly.\";\n }\n }\n }\n proc->start(command, QIODevice::ReadOnly);\n connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(procFinished()) );\n PROCS << proc;\n}\n\nvoid LSession::setupCompositor(bool force){\n \/\/Compositing manager\n QSettings settings(\"lumina-desktop\",\"sessionsettings\");\n if(settings.value(\"enableCompositing\",false).toBool() || force){\n if(LUtils::isValidBinary(\"compton\")){\n \/\/Compton available - check the config file\n QString set = QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/compton.conf\";\n if(!QFile::exists(set)){\n\t if(QFile::exists(LOS::LuminaShare()+\"\/compton.conf\")){\n\t QFile::copy(LOS::LuminaShare()+\"\/compton.conf\", set);\n\t }\n }\n\t\/\/Auto-detect if GLX is available on the system and turn it on\/off as needed\n bool startcompton = true;\n if(LUtils::isValidBinary(\"glxinfo\")){\n\t bool hasAccel =! LUtils::getCmdOutput(\"glxinfo -B\").filter(\"direct rendering:\").filter(\"Yes\").isEmpty();\n\t qDebug() << \"Detected GPU Acceleration:\" << hasAccel;\n\t QStringList info = LUtils::readFile(set);\n\t for(int i=0; i 1000000], [1.2.3 -> 1002003], [0.6.1 -> 6001]\n qDebug() << \"[Lumina] Checking User Files\";\n QSettings sset(\"lumina-desktop\", \"sessionsettings\");\n QString OVS = sset.value(\"DesktopVersion\",\"0\").toString(); \/\/Old Version String\n qDebug() << \" - Old Version:\" << OVS;\n qDebug() << \" - Current Version:\" << LDesktopUtils::LuminaDesktopVersion();\n bool changed = LDesktopUtils::checkUserFiles(OVS, LDesktopUtils::LuminaDesktopVersion());\n qDebug() << \" - Made Changes:\" << changed;\n if(changed){\n \/\/Save the current version of the session to the settings file (for next time)\n sset.setValue(\"DesktopVersion\", LDesktopUtils::LuminaDesktopVersion());\n }\n qDebug() << \"Finished with user files check\";\n}\nEnsure that the Fluxbox background\/wallpaper setter is disabled before Lumina starts it up\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2016, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#include \"session.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nvoid LSession::stopall(){\n stopping = true;\n for(int i=0; istate()!=QProcess::NotRunning){ PROCS[i]->kill(); }\n }\n QCoreApplication::processEvents();\n for(int i=0; istate()!=QProcess::NotRunning){ PROCS[i]->terminate(); }\n }\n QCoreApplication::exit(0);\n}\n\nvoid LSession::procFinished(){\n \/\/Go through and check the status on all the procs to determine which one finished\n int stopped = 0;\n \/\/qDebug() << \"Got Process Stopped Signal:\";\n for(int i=0; istate()==QProcess::NotRunning){\n \/\/qDebug() << \" - Stopped:\" << PROCS[i]->objectName();\n stopped++;\n if(!stopping){\n \/\/See if this process is the main desktop binary\n if(PROCS[i]->objectName()==\"runtime\"){\n qDebug() << \"Got Desktop Process Finished:\" << PROCS[i]->exitCode();\n \/\/if(PROCS[i]->exitCode()==787){ PROCS[i]->start(QIODevice::ReadOnly); } \/\/special internal restart code\n \/\/else{\n stopall(); \/\/}\n }else if(PROCS[i]->objectName()==\"wm\" && wmfails<2){ wmfails++; PROCS[i]->start(QIODevice::ReadOnly); wmTimer->start(); } \/\/restart the WM\n \/\/if(PROCS[i]->program().section(\"\/\",-1) == \"lumina-desktop\"){ stopall(); } \/\/start closing down everything\n \/\/else{ PROCS[i]->start(QIODevice::ReadOnly); } \/\/restart the process\n \/\/break;\n }\n }\n }\n \/\/qDebug() << \" - Final Count:\" << stopped << stopping;\n if(stopping || stopped==PROCS.length()){\n \/\/Note about compton: It does not like running multiple sessions under the *same user*\n \/\/ (even on different displays). Run a blanket killall on it when closing down so that\n \/\/ any other Lumina sessions will automatically restart compton on that specific display\n QProcess::execute(\"killall compton\");\n QCoreApplication::exit(0);\n }else{\n \/\/Make sure we restart the process as needed\n for(int i=0; istate()==QProcess::NotRunning){\n \/\/runtime\/wm processes have special restart rules above\n if(PROCS[i]->objectName()!=\"runtime\" && PROCS[i]->objectName()!=\"wm\"){\n PROCS[i]->start(QIODevice::ReadOnly);\n }\n }\n }\n }\n}\n\nvoid LSession::startProcess(QString ID, QString command, QStringList watchfiles){\n QString dir = QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/logs\";\n QString display = QString(getenv(\"DISPLAY\")).section(\":\",1,1);\n if(!QFile::exists(dir)){ QDir tmp(dir); tmp.mkpath(dir); }\n QString logfile = dir+\"\/\"+ID+\"_\"+display+\".log\";\n if(QFile::exists(logfile+\".old\")){ QFile::remove(logfile+\".old\"); }\n if(QFile::exists(logfile)){ QFile::rename(logfile,logfile+\".old\"); }\n\n LProcess *proc = new LProcess(ID, watchfiles);\n proc->setProcessChannelMode(QProcess::MergedChannels);\n proc->setProcessEnvironment( QProcessEnvironment::systemEnvironment() );\n proc->setStandardOutputFile(logfile);\n proc->setObjectName(ID);\n if(ID==\"runtime\"){\n \/\/Bypass for a hidden dbus file requirement for Qt itself (Qt 5.5.1+?)\n if(!QFile::exists(\"\/etc\/machine-id\") && !QFile::exists(\"\/var\/db\/dbus\/machine-id\")){\n if(LUtils::isValidBinary(\"dbus-uuidgen\") && LUtils::runCmd(\"dbus-uuidgen --ensure\") ){ } \/\/good - the UUID was created successfully\n else if(LUtils::isValidBinary(\"dbus-launch\")){ command.prepend(\"dbus-launch --exit-with-session \"); }\n else{\n \/\/create a simple DBUS UUID and put it in the universal-fallback location (OS-independent)\n \/\/ TO-DO - root vs user level permissions issue?\n qDebug() << \"Could not find '\/etc\/machine-id' or '\/var\/db\/dbus\/machine-id': Qt will most likely crash. \\nPlease run 'dbus-uuidgen --ensure' with root permissions to generate this file if Lumina does not start properly.\";\n }\n }\n }\n proc->start(command, QIODevice::ReadOnly);\n connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(procFinished()) );\n PROCS << proc;\n}\n\nvoid LSession::setupCompositor(bool force){\n \/\/Compositing manager\n QSettings settings(\"lumina-desktop\",\"sessionsettings\");\n if(settings.value(\"enableCompositing\",false).toBool() || force){\n if(LUtils::isValidBinary(\"compton\")){\n \/\/Compton available - check the config file\n QString set = QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/compton.conf\";\n if(!QFile::exists(set)){\n\t if(QFile::exists(LOS::LuminaShare()+\"\/compton.conf\")){\n\t QFile::copy(LOS::LuminaShare()+\"\/compton.conf\", set);\n\t }\n }\n\t\/\/Auto-detect if GLX is available on the system and turn it on\/off as needed\n bool startcompton = true;\n if(LUtils::isValidBinary(\"glxinfo\")){\n\t bool hasAccel =! LUtils::getCmdOutput(\"glxinfo -B\").filter(\"direct rendering:\").filter(\"Yes\").isEmpty();\n\t qDebug() << \"Detected GPU Acceleration:\" << hasAccel;\n\t QStringList info = LUtils::readFile(set);\n\t for(int i=0; i 1000000], [1.2.3 -> 1002003], [0.6.1 -> 6001]\n qDebug() << \"[Lumina] Checking User Files\";\n QSettings sset(\"lumina-desktop\", \"sessionsettings\");\n QString OVS = sset.value(\"DesktopVersion\",\"0\").toString(); \/\/Old Version String\n qDebug() << \" - Old Version:\" << OVS;\n qDebug() << \" - Current Version:\" << LDesktopUtils::LuminaDesktopVersion();\n bool changed = LDesktopUtils::checkUserFiles(OVS, LDesktopUtils::LuminaDesktopVersion());\n qDebug() << \" - Made Changes:\" << changed;\n if(changed){\n \/\/Save the current version of the session to the settings file (for next time)\n sset.setValue(\"DesktopVersion\", LDesktopUtils::LuminaDesktopVersion());\n }\n qDebug() << \"Finished with user files check\";\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: waitsymbol.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: obo $ $Date: 2007-07-17 14:43:26 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_slideshow.hxx\"\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \"waitsymbol.hxx\"\n#include \"eventmultiplexer.hxx\"\n\n#include \n\n\nusing namespace com::sun::star;\n\nnamespace slideshow {\nnamespace internal {\n\nconst sal_Int32 LEFT_BORDER_SPACE = 10;\nconst sal_Int32 LOWER_BORDER_SPACE = 10;\n\nWaitSymbolSharedPtr WaitSymbol::create( const uno::Reference& xBitmap,\n ScreenUpdater& rScreenUpdater,\n EventMultiplexer& rEventMultiplexer,\n const UnoViewContainer& rViewContainer )\n{\n WaitSymbolSharedPtr pRet(\n new WaitSymbol( xBitmap,\n rScreenUpdater,\n rViewContainer ));\n\n rEventMultiplexer.addViewHandler( pRet );\n\n return pRet;\n}\n\nWaitSymbol::WaitSymbol( uno::Reference const & xBitmap,\n ScreenUpdater& rScreenUpdater,\n const UnoViewContainer& rViewContainer ) :\n mxBitmap(xBitmap),\n maViews(),\n mrScreenUpdater( rScreenUpdater ),\n mbVisible(false)\n{\n std::for_each( rViewContainer.begin(),\n rViewContainer.end(),\n boost::bind( &WaitSymbol::viewAdded,\n this,\n _1 ));\n}\n\nvoid WaitSymbol::setVisible( const bool bVisible )\n{\n if( mbVisible != bVisible )\n {\n mbVisible = bVisible;\n\n ViewsVecT::const_iterator aIter( maViews.begin() );\n ViewsVecT::const_iterator const aEnd ( maViews.end() );\n while( aIter != aEnd )\n {\n if( aIter->second )\n {\n if( bVisible )\n aIter->second->show();\n else\n aIter->second->hide();\n }\n\n ++aIter;\n }\n\n \/\/ sprites changed, need a screen update for this frame.\n mrScreenUpdater.requestImmediateUpdate();\n }\n}\n\nbasegfx::B2DPoint WaitSymbol::calcSpritePos(\n UnoViewSharedPtr const & rView ) const\n{\n const uno::Reference xBitmap( rView->getCanvas()->getUNOCanvas(),\n uno::UNO_QUERY_THROW );\n const geometry::IntegerSize2D realSize( xBitmap->getSize() );\n return basegfx::B2DPoint(\n std::min( realSize.Width, LEFT_BORDER_SPACE ),\n std::max( 0, realSize.Height - mxBitmap->getSize().Height\n - LOWER_BORDER_SPACE ) );\n}\n\nvoid WaitSymbol::viewAdded( const UnoViewSharedPtr& rView )\n{\n cppcanvas::CustomSpriteSharedPtr sprite;\n\n try\n {\n const geometry::IntegerSize2D spriteSize( mxBitmap->getSize() );\n sprite = rView->createSprite( basegfx::B2DVector( spriteSize.Width,\n spriteSize.Height ),\n 1000.0 ); \/\/ sprite should be in front of all\n \/\/ other sprites\n rendering::ViewState viewState;\n canvas::tools::initViewState( viewState );\n rendering::RenderState renderState;\n canvas::tools::initRenderState( renderState );\n sprite->getContentCanvas()->getUNOCanvas()->drawBitmap(\n mxBitmap, viewState, renderState );\n\n sprite->setAlpha( 0.9 );\n sprite->movePixel( calcSpritePos( rView ) );\n if( mbVisible )\n sprite->show();\n }\n catch( uno::Exception& )\n {\n OSL_ENSURE( false,\n rtl::OUStringToOString(\n comphelper::anyToString( cppu::getCaughtException() ),\n RTL_TEXTENCODING_UTF8 ).getStr() );\n }\n\n maViews.push_back( ViewsVecT::value_type( rView, sprite ) );\n}\n\nvoid WaitSymbol::viewRemoved( const UnoViewSharedPtr& rView )\n{\n maViews.erase(\n std::remove_if(\n maViews.begin(), maViews.end(),\n boost::bind(\n std::equal_to(),\n rView,\n \/\/ select view:\n boost::bind( std::select1st(), _1 ) ) ),\n maViews.end() );\n}\n\nvoid WaitSymbol::viewChanged( const UnoViewSharedPtr& rView )\n{\n \/\/ find entry corresponding to modified view\n ViewsVecT::iterator aModifiedEntry(\n std::find_if(\n maViews.begin(),\n maViews.end(),\n boost::bind(\n std::equal_to(),\n rView,\n \/\/ select view:\n boost::bind( std::select1st(), _1 ))));\n\n OSL_ASSERT( aModifiedEntry != maViews.end() );\n if( aModifiedEntry == maViews.end() )\n return;\n\n if( aModifiedEntry->second )\n aModifiedEntry->second->movePixel(\n calcSpritePos(aModifiedEntry->first) );\n}\n\nvoid WaitSymbol::viewsChanged()\n{\n \/\/ reposition sprites on all views\n ViewsVecT::const_iterator aIter( maViews.begin() );\n ViewsVecT::const_iterator const aEnd ( maViews.end() );\n while( aIter != aEnd )\n {\n if( aIter->second )\n aIter->second->movePixel(\n calcSpritePos( aIter->first ));\n ++aIter;\n }\n}\n\n} \/\/ namespace internal\n} \/\/ namespace presentation\nINTEGRATION: CWS changefileheader (1.10.46); FILE MERGED 2008\/03\/31 14:00:15 rt 1.10.46.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: waitsymbol.cxx,v $\n * $Revision: 1.11 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_slideshow.hxx\"\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \"waitsymbol.hxx\"\n#include \"eventmultiplexer.hxx\"\n\n#include \n\n\nusing namespace com::sun::star;\n\nnamespace slideshow {\nnamespace internal {\n\nconst sal_Int32 LEFT_BORDER_SPACE = 10;\nconst sal_Int32 LOWER_BORDER_SPACE = 10;\n\nWaitSymbolSharedPtr WaitSymbol::create( const uno::Reference& xBitmap,\n ScreenUpdater& rScreenUpdater,\n EventMultiplexer& rEventMultiplexer,\n const UnoViewContainer& rViewContainer )\n{\n WaitSymbolSharedPtr pRet(\n new WaitSymbol( xBitmap,\n rScreenUpdater,\n rViewContainer ));\n\n rEventMultiplexer.addViewHandler( pRet );\n\n return pRet;\n}\n\nWaitSymbol::WaitSymbol( uno::Reference const & xBitmap,\n ScreenUpdater& rScreenUpdater,\n const UnoViewContainer& rViewContainer ) :\n mxBitmap(xBitmap),\n maViews(),\n mrScreenUpdater( rScreenUpdater ),\n mbVisible(false)\n{\n std::for_each( rViewContainer.begin(),\n rViewContainer.end(),\n boost::bind( &WaitSymbol::viewAdded,\n this,\n _1 ));\n}\n\nvoid WaitSymbol::setVisible( const bool bVisible )\n{\n if( mbVisible != bVisible )\n {\n mbVisible = bVisible;\n\n ViewsVecT::const_iterator aIter( maViews.begin() );\n ViewsVecT::const_iterator const aEnd ( maViews.end() );\n while( aIter != aEnd )\n {\n if( aIter->second )\n {\n if( bVisible )\n aIter->second->show();\n else\n aIter->second->hide();\n }\n\n ++aIter;\n }\n\n \/\/ sprites changed, need a screen update for this frame.\n mrScreenUpdater.requestImmediateUpdate();\n }\n}\n\nbasegfx::B2DPoint WaitSymbol::calcSpritePos(\n UnoViewSharedPtr const & rView ) const\n{\n const uno::Reference xBitmap( rView->getCanvas()->getUNOCanvas(),\n uno::UNO_QUERY_THROW );\n const geometry::IntegerSize2D realSize( xBitmap->getSize() );\n return basegfx::B2DPoint(\n std::min( realSize.Width, LEFT_BORDER_SPACE ),\n std::max( 0, realSize.Height - mxBitmap->getSize().Height\n - LOWER_BORDER_SPACE ) );\n}\n\nvoid WaitSymbol::viewAdded( const UnoViewSharedPtr& rView )\n{\n cppcanvas::CustomSpriteSharedPtr sprite;\n\n try\n {\n const geometry::IntegerSize2D spriteSize( mxBitmap->getSize() );\n sprite = rView->createSprite( basegfx::B2DVector( spriteSize.Width,\n spriteSize.Height ),\n 1000.0 ); \/\/ sprite should be in front of all\n \/\/ other sprites\n rendering::ViewState viewState;\n canvas::tools::initViewState( viewState );\n rendering::RenderState renderState;\n canvas::tools::initRenderState( renderState );\n sprite->getContentCanvas()->getUNOCanvas()->drawBitmap(\n mxBitmap, viewState, renderState );\n\n sprite->setAlpha( 0.9 );\n sprite->movePixel( calcSpritePos( rView ) );\n if( mbVisible )\n sprite->show();\n }\n catch( uno::Exception& )\n {\n OSL_ENSURE( false,\n rtl::OUStringToOString(\n comphelper::anyToString( cppu::getCaughtException() ),\n RTL_TEXTENCODING_UTF8 ).getStr() );\n }\n\n maViews.push_back( ViewsVecT::value_type( rView, sprite ) );\n}\n\nvoid WaitSymbol::viewRemoved( const UnoViewSharedPtr& rView )\n{\n maViews.erase(\n std::remove_if(\n maViews.begin(), maViews.end(),\n boost::bind(\n std::equal_to(),\n rView,\n \/\/ select view:\n boost::bind( std::select1st(), _1 ) ) ),\n maViews.end() );\n}\n\nvoid WaitSymbol::viewChanged( const UnoViewSharedPtr& rView )\n{\n \/\/ find entry corresponding to modified view\n ViewsVecT::iterator aModifiedEntry(\n std::find_if(\n maViews.begin(),\n maViews.end(),\n boost::bind(\n std::equal_to(),\n rView,\n \/\/ select view:\n boost::bind( std::select1st(), _1 ))));\n\n OSL_ASSERT( aModifiedEntry != maViews.end() );\n if( aModifiedEntry == maViews.end() )\n return;\n\n if( aModifiedEntry->second )\n aModifiedEntry->second->movePixel(\n calcSpritePos(aModifiedEntry->first) );\n}\n\nvoid WaitSymbol::viewsChanged()\n{\n \/\/ reposition sprites on all views\n ViewsVecT::const_iterator aIter( maViews.begin() );\n ViewsVecT::const_iterator const aEnd ( maViews.end() );\n while( aIter != aEnd )\n {\n if( aIter->second )\n aIter->second->movePixel(\n calcSpritePos( aIter->first ));\n ++aIter;\n }\n}\n\n} \/\/ namespace internal\n} \/\/ namespace presentation\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/tabbed_pane\/native_tabbed_pane_win.h\"\n\n#include \n\n#include \"app\/l10n_util_win.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/logging.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"gfx\/canvas.h\"\n#include \"gfx\/font.h\"\n#include \"gfx\/native_theme_win.h\"\n#include \"views\/controls\/tabbed_pane\/tabbed_pane.h\"\n#include \"views\/fill_layout.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_win.h\"\n\nnamespace views {\n\n\/\/ A background object that paints the tab panel background which may be\n\/\/ rendered by the system visual styles system.\nclass TabBackground : public Background {\n public:\n explicit TabBackground() {\n \/\/ TMT_FILLCOLORHINT returns a color value that supposedly\n \/\/ approximates the texture drawn by PaintTabPanelBackground.\n SkColor tab_page_color =\n gfx::NativeTheme::instance()->GetThemeColorWithDefault(\n gfx::NativeTheme::TAB, TABP_BODY, 0, TMT_FILLCOLORHINT,\n COLOR_3DFACE);\n SetNativeControlColor(tab_page_color);\n }\n virtual ~TabBackground() {}\n\n virtual void Paint(gfx::Canvas* canvas, View* view) const {\n HDC dc = canvas->beginPlatformPaint();\n RECT r = {0, 0, view->width(), view->height()};\n gfx::NativeTheme::instance()->PaintTabPanelBackground(dc, &r);\n canvas->endPlatformPaint();\n }\n\n private:\n DISALLOW_COPY_AND_ASSIGN(TabBackground);\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, public:\n\nNativeTabbedPaneWin::NativeTabbedPaneWin(TabbedPane* tabbed_pane)\n : NativeControlWin(),\n tabbed_pane_(tabbed_pane),\n content_window_(NULL),\n selected_index_(-1) {\n \/\/ Associates the actual HWND with the tabbed-pane so the tabbed-pane is\n \/\/ the one considered as having the focus (not the wrapper) when the HWND is\n \/\/ focused directly (with a click for example).\n set_focus_view(tabbed_pane);\n}\n\nNativeTabbedPaneWin::~NativeTabbedPaneWin() {\n \/\/ We own the tab views, let's delete them.\n STLDeleteContainerPointers(tab_views_.begin(), tab_views_.end());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, NativeTabbedPaneWrapper implementation:\n\nvoid NativeTabbedPaneWin::AddTab(const std::wstring& title, View* contents) {\n AddTabAtIndex(static_cast(tab_views_.size()), title, contents, true);\n}\n\nvoid NativeTabbedPaneWin::AddTabAtIndex(int index, const std::wstring& title,\n View* contents,\n bool select_if_first_tab) {\n DCHECK(index <= static_cast(tab_views_.size()));\n contents->set_parent_owned(false);\n tab_views_.insert(tab_views_.begin() + index, contents);\n tab_titles_.insert(tab_titles_.begin() + index, title);\n\n if (!contents->background())\n contents->set_background(new TabBackground);\n\n if (tab_views_.size() == 1 && select_if_first_tab) {\n \/\/ If this is the only tab displayed, make sure the contents is set.\n selected_index_ = 0;\n if (content_window_)\n content_window_->GetRootView()->AddChildView(contents);\n }\n\n \/\/ Add native tab only if the native control is alreay created.\n if (content_window_) {\n AddNativeTab(index, title, contents);\n\n \/\/ The newly added tab may have made the contents window smaller.\n ResizeContents();\n }\n}\n\nvoid NativeTabbedPaneWin::AddNativeTab(int index,\n const std::wstring &title,\n views::View* contents) {\n TCITEM tcitem;\n tcitem.mask = TCIF_TEXT;\n\n \/\/ If the locale is RTL, we set the TCIF_RTLREADING so that BiDi text is\n \/\/ rendered properly on the tabs.\n if (UILayoutIsRightToLeft()) {\n tcitem.mask |= TCIF_RTLREADING;\n }\n\n tcitem.pszText = const_cast(title.c_str());\n int result = TabCtrl_InsertItem(native_view(), index, &tcitem);\n DCHECK(result != -1);\n}\n\nView* NativeTabbedPaneWin::RemoveTabAtIndex(int index) {\n int tab_count = static_cast(tab_views_.size());\n DCHECK(index >= 0 && index < tab_count);\n\n if (index < (tab_count - 1)) {\n \/\/ Select the next tab.\n SelectTabAt(index + 1);\n } else {\n \/\/ We are the last tab, select the previous one.\n if (index > 0) {\n SelectTabAt(index - 1);\n } else if (content_window_) {\n \/\/ That was the last tab. Remove the contents.\n content_window_->GetRootView()->RemoveAllChildViews(false);\n }\n }\n TabCtrl_DeleteItem(native_view(), index);\n\n \/\/ The removed tab may have made the contents window bigger.\n if (content_window_)\n ResizeContents();\n\n std::vector::iterator iter = tab_views_.begin() + index;\n View* removed_tab = *iter;\n tab_views_.erase(iter);\n tab_titles_.erase(tab_titles_.begin() + index);\n\n return removed_tab;\n}\n\nvoid NativeTabbedPaneWin::SelectTabAt(int index) {\n DCHECK((index >= 0) && (index < static_cast(tab_views_.size())));\n if (native_view())\n TabCtrl_SetCurSel(native_view(), index);\n DoSelectTabAt(index, true);\n}\n\nint NativeTabbedPaneWin::GetTabCount() {\n return TabCtrl_GetItemCount(native_view());\n}\n\nint NativeTabbedPaneWin::GetSelectedTabIndex() {\n return TabCtrl_GetCurSel(native_view());\n}\n\nView* NativeTabbedPaneWin::GetSelectedTab() {\n if (selected_index_ < 0)\n return NULL;\n return tab_views_[selected_index_];\n}\n\nView* NativeTabbedPaneWin::GetView() {\n return this;\n}\n\nvoid NativeTabbedPaneWin::SetFocus() {\n \/\/ Focus the associated HWND.\n Focus();\n}\n\ngfx::NativeView NativeTabbedPaneWin::GetTestingHandle() const {\n return native_view();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, NativeControlWin override:\n\nvoid NativeTabbedPaneWin::CreateNativeControl() {\n \/\/ Create the tab control.\n \/\/\n \/\/ Note that we don't follow the common convention for NativeControl\n \/\/ subclasses and we don't pass the value returned from\n \/\/ NativeControl::GetAdditionalExStyle() as the dwExStyle parameter. Here is\n \/\/ why: on RTL locales, if we pass NativeControl::GetAdditionalExStyle() when\n \/\/ we basically tell Windows to create our HWND with the WS_EX_LAYOUTRTL. If\n \/\/ we do that, then the HWND we create for |content_window_| below will\n \/\/ inherit the WS_EX_LAYOUTRTL property and this will result in the contents\n \/\/ being flipped, which is not what we want (because we handle mirroring in\n \/\/ views without the use of Windows' support for mirroring). Therefore,\n \/\/ we initially create our HWND without the aforementioned property and we\n \/\/ explicitly set this property our child is created. This way, on RTL\n \/\/ locales, our tabs will be nicely rendered from right to left (by virtue of\n \/\/ Windows doing the right thing with the TabbedPane HWND) and each tab\n \/\/ contents will use an RTL layout correctly (by virtue of the mirroring\n \/\/ infrastructure in views doing the right thing with each View we put\n \/\/ in the tab).\n HWND tab_control = ::CreateWindowEx(0,\n WC_TABCONTROL,\n L\"\",\n WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,\n 0, 0, width(), height(),\n GetWidget()->GetNativeView(), NULL, NULL,\n NULL);\n\n HFONT font = ResourceBundle::GetSharedInstance().\n GetFont(ResourceBundle::BaseFont).hfont();\n SendMessage(tab_control, WM_SETFONT, reinterpret_cast(font), FALSE);\n\n \/\/ Create the view container which is a child of the TabControl.\n content_window_ = new WidgetWin();\n content_window_->Init(tab_control, gfx::Rect());\n\n \/\/ Explicitly setting the WS_EX_LAYOUTRTL property for the HWND (see above\n \/\/ for a thorough explanation regarding why we waited until |content_window_|\n \/\/ if created before we set this property for the tabbed pane's HWND).\n if (UILayoutIsRightToLeft())\n l10n_util::HWNDSetRTLLayout(tab_control);\n\n RootView* root_view = content_window_->GetRootView();\n root_view->SetLayoutManager(new FillLayout());\n DWORD sys_color = ::GetSysColor(COLOR_3DHILIGHT);\n SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color),\n GetBValue(sys_color));\n root_view->set_background(Background::CreateSolidBackground(color));\n\n content_window_->SetFocusTraversableParentView(this);\n\n NativeControlCreated(tab_control);\n\n \/\/ Add tabs that are already added if any.\n if (tab_views_.size() > 0) {\n InitializeTabs();\n if (selected_index_ >= 0)\n DoSelectTabAt(selected_index_, false);\n }\n\n ResizeContents();\n}\n\nbool NativeTabbedPaneWin::ProcessMessage(UINT message,\n WPARAM w_param,\n LPARAM l_param,\n LRESULT* result) {\n if (message == WM_NOTIFY &&\n reinterpret_cast(l_param)->code == TCN_SELCHANGE) {\n int selected_tab = TabCtrl_GetCurSel(native_view());\n DCHECK(selected_tab != -1);\n DoSelectTabAt(selected_tab, true);\n return TRUE;\n }\n return NativeControlWin::ProcessMessage(message, w_param, l_param, result);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ View override:\n\nvoid NativeTabbedPaneWin::Layout() {\n NativeControlWin::Layout();\n ResizeContents();\n}\n\nFocusTraversable* NativeTabbedPaneWin::GetFocusTraversable() {\n return content_window_;\n}\n\nvoid NativeTabbedPaneWin::ViewHierarchyChanged(bool is_add,\n View *parent,\n View *child) {\n NativeControlWin::ViewHierarchyChanged(is_add, parent, child);\n\n if (is_add && (child == this) && content_window_) {\n \/\/ We have been added to a view hierarchy, update the FocusTraversable\n \/\/ parent.\n content_window_->SetFocusTraversableParent(GetRootView());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, private:\n\nvoid NativeTabbedPaneWin::InitializeTabs() {\n for (size_t i = 0; i < tab_views_.size(); ++i) {\n AddNativeTab(i, tab_titles_[i], tab_views_[i]);\n }\n}\n\nvoid NativeTabbedPaneWin::DoSelectTabAt(int index, boolean invoke_listener) {\n selected_index_ = index;\n if (content_window_) {\n RootView* content_root = content_window_->GetRootView();\n\n \/\/ Clear the focus if the focused view was on the tab.\n FocusManager* focus_manager = GetFocusManager();\n DCHECK(focus_manager);\n View* focused_view = focus_manager->GetFocusedView();\n if (focused_view && content_root->IsParentOf(focused_view))\n focus_manager->ClearFocus();\n\n content_root->RemoveAllChildViews(false);\n content_root->AddChildView(tab_views_[index]);\n content_root->Layout();\n }\n if (invoke_listener && tabbed_pane_->listener())\n tabbed_pane_->listener()->TabSelectedAt(index);\n}\n\nvoid NativeTabbedPaneWin::ResizeContents() {\n CRect content_bounds;\n if (!GetClientRect(native_view(), &content_bounds))\n return;\n TabCtrl_AdjustRect(native_view(), FALSE, &content_bounds);\n content_window_->MoveWindow(content_bounds.left, content_bounds.top,\n content_bounds.Width(), content_bounds.Height(),\n TRUE);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWrapper, public:\n\n\/\/ static\nNativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper(\n TabbedPane* tabbed_pane) {\n return new NativeTabbedPaneWin(tabbed_pane);\n}\n\n} \/\/ namespace views\nAdd style to clip children which reduces flashing when the tab control is resized. The tab control still flashes a little bit but it is only the outer area and not the large content area\/child controls. Fixing that probably requires drawing the tab control on our own which is perhaps overkill. BUG=28383 TEST=follow steps given in the bug and resize password manager window, tab should not flicker as much as it did earlier. \/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/tabbed_pane\/native_tabbed_pane_win.h\"\n\n#include \n\n#include \"app\/l10n_util_win.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/logging.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"gfx\/canvas.h\"\n#include \"gfx\/font.h\"\n#include \"gfx\/native_theme_win.h\"\n#include \"views\/controls\/tabbed_pane\/tabbed_pane.h\"\n#include \"views\/fill_layout.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_win.h\"\n\nnamespace views {\n\n\/\/ A background object that paints the tab panel background which may be\n\/\/ rendered by the system visual styles system.\nclass TabBackground : public Background {\n public:\n explicit TabBackground() {\n \/\/ TMT_FILLCOLORHINT returns a color value that supposedly\n \/\/ approximates the texture drawn by PaintTabPanelBackground.\n SkColor tab_page_color =\n gfx::NativeTheme::instance()->GetThemeColorWithDefault(\n gfx::NativeTheme::TAB, TABP_BODY, 0, TMT_FILLCOLORHINT,\n COLOR_3DFACE);\n SetNativeControlColor(tab_page_color);\n }\n virtual ~TabBackground() {}\n\n virtual void Paint(gfx::Canvas* canvas, View* view) const {\n HDC dc = canvas->beginPlatformPaint();\n RECT r = {0, 0, view->width(), view->height()};\n gfx::NativeTheme::instance()->PaintTabPanelBackground(dc, &r);\n canvas->endPlatformPaint();\n }\n\n private:\n DISALLOW_COPY_AND_ASSIGN(TabBackground);\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, public:\n\nNativeTabbedPaneWin::NativeTabbedPaneWin(TabbedPane* tabbed_pane)\n : NativeControlWin(),\n tabbed_pane_(tabbed_pane),\n content_window_(NULL),\n selected_index_(-1) {\n \/\/ Associates the actual HWND with the tabbed-pane so the tabbed-pane is\n \/\/ the one considered as having the focus (not the wrapper) when the HWND is\n \/\/ focused directly (with a click for example).\n set_focus_view(tabbed_pane);\n}\n\nNativeTabbedPaneWin::~NativeTabbedPaneWin() {\n \/\/ We own the tab views, let's delete them.\n STLDeleteContainerPointers(tab_views_.begin(), tab_views_.end());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, NativeTabbedPaneWrapper implementation:\n\nvoid NativeTabbedPaneWin::AddTab(const std::wstring& title, View* contents) {\n AddTabAtIndex(static_cast(tab_views_.size()), title, contents, true);\n}\n\nvoid NativeTabbedPaneWin::AddTabAtIndex(int index, const std::wstring& title,\n View* contents,\n bool select_if_first_tab) {\n DCHECK(index <= static_cast(tab_views_.size()));\n contents->set_parent_owned(false);\n tab_views_.insert(tab_views_.begin() + index, contents);\n tab_titles_.insert(tab_titles_.begin() + index, title);\n\n if (!contents->background())\n contents->set_background(new TabBackground);\n\n if (tab_views_.size() == 1 && select_if_first_tab) {\n \/\/ If this is the only tab displayed, make sure the contents is set.\n selected_index_ = 0;\n if (content_window_)\n content_window_->GetRootView()->AddChildView(contents);\n }\n\n \/\/ Add native tab only if the native control is alreay created.\n if (content_window_) {\n AddNativeTab(index, title, contents);\n\n \/\/ The newly added tab may have made the contents window smaller.\n ResizeContents();\n }\n}\n\nvoid NativeTabbedPaneWin::AddNativeTab(int index,\n const std::wstring &title,\n views::View* contents) {\n TCITEM tcitem;\n tcitem.mask = TCIF_TEXT;\n\n \/\/ If the locale is RTL, we set the TCIF_RTLREADING so that BiDi text is\n \/\/ rendered properly on the tabs.\n if (UILayoutIsRightToLeft()) {\n tcitem.mask |= TCIF_RTLREADING;\n }\n\n tcitem.pszText = const_cast(title.c_str());\n int result = TabCtrl_InsertItem(native_view(), index, &tcitem);\n DCHECK(result != -1);\n}\n\nView* NativeTabbedPaneWin::RemoveTabAtIndex(int index) {\n int tab_count = static_cast(tab_views_.size());\n DCHECK(index >= 0 && index < tab_count);\n\n if (index < (tab_count - 1)) {\n \/\/ Select the next tab.\n SelectTabAt(index + 1);\n } else {\n \/\/ We are the last tab, select the previous one.\n if (index > 0) {\n SelectTabAt(index - 1);\n } else if (content_window_) {\n \/\/ That was the last tab. Remove the contents.\n content_window_->GetRootView()->RemoveAllChildViews(false);\n }\n }\n TabCtrl_DeleteItem(native_view(), index);\n\n \/\/ The removed tab may have made the contents window bigger.\n if (content_window_)\n ResizeContents();\n\n std::vector::iterator iter = tab_views_.begin() + index;\n View* removed_tab = *iter;\n tab_views_.erase(iter);\n tab_titles_.erase(tab_titles_.begin() + index);\n\n return removed_tab;\n}\n\nvoid NativeTabbedPaneWin::SelectTabAt(int index) {\n DCHECK((index >= 0) && (index < static_cast(tab_views_.size())));\n if (native_view())\n TabCtrl_SetCurSel(native_view(), index);\n DoSelectTabAt(index, true);\n}\n\nint NativeTabbedPaneWin::GetTabCount() {\n return TabCtrl_GetItemCount(native_view());\n}\n\nint NativeTabbedPaneWin::GetSelectedTabIndex() {\n return TabCtrl_GetCurSel(native_view());\n}\n\nView* NativeTabbedPaneWin::GetSelectedTab() {\n if (selected_index_ < 0)\n return NULL;\n return tab_views_[selected_index_];\n}\n\nView* NativeTabbedPaneWin::GetView() {\n return this;\n}\n\nvoid NativeTabbedPaneWin::SetFocus() {\n \/\/ Focus the associated HWND.\n Focus();\n}\n\ngfx::NativeView NativeTabbedPaneWin::GetTestingHandle() const {\n return native_view();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, NativeControlWin override:\n\nvoid NativeTabbedPaneWin::CreateNativeControl() {\n \/\/ Create the tab control.\n \/\/\n \/\/ Note that we don't follow the common convention for NativeControl\n \/\/ subclasses and we don't pass the value returned from\n \/\/ NativeControl::GetAdditionalExStyle() as the dwExStyle parameter. Here is\n \/\/ why: on RTL locales, if we pass NativeControl::GetAdditionalExStyle() when\n \/\/ we basically tell Windows to create our HWND with the WS_EX_LAYOUTRTL. If\n \/\/ we do that, then the HWND we create for |content_window_| below will\n \/\/ inherit the WS_EX_LAYOUTRTL property and this will result in the contents\n \/\/ being flipped, which is not what we want (because we handle mirroring in\n \/\/ views without the use of Windows' support for mirroring). Therefore,\n \/\/ we initially create our HWND without the aforementioned property and we\n \/\/ explicitly set this property our child is created. This way, on RTL\n \/\/ locales, our tabs will be nicely rendered from right to left (by virtue of\n \/\/ Windows doing the right thing with the TabbedPane HWND) and each tab\n \/\/ contents will use an RTL layout correctly (by virtue of the mirroring\n \/\/ infrastructure in views doing the right thing with each View we put\n \/\/ in the tab).\n DWORD style = WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE | WS_CLIPCHILDREN;\n HWND tab_control = ::CreateWindowEx(0,\n WC_TABCONTROL,\n L\"\",\n style,\n 0, 0, width(), height(),\n GetWidget()->GetNativeView(), NULL, NULL,\n NULL);\n\n HFONT font = ResourceBundle::GetSharedInstance().\n GetFont(ResourceBundle::BaseFont).hfont();\n SendMessage(tab_control, WM_SETFONT, reinterpret_cast(font), FALSE);\n\n \/\/ Create the view container which is a child of the TabControl.\n content_window_ = new WidgetWin();\n content_window_->Init(tab_control, gfx::Rect());\n\n \/\/ Explicitly setting the WS_EX_LAYOUTRTL property for the HWND (see above\n \/\/ for a thorough explanation regarding why we waited until |content_window_|\n \/\/ if created before we set this property for the tabbed pane's HWND).\n if (UILayoutIsRightToLeft())\n l10n_util::HWNDSetRTLLayout(tab_control);\n\n RootView* root_view = content_window_->GetRootView();\n root_view->SetLayoutManager(new FillLayout());\n DWORD sys_color = ::GetSysColor(COLOR_3DHILIGHT);\n SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color),\n GetBValue(sys_color));\n root_view->set_background(Background::CreateSolidBackground(color));\n\n content_window_->SetFocusTraversableParentView(this);\n\n NativeControlCreated(tab_control);\n\n \/\/ Add tabs that are already added if any.\n if (tab_views_.size() > 0) {\n InitializeTabs();\n if (selected_index_ >= 0)\n DoSelectTabAt(selected_index_, false);\n }\n\n ResizeContents();\n}\n\nbool NativeTabbedPaneWin::ProcessMessage(UINT message,\n WPARAM w_param,\n LPARAM l_param,\n LRESULT* result) {\n if (message == WM_NOTIFY &&\n reinterpret_cast(l_param)->code == TCN_SELCHANGE) {\n int selected_tab = TabCtrl_GetCurSel(native_view());\n DCHECK(selected_tab != -1);\n DoSelectTabAt(selected_tab, true);\n return TRUE;\n }\n return NativeControlWin::ProcessMessage(message, w_param, l_param, result);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ View override:\n\nvoid NativeTabbedPaneWin::Layout() {\n NativeControlWin::Layout();\n ResizeContents();\n}\n\nFocusTraversable* NativeTabbedPaneWin::GetFocusTraversable() {\n return content_window_;\n}\n\nvoid NativeTabbedPaneWin::ViewHierarchyChanged(bool is_add,\n View *parent,\n View *child) {\n NativeControlWin::ViewHierarchyChanged(is_add, parent, child);\n\n if (is_add && (child == this) && content_window_) {\n \/\/ We have been added to a view hierarchy, update the FocusTraversable\n \/\/ parent.\n content_window_->SetFocusTraversableParent(GetRootView());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, private:\n\nvoid NativeTabbedPaneWin::InitializeTabs() {\n for (size_t i = 0; i < tab_views_.size(); ++i) {\n AddNativeTab(i, tab_titles_[i], tab_views_[i]);\n }\n}\n\nvoid NativeTabbedPaneWin::DoSelectTabAt(int index, boolean invoke_listener) {\n selected_index_ = index;\n if (content_window_) {\n RootView* content_root = content_window_->GetRootView();\n\n \/\/ Clear the focus if the focused view was on the tab.\n FocusManager* focus_manager = GetFocusManager();\n DCHECK(focus_manager);\n View* focused_view = focus_manager->GetFocusedView();\n if (focused_view && content_root->IsParentOf(focused_view))\n focus_manager->ClearFocus();\n\n content_root->RemoveAllChildViews(false);\n content_root->AddChildView(tab_views_[index]);\n content_root->Layout();\n }\n if (invoke_listener && tabbed_pane_->listener())\n tabbed_pane_->listener()->TabSelectedAt(index);\n}\n\nvoid NativeTabbedPaneWin::ResizeContents() {\n CRect content_bounds;\n if (!GetClientRect(native_view(), &content_bounds))\n return;\n TabCtrl_AdjustRect(native_view(), FALSE, &content_bounds);\n content_window_->MoveWindow(content_bounds.left, content_bounds.top,\n content_bounds.Width(), content_bounds.Height(),\n TRUE);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWrapper, public:\n\n\/\/ static\nNativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper(\n TabbedPane* tabbed_pane) {\n return new NativeTabbedPaneWin(tabbed_pane);\n}\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"#include \"powerup.hpp\"\n\n#define SEARCH_RADIUS 5\n\nint Powerup::vertex_type( Vertex& v ) {\n\tint num_neighbors = map->getNumActors();\n\tfor ( int i = 0; i < num_neighbors; i++ ) {\n\t\tint a, b;\n\t\tmap->getActorPosition( i, a, b );\n\t\tVertex temp( a, b );\n\t\tif( temp == v ) {\n\t\t\treturn map->getActorType( i );\n\t\t}\n\t}\n\treturn 0;\n}\n\nPowerup::Powerup( int type ): Actor( type ) {}\n\nPowerup* Powerup::duplicate() {\n\treturn new Powerup( getType() );\n}\n\nconst char* Powerup::getActorId() { \t\n\treturn \"simplehero\"; \n}\n\nconst char* Powerup::getNetId() {\n\treturn \"hammesa\"; \n}\n\nbool Powerup::visited( const Vertex& v ) const {\n\treturn v_set.find( v ) != v_set.end();\n}\n\nint Powerup::selectNeighbor( GraphMap* map, int cur_x, int cur_y ) {\n\tthis->map = map;\n\tv_set.clear();\n\trank_nodes( cur_x, cur_y );\n\n\treturn 0;\n}\n\nvoid Powerup::rank_nodes( int x, int y ) {\n\tqueue< Vertex > q;\n\tVertex temp( x, y );\n\tdist[temp] = 0;\n\n\tq.push( Vertex( x, y ) );\n\n\tvector< Vertex > enemies;\n\tvector< Vertex > eatables;\n\n\tbool stop = false;\n\twhile( !q.empty() && enemies.size() < SEARCH_RADIUS && !stop ) {\n\t\tVertex popped = q.front();\n\t\tq.pop();\n\n\t\tv_set.insert( popped );\n\t\tif( vertex_type( popped ) & ACTOR_ENEMY ) {\n\t\t\tenemies.push_back( popped );\n\t\t}\n\n\t\tif( vertex_type( popped ) & ACTOR_EATABLE ) {\n\t\t\teatables.push_back( popped );\n\t\t}\n\n\t\tint num_neighbors = map->getNumNeighbors( popped.x, popped. y )\n\t\tfor ( int i = 0; i < num_neighbors; i++ ) {\n\t\t\tint a, b;\n\t\t\tmap->getNeighbor( popped.x, popped.y, i, a, b );\n\t\t\tVertex temp( a, b );\n\n\t\t\tif( !visited( temp ) ) {\n\t\t\t\tdist[temp] = dist[popped] + 1;\n\t\t\t\tif( dist[temp] > SEARCH_RADIUS ) {\n\t\t\t\t\tstop = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tq.push( temp );\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n\nadded const#include \"powerup.hpp\"\n\n#define SEARCH_RADIUS 5\n\nint Powerup::vertex_type( const Vertex& v ) const {\n\tint num_neighbors = map->getNumActors();\n\tfor ( int i = 0; i < num_neighbors; i++ ) {\n\t\tint a, b;\n\t\tmap->getActorPosition( i, a, b );\n\t\tVertex temp( a, b );\n\t\tif( temp == v ) {\n\t\t\treturn map->getActorType( i );\n\t\t}\n\t}\n\treturn 0;\n}\n\nPowerup::Powerup( int type ): Actor( type ) {}\n\nPowerup* Powerup::duplicate() {\n\treturn new Powerup( getType() );\n}\n\nconst char* Powerup::getActorId() { \t\n\treturn \"simplehero\"; \n}\n\nconst char* Powerup::getNetId() {\n\treturn \"hammesa\"; \n}\n\nbool Powerup::visited( const Vertex& v ) const {\n\treturn v_set.find( v ) != v_set.end();\n}\n\nint Powerup::selectNeighbor( GraphMap* map, int cur_x, int cur_y ) {\n\tthis->map = map;\n\tv_set.clear();\n\trank_nodes( cur_x, cur_y );\n\n\treturn 0;\n}\n\nvoid Powerup::rank_nodes( int x, int y ) {\n\tqueue< Vertex > q;\n\tVertex temp( x, y );\n\tdist[temp] = 0;\n\n\tq.push( Vertex( x, y ) );\n\n\tvector< Vertex > enemies;\n\tvector< Vertex > eatables;\n\n\tbool stop = false;\n\twhile( !q.empty() && enemies.size() < SEARCH_RADIUS && !stop ) {\n\t\tVertex popped = q.front();\n\t\tq.pop();\n\n\t\tv_set.insert( popped );\n\t\tif( vertex_type( popped ) & ACTOR_ENEMY ) {\n\t\t\tenemies.push_back( popped );\n\t\t}\n\n\t\tif( vertex_type( popped ) & ACTOR_EATABLE ) {\n\t\t\teatables.push_back( popped );\n\t\t}\n\n\t\tint num_neighbors = map->getNumNeighbors( popped.x, popped. y );\n\t\tfor ( int i = 0; i < num_neighbors; i++ ) {\n\t\t\tint a, b;\n\t\t\tmap->getNeighbor( popped.x, popped.y, i, a, b );\n\t\t\tVertex temp( a, b );\n\n\t\t\tif( !visited( temp ) ) {\n\t\t\t\tdist[temp] = dist[popped] + 1;\n\t\t\t\tif( dist[temp] > SEARCH_RADIUS ) {\n\t\t\t\t\tstop = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tq.push( temp );\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nstd::string assets_folder = BABYLON::babylon_repo_folder() + std::string(\"\/assets\/\");\n\nstd::string textUrl = std::string(\"file:\/\") + assets_folder + \"\/fonts\/fa-regular-400.ttf\";\nstd::string binaryUrl = std::string(\"file:\/\") + assets_folder\n + \"\/glTF-Sample-Models\/2.0\/AntiqueCamera\/glTF\/camera_camera_Normal.png\";\nstd::string nonExistingFileUrl = \"file:\/non_existing_file\";\n\nstd::vector textFilesUrls = {\n textUrl, nonExistingFileUrl, textUrl, textUrl, nonExistingFileUrl, textUrl, nonExistingFileUrl\n};\n\nstd::vector binaryFilesUrls = {\n binaryUrl, nonExistingFileUrl, binaryUrl, binaryUrl, nonExistingFileUrl, binaryUrl, nonExistingFileUrl\n};\n\nvoid SampleApplicationLoop()\n{\n auto mainThreadId = std::this_thread::get_id();\n\n int nb_success_text = 0;\n int nb_success_binary = 0;\n int nb_error = 0;\n int nb_calls_to_progress = 0;\n\n \/\/ Sample callbacks that will be called *synchronously*\n auto onSuccessText = [&nb_success_text, mainThreadId](const std::string& \/*textContent*\/) {\n auto thisThreadId = std::this_thread::get_id();\n EXPECT_EQ(thisThreadId, mainThreadId);\n ++nb_success_text;\n };\n auto onSuccessBinary = [&nb_success_binary, mainThreadId](const BABYLON::ArrayBuffer& \/*data*\/) {\n auto thisThreadId = std::this_thread::get_id();\n EXPECT_EQ(thisThreadId, mainThreadId);\n ++nb_success_binary;\n };\n auto onError = [&nb_error, mainThreadId](const std::string& message) {\n auto thisThreadId = std::this_thread::get_id();\n EXPECT_EQ(thisThreadId, mainThreadId);\n ++nb_error;\n std::cout << \"onError: \"<< message << \"\\n\";\n };\n auto onProgress = [&nb_calls_to_progress, mainThreadId](bool \/*lengthComputable*\/, size_t \/*loaded*\/, size_t \/*total*\/) {\n auto thisThreadId = std::this_thread::get_id();\n EXPECT_EQ(thisThreadId, mainThreadId);\n ++nb_calls_to_progress;\n };\n\n\n \/\/ Sample application main loop\n bool applicationShallExit = false;\n while(!applicationShallExit)\n {\n if (!textFilesUrls.empty())\n {\n std::string url = textFilesUrls.back();\n textFilesUrls.pop_back();\n BABYLON::asio::LoadAssetAsync_Text(url, onSuccessText, onError, onProgress);\n }\n if (!binaryFilesUrls.empty())\n {\n std::string url = binaryFilesUrls.back();\n binaryFilesUrls.pop_back();\n BABYLON::asio::LoadAssetAsync_Binary(url, onSuccessBinary, onError, onProgress);\n }\n\n applicationShallExit =\n textFilesUrls.empty() && binaryFilesUrls.empty() && ! BABYLON::asio::HasRemainingTasks();\n\n \/\/ Remember to call asio::HeartBeat_Sync() in your application main loop:\n \/\/ if there are pending callbacks, this will call the first one *synchronously*\n BABYLON::asio::HeartBeat_Sync();\n };\n\n EXPECT_EQ(nb_success_text, 4);\n EXPECT_EQ(nb_success_binary, 4);\n EXPECT_EQ(nb_error, 6);\n EXPECT_GT(nb_calls_to_progress, 10);\n\/\/ printf(\"nb_success_text=%i, nb_success_binary=%i, nb_error=%i nb_calls_to_progress=%i\\n\",\n\/\/ nb_success_text, nb_success_binary, nb_error, nb_calls_to_progress);\n}\n\nTEST(async_requests, SampleApplicationLoop)\n{\n#ifndef _WIN32\n std::cout << \"isFile(\" << textUrl.substr(6) << \") => \" << BABYLON::Filesystem::isFile(textUrl.substr(6)) << \"\\n\";\n std::cout << \"isFile(\" << binaryUrl.substr(6) << \") => \" << BABYLON::Filesystem::isFile(binaryUrl.substr(6)) << \"\\n\";\n SampleApplicationLoop();\n BABYLON::asio::Service_Stop();\n#endif \/\/ _WIN32\n}\n\nTEST(async_requests, LoadText)\n{\n#if 0 \/\/ This code works, but features no real google test call\n std::cout << \"\\n\";\n auto onSuccessText = [](const std::string& textContent) {\n std::cout << \"\\n==>\\n\" << textContent << \"\\n<==\\n\";\n };\n auto onError = [](const std::string& message) {\n std::cout << \"Error:\" << message << \"!!!\\n\";\n };\n auto onProgress = [](bool lengthComputable, size_t loaded, size_t total) {\n std::cout << \"onProgress \" << loaded << \" \/ \" << total << \" lengthComputable: \" << lengthComputable << \"\\n\";\n };\n\n BABYLON::asio::LoadUrlAsync_Text(textUrl, onSuccessText, onError, onProgress);\n BABYLON::asio::Service_WaitAll_Sync();\n#endif\n}\nfix asio_test#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nstd::string textUrl = \"fonts\/fa-regular-400.ttf\";\nstd::string binaryUrl = \"glTF-Sample-Models\/2.0\/AntiqueCamera\/glTF\/camera_camera_Normal.png\";\nstd::string nonExistingFileUrl = \"non_existing_file\";\n\nstd::vector textFilesUrls = {\n textUrl, nonExistingFileUrl, textUrl, textUrl, nonExistingFileUrl, textUrl, nonExistingFileUrl\n};\n\nstd::vector binaryFilesUrls = {\n binaryUrl, nonExistingFileUrl, binaryUrl, binaryUrl, nonExistingFileUrl, binaryUrl, nonExistingFileUrl\n};\n\nvoid SampleApplicationLoop()\n{\n auto mainThreadId = std::this_thread::get_id();\n\n int nb_success_text = 0;\n int nb_success_binary = 0;\n int nb_error = 0;\n int nb_calls_to_progress = 0;\n\n \/\/ Sample callbacks that will be called *synchronously*\n auto onSuccessText = [&nb_success_text, mainThreadId](const std::string& \/*textContent*\/) {\n auto thisThreadId = std::this_thread::get_id();\n EXPECT_EQ(thisThreadId, mainThreadId);\n ++nb_success_text;\n };\n auto onSuccessBinary = [&nb_success_binary, mainThreadId](const BABYLON::ArrayBuffer& \/*data*\/) {\n auto thisThreadId = std::this_thread::get_id();\n EXPECT_EQ(thisThreadId, mainThreadId);\n ++nb_success_binary;\n };\n auto onError = [&nb_error, mainThreadId](const std::string& message) {\n auto thisThreadId = std::this_thread::get_id();\n EXPECT_EQ(thisThreadId, mainThreadId);\n ++nb_error;\n std::cout << \"onError: \"<< message << \"\\n\";\n };\n auto onProgress = [&nb_calls_to_progress, mainThreadId](bool \/*lengthComputable*\/, size_t \/*loaded*\/, size_t \/*total*\/) {\n auto thisThreadId = std::this_thread::get_id();\n EXPECT_EQ(thisThreadId, mainThreadId);\n ++nb_calls_to_progress;\n };\n\n\n \/\/ Sample application main loop\n bool applicationShallExit = false;\n while(!applicationShallExit)\n {\n if (!textFilesUrls.empty())\n {\n std::string url = textFilesUrls.back();\n textFilesUrls.pop_back();\n BABYLON::asio::LoadAssetAsync_Text(url, onSuccessText, onError, onProgress);\n }\n if (!binaryFilesUrls.empty())\n {\n std::string url = binaryFilesUrls.back();\n binaryFilesUrls.pop_back();\n BABYLON::asio::LoadAssetAsync_Binary(url, onSuccessBinary, onError, onProgress);\n }\n\n applicationShallExit =\n textFilesUrls.empty() && binaryFilesUrls.empty() && ! BABYLON::asio::HasRemainingTasks();\n\n \/\/ Remember to call asio::HeartBeat_Sync() in your application main loop:\n \/\/ if there are pending callbacks, this will call the first one *synchronously*\n BABYLON::asio::HeartBeat_Sync();\n };\n\n EXPECT_EQ(nb_success_text, 4);\n EXPECT_EQ(nb_success_binary, 4);\n EXPECT_EQ(nb_error, 6);\n EXPECT_GT(nb_calls_to_progress, 10);\n\/\/ printf(\"nb_success_text=%i, nb_success_binary=%i, nb_error=%i nb_calls_to_progress=%i\\n\",\n\/\/ nb_success_text, nb_success_binary, nb_error, nb_calls_to_progress);\n}\n\nTEST(async_requests, SampleApplicationLoop)\n{\n#ifndef _WIN32\n std::cout << \"isFile(\" << textUrl.substr(6) << \") => \" << BABYLON::Filesystem::isFile(textUrl.substr(6)) << \"\\n\";\n std::cout << \"isFile(\" << binaryUrl.substr(6) << \") => \" << BABYLON::Filesystem::isFile(binaryUrl.substr(6)) << \"\\n\";\n SampleApplicationLoop();\n BABYLON::asio::Service_Stop();\n#endif \/\/ _WIN32\n}\n\nTEST(async_requests, LoadText)\n{\n#if 0 \/\/ This code works, but features no real google test call\n std::cout << \"\\n\";\n auto onSuccessText = [](const std::string& textContent) {\n std::cout << \"\\n==>\\n\" << textContent << \"\\n<==\\n\";\n };\n auto onError = [](const std::string& message) {\n std::cout << \"Error:\" << message << \"!!!\\n\";\n };\n auto onProgress = [](bool lengthComputable, size_t loaded, size_t total) {\n std::cout << \"onProgress \" << loaded << \" \/ \" << total << \" lengthComputable: \" << lengthComputable << \"\\n\";\n };\n\n BABYLON::asio::LoadUrlAsync_Text(textUrl, onSuccessText, onError, onProgress);\n BABYLON::asio::Service_WaitAll_Sync();\n#endif\n}\n<|endoftext|>"} {"text":"#include \"StdAfx.h\"\r\n#include \"WebBrowserHelper.h\"\r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace Utilities::WebBrowser;\r\n\r\nWebBrowserHelper::WebBrowserHelper(void)\r\n{\r\n}\r\n\r\n\r\nWebBrowserHelper::~WebBrowserHelper(void)\r\n{\r\n}\r\n\r\nint WebBrowserHelper::ClearCache()\r\n{\r\n\/\/ Pointer to a GROUPID variable\r\n\tGROUPID groupId = 0;\r\n\t\r\n\t\/\/ Local variables\r\n\tDWORD cacheEntryInfoBufferSizeInitial = 0;\r\n DWORD cacheEntryInfoBufferSize = 0;\r\n int *cacheEntryInfoBuffer = 0;\r\n INTERNET_CACHE_ENTRY_INFO *internetCacheEntry;\r\n HANDLE enumHandle = NULL;\r\n BOOL returnValue = false;\r\n\r\n\t\/\/ Delete the groups first.\r\n \/\/ Groups may not always exist on the system.\r\n \/\/ For more information, visit the following Microsoft Web site:\r\n \/\/ http:\/\/msdn2.microsoft.com\/en-us\/library\/ms909365.aspx\t\t\t\r\n \/\/ By default, a URL does not belong to any group. Therefore, that cache may become\r\n \/\/ empty even when the CacheGroup APIs are not used because the existing URL does not belong to any group.\t\t\t\r\n enumHandle = FindFirstUrlCacheGroup(0, CACHEGROUP_SEARCH_ALL, 0, 0, &groupId, 0);\r\n\r\n\t\/\/ If there are no items in the Cache, you are finished.\r\n\tif (enumHandle != NULL && ERROR_NO_MORE_ITEMS == GetLastError())\r\n\t\treturn 0;\r\n\t\r\n\t\/\/ Loop through Cache Group, and then delete entries.\r\n\tif (enumHandle != NULL)\r\n\t{\r\n\t\twhile (groupId != NULL)\r\n\t\t{\r\n\t\t\t\/\/ Delete a particular Cache Group.\r\n\t\t\treturnValue = DeleteUrlCacheGroup(groupId, CACHEGROUP_FLAG_FLUSHURL_ONDELETE, 0);\r\n\t\t\r\n\t\t\tif (!returnValue && ERROR_FILE_NOT_FOUND == GetLastError())\r\n\t\t\t{\t\r\n\t\t\t\treturnValue = FindNextUrlCacheGroup(enumHandle, &groupId, 0);\r\n\t\t\t}\r\n\t\t\r\n\t\t\tif (!returnValue && (ERROR_NO_MORE_ITEMS == GetLastError() || ERROR_FILE_NOT_FOUND == GetLastError()))\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t \/\/ Start to delete URLs that do not belong to any group.\r\n\tenumHandle = FindFirstUrlCacheEntry(NULL, 0, &cacheEntryInfoBufferSizeInitial);\r\n\tif (enumHandle == NULL && ERROR_NO_MORE_ITEMS == GetLastError())\r\n\t\treturn 0;\r\n\t\r\n\tcacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;\r\n\tinternetCacheEntry = (INTERNET_CACHE_ENTRY_INFO*)malloc(cacheEntryInfoBufferSize);\r\n\tenumHandle = FindFirstUrlCacheEntry(NULL, internetCacheEntry, &cacheEntryInfoBufferSizeInitial);\r\n\tif (enumHandle != NULL)\r\n\t{\r\n\t\twhile (internetCacheEntry != NULL)\r\n\t\t{\r\n\t\t\tcacheEntryInfoBufferSizeInitial = cacheEntryInfoBufferSize;\t\t\r\n\t\t\treturnValue = DeleteUrlCacheEntry(internetCacheEntry->lpszSourceUrlName);\t\t\t\t\r\n\t\t\r\n\t\t\tif (!returnValue)\r\n\t\t\t{\t\r\n\t\t\t\treturnValue = FindNextUrlCacheEntry(enumHandle, internetCacheEntry, &cacheEntryInfoBufferSizeInitial);\r\n\t\t\t}\r\n\t\t\r\n\t\t\tDWORD dwError = GetLastError();\r\n\t\t\tif (!returnValue && ERROR_NO_MORE_ITEMS == dwError)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\t\t\t\r\n\t\t\r\n\t\t\tif (!returnValue && cacheEntryInfoBufferSizeInitial > cacheEntryInfoBufferSize)\r\n\t\t\t{\r\n\t\t\t\tcacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;\r\n\t\t\t\tinternetCacheEntry = (INTERNET_CACHE_ENTRY_INFO*)realloc(internetCacheEntry, cacheEntryInfoBufferSize);\r\n\t\t\t\treturnValue = FindNextUrlCacheEntry(enumHandle, internetCacheEntry, &cacheEntryInfoBufferSizeInitial);\t\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tfree(internetCacheEntry);\r\n\treturn 0;\r\n}\r\n\r\nstd::wstring WebBrowserHelper::hexencode(const std::wstring& input)\r\n{\r\n\tstd::wostringstream ssOut;\r\n ssOut << std::setbase(16);\r\n for(std::wstring::const_iterator i = input.begin(); i != input.end(); ++i)\r\n {\r\n if(isalnum(*i))\r\n ssOut << *i;\r\n else\r\n ssOut << '%' << std::setw(2) << ((unsigned int)(unsigned char)*i);\r\n }\r\n return ssOut.str();\r\n}Modify MS ClearCache procedure to fix infinite loop#include \"StdAfx.h\"\r\n#include \"WebBrowserHelper.h\"\r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace Utilities::WebBrowser;\r\n\r\nWebBrowserHelper::WebBrowserHelper(void)\r\n{\r\n}\r\n\r\n\r\nWebBrowserHelper::~WebBrowserHelper(void)\r\n{\r\n}\r\n\r\nint WebBrowserHelper::ClearCache()\r\n{\r\n\t\/\/ Pointer to a GROUPID variable\r\n\tGROUPID groupId = 0;\r\n\t\r\n\t\/\/ Local variables\r\n\tDWORD cacheEntryInfoBufferSizeInitial = 0;\r\n DWORD cacheEntryInfoBufferSize = 0;\r\n int *cacheEntryInfoBuffer = 0;\r\n INTERNET_CACHE_ENTRY_INFO *internetCacheEntry;\r\n HANDLE enumHandle = NULL;\r\n BOOL returnValue = false;\r\n\r\n\t\/\/ Delete the groups first.\r\n \/\/ Groups may not always exist on the system.\r\n \/\/ For more information, visit the following Microsoft Web site:\r\n \/\/ http:\/\/msdn2.microsoft.com\/en-us\/library\/ms909365.aspx\t\t\t\r\n \/\/ By default, a URL does not belong to any group. Therefore, that cache may become\r\n \/\/ empty even when the CacheGroup APIs are not used because the existing URL does not belong to any group.\t\t\t\r\n enumHandle = FindFirstUrlCacheGroup(0, CACHEGROUP_SEARCH_ALL, 0, 0, &groupId, 0);\r\n\r\n\t\/\/ If there are no items in the Cache, you are finished.\r\n\tif (enumHandle != NULL && ERROR_NO_MORE_ITEMS == GetLastError())\r\n\t\treturn 0;\r\n\t\r\n\t\/\/ Loop through Cache Group, and then delete entries.\r\n\tif (enumHandle != NULL)\r\n\t{\r\n\t\twhile (1)\r\n\t\t{\r\n\t\t\t\/\/ Delete a particular Cache Group.\r\n\t\t\treturnValue = DeleteUrlCacheGroup(groupId, CACHEGROUP_FLAG_FLUSHURL_ONDELETE, 0);\r\n\t\t\r\n\t\t\treturnValue = FindNextUrlCacheGroup(enumHandle, &groupId, 0);\r\n\t\t\t\r\n\t\t\tif (!returnValue)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t \/\/ Start to delete URLs that do not belong to any group.\r\n\tenumHandle = FindFirstUrlCacheEntry(NULL, 0, &cacheEntryInfoBufferSizeInitial);\r\n\tif (enumHandle == NULL && ERROR_NO_MORE_ITEMS == GetLastError())\r\n\t\treturn 0;\r\n\t\r\n\tcacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;\r\n\tinternetCacheEntry = (INTERNET_CACHE_ENTRY_INFO*)malloc(cacheEntryInfoBufferSize);\r\n\tenumHandle = FindFirstUrlCacheEntry(NULL, internetCacheEntry, &cacheEntryInfoBufferSizeInitial);\r\n\tif (enumHandle != NULL)\r\n\t{\r\n\t\twhile (1)\r\n\t\t{\r\n\t\t\tcacheEntryInfoBufferSizeInitial = cacheEntryInfoBufferSize;\t\t\r\n\t\t\treturnValue = DeleteUrlCacheEntry(internetCacheEntry->lpszSourceUrlName);\t\t\t\t\r\n\t\t\r\n\t\t\t\/\/ Allows try to get the next entry\r\n\t\t\treturnValue = FindNextUrlCacheEntry(enumHandle, internetCacheEntry, &cacheEntryInfoBufferSizeInitial);\r\n\t\t\t\r\n\t\t\tDWORD dwError = GetLastError();\r\n\t\t\tif (!returnValue && ERROR_NO_MORE_ITEMS == dwError)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\t\t\t\r\n\t\t\r\n\t\t\tif (!returnValue && cacheEntryInfoBufferSizeInitial > cacheEntryInfoBufferSize)\r\n\t\t\t{\r\n\t\t\t\tcacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;\r\n\t\t\t\tinternetCacheEntry = (INTERNET_CACHE_ENTRY_INFO*)realloc(internetCacheEntry, cacheEntryInfoBufferSize);\r\n\t\t\t\treturnValue = FindNextUrlCacheEntry(enumHandle, internetCacheEntry, &cacheEntryInfoBufferSizeInitial);\t\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tfree(internetCacheEntry);\r\n\treturn 0;\r\n}\r\n\r\nstd::wstring WebBrowserHelper::hexencode(const std::wstring& input)\r\n{\r\n\tstd::wostringstream ssOut;\r\n ssOut << std::setbase(16);\r\n for(std::wstring::const_iterator i = input.begin(); i != input.end(); ++i)\r\n {\r\n if(isalnum(*i))\r\n ssOut << *i;\r\n else\r\n ssOut << '%' << std::setw(2) << ((unsigned int)(unsigned char)*i);\r\n }\r\n return ssOut.str();\r\n}<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkGenericDataSetTessellator.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkGenericDataSetTessellator.h\"\n\n#include \"vtkObjectFactory.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkPointData.h\"\n#include \"vtkTetra.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkUnsignedCharArray.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkMergePoints.h\"\n#include \"vtkGenericDataSet.h\"\n#include \"vtkGenericCellIterator.h\"\n#include \"vtkGenericAdaptorCell.h\"\n\nvtkCxxRevisionMacro(vtkGenericDataSetTessellator, \"1.2\");\nvtkStandardNewMacro(vtkGenericDataSetTessellator);\n\n\/\/----------------------------------------------------------------------------\n\/\/\nvtkGenericDataSetTessellator::vtkGenericDataSetTessellator()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvtkGenericDataSetTessellator::~vtkGenericDataSetTessellator()\n{\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/\nvoid vtkGenericDataSetTessellator::Execute()\n{\n vtkDebugMacro(<< \"Executing vtkGenericDataSetTessellator...\");\n\n vtkGenericDataSet *input = this->GetInput();\n vtkUnstructuredGrid *output = this->GetOutput();\n vtkIdType numPts = input->GetNumberOfPoints();\n vtkIdType numCells = input->GetNumberOfCells();\n vtkPointData *outputPD = output->GetPointData();\n vtkCellData *outputCD = output->GetCellData();\n vtkGenericAdaptorCell *cell;\n vtkIdType numInserted=0, numNew, i;\n vtkIdType npts, *pts;\n\n \/\/ Copy original points and point data\n vtkPoints *newPts = vtkPoints::New();\n newPts->Allocate(2*numPts,numPts);\n\n \/\/ loop over region\n vtkUnsignedCharArray *types = vtkUnsignedCharArray::New();\n types->Allocate(numCells);\n vtkIdTypeArray *locs = vtkIdTypeArray::New();\n locs->Allocate(numCells);\n vtkCellArray *conn = vtkCellArray::New();\n conn->Allocate(numCells);\n\n vtkGenericCellIterator *cellIt = input->NewCellIterator();\n for(cellIt->Begin(); !cellIt->IsAtEnd(); cellIt->Next())\n {\n cell = cellIt->GetCell();\n cell->Tessellate(input->GetAttributes(), input->GetTessellator(),\n newPts, conn, outputPD, outputCD);\n\n numNew = conn->GetNumberOfCells() - numInserted;\n numInserted = conn->GetNumberOfCells();\n \n for (i=0; i < numNew; i++) \n {\n locs->InsertNextValue(conn->GetTraversalLocation());\n conn->GetNextCell(npts,pts); \/\/side effect updates traversal location\n switch (cell->GetDimension())\n {\n case 1:\n types->InsertNextValue(VTK_LINE);\n break;\n case 2:\n types->InsertNextValue(VTK_TRIANGLE);\n break;\n case 3:\n types->InsertNextValue(VTK_TETRA);\n break;\n default:\n vtkErrorMacro(<<\"Bad mojo in data set tessellation\");\n } \/\/switch\n } \/\/insert each new cell\n } \/\/for all cells\n cellIt->Delete();\n \n \/\/ Send to the output\n output->SetPoints(newPts);\n output->SetCells(types, locs, conn);\n\n vtkDebugMacro(<<\"Subdivided \" << numCells << \" cells to produce \"\n << conn->GetNumberOfCells() << \"new cells\");\n\n newPts->Delete();\n types->Delete();\n locs->Delete();\n conn->Delete();\n\n output->Squeeze(); \n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGenericDataSetTessellator::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n}\nERR:Handle progress events and abort\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkGenericDataSetTessellator.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkGenericDataSetTessellator.h\"\n\n#include \"vtkObjectFactory.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkPointData.h\"\n#include \"vtkTetra.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkUnsignedCharArray.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkMergePoints.h\"\n#include \"vtkGenericDataSet.h\"\n#include \"vtkGenericCellIterator.h\"\n#include \"vtkGenericAdaptorCell.h\"\n\nvtkCxxRevisionMacro(vtkGenericDataSetTessellator, \"1.3\");\nvtkStandardNewMacro(vtkGenericDataSetTessellator);\n\n\/\/----------------------------------------------------------------------------\n\/\/\nvtkGenericDataSetTessellator::vtkGenericDataSetTessellator()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvtkGenericDataSetTessellator::~vtkGenericDataSetTessellator()\n{\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/\nvoid vtkGenericDataSetTessellator::Execute()\n{\n vtkDebugMacro(<< \"Executing vtkGenericDataSetTessellator...\");\n\n vtkGenericDataSet *input = this->GetInput();\n vtkUnstructuredGrid *output = this->GetOutput();\n vtkIdType numPts = input->GetNumberOfPoints();\n vtkIdType numCells = input->GetNumberOfCells();\n vtkPointData *outputPD = output->GetPointData();\n vtkCellData *outputCD = output->GetCellData();\n vtkGenericAdaptorCell *cell;\n vtkIdType numInserted=0, numNew, i;\n vtkIdType npts, *pts;\n int abortExecute=0;\n\n \/\/ Copy original points and point data\n vtkPoints *newPts = vtkPoints::New();\n newPts->Allocate(2*numPts,numPts);\n\n \/\/ loop over region\n vtkUnsignedCharArray *types = vtkUnsignedCharArray::New();\n types->Allocate(numCells);\n vtkIdTypeArray *locs = vtkIdTypeArray::New();\n locs->Allocate(numCells);\n vtkCellArray *conn = vtkCellArray::New();\n conn->Allocate(numCells);\n\n vtkGenericCellIterator *cellIt = input->NewCellIterator();\n vtkIdType updateTime = numCells\/20 + 1; \/\/ update roughly every 5%\n vtkIdType count = 0;\n for(cellIt->Begin(); !cellIt->IsAtEnd() && !abortExecute; cellIt->Next(), count++)\n {\n if ( !(count % updateTime) )\n {\n this->UpdateProgress((double)count \/ numCells);\n abortExecute = this->GetAbortExecute();\n }\n\n cell = cellIt->GetCell();\n cell->Tessellate(input->GetAttributes(), input->GetTessellator(),\n newPts, conn, outputPD, outputCD);\n\n numNew = conn->GetNumberOfCells() - numInserted;\n numInserted = conn->GetNumberOfCells();\n \n for (i=0; i < numNew; i++) \n {\n locs->InsertNextValue(conn->GetTraversalLocation());\n conn->GetNextCell(npts,pts); \/\/side effect updates traversal location\n switch (cell->GetDimension())\n {\n case 1:\n types->InsertNextValue(VTK_LINE);\n break;\n case 2:\n types->InsertNextValue(VTK_TRIANGLE);\n break;\n case 3:\n types->InsertNextValue(VTK_TETRA);\n break;\n default:\n vtkErrorMacro(<<\"Bad mojo in data set tessellation\");\n } \/\/switch\n } \/\/insert each new cell\n } \/\/for all cells\n cellIt->Delete();\n \n \/\/ Send to the output\n output->SetPoints(newPts);\n output->SetCells(types, locs, conn);\n\n vtkDebugMacro(<<\"Subdivided \" << numCells << \" cells to produce \"\n << conn->GetNumberOfCells() << \"new cells\");\n\n newPts->Delete();\n types->Delete();\n locs->Delete();\n conn->Delete();\n\n output->Squeeze(); \n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkGenericDataSetTessellator::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n}\n<|endoftext|>"} {"text":"\/\/\/ @file SNIIS_Linux.cpp\n\/\/\/ Linux implementation of input\n\n#include \"SNIIS_Linux.h\"\n#include \"SNIIS_Intern.h\"\n\n#if SNIIS_SYSTEM_LINUX\nusing namespace SNIIS;\n#include \"..\/Traumklassen\/TraumBasis.h\"\n\n#include \n#include \n#include \n#include \n\nstatic bool IsBitSet( const uint8_t* bits, size_t i) { return (bits[i\/8] & (1<<(i&7))) != 0; }\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Constructor\nLinuxInput::LinuxInput( Window wnd)\n{\n mWindow = wnd;\n mDisplay = nullptr;\n\n mDisplay = XOpenDisplay( nullptr);\n if( !mDisplay )\n throw std::runtime_error( \"Failed to open XDisplay\");\n\n int event = 0, error = 0;\n int major = 2, minor = 0;\n bool isAvailable = (XQueryExtension( mDisplay, \"XInputExtension\", &mXiOpcode, &event, &error) != False\n && XIQueryVersion( mDisplay, &major, &minor) != BadRequest);\n if( !isAvailable )\n throw std::runtime_error( \"Failed to get XInputExtension\");\n\n \/\/ Register for events\n XIEventMask evmask;\n uint8_t mask[] = { 0, 0, 0, 0 };\n XISetMask( mask, XI_HierarchyChanged);\n XISetMask( mask, XI_RawMotion);\n XISetMask( mask, XI_RawButtonPress);\n XISetMask( mask, XI_RawButtonRelease);\n XISetMask( mask, XI_RawKeyPress);\n XISetMask( mask, XI_RawKeyRelease);\n\n evmask.deviceid = XIAllDevices;\n evmask.mask_len = sizeof( mask);\n evmask.mask = mask;\n auto selwnd = DefaultRootWindow( mDisplay);\n if( XISelectEvents( mDisplay, selwnd, &evmask, 1) != 0 )\n throw std::runtime_error( \"Failed to register for XInput2 events\");\n\n int deviceCount = 0;\n XIDeviceInfo* devices = XIQueryDevice( mDisplay, XIAllDevices, &deviceCount);\n for( int i = 0; i < deviceCount; i++ )\n {\n \/* We only look at \"slave\" devices. \"Master\" pointers are the logical\n * cursors, \"slave\" pointers are the hardware that back them.\n * \"Floating slaves\" are hardware that don't back a cursor.\n *\/\n\n switch( devices[i].use )\n {\n case XISlavePointer:\n case XIFloatingSlave:\n {\n Traum::Konsole.Log( \"Mouse %d (id %d) - \\\"%s\\\"\", mNumMice, mDevices.size(), devices[i].name);\n\n \/\/ a mouse. probably. Ignore some common pffft cases\n if( strstr(devices[i].name, \"XTEST\") != nullptr )\n break;\n\n try {\n auto m = new LinuxMouse( this, mDevices.size(), devices[i]);\n InputSystemHelper::AddDevice( m);\n mMiceById[devices[i].deviceid] = m;\n } catch( std::exception& e)\n {\n \/\/ TODO: invent logging\n Traum::Konsole.Log( \"Exception: %s\", e.what());\n }\n break;\n }\n\n case XISlaveKeyboard:\n {\n Traum::Konsole.Log( \"Keyboard %d (id %d) - \\\"%s\\\"\", mNumKeyboards, mDevices.size(), devices[i].name);\n \/\/ a keyboard\n if( strstr(devices[i].name, \"XTEST\") != nullptr )\n break;\n\n try {\n auto k = new LinuxKeyboard( this, mDevices.size(), devices[i]);\n InputSystemHelper::AddDevice( k);\n mKeyboardsById[devices[i].deviceid] = k;\n } catch( std::exception& e)\n {\n \/\/ TODO: invent logging\n Traum::Konsole.Log( \"Exception: %s\", e.what());\n }\n break;\n }\n\n default:\n \/\/ pffft.\n break;\n }\n }\n\n XIFreeDeviceInfo( devices);\n\n \/\/ use a completely different API for controllers, because XInput would be perfectly capable of supporting\n \/\/ those, too, but refuses to do so. It enumerates my USB headset as a keyboard, but it does not expose\n \/\/ my XBox controller. Sometimes I wish to look into the coders' minds and learn what possessed them when\n \/\/ designing x separate APIs for the same purpose, but each with a different set of flaws.\n\tfor( size_t a = 0; a < 64; ++a )\n\t{\n\t\tstd::stringstream eventPath;\n\t\teventPath << \"\/dev\/input\/event\" << a;\n\t\tint fd = open( eventPath.str().c_str(), O_RDWR |O_NONBLOCK );\n\t\tif( fd == -1 )\n\t\t\tcontinue;\n\n char tmp[256] = \"Unknown\";\n if( ioctl( fd, EVIOCGNAME( sizeof( tmp)), tmp) < 0)\n throw std::runtime_error( \"Could not read device name\");\n\n Traum::Konsole.Log( \"Controller %d (id %d) - \\\"%s\\\"\", mNumJoysticks, mDevices.size(), &tmp[0]);\n\n \/\/ check if it's a controller. If we're started with root privileges, we'd get mice and keyboards here, too,\n \/\/ but we can't rely on it, so we sort those out and only use it for controllers.\n \/\/ (Side note: mice and keyboards are root-only because you'd otherwise be able to write a keylogger with it.\n \/\/ It will take a few years until someone will notice that on SteamOS you enter your credit card credentials\n \/\/ and passwords with a controller. Then it's a viable approach to also spy on the controller, so they'll\n \/\/ probably make the controllers root-only, too, and this whole mess finally ends up\n \/\/ in the \"Linux Hall Of Self-Digged Graves\" where it belongs. Sorry for the rant.)\n uint8_t ev_bits[(EV_MAX+7)\/8];\n memset( ev_bits, 0, sizeof(ev_bits) );\n\n \/\/Read \"all\" (hence 0) components of the device\n if( ioctl( fd, EVIOCGBIT(0, sizeof(ev_bits)), ev_bits) == -1 )\n throw std::runtime_error( \"Could not read device events features\");\n\n if( IsBitSet( ev_bits, EV_KEY) )\n {\n uint8_t key_bits[(KEY_MAX+7)\/8];\n memset( key_bits, 0, sizeof(key_bits) );\n\n if( ioctl( fd, EVIOCGBIT( EV_KEY, sizeof(key_bits)), key_bits) == -1 )\n throw std::runtime_error( \"Could not read device buttons features\");\n\n bool isController = false;\n for( size_t b = 0; b < KEY_MAX; b++ )\n {\n if( IsBitSet( key_bits, b) )\n {\n \/\/ Check to ensure we find at least one joy only button\n if( (b >= BTN_JOYSTICK && b < BTN_GAMEPAD) || (b >= BTN_GAMEPAD && b < BTN_DIGI) || (b >= BTN_WHEEL && b < KEY_OK) )\n isController = true;\n }\n }\n\n if( isController )\n {\n try {\n auto j = new LinuxJoystick( this, mDevices.size(), fd);\n InputSystemHelper::AddDevice( j);\n } catch( std::exception& e)\n {\n \/\/ TODO: invent logging\n Traum::Konsole.Log( \"Exception: %s\", e.what());\n }\n } else\n {\n close( fd);\n }\n }\n\t}\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Destructor\nLinuxInput::~LinuxInput()\n{\n for( auto d : mDevices )\n delete d;\n\n if( mDisplay != nullptr )\n XCloseDisplay( mDisplay);\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Updates the inputs, to be called before handling system messages\nvoid LinuxInput::Update()\n{\n \/\/ Basis work\n InputSystem::Update();\n\n \/\/ begin updating all devices\n for( auto d : mDevices )\n {\n if( auto mouse = dynamic_cast (d) )\n mouse->StartUpdate();\n else if( auto keyboard = dynamic_cast (d) )\n keyboard->StartUpdate();\n else if( auto joy = dynamic_cast (d) )\n joy->StartUpdate();\n }\n\n \/\/ process XEvents\n XEvent event;\n\twhile( XPending( mDisplay) > 0 )\n\t{\n\t\tXNextEvent( mDisplay, &event);\n\n if( event.xcookie.type != GenericEvent )\n continue;\n else if( event.xcookie.extension != mXiOpcode )\n continue;\n else if( !XGetEventData( mDisplay, &event.xcookie) )\n continue;\n\n switch( event.xcookie.evtype )\n {\n case XI_RawMotion:\n case XI_RawButtonPress:\n case XI_RawButtonRelease:\n {\n auto rawev = *((const XIRawEvent *) event.xcookie.data);\n auto mit = mMiceById.find( rawev.deviceid);\n if( mit == mMiceById.end() )\n break;\n mit->second->HandleEvent( rawev);\n break;\n }\n\n case XI_RawKeyPress:\n case XI_RawKeyRelease:\n {\n auto rawev = *((const XIRawEvent *) event.xcookie.data);\n auto kit = mKeyboardsById.find( rawev.deviceid);\n if( kit == mKeyboardsById.end() )\n break;\n kit->second->HandleEvent( rawev);\n break;\n }\n }\n\n XFreeEventData( mDisplay, &event.xcookie);\n }\n\n \/\/ update postprocessing\n for( auto d : mDevices )\n {\n if( auto mouse = dynamic_cast (d) )\n mouse->EndUpdate();\n }\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Notifies the input system that the application has lost\/gained focus.\nvoid LinuxInput::InternSetFocus( bool pHasFocus)\n{\n for( auto d : mDevices )\n {\n if( auto k = dynamic_cast (d) )\n k->SetFocus( mHasFocus);\n else if( auto m = dynamic_cast (d) )\n m->SetFocus( mHasFocus);\n else if( auto j = dynamic_cast (d) )\n j->SetFocus( mHasFocus);\n }\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\nvoid LinuxInput::InternSetMouseGrab( bool enabled)\n{\n \/\/ The Linux XInput2 API is nice to already provide mouse acceleration and all, so all that mouse coordinate cheating\n \/\/ is simply not necessary. Just grab the mouse and be happy\n if( enabled )\n {\n XGrabPointer( mDisplay, mWindow, True, 0, GrabModeAsync, GrabModeAsync, mWindow, None, CurrentTime);\n } else\n {\n XUngrabPointer( mDisplay, CurrentTime);\n }\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Initializes the input system with the given InitArgs. When successful, gInstance is not Null.\nbool InputSystem::Initialize(void* pInitArg)\n{\n if( gInstance )\n throw std::runtime_error( \"Input already initialized\");\n\n try\n {\n gInstance = new LinuxInput( (Window) pInitArg);\n } catch( std::exception& )\n {\n \/\/ nope\n gInstance = nullptr;\n return false;\n }\n\n return true;\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Destroys the input system. After returning gInstance is Null again\nvoid InputSystem::Shutdown()\n{\n delete gInstance;\n gInstance = nullptr;\n}\n\n#endif \/\/ SNIIS_SYSTEM_LINUX\n- improved guessing the device type on Linux\/\/\/ @file SNIIS_Linux.cpp\n\/\/\/ Linux implementation of input\n\n#include \"SNIIS_Linux.h\"\n#include \"SNIIS_Intern.h\"\n\n#if SNIIS_SYSTEM_LINUX\nusing namespace SNIIS;\n#include \"..\/Traumklassen\/TraumBasis.h\"\n\n#include \n#include \n#include \n#include \n\nstatic bool IsBitSet( const uint8_t* bits, size_t i) { return (bits[i\/8] & (1<<(i&7))) != 0; }\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Constructor\nLinuxInput::LinuxInput( Window wnd)\n{\n mWindow = wnd;\n mDisplay = nullptr;\n\n mDisplay = XOpenDisplay( nullptr);\n if( !mDisplay )\n throw std::runtime_error( \"Failed to open XDisplay\");\n\n int event = 0, error = 0;\n int major = 2, minor = 0;\n bool isAvailable = (XQueryExtension( mDisplay, \"XInputExtension\", &mXiOpcode, &event, &error) != False\n && XIQueryVersion( mDisplay, &major, &minor) != BadRequest);\n if( !isAvailable )\n throw std::runtime_error( \"Failed to get XInputExtension\");\n\n \/\/ Register for events\n XIEventMask evmask;\n uint8_t mask[] = { 0, 0, 0, 0 };\n XISetMask( mask, XI_HierarchyChanged);\n XISetMask( mask, XI_RawMotion);\n XISetMask( mask, XI_RawButtonPress);\n XISetMask( mask, XI_RawButtonRelease);\n XISetMask( mask, XI_RawKeyPress);\n XISetMask( mask, XI_RawKeyRelease);\n\n evmask.deviceid = XIAllDevices;\n evmask.mask_len = sizeof( mask);\n evmask.mask = mask;\n auto selwnd = DefaultRootWindow( mDisplay);\n if( XISelectEvents( mDisplay, selwnd, &evmask, 1) != 0 )\n throw std::runtime_error( \"Failed to register for XInput2 events\");\n\n int deviceCount = 0;\n XIDeviceInfo* devices = XIQueryDevice( mDisplay, XIAllDevices, &deviceCount);\n for( int i = 0; i < deviceCount; i++ )\n {\n \/* We only look at \"slave\" devices. \"Master\" pointers are the logical\n * cursors, \"slave\" pointers are the hardware that back them.\n * \"Floating slaves\" are hardware that don't back a cursor.\n *\/\n\n switch( devices[i].use )\n {\n case XISlavePointer:\n {\n Traum::Konsole.Log( \"Mouse %d (id %d) - \\\"%s\\\"\", mNumMice, mDevices.size(), devices[i].name);\n\n \/\/ a mouse. probably. Ignore some common pffft cases\n if( strstr(devices[i].name, \"XTEST\") != nullptr )\n break;\n\n try {\n auto m = new LinuxMouse( this, mDevices.size(), devices[i]);\n InputSystemHelper::AddDevice( m);\n mMiceById[devices[i].deviceid] = m;\n } catch( std::exception& e)\n {\n \/\/ TODO: invent logging\n Traum::Konsole.Log( \"Exception: %s\", e.what());\n }\n break;\n }\n\n case XISlaveKeyboard:\n {\n Traum::Konsole.Log( \"Keyboard %d (id %d) - \\\"%s\\\"\", mNumKeyboards, mDevices.size(), devices[i].name);\n \/\/ a keyboard\n if( strstr(devices[i].name, \"XTEST\") != nullptr )\n break;\n\n try {\n auto k = new LinuxKeyboard( this, mDevices.size(), devices[i]);\n InputSystemHelper::AddDevice( k);\n mKeyboardsById[devices[i].deviceid] = k;\n } catch( std::exception& e)\n {\n \/\/ TODO: invent logging\n Traum::Konsole.Log( \"Exception: %s\", e.what());\n }\n break;\n }\n\n case XIFloatingSlave:\n {\n \/\/ Look through the controls of this device - if we find two absolute axes at 0 and 1, it might be a mouse.\n \/\/ Otherwise register it as a keyboard.\n const auto& dev = devices[i];\n bool isAxisPresent[2] = { false, false };\n for( int a = 0; a < dev.num_classes; ++a )\n {\n auto cl = dev.classes[a];\n if( cl->type != XIValuatorClass )\n continue;\n\n auto vcl = reinterpret_cast (cl);\n if( vcl->number < 2 && vcl->mode == XIModeAbsolute )\n isAxisPresent[vcl->number] = true;\n }\n\n try {\n if( isAxisPresent[0] && isAxisPresent[1] )\n {\n Traum::Konsole.Log( \"Floating slave \\\"%s\\\", seems to be mouse %d (id %d)\", devices[i].name, mNumMice, mDevices.size());\n auto m = new LinuxMouse( this, mDevices.size(), dev);\n InputSystemHelper::AddDevice( m);\n mMiceById[dev.deviceid] = m;\n } else\n {\n Traum::Konsole.Log( \"Floating slave \\\"%s\\\", seems to be keyboard %d (id %d)\", devices[i].name, mNumKeyboards, mDevices.size());\n auto k = new LinuxKeyboard( this, mDevices.size(), dev);\n InputSystemHelper::AddDevice( k);\n mKeyboardsById[dev.deviceid] = k;\n }\n } catch( std::exception& e)\n {\n \/\/ TODO: invent logging\n Traum::Konsole.Log( \"Exception: %s\", e.what());\n }\n break;\n }\n\n default:\n \/\/ pffft.\n Traum::Konsole.Log( \"Unknown device classs %d, ignoring.\", devices[i].use);\n break;\n }\n }\n\n XIFreeDeviceInfo( devices);\n\n \/\/ use a completely different API for controllers, because XInput would be perfectly capable of supporting\n \/\/ those, too, but refuses to do so. It enumerates my USB headset as a keyboard, but it does not expose\n \/\/ my XBox controller. Sometimes I wish to look into the coders' minds and learn what possessed them when\n \/\/ designing x separate APIs for the same purpose, but each with a different set of flaws.\n\tfor( size_t a = 0; a < 64; ++a )\n\t{\n\t\tstd::stringstream eventPath;\n\t\teventPath << \"\/dev\/input\/event\" << a;\n\t\tint fd = open( eventPath.str().c_str(), O_RDWR |O_NONBLOCK );\n\t\tif( fd == -1 )\n\t\t\tcontinue;\n\n char tmp[256] = \"Unknown\";\n if( ioctl( fd, EVIOCGNAME( sizeof( tmp)), tmp) < 0)\n throw std::runtime_error( \"Could not read device name\");\n\n Traum::Konsole.Log( \"Controller %d (id %d) - \\\"%s\\\"\", mNumJoysticks, mDevices.size(), &tmp[0]);\n\n \/\/ check if it's a controller. If we're started with root privileges, we'd get mice and keyboards here, too,\n \/\/ but we can't rely on it, so we sort those out and only use it for controllers.\n \/\/ (Side note: mice and keyboards are root-only because you'd otherwise be able to write a keylogger with it.\n \/\/ It will take a few years until someone will notice that on SteamOS you enter your credit card credentials\n \/\/ and passwords with a controller. Then it's a viable approach to also spy on the controller, so they'll\n \/\/ probably make the controllers root-only, too, and this whole mess finally ends up\n \/\/ in the \"Linux Hall Of Self-Digged Graves\" where it belongs. Sorry for the rant.)\n uint8_t ev_bits[(EV_MAX+7)\/8];\n memset( ev_bits, 0, sizeof(ev_bits) );\n\n \/\/Read \"all\" (hence 0) components of the device\n if( ioctl( fd, EVIOCGBIT(0, sizeof(ev_bits)), ev_bits) == -1 )\n throw std::runtime_error( \"Could not read device events features\");\n\n if( IsBitSet( ev_bits, EV_KEY) )\n {\n uint8_t key_bits[(KEY_MAX+7)\/8];\n memset( key_bits, 0, sizeof(key_bits) );\n\n if( ioctl( fd, EVIOCGBIT( EV_KEY, sizeof(key_bits)), key_bits) == -1 )\n throw std::runtime_error( \"Could not read device buttons features\");\n\n bool isController = false;\n for( size_t b = 0; b < KEY_MAX; b++ )\n {\n if( IsBitSet( key_bits, b) )\n {\n \/\/ Check to ensure we find at least one joy only button\n if( (b >= BTN_JOYSTICK && b < BTN_GAMEPAD) || (b >= BTN_GAMEPAD && b < BTN_DIGI) || (b >= BTN_WHEEL && b < KEY_OK) )\n isController = true;\n }\n }\n\n if( isController )\n {\n try {\n auto j = new LinuxJoystick( this, mDevices.size(), fd);\n InputSystemHelper::AddDevice( j);\n } catch( std::exception& e)\n {\n \/\/ TODO: invent logging\n Traum::Konsole.Log( \"Exception: %s\", e.what());\n }\n } else\n {\n close( fd);\n }\n }\n\t}\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Destructor\nLinuxInput::~LinuxInput()\n{\n for( auto d : mDevices )\n delete d;\n\n if( mDisplay != nullptr )\n XCloseDisplay( mDisplay);\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Updates the inputs, to be called before handling system messages\nvoid LinuxInput::Update()\n{\n \/\/ Basis work\n InputSystem::Update();\n\n \/\/ begin updating all devices\n for( auto d : mDevices )\n {\n if( auto mouse = dynamic_cast (d) )\n mouse->StartUpdate();\n else if( auto keyboard = dynamic_cast (d) )\n keyboard->StartUpdate();\n else if( auto joy = dynamic_cast (d) )\n joy->StartUpdate();\n }\n\n \/\/ process XEvents\n XEvent event;\n\twhile( XPending( mDisplay) > 0 )\n\t{\n\t\tXNextEvent( mDisplay, &event);\n\n if( event.xcookie.type != GenericEvent )\n continue;\n else if( event.xcookie.extension != mXiOpcode )\n continue;\n else if( !XGetEventData( mDisplay, &event.xcookie) )\n continue;\n\n switch( event.xcookie.evtype )\n {\n case XI_RawMotion:\n case XI_RawButtonPress:\n case XI_RawButtonRelease:\n {\n auto rawev = *((const XIRawEvent *) event.xcookie.data);\n auto mit = mMiceById.find( rawev.deviceid);\n if( mit == mMiceById.end() )\n break;\n mit->second->HandleEvent( rawev);\n break;\n }\n\n case XI_RawKeyPress:\n case XI_RawKeyRelease:\n {\n auto rawev = *((const XIRawEvent *) event.xcookie.data);\n auto kit = mKeyboardsById.find( rawev.deviceid);\n if( kit == mKeyboardsById.end() )\n break;\n kit->second->HandleEvent( rawev);\n break;\n }\n }\n\n XFreeEventData( mDisplay, &event.xcookie);\n }\n\n \/\/ update postprocessing\n for( auto d : mDevices )\n {\n if( auto mouse = dynamic_cast (d) )\n mouse->EndUpdate();\n }\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Notifies the input system that the application has lost\/gained focus.\nvoid LinuxInput::InternSetFocus( bool pHasFocus)\n{\n for( auto d : mDevices )\n {\n if( auto k = dynamic_cast (d) )\n k->SetFocus( mHasFocus);\n else if( auto m = dynamic_cast (d) )\n m->SetFocus( mHasFocus);\n else if( auto j = dynamic_cast (d) )\n j->SetFocus( mHasFocus);\n }\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\nvoid LinuxInput::InternSetMouseGrab( bool enabled)\n{\n \/\/ The Linux XInput2 API is nice to already provide mouse acceleration and all, so all that mouse coordinate cheating\n \/\/ is simply not necessary. Just grab the mouse and be happy\n if( enabled )\n {\n XGrabPointer( mDisplay, mWindow, True, 0, GrabModeAsync, GrabModeAsync, mWindow, None, CurrentTime);\n } else\n {\n XUngrabPointer( mDisplay, CurrentTime);\n }\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Initializes the input system with the given InitArgs. When successful, gInstance is not Null.\nbool InputSystem::Initialize(void* pInitArg)\n{\n if( gInstance )\n throw std::runtime_error( \"Input already initialized\");\n\n try\n {\n gInstance = new LinuxInput( (Window) pInitArg);\n } catch( std::exception& )\n {\n \/\/ nope\n gInstance = nullptr;\n return false;\n }\n\n return true;\n}\n\n\/\/ --------------------------------------------------------------------------------------------------------------------\n\/\/ Destroys the input system. After returning gInstance is Null again\nvoid InputSystem::Shutdown()\n{\n delete gInstance;\n gInstance = nullptr;\n}\n\n#endif \/\/ SNIIS_SYSTEM_LINUX\n<|endoftext|>"} {"text":"#include \"process.h\"\n#include \n#include \n#include \n#include \n#include \n\n#if defined(__linux__)\n# include \n# include \n# include \nnamespace scpak\n{\n const char pathsep = '\/';\n\n void createDirectory(const char *path)\n {\n int result = mkdir(path, 0777);\n if (result == -1)\n throw std::runtime_error(\"failed to create directory: \" + std::string(path));\n }\n\n bool directoryExists(const char *path)\n {\n return access(path, F_OK) == 0;\n }\n\n int getFileSize(const char *path)\n {\n unsigned long filesize = -1;\n struct stat statbuf;\n if (stat(path, &statbuf) < 0)\n throw std::runtime_error(\"failed to get stat: \" + std::string(path));\n filesize = statbuf.st_size;\n return static_cast(filesize);\n }\n}\n#elif defined(MSV_VER)\n# include \nnamespace scpak\n{\n const char pathsep = '\\\\';\n\n void createDirectory(const char *path)\n {\n int result = _mkdir(path);\n if (result == -1)\n throw std::runtime_error(\"failed to create directory: \" + std::string(path));\n }\n bool directoryExists(const char *path)\n {\n return _access(path, 0) == 0;\n }\n}\n#endif\n\nnamespace scpak\n{\n void unpack(const PakFile &pak, const std::string &dirPath)\n {\n std::string dirPathSafe = dirPath;\n if (*dirPathSafe.rbegin() != pathsep)\n dirPathSafe += pathsep;\n \/\/ find all the directories we possibly need to create\n std::set directoriesToCreate;\n directoriesToCreate.insert(dirPath);\n for (const PakItem &item : pak.contents())\n {\n std::string filePath = dirPathSafe + item.name;\n std::size_t pend = filePath.rfind(pathsep);\n if (pend == std::string::npos)\n continue;\n std::size_t p = 0;\n while (p != pend)\n {\n p = filePath.find(pathsep, p+1);\n directoriesToCreate.insert(filePath.substr(0, p));\n }\n }\n \/\/ create directories if necessary\n for (const std::string &dir : directoriesToCreate)\n if (!directoryExists(dir.c_str()))\n createDirectory(dir.c_str());\n \/\/ unpack contents\n for (const PakItem &item : pak.contents())\n {\n if (std::strcmp(item.type, \"System.String\") == 0)\n {\n std::ofstream fout(dirPathSafe + item.name + \".txt\", std::ios::binary);\n std::stringstream ss(reinterpret_cast(item.data));\n BinaryReader reader(&ss);\n std::string value = reader.readString();\n fout.write(value.data(), value.length());\n fout.close();\n }\n else if (std::strcmp(item.type, \"System.Xml.Linq.XElement\") == 0)\n {\n std::ofstream fout(dirPathSafe + item.name + \".xml\", std::ios::binary);\n std::stringstream ss(reinterpret_cast(item.data));\n BinaryReader reader(&ss);\n std::string value = reader.readString();\n fout.write(value.data(), value.length());\n fout.close();\n }\n else\n {\n \/\/ just write out raw data\n std::ofstream fout(dirPathSafe + item.name, std::ios::binary);\n fout.write(reinterpret_cast(item.data), item.length);\n fout.close();\n }\n }\n \/\/ write pakinfo.txt - we need to repack it later\n std::ofstream fout(dirPathSafe + \"pakinfo.txt\");\n for (const PakItem &item : pak.contents())\n fout << item.name << ':' << item.type << std::endl;\n fout.close();\n }\n\n PakFile pack(const std::string &dirPath)\n {\n PakFile pak;\n std::vector contents = pak.contents();\n std::string dirPathSafe = dirPath;\n if (*dirPathSafe.rbegin() != pathsep)\n dirPathSafe += pathsep;\n std::ifstream fPakInfo(dirPathSafe + \"pakinfo.txt\");\n std::string line;\n int lineNumber = 1;\n while(std::getline(fPakInfo, line))\n {\n std::size_t p = line.find(':');\n if (p == std::string::npos)\n {\n std::stringstream ss;\n ss << \"cannot parse pakinfo.txt, line \" << lineNumber;\n throw std::runtime_error(ss.str());\n }\n std::string name = line.substr(0, p);\n std::string type = line.substr(p+1, std::string::npos);\n PakItem item;\n item.name = new char[name.length()+1];\n strcpy(item.name, name.c_str());\n item.type = new char[type.length()+1];\n strcpy(item.type, type.c_str());\n if (type == \"System.String\")\n {\n std::string filePath = dirPathSafe + name + \".txt\";\n int fileSize = getFileSize(filePath.c_str());\n std::ifstream file(filePath, std::ios::binary);\n item.data = new byte[fileSize+5];\n std::stringstream ss(reinterpret_cast(item.data));\n BinaryWriter writer(&ss);\n writer.write7BitEncodedInt(fileSize);\n item.length = fileSize + ss.tellp();\n file.read(reinterpret_cast(item.data+ss.tellp()), fileSize);\n file.close();\n }\n else if (type == \"System.Xml.Linq.XElement\")\n {\n std::string filePath = dirPathSafe + name + \".xml\";\n int fileSize = getFileSize(filePath.c_str());\n std::ifstream file(filePath, std::ios::binary);\n item.data = new byte[fileSize+5];\n std::stringstream ss(reinterpret_cast(item.data));\n BinaryWriter writer(&ss);\n writer.write7BitEncodedInt(fileSize);\n item.length = fileSize + ss.tellp();\n file.read(reinterpret_cast(item.data+ss.tellp()), fileSize);\n file.close();\n }\n else\n {\n std::string filePath = dirPathSafe + name;\n int fileSize = getFileSize(filePath.c_str());\n std::ifstream file(filePath, std::ios::binary);\n item.data = new byte[fileSize];\n item.length = fileSize;\n file.read(reinterpret_cast(item.data), fileSize);\n file.close();\n }\n pak.addItem(std::move(item));\n ++lineNumber;\n }\n fPakInfo.close();\n return pak;\n }\n}\n\nport to win32#include \"process.h\"\n#include \n#include \n#include \n#include \n#include \n\n#if defined(__linux__)\n# include \n# include \n# include \nnamespace scpak\n{\n const char pathsep = '\/';\n\n void createDirectory(const char *path)\n {\n int result = mkdir(path, 0777);\n if (result == -1)\n throw std::runtime_error(\"failed to create directory: \" + std::string(path));\n }\n\n bool directoryExists(const char *path)\n {\n return access(path, F_OK) == 0;\n }\n\n int getFileSize(const char *path)\n {\n unsigned long filesize = -1;\n struct stat statbuf;\n if (stat(path, &statbuf) < 0)\n throw std::runtime_error(\"failed to get call stat: \" + std::string(path));\n filesize = statbuf.st_size;\n return static_cast(filesize);\n }\n}\n#elif defined(_WIN32)\n# include \nnamespace scpak\n{\n const char pathsep = '\\\\';\n\n void createDirectory(const char *path)\n {\n\t\tint result = CreateDirectoryA(path, NULL);\n if (result == 0)\n throw std::runtime_error(\"failed to get file size: \" + std::string(path));\n }\n\n bool directoryExists(const char *path)\n {\n\t\tWIN32_FIND_DATA FindFileData;\n\t\tHANDLE hFind;\n\t\thFind = FindFirstFileA(path, &FindFileData);\n\t\tif (hFind == INVALID_HANDLE_VALUE)\n\t\t\treturn false;\n\t\telse\n\t\t{\n\t\t\tFindClose(hFind);\n\t\t\treturn true;\n\t\t}\n }\n\n\tint getFileSize(const char *path)\n\t{\n\t\tWIN32_FIND_DATA fileInfo;\n\t\tHANDLE hFind;\n\t\thFind = FindFirstFileA(path, &fileInfo);\n\t\tif (hFind == INVALID_HANDLE_VALUE)\n\t\t\tthrow std::runtime_error(\"failed get file size: \" + std::string(path));\n\t\tint size = fileInfo.nFileSizeLow;\n\t\tFindClose(hFind);\n\t\treturn size;\n\t}\n}\n#endif\n\nnamespace scpak\n{\n void unpack(const PakFile &pak, const std::string &dirPath)\n {\n std::string dirPathSafe = dirPath;\n if (*dirPathSafe.rbegin() != pathsep)\n dirPathSafe += pathsep;\n \/\/ find all the directories we possibly need to create\n std::set directoriesToCreate;\n directoriesToCreate.insert(dirPath);\n for (const PakItem &item : pak.contents())\n {\n std::string filePath = dirPathSafe + item.name;\n std::size_t pend = filePath.rfind(pathsep);\n if (pend == std::string::npos)\n continue;\n std::size_t p = 0;\n while (p != pend)\n {\n p = filePath.find(pathsep, p+1);\n directoriesToCreate.insert(filePath.substr(0, p));\n }\n }\n \/\/ create directories if necessary\n for (const std::string &dir : directoriesToCreate)\n if (!directoryExists(dir.c_str()))\n createDirectory(dir.c_str());\n \/\/ unpack contents\n for (const PakItem &item : pak.contents())\n {\n if (std::strcmp(item.type, \"System.String\") == 0)\n {\n std::ofstream fout(dirPathSafe + item.name + \".txt\", std::ios::binary);\n std::stringstream ss(reinterpret_cast(item.data));\n BinaryReader reader(&ss);\n std::string value = reader.readString();\n fout.write(value.data(), value.length());\n fout.close();\n }\n else if (std::strcmp(item.type, \"System.Xml.Linq.XElement\") == 0)\n {\n std::ofstream fout(dirPathSafe + item.name + \".xml\", std::ios::binary);\n std::stringstream ss(reinterpret_cast(item.data));\n BinaryReader reader(&ss);\n std::string value = reader.readString();\n fout.write(value.data(), value.length());\n fout.close();\n }\n else\n {\n \/\/ just write out raw data\n std::ofstream fout(dirPathSafe + item.name, std::ios::binary);\n fout.write(reinterpret_cast(item.data), item.length);\n fout.close();\n }\n }\n \/\/ write pakinfo.txt - we need to repack it later\n std::ofstream fout(dirPathSafe + \"pakinfo.txt\");\n for (const PakItem &item : pak.contents())\n fout << item.name << ':' << item.type << std::endl;\n fout.close();\n }\n\n PakFile pack(const std::string &dirPath)\n {\n PakFile pak;\n std::vector contents = pak.contents();\n std::string dirPathSafe = dirPath;\n if (*dirPathSafe.rbegin() != pathsep)\n dirPathSafe += pathsep;\n std::ifstream fPakInfo(dirPathSafe + \"pakinfo.txt\");\n std::string line;\n int lineNumber = 1;\n while(std::getline(fPakInfo, line))\n {\n std::size_t p = line.find(':');\n if (p == std::string::npos)\n {\n std::stringstream ss;\n ss << \"cannot parse pakinfo.txt, line \" << lineNumber;\n throw std::runtime_error(ss.str());\n }\n std::string name = line.substr(0, p);\n std::string type = line.substr(p+1, std::string::npos);\n PakItem item;\n item.name = new char[name.length()+1];\n strcpy(item.name, name.c_str());\n item.type = new char[type.length()+1];\n strcpy(item.type, type.c_str());\n if (type == \"System.String\")\n {\n std::string filePath = dirPathSafe + name + \".txt\";\n int fileSize = getFileSize(filePath.c_str());\n std::ifstream file(filePath, std::ios::binary);\n item.data = new byte[fileSize+5];\n std::stringstream ss(reinterpret_cast(item.data));\n BinaryWriter writer(&ss);\n writer.write7BitEncodedInt(fileSize);\n item.length = fileSize + ss.tellp();\n file.read(reinterpret_cast(item.data+ss.tellp()), fileSize);\n file.close();\n }\n else if (type == \"System.Xml.Linq.XElement\")\n {\n std::string filePath = dirPathSafe + name + \".xml\";\n int fileSize = getFileSize(filePath.c_str());\n std::ifstream file(filePath, std::ios::binary);\n item.data = new byte[fileSize+5];\n std::stringstream ss(reinterpret_cast(item.data));\n BinaryWriter writer(&ss);\n writer.write7BitEncodedInt(fileSize);\n item.length = fileSize + ss.tellp();\n file.read(reinterpret_cast(item.data+ss.tellp()), fileSize);\n file.close();\n }\n else\n {\n std::string filePath = dirPathSafe + name;\n int fileSize = getFileSize(filePath.c_str());\n std::ifstream file(filePath, std::ios::binary);\n item.data = new byte[fileSize];\n item.length = fileSize;\n file.read(reinterpret_cast(item.data), fileSize);\n file.close();\n }\n pak.addItem(std::move(item));\n ++lineNumber;\n }\n fPakInfo.close();\n return pak;\n }\n}\n\n<|endoftext|>"} {"text":"\/**\n * A set of network utility functions.\n *\n * @date December 13, 2014\n * @author Joeri HERMANS\n * @version 0.1\n *\n * Copyright 2014 Joeri HERMANS\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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\/\/ BEGIN Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ System dependencies.\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ System dependencies.\n#include \n\n\/\/ END Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint connect( const std::string & address, const std::size_t port ) {\n struct addrinfo hints;\n struct addrinfo * results;\n std::string portString;\n int result;\n int fd;\n\n \/\/ Checking the precondition.\n assert( !address.empty() && port > 0 );\n\n result = -1;\n memset(&hints,0,sizeof hints);\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_flags = AI_PASSIVE;\n portString = std::to_string(port);\n getaddrinfo(address.c_str(),portString.c_str(),&hints,&results);\n if( results != nullptr ) {\n fd = socket(results->ai_family,results->ai_socktype,results->ai_protocol);\n if( fd >= 0 ) {\n if( connect(fd,results->ai_addr,results->ai_addrlen) == 0 )\n result = fd;\n else\n close(fd);\n }\n freeaddrinfo(results);\n }\n\n return ( result );\n}\n\nbool enableKeepAlive( const int fd ) {\n static const int optval = 1;\n bool s;\n\n s = (setsockopt(fd,SOL_SOCKET,SO_KEEPALIVE,&optval,sizeof optval) >= 0);\n\n return ( s );\n}\nAdd implementation of the disableNagle prototype. Add preconditions.\/**\n * A set of network utility functions.\n *\n * @date December 13, 2014\n * @author Joeri HERMANS\n * @version 0.1\n *\n * Copyright 2014 Joeri HERMANS\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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\/\/ BEGIN Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ System dependencies.\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ System dependencies.\n#include \n\n\/\/ END Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint connect( const std::string & address, const std::size_t port ) {\n struct addrinfo hints;\n struct addrinfo * results;\n std::string portString;\n int result;\n int fd;\n\n \/\/ Checking the precondition.\n assert( !address.empty() && port > 0 );\n\n result = -1;\n memset(&hints,0,sizeof hints);\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_flags = AI_PASSIVE;\n portString = std::to_string(port);\n getaddrinfo(address.c_str(),portString.c_str(),&hints,&results);\n if( results != nullptr ) {\n fd = socket(results->ai_family,results->ai_socktype,results->ai_protocol);\n if( fd >= 0 ) {\n if( connect(fd,results->ai_addr,results->ai_addrlen) == 0 )\n result = fd;\n else\n close(fd);\n }\n freeaddrinfo(results);\n }\n\n return ( result );\n}\n\nbool enableKeepAlive( const int fd ) {\n static const int optval = 1;\n bool s;\n\n s = (setsockopt(fd,SOL_SOCKET,SO_KEEPALIVE,&optval,sizeof optval) >= 0);\n\n return ( s );\n}\n\nbool disableNagle( const int fd ) {\n static const int optval = 1;\n bool s;\n\n s = (setsockopt(fd,IPPROTO_TCP,TCP_NODELAY,&optval,sizeof optval) >= 0);\n\n return (s);\n}\n<|endoftext|>"} {"text":"\/\/#####################################################################\n\/\/ Class Rotation\n\/\/#####################################################################\n#include \n#include \n#include \n#include \n#include \n#include \nnamespace other{\n\ntypedef real T;\n\n#ifdef OTHER_PYTHON\n\nnamespace {\ntemplate struct NumpyDescr>{static PyArray_Descr* d;static PyArray_Descr* descr(){OTHER_ASSERT(d);Py_INCREF(d);return d;}};\ntemplate struct NumpyArrayType>{static PyTypeObject* t;static PyTypeObject* type(){OTHER_ASSERT(t);Py_INCREF(t);return t;}};\ntemplate struct NumpyIsStatic>:public mpl::true_{};\ntemplate struct NumpyRank>:public mpl::int_<0>{};\n\ntemplate PyArray_Descr* NumpyDescr>::d;\ntemplate PyTypeObject* NumpyArrayType>::t;\n}\n\nstatic void set_rotation_types(PyObject* t2d,PyObject* t3d) {\n OTHER_ASSERT(PyType_Check(t2d));\n OTHER_ASSERT(PyType_Check(t3d));\n PyObject* d2d = PyObject_GetAttrString(t2d,\"dtype\");\n if (!d2d) throw_python_error();\n PyObject* d3d = PyObject_GetAttrString(t3d,\"dtype\");\n if (!d3d) throw_python_error();\n OTHER_ASSERT(PyArray_DescrCheck(d2d));\n OTHER_ASSERT(PyArray_DescrCheck(d3d));\n Py_INCREF(t2d);\n Py_INCREF(t3d);\n Py_INCREF(d2d);\n Py_INCREF(d3d);\n NumpyArrayType>>::t = (PyTypeObject*)t2d;\n NumpyArrayType>>::t = (PyTypeObject*)t3d;\n NumpyDescr>>::d = (PyArray_Descr*)d2d;\n NumpyDescr>>::d = (PyArray_Descr*)d3d;\n}\n\ntemplate PyObject* to_python(const Rotation& q) {\n return to_numpy(q);\n}\n\ntemplate bool rotations_check(PyObject* object) {\n return PyArray_Check(object) && PyArray_EquivTypes(PyArray_DESCR((PyArrayObject*)object),NumpyDescr>::d);\n}\n\ntemplate Rotation FromPython>::convert(PyObject* object) {\n if (!rotations_check(object))\n throw_array_conversion_error(object,0,0,NumpyDescr>::d);\n return from_numpy>(object);\n}\n\n#define INSTANTIATE(T,d) \\\n template OTHER_CORE_EXPORT PyObject* to_python>(const Rotation>&); \\\n template OTHER_CORE_EXPORT Rotation> FromPython>>::convert(PyObject*); \\\n template OTHER_CORE_EXPORT bool rotations_check>(PyObject*); \\\n ARRAY_CONVERSIONS(1,Rotation>)\nINSTANTIATE(real,2)\nINSTANTIATE(real,3)\n\ntemplate static Rotation rotation_test(const Rotation& r) {\n return r*r;\n}\n\ntemplate static Array> rotation_array_test(Array> r) {\n Array> rr(r.size());\n for (int i=0;i A) {\n OTHER_ASSERT(A.rank()>=2);\n const int r = A.rank();\n if (A.shape[r-1]==2 && A.shape[r-2]==2) {\n NdArray>> rs(A.shape.slice_own(0,r-2),false);\n for (const int i : range(rs.flat.size()))\n rs.flat[i] = Rotation>(Matrix(A.flat.slice(4*i,4*(i+1)).reshape(2,2)));\n return to_python(rs);\n } else if (A.shape[r-1]==3 && A.shape[r-2]==3) {\n NdArray>> rs(A.shape.slice_own(0,r-2),false);\n for (const int i : range(rs.flat.size()))\n rs.flat[i] = Rotation>(Matrix(A.flat.slice(9*i,9*(i+1)).reshape(3,3)));\n return to_python(rs);\n } else\n throw TypeError(format(\"expected 2x2 or 3x3 matrices, got shape %s\",str(A.shape)));\n}\n\n#endif\n}\nusing namespace other;\n\nvoid wrap_rotation() {\n#ifdef OTHER_PYTHON\n using namespace python;\n function(\"_set_rotation_types\",set_rotation_types);\n function(\"rotation_test_2d\",rotation_test>);\n function(\"rotation_test_3d\",rotation_test>);\n function(\"rotation_array_test_2d\",rotation_array_test>);\n function(\"rotation_array_test_3d\",rotation_array_test>);\n OTHER_FUNCTION(rotation_from_matrix);\n#endif\n}\nRemove an unnecessary semicolon\/\/#####################################################################\n\/\/ Class Rotation\n\/\/#####################################################################\n#include \n#include \n#include \n#include \n#include \n#include \nnamespace other{\n\ntypedef real T;\n\n#ifdef OTHER_PYTHON\n\nnamespace {\ntemplate struct NumpyDescr>{static PyArray_Descr* d;static PyArray_Descr* descr(){OTHER_ASSERT(d);Py_INCREF(d);return d;}};\ntemplate struct NumpyArrayType>{static PyTypeObject* t;static PyTypeObject* type(){OTHER_ASSERT(t);Py_INCREF(t);return t;}};\ntemplate struct NumpyIsStatic>:public mpl::true_{};\ntemplate struct NumpyRank>:public mpl::int_<0>{};\n\ntemplate PyArray_Descr* NumpyDescr>::d;\ntemplate PyTypeObject* NumpyArrayType>::t;\n}\n\nstatic void set_rotation_types(PyObject* t2d,PyObject* t3d) {\n OTHER_ASSERT(PyType_Check(t2d));\n OTHER_ASSERT(PyType_Check(t3d));\n PyObject* d2d = PyObject_GetAttrString(t2d,\"dtype\");\n if (!d2d) throw_python_error();\n PyObject* d3d = PyObject_GetAttrString(t3d,\"dtype\");\n if (!d3d) throw_python_error();\n OTHER_ASSERT(PyArray_DescrCheck(d2d));\n OTHER_ASSERT(PyArray_DescrCheck(d3d));\n Py_INCREF(t2d);\n Py_INCREF(t3d);\n Py_INCREF(d2d);\n Py_INCREF(d3d);\n NumpyArrayType>>::t = (PyTypeObject*)t2d;\n NumpyArrayType>>::t = (PyTypeObject*)t3d;\n NumpyDescr>>::d = (PyArray_Descr*)d2d;\n NumpyDescr>>::d = (PyArray_Descr*)d3d;\n}\n\ntemplate PyObject* to_python(const Rotation& q) {\n return to_numpy(q);\n}\n\ntemplate bool rotations_check(PyObject* object) {\n return PyArray_Check(object) && PyArray_EquivTypes(PyArray_DESCR((PyArrayObject*)object),NumpyDescr>::d);\n}\n\ntemplate Rotation FromPython>::convert(PyObject* object) {\n if (!rotations_check(object))\n throw_array_conversion_error(object,0,0,NumpyDescr>::d);\n return from_numpy>(object);\n}\n\n#define INSTANTIATE(T,d) \\\n template OTHER_CORE_EXPORT PyObject* to_python>(const Rotation>&); \\\n template OTHER_CORE_EXPORT Rotation> FromPython>>::convert(PyObject*); \\\n template OTHER_CORE_EXPORT bool rotations_check>(PyObject*); \\\n ARRAY_CONVERSIONS(1,Rotation>)\nINSTANTIATE(real,2)\nINSTANTIATE(real,3)\n\ntemplate static Rotation rotation_test(const Rotation& r) {\n return r*r;\n}\n\ntemplate static Array> rotation_array_test(Array> r) {\n Array> rr(r.size());\n for (int i=0;i A) {\n OTHER_ASSERT(A.rank()>=2);\n const int r = A.rank();\n if (A.shape[r-1]==2 && A.shape[r-2]==2) {\n NdArray>> rs(A.shape.slice_own(0,r-2),false);\n for (const int i : range(rs.flat.size()))\n rs.flat[i] = Rotation>(Matrix(A.flat.slice(4*i,4*(i+1)).reshape(2,2)));\n return to_python(rs);\n } else if (A.shape[r-1]==3 && A.shape[r-2]==3) {\n NdArray>> rs(A.shape.slice_own(0,r-2),false);\n for (const int i : range(rs.flat.size()))\n rs.flat[i] = Rotation>(Matrix(A.flat.slice(9*i,9*(i+1)).reshape(3,3)));\n return to_python(rs);\n } else\n throw TypeError(format(\"expected 2x2 or 3x3 matrices, got shape %s\",str(A.shape)));\n}\n\n#endif\n}\nusing namespace other;\n\nvoid wrap_rotation() {\n#ifdef OTHER_PYTHON\n using namespace python;\n function(\"_set_rotation_types\",set_rotation_types);\n function(\"rotation_test_2d\",rotation_test>);\n function(\"rotation_test_3d\",rotation_test>);\n function(\"rotation_array_test_2d\",rotation_array_test>);\n function(\"rotation_array_test_3d\",rotation_array_test>);\n OTHER_FUNCTION(rotation_from_matrix)\n#endif\n}\n<|endoftext|>"} {"text":"\/\/----------------------------------------------------------------------------\n\/\/ This software is in the public domain, furnished \"as is\", without technical\n\/\/ support, and with no warranty, express or implied, as to its usefulness for\n\/\/ any purpose.\n\/\/\n\/\/ array.hpp\n\/\/ An STL-like structure that resides in video memory.\n\/\/\n\/\/ Author: Scott D. Zuyderduyn, Ph.D. (scott.zuyderduyn@utoronto.ca)\n\/\/----------------------------------------------------------------------------\n\n#pragma once\n#ifndef ECUDA_ARRAY_HPP\n#define ECUDA_ARRAY_HPP\n\n#include \n#include \n#include \n#include \"iterators.hpp\"\n\/\/#include \n#include \"global.hpp\"\n#include \"memory.hpp\"\n\nnamespace ecuda {\n\ntemplate\nclass array {\n\npublic:\n\ttypedef T value_type;\n\ttypedef std::size_t size_type;\n\ttypedef std::ptrdiff_t difference_type;\n\ttypedef value_type& reference;\n\ttypedef const value_type& const_reference;\n\ttypedef value_type* pointer;\n\ttypedef const value_type* const_pointer;\n\n\ttypedef ecuda::RandomAccessIterator< array > iterator;\n\ttypedef const ecuda::RandomAccessIterator< const array > const_iterator;\n\/*\npublic:\n\tstruct DevicePayload {\n\t\tsize_type n;\n\t\tdevice_ptr deviceMemory;\n\t};\n*\/\nprivate:\n\tsize_type n;\n\tdevice_ptr deviceMemory; \/\/ video card memory\n\npublic:\n\t__host__ __device__ array( const size_type n=0, const_reference value = T() ) : n(n) {\n\t\t#ifndef __CUDA_ARCH__\n\t\tif( n ) {\n\t\t\tCUDA_CALL( cudaMalloc( deviceMemory.alloc_ptr(), n*sizeof(T) ) );\n\t\t\tstd::vector v( n, value );\n\t\t\tCUDA_CALL( cudaMemcpy( deviceMemory.get(), &v[0], n*sizeof(T), cudaMemcpyHostToDevice ) );\n\t\t}\n\t\t#endif\n\t}\n\t__host__ array( const array& src ) : n(src.n) {\n\t\tif( n ) {\n\t\t\tCUDA_CALL( cudaMalloc( deviceMemory.alloc_ptr(), n*sizeof(T) ) );\n\t\t\tCUDA_CALL( cudaMemcpy( deviceMemory.get(), src.deviceMemory.get(), n*sizeof(T), cudaMemcpyDeviceToDevice ) );\n\t\t}\n\t}\n\t__host__ array( const std::vector& src ) : n(src.size()) {\n\t\tif( n ) {\n\t\t\tCUDA_CALL( cudaMalloc( deviceMemory.alloc_ptr(), n*sizeof(T) ) );\n\t\t\tCUDA_CALL( cudaMemcpy( deviceMemory.get(), &src[0], n*sizeof(T), cudaMemcpyHostToDevice ) );\n\t\t}\n\t}\n\t\/*\n\t__host__ array( const T* sourcePtr, const size_type n=0 ) : n(n) {\n\t\tif( n ) {\n\t\t\tCUDA_CALL( cudaMalloc( deviceMemory.alloc_ptr(), n*sizeof(T) ) );\n\t\t\tCUDA_CALL( cudaMemcpy( deviceMemory.get(), sourcePtr, n*sizeof(T), cudaMemcpyHostToDevice ) );\n\t\t}\n\t}\n\t*\/\n\n\t\/\/__device__ array( const DevicePayload& devicePayload ) : n(devicePayload.n), deviceMemory(devicePayload.deviceMemory) {}\n\n\t__host__ __device__ virtual ~array() {}\n\n\t__device__ reference at( size_type index ) { return deviceMemory[index]; }\n\t__device__ reference operator[]( size_type index ) { return deviceMemory[index]; }\n\t__device__ const_reference at( size_type index ) const { return deviceMemory[index]; }\n\t__device__ const_reference operator[]( size_type index ) const { return deviceMemory[index]; }\n\n\t__device__ reference front() { return *deviceMemory; }\n\t__device__ reference back() { return operator[]( size()-1 ); }\n\t__device__ const_reference front() const { return *deviceMemory; }\n\t__device__ const_reference back() const { return operator[]( size()-1 ); }\n\n\t__host__ __device__ size_type size() const { return n; }\n\n\t__device__ iterator begin() { return iterator(*this); }\n\t__device__ iterator end() { return iterator(*this,size()); }\n\t__device__ const_iterator begin() const { return const_iterator(*this); }\n\t__device__ const_iterator end() const { return const_iterator(*this,size()); }\n\n\t__host__ const array& operator>>( std::vector& vector ) const {\n\t\tvector.resize( n );\nstd::cerr << \"copy destination = \" << deviceMemory.get() << std::endl;\nstd::cerr << \"copying device contents of size \" << n << \" [\" << (n*sizeof(T)) << \"] to host vector\" << std::endl;\n\t\tCUDA_CALL( cudaMemcpy( &vector[0], deviceMemory.get(), n*sizeof(T), cudaMemcpyDeviceToHost ) );\nfor( size_t i = 0; i < n; ++i ) std::cerr << \"IN SITU [\" << i << \"]=\" << vector[i] << std::endl;\n\t\treturn *this;\n\t}\n\n\t__device__ array& operator=( const array& other ) {\n\t\tn = other.n;\n\t\tdeviceMemory = other.deviceMemory;\n\t\treturn *this;\n\t}\n\n\t\/*\n\tDevicePayload passToDevice() {\n\t\tDevicePayload payload;\n\t\tpayload.n = n;\n\t\tpayload.deviceMemory = deviceMemory;\n\t\treturn payload;\n\t}\n\t*\/\n\n};\n\n} \/\/ namespace ecuda\n\n#endif\nworking array\/\/----------------------------------------------------------------------------\n\/\/ This software is in the public domain, furnished \"as is\", without technical\n\/\/ support, and with no warranty, express or implied, as to its usefulness for\n\/\/ any purpose.\n\/\/\n\/\/ array.hpp\n\/\/ An STL-like structure that resides in video memory.\n\/\/\n\/\/ Author: Scott D. Zuyderduyn, Ph.D. (scott.zuyderduyn@utoronto.ca)\n\/\/----------------------------------------------------------------------------\n\n#pragma once\n#ifndef ECUDA_ARRAY_HPP\n#define ECUDA_ARRAY_HPP\n\n#include \n#include \n#include \n#include \"iterators.hpp\"\n\/\/#include \n#include \"global.hpp\"\n#include \"memory.hpp\"\n\nnamespace ecuda {\n\ntemplate\nclass array {\n\npublic:\n\ttypedef T value_type;\n\ttypedef std::size_t size_type;\n\ttypedef std::ptrdiff_t difference_type;\n\ttypedef value_type& reference;\n\ttypedef const value_type& const_reference;\n\ttypedef value_type* pointer;\n\ttypedef const value_type* const_pointer;\n\n\ttypedef ecuda::RandomAccessIterator< array > iterator;\n\ttypedef const ecuda::RandomAccessIterator< const array > const_iterator;\n\/*\npublic:\n\tstruct DevicePayload {\n\t\tsize_type n;\n\t\tdevice_ptr deviceMemory;\n\t};\n*\/\nprivate:\n\tsize_type n;\n\tdevice_ptr deviceMemory; \/\/ video card memory\n\npublic:\n\t__host__ __device__ array( const size_type n=0, const_reference value = T() ) : n(n) {\n\t\t#ifndef __CUDA_ARCH__\n\t\tif( n ) {\n\t\t\tCUDA_CALL( cudaMalloc( deviceMemory.alloc_ptr(), n*sizeof(T) ) );\n\t\t\tstd::vector v( n, value );\n\t\t\tCUDA_CALL( cudaMemcpy( deviceMemory.get(), &v[0], n*sizeof(T), cudaMemcpyHostToDevice ) );\n\t\t}\n\t\t#endif\n\t}\n\t__host__ array( const array& src ) : n(src.n), deviceMemory(src.deviceMemory) {\n\t\tstd::cerr << \"performing inplace copy\" << std::endl;\n\/*\n\t\tif( n ) {\n\t\t\tCUDA_CALL( cudaMalloc( deviceMemory.alloc_ptr(), n*sizeof(T) ) );\n\t\t\tCUDA_CALL( cudaMemcpy( deviceMemory.get(), src.deviceMemory.get(), n*sizeof(T), cudaMemcpyDeviceToDevice ) );\n\t\t}\n*\/\n\t}\n\t__host__ array( const std::vector& src ) : n(src.size()) {\n\t\tif( n ) {\n\t\t\tCUDA_CALL( cudaMalloc( deviceMemory.alloc_ptr(), n*sizeof(T) ) );\n\t\t\tCUDA_CALL( cudaMemcpy( deviceMemory.get(), &src[0], n*sizeof(T), cudaMemcpyHostToDevice ) );\n\t\t}\n\t}\n\t\/*\n\t__host__ array( const T* sourcePtr, const size_type n=0 ) : n(n) {\n\t\tif( n ) {\n\t\t\tCUDA_CALL( cudaMalloc( deviceMemory.alloc_ptr(), n*sizeof(T) ) );\n\t\t\tCUDA_CALL( cudaMemcpy( deviceMemory.get(), sourcePtr, n*sizeof(T), cudaMemcpyHostToDevice ) );\n\t\t}\n\t}\n\t*\/\n\n\t\/\/__device__ array( const DevicePayload& devicePayload ) : n(devicePayload.n), deviceMemory(devicePayload.deviceMemory) {}\n\n\t__host__ __device__ virtual ~array() {}\n\n\t__device__ reference at( size_type index ) { return deviceMemory[index]; }\n\t__device__ reference operator[]( size_type index ) { return deviceMemory[index]; }\n\t__device__ const_reference at( size_type index ) const { return deviceMemory[index]; }\n\t__device__ const_reference operator[]( size_type index ) const { return deviceMemory[index]; }\n\n\t__device__ reference front() { return *deviceMemory; }\n\t__device__ reference back() { return operator[]( size()-1 ); }\n\t__device__ const_reference front() const { return *deviceMemory; }\n\t__device__ const_reference back() const { return operator[]( size()-1 ); }\n\n\t__host__ __device__ size_type size() const { return n; }\n\n\t__device__ iterator begin() { return iterator(*this); }\n\t__device__ iterator end() { return iterator(*this,size()); }\n\t__device__ const_iterator begin() const { return const_iterator(*this); }\n\t__device__ const_iterator end() const { return const_iterator(*this,size()); }\n\n\t__host__ const array& operator>>( std::vector& vector ) const {\n\t\tvector.resize( n );\nstd::cerr << \"copy destination = \" << deviceMemory.get() << std::endl;\nstd::cerr << \"copying device contents of size \" << n << \" [\" << (n*sizeof(T)) << \"] to host vector\" << std::endl;\n\t\tCUDA_CALL( cudaMemcpy( &vector[0], deviceMemory.get(), n*sizeof(T), cudaMemcpyDeviceToHost ) );\nfor( size_t i = 0; i < n; ++i ) std::cerr << \"IN SITU [\" << i << \"]=\" << vector[i] << std::endl;\n\t\treturn *this;\n\t}\n\n\t__device__ array& operator=( const array& other ) {\n\t\tn = other.n;\n\t\tdeviceMemory = other.deviceMemory;\n\t\treturn *this;\n\t}\n\n\t\/*\n\tDevicePayload passToDevice() {\n\t\tDevicePayload payload;\n\t\tpayload.n = n;\n\t\tpayload.deviceMemory = deviceMemory;\n\t\treturn payload;\n\t}\n\t*\/\n\n};\n\n} \/\/ namespace ecuda\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see .\n *\/\n\n#include \"CreatureAI.h\"\n#include \"InstanceScript.h\"\n#include \"ScriptMgr.h\"\n#include \"SpellScript.h\"\n#include \"uldaman.h\"\n\nenum Spells\n{\n SPELL_ARCHAEDAS_AWAKEN = 10347,\n SPELL_AWAKEN_VAULT_WALKER = 10258,\n};\n\nenum Events\n{\n EVENT_SUB_BOSS_AGGRO = 2228\n};\n\nclass instance_uldaman : public InstanceMapScript\n{\npublic:\n instance_uldaman() : InstanceMapScript(\"instance_uldaman\", 70) { }\n\n struct instance_uldaman_InstanceMapScript : public InstanceScript\n {\n instance_uldaman_InstanceMapScript(Map* map) : InstanceScript(map) { }\n\n void Initialize() override\n {\n memset(&_encounters, 0, sizeof(_encounters));\n }\n\n void OnGameObjectCreate(GameObject* gameobject) override\n {\n switch (gameobject->GetEntry())\n {\n case GO_IRONAYA_SEAL_DOOR:\n case GO_KEYSTONE:\n if (_encounters[DATA_IRONAYA_DOORS] == DONE)\n {\n HandleGameObject(ObjectGuid::Empty, true, gameobject);\n gameobject->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);\n }\n break;\n case GO_TEMPLE_DOOR:\n if (_encounters[DATA_STONE_KEEPERS] == DONE)\n HandleGameObject(ObjectGuid::Empty, true, gameobject);\n break;\n case GO_ANCIENT_VAULT_DOOR:\n ancientVaultDoorGUID = gameobject->GetGUID();\n if (_encounters[DATA_ARCHAEDAS] == DONE)\n HandleGameObject(ObjectGuid::Empty, true, gameobject);\n break;\n case GO_ARCHAEDAS_TEMPLE_DOOR:\n archaedasTempleDoorGUID = gameobject->GetGUID();\n break;\n }\n }\n\n void SetData(uint32 type, uint32 data) override\n {\n switch (type)\n {\n case DATA_IRONAYA_DOORS:\n case DATA_STONE_KEEPERS:\n _encounters[type] = data;\n break;\n case DATA_ARCHAEDAS:\n _encounters[type] = data;\n HandleGameObject(ancientVaultDoorGUID, data == DONE, nullptr);\n HandleGameObject(archaedasTempleDoorGUID, data != IN_PROGRESS, nullptr);\n break;\n }\n\n if (data == DONE)\n SaveToDB();\n }\n\n std::string GetSaveData() override\n {\n std::ostringstream saveStream;\n saveStream << \"U D \" << _encounters[DATA_IRONAYA_DOORS] << ' ' << _encounters[DATA_STONE_KEEPERS] << ' ' << _encounters[DATA_ARCHAEDAS];\n return saveStream.str();\n }\n\n void Load(const char* in) override\n {\n if (!in)\n return;\n\n char dataHead1, dataHead2;\n std::istringstream loadStream(in);\n loadStream >> dataHead1 >> dataHead2;\n\n if (dataHead1 == 'U' && dataHead2 == 'D')\n {\n for (uint8 i = 0; i < MAX_ENCOUNTERS; ++i)\n {\n loadStream >> _encounters[i];\n if (_encounters[i] == IN_PROGRESS)\n _encounters[i] = NOT_STARTED;\n }\n }\n }\n\n void OnCreatureCreate(Creature* creature) override\n {\n switch (creature->GetEntry())\n {\n case NPC_STONE_KEEPER:\n if (_encounters[DATA_STONE_KEEPERS] != DONE && !creature->IsAlive())\n creature->Respawn();\n break;\n }\n }\n\n private:\n uint32 _encounters[MAX_ENCOUNTERS];\n ObjectGuid archaedasTempleDoorGUID;\n ObjectGuid ancientVaultDoorGUID;\n };\n\n InstanceScript* GetInstanceScript(InstanceMap* map) const override\n {\n return new instance_uldaman_InstanceMapScript(map);\n }\n};\n\nclass spell_uldaman_sub_boss_agro_keepers : public SpellScriptLoader\n{\npublic:\n spell_uldaman_sub_boss_agro_keepers() : SpellScriptLoader(\"spell_uldaman_sub_boss_agro_keepers\") { }\n\n class spell_uldaman_sub_boss_agro_keepers_SpellScript : public SpellScript\n {\n PrepareSpellScript(spell_uldaman_sub_boss_agro_keepers_SpellScript);\n\n void HandleSendEvent(SpellEffIndex \/*effIndex*\/)\n {\n if (Creature* keeper = GetCaster()->FindNearestCreature(NPC_STONE_KEEPER, 100.0f, true))\n keeper->AI()->SetData(1, 1);\n }\n\n void Register() override\n {\n OnEffectLaunch += SpellEffectFn(spell_uldaman_sub_boss_agro_keepers_SpellScript::HandleSendEvent, EFFECT_0, SPELL_EFFECT_SEND_EVENT);\n }\n };\n\n SpellScript* GetSpellScript() const override\n {\n return new spell_uldaman_sub_boss_agro_keepers_SpellScript();\n }\n};\n\nenum UldamanStonedEnum\n{\n MAP_ULDAMAN = 70\n};\n\nclass spell_uldaman_stoned : public SpellScriptLoader\n{\npublic:\n spell_uldaman_stoned() : SpellScriptLoader(\"spell_uldaman_stoned\") { }\n\n class spell_uldaman_stoned_AuraScript : public AuraScript\n {\n PrepareAuraScript(spell_uldaman_stoned_AuraScript);\n\n bool Load() override\n {\n return GetUnitOwner()->GetTypeId() == TYPEID_UNIT && GetUnitOwner()->GetMapId() == MAP_ULDAMAN;\n }\n\n void HandleEffectApply(AuraEffect const* \/*aurEff*\/, AuraEffectHandleModes \/*mode*\/)\n {\n Creature* target = GetUnitOwner()->ToCreature();\n target->SetReactState(REACT_PASSIVE);\n target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC);\n }\n\n void HandleEffectRemove(AuraEffect const* \/*aurEff*\/, AuraEffectHandleModes \/*mode*\/)\n {\n Creature* target = GetUnitOwner()->ToCreature();\n target->SetReactState(REACT_AGGRESSIVE);\n target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC);\n }\n\n void Register() override\n {\n OnEffectApply += AuraEffectApplyFn(spell_uldaman_stoned_AuraScript::HandleEffectApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);\n OnEffectRemove += AuraEffectRemoveFn(spell_uldaman_stoned_AuraScript::HandleEffectRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);\n }\n };\n\n AuraScript* GetAuraScript() const override\n {\n return new spell_uldaman_stoned_AuraScript();\n }\n};\n\nclass spell_uldaman_boss_agro_archaedas : public SpellScriptLoader\n{\npublic:\n spell_uldaman_boss_agro_archaedas() : SpellScriptLoader(\"spell_uldaman_boss_agro_archaedas\") { }\n\n class spell_uldaman_boss_agro_archaedas_SpellScript : public SpellScript\n {\n PrepareSpellScript(spell_uldaman_boss_agro_archaedas_SpellScript);\n\n void HandleSendEvent(SpellEffIndex \/*effIndex*\/)\n {\n InstanceScript* instance = GetCaster()->GetInstanceScript();\n if (!instance || instance->GetData(DATA_ARCHAEDAS) == IN_PROGRESS)\n return;\n\n instance->SetData(DATA_ARCHAEDAS, IN_PROGRESS);\n if (Creature* archaedas = GetCaster()->FindNearestCreature(NPC_ARCHAEDAS, 100.0f, true))\n archaedas->AI()->SetData(1, 1);\n }\n\n void Register() override\n {\n OnEffectLaunch += SpellEffectFn(spell_uldaman_boss_agro_archaedas_SpellScript::HandleSendEvent, EFFECT_0, SPELL_EFFECT_SEND_EVENT);\n }\n };\n\n SpellScript* GetSpellScript() const override\n {\n return new spell_uldaman_boss_agro_archaedas_SpellScript();\n }\n};\n\nvoid AddSC_instance_uldaman()\n{\n new instance_uldaman();\n new spell_uldaman_sub_boss_agro_keepers();\n new spell_uldaman_stoned();\n new spell_uldaman_boss_agro_archaedas();\n}\nFix(Core\/Uldaman): Door behind Archaedas can close after event. (#8024)\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see .\n *\/\n\n#include \"CreatureAI.h\"\n#include \"InstanceScript.h\"\n#include \"ScriptMgr.h\"\n#include \"SpellScript.h\"\n#include \"uldaman.h\"\n\nenum Spells\n{\n SPELL_ARCHAEDAS_AWAKEN = 10347,\n SPELL_AWAKEN_VAULT_WALKER = 10258,\n};\n\nenum Events\n{\n EVENT_SUB_BOSS_AGGRO = 2228\n};\n\nclass instance_uldaman : public InstanceMapScript\n{\npublic:\n instance_uldaman() : InstanceMapScript(\"instance_uldaman\", 70) { }\n\n struct instance_uldaman_InstanceMapScript : public InstanceScript\n {\n instance_uldaman_InstanceMapScript(Map* map) : InstanceScript(map) { }\n\n void Initialize() override\n {\n memset(&_encounters, 0, sizeof(_encounters));\n }\n\n void OnGameObjectCreate(GameObject* gameobject) override\n {\n switch (gameobject->GetEntry())\n {\n case GO_IRONAYA_SEAL_DOOR:\n case GO_KEYSTONE:\n if (_encounters[DATA_IRONAYA_DOORS] == DONE)\n {\n HandleGameObject(ObjectGuid::Empty, true, gameobject);\n gameobject->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);\n }\n break;\n case GO_TEMPLE_DOOR:\n if (_encounters[DATA_STONE_KEEPERS] == DONE)\n HandleGameObject(ObjectGuid::Empty, true, gameobject);\n break;\n case GO_ANCIENT_VAULT_DOOR:\n ancientVaultDoorGUID = gameobject->GetGUID();\n if (_encounters[DATA_ARCHAEDAS] == DONE)\n HandleGameObject(ObjectGuid::Empty, true, gameobject);\n break;\n case GO_ARCHAEDAS_TEMPLE_DOOR:\n archaedasTempleDoorGUID = gameobject->GetGUID();\n break;\n }\n }\n\n void SetData(uint32 type, uint32 data) override\n {\n switch (type)\n {\n case DATA_IRONAYA_DOORS:\n case DATA_STONE_KEEPERS:\n _encounters[type] = data;\n break;\n case DATA_ARCHAEDAS:\n _encounters[type] = data;\n HandleGameObject(ancientVaultDoorGUID, data == DONE, nullptr);\n HandleGameObject(archaedasTempleDoorGUID, data != IN_PROGRESS, nullptr);\n break;\n }\n\n if (data == DONE)\n SaveToDB();\n }\n\n uint32 GetData(uint32 data) const override\n {\n if (data < MAX_ENCOUNTERS)\n {\n return _encounters[data];\n }\n return 0;\n }\n\n std::string GetSaveData() override\n {\n std::ostringstream saveStream;\n saveStream << \"U D \" << _encounters[DATA_IRONAYA_DOORS] << ' ' << _encounters[DATA_STONE_KEEPERS] << ' ' << _encounters[DATA_ARCHAEDAS];\n return saveStream.str();\n }\n\n void Load(const char* in) override\n {\n if (!in)\n return;\n\n char dataHead1, dataHead2;\n std::istringstream loadStream(in);\n loadStream >> dataHead1 >> dataHead2;\n\n if (dataHead1 == 'U' && dataHead2 == 'D')\n {\n for (uint8 i = 0; i < MAX_ENCOUNTERS; ++i)\n {\n loadStream >> _encounters[i];\n if (_encounters[i] == IN_PROGRESS)\n _encounters[i] = NOT_STARTED;\n }\n }\n }\n\n void OnCreatureCreate(Creature* creature) override\n {\n switch (creature->GetEntry())\n {\n case NPC_STONE_KEEPER:\n if (_encounters[DATA_STONE_KEEPERS] != DONE && !creature->IsAlive())\n creature->Respawn();\n break;\n }\n }\n\n private:\n uint32 _encounters[MAX_ENCOUNTERS];\n ObjectGuid archaedasTempleDoorGUID;\n ObjectGuid ancientVaultDoorGUID;\n };\n\n InstanceScript* GetInstanceScript(InstanceMap* map) const override\n {\n return new instance_uldaman_InstanceMapScript(map);\n }\n};\n\nclass spell_uldaman_sub_boss_agro_keepers : public SpellScriptLoader\n{\npublic:\n spell_uldaman_sub_boss_agro_keepers() : SpellScriptLoader(\"spell_uldaman_sub_boss_agro_keepers\") { }\n\n class spell_uldaman_sub_boss_agro_keepers_SpellScript : public SpellScript\n {\n PrepareSpellScript(spell_uldaman_sub_boss_agro_keepers_SpellScript);\n\n void HandleSendEvent(SpellEffIndex \/*effIndex*\/)\n {\n if (Creature* keeper = GetCaster()->FindNearestCreature(NPC_STONE_KEEPER, 100.0f, true))\n keeper->AI()->SetData(1, 1);\n }\n\n void Register() override\n {\n OnEffectLaunch += SpellEffectFn(spell_uldaman_sub_boss_agro_keepers_SpellScript::HandleSendEvent, EFFECT_0, SPELL_EFFECT_SEND_EVENT);\n }\n };\n\n SpellScript* GetSpellScript() const override\n {\n return new spell_uldaman_sub_boss_agro_keepers_SpellScript();\n }\n};\n\nenum UldamanStonedEnum\n{\n MAP_ULDAMAN = 70\n};\n\nclass spell_uldaman_stoned : public SpellScriptLoader\n{\npublic:\n spell_uldaman_stoned() : SpellScriptLoader(\"spell_uldaman_stoned\") { }\n\n class spell_uldaman_stoned_AuraScript : public AuraScript\n {\n PrepareAuraScript(spell_uldaman_stoned_AuraScript);\n\n bool Load() override\n {\n return GetUnitOwner()->GetTypeId() == TYPEID_UNIT && GetUnitOwner()->GetMapId() == MAP_ULDAMAN;\n }\n\n void HandleEffectApply(AuraEffect const* \/*aurEff*\/, AuraEffectHandleModes \/*mode*\/)\n {\n Creature* target = GetUnitOwner()->ToCreature();\n target->SetReactState(REACT_PASSIVE);\n target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC);\n }\n\n void HandleEffectRemove(AuraEffect const* \/*aurEff*\/, AuraEffectHandleModes \/*mode*\/)\n {\n Creature* target = GetUnitOwner()->ToCreature();\n target->SetReactState(REACT_AGGRESSIVE);\n target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC);\n }\n\n void Register() override\n {\n OnEffectApply += AuraEffectApplyFn(spell_uldaman_stoned_AuraScript::HandleEffectApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);\n OnEffectRemove += AuraEffectRemoveFn(spell_uldaman_stoned_AuraScript::HandleEffectRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);\n }\n };\n\n AuraScript* GetAuraScript() const override\n {\n return new spell_uldaman_stoned_AuraScript();\n }\n};\n\nclass spell_uldaman_boss_agro_archaedas : public SpellScriptLoader\n{\npublic:\n spell_uldaman_boss_agro_archaedas() : SpellScriptLoader(\"spell_uldaman_boss_agro_archaedas\") { }\n\n class spell_uldaman_boss_agro_archaedas_SpellScript : public SpellScript\n {\n PrepareSpellScript(spell_uldaman_boss_agro_archaedas_SpellScript);\n\n void HandleSendEvent(SpellEffIndex \/*effIndex*\/)\n {\n InstanceScript* instance = GetCaster()->GetInstanceScript();\n\n if (!instance || instance->GetData(DATA_ARCHAEDAS) == IN_PROGRESS || instance->GetData(DATA_ARCHAEDAS) == DONE)\n return;\n\n instance->SetData(DATA_ARCHAEDAS, IN_PROGRESS);\n if (Creature* archaedas = GetCaster()->FindNearestCreature(NPC_ARCHAEDAS, 100.0f, true))\n archaedas->AI()->SetData(1, 1);\n }\n\n void Register() override\n {\n OnEffectLaunch += SpellEffectFn(spell_uldaman_boss_agro_archaedas_SpellScript::HandleSendEvent, EFFECT_0, SPELL_EFFECT_SEND_EVENT);\n }\n };\n\n SpellScript* GetSpellScript() const override\n {\n return new spell_uldaman_boss_agro_archaedas_SpellScript();\n }\n};\n\nvoid AddSC_instance_uldaman()\n{\n new instance_uldaman();\n new spell_uldaman_sub_boss_agro_keepers();\n new spell_uldaman_stoned();\n new spell_uldaman_boss_agro_archaedas();\n}\n<|endoftext|>"} {"text":"\n\/\/ DungeonRoomsFinisher.cpp\n\n\/\/ Declares the cDungeonRoomsFinisher class representing the finisher that generates dungeon rooms\n\n#include \"Globals.h\"\n#include \"DungeonRoomsFinisher.h\"\n#include \"..\/FastRandom.h\"\n\n\n\n\n\n\/** Height, in blocks, of the internal dungeon room open space. This many air blocks Y-wise. *\/\nstatic const int ROOM_HEIGHT = 4;\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ cDungeonRoom:\n\nclass cDungeonRoom :\n\tpublic cGridStructGen::cStructure\n{\n\ttypedef cGridStructGen::cStructure super;\n\npublic:\n\n\tcDungeonRoom(\n\t\tint a_GridX, int a_GridZ,\n\t\tint a_OriginX, int a_OriginZ,\n\t\tint a_HalfSizeX, int a_HalfSizeZ,\n\t\tint a_FloorHeight,\n\t\tcNoise & a_Noise\n\t) :\n\t\tsuper(a_GridX, a_GridZ, a_OriginX, a_OriginZ),\n\t\tm_StartX(a_OriginX - a_HalfSizeX),\n\t\tm_EndX(a_OriginX + a_HalfSizeX),\n\t\tm_StartZ(a_OriginZ - a_HalfSizeZ),\n\t\tm_EndZ(a_OriginZ + a_HalfSizeZ),\n\t\tm_FloorHeight(a_FloorHeight)\n\t{\n\t\t\/*\n\t\tPick coords next to the wall for the chests.\n\t\tThis is done by indexing the possible coords, picking any one for the first chest\n\t\tand then picking another position for the second chest that is not adjacent to the first pos\n\t\t*\/\n\t\tint rnd = a_Noise.IntNoise2DInt(a_OriginX, a_OriginZ) \/ 7;\n\t\tint SizeX = m_EndX - m_StartX - 1;\n\t\tint SizeZ = m_EndZ - m_StartZ - 1;\n\t\tint NumPositions = 2 * SizeX + 2 * SizeZ;\n\t\tint FirstChestPos = rnd % NumPositions; \/\/ The corner positions are a bit more likely, but we don't mind\n\t\trnd = rnd \/ 512;\n\t\tint SecondChestPos = (FirstChestPos + 2 + (rnd % (NumPositions - 3))) % NumPositions;\n\t\tm_Chest1 = DecodeChestCoords(FirstChestPos, SizeX, SizeZ);\n\t\tm_Chest2 = DecodeChestCoords(SecondChestPos, SizeX, SizeZ);\n\t}\n\nprotected:\n\n\t\/\/ The X range of the room, start inclusive, end exclusive:\n\tint m_StartX, m_EndX;\n\n\t\/\/ The Z range of the room, start inclusive, end exclusive:\n\tint m_StartZ, m_EndZ;\n\n\t\/** The Y coord of the floor of the room *\/\n\tint m_FloorHeight;\n\n\t\/** The (absolute) coords of the first chest. The Y coord represents the chest's Meta value (facing). *\/\n\tVector3i m_Chest1;\n\n\t\/** The (absolute) coords of the second chest. The Y coord represents the chest's Meta value (facing). *\/\n\tVector3i m_Chest2;\n\n\n\n\t\/** Decodes the position index along the room walls into a proper 2D position for a chest. *\/\n\tVector3i DecodeChestCoords(int a_PosIdx, int a_SizeX, int a_SizeZ)\n\t{\n\t\tif (a_PosIdx < a_SizeX)\n\t\t{\n\t\t\t\/\/ Return a coord on the ZM side of the room:\n\t\t\treturn Vector3i(m_StartX + a_PosIdx + 1, E_META_CHEST_FACING_ZP, m_StartZ + 1);\n\t\t}\n\t\ta_PosIdx -= a_SizeX;\n\t\tif (a_PosIdx < a_SizeZ)\n\t\t{\n\t\t\t\/\/ Return a coord on the XP side of the room:\n\t\t\treturn Vector3i(m_EndX - 1, E_META_CHEST_FACING_XM, m_StartZ + a_PosIdx + 1);\n\t\t}\n\t\ta_PosIdx -= a_SizeZ;\n\t\tif (a_PosIdx < a_SizeX)\n\t\t{\n\t\t\t\/\/ Return a coord on the ZP side of the room:\n\t\t\treturn Vector3i(m_StartX + a_PosIdx + 1, E_META_CHEST_FACING_ZM, m_StartZ + 1);\n\t\t}\n\t\ta_PosIdx -= a_SizeX;\n\t\t\/\/ Return a coord on the XM side of the room:\n\t\treturn Vector3i(m_StartX + 1, E_META_CHEST_FACING_XP, m_StartZ + a_PosIdx + 1);\n\t}\n\n\n\n\t\/** Fills the specified area of blocks in the chunk with the specified blocktype if they are one of the overwritten block types.\n\tThe coords are absolute, start coords are inclusive, end coords are exclusive. *\/\n\tvoid ReplaceCuboid(cChunkDesc & a_ChunkDesc, int a_StartX, int a_StartY, int a_StartZ, int a_EndX, int a_EndY, int a_EndZ, BLOCKTYPE a_DstBlockType)\n\t{\n\t\tint BlockX = a_ChunkDesc.GetChunkX() * cChunkDef::Width;\n\t\tint BlockZ = a_ChunkDesc.GetChunkZ() * cChunkDef::Width;\n\t\tint RelStartX = Clamp(a_StartX - BlockX, 0, cChunkDef::Width - 1);\n\t\tint RelStartZ = Clamp(a_StartZ - BlockZ, 0, cChunkDef::Width - 1);\n\t\tint RelEndX = Clamp(a_EndX - BlockX, 0, cChunkDef::Width);\n\t\tint RelEndZ = Clamp(a_EndZ - BlockZ, 0, cChunkDef::Width);\n\t\tfor (int y = a_StartY; y < a_EndY; y++)\n\t\t{\n\t\t\tfor (int z = RelStartZ; z < RelEndZ; z++)\n\t\t\t{\n\t\t\t\tfor (int x = RelStartX; x < RelEndX; x++)\n\t\t\t\t{\n\t\t\t\t\tif (cBlockInfo::CanBeTerraformed(a_ChunkDesc.GetBlockType(x, y, z)))\n\t\t\t\t\t{\n\t\t\t\t\t\ta_ChunkDesc.SetBlockType(x, y, z, a_DstBlockType);\n\t\t\t\t\t}\n\t\t\t\t} \/\/ for x\n\t\t\t} \/\/ for z\n\t\t} \/\/ for z\n\t}\n\n\n\n\t\/** Fills the specified area of blocks in the chunk with a random pattern of the specified blocktypes, if they are one of the overwritten block types.\n\tThe coords are absolute, start coords are inclusive, end coords are exclusive. The first blocktype uses 75% chance, the second 25% chance. *\/\n\tvoid ReplaceCuboidRandom(cChunkDesc & a_ChunkDesc, int a_StartX, int a_StartY, int a_StartZ, int a_EndX, int a_EndY, int a_EndZ, BLOCKTYPE a_DstBlockType1, BLOCKTYPE a_DstBlockType2)\n\t{\n\t\tint BlockX = a_ChunkDesc.GetChunkX() * cChunkDef::Width;\n\t\tint BlockZ = a_ChunkDesc.GetChunkZ() * cChunkDef::Width;\n\t\tint RelStartX = Clamp(a_StartX - BlockX, 0, cChunkDef::Width - 1);\n\t\tint RelStartZ = Clamp(a_StartZ - BlockZ, 0, cChunkDef::Width - 1);\n\t\tint RelEndX = Clamp(a_EndX - BlockX, 0, cChunkDef::Width);\n\t\tint RelEndZ = Clamp(a_EndZ - BlockZ, 0, cChunkDef::Width);\n\t\tcFastRandom rnd;\n\t\tfor (int y = a_StartY; y < a_EndY; y++)\n\t\t{\n\t\t\tfor (int z = RelStartZ; z < RelEndZ; z++)\n\t\t\t{\n\t\t\t\tfor (int x = RelStartX; x < RelEndX; x++)\n\t\t\t\t{\n\t\t\t\t\tif (cBlockInfo::CanBeTerraformed(a_ChunkDesc.GetBlockType(x, y, z)))\n\t\t\t\t\t{\n\t\t\t\t\t\tBLOCKTYPE BlockType = (rnd.NextInt(101) < 75) ? a_DstBlockType1 : a_DstBlockType2;\n\t\t\t\t\t\ta_ChunkDesc.SetBlockType(x, y, z, BlockType);\n\t\t\t\t\t}\n\t\t\t\t} \/\/ for x\n\t\t\t} \/\/ for z\n\t\t} \/\/ for z\n\t}\n\n\n\n\t\/** Tries to place a chest at the specified (absolute) coords.\n\tDoes nothing if the coords are outside the chunk. *\/\n\tvoid TryPlaceChest(cChunkDesc & a_ChunkDesc, const Vector3i & a_Chest)\n\t{\n\t\tint RelX = a_Chest.x - a_ChunkDesc.GetChunkX() * cChunkDef::Width;\n\t\tint RelZ = a_Chest.z - a_ChunkDesc.GetChunkZ() * cChunkDef::Width;\n\t\tif (\n\t\t\t(RelX < 0) || (RelX >= cChunkDef::Width) || \/\/ The X coord is not in this chunk\n\t\t\t(RelZ < 0) || (RelZ >= cChunkDef::Width) \/\/ The Z coord is not in this chunk\n\t\t)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\ta_ChunkDesc.SetBlockTypeMeta(RelX, m_FloorHeight + 1, RelZ, E_BLOCK_CHEST, (NIBBLETYPE)a_Chest.y);\n\n\t\t\/\/ TODO: Fill the chest with random loot\n\t}\n\n\n\n\t\/\/ cGridStructGen::cStructure override:\n\tvirtual void DrawIntoChunk(cChunkDesc & a_ChunkDesc) override\n\t{\n\t\tif (\n\t\t\t(m_EndX <= a_ChunkDesc.GetChunkX() * cChunkDef::Width) ||\n\t\t\t(m_StartX >= a_ChunkDesc.GetChunkX() * cChunkDef::Width + cChunkDef::Width) ||\n\t\t\t(m_EndZ <= a_ChunkDesc.GetChunkZ() * cChunkDef::Width) ||\n\t\t\t(m_StartZ >= a_ChunkDesc.GetChunkZ() * cChunkDef::Width + cChunkDef::Width)\n\t\t)\n\t\t{\n\t\t\t\/\/ The chunk is not intersecting the room at all, bail out\n\t\t\treturn;\n\t\t}\n\t\tint b = m_FloorHeight + 1; \/\/ Bottom\n\t\tint t = m_FloorHeight + 1 + ROOM_HEIGHT; \/\/ Top\n\t\tReplaceCuboidRandom(a_ChunkDesc, m_StartX, m_FloorHeight, m_StartZ, m_EndX + 1, b, m_EndZ + 1, E_BLOCK_MOSSY_COBBLESTONE, E_BLOCK_COBBLESTONE); \/\/ Floor\n\t\tReplaceCuboid(a_ChunkDesc, m_StartX + 1, b, m_StartZ + 1, m_EndX, t, m_EndZ, E_BLOCK_AIR); \/\/ Insides\n\n\t\t\/\/ Walls:\n\t\tReplaceCuboid(a_ChunkDesc, m_StartX, b, m_StartZ, m_StartX + 1, t, m_EndZ, E_BLOCK_COBBLESTONE); \/\/ XM wall\n\t\tReplaceCuboid(a_ChunkDesc, m_EndX, b, m_StartZ, m_EndX + 1, t, m_EndZ, E_BLOCK_COBBLESTONE); \/\/ XP wall\n\t\tReplaceCuboid(a_ChunkDesc, m_StartX, b, m_StartZ, m_EndX + 1, t, m_StartZ + 1, E_BLOCK_COBBLESTONE); \/\/ ZM wall\n\t\tReplaceCuboid(a_ChunkDesc, m_StartX, b, m_EndZ, m_EndX + 1, t, m_EndZ + 1, E_BLOCK_COBBLESTONE); \/\/ ZP wall\n\n\t\t\/\/ Place chests:\n\t\tTryPlaceChest(a_ChunkDesc, m_Chest1);\n\t\tTryPlaceChest(a_ChunkDesc, m_Chest2);\n\n\t\t\/\/ Place the spawner:\n\t\tint CenterX = (m_StartX + m_EndX) \/ 2 - a_ChunkDesc.GetChunkX() * cChunkDef::Width;\n\t\tint CenterZ = (m_StartZ + m_EndZ) \/ 2 - a_ChunkDesc.GetChunkZ() * cChunkDef::Width;\n\t\tif (\n\t\t\t(CenterX >= 0) && (CenterX < cChunkDef::Width) &&\n\t\t\t(CenterZ >= 0) && (CenterZ < cChunkDef::Width)\n\t\t)\n\t\t{\n\t\t\ta_ChunkDesc.SetBlockTypeMeta(CenterX, b, CenterZ, E_BLOCK_MOB_SPAWNER, 0);\n\t\t\t\/\/ TODO: Set the spawned mob\n\t\t}\n\t}\n} ;\n\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ cDungeonRoomsFinisher:\n\ncDungeonRoomsFinisher::cDungeonRoomsFinisher(cTerrainHeightGen & a_HeightGen, int a_Seed, int a_GridSize, int a_MaxSize, int a_MinSize, const AString & a_HeightDistrib) :\n\tsuper(a_Seed + 100, a_GridSize, a_GridSize, a_GridSize, a_GridSize, a_MaxSize, a_MaxSize, 1024),\n\tm_HeightGen(a_HeightGen),\n\tm_MaxHalfSize((a_MaxSize + 1) \/ 2),\n\tm_MinHalfSize((a_MinSize + 1) \/ 2),\n\tm_HeightProbability(cChunkDef::Height)\n{\n\t\/\/ Initialize the height probability distribution:\n\tm_HeightProbability.SetDefString(a_HeightDistrib);\n\n\t\/\/ Normalize the min and max size:\n\tif (m_MinHalfSize > m_MaxHalfSize)\n\t{\n\t\tstd::swap(m_MinHalfSize, m_MaxHalfSize);\n\t}\n}\n\n\n\n\n\n\ncDungeonRoomsFinisher::cStructurePtr cDungeonRoomsFinisher::CreateStructure(int a_GridX, int a_GridZ, int a_OriginX, int a_OriginZ)\n{\n\t\/\/ Select a random room size in each direction:\n\tint rnd = m_Noise.IntNoise2DInt(a_OriginX, a_OriginZ) \/ 7;\n\tint HalfSizeX = m_MinHalfSize + (rnd % (m_MaxHalfSize - m_MinHalfSize + 1));\n\trnd = rnd \/ 32;\n\tint HalfSizeZ = m_MinHalfSize + (rnd % (m_MaxHalfSize - m_MinHalfSize + 1));\n\trnd = rnd \/ 32;\n\n\t\/\/ Select a random floor height for the room, based on the height generator:\n\tint ChunkX, ChunkZ;\n\tint RelX = a_OriginX, RelY = 0, RelZ = a_OriginZ;\n\tcChunkDef::AbsoluteToRelative(RelX, RelY, RelZ, ChunkX, ChunkZ);\n\tcChunkDef::HeightMap HeightMap;\n\tm_HeightGen.GenHeightMap(ChunkX, ChunkZ, HeightMap);\n\tint Height = cChunkDef::GetHeight(HeightMap, RelX, RelZ); \/\/ Max room height at {a_OriginX, a_OriginZ}\n\tHeight = Clamp(m_HeightProbability.MapValue(rnd % m_HeightProbability.GetSum()), 10, Height - 5);\n\n\t\/\/ Create the dungeon room descriptor:\n\treturn cStructurePtr(new cDungeonRoom(a_GridX, a_GridZ, a_OriginX, a_OriginZ, HalfSizeX, HalfSizeZ, Height, m_Noise));\n}\n\n\n\n\nDungeonRooms: Fixed an off-by-one error.\n\/\/ DungeonRoomsFinisher.cpp\n\n\/\/ Declares the cDungeonRoomsFinisher class representing the finisher that generates dungeon rooms\n\n#include \"Globals.h\"\n#include \"DungeonRoomsFinisher.h\"\n#include \"..\/FastRandom.h\"\n\n\n\n\n\n\/** Height, in blocks, of the internal dungeon room open space. This many air blocks Y-wise. *\/\nstatic const int ROOM_HEIGHT = 4;\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ cDungeonRoom:\n\nclass cDungeonRoom :\n\tpublic cGridStructGen::cStructure\n{\n\ttypedef cGridStructGen::cStructure super;\n\npublic:\n\n\tcDungeonRoom(\n\t\tint a_GridX, int a_GridZ,\n\t\tint a_OriginX, int a_OriginZ,\n\t\tint a_HalfSizeX, int a_HalfSizeZ,\n\t\tint a_FloorHeight,\n\t\tcNoise & a_Noise\n\t) :\n\t\tsuper(a_GridX, a_GridZ, a_OriginX, a_OriginZ),\n\t\tm_StartX(a_OriginX - a_HalfSizeX),\n\t\tm_EndX(a_OriginX + a_HalfSizeX),\n\t\tm_StartZ(a_OriginZ - a_HalfSizeZ),\n\t\tm_EndZ(a_OriginZ + a_HalfSizeZ),\n\t\tm_FloorHeight(a_FloorHeight)\n\t{\n\t\t\/*\n\t\tPick coords next to the wall for the chests.\n\t\tThis is done by indexing the possible coords, picking any one for the first chest\n\t\tand then picking another position for the second chest that is not adjacent to the first pos\n\t\t*\/\n\t\tint rnd = a_Noise.IntNoise2DInt(a_OriginX, a_OriginZ) \/ 7;\n\t\tint SizeX = m_EndX - m_StartX - 1;\n\t\tint SizeZ = m_EndZ - m_StartZ - 1;\n\t\tint NumPositions = 2 * SizeX + 2 * SizeZ;\n\t\tint FirstChestPos = rnd % NumPositions; \/\/ The corner positions are a bit more likely, but we don't mind\n\t\trnd = rnd \/ 512;\n\t\tint SecondChestPos = (FirstChestPos + 2 + (rnd % (NumPositions - 3))) % NumPositions;\n\t\tm_Chest1 = DecodeChestCoords(FirstChestPos, SizeX, SizeZ);\n\t\tm_Chest2 = DecodeChestCoords(SecondChestPos, SizeX, SizeZ);\n\t}\n\nprotected:\n\n\t\/\/ The X range of the room, start inclusive, end exclusive:\n\tint m_StartX, m_EndX;\n\n\t\/\/ The Z range of the room, start inclusive, end exclusive:\n\tint m_StartZ, m_EndZ;\n\n\t\/** The Y coord of the floor of the room *\/\n\tint m_FloorHeight;\n\n\t\/** The (absolute) coords of the first chest. The Y coord represents the chest's Meta value (facing). *\/\n\tVector3i m_Chest1;\n\n\t\/** The (absolute) coords of the second chest. The Y coord represents the chest's Meta value (facing). *\/\n\tVector3i m_Chest2;\n\n\n\n\t\/** Decodes the position index along the room walls into a proper 2D position for a chest. *\/\n\tVector3i DecodeChestCoords(int a_PosIdx, int a_SizeX, int a_SizeZ)\n\t{\n\t\tif (a_PosIdx < a_SizeX)\n\t\t{\n\t\t\t\/\/ Return a coord on the ZM side of the room:\n\t\t\treturn Vector3i(m_StartX + a_PosIdx + 1, E_META_CHEST_FACING_ZP, m_StartZ + 1);\n\t\t}\n\t\ta_PosIdx -= a_SizeX;\n\t\tif (a_PosIdx < a_SizeZ)\n\t\t{\n\t\t\t\/\/ Return a coord on the XP side of the room:\n\t\t\treturn Vector3i(m_EndX - 1, E_META_CHEST_FACING_XM, m_StartZ + a_PosIdx + 1);\n\t\t}\n\t\ta_PosIdx -= a_SizeZ;\n\t\tif (a_PosIdx < a_SizeX)\n\t\t{\n\t\t\t\/\/ Return a coord on the ZP side of the room:\n\t\t\treturn Vector3i(m_StartX + a_PosIdx + 1, E_META_CHEST_FACING_ZM, m_StartZ + 1);\n\t\t}\n\t\ta_PosIdx -= a_SizeX;\n\t\t\/\/ Return a coord on the XM side of the room:\n\t\treturn Vector3i(m_StartX + 1, E_META_CHEST_FACING_XP, m_StartZ + a_PosIdx + 1);\n\t}\n\n\n\n\t\/** Fills the specified area of blocks in the chunk with the specified blocktype if they are one of the overwritten block types.\n\tThe coords are absolute, start coords are inclusive, end coords are exclusive. *\/\n\tvoid ReplaceCuboid(cChunkDesc & a_ChunkDesc, int a_StartX, int a_StartY, int a_StartZ, int a_EndX, int a_EndY, int a_EndZ, BLOCKTYPE a_DstBlockType)\n\t{\n\t\tint BlockX = a_ChunkDesc.GetChunkX() * cChunkDef::Width;\n\t\tint BlockZ = a_ChunkDesc.GetChunkZ() * cChunkDef::Width;\n\t\tint RelStartX = Clamp(a_StartX - BlockX, 0, cChunkDef::Width - 1);\n\t\tint RelStartZ = Clamp(a_StartZ - BlockZ, 0, cChunkDef::Width - 1);\n\t\tint RelEndX = Clamp(a_EndX - BlockX, 0, cChunkDef::Width);\n\t\tint RelEndZ = Clamp(a_EndZ - BlockZ, 0, cChunkDef::Width);\n\t\tfor (int y = a_StartY; y < a_EndY; y++)\n\t\t{\n\t\t\tfor (int z = RelStartZ; z < RelEndZ; z++)\n\t\t\t{\n\t\t\t\tfor (int x = RelStartX; x < RelEndX; x++)\n\t\t\t\t{\n\t\t\t\t\tif (cBlockInfo::CanBeTerraformed(a_ChunkDesc.GetBlockType(x, y, z)))\n\t\t\t\t\t{\n\t\t\t\t\t\ta_ChunkDesc.SetBlockType(x, y, z, a_DstBlockType);\n\t\t\t\t\t}\n\t\t\t\t} \/\/ for x\n\t\t\t} \/\/ for z\n\t\t} \/\/ for z\n\t}\n\n\n\n\t\/** Fills the specified area of blocks in the chunk with a random pattern of the specified blocktypes, if they are one of the overwritten block types.\n\tThe coords are absolute, start coords are inclusive, end coords are exclusive. The first blocktype uses 75% chance, the second 25% chance. *\/\n\tvoid ReplaceCuboidRandom(cChunkDesc & a_ChunkDesc, int a_StartX, int a_StartY, int a_StartZ, int a_EndX, int a_EndY, int a_EndZ, BLOCKTYPE a_DstBlockType1, BLOCKTYPE a_DstBlockType2)\n\t{\n\t\tint BlockX = a_ChunkDesc.GetChunkX() * cChunkDef::Width;\n\t\tint BlockZ = a_ChunkDesc.GetChunkZ() * cChunkDef::Width;\n\t\tint RelStartX = Clamp(a_StartX - BlockX, 0, cChunkDef::Width - 1);\n\t\tint RelStartZ = Clamp(a_StartZ - BlockZ, 0, cChunkDef::Width - 1);\n\t\tint RelEndX = Clamp(a_EndX - BlockX, 0, cChunkDef::Width);\n\t\tint RelEndZ = Clamp(a_EndZ - BlockZ, 0, cChunkDef::Width);\n\t\tcFastRandom rnd;\n\t\tfor (int y = a_StartY; y < a_EndY; y++)\n\t\t{\n\t\t\tfor (int z = RelStartZ; z < RelEndZ; z++)\n\t\t\t{\n\t\t\t\tfor (int x = RelStartX; x < RelEndX; x++)\n\t\t\t\t{\n\t\t\t\t\tif (cBlockInfo::CanBeTerraformed(a_ChunkDesc.GetBlockType(x, y, z)))\n\t\t\t\t\t{\n\t\t\t\t\t\tBLOCKTYPE BlockType = (rnd.NextInt(101) < 75) ? a_DstBlockType1 : a_DstBlockType2;\n\t\t\t\t\t\ta_ChunkDesc.SetBlockType(x, y, z, BlockType);\n\t\t\t\t\t}\n\t\t\t\t} \/\/ for x\n\t\t\t} \/\/ for z\n\t\t} \/\/ for z\n\t}\n\n\n\n\t\/** Tries to place a chest at the specified (absolute) coords.\n\tDoes nothing if the coords are outside the chunk. *\/\n\tvoid TryPlaceChest(cChunkDesc & a_ChunkDesc, const Vector3i & a_Chest)\n\t{\n\t\tint RelX = a_Chest.x - a_ChunkDesc.GetChunkX() * cChunkDef::Width;\n\t\tint RelZ = a_Chest.z - a_ChunkDesc.GetChunkZ() * cChunkDef::Width;\n\t\tif (\n\t\t\t(RelX < 0) || (RelX >= cChunkDef::Width) || \/\/ The X coord is not in this chunk\n\t\t\t(RelZ < 0) || (RelZ >= cChunkDef::Width) \/\/ The Z coord is not in this chunk\n\t\t)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\ta_ChunkDesc.SetBlockTypeMeta(RelX, m_FloorHeight + 1, RelZ, E_BLOCK_CHEST, (NIBBLETYPE)a_Chest.y);\n\n\t\t\/\/ TODO: Fill the chest with random loot\n\t}\n\n\n\n\t\/\/ cGridStructGen::cStructure override:\n\tvirtual void DrawIntoChunk(cChunkDesc & a_ChunkDesc) override\n\t{\n\t\tif (\n\t\t\t(m_EndX < a_ChunkDesc.GetChunkX() * cChunkDef::Width) ||\n\t\t\t(m_StartX >= a_ChunkDesc.GetChunkX() * cChunkDef::Width + cChunkDef::Width) ||\n\t\t\t(m_EndZ < a_ChunkDesc.GetChunkZ() * cChunkDef::Width) ||\n\t\t\t(m_StartZ >= a_ChunkDesc.GetChunkZ() * cChunkDef::Width + cChunkDef::Width)\n\t\t)\n\t\t{\n\t\t\t\/\/ The chunk is not intersecting the room at all, bail out\n\t\t\treturn;\n\t\t}\n\t\tint b = m_FloorHeight + 1; \/\/ Bottom\n\t\tint t = m_FloorHeight + 1 + ROOM_HEIGHT; \/\/ Top\n\t\tReplaceCuboidRandom(a_ChunkDesc, m_StartX, m_FloorHeight, m_StartZ, m_EndX + 1, b, m_EndZ + 1, E_BLOCK_MOSSY_COBBLESTONE, E_BLOCK_COBBLESTONE); \/\/ Floor\n\t\tReplaceCuboid(a_ChunkDesc, m_StartX + 1, b, m_StartZ + 1, m_EndX, t, m_EndZ, E_BLOCK_AIR); \/\/ Insides\n\n\t\t\/\/ Walls:\n\t\tReplaceCuboid(a_ChunkDesc, m_StartX, b, m_StartZ, m_StartX + 1, t, m_EndZ, E_BLOCK_COBBLESTONE); \/\/ XM wall\n\t\tReplaceCuboid(a_ChunkDesc, m_EndX, b, m_StartZ, m_EndX + 1, t, m_EndZ, E_BLOCK_COBBLESTONE); \/\/ XP wall\n\t\tReplaceCuboid(a_ChunkDesc, m_StartX, b, m_StartZ, m_EndX + 1, t, m_StartZ + 1, E_BLOCK_COBBLESTONE); \/\/ ZM wall\n\t\tReplaceCuboid(a_ChunkDesc, m_StartX, b, m_EndZ, m_EndX + 1, t, m_EndZ + 1, E_BLOCK_COBBLESTONE); \/\/ ZP wall\n\n\t\t\/\/ Place chests:\n\t\tTryPlaceChest(a_ChunkDesc, m_Chest1);\n\t\tTryPlaceChest(a_ChunkDesc, m_Chest2);\n\n\t\t\/\/ Place the spawner:\n\t\tint CenterX = (m_StartX + m_EndX) \/ 2 - a_ChunkDesc.GetChunkX() * cChunkDef::Width;\n\t\tint CenterZ = (m_StartZ + m_EndZ) \/ 2 - a_ChunkDesc.GetChunkZ() * cChunkDef::Width;\n\t\tif (\n\t\t\t(CenterX >= 0) && (CenterX < cChunkDef::Width) &&\n\t\t\t(CenterZ >= 0) && (CenterZ < cChunkDef::Width)\n\t\t)\n\t\t{\n\t\t\ta_ChunkDesc.SetBlockTypeMeta(CenterX, b, CenterZ, E_BLOCK_MOB_SPAWNER, 0);\n\t\t\t\/\/ TODO: Set the spawned mob\n\t\t}\n\t}\n} ;\n\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ cDungeonRoomsFinisher:\n\ncDungeonRoomsFinisher::cDungeonRoomsFinisher(cTerrainHeightGen & a_HeightGen, int a_Seed, int a_GridSize, int a_MaxSize, int a_MinSize, const AString & a_HeightDistrib) :\n\tsuper(a_Seed + 100, a_GridSize, a_GridSize, a_GridSize, a_GridSize, a_MaxSize, a_MaxSize, 1024),\n\tm_HeightGen(a_HeightGen),\n\tm_MaxHalfSize((a_MaxSize + 1) \/ 2),\n\tm_MinHalfSize((a_MinSize + 1) \/ 2),\n\tm_HeightProbability(cChunkDef::Height)\n{\n\t\/\/ Initialize the height probability distribution:\n\tm_HeightProbability.SetDefString(a_HeightDistrib);\n\n\t\/\/ Normalize the min and max size:\n\tif (m_MinHalfSize > m_MaxHalfSize)\n\t{\n\t\tstd::swap(m_MinHalfSize, m_MaxHalfSize);\n\t}\n}\n\n\n\n\n\n\ncDungeonRoomsFinisher::cStructurePtr cDungeonRoomsFinisher::CreateStructure(int a_GridX, int a_GridZ, int a_OriginX, int a_OriginZ)\n{\n\t\/\/ Select a random room size in each direction:\n\tint rnd = m_Noise.IntNoise2DInt(a_OriginX, a_OriginZ) \/ 7;\n\tint HalfSizeX = m_MinHalfSize + (rnd % (m_MaxHalfSize - m_MinHalfSize + 1));\n\trnd = rnd \/ 32;\n\tint HalfSizeZ = m_MinHalfSize + (rnd % (m_MaxHalfSize - m_MinHalfSize + 1));\n\trnd = rnd \/ 32;\n\n\t\/\/ Select a random floor height for the room, based on the height generator:\n\tint ChunkX, ChunkZ;\n\tint RelX = a_OriginX, RelY = 0, RelZ = a_OriginZ;\n\tcChunkDef::AbsoluteToRelative(RelX, RelY, RelZ, ChunkX, ChunkZ);\n\tcChunkDef::HeightMap HeightMap;\n\tm_HeightGen.GenHeightMap(ChunkX, ChunkZ, HeightMap);\n\tint Height = cChunkDef::GetHeight(HeightMap, RelX, RelZ); \/\/ Max room height at {a_OriginX, a_OriginZ}\n\tHeight = Clamp(m_HeightProbability.MapValue(rnd % m_HeightProbability.GetSum()), 10, Height - 5);\n\n\t\/\/ Create the dungeon room descriptor:\n\treturn cStructurePtr(new cDungeonRoom(a_GridX, a_GridZ, a_OriginX, a_OriginZ, HalfSizeX, HalfSizeZ, Height, m_Noise));\n}\n\n\n\n\n<|endoftext|>"} {"text":"\/**\n* Released under the same permissive MIT-license as Urho3D.\n* https:\/\/raw.githubusercontent.com\/urho3d\/Urho3D\/master\/License.txt\n*\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"gs_main_menu.h\"\n#include \"gs_playing.h\"\n\nusing namespace Urho3D;\n\nclass MyApp : public Application\n{\npublic:\n SharedPtr scene_;\n Node* cameraNode_;\n\n MyApp(Context * context) : Application(context)\n {\n }\n\n virtual void Setup()\n {\n engineParameters_[\"FullScreen\"]=false;\n engineParameters_[\"WindowWidth\"]=1280;\n engineParameters_[\"WindowHeight\"]=720;\n engineParameters_[\"WindowResizable\"]=true;\n engineParameters_[\"Multisample\"]=4;\n }\n\n virtual void Start()\n {\n ResourceCache* cache=GetSubsystem();\n GetSubsystem()->GetRoot()->SetDefaultStyle(cache->GetResource(\"UI\/DefaultStyle.xml\"));\n\n scene_=new Scene(context_);\n scene_->CreateComponent();\n scene_->CreateComponent();\n\n \/\/ until we get a better sky system\n Node* skyNode=scene_->CreateChild(\"Sky\");\n skyNode->SetScale(500.0f);\n Skybox* skybox=skyNode->CreateComponent();\n skybox->SetModel(cache->GetResource(\"Models\/Box.mdl\"));\n skybox->SetMaterial(cache->GetResource(\"Materials\/Skybox.xml\"));\n\n cameraNode_=scene_->CreateChild(\"Camera\");\n Camera* camera=cameraNode_->CreateComponent();\n camera->SetFarClip(10000);\n SoundListener* listener=cameraNode_->CreateComponent();\n GetSubsystem
\";\r\n\r\n\t} else if (mode == \"ADDMENU\") {\r\n\r\n\t\t#define menu arg3\r\n\t\tif (arg4.unassigned()) {\r\n\t\t\tid = \"\";\r\n\t\t}else{\r\n\t\t\tid = arg4;\r\n\t\t}\r\n\r\n\t\t\/\/_Support<\/a>\r\n\t\t\/\/
\r\n\r\n\t\t\/\/use menu title as menu id\r\n\t\tif (not id) {\r\n\t\t\tid = var(menu).ucase();\r\n\t\t\tid.converter(\"_\", \"\");\r\n\t\t}\r\n\r\n\t\t\/\/convert _x to x<\/u> to indicate keyboard shortcut\r\n\t\tvar tt = var(menu).index(\"_\");\r\n\t\tif (tt) {\r\n\t\t\tvar(menu).splicer(tt, 2, \"\" ^ var(menu)[tt + 1] ^ \"<\/u>\");\r\n\t\t}\r\n\r\n\t\ttx ^= FM ^ \"\" ^ menu ^ \"<\/a>\";\r\n\t\ttx ^= FM ^ \"
\";\r\n\r\n\t\tid = \"\";\r\n\r\n\t} else if (mode == \"SUBMENU\") {\r\n\r\n\t\t\/\/_Reports<\/a>\r\n\t\t\/\/
\r\n\r\n\t\tvar submenu = arg3;\r\n\r\n\t\t\/\/convert _x to x<\/u> to indicate keyboard shortcut\r\n\t\tvar tt = submenu.index(\"_\");\r\n\t\tif (tt) {\r\n\t\t\tsubmenu.splicer(tt, 2, \"\" ^ submenu[tt + 1] ^ \"<\/u>\");\r\n\t\t}\r\n\r\n\t\ttx ^= FM ^ \"\" ^ submenu ^ \"<\/a>\";\r\n\t\t\/\/submenus are same class as menus\r\n\t\ttx ^= FM ^ \"
\";\r\n\r\n\t} else if (mode == \"ADDITEM\") {\r\n\r\n\t\tvar item = arg3;\r\n\t\t#define href arg4\r\n\t\t\/\/equate onclick to arg5\r\n\r\n\t\t\/\/M<\/u>onth Plan File<\/a>
\r\n\t\tvar props = \"\";\r\n\t\t\/\/if unassigned(id) else props:=' id=':quote(id)\r\n\t\t\/\/if unassigned(onclick) else props:=' onclick = ':quote(onclick)\r\n\t\tif (not(arg5.unassigned())) {\r\n\t\t\tprops ^= \" arg5 = \" ^ (arg5.quote());\r\n\t\t}\r\n\r\n\t\t\/\/convert _x to x<\/u> to indicate keyboard shortcut\r\n\t\tvar tt = item.index(\"_\");\r\n\t\tif (tt) {\r\n\t\t\titem.splicer(tt, 2, \"\" ^ item[tt + 1] ^ \"<\/u>\");\r\n\t\t}\r\n\r\n\t\ttx ^= FM ^ \" \" ^ item ^ \"<\/a>
\";\r\n\r\n\t} else if (mode == \"ADDSEP\") {\r\n\r\n\t\ttx ^= FM ^ \"
\";\r\n\r\n\t} else if (mode == \"ENDSUBMENU\") {\r\n\r\n\t\ttx ^= FM ^ \"<\/div>\";\r\n\t\ttx ^= FM ^ \"
\";\r\n\r\n\t} else if (mode == \"ENDMENU\") {\r\n\r\n\t\ttx ^= FM ^ \"<\/div>\";\r\n\r\n\t} else if (mode == \"EXITMENUS\") {\r\n\r\n\t\ttx ^= FM ^ \"