text
stringlengths
54
60.6k
<commit_before>#include "tagentry.h" using namespace AhoViewer::Booru; TagEntry::TagEntry(BaseObjectType *cobj, const Glib::RefPtr<Gtk::Builder> &bldr) : Gtk::Entry(cobj) { m_TagCompletion = Glib::RefPtr<Gtk::EntryCompletion>::cast_static( bldr->get_object("Booru::Browser::TagEntryCompletion")); m_Model = Gtk::ListStore::create(m_Columns); set_completion(m_TagCompletion); m_TagCompletion->set_match_func(sigc::mem_fun(*this, &TagEntry::match_func)); m_TagCompletion->set_model(m_Model); m_TagCompletion->set_text_column(m_Columns.tag_column); m_TagCompletion->signal_match_selected().connect(sigc::mem_fun(*this, &TagEntry::on_match_selected), false); // XXX: gtkmm's cursor-on-match signal seems to be broken. g_signal_connect(m_TagCompletion->gobj(), "cursor-on-match", G_CALLBACK(on_cursor_on_match_c), this); m_ChangedConn = signal_changed().connect(sigc::mem_fun(*this, &TagEntry::on_text_changed)); } void TagEntry::set_tags(const std::set<std::string> &tags) { m_Tags = &tags; } void TagEntry::on_grab_focus() { Gtk::Entry::on_grab_focus(); select_region(0, 0); set_position(-1); } void TagEntry::on_text_changed() { size_t pos = get_text().find_last_of(' '); int spos, epos; get_selection_bounds(spos, epos); std::string key = pos == std::string::npos ? get_text() : get_text().substr(pos + 1, spos - pos + 1); // Check if key is prefixed if (key[0] == '-') key = key.substr(1); Gtk::TreeRow row; m_Model->clear(); if (key.length() >= static_cast<size_t>(m_TagCompletion->get_minimum_key_length())) { size_t i = 0; for (const std::string &tag : *m_Tags) { if (tag.compare(0, key.length(), key) == 0) { row = *(m_Model->append()); row[m_Columns.tag_column] = tag; // Limit list to 20 tags if (++i >= 20) break; } } } m_TagCompletion->complete(); } gboolean TagEntry::on_cursor_on_match_c(GtkEntryCompletion*, GtkTreeModel *model, GtkTreeIter *iter, TagEntry *entry) { GValue value = G_VALUE_INIT; gtk_tree_model_get_value(model, iter, 0, &value); entry->on_cursor_on_match(static_cast<const char*>(g_value_get_string(&value))); g_value_unset(&value); return TRUE; } void TagEntry::on_cursor_on_match(const std::string &tag) { size_t pos = get_text().find_last_of(' '); std::string tags = pos == std::string::npos ? "" : get_text().substr(0, pos + 1), prefix = (pos == std::string::npos ? get_text()[0] : get_text()[pos + 1]) == '-' ? "-" : ""; int spos, epos; get_selection_bounds(spos, epos); m_ChangedConn.block(); set_text(tags + prefix + tag); m_ChangedConn.unblock(); select_region(spos, -1); } bool TagEntry::on_match_selected(const Gtk::TreeIter &iter) { std::string tag((*iter)->get_value(m_Columns.tag_column)); size_t pos = get_text().find_last_of(' '); std::string tags = pos == std::string::npos ? "" : get_text().substr(0, pos + 1), prefix = (pos == std::string::npos ? get_text()[0] : get_text()[pos + 1]) == '-' ? "-" : ""; m_ChangedConn.block(); set_text(tags + prefix + tag + " "); m_ChangedConn.unblock(); select_region(0, 0); set_position(-1); return true; } <commit_msg>booru/tagentry: Some minor code clean up<commit_after>#include "tagentry.h" using namespace AhoViewer::Booru; TagEntry::TagEntry(BaseObjectType *cobj, const Glib::RefPtr<Gtk::Builder> &bldr) : Gtk::Entry(cobj) { m_TagCompletion = Glib::RefPtr<Gtk::EntryCompletion>::cast_static( bldr->get_object("Booru::Browser::TagEntryCompletion")); m_Model = Gtk::ListStore::create(m_Columns); set_completion(m_TagCompletion); m_TagCompletion->set_match_func(sigc::mem_fun(*this, &TagEntry::match_func)); m_TagCompletion->set_model(m_Model); m_TagCompletion->set_text_column(m_Columns.tag_column); m_TagCompletion->signal_match_selected().connect(sigc::mem_fun(*this, &TagEntry::on_match_selected), false); // XXX: gtkmm's cursor-on-match signal seems to be broken. g_signal_connect(m_TagCompletion->gobj(), "cursor-on-match", G_CALLBACK(on_cursor_on_match_c), this); m_ChangedConn = signal_changed().connect(sigc::mem_fun(*this, &TagEntry::on_text_changed)); } void TagEntry::set_tags(const std::set<std::string> &tags) { m_Tags = &tags; } void TagEntry::on_grab_focus() { Gtk::Entry::on_grab_focus(); select_region(0, 0); set_position(-1); } void TagEntry::on_text_changed() { size_t pos = get_text().find_last_of(' '); int spos, epos; get_selection_bounds(spos, epos); std::string key = pos == std::string::npos ? get_text() : get_text().substr(pos + 1, spos - pos + 1); // Check if key is prefixed if (key[0] == '-') key = key.substr(1); m_Model->clear(); if (key.length() >= static_cast<size_t>(m_TagCompletion->get_minimum_key_length())) { size_t i = 0; for (const std::string &tag : *m_Tags) { if (tag.compare(0, key.length(), key) == 0) { Gtk::TreeIter iter = m_Model->append(); iter->set_value(m_Columns.tag_column, tag); // Limit list to 20 tags if (++i >= 20) break; } } } m_TagCompletion->complete(); } gboolean TagEntry::on_cursor_on_match_c(GtkEntryCompletion*, GtkTreeModel *model, GtkTreeIter *iter, TagEntry *entry) { GValue value = G_VALUE_INIT; gtk_tree_model_get_value(model, iter, 0, &value); entry->on_cursor_on_match(static_cast<const char*>(g_value_get_string(&value))); g_value_unset(&value); return TRUE; } void TagEntry::on_cursor_on_match(const std::string &tag) { size_t pos = get_text().find_last_of(' '); std::string tags = pos == std::string::npos ? "" : get_text().substr(0, pos + 1), prefix = (pos == std::string::npos ? get_text()[0] : get_text()[pos + 1]) == '-' ? "-" : ""; int spos, epos; get_selection_bounds(spos, epos); m_ChangedConn.block(); set_text(tags + prefix + tag); m_ChangedConn.unblock(); // This is needed to keep track of what part of the tag was completed select_region(spos, -1); } bool TagEntry::on_match_selected(const Gtk::TreeIter &iter) { size_t pos = get_text().find_last_of(' '); std::string tag = iter->get_value(m_Columns.tag_column), tags = pos == std::string::npos ? "" : get_text().substr(0, pos + 1), prefix = (pos == std::string::npos ? get_text()[0] : get_text()[pos + 1]) == '-' ? "-" : ""; m_ChangedConn.block(); set_text(tags + prefix + tag + " "); m_ChangedConn.unblock(); select_region(0, 0); set_position(-1); return true; } <|endoftext|>
<commit_before>/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include <gtest/gtest.h> #include <mrpt/io/CFileGZInputStream.h> #include <mrpt/maps/COccupancyGridMap3D.h> #include <mrpt/obs/CObservation2DRangeScan.h> #include <mrpt/obs/CObservation3DRangeScan.h> #include <mrpt/obs/CSensoryFrame.h> #include <mrpt/obs/stock_observations.h> #include <mrpt/serialization/CArchive.h> #include <mrpt/system/filesystem.h> #include <test_mrpt_common.h> TEST(COccupancyGridMap3DTests, insert2DScan) { mrpt::obs::CObservation2DRangeScan scan1; mrpt::obs::stock_observations::example2DRangeScan(scan1); // Insert the scan in the grid map and check expected values: { mrpt::maps::COccupancyGridMap3D grid; grid.insertObservation(&scan1); // A cell in front of the laser should have a high "freeness" EXPECT_GT(grid.getFreenessByPos(0.5, 0, 0), 0.53f); } } TEST(COccupancyGridMap3DTests, insertScan3D) { using namespace std::string_literals; const auto fil = mrpt::UNITTEST_BASEDIR + "/tests/test-3d-obs-ground.rawlog"s; if (!mrpt::system::fileExists(fil)) { GTEST_FAIL() << "ERROR: test due to missing file: " << fil << "\n"; return; } // Load sample 3D scan from file: mrpt::obs::CSensoryFrame sf; mrpt::io::CFileGZInputStream f(fil); mrpt::serialization::archiveFrom(f) >> sf; auto obs = sf.getObservationByClass<mrpt::obs::CObservation3DRangeScan>(); ASSERT_(obs); { mrpt::maps::COccupancyGridMap3D grid; grid.insertObservation(obs.get()); // A cell in front of the laser should have a high "freeness" EXPECT_GT(grid.getFreenessByPos(0.2, 0.2, 0.1), 0.53f); } } <commit_msg>fix unit tests w/o OpenCV<commit_after>/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include <gtest/gtest.h> #include <mrpt/io/CFileGZInputStream.h> #include <mrpt/maps/COccupancyGridMap3D.h> #include <mrpt/obs/CObservation2DRangeScan.h> #include <mrpt/obs/CObservation3DRangeScan.h> #include <mrpt/obs/CSensoryFrame.h> #include <mrpt/obs/stock_observations.h> #include <mrpt/serialization/CArchive.h> #include <mrpt/system/filesystem.h> #include <test_mrpt_common.h> TEST(COccupancyGridMap3DTests, insert2DScan) { mrpt::obs::CObservation2DRangeScan scan1; mrpt::obs::stock_observations::example2DRangeScan(scan1); // Insert the scan in the grid map and check expected values: { mrpt::maps::COccupancyGridMap3D grid; grid.insertObservation(&scan1); // A cell in front of the laser should have a high "freeness" EXPECT_GT(grid.getFreenessByPos(0.5, 0, 0), 0.53f); } } // We need OPENCV to read the image internal to CObservation3DRangeScan, // so skip this test if built without opencv. #if MRPT_HAS_OPENCV TEST(COccupancyGridMap3DTests, insertScan3D) { using namespace std::string_literals; const auto fil = mrpt::UNITTEST_BASEDIR + "/tests/test-3d-obs-ground.rawlog"s; if (!mrpt::system::fileExists(fil)) { GTEST_FAIL() << "ERROR: test due to missing file: " << fil << "\n"; return; } // Load sample 3D scan from file: mrpt::obs::CSensoryFrame sf; mrpt::io::CFileGZInputStream f(fil); mrpt::serialization::archiveFrom(f) >> sf; auto obs = sf.getObservationByClass<mrpt::obs::CObservation3DRangeScan>(); ASSERT_(obs); { mrpt::maps::COccupancyGridMap3D grid; grid.insertObservation(obs.get()); // A cell in front of the laser should have a high "freeness" EXPECT_GT(grid.getFreenessByPos(0.2f, 0.2f, 0.1f), 0.53f); } } #endif <|endoftext|>
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGInertial.cpp Author: Jon S. Berndt Date started: 09/13/00 Purpose: Encapsulates the inertial frame forces (coriolis and centrifugal) ------------- Copyright (C) 2000 Jon S. Berndt ([email protected]) ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- HISTORY -------------------------------------------------------------------------------- 09/13/00 JSB Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGInertial.h" #include "FGFDMExec.h" #include <iostream> using namespace std; namespace JSBSim { IDENT(IdSrc,"$Id: FGInertial.cpp,v 1.29 2014/01/13 10:46:07 ehofman Exp $"); IDENT(IdHdr,ID_INERTIAL); /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ FGInertial::FGInertial(FGFDMExec* fgex) : FGModel(fgex) { Name = "FGInertial"; // Earth defaults RotationRate = 0.00007292115; GM = 14.07644180E15; // WGS84 value RadiusReference = 20925650.00; // Equatorial radius (WGS84) C2_0 = -4.84165371736E-04; // WGS84 value for the C2,0 coefficient J2 = 1.0826266836E-03; // WGS84 value for J2 a = 20925646.3255; // WGS84 semimajor axis length in feet b = 20855486.5951; // WGS84 semiminor axis length in feet // Lunar defaults /* RotationRate = 0.0000026617; GM = 1.7314079E14; // Lunar GM RadiusReference = 5702559.05; // Equatorial radius C2_0 = 0; // value for the C2,0 coefficient J2 = 2.033542482111609E-4; // value for J2 a = 5702559.05; // semimajor axis length in feet b = 5695439.63; // semiminor axis length in feet */ vOmegaPlanet = FGColumnVector3( 0.0, 0.0, RotationRate ); gAccelReference = GM/(RadiusReference*RadiusReference); gAccel = GM/(RadiusReference*RadiusReference); bind(); Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGInertial::~FGInertial(void) { Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGInertial::InitModel(void) { return FGModel::InitModel(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGInertial::Run(bool Holding) { // Fast return if we have nothing to do ... if (FGModel::Run(Holding)) return true; if (Holding) return false; // Gravitation accel gAccel = GetGAccel(in.Radius); return false; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGInertial::GetGAccel(double r) const { return GM/(r*r); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // // Calculate the WGS84 gravitation value in ECEF frame. Pass in the ECEF position // via the position parameter. The J2Gravity value returned is in ECEF frame, // and therefore may need to be expressed (transformed) in another frame, // depending on how it is used. See Stevens and Lewis eqn. 1.4-16. FGColumnVector3 FGInertial::GetGravityJ2(const FGColumnVector3& position) const { FGColumnVector3 J2Gravity; // Gravitation accel double r = position.Magnitude(); double sinLat = sin(in.Latitude); double adivr = a/r; double preCommon = 1.5*J2*adivr*adivr; double xy = 1.0 - 5.0*(sinLat*sinLat); double z = 3.0 - 5.0*(sinLat*sinLat); double GMOverr2 = GM/(r*r); J2Gravity(1) = -GMOverr2 * ((1.0 + (preCommon * xy)) * position(eX)/r); J2Gravity(2) = -GMOverr2 * ((1.0 + (preCommon * xy)) * position(eY)/r); J2Gravity(3) = -GMOverr2 * ((1.0 + (preCommon * z)) * position(eZ)/r); return J2Gravity; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGInertial::bind(void) { PropertyManager->Tie("inertial/sea-level-radius_ft", this, &FGInertial::GetRefRadius); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print // out the normally expected messages, essentially echoing // the config files as they are read. If the environment // variable is not set, debug_lvl is set to 1 internally // 0: This requests JSBSim not to output any messages // whatsoever. // 1: This value explicity requests the normal JSBSim // startup messages // 2: This value asks for a message to be printed out when // a class is instantiated // 4: When this value is set, a message is displayed when a // FGModel object executes its Run() method // 8: When this value is set, various runtime state variables // are printed out periodically // 16: When set various parameters are sanity checked and // a message is printed out when they go out of bounds void FGInertial::Debug(int from) { if (debug_lvl <= 0) return; if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification if (from == 0) cout << "Instantiated: FGInertial" << endl; if (from == 1) cout << "Destroyed: FGInertial" << endl; } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } if (debug_lvl & 8 ) { // Runtime state variables } if (debug_lvl & 16) { // Sanity checking } if (debug_lvl & 64) { if (from == 0) { // Constructor cout << IdSrc << endl; cout << IdHdr << endl; } } } } <commit_msg>Fixed a slight error in reference radius<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGInertial.cpp Author: Jon S. Berndt Date started: 09/13/00 Purpose: Encapsulates the inertial frame forces (coriolis and centrifugal) ------------- Copyright (C) 2000 Jon S. Berndt ([email protected]) ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- HISTORY -------------------------------------------------------------------------------- 09/13/00 JSB Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGInertial.h" #include "FGFDMExec.h" #include <iostream> using namespace std; namespace JSBSim { IDENT(IdSrc,"$Id: FGInertial.cpp,v 1.30 2014/03/10 14:09:56 jberndt Exp $"); IDENT(IdHdr,ID_INERTIAL); /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ FGInertial::FGInertial(FGFDMExec* fgex) : FGModel(fgex) { Name = "FGInertial"; // Earth defaults RotationRate = 0.00007292115; GM = 14.07644180E15; // WGS84 value RadiusReference = 20925646.3255; // Equatorial radius (WGS84) C2_0 = -4.84165371736E-04; // WGS84 value for the C2,0 coefficient J2 = 1.0826266836E-03; // WGS84 value for J2 a = 20925646.3255; // WGS84 semimajor axis length in feet b = 20855486.5951; // WGS84 semiminor axis length in feet // Lunar defaults /* RotationRate = 0.0000026617; GM = 1.7314079E14; // Lunar GM RadiusReference = 5702559.05; // Equatorial radius C2_0 = 0; // value for the C2,0 coefficient J2 = 2.033542482111609E-4; // value for J2 a = 5702559.05; // semimajor axis length in feet b = 5695439.63; // semiminor axis length in feet */ vOmegaPlanet = FGColumnVector3( 0.0, 0.0, RotationRate ); gAccelReference = GM/(RadiusReference*RadiusReference); gAccel = GM/(RadiusReference*RadiusReference); bind(); Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGInertial::~FGInertial(void) { Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGInertial::InitModel(void) { return FGModel::InitModel(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGInertial::Run(bool Holding) { // Fast return if we have nothing to do ... if (FGModel::Run(Holding)) return true; if (Holding) return false; // Gravitation accel gAccel = GetGAccel(in.Radius); return false; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGInertial::GetGAccel(double r) const { return GM/(r*r); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // // Calculate the WGS84 gravitation value in ECEF frame. Pass in the ECEF position // via the position parameter. The J2Gravity value returned is in ECEF frame, // and therefore may need to be expressed (transformed) in another frame, // depending on how it is used. See Stevens and Lewis eqn. 1.4-16. FGColumnVector3 FGInertial::GetGravityJ2(const FGColumnVector3& position) const { FGColumnVector3 J2Gravity; // Gravitation accel double r = position.Magnitude(); double sinLat = sin(in.Latitude); double adivr = a/r; double preCommon = 1.5*J2*adivr*adivr; double xy = 1.0 - 5.0*(sinLat*sinLat); double z = 3.0 - 5.0*(sinLat*sinLat); double GMOverr2 = GM/(r*r); J2Gravity(1) = -GMOverr2 * ((1.0 + (preCommon * xy)) * position(eX)/r); J2Gravity(2) = -GMOverr2 * ((1.0 + (preCommon * xy)) * position(eY)/r); J2Gravity(3) = -GMOverr2 * ((1.0 + (preCommon * z)) * position(eZ)/r); return J2Gravity; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGInertial::bind(void) { PropertyManager->Tie("inertial/sea-level-radius_ft", this, &FGInertial::GetRefRadius); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print // out the normally expected messages, essentially echoing // the config files as they are read. If the environment // variable is not set, debug_lvl is set to 1 internally // 0: This requests JSBSim not to output any messages // whatsoever. // 1: This value explicity requests the normal JSBSim // startup messages // 2: This value asks for a message to be printed out when // a class is instantiated // 4: When this value is set, a message is displayed when a // FGModel object executes its Run() method // 8: When this value is set, various runtime state variables // are printed out periodically // 16: When set various parameters are sanity checked and // a message is printed out when they go out of bounds void FGInertial::Debug(int from) { if (debug_lvl <= 0) return; if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification if (from == 0) cout << "Instantiated: FGInertial" << endl; if (from == 1) cout << "Destroyed: FGInertial" << endl; } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } if (debug_lvl & 8 ) { // Runtime state variables } if (debug_lvl & 16) { // Sanity checking } if (debug_lvl & 64) { if (from == 0) { // Constructor cout << IdSrc << endl; cout << IdHdr << endl; } } } } <|endoftext|>
<commit_before>// // // Copyright (C) 2004-05 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-05 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Cloned from syslogviewer #include <errno.h> #include <fcntl.h> #include <stdio.h> #if defined(_WIN32) # include <io.h> # include <string.h> #elif defined(__linux__) # include <unistd.h> #endif #define BUFFER_SIZE 8192 #include <os/OsDefs.h> #include <os/OsSysLog.h> #include <net/NameValueTokenizer.h> #include <net/SipMessage.h> void writeMessageNodesBegin(int outputFileDescriptor) { UtlString nodeBegin("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<sipTrace>\n"); write(outputFileDescriptor, nodeBegin.data(), nodeBegin.length()); } void writeMessageNodesEnd(int outputFileDescriptor) { UtlString nodeEnd("</sipTrace>\n"); write(outputFileDescriptor, nodeEnd.data(), nodeEnd.length()); } void writeBranchNodeBegin(int outputFileDescriptor) { UtlString nodeBegin("\t<branchNode>\n"); write(outputFileDescriptor, nodeBegin.data(), nodeBegin.length()); } void writeBranchNodeEnd(int outputFileDescriptor) { UtlString nodeEnd("\t</branchNode>\n"); write(outputFileDescriptor, nodeEnd.data(), nodeEnd.length()); } void writeBranchSetBegin(int outputFileDescriptor) { UtlString nodeBegin("\t\t<branchIdSet>\n"); write(outputFileDescriptor, nodeBegin.data(), nodeBegin.length()); } void writeBranchSetEnd(int outputFileDescriptor) { UtlString nodeEnd("\t\t</branchIdSet>\n"); write(outputFileDescriptor, nodeEnd.data(), nodeEnd.length()); } void writeBranchId(int outputFileDescriptor, UtlString& branchId) { NameValueTokenizer::frontBackTrim(&branchId, " \t\n\r"); UtlString node("\t\t\t<branchId>"); node.append(branchId); node.append("</branchId>\n"); write(outputFileDescriptor, node.data(), node.length()); } void writeBranchNodeData(int outputFileDescriptor, UtlString& time, UtlString& source, UtlString& destination, UtlString& sourceAddress, UtlString& destinationAddress, UtlString& transactionId, UtlString& frameId, UtlString& method, UtlString& responseCode, UtlString& responseText, UtlString& message) { NameValueTokenizer::frontBackTrim(&time, " \t\n\r"); NameValueTokenizer::frontBackTrim(&source, " \t\n\r"); NameValueTokenizer::frontBackTrim(&destination, " \t\n\r"); NameValueTokenizer::frontBackTrim(&sourceAddress, " \t\n\r"); NameValueTokenizer::frontBackTrim(&destinationAddress, " \t\n\r"); NameValueTokenizer::frontBackTrim(&transactionId, " \t\n\r"); NameValueTokenizer::frontBackTrim(&frameId, " \t\n\r"); NameValueTokenizer::frontBackTrim(&method, " \t\n\r"); NameValueTokenizer::frontBackTrim(&responseCode, " \t\n\r"); NameValueTokenizer::frontBackTrim(&responseText, " \t\n\r"); //NameValueTokenizer::frontBackTrim(&message, " \t\n\r"); UtlString node("\t\t<time>"); node.append(time); node.append("</time>\n"); if(!source.isNull()) { node.append("\t\t<source>"); node.append(source); node.append("</source>\n"); } if(!destination.isNull()) { node.append("\t\t<destination>"); node.append(destination); node.append("</destination>\n"); } node.append("\t\t<sourceAddress>"); node.append(sourceAddress); node.append("</sourceAddress>\n"); node.append("\t\t<destinationAddress>"); node.append(destinationAddress); node.append("</destinationAddress>\n"); node.append("\t\t<transactionId>"); node.append(transactionId); node.append("</transactionId>\n"); if(!method.isNull()) { node.append("\t\t<method>"); node.append(method); node.append("</method>\n"); } else { node.append("\t\t<responseCode>"); node.append(responseCode); node.append("</responseCode>\n"); node.append("\t\t<responseText>"); node.append(responseText); node.append("</responseText>\n"); } node.append("\t\t<frameId>"); node.append(frameId); node.append("</frameId>\n"); node.append("\t\t<message><![CDATA["); node.append(message); node.append("]]></message>\n"); write(outputFileDescriptor, node.data(), node.length()); } void getMessageData(UtlString& content, UtlBoolean isOutgoing, UtlString& date, UtlString& hostname, UtlString& eventCount, int outputFileDescriptor) { UtlString remoteHost; UtlString remoteAddress; UtlString remotePort; UtlString remoteSourceAddress; UtlString message; UtlString branchId; UtlString transactionId; UtlString method; UtlString responseCode; UtlString responseText; UtlBoolean failed = FALSE; int hostIndex = content.index("----Remote Host:"); if(hostIndex > 0) { hostIndex += 16; int hostEnd = content.index("----", hostIndex); remoteHost.append(&(content.data()[hostIndex]), hostEnd - hostIndex); remoteAddress = remoteHost; remoteHost.append(":"); int portIndex = hostEnd + 11; int portEnd = content.index("----", portIndex); remotePort.append(&(content.data()[portIndex]), portEnd - portIndex); remoteHost.append(remotePort); int messageIndex = portEnd + 5; unsigned int messageEnd; if(isOutgoing) { messageEnd = content.index("--------------------END", messageIndex); // Record whether the send failed or not. failed = (content.index("User Agent failed to send message") != UTL_NOT_FOUND); } else { messageEnd = content.index("====================END", messageIndex); } if ( UTL_NOT_FOUND == messageEnd ) { messageEnd = content.length(); } message.append(&(content.data()[messageIndex]), messageEnd - messageIndex); SipMessage sipMsg(message); remoteSourceAddress = remoteHost; if(sipMsg.isResponse()) { sipMsg.getFirstHeaderLinePart(1, &responseCode); if (failed) { responseCode = responseCode + " FAILED"; } sipMsg.getFirstHeaderLinePart(2, &responseText); if(!isOutgoing) { remoteHost.remove(0); } } else { sipMsg.getRequestMethod(&method); if (failed) { method = "FAILED " + method; } //We can derive the source entity from the via in // incoming requests if(!isOutgoing) { UtlString viaAddress; UtlString protocol; int viaPortNum; sipMsg.getLastVia(&viaAddress, &viaPortNum, &protocol); char numBuff[30]; sprintf(numBuff, "%d", viaPortNum); UtlString viaPort(numBuff); remoteHost = remoteAddress + ":" + viaPort; } } // transaction token: cseq,call-id,from-tag,to=tag int cseq; UtlString cseqMethod; sipMsg.getCSeqField(&cseq, &cseqMethod); char numBuf[20]; sprintf(numBuf, "%d", cseq); UtlString callId; sipMsg.getCallIdField(&callId); Url to; sipMsg.getToUrl(to); UtlString toTag; to.getFieldParameter("tag", toTag); Url from; sipMsg.getFromUrl(from); UtlString fromTag; from.getFieldParameter("tag", fromTag); transactionId = numBuf; transactionId.append(","); transactionId.append(callId); transactionId.append(","); transactionId.append(fromTag); transactionId.append(","); transactionId.append(toTag); // Write all the stuff out // Write out the node container start writeBranchNodeBegin(outputFileDescriptor); // Write out the branchId container start writeBranchSetBegin(outputFileDescriptor); // Write out the branchIds int viaIndex = 0; UtlString topVia; while(sipMsg.getViaField(&topVia, viaIndex)) { SipMessage::getViaTag(topVia.data(), "branch", branchId); writeBranchId(outputFileDescriptor, branchId); viaIndex++; } // Write out the branchId container finish writeBranchSetEnd(outputFileDescriptor); // Write out the rest of the node data writeBranchNodeData(outputFileDescriptor, date, isOutgoing ? hostname : remoteHost, isOutgoing ? remoteHost : hostname, isOutgoing ? hostname : remoteSourceAddress, isOutgoing ? remoteSourceAddress : hostname, transactionId, eventCount, method, responseCode, responseText, message); // Write out the node container finish writeBranchNodeEnd(outputFileDescriptor); } } void convertToXml(UtlString& bufferString, int outputFileDescriptor) { UtlString date; UtlString eventCount; UtlString facility; UtlString priority; UtlString hostname; UtlString taskname; UtlString taskId; UtlString processId; UtlString content; OsSysLog::parseLogString(bufferString.data(), date, eventCount, facility, priority, hostname, taskname, taskId, processId, content); if(facility.compareTo("OUTGOING") == 0) { hostname.append("-"); hostname.append(processId); getMessageData(content, TRUE, date, hostname, eventCount, outputFileDescriptor); } else if(facility.compareTo("INCOMING") == 0) { hostname.append("-"); hostname.append(processId); getMessageData(content, FALSE, date, hostname, eventCount, outputFileDescriptor); } } int main(int argc, char * argv[]) { int i; // Input file descriptor. Default is stdin. int ifd = 0; // Output file descriptor. Default is stdout. int ofd = 1; // Parse the arguments. for(i = 1; i < argc; i++) { if(!strcmp(argv[i], "-h")) { // If an argument is -h, print the usage message and exit. fprintf(stderr, "Usage:\n\t%s [-h] [if=input] [of=output]\n", argv[0]); return 0; } else if(!strncmp(argv[i], "if=", 3)) { // if= designates the input file. ifd = open(&argv[i][3], O_RDONLY); if(ifd == -1) { fprintf(stderr, "%s: %s\n", &argv[i][3], strerror(errno)); return 1; } } else if(!strncmp(argv[i], "of=", 3)) { // of= designates the output file. #ifdef _WIN32 ofd = open(&argv[i][3], O_BINARY | O_WRONLY | O_CREAT, 0644); #else /* No such thing as a "binary" file on POSIX */ ofd = open(&argv[i][3], O_WRONLY | O_CREAT, 0644); #endif if(ofd == -1) { fprintf(stderr, "%s: %s\n", &argv[i][3], strerror(errno)); return 1; } } else { // All other options are errors. fprintf(stderr, "Unknown option: %s\n", argv[i]); return 1; } } writeMessageNodesBegin(ofd); char inputBuffer[BUFFER_SIZE + 1]; UtlString bufferString; int lineLen; int nextLineStart; do { i = read(ifd, inputBuffer, BUFFER_SIZE); if(i > 0) { inputBuffer[i] = '\0'; bufferString.append(inputBuffer); } do { lineLen = NameValueTokenizer::findNextLineTerminator(bufferString.data(), bufferString.length(), &nextLineStart); // If a new line was found if(nextLineStart > 0) { UtlString line; line.append(bufferString, lineLen); bufferString.remove(0, nextLineStart); convertToXml(line, ofd); } } while(nextLineStart > 0); } while(i && i != -1); // Last line without a newline convertToXml(bufferString, ofd); writeMessageNodesEnd(ofd); close(ofd); return 0; } <commit_msg>Distinguish re-INVITEs from INVITEs.<commit_after>// // // Copyright (C) 2004-05 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-05 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Cloned from syslogviewer #include <errno.h> #include <fcntl.h> #include <stdio.h> #if defined(_WIN32) # include <io.h> # include <string.h> #elif defined(__linux__) # include <unistd.h> #endif #define BUFFER_SIZE 8192 #include <os/OsDefs.h> #include <os/OsSysLog.h> #include <net/NameValueTokenizer.h> #include <net/SipMessage.h> void writeMessageNodesBegin(int outputFileDescriptor) { UtlString nodeBegin("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<sipTrace>\n"); write(outputFileDescriptor, nodeBegin.data(), nodeBegin.length()); } void writeMessageNodesEnd(int outputFileDescriptor) { UtlString nodeEnd("</sipTrace>\n"); write(outputFileDescriptor, nodeEnd.data(), nodeEnd.length()); } void writeBranchNodeBegin(int outputFileDescriptor) { UtlString nodeBegin("\t<branchNode>\n"); write(outputFileDescriptor, nodeBegin.data(), nodeBegin.length()); } void writeBranchNodeEnd(int outputFileDescriptor) { UtlString nodeEnd("\t</branchNode>\n"); write(outputFileDescriptor, nodeEnd.data(), nodeEnd.length()); } void writeBranchSetBegin(int outputFileDescriptor) { UtlString nodeBegin("\t\t<branchIdSet>\n"); write(outputFileDescriptor, nodeBegin.data(), nodeBegin.length()); } void writeBranchSetEnd(int outputFileDescriptor) { UtlString nodeEnd("\t\t</branchIdSet>\n"); write(outputFileDescriptor, nodeEnd.data(), nodeEnd.length()); } void writeBranchId(int outputFileDescriptor, UtlString& branchId) { NameValueTokenizer::frontBackTrim(&branchId, " \t\n\r"); UtlString node("\t\t\t<branchId>"); node.append(branchId); node.append("</branchId>\n"); write(outputFileDescriptor, node.data(), node.length()); } void writeBranchNodeData(int outputFileDescriptor, UtlString& time, UtlString& source, UtlString& destination, UtlString& sourceAddress, UtlString& destinationAddress, UtlString& transactionId, UtlString& frameId, UtlString& method, UtlString& responseCode, UtlString& responseText, UtlString& message) { NameValueTokenizer::frontBackTrim(&time, " \t\n\r"); NameValueTokenizer::frontBackTrim(&source, " \t\n\r"); NameValueTokenizer::frontBackTrim(&destination, " \t\n\r"); NameValueTokenizer::frontBackTrim(&sourceAddress, " \t\n\r"); NameValueTokenizer::frontBackTrim(&destinationAddress, " \t\n\r"); NameValueTokenizer::frontBackTrim(&transactionId, " \t\n\r"); NameValueTokenizer::frontBackTrim(&frameId, " \t\n\r"); NameValueTokenizer::frontBackTrim(&method, " \t\n\r"); NameValueTokenizer::frontBackTrim(&responseCode, " \t\n\r"); NameValueTokenizer::frontBackTrim(&responseText, " \t\n\r"); //NameValueTokenizer::frontBackTrim(&message, " \t\n\r"); UtlString node("\t\t<time>"); node.append(time); node.append("</time>\n"); if(!source.isNull()) { node.append("\t\t<source>"); node.append(source); node.append("</source>\n"); } if(!destination.isNull()) { node.append("\t\t<destination>"); node.append(destination); node.append("</destination>\n"); } node.append("\t\t<sourceAddress>"); node.append(sourceAddress); node.append("</sourceAddress>\n"); node.append("\t\t<destinationAddress>"); node.append(destinationAddress); node.append("</destinationAddress>\n"); node.append("\t\t<transactionId>"); node.append(transactionId); node.append("</transactionId>\n"); if(!method.isNull()) { node.append("\t\t<method>"); node.append(method); node.append("</method>\n"); } else { node.append("\t\t<responseCode>"); node.append(responseCode); node.append("</responseCode>\n"); node.append("\t\t<responseText>"); node.append(responseText); node.append("</responseText>\n"); } node.append("\t\t<frameId>"); node.append(frameId); node.append("</frameId>\n"); node.append("\t\t<message><![CDATA["); node.append(message); node.append("]]></message>\n"); write(outputFileDescriptor, node.data(), node.length()); } void getMessageData(UtlString& content, UtlBoolean isOutgoing, UtlString& date, UtlString& hostname, UtlString& eventCount, int outputFileDescriptor) { UtlString remoteHost; UtlString remoteAddress; UtlString remotePort; UtlString remoteSourceAddress; UtlString message; UtlString branchId; UtlString transactionId; UtlString method; UtlString responseCode; UtlString responseText; UtlBoolean failed = FALSE; int hostIndex = content.index("----Remote Host:"); if(hostIndex > 0) { hostIndex += 16; int hostEnd = content.index("----", hostIndex); remoteHost.append(&(content.data()[hostIndex]), hostEnd - hostIndex); remoteAddress = remoteHost; remoteHost.append(":"); int portIndex = hostEnd + 11; int portEnd = content.index("----", portIndex); remotePort.append(&(content.data()[portIndex]), portEnd - portIndex); remoteHost.append(remotePort); int messageIndex = portEnd + 5; unsigned int messageEnd; if(isOutgoing) { messageEnd = content.index("--------------------END", messageIndex); // Record whether the send failed or not. failed = (content.index("User Agent failed to send message") != UTL_NOT_FOUND); } else { messageEnd = content.index("====================END", messageIndex); } if ( UTL_NOT_FOUND == messageEnd ) { messageEnd = content.length(); } message.append(&(content.data()[messageIndex]), messageEnd - messageIndex); SipMessage sipMsg(message); remoteSourceAddress = remoteHost; if(sipMsg.isResponse()) { sipMsg.getFirstHeaderLinePart(1, &responseCode); if (failed) { responseCode = responseCode + " FAILED"; } sipMsg.getFirstHeaderLinePart(2, &responseText); if(!isOutgoing) { remoteHost.remove(0); } } else { // Get the method. sipMsg.getRequestMethod(&method); // If it is a re-INVITE, make that clear. if (method.compareTo("INVITE", UtlString::ignoreCase) == 0) { Url to; sipMsg.getToUrl(to); UtlString toTag; to.getFieldParameter("tag", toTag); if (!toTag.isNull()) { method = "re-INVITE"; } } // Prepend FAILED if it is a failed transmission. if (failed) { method = "FAILED " + method; } //We can derive the source entity from the via in // incoming requests if(!isOutgoing) { UtlString viaAddress; UtlString protocol; int viaPortNum; sipMsg.getLastVia(&viaAddress, &viaPortNum, &protocol); char numBuff[30]; sprintf(numBuff, "%d", viaPortNum); UtlString viaPort(numBuff); remoteHost = remoteAddress + ":" + viaPort; } } // transaction token: cseq,call-id,from-tag,to=tag int cseq; UtlString cseqMethod; sipMsg.getCSeqField(&cseq, &cseqMethod); char numBuf[20]; sprintf(numBuf, "%d", cseq); UtlString callId; sipMsg.getCallIdField(&callId); Url to; sipMsg.getToUrl(to); UtlString toTag; to.getFieldParameter("tag", toTag); Url from; sipMsg.getFromUrl(from); UtlString fromTag; from.getFieldParameter("tag", fromTag); transactionId = numBuf; transactionId.append(","); transactionId.append(callId); transactionId.append(","); transactionId.append(fromTag); transactionId.append(","); transactionId.append(toTag); // Write all the stuff out // Write out the node container start writeBranchNodeBegin(outputFileDescriptor); // Write out the branchId container start writeBranchSetBegin(outputFileDescriptor); // Write out the branchIds int viaIndex = 0; UtlString topVia; while(sipMsg.getViaField(&topVia, viaIndex)) { SipMessage::getViaTag(topVia.data(), "branch", branchId); writeBranchId(outputFileDescriptor, branchId); viaIndex++; } // Write out the branchId container finish writeBranchSetEnd(outputFileDescriptor); // Write out the rest of the node data writeBranchNodeData(outputFileDescriptor, date, isOutgoing ? hostname : remoteHost, isOutgoing ? remoteHost : hostname, isOutgoing ? hostname : remoteSourceAddress, isOutgoing ? remoteSourceAddress : hostname, transactionId, eventCount, method, responseCode, responseText, message); // Write out the node container finish writeBranchNodeEnd(outputFileDescriptor); } } void convertToXml(UtlString& bufferString, int outputFileDescriptor) { UtlString date; UtlString eventCount; UtlString facility; UtlString priority; UtlString hostname; UtlString taskname; UtlString taskId; UtlString processId; UtlString content; OsSysLog::parseLogString(bufferString.data(), date, eventCount, facility, priority, hostname, taskname, taskId, processId, content); if(facility.compareTo("OUTGOING") == 0) { hostname.append("-"); hostname.append(processId); getMessageData(content, TRUE, date, hostname, eventCount, outputFileDescriptor); } else if(facility.compareTo("INCOMING") == 0) { hostname.append("-"); hostname.append(processId); getMessageData(content, FALSE, date, hostname, eventCount, outputFileDescriptor); } } int main(int argc, char * argv[]) { int i; // Input file descriptor. Default is stdin. int ifd = 0; // Output file descriptor. Default is stdout. int ofd = 1; // Parse the arguments. for(i = 1; i < argc; i++) { if(!strcmp(argv[i], "-h")) { // If an argument is -h, print the usage message and exit. fprintf(stderr, "Usage:\n\t%s [-h] [if=input] [of=output]\n", argv[0]); return 0; } else if(!strncmp(argv[i], "if=", 3)) { // if= designates the input file. ifd = open(&argv[i][3], O_RDONLY); if(ifd == -1) { fprintf(stderr, "%s: %s\n", &argv[i][3], strerror(errno)); return 1; } } else if(!strncmp(argv[i], "of=", 3)) { // of= designates the output file. #ifdef _WIN32 ofd = open(&argv[i][3], O_BINARY | O_WRONLY | O_CREAT, 0644); #else /* No such thing as a "binary" file on POSIX */ ofd = open(&argv[i][3], O_WRONLY | O_CREAT, 0644); #endif if(ofd == -1) { fprintf(stderr, "%s: %s\n", &argv[i][3], strerror(errno)); return 1; } } else { // All other options are errors. fprintf(stderr, "Unknown option: %s\n", argv[i]); return 1; } } writeMessageNodesBegin(ofd); char inputBuffer[BUFFER_SIZE + 1]; UtlString bufferString; int lineLen; int nextLineStart; do { i = read(ifd, inputBuffer, BUFFER_SIZE); if(i > 0) { inputBuffer[i] = '\0'; bufferString.append(inputBuffer); } do { lineLen = NameValueTokenizer::findNextLineTerminator(bufferString.data(), bufferString.length(), &nextLineStart); // If a new line was found if(nextLineStart > 0) { UtlString line; line.append(bufferString, lineLen); bufferString.remove(0, nextLineStart); convertToXml(line, ofd); } } while(nextLineStart > 0); } while(i && i != -1); // Last line without a newline convertToXml(bufferString, ofd); writeMessageNodesEnd(ofd); close(ofd); return 0; } <|endoftext|>
<commit_before> /* This file is part of QJson * * Copyright (C) 2009 Flavio Castelli <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <limits> #include <QtTest/QtTest> #include "person.h" #include "qobjecthelper.h" #include <QtCore/QVariant> class TestQObjectHelper: public QObject { Q_OBJECT private slots: void testQObject2QVariant(); void testQVariant2QObject(); }; Q_DECLARE_METATYPE(QVariant) using namespace QJson; void TestQObjectHelper::testQObject2QVariant() { QString name = QLatin1String("Flavio Castelli"); int phoneNumber = 123456; Person::Gender gender = Person::Male; QDate dob (1982, 7, 12); Person person; person.setName(name); person.setPhoneNumber(phoneNumber); person.setGender(gender); person.setDob(dob); QVariantMap expected; expected[QLatin1String("name")] = QVariant(name); expected[QLatin1String("phoneNumber")] = QVariant(phoneNumber); expected[QLatin1String("gender")] = QVariant(gender); expected[QLatin1String("dob")] = QVariant(dob); QVariantMap result = QObjectHelper::qobject2qvariant(&person); QCOMPARE(result, expected); } void TestQObjectHelper::testQVariant2QObject() { QString name = QLatin1String("Flavio Castelli"); int phoneNumber = 123456; Person::Gender gender = Person::Male; QDate dob (1982, 7, 12); Person person; QVariantMap variant; variant[QLatin1String("name")] = QVariant(name); variant[QLatin1String("phoneNumber")] = QVariant(phoneNumber); variant[QLatin1String("gender")] = QVariant(gender); variant[QLatin1String("dob")] = QVariant(dob); QObjectHelper::qvariant2qobject(variant, &person); QCOMPARE(person.name(), name); QCOMPARE(person.phoneNumber(),phoneNumber); QCOMPARE(person.gender(), gender); QCOMPARE(person.dob(), dob); } QTEST_MAIN(TestQObjectHelper) #ifdef QMAKE_BUILD #include "testqobjecthelper.moc" #else #include "moc_testqobjecthelper.cxx" #endif <commit_msg>Eating our own dog food inside of the tests<commit_after> /* This file is part of QJson * * Copyright (C) 2009 Flavio Castelli <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <limits> #include <QtTest/QtTest> #include "person.h" #include "qobjecthelper.h" #include <QtCore/QVariant> class TestQObjectHelper: public QObject { Q_OBJECT private slots: void testQObject2QVariant(); void testQVariant2QObject(); }; using namespace QJson; void TestQObjectHelper::testQObject2QVariant() { QString name = QLatin1String("Flavio Castelli"); int phoneNumber = 123456; Person::Gender gender = Person::Male; QDate dob (1982, 7, 12); Person person; person.setName(name); person.setPhoneNumber(phoneNumber); person.setGender(gender); person.setDob(dob); QVariantMap expected; expected[QLatin1String("name")] = QVariant(name); expected[QLatin1String("phoneNumber")] = QVariant(phoneNumber); expected[QLatin1String("gender")] = QVariant(gender); expected[QLatin1String("dob")] = QVariant(dob); QVariantMap result = QObjectHelper::qobject2qvariant(&person); QCOMPARE(result, expected); } void TestQObjectHelper::testQVariant2QObject() { QString name = QLatin1String("Flavio Castelli"); int phoneNumber = 123456; Person::Gender gender = Person::Male; QDate dob (1982, 7, 12); Person person; QVariantMap variant = QObjectHelper::qobject2qvariant(&person); QObjectHelper::qvariant2qobject(variant, &person); QCOMPARE(person.name(), name); QCOMPARE(person.phoneNumber(),phoneNumber); QCOMPARE(person.gender(), gender); QCOMPARE(person.dob(), dob); } QTEST_MAIN(TestQObjectHelper) #ifdef QMAKE_BUILD #include "testqobjecthelper.moc" #else #include "moc_testqobjecthelper.cxx" #endif <|endoftext|>
<commit_before>/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "DataBrokerLoadReaction.h" #include "DataBrokerLoadDialog.h" #include "DataSource.h" #include "LoadDataReaction.h" #include "Utilities.h" #include <vtkImageData.h> #include <QMessageBox> namespace tomviz { DataBrokerLoadReaction::DataBrokerLoadReaction(QAction* parentObject) : pqReaction(parentObject) { } DataBrokerLoadReaction::~DataBrokerLoadReaction() = default; void DataBrokerLoadReaction::onTriggered() { loadData(); } void DataBrokerLoadReaction::loadData() { auto dataBroker = new DataBroker(tomviz::mainWidget()); DataBrokerLoadDialog dialog(dataBroker, tomviz::mainWidget()); if (dialog.exec() == QDialog::Accepted) { auto catalog = dialog.selectedCatalog(); auto runUid = dialog.selectedRunUid(); auto table = dialog.selectedTable(); auto variable = dialog.selectedVariable(); tomviz::mainWidget()->setCursor(Qt::WaitCursor); auto call = dataBroker->loadVariable(catalog, runUid, table, variable); connect(call, &LoadDataCall::complete, dataBroker, [dataBroker, catalog, runUid, table, variable](vtkSmartPointer<vtkImageData> imageData) { // relable axes first relabelXAndZAxes(imageData); auto dataSource = new DataSource(imageData, DataSource::TiltSeries); dataSource->setLabel(QString("db:///%1/%2/%3/%4") .arg(catalog) .arg(runUid) .arg(table) .arg(variable)); LoadDataReaction::dataSourceAdded(dataSource, true, false); dataBroker->deleteLater(); tomviz::mainWidget()->unsetCursor(); }); connect(call, &DataBrokerCall::error, dataBroker, [dataBroker](const QString& errorMessage) { tomviz::mainWidget()->unsetCursor(); dataBroker->deleteLater(); QMessageBox messageBox( QMessageBox::Warning, "tomviz", QString("Error loading DataBroker dataset: %1. Please check " "message log for details.") .arg(errorMessage), QMessageBox::Ok); messageBox.exec(); }); } } } // namespace tomviz <commit_msg>Reorder the data and then relabel X and Z<commit_after>/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "DataBrokerLoadReaction.h" #include "DataBrokerLoadDialog.h" #include "DataSource.h" #include "LoadDataReaction.h" #include "Utilities.h" #include "GenericHDF5Format.h" #include <vtkImageData.h> #include <QMessageBox> namespace tomviz { DataBrokerLoadReaction::DataBrokerLoadReaction(QAction* parentObject) : pqReaction(parentObject) { } DataBrokerLoadReaction::~DataBrokerLoadReaction() = default; void DataBrokerLoadReaction::onTriggered() { loadData(); } void DataBrokerLoadReaction::loadData() { auto dataBroker = new DataBroker(tomviz::mainWidget()); DataBrokerLoadDialog dialog(dataBroker, tomviz::mainWidget()); if (dialog.exec() == QDialog::Accepted) { auto catalog = dialog.selectedCatalog(); auto runUid = dialog.selectedRunUid(); auto table = dialog.selectedTable(); auto variable = dialog.selectedVariable(); tomviz::mainWidget()->setCursor(Qt::WaitCursor); auto call = dataBroker->loadVariable(catalog, runUid, table, variable); connect(call, &LoadDataCall::complete, dataBroker, [dataBroker, catalog, runUid, table, variable](vtkSmartPointer<vtkImageData> imageData) { // Relabel axes first, short-term workaround reorder to C (again). GenericHDF5Format::reorderData(imageData, ReorderMode::FortranToC); relabelXAndZAxes(imageData); auto dataSource = new DataSource(imageData, DataSource::TiltSeries); dataSource->setLabel(QString("db:///%1/%2/%3/%4") .arg(catalog) .arg(runUid) .arg(table) .arg(variable)); LoadDataReaction::dataSourceAdded(dataSource, true, false); dataBroker->deleteLater(); tomviz::mainWidget()->unsetCursor(); }); connect(call, &DataBrokerCall::error, dataBroker, [dataBroker](const QString& errorMessage) { tomviz::mainWidget()->unsetCursor(); dataBroker->deleteLater(); QMessageBox messageBox( QMessageBox::Warning, "tomviz", QString("Error loading DataBroker dataset: %1. Please check " "message log for details.") .arg(errorMessage), QMessageBox::Ok); messageBox.exec(); }); } } } // namespace tomviz <|endoftext|>
<commit_before>#include <StdInc.h> #include "SparrowNodes.h" #include "SparrowNodesAccessors.h" #include <SprDebug.h> #include <Helpers/DeclsHelpers.h> #include <Helpers/QualifiedId.h> #include "Nest/Api/SourceCode.h" #include "Nest/Utils/NodeUtils.hpp" using namespace SprFrontend; using namespace Nest; SourceCode* g_implicitLibSC = nullptr; /// Given a module node, infer the the module name from the source code URL StringRef inferModuleName(Node* node) { ASSERT(node->location.sourceCode); ASSERT(node->location.sourceCode->url); const char* url = node->location.sourceCode->url; // Remove the path part const char* p = strrchr(url, '/'); if ( !p ) p = strrchr(url, '\\'); if ( p ) url = p+1; // Remove the extension part p = strchr(url, '.'); // Create a StringRef out of the selected part StringRef id = { url, p ? p : url + strlen(url) }; return id; } namespace { /** * Create a structure of nested packages corresponding to the given QID * * Does not check to reuse any of the existing package. The assumption is * that there is nothing created yet. * * We use this to create the packages for the module. * * qid needs to have at least one element. * * @param qid The list of names for the packages * @param accessType The access type to be used for creating the packages * @param [out] innerPackage The inner most package created * * @return The inner most package created/reused */ Node* createPackagesFromQid(const QidVec& qid, AccessType accessType, Node*& innerPackage) { innerPackage = nullptr; Node* pkg = nullptr; // Create the packages bottom-up for ( int i = int(qid.size())-1; i>=0; i-- ) { const auto& id = qid[i]; NodeRange children = pkg ? fromIniList({ pkg }) : fromIniList({}); Node* pkgContent = Feather_mkNodeListVoid(id.second, children); pkg = mkSprPackage(id.second, id.first, pkgContent, accessType); if ( !innerPackage ) innerPackage = pkg; } return pkg; } /** * Structure describing info about a package into a hierarchy of packages. * * Instead of holding pointers to the actual package nodes, we will hold * pointers to the content of the packages (their internal node-list). * * The top-level package will contain a null parent and an empty name. */ struct PackageDesc { Node* parent; //!< The parent package content node StringRef name; //!< The name of the package Node* content; //!< The node that holds the content of the package (node-list) }; /// Descriptions to the packages we've encountered /// The first entry will represent the top-level package typedef vector<PackageDesc> Packages; /** * Find or create a package node * * This makes sure that we don't create the same package multiple times. It * records each package that we've created, so that we can reuse them. * * If a package is not found, we create it here. * This will also create the content of the package, a node-list. * * We have a relatively small number of packages, so linear operations sound * good for our purpose. * * @param packages The list of existing packages * @param parent The package content that contains the requested package * @param name The name of the package to be found/created * @param loc The location to be used for this package * @param accessType The access type for the package * * @return The content node of the required package */ Node* findOrCreatePackage(Packages& packages, Node* parent, StringRef name, Location loc, AccessType accessType) { // Try to find the package to create for ( auto& pk : packages ) { if ( pk.parent == parent && pk.name == name ) return pk.content; // Package already exiting } // Create a new package (and add it to the parent) Node* pkgContent = Feather_mkNodeListVoid(loc, fromIniList({})); Node* pkg = mkSprPackage(loc, name, pkgContent, accessType); ASSERT(parent); Feather_addToNodeList(parent, pkg); // Add a new entry to our list of packages descriptions packages.emplace_back(PackageDesc{parent, name, pkgContent}); return pkgContent; } /** * Create/reuse a structure of nested packages corresponding to the given QID * * If qid is empty, then this will return the node-list in which all the packages are placed * * @param qid The list of names for the packages * @param loc The location to be used for creating the packages * @param accessType The access type to be used for creating the packages * @param packages The list of existing packages to be used/updated * * @return The content node (node-list) of the inner most package created/reused */ Node* createReusePackages(const QidVec& qid, Location loc, AccessType accessType, Packages& packages) { // Start searching from the first package Node* pkgContent = packages[0].content; // Create or reuse package top-down for ( const auto& id : qid ) { pkgContent = findOrCreatePackage(packages, pkgContent, id.first, loc, accessType); } return pkgContent; } /// Given an import module name, add the corresponding source code to the compiler /// Returns the created SourceCode object SourceCode* addImportedSourceCode(const SourceCode* curSourceCode, Node* moduleName) { ASSERT(moduleName); SourceCode* importedSc; if ( moduleName->nodeKind == nkSparrowExpLiteral ) { if ( !Literal_isString(moduleName) ) REP_INTERNAL(moduleName->location, "Invalid import name found %1%") % Nest_toStringEx(moduleName); importedSc = Nest_addSourceCodeByFilename(curSourceCode, Literal_getData(moduleName)); } else { QidVec qid; interpretQualifiedId(moduleName, qid); if ( qid.empty() ) REP_INTERNAL(moduleName->location, "Nothing to import"); // Transform qid into filename/dirname string filename; for ( const auto& part: qid ) { if ( !filename.empty() ) filename += "/"; filename += toString(part.first); } importedSc = Nest_addSourceCodeByFilename(curSourceCode, fromString(filename + ".spr")); } if ( !importedSc ) REP_INTERNAL(moduleName->location, "Cannot import %1%") % moduleName; return importedSc; } /** * Adds the code supporting an import to the current source code. * * @param curSourceCode The source code of the current module * @param packages [in/out] The list of packages to be created for the current module * @param importLoc The location from which this import is added (into the current source code) * @param importedSc The source code to be imported * @param declNames Node list of identifiers describing the decls to be imported * @param equals True if this is an equals import (e.g., renamed import) * @param alias The alias passed to the import (maybe empty) * @param accessType The access type to be used for the import */ void addImportCode(const SourceCode* curSourceCode, Packages& packages, Location importLoc, const SourceCode* importedSc, Node* declNames, bool equals, StringRef alias, AccessType accessType = unspecifiedAccess) { // By default imports are private if ( accessType == unspecifiedAccess ) accessType = privateAccess; // Reference to the content of the module we are importing Node* refImpContent = nullptr; if ( importedSc->mainNode->nodeKind != nkSparrowDeclModule ) { if ( size(alias) > 0 ) REP_ERROR(importLoc, "Cannot use import with alias for non Sparrow files"); if ( equals ) REP_ERROR(importLoc, "Cannot use equal import for non Sparrow files"); if ( declNames && size(declNames->children) > 0 ) REP_ERROR(importLoc, "Cannot use selective import for non Sparrow files"); return; } else { refImpContent = mkModuleRef(importLoc, importedSc->mainNode); } // Get the QID used to refer the module equals = true; // TODO(modules): Change this QidVec refQid; if ( equals ) { // The given alias is the QID used to access the imported module if ( size(alias) > 0 ) refQid.emplace_back(make_pair(alias, importLoc)); // If no 'alias' is given, refQid will be empty, and no extra package will be created for the import } else { // The QID is the name of the imported module Node* impModName = nullptr; Node* impMainNode = importedSc->mainNode; if ( impMainNode && impMainNode->nodeKind == nkSparrowDeclModule ) { impModName = at(impMainNode->children, 0); } if ( impModName ) { interpretQualifiedId(impModName, refQid); } else { StringRef inferredName = inferModuleName(impMainNode); refQid.emplace_back(make_pair(inferredName, importLoc)); } if ( refQid.empty() ) { Location loc = impModName ? impModName->location : Nest_mkLocation1(importedSc, 1, 1); REP_INTERNAL(loc, "Invalid qualified ID for module name (%1%)") % Nest_toStringEx(impModName); } } // Drop the end name in the classic (non-equals) case: 'using foo.bar' pair<StringRef, Location> lastId; if ( !declNames && !equals ) { ASSERT(!refQid.empty()); lastId = refQid.back(); refQid.pop_back(); } // Create the required packages Node* pkgContent = createReusePackages(refQid, importLoc, accessType, packages); // The using(s) that we need to add if ( declNames ) { if ( declNames->nodeKind != nkFeatherNodeList ) REP_INTERNAL(declNames->location, "Expected node list, found %1%") % Nest_nodeKindName(declNames); // For something like: // import foo.bar(f, g); // we create something like: // package foo { package bar { // using f = <foobarContentRef>.f; // using g = <foobarContentRef>.g; // }} for ( Node* id : all(declNames->children) ) { StringRef name = Feather_getName(id); Node* cid = mkCompoundExp(id->location, refImpContent, name); Feather_addToNodeList(pkgContent, mkSprUsing(id->location, name, cid, accessType)); } } else if ( !equals ) { // For something like: // import foo.bar; // we create something like: // package foo { // using bar = <foobarContentRef>; // } // Create a using towards the imported module name, using the last // name from the QID Feather_addToNodeList(pkgContent, mkSprUsing(lastId.second, lastId.first, refImpContent, accessType)); } else { // For something like: // import =foo.bar; // we create something like: // using<foobarContentRef>.*; Node* starExp = mkStarExp(importLoc, refImpContent, fromCStr("*")); Feather_addToNodeList(pkgContent, mkSprUsing(importLoc, StringRef({0,0}), starExp, accessType)); } } /** * Handle an import; add the new source code; add the code corresponding to current source code * * @param curSourceCode The source code of the current module * @param packages [in/out] The list of packages to be created for the current module * @param importName The import name describing what to import */ void handleImport(const SourceCode* curSourceCode, Packages& packages, Node* importName) { if ( importName->nodeKind != nkSparrowDeclImportName ) { Nest_reportFmt(importName->location, diagInternalError, "Expected spr.importName node; found %s", Nest_nodeKindName(importName)); return; } Node* moduleName = at(importName->children, 0); Node* declNames = at(importName->children, 1); bool equals = 0 != Feather_hasName(importName); StringRef alias = equals ? Feather_getName(importName) : StringRef({0, 0}); AccessType accessType = getAccessType(importName); // Add the new source code to the compiler SourceCode* importedSc = addImportedSourceCode(curSourceCode, moduleName); // Now actually handle the import in the current source code addImportCode(curSourceCode, packages, moduleName->location, importedSc, declNames, equals, alias, accessType); } void handleImplicitImport(const SourceCode* curSourceCode, Packages& packages) { if ( g_implicitLibSC ) { Location impModuleLoc = Nest_mkLocation1(curSourceCode, 1, 1); addImportCode(curSourceCode, packages, impModuleLoc, g_implicitLibSC, nullptr, true, StringRef{0, 0}); } } /** * Given a module node, this will generate the appropriate code for it * * It will first create the top-level packages corresponding to the module * name. Then it will check the imports of the module and expand them into * the appropriate content * * @param node The node describing the module * * @return The node that the module will expand to */ Node* expandModule(Node* node) { ASSERT(Nest_nodeArraySize(node->children) == 3); Node* moduleName = at(node->children, 0); Node* imports = at(node->children, 1); Node* declarations = at(node->children, 2); Location modLoc; // Get the QID representing the module // If we don't have a module name, infer it from the name of the file QidVec moduleNameQid; if ( moduleName ) { modLoc = moduleName->location; interpretQualifiedId(moduleName, moduleNameQid); } else { modLoc = Nest_mkLocation1(node->location.sourceCode, 1, 1); StringRef name = inferModuleName(node); moduleNameQid.emplace_back(make_pair(name, modLoc)); } if ( moduleNameQid.empty() || size(moduleNameQid.back().first) == 0 ) REP_INTERNAL(modLoc, "Invalid module name"); // Create the packages corresponding to the module name Node* innerMostPackage = nullptr; Node* outerContent = createPackagesFromQid(moduleNameQid, publicAccess, innerMostPackage); CHECK(modLoc, outerContent); CHECK(modLoc, innerMostPackage); // The inner content, without any packages -- a node list Node* innerContent = at(innerMostPackage->children, 0); // Handle imports if ( imports || g_implicitLibSC ) { // The packages that we want to import // Add one entry to indicate the top-level without any package Packages packages; packages.emplace_back(PackageDesc{nullptr, fromCStr(""), innerContent}); // Add the implicit import handleImplicitImport(node->location.sourceCode, packages); // Accumulate everything that we need to add if ( imports ) { for ( Node* i: imports->children ) handleImport(node->location.sourceCode, packages, i); } } // Add the declarations to the inner content // We do this after adding imports code Feather_addToNodeList(innerContent, declarations); // The resulting decl is the inner most package created for this module Nest_setPropertyNode(node, propResultingDecl, innerMostPackage); // We already know the explanation of this node Nest_setPropertyNode(node, "spr.moduleOuterContent", outerContent); return outerContent; } } void Module_SetContextForChildren(Node* node) { // Expand the module node Node* outerContent = expandModule(node); // Create a children context, and set it to the explanation of the module // This will create a symtab that it's independent of what we have so far CompilationContext* ctx = Nest_mkChildContextWithSymTab(node->context, node, modeUnspecified); Nest_setContext(outerContent, ctx); } Node* Module_SemanticCheck(Node* node) { node->type = Feather_getVoidType(modeCt); Node* content = Nest_getCheckPropertyNode(node, "spr.moduleOuterContent"); return content; } <commit_msg>Fix invalid mem access that made tests fail on Linux<commit_after>#include <StdInc.h> #include "SparrowNodes.h" #include "SparrowNodesAccessors.h" #include <SprDebug.h> #include <Helpers/DeclsHelpers.h> #include <Helpers/QualifiedId.h> #include "Nest/Api/SourceCode.h" #include "Nest/Utils/NodeUtils.hpp" using namespace SprFrontend; using namespace Nest; SourceCode* g_implicitLibSC = nullptr; /// Given a module node, infer the the module name from the source code URL StringRef inferModuleName(Node* node) { ASSERT(node->location.sourceCode); ASSERT(node->location.sourceCode->url); const char* url = node->location.sourceCode->url; // Remove the path part const char* p = strrchr(url, '/'); if ( !p ) p = strrchr(url, '\\'); if ( p ) url = p+1; // Remove the extension part p = strchr(url, '.'); // Create a StringRef out of the selected part StringRef id = { url, p ? p : url + strlen(url) }; return id; } namespace { /** * Create a structure of nested packages corresponding to the given QID * * Does not check to reuse any of the existing package. The assumption is * that there is nothing created yet. * * We use this to create the packages for the module. * * qid needs to have at least one element. * * @param qid The list of names for the packages * @param accessType The access type to be used for creating the packages * @param [out] innerPackage The inner most package created * * @return The inner most package created/reused */ Node* createPackagesFromQid(const QidVec& qid, AccessType accessType, Node*& innerPackage) { innerPackage = nullptr; Node* pkg = nullptr; // Create the packages bottom-up for ( int i = int(qid.size())-1; i>=0; i-- ) { const auto& id = qid[i]; Node* pkgContent = Feather_mkNodeListVoid(id.second, pkg ? fromIniList({ pkg }) : fromIniList({})); pkg = mkSprPackage(id.second, id.first, pkgContent, accessType); if ( !innerPackage ) innerPackage = pkg; } return pkg; } /** * Structure describing info about a package into a hierarchy of packages. * * Instead of holding pointers to the actual package nodes, we will hold * pointers to the content of the packages (their internal node-list). * * The top-level package will contain a null parent and an empty name. */ struct PackageDesc { Node* parent; //!< The parent package content node StringRef name; //!< The name of the package Node* content; //!< The node that holds the content of the package (node-list) }; /// Descriptions to the packages we've encountered /// The first entry will represent the top-level package typedef vector<PackageDesc> Packages; /** * Find or create a package node * * This makes sure that we don't create the same package multiple times. It * records each package that we've created, so that we can reuse them. * * If a package is not found, we create it here. * This will also create the content of the package, a node-list. * * We have a relatively small number of packages, so linear operations sound * good for our purpose. * * @param packages The list of existing packages * @param parent The package content that contains the requested package * @param name The name of the package to be found/created * @param loc The location to be used for this package * @param accessType The access type for the package * * @return The content node of the required package */ Node* findOrCreatePackage(Packages& packages, Node* parent, StringRef name, Location loc, AccessType accessType) { // Try to find the package to create for ( auto& pk : packages ) { if ( pk.parent == parent && pk.name == name ) return pk.content; // Package already exiting } // Create a new package (and add it to the parent) Node* pkgContent = Feather_mkNodeListVoid(loc, fromIniList({})); Node* pkg = mkSprPackage(loc, name, pkgContent, accessType); ASSERT(parent); Feather_addToNodeList(parent, pkg); // Add a new entry to our list of packages descriptions packages.emplace_back(PackageDesc{parent, name, pkgContent}); return pkgContent; } /** * Create/reuse a structure of nested packages corresponding to the given QID * * If qid is empty, then this will return the node-list in which all the packages are placed * * @param qid The list of names for the packages * @param loc The location to be used for creating the packages * @param accessType The access type to be used for creating the packages * @param packages The list of existing packages to be used/updated * * @return The content node (node-list) of the inner most package created/reused */ Node* createReusePackages(const QidVec& qid, Location loc, AccessType accessType, Packages& packages) { // Start searching from the first package Node* pkgContent = packages[0].content; // Create or reuse package top-down for ( const auto& id : qid ) { pkgContent = findOrCreatePackage(packages, pkgContent, id.first, loc, accessType); } return pkgContent; } /// Given an import module name, add the corresponding source code to the compiler /// Returns the created SourceCode object SourceCode* addImportedSourceCode(const SourceCode* curSourceCode, Node* moduleName) { ASSERT(moduleName); SourceCode* importedSc; if ( moduleName->nodeKind == nkSparrowExpLiteral ) { if ( !Literal_isString(moduleName) ) REP_INTERNAL(moduleName->location, "Invalid import name found %1%") % Nest_toStringEx(moduleName); importedSc = Nest_addSourceCodeByFilename(curSourceCode, Literal_getData(moduleName)); } else { QidVec qid; interpretQualifiedId(moduleName, qid); if ( qid.empty() ) REP_INTERNAL(moduleName->location, "Nothing to import"); // Transform qid into filename/dirname string filename; for ( const auto& part: qid ) { if ( !filename.empty() ) filename += "/"; filename += toString(part.first); } importedSc = Nest_addSourceCodeByFilename(curSourceCode, fromString(filename + ".spr")); } if ( !importedSc ) REP_INTERNAL(moduleName->location, "Cannot import %1%") % moduleName; return importedSc; } /** * Adds the code supporting an import to the current source code. * * @param curSourceCode The source code of the current module * @param packages [in/out] The list of packages to be created for the current module * @param importLoc The location from which this import is added (into the current source code) * @param importedSc The source code to be imported * @param declNames Node list of identifiers describing the decls to be imported * @param equals True if this is an equals import (e.g., renamed import) * @param alias The alias passed to the import (maybe empty) * @param accessType The access type to be used for the import */ void addImportCode(const SourceCode* curSourceCode, Packages& packages, Location importLoc, const SourceCode* importedSc, Node* declNames, bool equals, StringRef alias, AccessType accessType = unspecifiedAccess) { // By default imports are private if ( accessType == unspecifiedAccess ) accessType = privateAccess; // Reference to the content of the module we are importing Node* refImpContent = nullptr; if ( importedSc->mainNode->nodeKind != nkSparrowDeclModule ) { if ( size(alias) > 0 ) REP_ERROR(importLoc, "Cannot use import with alias for non Sparrow files"); if ( equals ) REP_ERROR(importLoc, "Cannot use equal import for non Sparrow files"); if ( declNames && size(declNames->children) > 0 ) REP_ERROR(importLoc, "Cannot use selective import for non Sparrow files"); return; } else { refImpContent = mkModuleRef(importLoc, importedSc->mainNode); } // Get the QID used to refer the module equals = true; // TODO(modules): Change this QidVec refQid; if ( equals ) { // The given alias is the QID used to access the imported module if ( size(alias) > 0 ) refQid.emplace_back(make_pair(alias, importLoc)); // If no 'alias' is given, refQid will be empty, and no extra package will be created for the import } else { // The QID is the name of the imported module Node* impModName = nullptr; Node* impMainNode = importedSc->mainNode; if ( impMainNode && impMainNode->nodeKind == nkSparrowDeclModule ) { impModName = at(impMainNode->children, 0); } if ( impModName ) { interpretQualifiedId(impModName, refQid); } else { StringRef inferredName = inferModuleName(impMainNode); refQid.emplace_back(make_pair(inferredName, importLoc)); } if ( refQid.empty() ) { Location loc = impModName ? impModName->location : Nest_mkLocation1(importedSc, 1, 1); REP_INTERNAL(loc, "Invalid qualified ID for module name (%1%)") % Nest_toStringEx(impModName); } } // Drop the end name in the classic (non-equals) case: 'using foo.bar' pair<StringRef, Location> lastId; if ( !declNames && !equals ) { ASSERT(!refQid.empty()); lastId = refQid.back(); refQid.pop_back(); } // Create the required packages Node* pkgContent = createReusePackages(refQid, importLoc, accessType, packages); // The using(s) that we need to add if ( declNames ) { if ( declNames->nodeKind != nkFeatherNodeList ) REP_INTERNAL(declNames->location, "Expected node list, found %1%") % Nest_nodeKindName(declNames); // For something like: // import foo.bar(f, g); // we create something like: // package foo { package bar { // using f = <foobarContentRef>.f; // using g = <foobarContentRef>.g; // }} for ( Node* id : all(declNames->children) ) { StringRef name = Feather_getName(id); Node* cid = mkCompoundExp(id->location, refImpContent, name); Feather_addToNodeList(pkgContent, mkSprUsing(id->location, name, cid, accessType)); } } else if ( !equals ) { // For something like: // import foo.bar; // we create something like: // package foo { // using bar = <foobarContentRef>; // } // Create a using towards the imported module name, using the last // name from the QID Feather_addToNodeList(pkgContent, mkSprUsing(lastId.second, lastId.first, refImpContent, accessType)); } else { // For something like: // import =foo.bar; // we create something like: // using<foobarContentRef>.*; Node* starExp = mkStarExp(importLoc, refImpContent, fromCStr("*")); Feather_addToNodeList(pkgContent, mkSprUsing(importLoc, StringRef({0,0}), starExp, accessType)); } } /** * Handle an import; add the new source code; add the code corresponding to current source code * * @param curSourceCode The source code of the current module * @param packages [in/out] The list of packages to be created for the current module * @param importName The import name describing what to import */ void handleImport(const SourceCode* curSourceCode, Packages& packages, Node* importName) { if ( importName->nodeKind != nkSparrowDeclImportName ) { Nest_reportFmt(importName->location, diagInternalError, "Expected spr.importName node; found %s", Nest_nodeKindName(importName)); return; } Node* moduleName = at(importName->children, 0); Node* declNames = at(importName->children, 1); bool equals = 0 != Feather_hasName(importName); StringRef alias = equals ? Feather_getName(importName) : StringRef({0, 0}); AccessType accessType = getAccessType(importName); // Add the new source code to the compiler SourceCode* importedSc = addImportedSourceCode(curSourceCode, moduleName); // Now actually handle the import in the current source code addImportCode(curSourceCode, packages, moduleName->location, importedSc, declNames, equals, alias, accessType); } void handleImplicitImport(const SourceCode* curSourceCode, Packages& packages) { if ( g_implicitLibSC ) { Location impModuleLoc = Nest_mkLocation1(curSourceCode, 1, 1); addImportCode(curSourceCode, packages, impModuleLoc, g_implicitLibSC, nullptr, true, StringRef{0, 0}); } } /** * Given a module node, this will generate the appropriate code for it * * It will first create the top-level packages corresponding to the module * name. Then it will check the imports of the module and expand them into * the appropriate content * * @param node The node describing the module * * @return The node that the module will expand to */ Node* expandModule(Node* node) { ASSERT(Nest_nodeArraySize(node->children) == 3); Node* moduleName = at(node->children, 0); Node* imports = at(node->children, 1); Node* declarations = at(node->children, 2); Location modLoc; // Get the QID representing the module // If we don't have a module name, infer it from the name of the file QidVec moduleNameQid; if ( moduleName ) { modLoc = moduleName->location; interpretQualifiedId(moduleName, moduleNameQid); } else { modLoc = Nest_mkLocation1(node->location.sourceCode, 1, 1); StringRef name = inferModuleName(node); moduleNameQid.emplace_back(make_pair(name, modLoc)); } if ( moduleNameQid.empty() || size(moduleNameQid.back().first) == 0 ) REP_INTERNAL(modLoc, "Invalid module name"); // Create the packages corresponding to the module name Node* innerMostPackage = nullptr; Node* outerContent = createPackagesFromQid(moduleNameQid, publicAccess, innerMostPackage); CHECK(modLoc, outerContent); CHECK(modLoc, innerMostPackage); // The inner content, without any packages -- a node list Node* innerContent = at(innerMostPackage->children, 0); // Handle imports if ( imports || g_implicitLibSC ) { // The packages that we want to import // Add one entry to indicate the top-level without any package Packages packages; packages.emplace_back(PackageDesc{nullptr, fromCStr(""), innerContent}); // Add the implicit import handleImplicitImport(node->location.sourceCode, packages); // Accumulate everything that we need to add if ( imports ) { for ( Node* i: imports->children ) handleImport(node->location.sourceCode, packages, i); } } // Add the declarations to the inner content // We do this after adding imports code Feather_addToNodeList(innerContent, declarations); // The resulting decl is the inner most package created for this module Nest_setPropertyNode(node, propResultingDecl, innerMostPackage); // We already know the explanation of this node Nest_setPropertyNode(node, "spr.moduleOuterContent", outerContent); return outerContent; } } void Module_SetContextForChildren(Node* node) { // Expand the module node Node* outerContent = expandModule(node); // Create a children context, and set it to the explanation of the module // This will create a symtab that it's independent of what we have so far CompilationContext* ctx = Nest_mkChildContextWithSymTab(node->context, node, modeUnspecified); Nest_setContext(outerContent, ctx); } Node* Module_SemanticCheck(Node* node) { node->type = Feather_getVoidType(modeCt); Node* content = Nest_getCheckPropertyNode(node, "spr.moduleOuterContent"); return content; } <|endoftext|>
<commit_before>#include "LBP.h" LBP::LBP(unsigned int windowHeight, unsigned int windowWidth, unsigned int numberOfChannels, unsigned int *radius, unsigned int *samples, unsigned int numberOfRadiusSamplesCombinations) { unsigned int descriptorLengthPerWindow = numberOfRadiusSamplesCombinations * numberOfChannels; this->radius = radius; this->samples = samples; this->numberOfRadiusSamplesCombinations = numberOfRadiusSamplesCombinations; this->descriptorLengthPerWindow = descriptorLengthPerWindow; this->windowHeight = windowHeight; this->windowWidth = windowWidth; this->numberOfChannels = numberOfChannels; } LBP::~LBP() { } void LBP::apply(double *windowImage, double *descriptorVector) { LBPdescriptor(windowImage, this->radius, this->samples, this->numberOfRadiusSamplesCombinations, this->windowHeight, this->windowWidth, this->numberOfChannels, descriptorVector); } void LBPdescriptor(double *inputImage, unsigned int *radius, unsigned int *samples, unsigned int numberOfRadiusSamplesCombinations, unsigned int imageHeight, unsigned int imageWidth, unsigned int numberOfChannels, double *descriptorVector) { unsigned int i, s, ch; int centre_y, centre_x, rx, ry; double angle_step, min_x, max_x, min_y, max_y, block_size_x, block_size_y, sample_x, sample_y, centre_val, sample_val; double *samples_coords_x; double *samples_coords_y; // bool flag; double tx, ty, w1, w2, w3, w4; int lbp_code; for (i=0; i<numberOfRadiusSamplesCombinations; i++) { // find coordinates of sampling points with the axes origin (0,0) on the window centre samples_coords_x = new double[samples[i]]; samples_coords_y = new double[samples[i]]; angle_step = 2*PI/samples[i]; for (s=0; s<samples[i]; s++) { samples_coords_x[s] = radius[i] * cos(s * angle_step); samples_coords_y[s] = - (radius[i] * sin(s * angle_step)); } // find max and min coordinates of sampling points with the axes origin (0,0) on the window centre min_x = samples_coords_x[0]; max_x = samples_coords_x[0]; min_y = samples_coords_y[0]; max_y = samples_coords_y[0]; for (s=1; s<samples[i]; s++) { if (samples_coords_x[s] < min_x) min_x = samples_coords_x[s]; if (samples_coords_x[s] > max_x) max_x = samples_coords_x[s]; if (samples_coords_y[s] < min_y) min_y = samples_coords_y[s]; if (samples_coords_y[s] > max_y) max_y = samples_coords_y[s]; } // find coordinates of the window centre in the window reference frame (axes origin in bottom left corner) centre_y = (int)-floor(min(min_y,0.0)); centre_x = (int)-floor(min(min_x,0.0)); // find block size block_size_x = ceil(max(max_x,0.0)) - floor(min(min_x,0.0)) + 1; block_size_y = ceil(max(max_y,0.0)) - floor(min(min_y,0.0)) + 1; // for each channel, compute the lbp code for (ch=0; ch<numberOfChannels; ch++) { lbp_code = 0; for (s=0; s<samples[i]; s++) { // coordinates of sampling point in the window reference frame (axes origin in bottom left corner) sample_x = centre_x + samples_coords_x[s]; sample_y = centre_y + samples_coords_y[s]; // value of centre centre_val = inputImage[centre_y + centre_x*imageHeight + ch*imageHeight*imageWidth]; // check if interpolation is needed rx = (int)round(sample_x); ry = (int)round(sample_y); if ( (fabs(sample_x - rx) < small_val) && (fabs(sample_y - ry) < small_val) ) sample_val = inputImage[ry + rx*imageHeight + ch*imageHeight*imageWidth]; else { tx = sample_x - floor(sample_x); ty = sample_y - floor(sample_y); w1 = roundn((1 - tx) * (1 - ty), -6); w2 = roundn(tx * (1 - ty), -6); w3 = roundn((1 - tx) * ty, -6); // w4 = roundn(tx * ty, -6); w4 = roundn(1 - w1 - w2 - w3, -6); sample_val = inputImage[ry + rx*imageHeight + ch*imageHeight*imageWidth]; } // update the lbp code if (sample_val >= centre_val) lbp_code = lbp_code + 2^s; } descriptorVector[i + ch*numberOfRadiusSamplesCombinations] = lbp_code; } } // Empty memory delete [] samples_coords_x; delete [] samples_coords_y; } double roundn(double x, int n) { double p; if (n < 0) { p = 10 ^ -n; x = round(p * x) / p; } else if (n > 0) { p = 10 ^ n; x = p * round(x / p); } else x = round(x); return x; } <commit_msg>adds interpolation to lbp<commit_after>#include "LBP.h" LBP::LBP(unsigned int windowHeight, unsigned int windowWidth, unsigned int numberOfChannels, unsigned int *radius, unsigned int *samples, unsigned int numberOfRadiusSamplesCombinations) { unsigned int descriptorLengthPerWindow = numberOfRadiusSamplesCombinations * numberOfChannels; this->radius = radius; this->samples = samples; this->numberOfRadiusSamplesCombinations = numberOfRadiusSamplesCombinations; this->descriptorLengthPerWindow = descriptorLengthPerWindow; this->windowHeight = windowHeight; this->windowWidth = windowWidth; this->numberOfChannels = numberOfChannels; } LBP::~LBP() { } void LBP::apply(double *windowImage, double *descriptorVector) { LBPdescriptor(windowImage, this->radius, this->samples, this->numberOfRadiusSamplesCombinations, this->windowHeight, this->windowWidth, this->numberOfChannels, descriptorVector); } void LBPdescriptor(double *inputImage, unsigned int *radius, unsigned int *samples, unsigned int numberOfRadiusSamplesCombinations, unsigned int imageHeight, unsigned int imageWidth, unsigned int numberOfChannels, double *descriptorVector) { unsigned int i, s, ch; int centre_y, centre_x, rx, ry, fx, fy, cx, cy; double angle_step, min_x, min_y, sample_x, sample_y, centre_val, sample_val; double *samples_coords_x; double *samples_coords_y; double tx, ty, w1, w2, w3, w4; int lbp_code; for (i=0; i<numberOfRadiusSamplesCombinations; i++) { // find coordinates of sampling points with the axes origin (0,0) on the window centre samples_coords_x = new double[samples[i]]; samples_coords_y = new double[samples[i]]; angle_step = 2*PI/samples[i]; for (s=0; s<samples[i]; s++) { samples_coords_x[s] = radius[i] * cos(s * angle_step); samples_coords_y[s] = - (radius[i] * sin(s * angle_step)); } // find min coordinates of sampling points with the axes origin (0,0) on the window centre min_x = samples_coords_x[0]; min_y = samples_coords_y[0]; for (s=1; s<samples[i]; s++) { if (samples_coords_x[s] < min_x) min_x = samples_coords_x[s]; if (samples_coords_y[s] < min_y) min_y = samples_coords_y[s]; } // find coordinates of the window centre in the window reference frame (axes origin in bottom left corner) centre_y = (int)-floor(min(min_y,0.0)); centre_x = (int)-floor(min(min_x,0.0)); // value of centre centre_val = inputImage[centre_y + centre_x*imageHeight + ch*imageHeight*imageWidth]; // for each channel, compute the lbp code for (ch=0; ch<numberOfChannels; ch++) { lbp_code = 0; for (s=0; s<samples[i]; s++) { // coordinates of sampling point in the window reference frame (axes origin in bottom left corner) sample_x = centre_x + samples_coords_x[s]; sample_y = centre_y + samples_coords_y[s]; // check if interpolation is needed rx = (int)round(sample_x); ry = (int)round(sample_y); if ( (fabs(sample_x - rx) < small_val) && (fabs(sample_y - ry) < small_val) ) sample_val = inputImage[ry + rx*imageHeight + ch*imageHeight*imageWidth]; else { fx = (int)floor(sample_x); fy = (int)floor(sample_y); cx = (int)ceil(sample_x); cy = (int)ceil(sample_y); tx = sample_x - fx; ty = sample_y - fy; w1 = roundn((1 - tx) * (1 - ty), -6); w2 = roundn(tx * (1 - ty), -6); w3 = roundn((1 - tx) * ty, -6); // w4 = roundn(tx * ty, -6); w4 = roundn(1 - w1 - w2 - w3, -6); sample_val = w1*inputImage[fy + fx*imageHeight + ch*imageHeight*imageWidth] + w2*inputImage[fy + cx*imageHeight + ch*imageHeight*imageWidth] + w3*inputImage[cy + fx*imageHeight + ch*imageHeight*imageWidth] + w4*inputImage[cy + cx*imageHeight + ch*imageHeight*imageWidth]; sample_val = roundn(sample_val, -4); } // update the lbp code if (sample_val >= centre_val) lbp_code = lbp_code + 2^s; } descriptorVector[i + ch*numberOfRadiusSamplesCombinations] = lbp_code; } } // Empty memory delete [] samples_coords_x; delete [] samples_coords_y; } double roundn(double x, int n) { if (n < 0) { double p = 10 ^ -n; x = round(p * x) / p; } else if (n > 0) { double p = 10 ^ n; x = p * round(x / p); } else x = round(x); return x; } <|endoftext|>
<commit_before>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <limits> #include "src/ext/cpputil/include/command_line/command_line.h" #include "src/ext/cpputil/include/signal/debug_handler.h" #include "tools/args/target.h" #include "tools/gadgets/sandbox.h" #include "tools/gadgets/seed.h" #include "tools/gadgets/target.h" #include "tools/gadgets/testcases.h" #include "tools/ui/console.h" using namespace cpputil; using namespace std; using namespace stoke; auto& dbg = Heading::create("Debug Options:"); auto& debug = FlagArg::create("debug") .alternate("d") .description("Debug mode, equivalent to --breakpoint 0"); auto& breakpoint = ValueArg<size_t>::create("breakpoint") .usage("<line>") .description("Set breakpoint") .default_val(numeric_limits<size_t>::max()); void callback(const StateCallbackData& data, void* arg) { auto stepping = (bool*) arg; Console::msg() << data.state << endl; Console::msg() << endl; Console::msg() << "Current Instruction: " << target_arg.value().code[data.line] << endl; Console::msg() << endl; if (data.line != breakpoint && *stepping == false) { return; } auto key = ' '; while (key != 'c' && key != 's' && key != 'd') { Console::msg() << "(l)ist, (c)ontinue, (s)tep, (d)isable, or (q)uit: "; cin >> key; Console::msg() << endl; switch (key) { case 'l': for (size_t i = 0, ie = target_arg.value().code.size(); i < ie; ++i) { Console::msg() << (i == data.line ? "-> " : " ") << target_arg.value().code[i] << endl; } Console::msg() << endl; break; case 'c': *stepping = false; break; case 's': *stepping = true; break; case 'd': breakpoint.value() = numeric_limits<size_t>::max(); *stepping = false; break; case 'q': exit(0); default: break; } } } int main(int argc, char** argv) { CommandLineConfig::strict_with_convenience(argc, argv); DebugHandler::install_sigsegv(); DebugHandler::install_sigill(); if (testcases_arg.value().empty()) { Console::msg() << "No testcases provided." << endl; return 0; } if (debug) { if (target_arg.value().code[0].is_label_defn()) { breakpoint.value() = 1; } else { breakpoint.value() = 0; } } TargetGadget target; SeedGadget seed; TestcaseGadget tc(seed); CpuStates tcs; tcs.push_back(tc); SandboxGadget sb(tcs); auto stepping = false; if (!target.is_sound()) { Console::error(1) << "Target reads undefined variables, or leaves live_out undefined." << endl; } for (size_t i = 0, ie = target_arg.value().code.size(); i < ie; ++i) { sb.insert_before(i, callback, &stepping); } sb.run(target); const auto result = *(sb.result_begin()); if (result.code != ErrorCode::NORMAL) { Console::msg() << "Control returned abnormally with signal " << dec << (int)result.code << endl; } else { Console::msg() << "Control returned normally with state: " << endl; Console::msg() << endl; Console::msg() << result << endl; } Console::msg() << endl; return 0; } <commit_msg>whitespace<commit_after>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <limits> #include "src/ext/cpputil/include/command_line/command_line.h" #include "src/ext/cpputil/include/signal/debug_handler.h" #include "tools/args/target.h" #include "tools/gadgets/sandbox.h" #include "tools/gadgets/seed.h" #include "tools/gadgets/target.h" #include "tools/gadgets/testcases.h" #include "tools/ui/console.h" using namespace cpputil; using namespace std; using namespace stoke; auto& dbg = Heading::create("Debug Options:"); auto& debug = FlagArg::create("debug") .alternate("d") .description("Debug mode, equivalent to --breakpoint 0"); auto& breakpoint = ValueArg<size_t>::create("breakpoint") .usage("<line>") .description("Set breakpoint") .default_val(numeric_limits<size_t>::max()); void callback(const StateCallbackData& data, void* arg) { auto stepping = (bool*) arg; Console::msg() << data.state << endl; Console::msg() << endl; Console::msg() << "Current Instruction: " << target_arg.value().code[data.line] << endl; Console::msg() << endl; if (data.line != breakpoint && *stepping == false) { return; } auto key = ' '; while (key != 'c' && key != 's' && key != 'd') { Console::msg() << "(l)ist, (c)ontinue, (s)tep, (d)isable, or (q)uit: "; cin >> key; Console::msg() << endl; switch (key) { case 'l': for (size_t i = 0, ie = target_arg.value().code.size(); i < ie; ++i) { Console::msg() << (i == data.line ? "-> " : " ") << target_arg.value().code[i] << endl; } Console::msg() << endl; break; case 'c': *stepping = false; break; case 's': *stepping = true; break; case 'd': breakpoint.value() = numeric_limits<size_t>::max(); *stepping = false; break; case 'q': exit(0); default: break; } } } int main(int argc, char** argv) { CommandLineConfig::strict_with_convenience(argc, argv); DebugHandler::install_sigsegv(); DebugHandler::install_sigill(); if (testcases_arg.value().empty()) { Console::msg() << "No testcases provided." << endl; return 0; } if (debug) { if (target_arg.value().code[0].is_label_defn()) { breakpoint.value() = 1; } else { breakpoint.value() = 0; } } TargetGadget target; SeedGadget seed; TestcaseGadget tc(seed); CpuStates tcs; tcs.push_back(tc); SandboxGadget sb(tcs); auto stepping = false; if (!target.is_sound()) { Console::error(1) << "Target reads undefined variables, or leaves live_out undefined." << endl; } for (size_t i = 0, ie = target_arg.value().code.size(); i < ie; ++i) { sb.insert_before(i, callback, &stepping); } sb.run(target); const auto result = *(sb.result_begin()); if (result.code != ErrorCode::NORMAL) { Console::msg() << "Control returned abnormally with signal " << dec << (int)result.code << endl; } else { Console::msg() << "Control returned normally with state: " << endl; Console::msg() << endl; Console::msg() << result << endl; } Console::msg() << endl; return 0; } <|endoftext|>
<commit_before>/* * This File is part of Davix, The IO library for HTTP based protocols * Copyright (C) CERN 2013 * Author: Adrien Devresse <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <cstdio> #include <cstring> #include <davix.hpp> #include <sstream> #include <unistd.h> #include "copy_internal.hpp" #include "delegation/delegation.hpp" #include <utils/davix_logger_internal.hpp> #include <utils/davix_gcloud_utils.hpp> using namespace Davix; const std::string COPY_SCOPE = "Davix::HttpThirdPartyCopy"; // Gets the real location of uri respect to ref // uri can be absolute or relative to ref static std::string _full_url(const std::string ref, const std::string& uri) { std::string final; if (uri.find("://") != std::string::npos) { final = uri; } else if (uri[0] == '/') { size_t colon = ref.find(':'); size_t slash = std::string::npos; if (colon != std::string::npos) slash = ref.find('/', colon + 3); if (slash != std::string::npos) { std::string base = ref.substr(0, slash); final = base + uri; } } else { final = ref + uri; } return final; } // Same as _full_url, but it makes sure // that the destination is https static std::string _full_delegation_endpoint(const std::string& ref, const std::string& uri, DavixError** err) { std::string final = _full_url(ref, uri); if (final.substr(7).compare("http://") == 0) { DavixError::setupError(err, COPY_SCOPE, StatusCode::OperationNonSupported, std::string("Plain http can not be used for delegation: ") + uri); final.clear(); } return final; } DavixCopy::DavixCopy(Context &c, const RequestParams *params): d_ptr(NULL) { d_ptr = new DavixCopyInternal(c, params); } DavixCopy::~DavixCopy() { delete d_ptr; } void DavixCopy::copy(const Uri &source, const Uri &destination, unsigned nstreams, DavixError **error) { d_ptr->copy(source, destination, nstreams, error); } void DavixCopy::setPerformanceCallback(PerformanceCallback callback, void *udata) { d_ptr->setPerformanceCallback(callback, udata); } void DavixCopyInternal::setPerformanceCallback(DavixCopy::PerformanceCallback callback, void *udata) { perfCallback = callback; perfCallbackUdata = udata; } void DavixCopyInternal::copy(const Uri &src, const Uri &dst, unsigned nstreams, DavixError **error) { //std::string nextSrc(src.getString()), prevSrc(src.getString()); //std::string destination(dst.getString()); std::string nextSrc, prevSrc, destination; std::string delegationEndpoint; DavixError *internalError = NULL; bool suppressFinalHead = false; // set source and destination according to copy method if(parameters->getCopyMode() == CopyMode::Push){ nextSrc = src.getString(); prevSrc = src.getString(); destination = dst.getString(); }else if(parameters->getCopyMode() == CopyMode::Pull){ nextSrc = dst.getString(); prevSrc = dst.getString(); destination = src.getString(); } // nstreams as string char nstreamsStr[16]; snprintf(nstreamsStr, sizeof(nstreamsStr), "%u", nstreams); // Need a copy so we can modify it Davix::RequestParams requestParams(parameters); requestParams.setTransparentRedirectionSupport(false); size_t start_pos; // if destination is s3 endpoint, change prefix to http(s) and pre-sign the request as a PUT if(destination.compare(0,2,"s3") == 0){ destination.replace(0, 2, "http"); time_t expiration_time = time(NULL) +3600; Davix::HeaderVec vec; Uri tmp; if (parameters->getCopyMode() == CopyMode::Pull) tmp = Davix::S3::tokenizeRequest(requestParams, "GET", destination, vec, expiration_time); else tmp = Davix::S3::tokenizeRequest(requestParams, "PUT", destination, vec, expiration_time); destination = tmp.getString(); suppressFinalHead = true; } // handle gcloud endpoint as a destination if(destination.compare(0,6,"gcloud") == 0){ destination.replace(0, 6, "http"); Davix::HeaderVec vec; Uri tmp; if (parameters->getCopyMode() == CopyMode::Pull) tmp = Davix::gcloud::signURI(requestParams.getGcloudCredentials(), "GET", destination, vec, 3600); else tmp = Davix::gcloud::signURI(requestParams.getGcloudCredentials(), "PUT", destination, vec, 3600); destination = tmp.getString(); suppressFinalHead = true; } if(destination.compare(0, 3, "dav") == 0) { destination.replace(0, 3, "http"); } // Perform COPY hopping through redirections HttpRequest* request = NULL; do { nextSrc = _full_url(prevSrc, nextSrc); prevSrc = nextSrc; if (request) { request->discardBody(&internalError); if (!internalError) request->endRequest(&internalError); if (internalError) { DavixError::propagatePrefixedError(error, internalError, __func__); break; } } delete request; DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_GRID, "Hop: {}", nextSrc); request = context.createRequest(nextSrc, &internalError); if (internalError) { DavixError::propagatePrefixedError(error, internalError, __func__); break; } request->setRequestMethod("COPY"); if(parameters->getCopyMode() == CopyMode::Push){ request->addHeaderField("Destination", destination); }else if(parameters->getCopyMode() == CopyMode::Pull){ request->addHeaderField("Source", destination); } request->addHeaderField("X-Number-Of-Streams", nstreamsStr); // for lcgdm-dav, ask for secure redirection in all cases for COPY request->addHeaderField("Secure-Redirection", "1"); // for lcgdm-dav -> S3, add NoHead flag to suppress final head-to-close request if(suppressFinalHead) request->addHeaderField("Copy-Flags", "NoHead"); request->setParameters(requestParams); request->beginRequest(&internalError); if (internalError) { DavixError::propagatePrefixedError(error, internalError, __func__); break; } // If we get a X-Delegate-To, before continuing, delegate if (request->getAnswerHeader("X-Delegate-To", delegationEndpoint)) { delegationEndpoint = _full_delegation_endpoint(nextSrc, delegationEndpoint, &internalError); if (internalError) { DavixError::propagatePrefixedError(error, internalError, __func__); break; } DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_GRID, "Got delegation endpoint: {}", delegationEndpoint.c_str()); std::string dlg_id = DavixDelegation::delegate(context, delegationEndpoint, parameters, &internalError); if (internalError) { DavixError::propagatePrefixedError(error, internalError, __func__); break; } DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_GRID, "Got delegation ID {}", dlg_id.c_str()); dlg_id.clear(); } } while (request->getAnswerHeader("Location", nextSrc) && request->getRequestCode() >= 300 && request->getRequestCode() < 400); if (!*error) { int responseStatus = request->getRequestCode(); if (responseStatus == 404) { DavixError::setupError(error, COPY_SCOPE, StatusCode::FileNotFound, "Could not COPY. File not found"); } else if (responseStatus == 403) { DavixError::setupError(error, COPY_SCOPE, StatusCode::PermissionRefused, "Could not COPY. Permission denied."); } else if (responseStatus == 501) { DavixError::setupError(error, COPY_SCOPE, StatusCode::OperationNonSupported, "Could not COPY. The source service does not support it"); } else if (responseStatus >= 405) { DavixError::setupError(error, COPY_SCOPE, StatusCode::OperationNonSupported, "Could not COPY. The source service does not allow it"); } else if (responseStatus == 400) { std::string err_msg(request->getAnswerContentVec().begin(), request->getAnswerContentVec().end()); DavixError::setupError(error, COPY_SCOPE, StatusCode::InvalidArgument, fmt::format("Could not COPY. The server rejected the request: {}", err_msg)); } else if (responseStatus >= 300) { std::ostringstream msg; msg << "Could not COPY. Unknown error code: " << responseStatus; DavixError::setupError(error, COPY_SCOPE, StatusCode::UnknowError, msg.str()); } } // Did we fail? if (*error) return; // Finished hopping std::string finalSource = nextSrc; // Just wait for it to finish monitorPerformanceMarkers(request, error); request->endRequest(error); delete request; } void DavixCopyInternal::monitorPerformanceMarkers(Davix::HttpRequest *request, Davix::DavixError **error) { Davix::DavixError* daverr = NULL; char buffer[1024], *p; dav_ssize_t line_len; PerformanceMarker holder; PerformanceData performance; time_t lastPerfCallback = time(NULL); while ((line_len = request->readLine(buffer, sizeof(buffer), &daverr)) >= 0 && !daverr) { buffer[line_len] = '\0'; if (line_len > 0) DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_GRID, "Received: {}", buffer); // Skip heading whitespaces p = buffer; while (*p && p < buffer + sizeof(buffer) && isspace(*p)) ++p; if (strncasecmp("Perf Marker", p, 11) == 0) { memset(&holder, 0, sizeof(holder)); } else if (strncasecmp("Timestamp:", p, 10) == 0) { holder.latest = atol(p + 10); } else if (strncasecmp("Stripe Index:", p, 13) == 0) { holder.index = atoi(p + 13); } else if (strncasecmp("Stripe Bytes Transferred:", p, 25) == 0) { holder.transferred = atol(p + 26); } else if (strncasecmp("Total Stripe Count:", p, 19) == 0) { holder.count = atoi(p + 20); } else if (strncasecmp("End", p, 3) == 0) { performance.update(holder); time_t now = time(NULL); if (now - lastPerfCallback >= 1) { if (this->perfCallback) this->perfCallback(performance, this->perfCallbackUdata); lastPerfCallback = now; } } else if (strncasecmp("success", p, 7) == 0) { request->discardBody(&daverr); break; } else if (strncasecmp("aborted", p, 7) == 0) { Davix::DavixError::setupError(error, COPY_SCOPE, StatusCode::Canceled, "Transfer aborted in the remote end"); break; } else if (strncasecmp("failed", p, 6) == 0 || strncasecmp("failure", p, 7) == 0) { Davix::DavixError::setupError(error, COPY_SCOPE, StatusCode::RemoteError, std::string("Transfer failed: ") + p); break; } else if(line_len> 0) { DAVIX_SLOG(DAVIX_LOG_WARNING, DAVIX_LOG_GRID, "Unknown performance marker, ignoring: {}", buffer); } } } <commit_msg>DMC-1138 Ensure relevant error from TPC failure is propagated to the client<commit_after>/* * This File is part of Davix, The IO library for HTTP based protocols * Copyright (C) CERN 2013 * Author: Adrien Devresse <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <cstdio> #include <cstring> #include <davix.hpp> #include <sstream> #include <unistd.h> #include "copy_internal.hpp" #include "delegation/delegation.hpp" #include <utils/davix_logger_internal.hpp> #include <utils/davix_gcloud_utils.hpp> using namespace Davix; const std::string COPY_SCOPE = "Davix::HttpThirdPartyCopy"; // Gets the real location of uri respect to ref // uri can be absolute or relative to ref static std::string _full_url(const std::string ref, const std::string& uri) { std::string final; if (uri.find("://") != std::string::npos) { final = uri; } else if (uri[0] == '/') { size_t colon = ref.find(':'); size_t slash = std::string::npos; if (colon != std::string::npos) slash = ref.find('/', colon + 3); if (slash != std::string::npos) { std::string base = ref.substr(0, slash); final = base + uri; } } else { final = ref + uri; } return final; } // Same as _full_url, but it makes sure // that the destination is https static std::string _full_delegation_endpoint(const std::string& ref, const std::string& uri, DavixError** err) { std::string final = _full_url(ref, uri); if (final.substr(7).compare("http://") == 0) { DavixError::setupError(err, COPY_SCOPE, StatusCode::OperationNonSupported, std::string("Plain http can not be used for delegation: ") + uri); final.clear(); } return final; } DavixCopy::DavixCopy(Context &c, const RequestParams *params): d_ptr(NULL) { d_ptr = new DavixCopyInternal(c, params); } DavixCopy::~DavixCopy() { delete d_ptr; } void DavixCopy::copy(const Uri &source, const Uri &destination, unsigned nstreams, DavixError **error) { d_ptr->copy(source, destination, nstreams, error); } void DavixCopy::setPerformanceCallback(PerformanceCallback callback, void *udata) { d_ptr->setPerformanceCallback(callback, udata); } void DavixCopyInternal::setPerformanceCallback(DavixCopy::PerformanceCallback callback, void *udata) { perfCallback = callback; perfCallbackUdata = udata; } void DavixCopyInternal::copy(const Uri &src, const Uri &dst, unsigned nstreams, DavixError **error) { //std::string nextSrc(src.getString()), prevSrc(src.getString()); //std::string destination(dst.getString()); std::string nextSrc, prevSrc, destination; std::string delegationEndpoint; DavixError *internalError = NULL; bool suppressFinalHead = false; // set source and destination according to copy method if(parameters->getCopyMode() == CopyMode::Push){ nextSrc = src.getString(); prevSrc = src.getString(); destination = dst.getString(); }else if(parameters->getCopyMode() == CopyMode::Pull){ nextSrc = dst.getString(); prevSrc = dst.getString(); destination = src.getString(); } // nstreams as string char nstreamsStr[16]; snprintf(nstreamsStr, sizeof(nstreamsStr), "%u", nstreams); // Need a copy so we can modify it Davix::RequestParams requestParams(parameters); requestParams.setTransparentRedirectionSupport(false); size_t start_pos; // if destination is s3 endpoint, change prefix to http(s) and pre-sign the request as a PUT if(destination.compare(0,2,"s3") == 0){ destination.replace(0, 2, "http"); time_t expiration_time = time(NULL) +3600; Davix::HeaderVec vec; Uri tmp; if (parameters->getCopyMode() == CopyMode::Pull) tmp = Davix::S3::tokenizeRequest(requestParams, "GET", destination, vec, expiration_time); else tmp = Davix::S3::tokenizeRequest(requestParams, "PUT", destination, vec, expiration_time); destination = tmp.getString(); suppressFinalHead = true; } // handle gcloud endpoint as a destination if(destination.compare(0,6,"gcloud") == 0){ destination.replace(0, 6, "http"); Davix::HeaderVec vec; Uri tmp; if (parameters->getCopyMode() == CopyMode::Pull) tmp = Davix::gcloud::signURI(requestParams.getGcloudCredentials(), "GET", destination, vec, 3600); else tmp = Davix::gcloud::signURI(requestParams.getGcloudCredentials(), "PUT", destination, vec, 3600); destination = tmp.getString(); suppressFinalHead = true; } if(destination.compare(0, 3, "dav") == 0) { destination.replace(0, 3, "http"); } // Perform COPY hopping through redirections HttpRequest* request = NULL; do { nextSrc = _full_url(prevSrc, nextSrc); prevSrc = nextSrc; if (request) { request->discardBody(&internalError); if (!internalError) request->endRequest(&internalError); if (internalError) { DavixError::propagatePrefixedError(error, internalError, __func__); break; } } delete request; DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_GRID, "Hop: {}", nextSrc); request = context.createRequest(nextSrc, &internalError); if (internalError) { DavixError::propagatePrefixedError(error, internalError, __func__); break; } request->setRequestMethod("COPY"); if(parameters->getCopyMode() == CopyMode::Push){ request->addHeaderField("Destination", destination); }else if(parameters->getCopyMode() == CopyMode::Pull){ request->addHeaderField("Source", destination); } request->addHeaderField("X-Number-Of-Streams", nstreamsStr); // for lcgdm-dav, ask for secure redirection in all cases for COPY request->addHeaderField("Secure-Redirection", "1"); // for lcgdm-dav -> S3, add NoHead flag to suppress final head-to-close request if(suppressFinalHead) request->addHeaderField("Copy-Flags", "NoHead"); request->setParameters(requestParams); request->beginRequest(&internalError); if (internalError) { DavixError::propagatePrefixedError(error, internalError, __func__); break; } // If we get a X-Delegate-To, before continuing, delegate if (request->getAnswerHeader("X-Delegate-To", delegationEndpoint)) { delegationEndpoint = _full_delegation_endpoint(nextSrc, delegationEndpoint, &internalError); if (internalError) { DavixError::propagatePrefixedError(error, internalError, __func__); break; } DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_GRID, "Got delegation endpoint: {}", delegationEndpoint.c_str()); std::string dlg_id = DavixDelegation::delegate(context, delegationEndpoint, parameters, &internalError); if (internalError) { DavixError::propagatePrefixedError(error, internalError, __func__); break; } DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_GRID, "Got delegation ID {}", dlg_id.c_str()); dlg_id.clear(); } } while (request->getAnswerHeader("Location", nextSrc) && request->getRequestCode() >= 300 && request->getRequestCode() < 400); if (!*error) { int responseStatus = request->getRequestCode(); if (responseStatus == 404) { DavixError::setupError(error, COPY_SCOPE, StatusCode::FileNotFound, "Could not COPY. File not found"); } else if (responseStatus == 403) { DavixError::setupError(error, COPY_SCOPE, StatusCode::PermissionRefused, "Could not COPY. Permission denied."); } else if (responseStatus == 501) { DavixError::setupError(error, COPY_SCOPE, StatusCode::OperationNonSupported, "Could not COPY. The source service does not support it"); } else if (responseStatus >= 405) { DavixError::setupError(error, COPY_SCOPE, StatusCode::OperationNonSupported, "Could not COPY. The source service does not allow it"); } else if (responseStatus == 400) { std::string err_msg(request->getAnswerContentVec().begin(), request->getAnswerContentVec().end()); DavixError::setupError(error, COPY_SCOPE, StatusCode::InvalidArgument, fmt::format("Could not COPY. The server rejected the request: {}", err_msg)); } else if (responseStatus >= 300) { std::ostringstream msg; msg << "Could not COPY. Unknown error code: " << responseStatus; DavixError::setupError(error, COPY_SCOPE, StatusCode::UnknowError, msg.str()); } } // Did we fail? if (*error) return; // Finished hopping std::string finalSource = nextSrc; // Just wait for it to finish monitorPerformanceMarkers(request, error); // Don't override previous error when shutting down connection - sigh if(error && *error) { DavixError* tmp_err=NULL; request->endRequest(&tmp_err); DavixError::clearError(tmp_err); } else { request->endRequest(error); } delete request; } void DavixCopyInternal::monitorPerformanceMarkers(Davix::HttpRequest *request, Davix::DavixError **error) { Davix::DavixError* daverr = NULL; char buffer[1024], *p; dav_ssize_t line_len; PerformanceMarker holder; PerformanceData performance; time_t lastPerfCallback = time(NULL); while ((line_len = request->readLine(buffer, sizeof(buffer), &daverr)) >= 0 && !daverr) { buffer[line_len] = '\0'; if (line_len > 0) DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_GRID, "Received: {}", buffer); // Skip heading whitespaces p = buffer; while (*p && p < buffer + sizeof(buffer) && isspace(*p)) ++p; if (strncasecmp("Perf Marker", p, 11) == 0) { memset(&holder, 0, sizeof(holder)); } else if (strncasecmp("Timestamp:", p, 10) == 0) { holder.latest = atol(p + 10); } else if (strncasecmp("Stripe Index:", p, 13) == 0) { holder.index = atoi(p + 13); } else if (strncasecmp("Stripe Bytes Transferred:", p, 25) == 0) { holder.transferred = atol(p + 26); } else if (strncasecmp("Total Stripe Count:", p, 19) == 0) { holder.count = atoi(p + 20); } else if (strncasecmp("End", p, 3) == 0) { performance.update(holder); time_t now = time(NULL); if (now - lastPerfCallback >= 1) { if (this->perfCallback) this->perfCallback(performance, this->perfCallbackUdata); lastPerfCallback = now; } } else if (strncasecmp("success", p, 7) == 0) { request->discardBody(&daverr); break; } else if (strncasecmp("aborted", p, 7) == 0) { Davix::DavixError::setupError(error, COPY_SCOPE, StatusCode::Canceled, "Transfer aborted in the remote end"); break; } else if (strncasecmp("failed", p, 6) == 0 || strncasecmp("failure", p, 7) == 0) { Davix::DavixError::setupError(error, COPY_SCOPE, StatusCode::RemoteError, std::string("Transfer failed: ") + p); break; } else if(line_len> 0) { DAVIX_SLOG(DAVIX_LOG_WARNING, DAVIX_LOG_GRID, "Unknown performance marker, ignoring: {}", buffer); } } } <|endoftext|>
<commit_before>#include "MeshPrimitives.h" #include <math3d/geometry3d.h> #include <math3d/basis.h> #include <assert.h> #include <math/complex.h> namespace Meshing { void MakeTriPlane(int m,int n,TriMesh& mesh) { MakeTriPlane(m,n,1,1,mesh); } void MakeTriPlane(int m,int n,Real sx,Real sy,TriMesh& mesh) { m=Max(m,1); n=Max(n,1); mesh.verts.resize((m+1)*(n+1)); mesh.tris.resize(m*n*2); //set verts Real hx,hy; hx = sx/(Real)m; hy = sy/(Real)n; Real x,y; int k=0; x=0; for(int i=0;i<=m;i++,x+=hx) { y=0; for(int j=0;j<=n;j++,k++,y+=hy) { mesh.verts[k].set(x,y,0); } } //tris k=0; int v=0; //v jumps by n+1 every column for(int i=0;i<m;i++) { for(int j=0;j<n;j++,v++,k+=2) { mesh.tris[k].set(v,v+(n+1),v+1); mesh.tris[k+1].set(v+1,v+(n+1),v+n+2); } v++; } assert(mesh.IsValid()); } void MakeTriCube(int m,int n,int p,TriMesh& mesh) { MakeTriBox(m,n,p,1,1,1,mesh); } void MakeTriBox(int m,int n,int p,Real x,Real y,Real z,TriMesh& mesh) { if(m <= 1 && n <= 1 && p <= 1) { mesh.verts.resize(8); mesh.tris.resize(12); mesh.verts[0].set(0,0,0); mesh.verts[1].set(0,0,z); mesh.verts[2].set(0,y,0); mesh.verts[3].set(0,y,z); mesh.verts[4].set(x,0,0); mesh.verts[5].set(x,0,z); mesh.verts[6].set(x,y,0); mesh.verts[7].set(x,y,z); //-x face mesh.tris[0].set(0,1,3); mesh.tris[1].set(0,3,2); //+x face mesh.tris[2].set(4,6,7); mesh.tris[3].set(4,7,5); //-y face mesh.tris[4].set(0,4,5); mesh.tris[5].set(0,5,1); //+y face mesh.tris[6].set(2,3,7); mesh.tris[7].set(2,7,6); //-z face mesh.tris[8].set(0,2,6); mesh.tris[9].set(0,6,4); //+z face mesh.tris[10].set(1,5,7); mesh.tris[11].set(1,7,3); } else { if(m < 1) m = 1; if(n < 1) n = 1; if(p < 1) p = 1; TriMesh faceTemp; vector<TriMesh> faces(6); MakeTriPlane(m,n,x,y,faceTemp); faces[0] = faceTemp; faces[1] = faceTemp; for(size_t i=0;i<faces[1].verts.size();i++) faces[1].verts[i].z = z; MakeTriPlane(m,p,x,z,faceTemp); for(size_t i=0;i<faceTemp.verts.size();i++) { faceTemp.verts[i].z=faceTemp.verts[i].y; faceTemp.verts[i].y=0; } faces[2] = faceTemp; faces[3] = faceTemp; for(size_t i=0;i<faces[3].verts.size();i++) faces[3].verts[i].y = y; MakeTriPlane(n,p,y,z,faceTemp); for(size_t i=0;i<faceTemp.verts.size();i++) { faceTemp.verts[i].z=faceTemp.verts[i].y; faceTemp.verts[i].y=faceTemp.verts[i].x; faceTemp.verts[i].x=0; } faces[4] = faceTemp; faces[5] = faceTemp; for(size_t i=0;i<faces[5].verts.size();i++) faces[5].verts[i].x = x; faces[0].FlipFaces(); faces[3].FlipFaces(); faces[4].FlipFaces(); mesh.Merge(faces); //TODO: weld vertices? } } void MakeTriCenteredCube(int m,int n,int p,TriMesh& mesh) { MakeTriCenteredBox(m,n,p,1,1,1,mesh); } void MakeTriCenteredBox(int m,int n,int p,Real x,Real y,Real z,TriMesh& mesh) { MakeTriBox(m,n,p,x,y,z,mesh); Vector3 shift(0.5*x,0.5*y,0.5*z); for(size_t i=0;i<mesh.verts.size();i++) mesh.verts[i] -= shift; } void MakeTriSphere(int numStacks,int numSlices,TriMesh& mesh) { MakeTriSphere(numStacks,numSlices,1,mesh); } void MakeTriSphere(int numStacks,int numSlices,Real r,TriMesh& mesh) { numStacks=Max(numStacks,2); numSlices=Max(numSlices,3); mesh.verts.resize(numSlices*(numStacks-1)+2); mesh.tris.resize(2*numSlices*(numStacks-2) + 2*numSlices); //verts Real dtheta=TwoPi/(Real)numSlices; Real dphi=Pi/(Real)numStacks; Real phi; Complex x,dx; dx.setPolar(One,dtheta); mesh.verts[0].set(0,0,-r); int k=1; phi=-Pi*Half+dphi; for(int i=0;i<numStacks-1;i++,phi+=dphi) { Real z=Sin(phi)*r; x.set(Cos(phi)*r,0); for(int j=0;j<numSlices;j++,k++) { mesh.verts[k].set(x.x,x.y,z); x *= dx; } } mesh.verts[k].set(0,0,r); assert(k+1 == (int)mesh.verts.size()); //tris k=0; //bottom stack int v=1; for(int j=0;j<numSlices;j++,k++) { int n=(j+1 == numSlices ? 0 : j+1); mesh.tris[k].set(0,v+n,v+j); } //middle stacks for(int i=1;i+1<numStacks;i++) { //wrap a strip around starting from v for(int j=0;j<numSlices;j++,k+=2) { int n=(j+1 == numSlices ? 0 : j+1); mesh.tris[k].set(v+j+numSlices,v+j,v+n); mesh.tris[k+1].set(v+j+numSlices,v+n,v+n+numSlices); } v += numSlices; } //top stack for(int j=0;j<numSlices;j++,k++) { int n=(j+1 == numSlices ? 0 : j+1); mesh.tris[k].set(v+numSlices,v+j,v+n); } assert(k == (int)mesh.tris.size()); assert(v+numSlices+1 == (int)mesh.verts.size()); assert(mesh.IsValid()); } void MakeTriCone(int numSlices,TriMesh& mesh) { MakeTriCone(numSlices,1,1,mesh); } void MakeTriCone(int numSlices,Real h,Real rbase,TriMesh& mesh) { numSlices=Max(numSlices,3); mesh.verts.resize(numSlices+2); mesh.tris.resize(numSlices*2); Real dtheta=TwoPi/(Real)numSlices; //verts Complex x,dx; dx.setPolar(1,dtheta); x.set(rbase,0); mesh.verts[0].setZero(); for(int i=0;i<numSlices;i++) { mesh.verts[i+1].set(x.x,x.y,0); x *= dx; } mesh.verts[numSlices+1].set(0,0,h); //tris for(int i=0;i<numSlices;i++) { int n=(i+1==numSlices? 0 : i+1); mesh.tris[i].set(0,1+n,1+i); mesh.tris[i+numSlices].set(numSlices+1,1+i,1+n); } assert(mesh.IsValid()); } void MakeTriCylinder(int numSlices,TriMesh& mesh) { MakeTriCylinder(numSlices,1,1,mesh); } void MakeTriCylinder(int numSlices,Real h,Real rbase,TriMesh& mesh) { mesh.verts.resize(numSlices*2+2); mesh.tris.resize(numSlices*4); Real dtheta=TwoPi/(Real)numSlices; //verts Complex x,dx; dx.setPolar(1,dtheta); x.set(rbase,0); mesh.verts[0].setZero(); mesh.verts[numSlices*2+1].set(0,0,h); for(int i=0;i<numSlices;i++) { mesh.verts[i+1].set(x.x,x.y,0); mesh.verts[i+1+numSlices].set(x.x,x.y,h); x *= dx; } //tris for(int i=0;i<numSlices;i++) { int n=(i+1==numSlices? 0 : i+1); //bottom mesh.tris[i].set(0,1+n,1+i); //top mesh.tris[i+numSlices].set(numSlices*2+1,1+i+numSlices,1+n+numSlices); //sides mesh.tris[i*2+numSlices*2].set(1+i,1+n,1+i+numSlices); mesh.tris[i*2+numSlices*2+1].set(1+n,1+n+numSlices,1+i+numSlices); } assert(mesh.IsValid()); } void MakeTriMesh(const Sphere3D& geom,int numStacks,int numSlices,TriMesh& mesh) { MakeTriSphere(numStacks,numSlices,mesh); Matrix4 mat; mat.setIdentity(); mat(0,0) = mat(1,1) = mat(2,2) = geom.radius; geom.center.get(mat(3,0),mat(3,1),mat(3,2)); mesh.Transform(mat); } void MakeTriMesh(const Triangle3D& geom,TriMesh& mesh) { mesh.verts.resize(3); mesh.tris.resize(1); mesh.verts[0] = geom.a; mesh.verts[1] = geom.b; mesh.verts[2] = geom.c; mesh.tris[0].a = 0; mesh.tris[0].b = 1; mesh.tris[0].c = 2; } void MakeTriMesh(const AABB3D& geom,TriMesh& mesh) { MakeTriCube(1,1,1,mesh); Matrix4 mat; mat.setIdentity(); mat(0,0) = geom.bmax.x-geom.bmin.x; mat(1,1) = geom.bmax.y-geom.bmin.y; mat(2,2) = geom.bmax.z-geom.bmin.z; geom.bmin.get(mat(3,0),mat(3,1),mat(3,2)); mesh.Transform(mat); } void MakeTriMesh(const Box3D& geom,TriMesh& mesh) { MakeTriCube(1,1,1,mesh); Matrix4 mat; geom.getBasisScaled(mat); mesh.Transform(mat); } void MakeTriMesh(const Ellipsoid3D& geom,int numStacks,int numSlices,TriMesh& mesh) { MakeTriSphere(numStacks,numSlices,mesh); Matrix4 mat; geom.getBasisScaled(mat); mesh.Transform(mat); } void MakeTriMesh(const Cylinder3D& geom,int numSlices,TriMesh& mesh) { MakeTriCylinder(numSlices,geom.height,geom.radius,mesh); Vector3 x,y; GetCanonicalBasis(geom.axis,x,y); mesh.Transform(Matrix4(x,y,geom.axis,geom.center)); } ///makes a triangle mesh from a polygon (one sided) void MakeTriMesh(const Polygon3D& geom,TriMesh& mesh) { mesh.verts = geom.vertices; mesh.tris.resize(geom.vertices.size()-2); for(size_t i=0;i+2<geom.vertices.size();i++) mesh.tris[i].set(0,i+1,i+2); } ///makes a triangle mesh from a generic geometric primitive void MakeTriMesh(const GeometricPrimitive3D& geom,TriMesh& mesh,int numDivs) { switch(geom.type) { case GeometricPrimitive3D::Point: mesh.verts.resize(1); mesh.verts[0] = *AnyCast_Raw<Point3D>(&geom.data); mesh.tris.resize(0); break; case GeometricPrimitive3D::Segment: //make a degenerate mesh mesh.verts.resize(2); mesh.verts[0] = AnyCast_Raw<Segment3D>(&geom.data)->a; mesh.verts[1] = AnyCast_Raw<Segment3D>(&geom.data)->b; mesh.tris.resize(1); mesh.tris[0].set(0,1,1); break; case GeometricPrimitive3D::Triangle: MakeTriMesh(*AnyCast_Raw<Triangle3D>(&geom.data),mesh); break; case GeometricPrimitive3D::Polygon: MakeTriMesh(*AnyCast_Raw<Polygon3D>(&geom.data),mesh); break; case GeometricPrimitive3D::Box: MakeTriMesh(*AnyCast_Raw<Box3D>(&geom.data),mesh); break; case GeometricPrimitive3D::Cylinder: MakeTriMesh(*AnyCast_Raw<Cylinder3D>(&geom.data),numDivs,mesh); break; case GeometricPrimitive3D::Sphere: MakeTriMesh(*AnyCast_Raw<Sphere3D>(&geom.data),numDivs/2,numDivs,mesh); break; case GeometricPrimitive3D::Ellipsoid: MakeTriMesh(*AnyCast_Raw<Ellipsoid3D>(&geom.data),numDivs,numDivs,mesh); break; case GeometricPrimitive3D::AABB: MakeTriMesh(*AnyCast_Raw<AABB3D>(&geom.data),mesh); break; default: FatalError("Invalid primitive type %d for MakeTriMesh",geom.type); } } } //namespace Meshing <commit_msg>Fixed problem with making mesh primitives<commit_after>#include "MeshPrimitives.h" #include <math3d/geometry3d.h> #include <math3d/basis.h> #include <assert.h> #include <math/complex.h> namespace Meshing { void MakeTriPlane(int m,int n,TriMesh& mesh) { MakeTriPlane(m,n,1,1,mesh); } void MakeTriPlane(int m,int n,Real sx,Real sy,TriMesh& mesh) { m=Max(m,1); n=Max(n,1); mesh.verts.resize((m+1)*(n+1)); mesh.tris.resize(m*n*2); //set verts Real hx,hy; hx = sx/(Real)m; hy = sy/(Real)n; Real x,y; int k=0; x=0; for(int i=0;i<=m;i++,x+=hx) { y=0; for(int j=0;j<=n;j++,k++,y+=hy) { mesh.verts[k].set(x,y,0); } } //tris k=0; int v=0; //v jumps by n+1 every column for(int i=0;i<m;i++) { for(int j=0;j<n;j++,v++,k+=2) { mesh.tris[k].set(v,v+(n+1),v+1); mesh.tris[k+1].set(v+1,v+(n+1),v+n+2); } v++; } assert(mesh.IsValid()); } void MakeTriCube(int m,int n,int p,TriMesh& mesh) { MakeTriBox(m,n,p,1,1,1,mesh); } void MakeTriBox(int m,int n,int p,Real x,Real y,Real z,TriMesh& mesh) { if(m <= 1 && n <= 1 && p <= 1) { mesh.verts.resize(8); mesh.tris.resize(12); mesh.verts[0].set(0,0,0); mesh.verts[1].set(0,0,z); mesh.verts[2].set(0,y,0); mesh.verts[3].set(0,y,z); mesh.verts[4].set(x,0,0); mesh.verts[5].set(x,0,z); mesh.verts[6].set(x,y,0); mesh.verts[7].set(x,y,z); //-x face mesh.tris[0].set(0,1,3); mesh.tris[1].set(0,3,2); //+x face mesh.tris[2].set(4,6,7); mesh.tris[3].set(4,7,5); //-y face mesh.tris[4].set(0,4,5); mesh.tris[5].set(0,5,1); //+y face mesh.tris[6].set(2,3,7); mesh.tris[7].set(2,7,6); //-z face mesh.tris[8].set(0,2,6); mesh.tris[9].set(0,6,4); //+z face mesh.tris[10].set(1,5,7); mesh.tris[11].set(1,7,3); } else { if(m < 1) m = 1; if(n < 1) n = 1; if(p < 1) p = 1; TriMesh faceTemp; vector<TriMesh> faces(6); MakeTriPlane(m,n,x,y,faceTemp); faces[0] = faceTemp; faces[1] = faceTemp; for(size_t i=0;i<faces[1].verts.size();i++) faces[1].verts[i].z = z; MakeTriPlane(m,p,x,z,faceTemp); for(size_t i=0;i<faceTemp.verts.size();i++) { faceTemp.verts[i].z=faceTemp.verts[i].y; faceTemp.verts[i].y=0; } faces[2] = faceTemp; faces[3] = faceTemp; for(size_t i=0;i<faces[3].verts.size();i++) faces[3].verts[i].y = y; MakeTriPlane(n,p,y,z,faceTemp); for(size_t i=0;i<faceTemp.verts.size();i++) { faceTemp.verts[i].z=faceTemp.verts[i].y; faceTemp.verts[i].y=faceTemp.verts[i].x; faceTemp.verts[i].x=0; } faces[4] = faceTemp; faces[5] = faceTemp; for(size_t i=0;i<faces[5].verts.size();i++) faces[5].verts[i].x = x; faces[0].FlipFaces(); faces[3].FlipFaces(); faces[4].FlipFaces(); mesh.Merge(faces); //TODO: weld vertices? } } void MakeTriCenteredCube(int m,int n,int p,TriMesh& mesh) { MakeTriCenteredBox(m,n,p,1,1,1,mesh); } void MakeTriCenteredBox(int m,int n,int p,Real x,Real y,Real z,TriMesh& mesh) { MakeTriBox(m,n,p,x,y,z,mesh); Vector3 shift(0.5*x,0.5*y,0.5*z); for(size_t i=0;i<mesh.verts.size();i++) mesh.verts[i] -= shift; } void MakeTriSphere(int numStacks,int numSlices,TriMesh& mesh) { MakeTriSphere(numStacks,numSlices,1,mesh); } void MakeTriSphere(int numStacks,int numSlices,Real r,TriMesh& mesh) { numStacks=Max(numStacks,2); numSlices=Max(numSlices,3); mesh.verts.resize(numSlices*(numStacks-1)+2); mesh.tris.resize(2*numSlices*(numStacks-2) + 2*numSlices); //verts Real dtheta=TwoPi/(Real)numSlices; Real dphi=Pi/(Real)numStacks; Real phi; Complex x,dx; dx.setPolar(One,dtheta); mesh.verts[0].set(0,0,-r); int k=1; phi=-Pi*Half+dphi; for(int i=0;i<numStacks-1;i++,phi+=dphi) { Real z=Sin(phi)*r; x.set(Cos(phi)*r,0); for(int j=0;j<numSlices;j++,k++) { mesh.verts[k].set(x.x,x.y,z); x *= dx; } } mesh.verts[k].set(0,0,r); assert(k+1 == (int)mesh.verts.size()); //tris k=0; //bottom stack int v=1; for(int j=0;j<numSlices;j++,k++) { int n=(j+1 == numSlices ? 0 : j+1); mesh.tris[k].set(0,v+n,v+j); } //middle stacks for(int i=1;i+1<numStacks;i++) { //wrap a strip around starting from v for(int j=0;j<numSlices;j++,k+=2) { int n=(j+1 == numSlices ? 0 : j+1); mesh.tris[k].set(v+j+numSlices,v+j,v+n); mesh.tris[k+1].set(v+j+numSlices,v+n,v+n+numSlices); } v += numSlices; } //top stack for(int j=0;j<numSlices;j++,k++) { int n=(j+1 == numSlices ? 0 : j+1); mesh.tris[k].set(v+numSlices,v+j,v+n); } assert(k == (int)mesh.tris.size()); assert(v+numSlices+1 == (int)mesh.verts.size()); assert(mesh.IsValid()); } void MakeTriCone(int numSlices,TriMesh& mesh) { MakeTriCone(numSlices,1,1,mesh); } void MakeTriCone(int numSlices,Real h,Real rbase,TriMesh& mesh) { numSlices=Max(numSlices,3); mesh.verts.resize(numSlices+2); mesh.tris.resize(numSlices*2); Real dtheta=TwoPi/(Real)numSlices; //verts Complex x,dx; dx.setPolar(1,dtheta); x.set(rbase,0); mesh.verts[0].setZero(); for(int i=0;i<numSlices;i++) { mesh.verts[i+1].set(x.x,x.y,0); x *= dx; } mesh.verts[numSlices+1].set(0,0,h); //tris for(int i=0;i<numSlices;i++) { int n=(i+1==numSlices? 0 : i+1); mesh.tris[i].set(0,1+n,1+i); mesh.tris[i+numSlices].set(numSlices+1,1+i,1+n); } assert(mesh.IsValid()); } void MakeTriCylinder(int numSlices,TriMesh& mesh) { MakeTriCylinder(numSlices,1,1,mesh); } void MakeTriCylinder(int numSlices,Real h,Real rbase,TriMesh& mesh) { mesh.verts.resize(numSlices*2+2); mesh.tris.resize(numSlices*4); Real dtheta=TwoPi/(Real)numSlices; //verts Complex x,dx; dx.setPolar(1,dtheta); x.set(rbase,0); mesh.verts[0].setZero(); mesh.verts[numSlices*2+1].set(0,0,h); for(int i=0;i<numSlices;i++) { mesh.verts[i+1].set(x.x,x.y,0); mesh.verts[i+1+numSlices].set(x.x,x.y,h); x *= dx; } //tris for(int i=0;i<numSlices;i++) { int n=(i+1==numSlices? 0 : i+1); //bottom mesh.tris[i].set(0,1+n,1+i); //top mesh.tris[i+numSlices].set(numSlices*2+1,1+i+numSlices,1+n+numSlices); //sides mesh.tris[i*2+numSlices*2].set(1+i,1+n,1+i+numSlices); mesh.tris[i*2+numSlices*2+1].set(1+n,1+n+numSlices,1+i+numSlices); } assert(mesh.IsValid()); } void MakeTriMesh(const Sphere3D& geom,int numStacks,int numSlices,TriMesh& mesh) { MakeTriSphere(numStacks,numSlices,mesh); Matrix4 mat; mat.setIdentity(); mat(0,0) = mat(1,1) = mat(2,2) = geom.radius; geom.center.get(mat(0,3),mat(1,3),mat(2,3)); mesh.Transform(mat); } void MakeTriMesh(const Triangle3D& geom,TriMesh& mesh) { mesh.verts.resize(3); mesh.tris.resize(1); mesh.verts[0] = geom.a; mesh.verts[1] = geom.b; mesh.verts[2] = geom.c; mesh.tris[0].a = 0; mesh.tris[0].b = 1; mesh.tris[0].c = 2; } void MakeTriMesh(const AABB3D& geom,TriMesh& mesh) { MakeTriCube(1,1,1,mesh); Matrix4 mat; mat.setIdentity(); mat(0,0) = geom.bmax.x-geom.bmin.x; mat(1,1) = geom.bmax.y-geom.bmin.y; mat(2,2) = geom.bmax.z-geom.bmin.z; geom.bmin.get(mat(0,3),mat(1,3),mat(2,3)); mesh.Transform(mat); } void MakeTriMesh(const Box3D& geom,TriMesh& mesh) { MakeTriCube(1,1,1,mesh); Matrix4 mat; geom.getBasisScaled(mat); mesh.Transform(mat); } void MakeTriMesh(const Ellipsoid3D& geom,int numStacks,int numSlices,TriMesh& mesh) { MakeTriSphere(numStacks,numSlices,mesh); Matrix4 mat; geom.getBasisScaled(mat); mesh.Transform(mat); } void MakeTriMesh(const Cylinder3D& geom,int numSlices,TriMesh& mesh) { MakeTriCylinder(numSlices,geom.height,geom.radius,mesh); Vector3 x,y; GetCanonicalBasis(geom.axis,x,y); mesh.Transform(Matrix4(x,y,geom.axis,geom.center)); } ///makes a triangle mesh from a polygon (one sided) void MakeTriMesh(const Polygon3D& geom,TriMesh& mesh) { mesh.verts = geom.vertices; mesh.tris.resize(geom.vertices.size()-2); for(size_t i=0;i+2<geom.vertices.size();i++) mesh.tris[i].set(0,i+1,i+2); } ///makes a triangle mesh from a generic geometric primitive void MakeTriMesh(const GeometricPrimitive3D& geom,TriMesh& mesh,int numDivs) { switch(geom.type) { case GeometricPrimitive3D::Point: mesh.verts.resize(1); mesh.verts[0] = *AnyCast_Raw<Point3D>(&geom.data); mesh.tris.resize(0); break; case GeometricPrimitive3D::Segment: //make a degenerate mesh mesh.verts.resize(2); mesh.verts[0] = AnyCast_Raw<Segment3D>(&geom.data)->a; mesh.verts[1] = AnyCast_Raw<Segment3D>(&geom.data)->b; mesh.tris.resize(1); mesh.tris[0].set(0,1,1); break; case GeometricPrimitive3D::Triangle: MakeTriMesh(*AnyCast_Raw<Triangle3D>(&geom.data),mesh); break; case GeometricPrimitive3D::Polygon: MakeTriMesh(*AnyCast_Raw<Polygon3D>(&geom.data),mesh); break; case GeometricPrimitive3D::Box: MakeTriMesh(*AnyCast_Raw<Box3D>(&geom.data),mesh); break; case GeometricPrimitive3D::Cylinder: MakeTriMesh(*AnyCast_Raw<Cylinder3D>(&geom.data),numDivs,mesh); break; case GeometricPrimitive3D::Sphere: MakeTriMesh(*AnyCast_Raw<Sphere3D>(&geom.data),numDivs/2,numDivs,mesh); break; case GeometricPrimitive3D::Ellipsoid: MakeTriMesh(*AnyCast_Raw<Ellipsoid3D>(&geom.data),numDivs,numDivs,mesh); break; case GeometricPrimitive3D::AABB: MakeTriMesh(*AnyCast_Raw<AABB3D>(&geom.data),mesh); break; default: FatalError("Invalid primitive type %d for MakeTriMesh",geom.type); } } } //namespace Meshing <|endoftext|>
<commit_before>#include "minifluxapi.h" #include <curl/curl.h> #include <json-c/json.h> #include <thread> #include "3rd-party/json.hpp" #include "logger.h" #include "remoteapi.h" #include "rss/feed.h" #include "strprintf.h" #include "utils.h" using json = nlohmann::json; using HTTPMethod = newsboat::utils::HTTPMethod; namespace newsboat { MinifluxApi::MinifluxApi(ConfigContainer* c) : RemoteApi(c) { server = cfg->get_configvalue("miniflux-url"); } MinifluxApi::~MinifluxApi() {} bool MinifluxApi::authenticate() { // error check handled in Controller const Credentials creds = get_credentials("miniflux", ""); auth_info = strprintf::fmt("%s:%s", creds.user, creds.pass); return true; } TaggedFeedUrl MinifluxApi::feed_from_json(const json& jfeed, const std::vector<std::string>& addtags) { const int feed_id = jfeed["id"]; const std::string str_feed_id = std::to_string(feed_id); const std::string feed_title = jfeed["title"]; const std::string feed_url = jfeed["feed_url"]; std::vector<std::string> tags; // automatically tag by feedtitle tags.push_back(std::string("~") + feed_title); // add additional tags tags.insert(tags.end(), addtags.cbegin(), addtags.cend()); return TaggedFeedUrl(str_feed_id, tags); } std::vector<TaggedFeedUrl> MinifluxApi::get_subscribed_urls() { std::vector<TaggedFeedUrl> feeds; const json categories = run_op("/v1/categories", json()); std::map<int, std::string> category_names; for (const auto& category : categories) { std::string name = category["title"]; int id = category["id"]; category_names[id] = name; } const json feed_list = run_op("/v1/feeds", json()); if (feed_list.is_null()) { LOG(Level::ERROR, "MinifluxApi::get_subscribed_urls: Failed to " "retrieve feedlist"); return feeds; } for (const json& feed : feed_list) { const int category_id = feed["category"]["id"]; std::vector<std::string> tags; if (category_id > 0) { tags.push_back(category_names[category_id]); } feeds.push_back(feed_from_json(feed, tags)); } return feeds; } bool MinifluxApi::mark_all_read(const std::string& id) { // TODO create Miniflux PR to add endpoint for marking all entries in feed // as read const rsspp::Feed feed = fetch_feed(id, nullptr); std::vector<std::string> guids; for (const auto& item : feed.items) { guids.push_back(item.guid); } json args; args["status"] = "read"; return update_articles(guids, args); } bool MinifluxApi::mark_article_read(const std::string& guid, bool read) { // Do this in a thread, as we don't care about the result enough to wait // for it. std::thread t{[=]() { LOG(Level::DEBUG, "MinifluxApi::mark_article_read: inside thread, marking " "article as read..."); // Call the MinifluxApi's update_article function as a thread. json args; args["status"] = read ? "read" : "unread"; this->update_article(guid, args); }}; t.detach(); return true; } bool MinifluxApi::flag_changed(const std::string& oldflags, const std::string& newflags, const std::string& flagstr) { if (flagstr.length() == 0) { return false; } const char flag = flagstr[0]; const char* oldptr = strchr(oldflags.c_str(), flag); const char* newptr = strchr(newflags.c_str(), flag); if (oldptr == nullptr && newptr != nullptr) { return true; } if (oldptr != nullptr && newptr == nullptr) { return true; } return false; } bool MinifluxApi::update_article_flags(const std::string& oldflags, const std::string& newflags, const std::string& guid) { const std::string star_flag = cfg->get_configvalue("miniflux-flag-star"); const bool starred_flag_changed = flag_changed(oldflags, newflags, star_flag); bool success = true; if (starred_flag_changed) { success = toggle_star_article(guid); } return success; } rsspp::Feed MinifluxApi::fetch_feed(const std::string& id, CURL* cached_handle) { rsspp::Feed feed; feed.rss_version = rsspp::Feed::MINIFLUX_JSON; const std::string query = strprintf::fmt("/v1/feeds/%s/entries?order=published_at&direction=desc", id); const json content = run_op(query, json(), HTTPMethod::GET, cached_handle); if (content.is_null()) { return feed; } const json entries = content["entries"]; if (!entries.is_array()) { LOG(Level::ERROR, "MinifluxApi::fetch_feed: items is not an array"); return feed; } LOG(Level::DEBUG, "MinifluxApi::fetch_feed: %" PRIu64 " items", static_cast<uint64_t>(entries.size())); try { for (const auto& entry : entries) { rsspp::Item item; if (!entry["title"].is_null()) { item.title = entry["title"]; } if (!entry["url"].is_null()) { item.link = entry["url"]; } if (!entry["author"].is_null()) { item.author = entry["author"]; } if (!entry["content"].is_null()) { item.content_encoded = entry["content"]; } const int entry_id = entry["id"]; item.guid = std::to_string(entry_id); item.pubDate = entry["published_at"]; const std::string status = entry["status"]; if (status == "unread") { item.labels.push_back("miniflux:unread"); } else { item.labels.push_back("miniflux:read"); } feed.items.push_back(item); } } catch (json::exception& e) { LOG(Level::ERROR, "Exception occurred while parsing feeed: ", e.what()); } std::sort(feed.items.begin(), feed.items.end(), [](const rsspp::Item& a, const rsspp::Item& b) { return a.pubDate_ts > b.pubDate_ts; }); return feed; } void MinifluxApi::add_custom_headers(curl_slist** /* custom_headers */) { // nothing required } json MinifluxApi::run_op(const std::string& path, const json& args, const HTTPMethod method, /* = GET */ CURL* cached_handle /* = nullptr */) { const std::string url = server + path; std::string* body = nullptr; std::string arg_dump; if (!args.empty()) { arg_dump = args.dump(); body = &arg_dump; } const std::string result = utils::retrieve_url( url, cfg, auth_info, body, method, cached_handle); LOG(Level::DEBUG, "MinifluxApi::run_op(%s %s,...): body=%s reply = %s", utils::http_method_str(method), path, arg_dump, result); json content; if (result.length() > 0) { try { content = json::parse(result); } catch (json::parse_error& e) { LOG(Level::ERROR, "MinifluxApi::run_op: reply failed to parse: %s", result); content = json(nullptr); } } return content; } bool MinifluxApi::toggle_star_article(const std::string& guid) { const std::string query = strprintf::fmt("/v1/entries/%s/bookmark", guid); const json content = run_op(query, json(), HTTPMethod::PUT); return content.is_null(); } bool MinifluxApi::update_articles(const std::vector<std::string> guids, json& args) { std::vector<int> entry_ids; for (const std::string& guid : guids) { entry_ids.push_back(std::stoi(guid)); } args["entry_ids"] = entry_ids; const json content = run_op("/v1/entries", args, HTTPMethod::PUT); return content.is_null(); } bool MinifluxApi::update_article(const std::string& guid, json& args) { std::vector<std::string> guids; guids.push_back(guid); return update_articles(guids, args); } } // namespace newsboat <commit_msg>Use .empty() instead of .length()<commit_after>#include "minifluxapi.h" #include <curl/curl.h> #include <json-c/json.h> #include <thread> #include "3rd-party/json.hpp" #include "logger.h" #include "remoteapi.h" #include "rss/feed.h" #include "strprintf.h" #include "utils.h" using json = nlohmann::json; using HTTPMethod = newsboat::utils::HTTPMethod; namespace newsboat { MinifluxApi::MinifluxApi(ConfigContainer* c) : RemoteApi(c) { server = cfg->get_configvalue("miniflux-url"); } MinifluxApi::~MinifluxApi() {} bool MinifluxApi::authenticate() { // error check handled in Controller const Credentials creds = get_credentials("miniflux", ""); auth_info = strprintf::fmt("%s:%s", creds.user, creds.pass); return true; } TaggedFeedUrl MinifluxApi::feed_from_json(const json& jfeed, const std::vector<std::string>& addtags) { const int feed_id = jfeed["id"]; const std::string str_feed_id = std::to_string(feed_id); const std::string feed_title = jfeed["title"]; const std::string feed_url = jfeed["feed_url"]; std::vector<std::string> tags; // automatically tag by feedtitle tags.push_back(std::string("~") + feed_title); // add additional tags tags.insert(tags.end(), addtags.cbegin(), addtags.cend()); return TaggedFeedUrl(str_feed_id, tags); } std::vector<TaggedFeedUrl> MinifluxApi::get_subscribed_urls() { std::vector<TaggedFeedUrl> feeds; const json categories = run_op("/v1/categories", json()); std::map<int, std::string> category_names; for (const auto& category : categories) { std::string name = category["title"]; int id = category["id"]; category_names[id] = name; } const json feed_list = run_op("/v1/feeds", json()); if (feed_list.is_null()) { LOG(Level::ERROR, "MinifluxApi::get_subscribed_urls: Failed to " "retrieve feedlist"); return feeds; } for (const json& feed : feed_list) { const int category_id = feed["category"]["id"]; std::vector<std::string> tags; if (category_id > 0) { tags.push_back(category_names[category_id]); } feeds.push_back(feed_from_json(feed, tags)); } return feeds; } bool MinifluxApi::mark_all_read(const std::string& id) { // TODO create Miniflux PR to add endpoint for marking all entries in feed // as read const rsspp::Feed feed = fetch_feed(id, nullptr); std::vector<std::string> guids; for (const auto& item : feed.items) { guids.push_back(item.guid); } json args; args["status"] = "read"; return update_articles(guids, args); } bool MinifluxApi::mark_article_read(const std::string& guid, bool read) { // Do this in a thread, as we don't care about the result enough to wait // for it. std::thread t{[=]() { LOG(Level::DEBUG, "MinifluxApi::mark_article_read: inside thread, marking " "article as read..."); // Call the MinifluxApi's update_article function as a thread. json args; args["status"] = read ? "read" : "unread"; this->update_article(guid, args); }}; t.detach(); return true; } bool MinifluxApi::flag_changed(const std::string& oldflags, const std::string& newflags, const std::string& flagstr) { if (flagstr.length() == 0) { return false; } const char flag = flagstr[0]; const char* oldptr = strchr(oldflags.c_str(), flag); const char* newptr = strchr(newflags.c_str(), flag); if (oldptr == nullptr && newptr != nullptr) { return true; } if (oldptr != nullptr && newptr == nullptr) { return true; } return false; } bool MinifluxApi::update_article_flags(const std::string& oldflags, const std::string& newflags, const std::string& guid) { const std::string star_flag = cfg->get_configvalue("miniflux-flag-star"); const bool starred_flag_changed = flag_changed(oldflags, newflags, star_flag); bool success = true; if (starred_flag_changed) { success = toggle_star_article(guid); } return success; } rsspp::Feed MinifluxApi::fetch_feed(const std::string& id, CURL* cached_handle) { rsspp::Feed feed; feed.rss_version = rsspp::Feed::MINIFLUX_JSON; const std::string query = strprintf::fmt("/v1/feeds/%s/entries?order=published_at&direction=desc", id); const json content = run_op(query, json(), HTTPMethod::GET, cached_handle); if (content.is_null()) { return feed; } const json entries = content["entries"]; if (!entries.is_array()) { LOG(Level::ERROR, "MinifluxApi::fetch_feed: items is not an array"); return feed; } LOG(Level::DEBUG, "MinifluxApi::fetch_feed: %" PRIu64 " items", static_cast<uint64_t>(entries.size())); try { for (const auto& entry : entries) { rsspp::Item item; if (!entry["title"].is_null()) { item.title = entry["title"]; } if (!entry["url"].is_null()) { item.link = entry["url"]; } if (!entry["author"].is_null()) { item.author = entry["author"]; } if (!entry["content"].is_null()) { item.content_encoded = entry["content"]; } const int entry_id = entry["id"]; item.guid = std::to_string(entry_id); item.pubDate = entry["published_at"]; const std::string status = entry["status"]; if (status == "unread") { item.labels.push_back("miniflux:unread"); } else { item.labels.push_back("miniflux:read"); } feed.items.push_back(item); } } catch (json::exception& e) { LOG(Level::ERROR, "Exception occurred while parsing feeed: ", e.what()); } std::sort(feed.items.begin(), feed.items.end(), [](const rsspp::Item& a, const rsspp::Item& b) { return a.pubDate_ts > b.pubDate_ts; }); return feed; } void MinifluxApi::add_custom_headers(curl_slist** /* custom_headers */) { // nothing required } json MinifluxApi::run_op(const std::string& path, const json& args, const HTTPMethod method, /* = GET */ CURL* cached_handle /* = nullptr */) { const std::string url = server + path; std::string* body = nullptr; std::string arg_dump; if (!args.empty()) { arg_dump = args.dump(); body = &arg_dump; } const std::string result = utils::retrieve_url( url, cfg, auth_info, body, method, cached_handle); LOG(Level::DEBUG, "MinifluxApi::run_op(%s %s,...): body=%s reply = %s", utils::http_method_str(method), path, arg_dump, result); json content; if (!result.empty()) { try { content = json::parse(result); } catch (json::parse_error& e) { LOG(Level::ERROR, "MinifluxApi::run_op: reply failed to parse: %s", result); content = json(nullptr); } } return content; } bool MinifluxApi::toggle_star_article(const std::string& guid) { const std::string query = strprintf::fmt("/v1/entries/%s/bookmark", guid); const json content = run_op(query, json(), HTTPMethod::PUT); return content.is_null(); } bool MinifluxApi::update_articles(const std::vector<std::string> guids, json& args) { std::vector<int> entry_ids; for (const std::string& guid : guids) { entry_ids.push_back(std::stoi(guid)); } args["entry_ids"] = entry_ids; const json content = run_op("/v1/entries", args, HTTPMethod::PUT); return content.is_null(); } bool MinifluxApi::update_article(const std::string& guid, json& args) { std::vector<std::string> guids; guids.push_back(guid); return update_articles(guids, args); } } // namespace newsboat <|endoftext|>
<commit_before>/** MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com> Copyright (C) 2011 Far McKon <[email protected]>, Hugo Boyer ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. */ #include <iostream> #include <string> #include <stdlib.h> #include <stdint.h> #include "mgl/abstractable.h" #include "mgl/configuration.h" #include "mgl/miracle.h" #include "libthing/Vector2.h" #include "optionparser.h" #include "mgl/log.h" using namespace std; using namespace mgl; /// Extends options::Arg to specifiy limitations on arguments struct Arg: public option::Arg { static void printError(const char* msg1, const option::Option& opt, const char* msg2) { fprintf(stderr, "%s", msg1); fwrite(opt.name, opt.namelen, 1, stderr); fprintf(stderr, "%s", msg2); } static option::ArgStatus Unknown(const option::Option& option, bool msg) { if (msg) printError("Unknown option '", option, "'\n"); return option::ARG_ILLEGAL; } static option::ArgStatus Required(const option::Option& option, bool msg) { if (option.arg != 0) return option::ARG_OK; if (msg) printError("Option '", option, "' requires an argument\n"); return option::ARG_ILLEGAL; } static option::ArgStatus NonEmpty(const option::Option& option, bool msg) { if (option.arg != 0 && option.arg[0] != 0) return option::ARG_OK; if (msg) printError("Option '", option, "' requires a non-empty argument\n"); return option::ARG_ILLEGAL; } static option::ArgStatus Numeric(const option::Option& option, bool msg) { char* endptr = 0; if (option.arg != 0 && strtod(option.arg, &endptr)){}; if (endptr != option.arg && *endptr == 0) return option::ARG_OK; if (msg) printError("Option '", option, "' requires a numeric argument\n"); return option::ARG_ILLEGAL; } }; // all ID's of the options we expect enum optionIndex {UNKNOWN, HELP, CONFIG, FIRST_Z,LAYER_H,LAYER_W, FILL_ANGLE, FILL_DENSITY, N_SHELLS, BOTTOM_SLICE_IDX, TOP_SLICE_IDX, DEBUG_ME, START_GCODE, END_GCODE, OUT_FILENAME}; // options descriptor table const option::Descriptor usageDescriptor[] = { {UNKNOWN, 0, "", "",Arg::None, "miracle-grue [OPTIONS] FILE.STL \n\n" "Options:" }, {HELP, 0,"", "help",Arg::None, " --help \tPrint usage and exit." }, {CONFIG, 1,"c", "config", Arg::NonEmpty, "-c \tconfig data in a config.json file." "(default is local miracle.config)" }, {FIRST_Z, 2,"f", "firstLayerZ", Arg::Numeric, "-f \tfirst layer height (mm)" }, {LAYER_H, 3,"h", "layerH", Arg::Numeric, " -h \tgeneral layer height(mm)" }, {LAYER_W, 4,"w", "layerW", Arg::Numeric, " -w \tlayer width(mm)" }, { FILL_ANGLE, 5, "a","angle", Arg::Numeric, " -a \tinfill grid inter slice angle(radians)" }, { FILL_DENSITY, 6, "p", "density", Arg::Numeric, " -p \tapprox infill density(percent), aka rho aka p" }, { N_SHELLS, 7, "n", "nShells", Arg::Numeric, " -n \tnumber of shells per layer" }, { BOTTOM_SLICE_IDX, 8, "b", "bottomIdx", Arg::Numeric, " -b \tbottom slice index" }, { TOP_SLICE_IDX, 9, "t", "topIdx", Arg::Numeric, " -t \ttop slice index" }, { DEBUG_ME, 10, "d", "debug", Arg::Numeric, " -d \tdebug level, 0 to 99. 60 is 'info'" }, { START_GCODE, 11, "s", "header", Arg::NonEmpty, " -s \tstart gcode file" }, { END_GCODE, 12, "e", "footer", Arg::NonEmpty, " -e \tend gcode file" }, { OUT_FILENAME, 13, "o", "outFilename", Arg::NonEmpty, " -o \twrite gcode to specific filename (defaults to <model>.gcode" }, {0,0,0,0,0,0}, }; void usage() { cout << endl; cout << "It is pitch black. You are likely to be eaten by a grue." << endl; cout << "You are using " << GRUE_PROGRAM_NAME << " version " << GRUE_VERSION << endl; cout << endl; cout << "This program translates a 3d model file in STL format to GCODE toolpath for a " << endl; cout << "3D printer." << " Another fine MakerBot Industries product!"<< endl; cout << endl; option::printUsage(std::cout, usageDescriptor); Log::severe() <<" Log level::severe "; Log::info()<<"::info"; Log::fine() <<"::fine"; Log::finer() <<"::finer"; Log::finest() <<"::finest"; cout << endl; } int newParseArgs( Configuration &config, int argc, char *argv[], string &modelFile, int &firstSliceIdx, int &lastSliceIdx) { string configFilename = ""; argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present option::Stats stats(usageDescriptor, argc, argv); option::Option* options = new option::Option[stats.options_max]; option::Option* buffer = new option::Option[stats.buffer_max]; option::Parser parse(usageDescriptor, argc, argv, options, buffer); if (parse.error()) return -20; if (options[HELP] || argc == 0) { usage(); exit(0); } ///read config file and/or help option first if ( options[CONFIG]) { configFilename = string(options[CONFIG].arg); } // fallback to default config if (configFilename.compare(string("")) == 0) configFilename = "miracle.config"; config.readFromFile(configFilename); for (int i = 0; i < parse.optionsCount(); ++i) { option::Option& opt = buffer[i]; fprintf(stdout, "Argument #%d name %s is #%s\n", i, opt.desc->longopt, opt.arg ); switch (opt.index()) { case LAYER_H: case LAYER_W: case FILL_ANGLE: case FILL_DENSITY: case N_SHELLS: case BOTTOM_SLICE_IDX: case TOP_SLICE_IDX: case FIRST_Z: config["slicer"][opt.desc->longopt] = atof(opt.arg); break; case DEBUG_ME: config["meta"][opt.desc->longopt] = atof(opt.arg); break; case START_GCODE: case END_GCODE: case OUT_FILENAME: config["gcoder"][opt.desc->longopt] = opt.arg; break; case CONFIG: // handled above before other config values break; case HELP: // not possible, because handled further above and exits the program default: break; } } /// handle parameters (not options!) if ( parse.nonOptionsCount() == 0) { usage(); } else if ( parse.nonOptionsCount() != 1) { Log::severe() << "too many parameters" << endl; for (int i = 0; i < parse.nonOptionsCount(); ++i) Log::severe() << "Parameter #" << i << ": " << parse.nonOption(i) << "\n"; exit(-10); } else { //handle the unnamed parameter separately modelFile = parse.nonOption(0); Log::finer() << "filename " << modelFile << endl; ifstream testmodel(modelFile.c_str(), ifstream::in); if (testmodel.fail()) { usage(); throw mgl::Exception(("Invalid model file [" + modelFile + "]").c_str()); exit(-10); } } firstSliceIdx = -1; lastSliceIdx = -1; // [programName] and [versionStr] are always hard-code overwritten config["programName"] = GRUE_PROGRAM_NAME; config["versionStr"] = GRUE_VERSION; config["firmware"] = "unknown"; /// convert debug data to a module/level specific setting g_debugVerbosity = log_verbosity_unset; if ( config["meta"].isMember("debug") ) { try { uint32_t debugLvl = config["meta"]["debug"].asUInt(); if ( debugLvl < 90 ) g_debugVerbosity = log_finest; else if ( debugLvl < 80 ) g_debugVerbosity = log_finer; else if ( debugLvl < 70 ) g_debugVerbosity = log_fine; else if ( debugLvl < 60 ) g_debugVerbosity = log_info; else if ( debugLvl < 10 ) g_debugVerbosity = log_severe; else g_debugVerbosity = log_verbosity_unset; } catch (...){ cout << "fail sauce on debug level" << endl; // passed -d sans option. Assume default dbg level g_debugVerbosity = log_default_level; } } return 0; } int main(int argc, char *argv[], char *[]) // envp { string modelFile; Configuration config; try { int firstSliceIdx, lastSliceIdx; int ret = newParseArgs(config, argc, argv, modelFile, firstSliceIdx, lastSliceIdx); if(ret != 0){ usage(); exit(ret); } // cout << config.asJson() << endl; Log::finer() << "Tube spacing: " << config["slicer"]["tubeSpacing"] << endl; MyComputer computer; Log::fine() << endl << endl; Log::fine() << "behold!" << endl; Log::fine() << "Materialization of \"" << modelFile << "\" has begun at " << computer.clock.now() << endl; std::string scadFile = "."; // outDir scadFile += computer.fileSystem.getPathSeparatorCharacter(); scadFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".scad" ); std::string gcodeFile = config["gcoder"]["outFilename"].asString(); if (gcodeFile.empty()) { gcodeFile = "."; gcodeFile += computer.fileSystem.getPathSeparatorCharacter(); gcodeFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".gcode" ); } Log::fine() << endl << endl; Log::fine() << modelFile << " to \"" << gcodeFile << "\" and \"" << scadFile << "\"" << endl; GCoderConfig gcoderCfg; loadGCoderConfigFromFile(config, gcoderCfg); SlicerConfig slicerCfg; loadSlicerConfigFromFile(config, slicerCfg); const char* scad = NULL; if (scadFile.size() > 0 ) scad = scadFile.c_str(); Tomograph tomograph; Regions regions; std::vector<mgl::SliceData> slices; ProgressLog log; miracleGrue(gcoderCfg, slicerCfg, modelFile.c_str(), scad, gcodeFile.c_str(), firstSliceIdx, lastSliceIdx, tomograph, regions, slices, &log); } catch(mgl::Exception &mixup) { Log::severe() << "ERROR: "<< mixup.error << endl; return -1; } exit(EXIT_SUCCESS); } <commit_msg>tubeSpacing hasn't been an option for a while<commit_after>/** MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com> Copyright (C) 2011 Far McKon <[email protected]>, Hugo Boyer ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. */ #include <iostream> #include <string> #include <stdlib.h> #include <stdint.h> #include "mgl/abstractable.h" #include "mgl/configuration.h" #include "mgl/miracle.h" #include "libthing/Vector2.h" #include "optionparser.h" #include "mgl/log.h" using namespace std; using namespace mgl; /// Extends options::Arg to specifiy limitations on arguments struct Arg: public option::Arg { static void printError(const char* msg1, const option::Option& opt, const char* msg2) { fprintf(stderr, "%s", msg1); fwrite(opt.name, opt.namelen, 1, stderr); fprintf(stderr, "%s", msg2); } static option::ArgStatus Unknown(const option::Option& option, bool msg) { if (msg) printError("Unknown option '", option, "'\n"); return option::ARG_ILLEGAL; } static option::ArgStatus Required(const option::Option& option, bool msg) { if (option.arg != 0) return option::ARG_OK; if (msg) printError("Option '", option, "' requires an argument\n"); return option::ARG_ILLEGAL; } static option::ArgStatus NonEmpty(const option::Option& option, bool msg) { if (option.arg != 0 && option.arg[0] != 0) return option::ARG_OK; if (msg) printError("Option '", option, "' requires a non-empty argument\n"); return option::ARG_ILLEGAL; } static option::ArgStatus Numeric(const option::Option& option, bool msg) { char* endptr = 0; if (option.arg != 0 && strtod(option.arg, &endptr)){}; if (endptr != option.arg && *endptr == 0) return option::ARG_OK; if (msg) printError("Option '", option, "' requires a numeric argument\n"); return option::ARG_ILLEGAL; } }; // all ID's of the options we expect enum optionIndex {UNKNOWN, HELP, CONFIG, FIRST_Z,LAYER_H,LAYER_W, FILL_ANGLE, FILL_DENSITY, N_SHELLS, BOTTOM_SLICE_IDX, TOP_SLICE_IDX, DEBUG_ME, START_GCODE, END_GCODE, OUT_FILENAME}; // options descriptor table const option::Descriptor usageDescriptor[] = { {UNKNOWN, 0, "", "",Arg::None, "miracle-grue [OPTIONS] FILE.STL \n\n" "Options:" }, {HELP, 0,"", "help",Arg::None, " --help \tPrint usage and exit." }, {CONFIG, 1,"c", "config", Arg::NonEmpty, "-c \tconfig data in a config.json file." "(default is local miracle.config)" }, {FIRST_Z, 2,"f", "firstLayerZ", Arg::Numeric, "-f \tfirst layer height (mm)" }, {LAYER_H, 3,"h", "layerH", Arg::Numeric, " -h \tgeneral layer height(mm)" }, {LAYER_W, 4,"w", "layerW", Arg::Numeric, " -w \tlayer width(mm)" }, { FILL_ANGLE, 5, "a","angle", Arg::Numeric, " -a \tinfill grid inter slice angle(radians)" }, { FILL_DENSITY, 6, "p", "density", Arg::Numeric, " -p \tapprox infill density(percent), aka rho aka p" }, { N_SHELLS, 7, "n", "nShells", Arg::Numeric, " -n \tnumber of shells per layer" }, { BOTTOM_SLICE_IDX, 8, "b", "bottomIdx", Arg::Numeric, " -b \tbottom slice index" }, { TOP_SLICE_IDX, 9, "t", "topIdx", Arg::Numeric, " -t \ttop slice index" }, { DEBUG_ME, 10, "d", "debug", Arg::Numeric, " -d \tdebug level, 0 to 99. 60 is 'info'" }, { START_GCODE, 11, "s", "header", Arg::NonEmpty, " -s \tstart gcode file" }, { END_GCODE, 12, "e", "footer", Arg::NonEmpty, " -e \tend gcode file" }, { OUT_FILENAME, 13, "o", "outFilename", Arg::NonEmpty, " -o \twrite gcode to specific filename (defaults to <model>.gcode" }, {0,0,0,0,0,0}, }; void usage() { cout << endl; cout << "It is pitch black. You are likely to be eaten by a grue." << endl; cout << "You are using " << GRUE_PROGRAM_NAME << " version " << GRUE_VERSION << endl; cout << endl; cout << "This program translates a 3d model file in STL format to GCODE toolpath for a " << endl; cout << "3D printer." << " Another fine MakerBot Industries product!"<< endl; cout << endl; option::printUsage(std::cout, usageDescriptor); Log::severe() <<" Log level::severe "; Log::info()<<"::info"; Log::fine() <<"::fine"; Log::finer() <<"::finer"; Log::finest() <<"::finest"; cout << endl; } int newParseArgs( Configuration &config, int argc, char *argv[], string &modelFile, int &firstSliceIdx, int &lastSliceIdx) { string configFilename = ""; argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present option::Stats stats(usageDescriptor, argc, argv); option::Option* options = new option::Option[stats.options_max]; option::Option* buffer = new option::Option[stats.buffer_max]; option::Parser parse(usageDescriptor, argc, argv, options, buffer); if (parse.error()) return -20; if (options[HELP] || argc == 0) { usage(); exit(0); } ///read config file and/or help option first if ( options[CONFIG]) { configFilename = string(options[CONFIG].arg); } // fallback to default config if (configFilename.compare(string("")) == 0) configFilename = "miracle.config"; config.readFromFile(configFilename); for (int i = 0; i < parse.optionsCount(); ++i) { option::Option& opt = buffer[i]; fprintf(stdout, "Argument #%d name %s is #%s\n", i, opt.desc->longopt, opt.arg ); switch (opt.index()) { case LAYER_H: case LAYER_W: case FILL_ANGLE: case FILL_DENSITY: case N_SHELLS: case BOTTOM_SLICE_IDX: case TOP_SLICE_IDX: case FIRST_Z: config["slicer"][opt.desc->longopt] = atof(opt.arg); break; case DEBUG_ME: config["meta"][opt.desc->longopt] = atof(opt.arg); break; case START_GCODE: case END_GCODE: case OUT_FILENAME: config["gcoder"][opt.desc->longopt] = opt.arg; break; case CONFIG: // handled above before other config values break; case HELP: // not possible, because handled further above and exits the program default: break; } } /// handle parameters (not options!) if ( parse.nonOptionsCount() == 0) { usage(); } else if ( parse.nonOptionsCount() != 1) { Log::severe() << "too many parameters" << endl; for (int i = 0; i < parse.nonOptionsCount(); ++i) Log::severe() << "Parameter #" << i << ": " << parse.nonOption(i) << "\n"; exit(-10); } else { //handle the unnamed parameter separately modelFile = parse.nonOption(0); Log::finer() << "filename " << modelFile << endl; ifstream testmodel(modelFile.c_str(), ifstream::in); if (testmodel.fail()) { usage(); throw mgl::Exception(("Invalid model file [" + modelFile + "]").c_str()); exit(-10); } } firstSliceIdx = -1; lastSliceIdx = -1; // [programName] and [versionStr] are always hard-code overwritten config["programName"] = GRUE_PROGRAM_NAME; config["versionStr"] = GRUE_VERSION; config["firmware"] = "unknown"; /// convert debug data to a module/level specific setting g_debugVerbosity = log_verbosity_unset; if ( config["meta"].isMember("debug") ) { try { uint32_t debugLvl = config["meta"]["debug"].asUInt(); if ( debugLvl < 90 ) g_debugVerbosity = log_finest; else if ( debugLvl < 80 ) g_debugVerbosity = log_finer; else if ( debugLvl < 70 ) g_debugVerbosity = log_fine; else if ( debugLvl < 60 ) g_debugVerbosity = log_info; else if ( debugLvl < 10 ) g_debugVerbosity = log_severe; else g_debugVerbosity = log_verbosity_unset; } catch (...){ cout << "fail sauce on debug level" << endl; // passed -d sans option. Assume default dbg level g_debugVerbosity = log_default_level; } } return 0; } int main(int argc, char *argv[], char *[]) // envp { string modelFile; Configuration config; try { int firstSliceIdx, lastSliceIdx; int ret = newParseArgs(config, argc, argv, modelFile, firstSliceIdx, lastSliceIdx); if(ret != 0){ usage(); exit(ret); } // cout << config.asJson() << endl; MyComputer computer; Log::fine() << endl << endl; Log::fine() << "behold!" << endl; Log::fine() << "Materialization of \"" << modelFile << "\" has begun at " << computer.clock.now() << endl; std::string scadFile = "."; // outDir scadFile += computer.fileSystem.getPathSeparatorCharacter(); scadFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".scad" ); std::string gcodeFile = config["gcoder"]["outFilename"].asString(); if (gcodeFile.empty()) { gcodeFile = "."; gcodeFile += computer.fileSystem.getPathSeparatorCharacter(); gcodeFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".gcode" ); } Log::fine() << endl << endl; Log::fine() << modelFile << " to \"" << gcodeFile << "\" and \"" << scadFile << "\"" << endl; GCoderConfig gcoderCfg; loadGCoderConfigFromFile(config, gcoderCfg); SlicerConfig slicerCfg; loadSlicerConfigFromFile(config, slicerCfg); const char* scad = NULL; if (scadFile.size() > 0 ) scad = scadFile.c_str(); Tomograph tomograph; Regions regions; std::vector<mgl::SliceData> slices; ProgressLog log; miracleGrue(gcoderCfg, slicerCfg, modelFile.c_str(), scad, gcodeFile.c_str(), firstSliceIdx, lastSliceIdx, tomograph, regions, slices, &log); } catch(mgl::Exception &mixup) { Log::severe() << "ERROR: "<< mixup.error << endl; return -1; } exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ //===- kernel_creator.cc ----------------------------------------*- C++ -*-===// // // This file implements the function to compile a TF kernel function to gpu // binary (hsaco for AMD, cubin for NVIDIA) or to a gpu binary with host side. // //===----------------------------------------------------------------------===// #include "tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h" #include "llvm/Support/raw_ostream.h" #include "mlir/Conversion/AffineToStandard/AffineToStandard.h" // from @llvm-project #include "mlir/Conversion/GPUCommon/GPUCommonPass.h" // from @llvm-project #include "mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h" // from @llvm-project #include "mlir/Conversion/SCFToGPU/SCFToGPUPass.h" // from @llvm-project #include "mlir/Conversion/SCFToStandard/SCFToStandard.h" // from @llvm-project #include "mlir/Dialect/GPU/GPUDialect.h" // from @llvm-project #include "mlir/Dialect/GPU/ParallelLoopMapper.h" // from @llvm-project #include "mlir/Dialect/GPU/Passes.h" // from @llvm-project #include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project #include "mlir/Dialect/LLVMIR/NVVMDialect.h" // from @llvm-project #include "mlir/Dialect/Linalg/Passes.h" // from @llvm-project #include "mlir/Dialect/SCF/Passes.h" // from @llvm-project #include "mlir/Dialect/SCF/SCF.h" // from @llvm-project #include "mlir/Dialect/SCF/Transforms.h" // from @llvm-project #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/Parser.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Pass/PassManager.h" // from @llvm-project #include "mlir/Transforms/Bufferize.h" // from @llvm-project #include "mlir/Transforms/DialectConversion.h" // from @llvm-project #include "mlir/Transforms/Passes.h" // from @llvm-project #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/dialect_registration.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" #include "tensorflow/compiler/mlir/xla/transforms/passes.h" #include "tensorflow/compiler/xla/service/mlir_gpu/kernel_lowering.h" #include "tensorflow/compiler/xla/service/mlir_gpu/passes.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/path.h" namespace tensorflow { namespace kernel_gen { namespace { using tensorflow::Status; using xla::InternalError; using xla::StatusOr; constexpr llvm::StringRef kGpuBinaryAttrName = "gpu.binary"; Status LowerTFtoGPU(mlir::ModuleOp module, bool gpu_binary_only, llvm::ArrayRef<uint32_t> tile_sizes, llvm::ArrayRef<uint32_t> unroll_factors) { mlir::PassManager pm(module.getContext()); applyTensorflowAndCLOptions(pm); if (gpu_binary_only) { pm.addPass(mlir::mhlo::createLegalizeTFPass( /*allow_partial_conversion=*/false, /*legalize_chlo=*/true)); pm.addNestedPass<mlir::FuncOp>( mlir::kernel_gen::transforms::CreateMaterializeBroadcastsPass()); pm.addNestedPass<mlir::FuncOp>( mlir::kernel_gen::transforms::CreateUnfuseBatchNormPass()); pm.addPass(mlir::mhlo::createLegalizeToLhloPass( /*results_escape_functions=*/true)); // Moving `AllocOp`s and inserting missing `DeallocOp`s pm.addPass(::mlir::createBufferPlacementPass()); pm.addNestedPass<mlir::FuncOp>(mlir::createCopyRemovalPass()); pm.addPass(mlir::kernel_gen::transforms::CreateShapeToDescriptorsPass()); } else { pm.addPass(mlir::mhlo::createLegalizeTFPass( /*allow_partial_conversion=*/false, /*legalize_chlo=*/false)); pm.addPass(mlir::mhlo::createChloLegalizeToHloPass()); pm.addPass(mlir::createTransformUnrankedHloPass()); pm.addPass(mlir::kernel_gen::transforms::CreateShapeToDescriptorsPass()); // Clean up the IR created above. In particular, operations on descriptors // are simplified here. pm.addPass(mlir::createCanonicalizerPass()); pm.addPass(mlir::kernel_gen::transforms::CreateBufferizePass()); pm.addPass(mlir::kernel_gen::transforms::CreateParallelLoopsToSequential()); } // Clean up the IR for further processing. pm.addPass(mlir::createCanonicalizerPass()); // We have to anticipate later unrolling in tiling to make sure that we get // the requested tiling after unrolling. Compute the new tiling here if // needed. llvm::SmallVector<unsigned, 4> tiling_for_unrolling; llvm::SmallVector<int64_t, 4> as_int64; if (!unroll_factors.empty()) { tiling_for_unrolling.reserve(tile_sizes.size()); for (auto pair : llvm::zip(tile_sizes, unroll_factors)) { tiling_for_unrolling.push_back(std::get<0>(pair) * std::get<1>(pair)); as_int64.push_back(std::get<1>(pair)); } } else { tiling_for_unrolling.append(tile_sizes.begin(), tile_sizes.end()); } // Transform LHLO operations to LinAlg. pm.addPass(::mlir::lmhlo::createLegalizeLhloToLinalgPass()); // Fuse linalg operations. pm.addPass(::mlir::lmhlo::createLhloFuseLinalgPass( /*use_parallel_loops=*/true, tiling_for_unrolling)); // Transform the Linalg operations inside of the loop nest into parallel // loops. pm.addPass(::mlir::createConvertLinalgToParallelLoopsPass()); // Canonicalize the code to simplify index computations. This is needed so // that loop bounds have the same value. pm.addNestedPass<::mlir::FuncOp>(::mlir::createCanonicalizerPass()); pm.addNestedPass<::mlir::FuncOp>(::mlir::createCSEPass()); // Fuse the inner-most loops. pm.addPass(xla::mlir_gpu::createFuseInnerParallelLoopsPass()); // Run CSE to ensure that loads and stores to the same subview get // recognized as such. pm.addNestedPass<::mlir::FuncOp>(::mlir::createCSEPass()); // Forward stores to buffers to loads. pm.addPass(xla::mlir_gpu::createStoreForwardingPass()); // Remove now unused temporary buffers. pm.addPass(xla::mlir_gpu::createDeadTempBufferRemovalPass()); if (!unroll_factors.empty()) { pm.addPass(::mlir::createParallelLoopTilingPass(as_int64)); } // Some basic cleanup. pm.addNestedPass<::mlir::FuncOp>(::mlir::createCanonicalizerPass()); pm.addNestedPass<::mlir::FuncOp>(::mlir::createCSEPass()); // Greedily map the remaining loop to GPU hardware dimensions. pm.addPass(xla::mlir_gpu::createMapParallelLoopsPass()); // Apply the mapping. pm.addPass(mlir::createParallelLoopToGpuPass()); // Embed TF Framework ops. if (!gpu_binary_only) { pm.addPass(mlir::kernel_gen::tf_framework::CreateEmbedTFFrameworkPass()); } // Some basic cleanup. pm.addNestedPass<::mlir::FuncOp>(::mlir::createCanonicalizerPass()); pm.addNestedPass<::mlir::FuncOp>(::mlir::createCSEPass()); // Make loops with min bounds into a conditional plus static bounds. // Only do this if we unrolled in the first place. if (!unroll_factors.empty()) { pm.addNestedPass<::mlir::FuncOp>(mlir::createForLoopSpecializationPass()); } // Approximate Tanh using standard operations. pm.addNestedPass<::mlir::FuncOp>( ::mlir::mhlo::createLegalizeTrigonometricToApproximationPass()); // Take launches to launches with kernels. pm.addPass(::mlir::createGpuKernelOutliningPass()); if (gpu_binary_only) { // Make kernel signature deterministic so that we can call it externally. pm.addPass(xla::mlir_gpu::createRewriteKernelSignaturePass()); } pm.addPass(::mlir::createLowerAffinePass()); pm.addPass(::mlir::createLowerToCFGPass()); if (failed(pm.run(module))) { return InternalError("Lowering to GPU kernels failed."); } return Status::OK(); } Status LowerGPUToLLVM(mlir::ModuleOp module, bool gpu_binary_only, llvm::ArrayRef<uint32_t> same_shape, llvm::StringRef gpu_binary_attr_name, llvm::ArrayRef<std::string> architectures, bool generate_fatbin) { mlir::PassManager pm(module.getContext()); applyTensorflowAndCLOptions(pm); auto& kernel_pm = pm.nest<mlir::gpu::GPUModuleOp>(); if (gpu_binary_only) { // Grab the original signature from the single function. kernel_pm.addNestedPass<mlir::LLVM::LLVMFuncOp>( mlir::kernel_gen::transforms::CreatePropagateTensorFlowABIKnowledgePass( same_shape)); } kernel_pm.addPass(mlir::createStripDebugInfoPass()); kernel_pm.addPass(mlir::kernel_gen::transforms::CreateGpuKernelToBlobPass( gpu_binary_attr_name, architectures, generate_fatbin)); if (!gpu_binary_only) { pm.addPass(mlir::kernel_gen::transforms::CreateTFKernelToLLVMPass()); pm.addPass(mlir::createCanonicalizerPass()); pm.addPass(mlir::createCSEPass()); } return failed(pm.run(module)) ? InternalError("Lowering to LLVM IR failed.") : Status::OK(); } } // namespace StatusOr<mlir::OwningModuleRef> GenerateKernelForTfCode( mlir::MLIRContext& context, llvm::StringRef tf_code, bool gpu_binary_only, llvm::ArrayRef<std::string> architectures, llvm::ArrayRef<uint32_t> tile_sizes, llvm::ArrayRef<uint32_t> same_shape, llvm::ArrayRef<uint32_t> unroll_factors, bool generate_fatbin) { mlir::RegisterAllTensorFlowDialects(context.getDialectRegistry()); mlir::OwningModuleRef module = mlir::parseSourceString(tf_code, &context); TF_RETURN_IF_ERROR( LowerTFtoGPU(module.get(), gpu_binary_only, tile_sizes, unroll_factors)); #if !defined(TENSORFLOW_USE_ROCM) && !defined(GOOGLE_CUDA) return InternalError( "Neither TENSORFLOW_USE_ROCM nor GOOGLE_CUDA are defined." " Did you specify either --config=rocm or --config=cuda ?"); #endif #if TENSORFLOW_USE_ROCM TF_RETURN_IF_ERROR(xla::mlir_gpu::LowerKernelBodiesToROCDL(module.get())); #elif GOOGLE_CUDA TF_RETURN_IF_ERROR(xla::mlir_gpu::LowerKernelBodiesToNVVM(module.get())); #endif TF_RETURN_IF_ERROR(LowerGPUToLLVM(module.get(), gpu_binary_only, same_shape, kGpuBinaryAttrName, architectures, generate_fatbin)); return module; } StatusOr<std::string> ExtractGpuBinary(mlir::ModuleOp module) { auto gpu_modules = module.getOps<mlir::gpu::GPUModuleOp>(); if (std::distance(gpu_modules.begin(), gpu_modules.end()) != 1) { return InternalError("There should be exactly one GPU Module"); } mlir::gpu::GPUModuleOp gpu_mod = *gpu_modules.begin(); auto blob = gpu_mod.getAttrOfType<mlir::StringAttr>(kGpuBinaryAttrName); if (blob == nullptr) { return InternalError("No binary blob found in the module"); } return blob.getValue().str(); } } // namespace kernel_gen } // namespace tensorflow <commit_msg>Reorder kernel gen passes.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ //===- kernel_creator.cc ----------------------------------------*- C++ -*-===// // // This file implements the function to compile a TF kernel function to gpu // binary (hsaco for AMD, cubin for NVIDIA) or to a gpu binary with host side. // //===----------------------------------------------------------------------===// #include "tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h" #include "llvm/Support/raw_ostream.h" #include "mlir/Conversion/AffineToStandard/AffineToStandard.h" // from @llvm-project #include "mlir/Conversion/GPUCommon/GPUCommonPass.h" // from @llvm-project #include "mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h" // from @llvm-project #include "mlir/Conversion/SCFToGPU/SCFToGPUPass.h" // from @llvm-project #include "mlir/Conversion/SCFToStandard/SCFToStandard.h" // from @llvm-project #include "mlir/Dialect/GPU/GPUDialect.h" // from @llvm-project #include "mlir/Dialect/GPU/ParallelLoopMapper.h" // from @llvm-project #include "mlir/Dialect/GPU/Passes.h" // from @llvm-project #include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project #include "mlir/Dialect/LLVMIR/NVVMDialect.h" // from @llvm-project #include "mlir/Dialect/Linalg/Passes.h" // from @llvm-project #include "mlir/Dialect/SCF/Passes.h" // from @llvm-project #include "mlir/Dialect/SCF/SCF.h" // from @llvm-project #include "mlir/Dialect/SCF/Transforms.h" // from @llvm-project #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/Parser.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Pass/PassManager.h" // from @llvm-project #include "mlir/Transforms/Bufferize.h" // from @llvm-project #include "mlir/Transforms/DialectConversion.h" // from @llvm-project #include "mlir/Transforms/Passes.h" // from @llvm-project #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/dialect_registration.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" #include "tensorflow/compiler/mlir/xla/transforms/passes.h" #include "tensorflow/compiler/xla/service/mlir_gpu/kernel_lowering.h" #include "tensorflow/compiler/xla/service/mlir_gpu/passes.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/path.h" namespace tensorflow { namespace kernel_gen { namespace { using tensorflow::Status; using xla::InternalError; using xla::StatusOr; constexpr llvm::StringRef kGpuBinaryAttrName = "gpu.binary"; Status LowerTFtoGPU(mlir::ModuleOp module, bool gpu_binary_only, llvm::ArrayRef<uint32_t> tile_sizes, llvm::ArrayRef<uint32_t> unroll_factors) { mlir::PassManager pm(module.getContext()); applyTensorflowAndCLOptions(pm); if (gpu_binary_only) { pm.addPass(mlir::mhlo::createLegalizeTFPass( /*allow_partial_conversion=*/false, /*legalize_chlo=*/true)); pm.addNestedPass<mlir::FuncOp>( mlir::kernel_gen::transforms::CreateMaterializeBroadcastsPass()); pm.addNestedPass<mlir::FuncOp>( mlir::kernel_gen::transforms::CreateUnfuseBatchNormPass()); pm.addPass(mlir::mhlo::createLegalizeToLhloPass( /*results_escape_functions=*/true)); // Moving `AllocOp`s and inserting missing `DeallocOp`s pm.addPass(::mlir::createBufferPlacementPass()); pm.addNestedPass<mlir::FuncOp>(mlir::createCopyRemovalPass()); pm.addPass(mlir::kernel_gen::transforms::CreateShapeToDescriptorsPass()); } else { pm.addPass(mlir::mhlo::createLegalizeTFPass( /*allow_partial_conversion=*/false, /*legalize_chlo=*/false)); pm.addPass(mlir::createTransformUnrankedHloPass()); pm.addPass(mlir::mhlo::createChloLegalizeToHloPass()); pm.addPass(mlir::kernel_gen::transforms::CreateShapeToDescriptorsPass()); // Clean up the IR created above. In particular, operations on descriptors // are simplified here. pm.addPass(mlir::createCanonicalizerPass()); pm.addPass(mlir::kernel_gen::transforms::CreateBufferizePass()); pm.addPass(mlir::kernel_gen::transforms::CreateParallelLoopsToSequential()); } // Clean up the IR for further processing. pm.addPass(mlir::createCanonicalizerPass()); // We have to anticipate later unrolling in tiling to make sure that we get // the requested tiling after unrolling. Compute the new tiling here if // needed. llvm::SmallVector<unsigned, 4> tiling_for_unrolling; llvm::SmallVector<int64_t, 4> as_int64; if (!unroll_factors.empty()) { tiling_for_unrolling.reserve(tile_sizes.size()); for (auto pair : llvm::zip(tile_sizes, unroll_factors)) { tiling_for_unrolling.push_back(std::get<0>(pair) * std::get<1>(pair)); as_int64.push_back(std::get<1>(pair)); } } else { tiling_for_unrolling.append(tile_sizes.begin(), tile_sizes.end()); } // Transform LHLO operations to LinAlg. pm.addPass(::mlir::lmhlo::createLegalizeLhloToLinalgPass()); // Fuse linalg operations. pm.addPass(::mlir::lmhlo::createLhloFuseLinalgPass( /*use_parallel_loops=*/true, tiling_for_unrolling)); // Transform the Linalg operations inside of the loop nest into parallel // loops. pm.addPass(::mlir::createConvertLinalgToParallelLoopsPass()); // Canonicalize the code to simplify index computations. This is needed so // that loop bounds have the same value. pm.addNestedPass<::mlir::FuncOp>(::mlir::createCanonicalizerPass()); pm.addNestedPass<::mlir::FuncOp>(::mlir::createCSEPass()); // Fuse the inner-most loops. pm.addPass(xla::mlir_gpu::createFuseInnerParallelLoopsPass()); // Run CSE to ensure that loads and stores to the same subview get // recognized as such. pm.addNestedPass<::mlir::FuncOp>(::mlir::createCSEPass()); // Forward stores to buffers to loads. pm.addPass(xla::mlir_gpu::createStoreForwardingPass()); // Remove now unused temporary buffers. pm.addPass(xla::mlir_gpu::createDeadTempBufferRemovalPass()); if (!unroll_factors.empty()) { pm.addPass(::mlir::createParallelLoopTilingPass(as_int64)); } // Some basic cleanup. pm.addNestedPass<::mlir::FuncOp>(::mlir::createCanonicalizerPass()); pm.addNestedPass<::mlir::FuncOp>(::mlir::createCSEPass()); // Greedily map the remaining loop to GPU hardware dimensions. pm.addPass(xla::mlir_gpu::createMapParallelLoopsPass()); // Apply the mapping. pm.addPass(mlir::createParallelLoopToGpuPass()); // Embed TF Framework ops. if (!gpu_binary_only) { pm.addPass(mlir::kernel_gen::tf_framework::CreateEmbedTFFrameworkPass()); } // Some basic cleanup. pm.addNestedPass<::mlir::FuncOp>(::mlir::createCanonicalizerPass()); pm.addNestedPass<::mlir::FuncOp>(::mlir::createCSEPass()); // Make loops with min bounds into a conditional plus static bounds. // Only do this if we unrolled in the first place. if (!unroll_factors.empty()) { pm.addNestedPass<::mlir::FuncOp>(mlir::createForLoopSpecializationPass()); } // Approximate Tanh using standard operations. pm.addNestedPass<::mlir::FuncOp>( ::mlir::mhlo::createLegalizeTrigonometricToApproximationPass()); // Take launches to launches with kernels. pm.addPass(::mlir::createGpuKernelOutliningPass()); if (gpu_binary_only) { // Make kernel signature deterministic so that we can call it externally. pm.addPass(xla::mlir_gpu::createRewriteKernelSignaturePass()); } pm.addPass(::mlir::createLowerAffinePass()); pm.addPass(::mlir::createLowerToCFGPass()); if (failed(pm.run(module))) { return InternalError("Lowering to GPU kernels failed."); } return Status::OK(); } Status LowerGPUToLLVM(mlir::ModuleOp module, bool gpu_binary_only, llvm::ArrayRef<uint32_t> same_shape, llvm::StringRef gpu_binary_attr_name, llvm::ArrayRef<std::string> architectures, bool generate_fatbin) { mlir::PassManager pm(module.getContext()); applyTensorflowAndCLOptions(pm); auto& kernel_pm = pm.nest<mlir::gpu::GPUModuleOp>(); if (gpu_binary_only) { // Grab the original signature from the single function. kernel_pm.addNestedPass<mlir::LLVM::LLVMFuncOp>( mlir::kernel_gen::transforms::CreatePropagateTensorFlowABIKnowledgePass( same_shape)); } kernel_pm.addPass(mlir::createStripDebugInfoPass()); kernel_pm.addPass(mlir::kernel_gen::transforms::CreateGpuKernelToBlobPass( gpu_binary_attr_name, architectures, generate_fatbin)); if (!gpu_binary_only) { pm.addPass(mlir::kernel_gen::transforms::CreateTFKernelToLLVMPass()); pm.addPass(mlir::createCanonicalizerPass()); pm.addPass(mlir::createCSEPass()); } return failed(pm.run(module)) ? InternalError("Lowering to LLVM IR failed.") : Status::OK(); } } // namespace StatusOr<mlir::OwningModuleRef> GenerateKernelForTfCode( mlir::MLIRContext& context, llvm::StringRef tf_code, bool gpu_binary_only, llvm::ArrayRef<std::string> architectures, llvm::ArrayRef<uint32_t> tile_sizes, llvm::ArrayRef<uint32_t> same_shape, llvm::ArrayRef<uint32_t> unroll_factors, bool generate_fatbin) { mlir::RegisterAllTensorFlowDialects(context.getDialectRegistry()); mlir::OwningModuleRef module = mlir::parseSourceString(tf_code, &context); TF_RETURN_IF_ERROR( LowerTFtoGPU(module.get(), gpu_binary_only, tile_sizes, unroll_factors)); #if !defined(TENSORFLOW_USE_ROCM) && !defined(GOOGLE_CUDA) return InternalError( "Neither TENSORFLOW_USE_ROCM nor GOOGLE_CUDA are defined." " Did you specify either --config=rocm or --config=cuda ?"); #endif #if TENSORFLOW_USE_ROCM TF_RETURN_IF_ERROR(xla::mlir_gpu::LowerKernelBodiesToROCDL(module.get())); #elif GOOGLE_CUDA TF_RETURN_IF_ERROR(xla::mlir_gpu::LowerKernelBodiesToNVVM(module.get())); #endif TF_RETURN_IF_ERROR(LowerGPUToLLVM(module.get(), gpu_binary_only, same_shape, kGpuBinaryAttrName, architectures, generate_fatbin)); return module; } StatusOr<std::string> ExtractGpuBinary(mlir::ModuleOp module) { auto gpu_modules = module.getOps<mlir::gpu::GPUModuleOp>(); if (std::distance(gpu_modules.begin(), gpu_modules.end()) != 1) { return InternalError("There should be exactly one GPU Module"); } mlir::gpu::GPUModuleOp gpu_mod = *gpu_modules.begin(); auto blob = gpu_mod.getAttrOfType<mlir::StringAttr>(kGpuBinaryAttrName); if (blob == nullptr) { return InternalError("No binary blob found in the module"); } return blob.getValue().str(); } } // namespace kernel_gen } // namespace tensorflow <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/perv/p10_clock_test.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2021 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p10_clock_test.C /// /// @brief Test to see if the ref clock is valid. //------------------------------------------------------------------------------ // *HWP HW Maintainer : Anusha Reddy ([email protected]) // *HWP FW Maintainer : Raja Das ([email protected]) // *HWP Consumed by : FSP //------------------------------------------------------------------------------ #include "p10_clock_test.H" #include "p9_perv_scom_addresses.H" #include "p9_perv_scom_addresses_fld.H" enum P10_CLOCK_TEST_Private_Constants { HW_NS_DELAY = 20, // unit is nano seconds SIM_CYCLE_DELAY = 1000, // unit is sim cycles POLL_COUNT = 10 }; static fapi2::ReturnCode p10_clock_test_latches( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, bool set_rcs_clock_test_in); fapi2::ReturnCode p10_clock_test(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip) { fapi2::buffer<uint32_t> l_data32; FAPI_INF("p10_clock_test: Entering ..."); FAPI_DBG("unfence input wires to register 281D"); FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL0_FSI, l_data32)); l_data32.clearBit<PERV_ROOT_CTRL0_FENCE0_DC>(); FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_FSI, l_data32)); FAPI_DBG("unfence input wires to register 291D "); FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI, l_data32)); l_data32.clearBit<PERV_ROOT_CTRL0_FENCE0_DC>(); FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI, l_data32)); for(int i = 0; i < POLL_COUNT; i++) { FAPI_DBG("Set input valuse to clock test latches - RCS_CLOCK_TEST_IN = 1"); FAPI_TRY(p10_clock_test_latches(i_target_chip, true)); FAPI_DBG("Set input valuse to clock test latches - RCS_CLOCK_TEST_IN = 0"); FAPI_TRY(p10_clock_test_latches(i_target_chip, false)); } FAPI_INF("p10_clock_test: Exiting ..."); fapi_try_exit: return fapi2::current_err; } /// @brief Verify that latches clocked by input clocks transported input value to output /// /// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target /// @param[in] bool RCS_CLOCK_TEST_IN /// @return FAPI2_RC_SUCCESS if success, else error code. static fapi2::ReturnCode p10_clock_test_latches( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, bool set_rcs_clock_test_in) { fapi2::buffer<uint32_t> l_data32; uint8_t l_cp_refclck_select; bool check_clockA; bool check_clockB; FAPI_INF("p10_clock_test_latches: Entering ..."); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CP_REFCLOCK_SELECT, i_target_chip, l_cp_refclck_select), "Error from FAPI_ATTR_GET (ATTR_CP_REFCLOCK_SELECT)"); l_data32.flush<0>().setBit<4>(); FAPI_TRY(fapi2::putCfamRegister(i_target_chip, set_rcs_clock_test_in ? PERV_ROOT_CTRL5_SET_FSI : PERV_ROOT_CTRL5_CLEAR_FSI, l_data32)); fapi2::delay(HW_NS_DELAY, SIM_CYCLE_DELAY); FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SNS1LTH_FSI, l_data32)); check_clockA = set_rcs_clock_test_in ? (l_data32.getBit<0>() == 1) : (l_data32.getBit<0>() == 0) ; check_clockB = set_rcs_clock_test_in ? (l_data32.getBit<1>() == 1) : (l_data32.getBit<1>() == 0) ; if (! (l_cp_refclck_select == fapi2::ENUM_ATTR_CP_REFCLOCK_SELECT_OSC1)) { FAPI_ASSERT(check_clockA, fapi2::CLOCK_TEST_OUT_RCS_ERR() .set_READ_SNS1LTH(l_data32) .set_ATTR_CP_REFCLOCK_SELECT_VALUE(l_cp_refclck_select) .set_RCS_CLOCK_TEST_IN(set_rcs_clock_test_in), "Clock A is bad"); } if (! (l_cp_refclck_select == fapi2::ENUM_ATTR_CP_REFCLOCK_SELECT_OSC0)) { FAPI_ASSERT(check_clockB, fapi2::CLOCK_TEST_OUT_RCS_ERR() .set_READ_SNS1LTH(l_data32) .set_ATTR_CP_REFCLOCK_SELECT_VALUE(l_cp_refclck_select) .set_RCS_CLOCK_TEST_IN(set_rcs_clock_test_in), "Clock B is bad"); } FAPI_INF("p10_clock_test_latches: Exiting ..."); fapi_try_exit: return fapi2::current_err; } <commit_msg>IPL istep HWP updates<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/perv/p10_clock_test.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2021 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p10_clock_test.C /// /// @brief Test to see if the ref clock is valid. //------------------------------------------------------------------------------ // *HWP HW Maintainer : Anusha Reddy ([email protected]) // *HWP FW Maintainer : Raja Das ([email protected]) // *HWP Consumed by : FSP //------------------------------------------------------------------------------ #include "p10_clock_test.H" #include "p9_perv_scom_addresses.H" #include "p9_perv_scom_addresses_fld.H" enum P10_CLOCK_TEST_Private_Constants { HW_NS_DELAY = 20, // unit is nano seconds SIM_CYCLE_DELAY = 1000, // unit is sim cycles POLL_COUNT = 10 }; static fapi2::ReturnCode p10_clock_test_latches( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, bool set_rcs_clock_test_in); fapi2::ReturnCode p10_clock_test(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip) { fapi2::buffer<uint32_t> l_data32; FAPI_INF("p10_clock_test: Entering ..."); FAPI_DBG("unfence input wires to register 2810"); FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL0_FSI, l_data32)); l_data32.clearBit<PERV_ROOT_CTRL0_FENCE0_DC>(); FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_FSI, l_data32)); FAPI_DBG("unfence input wires to register 2910"); FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI, l_data32)); l_data32.clearBit<PERV_ROOT_CTRL0_FENCE0_DC>(); FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI, l_data32)); for(int i = 0; i < POLL_COUNT; i++) { FAPI_DBG("Set input valuse to clock test latches - RCS_CLOCK_TEST_IN = 1"); FAPI_TRY(p10_clock_test_latches(i_target_chip, true)); FAPI_DBG("Set input valuse to clock test latches - RCS_CLOCK_TEST_IN = 0"); FAPI_TRY(p10_clock_test_latches(i_target_chip, false)); } FAPI_INF("p10_clock_test: Exiting ..."); fapi_try_exit: return fapi2::current_err; } /// @brief Verify that latches clocked by input clocks transported input value to output /// /// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target /// @param[in] bool RCS_CLOCK_TEST_IN /// @return FAPI2_RC_SUCCESS if success, else error code. static fapi2::ReturnCode p10_clock_test_latches( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, bool set_rcs_clock_test_in) { fapi2::buffer<uint32_t> l_data32; uint8_t l_cp_refclck_select; bool check_clockA; bool check_clockB; FAPI_INF("p10_clock_test_latches: Entering ..."); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CP_REFCLOCK_SELECT, i_target_chip, l_cp_refclck_select), "Error from FAPI_ATTR_GET (ATTR_CP_REFCLOCK_SELECT)"); l_data32.flush<0>().setBit<3>(); FAPI_TRY(fapi2::putCfamRegister(i_target_chip, set_rcs_clock_test_in ? PERV_ROOT_CTRL5_SET_FSI : PERV_ROOT_CTRL5_CLEAR_FSI, l_data32)); fapi2::delay(HW_NS_DELAY, SIM_CYCLE_DELAY); FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SNS1LTH_FSI, l_data32)); check_clockA = set_rcs_clock_test_in ? (l_data32.getBit<4>() == 1) : (l_data32.getBit<4>() == 0) ; check_clockB = set_rcs_clock_test_in ? (l_data32.getBit<5>() == 1) : (l_data32.getBit<5>() == 0) ; if (! (l_cp_refclck_select == fapi2::ENUM_ATTR_CP_REFCLOCK_SELECT_OSC1)) { FAPI_ASSERT(check_clockA, fapi2::CLOCK_TEST_OUT_RCS_ERR() .set_READ_SNS1LTH(l_data32) .set_ATTR_CP_REFCLOCK_SELECT_VALUE(l_cp_refclck_select) .set_RCS_CLOCK_TEST_IN(set_rcs_clock_test_in), "Clock A is bad"); } if (! (l_cp_refclck_select == fapi2::ENUM_ATTR_CP_REFCLOCK_SELECT_OSC0)) { FAPI_ASSERT(check_clockB, fapi2::CLOCK_TEST_OUT_RCS_ERR() .set_READ_SNS1LTH(l_data32) .set_ATTR_CP_REFCLOCK_SELECT_VALUE(l_cp_refclck_select) .set_RCS_CLOCK_TEST_IN(set_rcs_clock_test_in), "Clock B is bad"); } FAPI_INF("p10_clock_test_latches: Exiting ..."); fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>#include "matrices.h" namespace BuiltInFunctions { namespace MatrixFunctions{ namespace { MatrixSum matrixSum; } RpnOperand MatrixSum::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator); QList<QList<Number> > matrix1 = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); QList<QList<Number> > matrix2 = RpnVector::toTwoDimensional(actualArguments.at(1).value.value<RpnVector>()); MathUtils::ensureMatrix(matrix1); MathUtils::ensureMatrix(matrix2); if (matrix1.first().size() != matrix2.first().size()) { THROW(ENotSameSizeMatrices()); } QList<QList<Number> > sum; for (int i = 0; i < matrix1.size(); ++i) { sum << MathUtils::addVectorToVector(matrix1.at(i), matrix2.at(i)); } RpnVector result = RpnVector::fromTwoDimensional(sum); return RpnOperand(RpnOperandVector, QVariant::fromValue(result)); } QList<RpnArgument> MatrixSum::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector) << RpnArgument(RpnOperandVector); return arguments; } namespace { MatrixDiff matrixDiff; } RpnOperand MatrixDiff::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator); QList<QList<Number> > matrix1 = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); QList<QList<Number> > matrix2 = RpnVector::toTwoDimensional(actualArguments.at(1).value.value<RpnVector>()); MathUtils::ensureMatrix(matrix1); MathUtils::ensureMatrix(matrix2); if (matrix1.first().size() != matrix2.first().size()) { THROW(ENotSameSizeMatrices()); } QList<QList<Number> > diff; for (int i = 0; i < matrix1.size(); ++i) { diff << MathUtils::subtractVectorFromVector(matrix1.at(i), matrix2.at(i)); } RpnVector result = RpnVector::fromTwoDimensional(diff); return RpnOperand(RpnOperandVector, QVariant::fromValue(result)); } QList<RpnArgument> MatrixDiff::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector) << RpnArgument(RpnOperandVector); return arguments; } namespace { MatrixTrace matrixTrace; } RpnOperand MatrixTrace::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator); QList<QList<Number> > matrix = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); MathUtils::ensureSquareMatrix(matrix); Number sum = 0.0; for (int i = 0; i < matrix.size(); ++i) { sum += matrix.at(i).at(i); } return RpnOperand(RpnOperandNumber, QVariant::fromValue(sum)); } QList<RpnArgument> MatrixTrace::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector); return arguments; } namespace { MatrixMultiply matrixMultiply; } RpnOperand MatrixMultiply::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator); QList<QList<Number> > matrix1 = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); QList<QList<Number> > matrix2 = RpnVector::toTwoDimensional(actualArguments.at(1).value.value<RpnVector>()); MathUtils::ensureMatrix(matrix1); MathUtils::ensureMatrix(matrix2); if (matrix1.first().size() != matrix2.size()) { THROW(ENotCorrespondingMatricesSizes()); } QList<QList<Number> > product; int columnsCount = matrix2.first().size(); int rowsCount = matrix1.size(); int sameSize = matrix2.size(); for (int i = 0; i < rowsCount; i++) { QList<Number> row; for (int j = 0; j < columnsCount; j++) { Number element = 0; for (int k = 0; k < sameSize; k++) { element += matrix1.at(i).at(k) * matrix2.at(k).at(j); } row << element; } product << row; } RpnVector result = RpnVector::fromTwoDimensional(product); return RpnOperand(RpnOperandVector, QVariant::fromValue(result)); } QList<RpnArgument> MatrixMultiply::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector) << RpnArgument(RpnOperandVector); return arguments; } namespace { // MatrixNormM matrixNormM; } namespace { // MatrixNormN matrixNormN; } namespace { MatrixNormFrobenius matrixNormFrobenius; } RpnOperand MatrixNormFrobenius::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator) QList<QList<Number> > matrix = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); MathUtils::ensureMatrix(matrix); Number result = 0.0; foreach (const QList<Number> &row, matrix) { foreach (Number element, row) { result += element * element; } } result = qSqrt(result); return RpnOperand(RpnOperandNumber, QVariant::fromValue(result)); } QList<RpnArgument> MatrixNormFrobenius::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector); return arguments; } } // namespaces } <commit_msg>L- and M- norms calculation<commit_after>#include "matrices.h" namespace BuiltInFunctions { namespace MatrixFunctions{ namespace { MatrixSum matrixSum; } RpnOperand MatrixSum::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator); QList<QList<Number> > matrix1 = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); QList<QList<Number> > matrix2 = RpnVector::toTwoDimensional(actualArguments.at(1).value.value<RpnVector>()); MathUtils::ensureMatrix(matrix1); MathUtils::ensureMatrix(matrix2); if (matrix1.first().size() != matrix2.first().size()) { THROW(ENotSameSizeMatrices()); } QList<QList<Number> > sum; for (int i = 0; i < matrix1.size(); ++i) { sum << MathUtils::addVectorToVector(matrix1.at(i), matrix2.at(i)); } RpnVector result = RpnVector::fromTwoDimensional(sum); return RpnOperand(RpnOperandVector, QVariant::fromValue(result)); } QList<RpnArgument> MatrixSum::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector) << RpnArgument(RpnOperandVector); return arguments; } namespace { MatrixDiff matrixDiff; } RpnOperand MatrixDiff::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator); QList<QList<Number> > matrix1 = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); QList<QList<Number> > matrix2 = RpnVector::toTwoDimensional(actualArguments.at(1).value.value<RpnVector>()); MathUtils::ensureMatrix(matrix1); MathUtils::ensureMatrix(matrix2); if (matrix1.first().size() != matrix2.first().size()) { THROW(ENotSameSizeMatrices()); } QList<QList<Number> > diff; for (int i = 0; i < matrix1.size(); ++i) { diff << MathUtils::subtractVectorFromVector(matrix1.at(i), matrix2.at(i)); } RpnVector result = RpnVector::fromTwoDimensional(diff); return RpnOperand(RpnOperandVector, QVariant::fromValue(result)); } QList<RpnArgument> MatrixDiff::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector) << RpnArgument(RpnOperandVector); return arguments; } namespace { MatrixTrace matrixTrace; } RpnOperand MatrixTrace::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator); QList<QList<Number> > matrix = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); MathUtils::ensureSquareMatrix(matrix); Number sum = 0.0; for (int i = 0; i < matrix.size(); ++i) { sum += matrix.at(i).at(i); } return RpnOperand(RpnOperandNumber, QVariant::fromValue(sum)); } QList<RpnArgument> MatrixTrace::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector); return arguments; } namespace { MatrixMultiply matrixMultiply; } RpnOperand MatrixMultiply::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator); QList<QList<Number> > matrix1 = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); QList<QList<Number> > matrix2 = RpnVector::toTwoDimensional(actualArguments.at(1).value.value<RpnVector>()); MathUtils::ensureMatrix(matrix1); MathUtils::ensureMatrix(matrix2); if (matrix1.first().size() != matrix2.size()) { THROW(ENotCorrespondingMatricesSizes()); } QList<QList<Number> > product; int columnsCount = matrix2.first().size(); int rowsCount = matrix1.size(); int sameSize = matrix2.size(); for (int i = 0; i < rowsCount; i++) { QList<Number> row; for (int j = 0; j < columnsCount; j++) { Number element = 0; for (int k = 0; k < sameSize; k++) { element += matrix1.at(i).at(k) * matrix2.at(k).at(j); } row << element; } product << row; } RpnVector result = RpnVector::fromTwoDimensional(product); return RpnOperand(RpnOperandVector, QVariant::fromValue(result)); } QList<RpnArgument> MatrixMultiply::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector) << RpnArgument(RpnOperandVector); return arguments; } namespace { MatrixNormM matrixNormM; } RpnOperand MatrixNormM::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator) QList<QList<Number> > matrix = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); MathUtils::ensureMatrix(matrix); Number result = 0.0; for (int i = 0; i < matrix.size(); i++) { Number sum = 0.0; foreach (Number element, matrix.at(i)) { sum += element; } // First line, remember it for comparsion if (i == 0) { result = sum; } else { if (sum > result) { result = sum; } } } return RpnOperand(RpnOperandNumber, QVariant::fromValue(result)); } QList<RpnArgument> MatrixNormM::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector); return arguments; } namespace { MatrixNormL matrixNormL; } RpnOperand MatrixNormL::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator) QList<QList<Number> > matrix = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); MathUtils::ensureMatrix(matrix); Number result = 0.0; for (int i = 0; i < matrix.first().size(); i++) { Number sum = 0.0; for (int j = 0; j < matrix.size(); j++) { sum += matrix.at(j).at(i); } // First column, remember it for comparsion if (i == 0) { result = sum; } else { if (sum > result) { result = sum; } } } return RpnOperand(RpnOperandNumber, QVariant::fromValue(result)); } QList<RpnArgument> MatrixNormL::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector); return arguments; } namespace { MatrixNormFrobenius matrixNormFrobenius; } RpnOperand MatrixNormFrobenius::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { Q_UNUSED(calculator) QList<QList<Number> > matrix = RpnVector::toTwoDimensional(actualArguments.at(0).value.value<RpnVector>()); MathUtils::ensureMatrix(matrix); Number result = 0.0; foreach (const QList<Number> &row, matrix) { foreach (Number element, row) { result += element * element; } } result = qSqrt(result); return RpnOperand(RpnOperandNumber, QVariant::fromValue(result)); } QList<RpnArgument> MatrixNormFrobenius::requiredArguments() { QList<RpnArgument> arguments; arguments << RpnArgument(RpnOperandVector); return arguments; } } // namespaces } <|endoftext|>
<commit_before>#ifndef SPECTER_TABLE_HPP #define SPECTER_TABLE_HPP #include "View.hpp" #include "ScrollView.hpp" #include "TextView.hpp" #include <array> namespace specter { #define SPECTER_TABLE_MAX_ROWS 128ul enum class SortDirection { None, Ascending, Descending }; struct ITableDataBinding { virtual size_t columnCount() const=0; virtual size_t rowCount() const=0; virtual std::string_view header(size_t cIdx) const {return nullptr;} virtual std::string_view cell(size_t cIdx, size_t rIdx) const {return nullptr;} }; struct ITableStateBinding { virtual float getColumnSplit(size_t cIdx) const {return -1.0;} virtual bool columnSplitResizeAllowed() const {return false;} virtual void setColumnSplit(size_t cIdx, float split) {} virtual SortDirection getSort(size_t& cIdx) const {cIdx = 0; return SortDirection::None;} virtual void setSort(size_t cIdx, SortDirection dir) {} virtual void setSelectedRow(size_t rIdx) {} virtual void rowActivated(size_t rIdx) {} }; class Table : public View { ITableDataBinding* m_data; ITableStateBinding* m_state; size_t m_maxColumns; size_t m_rows = 0; size_t m_columns = 0; size_t m_selectedRow = -1; size_t m_deferredActivation = -1; size_t m_clickFrames = 15; struct CellView : public View { Table& m_t; std::unique_ptr<TextView> m_text; size_t m_c, m_r; boo::SWindowRect m_scissorRect; uint64_t m_textHash = 0; CellView(Table& t, ViewResources& res); bool m_selected = false; void select(); void deselect(); void reset(); bool reset(size_t c); bool reset(size_t c, size_t r); void mouseDown(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseUp(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseEnter(const boo::SWindowCoord&); void mouseLeave(const boo::SWindowCoord&); void resized(const boo::SWindowRect& root, const boo::SWindowRect& sub, const boo::SWindowRect& scissor); void draw(boo::IGraphicsCommandQueue* gfxQ); }; std::vector<ViewChild<std::unique_ptr<CellView>>> m_headerViews; using ColumnPool = std::array<std::array<ViewChild<std::unique_ptr<CellView>>, SPECTER_TABLE_MAX_ROWS>, 2>; std::vector<ColumnPool> m_cellPools; size_t m_ensuredRows = 0; std::vector<ColumnPool>& ensureCellPools(size_t rows, size_t cols, ViewResources& res); size_t m_activePool = -1; bool m_header = false; std::vector<boo::SWindowRect> m_hCellRects; size_t m_hDraggingIdx = 0; std::unique_ptr<SolidShaderVert[]> m_hVerts; VertexBufferBindingSolid m_vertsBinding; void _setHeaderVerts(const boo::SWindowRect& rect); std::vector<boo::SWindowRect> getCellRects(const boo::SWindowRect& tableRect) const; ViewChild<std::unique_ptr<ScrollView>> m_scroll; struct RowsView : public View { Table& m_t; std::unique_ptr<SolidShaderVert[]> m_verts; VertexBufferBindingSolid m_vertsBinding; size_t m_visibleStart = 0; size_t m_visibleRows = 0; boo::SWindowRect m_scissorRect; void _setRowVerts(const boo::SWindowRect& rowsRect, const boo::SWindowRect& scissor); RowsView(Table& t, ViewResources& res); int nominalHeight() const; int nominalWidth() const {return m_t.m_scroll.m_view->nominalWidth();} void mouseDown(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseUp(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseMove(const boo::SWindowCoord&); void mouseLeave(const boo::SWindowCoord&); void resized(const boo::SWindowRect& root, const boo::SWindowRect& sub, const boo::SWindowRect& scissor); void draw(boo::IGraphicsCommandQueue* gfxQ); } m_rowsView; bool m_headerNeedsUpdate = false; bool m_inSelectRow = false; void _updateData(); public: Table(ViewResources& res, View& parentView, ITableDataBinding* data, ITableStateBinding* state=nullptr, size_t maxColumns=8); void cycleSortColumn(size_t c); void selectRow(size_t r); void setMultiplyColor(const zeus::CColor& color); void mouseDown(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseUp(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseMove(const boo::SWindowCoord&); void mouseEnter(const boo::SWindowCoord&); void mouseLeave(const boo::SWindowCoord&); void scroll(const boo::SWindowCoord&, const boo::SScrollDelta&); void think(); void updateData(); void resized(const boo::SWindowRect& root, const boo::SWindowRect& sub); void draw(boo::IGraphicsCommandQueue* gfxQ); }; } #endif // SPECTER_TABLE_HPP <commit_msg>null pointer fix<commit_after>#ifndef SPECTER_TABLE_HPP #define SPECTER_TABLE_HPP #include "View.hpp" #include "ScrollView.hpp" #include "TextView.hpp" #include <array> namespace specter { #define SPECTER_TABLE_MAX_ROWS 128ul enum class SortDirection { None, Ascending, Descending }; struct ITableDataBinding { virtual size_t columnCount() const=0; virtual size_t rowCount() const=0; virtual std::string_view header(size_t cIdx) const { return {}; } virtual std::string_view cell(size_t cIdx, size_t rIdx) const { return {}; } }; struct ITableStateBinding { virtual float getColumnSplit(size_t cIdx) const {return -1.0;} virtual bool columnSplitResizeAllowed() const {return false;} virtual void setColumnSplit(size_t cIdx, float split) {} virtual SortDirection getSort(size_t& cIdx) const {cIdx = 0; return SortDirection::None;} virtual void setSort(size_t cIdx, SortDirection dir) {} virtual void setSelectedRow(size_t rIdx) {} virtual void rowActivated(size_t rIdx) {} }; class Table : public View { ITableDataBinding* m_data; ITableStateBinding* m_state; size_t m_maxColumns; size_t m_rows = 0; size_t m_columns = 0; size_t m_selectedRow = -1; size_t m_deferredActivation = -1; size_t m_clickFrames = 15; struct CellView : public View { Table& m_t; std::unique_ptr<TextView> m_text; size_t m_c, m_r; boo::SWindowRect m_scissorRect; uint64_t m_textHash = 0; CellView(Table& t, ViewResources& res); bool m_selected = false; void select(); void deselect(); void reset(); bool reset(size_t c); bool reset(size_t c, size_t r); void mouseDown(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseUp(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseEnter(const boo::SWindowCoord&); void mouseLeave(const boo::SWindowCoord&); void resized(const boo::SWindowRect& root, const boo::SWindowRect& sub, const boo::SWindowRect& scissor); void draw(boo::IGraphicsCommandQueue* gfxQ); }; std::vector<ViewChild<std::unique_ptr<CellView>>> m_headerViews; using ColumnPool = std::array<std::array<ViewChild<std::unique_ptr<CellView>>, SPECTER_TABLE_MAX_ROWS>, 2>; std::vector<ColumnPool> m_cellPools; size_t m_ensuredRows = 0; std::vector<ColumnPool>& ensureCellPools(size_t rows, size_t cols, ViewResources& res); size_t m_activePool = -1; bool m_header = false; std::vector<boo::SWindowRect> m_hCellRects; size_t m_hDraggingIdx = 0; std::unique_ptr<SolidShaderVert[]> m_hVerts; VertexBufferBindingSolid m_vertsBinding; void _setHeaderVerts(const boo::SWindowRect& rect); std::vector<boo::SWindowRect> getCellRects(const boo::SWindowRect& tableRect) const; ViewChild<std::unique_ptr<ScrollView>> m_scroll; struct RowsView : public View { Table& m_t; std::unique_ptr<SolidShaderVert[]> m_verts; VertexBufferBindingSolid m_vertsBinding; size_t m_visibleStart = 0; size_t m_visibleRows = 0; boo::SWindowRect m_scissorRect; void _setRowVerts(const boo::SWindowRect& rowsRect, const boo::SWindowRect& scissor); RowsView(Table& t, ViewResources& res); int nominalHeight() const; int nominalWidth() const {return m_t.m_scroll.m_view->nominalWidth();} void mouseDown(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseUp(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseMove(const boo::SWindowCoord&); void mouseLeave(const boo::SWindowCoord&); void resized(const boo::SWindowRect& root, const boo::SWindowRect& sub, const boo::SWindowRect& scissor); void draw(boo::IGraphicsCommandQueue* gfxQ); } m_rowsView; bool m_headerNeedsUpdate = false; bool m_inSelectRow = false; void _updateData(); public: Table(ViewResources& res, View& parentView, ITableDataBinding* data, ITableStateBinding* state=nullptr, size_t maxColumns=8); void cycleSortColumn(size_t c); void selectRow(size_t r); void setMultiplyColor(const zeus::CColor& color); void mouseDown(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseUp(const boo::SWindowCoord&, boo::EMouseButton, boo::EModifierKey); void mouseMove(const boo::SWindowCoord&); void mouseEnter(const boo::SWindowCoord&); void mouseLeave(const boo::SWindowCoord&); void scroll(const boo::SWindowCoord&, const boo::SScrollDelta&); void think(); void updateData(); void resized(const boo::SWindowRect& root, const boo::SWindowRect& sub); void draw(boo::IGraphicsCommandQueue* gfxQ); }; } #endif // SPECTER_TABLE_HPP <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/lifetime/application_lifetime.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/notifications/notification_ui_manager.h" namespace browser { void HandleAppExitingForPlatform() { // Close All non browser windows now. Those includes notifications // and windows created by Ash (launcher, background, etc). g_browser_process->notification_ui_manager()->CancelAll(); // TODO(oshima): Close all non browser windows here while // the message loop is still alive. #if defined(OS_CHROMEOS) if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableZeroBrowsersOpenForTests)) { // App is exiting, call EndKeepAlive() on behalf of Aura Shell. EndKeepAlive(); // Make sure we have notified the session manager that we are exiting. // This might be called from FastShutdown() or CloseAllBrowsers(), but not // if something prevents a browser from closing before SetTryingToQuit() // gets called (e.g. browser->TabsNeedBeforeUnloadFired() is true). // NotifyAndTerminate does nothing if called more than once. NotifyAndTerminate(true); } #endif // OS_CHROMEOS } } // namespace browser <commit_msg>ash: Avoid hang on signout when desktop menu is open.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/lifetime/application_lifetime.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/notifications/notification_ui_manager.h" #if defined(USE_ASH) #include "ash/shell.h" #include "ui/aura/client/capture_client.h" #endif namespace browser { void HandleAppExitingForPlatform() { // Close all non browser windows now. Those includes notifications // and windows created by Ash (launcher, background, etc). g_browser_process->notification_ui_manager()->CancelAll(); #if defined(USE_ASH) // Releasing the capture will close any menus that might be open: // http://crbug.com/134472 aura::client::GetCaptureClient(ash::Shell::GetPrimaryRootWindow())-> SetCapture(NULL); #endif // TODO(oshima): Close all non browser windows here while // the message loop is still alive. #if defined(OS_CHROMEOS) if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableZeroBrowsersOpenForTests)) { // App is exiting, call EndKeepAlive() on behalf of Aura Shell. EndKeepAlive(); // Make sure we have notified the session manager that we are exiting. // This might be called from FastShutdown() or CloseAllBrowsers(), but not // if something prevents a browser from closing before SetTryingToQuit() // gets called (e.g. browser->TabsNeedBeforeUnloadFired() is true). // NotifyAndTerminate does nothing if called more than once. NotifyAndTerminate(true); } #endif // OS_CHROMEOS } } // namespace browser <|endoftext|>
<commit_before>/*************************************************************************** * io/diskqueue.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2002-2005 Roman Dementiev <[email protected]> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <stxxl/bits/io/iobase.h> #ifndef STXXL_BOOST_THREADS #ifdef STXXL_THREAD_PROFILING #define pthread_create gprof_pthread_create #endif #endif __STXXL_BEGIN_NAMESPACE disk_queue::disk_queue(int /*n*/) : sem(0), _priority_op(WRITE) // n is ignored #ifdef STXXL_BOOST_THREADS , thread(boost::bind(worker, static_cast<void *>(this))) #endif { // cout << "disk_queue created." << endl; #if STXXL_IO_STATS iostats = stats::get_instance(); #endif #ifdef STXXL_BOOST_THREADS // nothing to do #else check_pthread_call(pthread_create(&thread, NULL, (thread_function_t)worker, static_cast<void *>(this))); #endif } void disk_queue::add_readreq(request_ptr & req) { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock Lock(read_mutex); read_queue.push(req); Lock.unlock(); #else read_mutex.lock(); read_queue.push(req); read_mutex.unlock(); #endif sem++; } void disk_queue::add_writereq(request_ptr & req) { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock Lock(write_mutex); write_queue.push(req); Lock.unlock(); #else write_mutex.lock(); write_queue.push(req); write_mutex.unlock(); #endif sem++; } disk_queue::~disk_queue() { #ifdef STXXL_BOOST_THREADS // Boost.Threads do not support cancellation ? #else check_pthread_call(pthread_cancel(thread)); check_pthread_call(pthread_join(thread, NULL)); #endif } void * disk_queue::worker(void * arg) { disk_queue * pthis = static_cast<disk_queue *>(arg); request_ptr req; #ifdef STXXL_BOOST_THREADS #else check_pthread_call(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL)); check_pthread_call(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL)); // Allow cancellation in semaphore operator-- call #endif bool write_phase = true; for ( ; ; ) { pthis->sem--; if (write_phase) { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock WriteLock(pthis->write_mutex); #else pthis->write_mutex.lock(); #endif if (!pthis->write_queue.empty()) { req = pthis->write_queue.front(); pthis->write_queue.pop(); #ifdef STXXL_BOOST_THREADS WriteLock.unlock(); #else pthis->write_mutex.unlock(); #endif //assert(req->nref() > 1); req->serve(); } else { #ifdef STXXL_BOOST_THREADS WriteLock.unlock(); #else pthis->write_mutex.unlock(); #endif pthis->sem++; if (pthis->_priority_op == WRITE) write_phase = false; } if (pthis->_priority_op == NONE || pthis->_priority_op == READ) write_phase = false; } else { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock ReadLock(pthis->read_mutex); #else pthis->read_mutex.lock(); #endif if (!pthis->read_queue.empty()) { req = pthis->read_queue.front(); pthis->read_queue.pop(); #ifdef STXXL_BOOST_THREADS ReadLock.unlock(); #else pthis->read_mutex.unlock(); #endif STXXL_VERBOSE2("queue: before serve request has " << req->nref() << " references "); //assert(req->nref() > 1); req->serve(); STXXL_VERBOSE2("queue: after serve request has " << req->nref() << " references "); } else { #ifdef STXXL_BOOST_THREADS ReadLock.unlock(); #else pthis->read_mutex.unlock(); #endif pthis->sem++; if (pthis->_priority_op == READ) write_phase = true; } if (pthis->_priority_op == NONE || pthis->_priority_op == WRITE) write_phase = true; } } return NULL; } __STXXL_END_NAMESPACE <commit_msg>remove last trace of STXXL_THREAD_PROFILING<commit_after>/*************************************************************************** * io/diskqueue.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2002-2005 Roman Dementiev <[email protected]> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <stxxl/bits/io/iobase.h> __STXXL_BEGIN_NAMESPACE disk_queue::disk_queue(int /*n*/) : sem(0), _priority_op(WRITE) // n is ignored #ifdef STXXL_BOOST_THREADS , thread(boost::bind(worker, static_cast<void *>(this))) #endif { // cout << "disk_queue created." << endl; #if STXXL_IO_STATS iostats = stats::get_instance(); #endif #ifdef STXXL_BOOST_THREADS // nothing to do #else check_pthread_call(pthread_create(&thread, NULL, (thread_function_t)worker, static_cast<void *>(this))); #endif } void disk_queue::add_readreq(request_ptr & req) { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock Lock(read_mutex); read_queue.push(req); Lock.unlock(); #else read_mutex.lock(); read_queue.push(req); read_mutex.unlock(); #endif sem++; } void disk_queue::add_writereq(request_ptr & req) { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock Lock(write_mutex); write_queue.push(req); Lock.unlock(); #else write_mutex.lock(); write_queue.push(req); write_mutex.unlock(); #endif sem++; } disk_queue::~disk_queue() { #ifdef STXXL_BOOST_THREADS // Boost.Threads do not support cancellation ? #else check_pthread_call(pthread_cancel(thread)); check_pthread_call(pthread_join(thread, NULL)); #endif } void * disk_queue::worker(void * arg) { disk_queue * pthis = static_cast<disk_queue *>(arg); request_ptr req; #ifdef STXXL_BOOST_THREADS #else check_pthread_call(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL)); check_pthread_call(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL)); // Allow cancellation in semaphore operator-- call #endif bool write_phase = true; for ( ; ; ) { pthis->sem--; if (write_phase) { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock WriteLock(pthis->write_mutex); #else pthis->write_mutex.lock(); #endif if (!pthis->write_queue.empty()) { req = pthis->write_queue.front(); pthis->write_queue.pop(); #ifdef STXXL_BOOST_THREADS WriteLock.unlock(); #else pthis->write_mutex.unlock(); #endif //assert(req->nref() > 1); req->serve(); } else { #ifdef STXXL_BOOST_THREADS WriteLock.unlock(); #else pthis->write_mutex.unlock(); #endif pthis->sem++; if (pthis->_priority_op == WRITE) write_phase = false; } if (pthis->_priority_op == NONE || pthis->_priority_op == READ) write_phase = false; } else { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock ReadLock(pthis->read_mutex); #else pthis->read_mutex.lock(); #endif if (!pthis->read_queue.empty()) { req = pthis->read_queue.front(); pthis->read_queue.pop(); #ifdef STXXL_BOOST_THREADS ReadLock.unlock(); #else pthis->read_mutex.unlock(); #endif STXXL_VERBOSE2("queue: before serve request has " << req->nref() << " references "); //assert(req->nref() > 1); req->serve(); STXXL_VERBOSE2("queue: after serve request has " << req->nref() << " references "); } else { #ifdef STXXL_BOOST_THREADS ReadLock.unlock(); #else pthis->read_mutex.unlock(); #endif pthis->sem++; if (pthis->_priority_op == READ) write_phase = true; } if (pthis->_priority_op == NONE || pthis->_priority_op == WRITE) write_phase = true; } } return NULL; } __STXXL_END_NAMESPACE <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ItemConverter.cxx,v $ * $Revision: 1.14 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "ItemConverter.hxx" #include "macros.hxx" #include <com/sun/star/lang/XComponent.hpp> #include <svtools/itemprop.hxx> #include <svtools/itemiter.hxx> // header for class SfxWhichIter #include <svtools/whiter.hxx> using namespace ::com::sun::star; namespace comphelper { ItemConverter::ItemConverter( const uno::Reference< beans::XPropertySet > & rPropertySet, SfxItemPool& rItemPool ) : m_xPropertySet( rPropertySet ), m_xPropertySetInfo( NULL ), m_rItemPool( rItemPool ), m_bIsValid( true ) { resetPropertySet( m_xPropertySet ); } ItemConverter::~ItemConverter() { stopAllComponentListening(); } void ItemConverter::resetPropertySet( const uno::Reference< beans::XPropertySet > & xPropSet ) { if( xPropSet.is()) { stopAllComponentListening(); m_xPropertySet = xPropSet; m_xPropertySetInfo = m_xPropertySet->getPropertySetInfo(); uno::Reference< lang::XComponent > xComp( m_xPropertySet, uno::UNO_QUERY ); if( xComp.is()) { // method of base class ::utl::OEventListenerAdapter startComponentListening( xComp ); } } } SfxItemPool & ItemConverter::GetItemPool() const { return m_rItemPool; } SfxItemSet ItemConverter::CreateEmptyItemSet() const { return SfxItemSet( GetItemPool(), GetWhichPairs() ); } bool ItemConverter::IsValid() const { return m_bIsValid; } uno::Reference< beans::XPropertySet > ItemConverter::GetPropertySet() const { return m_xPropertySet; } void ItemConverter::_disposing( const lang::EventObject& rSource ) { if( rSource.Source == m_xPropertySet ) { m_bIsValid = false; } } void ItemConverter::FillItemSet( SfxItemSet & rOutItemSet ) const { const USHORT * pRanges = rOutItemSet.GetRanges(); tPropertyNameWithMemberId aProperty; SfxItemPool & rPool = GetItemPool(); OSL_ASSERT( pRanges != NULL ); OSL_ASSERT( m_xPropertySetInfo.is()); OSL_ASSERT( m_xPropertySet.is()); while( (*pRanges) != 0) { USHORT nBeg = (*pRanges); ++pRanges; USHORT nEnd = (*pRanges); ++pRanges; OSL_ASSERT( nBeg <= nEnd ); for( USHORT nWhich = nBeg; nWhich <= nEnd; ++nWhich ) { if( GetItemProperty( nWhich, aProperty )) { // put the Property into the itemset SfxPoolItem * pItem = rPool.GetDefaultItem( nWhich ).Clone(); if( pItem ) { try { if( ! pItem->PutValue( m_xPropertySet->getPropertyValue( aProperty.first ), aProperty.second // nMemberId )) { delete pItem; } else { rOutItemSet.Put( *pItem, nWhich ); delete pItem; } } catch( beans::UnknownPropertyException ex ) { delete pItem; OSL_ENSURE( false, ::rtl::OUStringToOString( ex.Message + ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( " - unknown Property: " )) + aProperty.first, RTL_TEXTENCODING_ASCII_US ).getStr()); } catch( uno::Exception ex ) { ASSERT_EXCEPTION( ex ); } } } else { try { FillSpecialItem( nWhich, rOutItemSet ); } catch( uno::Exception ex ) { ASSERT_EXCEPTION( ex ); } } } } } void ItemConverter::FillSpecialItem( USHORT /*nWhichId*/, SfxItemSet & /*rOutItemSet*/ ) const throw( uno::Exception ) { OSL_ENSURE( false, "ItemConverter: Unhandled special item found!" ); } bool ItemConverter::ApplySpecialItem( USHORT /*nWhichId*/, const SfxItemSet & /*rItemSet*/ ) throw( uno::Exception ) { OSL_ENSURE( false, "ItemConverter: Unhandled special item found!" ); return false; } bool ItemConverter::ApplyItemSet( const SfxItemSet & rItemSet ) { OSL_ASSERT( m_xPropertySet.is()); bool bItemsChanged = false; SfxItemIter aIter( rItemSet ); const SfxPoolItem * pItem = aIter.FirstItem(); tPropertyNameWithMemberId aProperty; uno::Any aValue; while( pItem ) { if( rItemSet.GetItemState( pItem->Which(), FALSE ) == SFX_ITEM_SET ) { if( GetItemProperty( pItem->Which(), aProperty )) { pItem->QueryValue( aValue, aProperty.second /* nMemberId */ ); try { if( aValue != m_xPropertySet->getPropertyValue( aProperty.first )) { m_xPropertySet->setPropertyValue( aProperty.first, aValue ); bItemsChanged = true; } } catch( beans::UnknownPropertyException ex ) { OSL_ENSURE( false, ::rtl::OUStringToOString( ex.Message + ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( " - unknown Property: " )) + aProperty.first, RTL_TEXTENCODING_ASCII_US).getStr()); } catch( uno::Exception ex ) { OSL_ENSURE( false, ::rtl::OUStringToOString( ex.Message, RTL_TEXTENCODING_ASCII_US ).getStr()); } } else { bItemsChanged = ApplySpecialItem( pItem->Which(), rItemSet ) || bItemsChanged; } } pItem = aIter.NextItem(); } return bItemsChanged; } // -------------------------------------------------------------------------------- //static void ItemConverter::InvalidateUnequalItems( SfxItemSet &rDestSet, const SfxItemSet &rSourceSet ) { SfxWhichIter aIter (rSourceSet); USHORT nWhich = aIter.FirstWhich (); const SfxPoolItem *pPoolItem = NULL; while (nWhich) { if ((rSourceSet.GetItemState(nWhich, TRUE, &pPoolItem) == SFX_ITEM_SET) && (rDestSet.GetItemState(nWhich, TRUE, &pPoolItem) == SFX_ITEM_SET)) { if (rSourceSet.Get(nWhich) != rDestSet.Get(nWhich)) rDestSet.InvalidateItem(nWhich); } else if( rSourceSet.GetItemState(nWhich, TRUE, &pPoolItem) == SFX_ITEM_DONTCARE ) rDestSet.InvalidateItem(nWhich); nWhich = aIter.NextWhich (); } } } // namespace comphelper <commit_msg>INTEGRATION: CWS chart25 (1.13.24); FILE MERGED 2008/04/24 12:46:39 iha 1.13.24.2: RESYNC: (1.13-1.14); FILE MERGED 2008/04/10 09:16:21 iha 1.13.24.1: #i26572# set an explicit text for the font preview<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ItemConverter.cxx,v $ * $Revision: 1.15 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "ItemConverter.hxx" #include "macros.hxx" #include <com/sun/star/lang/XComponent.hpp> #include <svtools/itemprop.hxx> #include <svtools/itemiter.hxx> // header for class SfxWhichIter #include <svtools/whiter.hxx> #include <svx/svxids.hrc> using namespace ::com::sun::star; namespace comphelper { ItemConverter::ItemConverter( const uno::Reference< beans::XPropertySet > & rPropertySet, SfxItemPool& rItemPool ) : m_xPropertySet( rPropertySet ), m_xPropertySetInfo( NULL ), m_rItemPool( rItemPool ), m_bIsValid( true ) { resetPropertySet( m_xPropertySet ); } ItemConverter::~ItemConverter() { stopAllComponentListening(); } void ItemConverter::resetPropertySet( const uno::Reference< beans::XPropertySet > & xPropSet ) { if( xPropSet.is()) { stopAllComponentListening(); m_xPropertySet = xPropSet; m_xPropertySetInfo = m_xPropertySet->getPropertySetInfo(); uno::Reference< lang::XComponent > xComp( m_xPropertySet, uno::UNO_QUERY ); if( xComp.is()) { // method of base class ::utl::OEventListenerAdapter startComponentListening( xComp ); } } } SfxItemPool & ItemConverter::GetItemPool() const { return m_rItemPool; } SfxItemSet ItemConverter::CreateEmptyItemSet() const { return SfxItemSet( GetItemPool(), GetWhichPairs() ); } bool ItemConverter::IsValid() const { return m_bIsValid; } uno::Reference< beans::XPropertySet > ItemConverter::GetPropertySet() const { return m_xPropertySet; } void ItemConverter::_disposing( const lang::EventObject& rSource ) { if( rSource.Source == m_xPropertySet ) { m_bIsValid = false; } } void ItemConverter::FillItemSet( SfxItemSet & rOutItemSet ) const { const USHORT * pRanges = rOutItemSet.GetRanges(); tPropertyNameWithMemberId aProperty; SfxItemPool & rPool = GetItemPool(); OSL_ASSERT( pRanges != NULL ); OSL_ASSERT( m_xPropertySetInfo.is()); OSL_ASSERT( m_xPropertySet.is()); while( (*pRanges) != 0) { USHORT nBeg = (*pRanges); ++pRanges; USHORT nEnd = (*pRanges); ++pRanges; OSL_ASSERT( nBeg <= nEnd ); for( USHORT nWhich = nBeg; nWhich <= nEnd; ++nWhich ) { if( GetItemProperty( nWhich, aProperty )) { // put the Property into the itemset SfxPoolItem * pItem = rPool.GetDefaultItem( nWhich ).Clone(); if( pItem ) { try { if( ! pItem->PutValue( m_xPropertySet->getPropertyValue( aProperty.first ), aProperty.second // nMemberId )) { delete pItem; } else { rOutItemSet.Put( *pItem, nWhich ); delete pItem; } } catch( beans::UnknownPropertyException ex ) { delete pItem; OSL_ENSURE( false, ::rtl::OUStringToOString( ex.Message + ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( " - unknown Property: " )) + aProperty.first, RTL_TEXTENCODING_ASCII_US ).getStr()); } catch( uno::Exception ex ) { ASSERT_EXCEPTION( ex ); } } } else { try { FillSpecialItem( nWhich, rOutItemSet ); } catch( uno::Exception ex ) { ASSERT_EXCEPTION( ex ); } } } } } void ItemConverter::FillSpecialItem( USHORT /*nWhichId*/, SfxItemSet & /*rOutItemSet*/ ) const throw( uno::Exception ) { OSL_ENSURE( false, "ItemConverter: Unhandled special item found!" ); } bool ItemConverter::ApplySpecialItem( USHORT /*nWhichId*/, const SfxItemSet & /*rItemSet*/ ) throw( uno::Exception ) { OSL_ENSURE( false, "ItemConverter: Unhandled special item found!" ); return false; } bool ItemConverter::ApplyItemSet( const SfxItemSet & rItemSet ) { OSL_ASSERT( m_xPropertySet.is()); bool bItemsChanged = false; SfxItemIter aIter( rItemSet ); const SfxPoolItem * pItem = aIter.FirstItem(); tPropertyNameWithMemberId aProperty; uno::Any aValue; while( pItem ) { if( rItemSet.GetItemState( pItem->Which(), FALSE ) == SFX_ITEM_SET ) { if( GetItemProperty( pItem->Which(), aProperty )) { pItem->QueryValue( aValue, aProperty.second /* nMemberId */ ); try { if( aValue != m_xPropertySet->getPropertyValue( aProperty.first )) { m_xPropertySet->setPropertyValue( aProperty.first, aValue ); bItemsChanged = true; } } catch( beans::UnknownPropertyException ex ) { OSL_ENSURE( false, ::rtl::OUStringToOString( ex.Message + ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( " - unknown Property: " )) + aProperty.first, RTL_TEXTENCODING_ASCII_US).getStr()); } catch( uno::Exception ex ) { OSL_ENSURE( false, ::rtl::OUStringToOString( ex.Message, RTL_TEXTENCODING_ASCII_US ).getStr()); } } else { bItemsChanged = ApplySpecialItem( pItem->Which(), rItemSet ) || bItemsChanged; } } pItem = aIter.NextItem(); } return bItemsChanged; } // -------------------------------------------------------------------------------- //static void ItemConverter::InvalidateUnequalItems( SfxItemSet &rDestSet, const SfxItemSet &rSourceSet ) { SfxWhichIter aIter (rSourceSet); USHORT nWhich = aIter.FirstWhich (); const SfxPoolItem *pPoolItem = NULL; while (nWhich) { if ((rSourceSet.GetItemState(nWhich, TRUE, &pPoolItem) == SFX_ITEM_SET) && (rDestSet.GetItemState(nWhich, TRUE, &pPoolItem) == SFX_ITEM_SET)) { if (rSourceSet.Get(nWhich) != rDestSet.Get(nWhich)) { if( SID_CHAR_DLG_PREVIEW_STRING != nWhich ) { rDestSet.InvalidateItem(nWhich); } } } else if( rSourceSet.GetItemState(nWhich, TRUE, &pPoolItem) == SFX_ITEM_DONTCARE ) rDestSet.InvalidateItem(nWhich); nWhich = aIter.NextWhich (); } } } // namespace comphelper <|endoftext|>
<commit_before><commit_msg>Revert "Force the foreground and background color of the omnibox text." This reverts commit r16383.<commit_after><|endoftext|>
<commit_before><commit_msg>Fix issue 30244<commit_after><|endoftext|>
<commit_before>/* This file is part of Pack My Sprites. Pack My Sprites is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License. Pack My Sprites is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "pms/app/general_program_options.hpp" #include "pms/app/version.hpp" #include <claw/logger.hpp> boost::program_options::options_description pms::app::get_general_program_options() { boost::program_options::options_description result( "General options" ); result.add_options() ( "help,h", "Print this message and exit." ) ( "version", "Print the version of the software." ) ( "verbose", "Show informative messages during processing." ); return result; } bool pms::app::parse_general_program_options ( const boost::program_options::options_description& options, const boost::program_options::variables_map& values, const std::string& program_name, const std::string& arguments_string ) { if ( values.count( "help" ) != 0 ) { std::cout << "Usage: " << program_name << ' ' << arguments_string << '\n' << options; return false; } if ( values.count( "version" ) != 0 ) { std::cout << PMS_VERSION_STRING << '\n'; return false; } claw::logger.set( new claw::console_logger() ); if ( values.count( "verbose" ) != 0 ) claw::logger.set_level( claw::log_verbose ); else claw::logger.set_level( claw::log_warning ); return true; } <commit_msg>Add a missing include directive.<commit_after>/* This file is part of Pack My Sprites. Pack My Sprites is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License. Pack My Sprites is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "pms/app/general_program_options.hpp" #include "pms/app/version.hpp" #include <claw/logger.hpp> #include <iostream> boost::program_options::options_description pms::app::get_general_program_options() { boost::program_options::options_description result( "General options" ); result.add_options() ( "help,h", "Print this message and exit." ) ( "version", "Print the version of the software." ) ( "verbose", "Show informative messages during processing." ); return result; } bool pms::app::parse_general_program_options ( const boost::program_options::options_description& options, const boost::program_options::variables_map& values, const std::string& program_name, const std::string& arguments_string ) { if ( values.count( "help" ) != 0 ) { std::cout << "Usage: " << program_name << ' ' << arguments_string << '\n' << options; return false; } if ( values.count( "version" ) != 0 ) { std::cout << PMS_VERSION_STRING << '\n'; return false; } claw::logger.set( new claw::console_logger() ); if ( values.count( "verbose" ) != 0 ) claw::logger.set_level( claw::log_verbose ); else claw::logger.set_level( claw::log_warning ); return true; } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/web_contents_view_gtk.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include "base/gfx/point.h" #include "base/gfx/rect.h" #include "chrome/browser/gtk/browser_window_gtk.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_widget_host_view_gtk.h" #include "chrome/browser/tab_contents/render_view_context_menu_gtk.h" #include "chrome/browser/tab_contents/tab_contents_delegate.h" #include "chrome/browser/tab_contents/web_contents.h" #include "webkit/glue/webinputevent.h" namespace { // Called when the content view gtk widget is tabbed to. We always return true // and grab focus if we don't have it. The call to SetInitialFocus(bool) // forwards the tab to webkit. We leave focus via TakeFocus(). // We cast the WebContents to a TabContents because SetInitialFocus is public // in TabContents and protected in WebContents. gboolean OnFocus(GtkWidget* widget, GtkDirectionType focus, TabContents* tab_contents) { if (GTK_WIDGET_HAS_FOCUS(widget)) return TRUE; gtk_widget_grab_focus(widget); bool reverse = focus == GTK_DIR_TAB_BACKWARD; tab_contents->SetInitialFocus(reverse); return TRUE; } // Called when the mouse leaves the widget. We notify our delegate. gboolean OnLeaveNotify(GtkWidget* widget, GdkEventCrossing* event, WebContents* web_contents) { if (web_contents->delegate()) web_contents->delegate()->ContentsMouseEvent(web_contents, false); return FALSE; } // Called when the mouse moves within the widget. We notify our delegate. gboolean OnMouseMove(GtkWidget* widget, GdkEventMotion* event, WebContents* web_contents) { if (web_contents->delegate()) web_contents->delegate()->ContentsMouseEvent(web_contents, true); return FALSE; } // Callback used in WebContentsViewGtk::CreateViewForWidget(). void RemoveWidget(GtkWidget* widget, gpointer container) { gtk_container_remove(GTK_CONTAINER(container), widget); } } // namespace // static WebContentsView* WebContentsView::Create(WebContents* web_contents) { return new WebContentsViewGtk(web_contents); } WebContentsViewGtk::WebContentsViewGtk(WebContents* web_contents) : WebContentsView(web_contents), vbox_(gtk_vbox_new(FALSE, 0)) { } WebContentsViewGtk::~WebContentsViewGtk() { vbox_.Destroy(); } void WebContentsViewGtk::CreateView() { NOTIMPLEMENTED(); } RenderWidgetHostView* WebContentsViewGtk::CreateViewForWidget( RenderWidgetHost* render_widget_host) { DCHECK(!render_widget_host->view()); RenderWidgetHostViewGtk* view = new RenderWidgetHostViewGtk(render_widget_host); view->InitAsChild(); content_view_ = view->native_view(); g_signal_connect(content_view_, "focus", G_CALLBACK(OnFocus), web_contents()); g_signal_connect(view->native_view(), "leave-notify-event", G_CALLBACK(OnLeaveNotify), web_contents()); g_signal_connect(view->native_view(), "motion-notify-event", G_CALLBACK(OnMouseMove), web_contents()); gtk_widget_add_events(view->native_view(), GDK_LEAVE_NOTIFY_MASK | GDK_POINTER_MOTION_MASK); gtk_container_foreach(GTK_CONTAINER(vbox_.get()), RemoveWidget, vbox_.get()); gtk_box_pack_start(GTK_BOX(vbox_.get()), content_view_, TRUE, TRUE, 0); return view; } gfx::NativeView WebContentsViewGtk::GetNativeView() const { return vbox_.get(); } gfx::NativeView WebContentsViewGtk::GetContentNativeView() const { return content_view_; } gfx::NativeWindow WebContentsViewGtk::GetTopLevelNativeWindow() const { GtkWidget* window = gtk_widget_get_ancestor(GetNativeView(), GTK_TYPE_WINDOW); return window ? GTK_WINDOW(window) : NULL; } void WebContentsViewGtk::GetContainerBounds(gfx::Rect* out) const { // This is used for positioning the download shelf arrow animation, // as well as sizing some other widgets in Windows. In GTK the size is // managed for us, so it appears to be only used for the download shelf // animation. out->SetRect(vbox_.get()->allocation.x, vbox_.get()->allocation.y, vbox_.get()->allocation.width, vbox_.get()->allocation.height); } void WebContentsViewGtk::OnContentsDestroy() { // TODO(estade): Windows uses this function cancel pending drag-n-drop drags. // We don't have drags yet, so do nothing for now. } void WebContentsViewGtk::SetPageTitle(const std::wstring& title) { // Set the window name to include the page title so it's easier to spot // when debugging (e.g. via xwininfo -tree). if (content_view_ && content_view_->window) gdk_window_set_title(content_view_->window, WideToUTF8(title).c_str()); } void WebContentsViewGtk::Invalidate() { NOTIMPLEMENTED(); } void WebContentsViewGtk::SizeContents(const gfx::Size& size) { NOTIMPLEMENTED(); } void WebContentsViewGtk::FindInPage(const Browser& browser, bool find_next, bool forward_direction) { NOTIMPLEMENTED(); } void WebContentsViewGtk::HideFindBar(bool end_session) { NOTIMPLEMENTED(); } void WebContentsViewGtk::ReparentFindWindow(Browser* new_browser) const { NOTIMPLEMENTED(); } bool WebContentsViewGtk::GetFindBarWindowInfo(gfx::Point* position, bool* fully_visible) const { NOTIMPLEMENTED(); return false; } void WebContentsViewGtk::SetInitialFocus() { if (web_contents()->FocusLocationBarByDefault()) web_contents()->delegate()->SetFocusToLocationBar(); else gtk_widget_grab_focus(content_view_); } void WebContentsViewGtk::StoreFocus() { NOTIMPLEMENTED(); } void WebContentsViewGtk::RestoreFocus() { // TODO(estade): implement this function. // For now just assume we are viewing the tab for the first time. SetInitialFocus(); NOTIMPLEMENTED() << " -- need to restore the focus position on this page."; } void WebContentsViewGtk::UpdateDragCursor(bool is_drop_target) { NOTIMPLEMENTED(); } // This is called when we the renderer asks us to take focus back (i.e., it has // iterated past the last focusable element on the page). void WebContentsViewGtk::TakeFocus(bool reverse) { web_contents()->delegate()->SetFocusToLocationBar(); } void WebContentsViewGtk::HandleKeyboardEvent( const NativeWebKeyboardEvent& event) { // This may be an accelerator. Try to pass it on to our browser window // to handle. GtkWindow* window = GetTopLevelNativeWindow(); // It's possible to not be associated with a window at the time when we're // handling the keyboard event (e.g., the user opened a new tab in the time). // What we really want to do is get whatever currently has focus and have // that handle the accelerator. TODO(tc): Consider walking // gtk_window_list_toplevels to find what has focus and if that's a browser // window, forward the event. if (!window) return; BrowserWindowGtk* browser_window = static_cast<BrowserWindowGtk*>( g_object_get_data(G_OBJECT(window), "browser_window_gtk")); DCHECK(browser_window); browser_window->HandleAccelerator(event.os_event->keyval, static_cast<GdkModifierType>(event.os_event->state)); } void WebContentsViewGtk::OnFindReply(int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { NOTIMPLEMENTED(); } void WebContentsViewGtk::ShowContextMenu(const ContextMenuParams& params) { context_menu_.reset(new RenderViewContextMenuGtk(web_contents(), params)); context_menu_->Popup(); } void WebContentsViewGtk::StartDragging(const WebDropData& drop_data) { NOTIMPLEMENTED(); // Until we have d'n'd implemented, just immediately pretend we're // already done with the drag and drop so we don't get stuck // thinking we're in mid-drag. // TODO(port): remove me when the above NOTIMPLEMENTED is fixed. if (web_contents()->render_view_host()) web_contents()->render_view_host()->DragSourceSystemDragEnded(); } WebContents* WebContentsViewGtk::CreateNewWindowInternal( int route_id, base::WaitableEvent* modal_dialog_event) { NOTIMPLEMENTED(); return NULL; } void WebContentsViewGtk::ShowCreatedWindowInternal( WebContents* new_web_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture) { NOTIMPLEMENTED(); } <commit_msg>Fix unintialized variable (only affected unit test).<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/web_contents_view_gtk.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include "base/gfx/point.h" #include "base/gfx/rect.h" #include "chrome/browser/gtk/browser_window_gtk.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_widget_host_view_gtk.h" #include "chrome/browser/tab_contents/render_view_context_menu_gtk.h" #include "chrome/browser/tab_contents/tab_contents_delegate.h" #include "chrome/browser/tab_contents/web_contents.h" #include "webkit/glue/webinputevent.h" namespace { // Called when the content view gtk widget is tabbed to. We always return true // and grab focus if we don't have it. The call to SetInitialFocus(bool) // forwards the tab to webkit. We leave focus via TakeFocus(). // We cast the WebContents to a TabContents because SetInitialFocus is public // in TabContents and protected in WebContents. gboolean OnFocus(GtkWidget* widget, GtkDirectionType focus, TabContents* tab_contents) { if (GTK_WIDGET_HAS_FOCUS(widget)) return TRUE; gtk_widget_grab_focus(widget); bool reverse = focus == GTK_DIR_TAB_BACKWARD; tab_contents->SetInitialFocus(reverse); return TRUE; } // Called when the mouse leaves the widget. We notify our delegate. gboolean OnLeaveNotify(GtkWidget* widget, GdkEventCrossing* event, WebContents* web_contents) { if (web_contents->delegate()) web_contents->delegate()->ContentsMouseEvent(web_contents, false); return FALSE; } // Called when the mouse moves within the widget. We notify our delegate. gboolean OnMouseMove(GtkWidget* widget, GdkEventMotion* event, WebContents* web_contents) { if (web_contents->delegate()) web_contents->delegate()->ContentsMouseEvent(web_contents, true); return FALSE; } // Callback used in WebContentsViewGtk::CreateViewForWidget(). void RemoveWidget(GtkWidget* widget, gpointer container) { gtk_container_remove(GTK_CONTAINER(container), widget); } } // namespace // static WebContentsView* WebContentsView::Create(WebContents* web_contents) { return new WebContentsViewGtk(web_contents); } WebContentsViewGtk::WebContentsViewGtk(WebContents* web_contents) : WebContentsView(web_contents), vbox_(gtk_vbox_new(FALSE, 0)), content_view_(NULL) { } WebContentsViewGtk::~WebContentsViewGtk() { vbox_.Destroy(); } void WebContentsViewGtk::CreateView() { NOTIMPLEMENTED(); } RenderWidgetHostView* WebContentsViewGtk::CreateViewForWidget( RenderWidgetHost* render_widget_host) { DCHECK(!render_widget_host->view()); RenderWidgetHostViewGtk* view = new RenderWidgetHostViewGtk(render_widget_host); view->InitAsChild(); content_view_ = view->native_view(); g_signal_connect(content_view_, "focus", G_CALLBACK(OnFocus), web_contents()); g_signal_connect(view->native_view(), "leave-notify-event", G_CALLBACK(OnLeaveNotify), web_contents()); g_signal_connect(view->native_view(), "motion-notify-event", G_CALLBACK(OnMouseMove), web_contents()); gtk_widget_add_events(view->native_view(), GDK_LEAVE_NOTIFY_MASK | GDK_POINTER_MOTION_MASK); gtk_container_foreach(GTK_CONTAINER(vbox_.get()), RemoveWidget, vbox_.get()); gtk_box_pack_start(GTK_BOX(vbox_.get()), content_view_, TRUE, TRUE, 0); return view; } gfx::NativeView WebContentsViewGtk::GetNativeView() const { return vbox_.get(); } gfx::NativeView WebContentsViewGtk::GetContentNativeView() const { return content_view_; } gfx::NativeWindow WebContentsViewGtk::GetTopLevelNativeWindow() const { GtkWidget* window = gtk_widget_get_ancestor(GetNativeView(), GTK_TYPE_WINDOW); return window ? GTK_WINDOW(window) : NULL; } void WebContentsViewGtk::GetContainerBounds(gfx::Rect* out) const { // This is used for positioning the download shelf arrow animation, // as well as sizing some other widgets in Windows. In GTK the size is // managed for us, so it appears to be only used for the download shelf // animation. out->SetRect(vbox_.get()->allocation.x, vbox_.get()->allocation.y, vbox_.get()->allocation.width, vbox_.get()->allocation.height); } void WebContentsViewGtk::OnContentsDestroy() { // TODO(estade): Windows uses this function cancel pending drag-n-drop drags. // We don't have drags yet, so do nothing for now. } void WebContentsViewGtk::SetPageTitle(const std::wstring& title) { // Set the window name to include the page title so it's easier to spot // when debugging (e.g. via xwininfo -tree). if (content_view_ && content_view_->window) gdk_window_set_title(content_view_->window, WideToUTF8(title).c_str()); } void WebContentsViewGtk::Invalidate() { NOTIMPLEMENTED(); } void WebContentsViewGtk::SizeContents(const gfx::Size& size) { NOTIMPLEMENTED(); } void WebContentsViewGtk::FindInPage(const Browser& browser, bool find_next, bool forward_direction) { NOTIMPLEMENTED(); } void WebContentsViewGtk::HideFindBar(bool end_session) { NOTIMPLEMENTED(); } void WebContentsViewGtk::ReparentFindWindow(Browser* new_browser) const { NOTIMPLEMENTED(); } bool WebContentsViewGtk::GetFindBarWindowInfo(gfx::Point* position, bool* fully_visible) const { NOTIMPLEMENTED(); return false; } void WebContentsViewGtk::SetInitialFocus() { if (web_contents()->FocusLocationBarByDefault()) web_contents()->delegate()->SetFocusToLocationBar(); else gtk_widget_grab_focus(content_view_); } void WebContentsViewGtk::StoreFocus() { NOTIMPLEMENTED(); } void WebContentsViewGtk::RestoreFocus() { // TODO(estade): implement this function. // For now just assume we are viewing the tab for the first time. SetInitialFocus(); NOTIMPLEMENTED() << " -- need to restore the focus position on this page."; } void WebContentsViewGtk::UpdateDragCursor(bool is_drop_target) { NOTIMPLEMENTED(); } // This is called when we the renderer asks us to take focus back (i.e., it has // iterated past the last focusable element on the page). void WebContentsViewGtk::TakeFocus(bool reverse) { web_contents()->delegate()->SetFocusToLocationBar(); } void WebContentsViewGtk::HandleKeyboardEvent( const NativeWebKeyboardEvent& event) { // This may be an accelerator. Try to pass it on to our browser window // to handle. GtkWindow* window = GetTopLevelNativeWindow(); // It's possible to not be associated with a window at the time when we're // handling the keyboard event (e.g., the user opened a new tab in the time). // What we really want to do is get whatever currently has focus and have // that handle the accelerator. TODO(tc): Consider walking // gtk_window_list_toplevels to find what has focus and if that's a browser // window, forward the event. if (!window) return; BrowserWindowGtk* browser_window = static_cast<BrowserWindowGtk*>( g_object_get_data(G_OBJECT(window), "browser_window_gtk")); DCHECK(browser_window); browser_window->HandleAccelerator(event.os_event->keyval, static_cast<GdkModifierType>(event.os_event->state)); } void WebContentsViewGtk::OnFindReply(int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { NOTIMPLEMENTED(); } void WebContentsViewGtk::ShowContextMenu(const ContextMenuParams& params) { context_menu_.reset(new RenderViewContextMenuGtk(web_contents(), params)); context_menu_->Popup(); } void WebContentsViewGtk::StartDragging(const WebDropData& drop_data) { NOTIMPLEMENTED(); // Until we have d'n'd implemented, just immediately pretend we're // already done with the drag and drop so we don't get stuck // thinking we're in mid-drag. // TODO(port): remove me when the above NOTIMPLEMENTED is fixed. if (web_contents()->render_view_host()) web_contents()->render_view_host()->DragSourceSystemDragEnded(); } WebContents* WebContentsViewGtk::CreateNewWindowInternal( int route_id, base::WaitableEvent* modal_dialog_event) { NOTIMPLEMENTED(); return NULL; } void WebContentsViewGtk::ShowCreatedWindowInternal( WebContents* new_web_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture) { NOTIMPLEMENTED(); } <|endoftext|>
<commit_before>/* Copyright: Copyright (C) 2003-2018 SIL International. Authors: mcdurdin */ #include <vector> #include <iterator> #include <codecvt> #include <locale> #include "kmx_processevent.h" #include "utfcodec.hpp" using namespace km::kbp; using namespace kmx; const km_kbp_cp *km::kbp::kmx::u16chr(const km_kbp_cp *p, km_kbp_cp ch) { while (*p) { if (*p == ch) return p; p++; } return ch == 0 ? p : NULL; } const km_kbp_cp *km::kbp::kmx::u16cpy(km_kbp_cp *dst, const km_kbp_cp *src) { km_kbp_cp *o = dst; while (*src) { *dst++ = *src++; } *dst = 0; return o; } const km_kbp_cp *km::kbp::kmx::u16ncpy(km_kbp_cp *dst, const km_kbp_cp *src, size_t max) { km_kbp_cp *o = dst; while (*src && max > 0) { *dst++ = *src++; max--; } while(max > 0) { *dst++ = 0; max--; } return o; } size_t km::kbp::kmx::u16len(const km_kbp_cp *p) { int i = 0; while (*p) { p++; i++; } return i; } int km::kbp::kmx::u16cmp(const km_kbp_cp *p, const km_kbp_cp *q) { while (*p && *q) { if (*p != *q) return *p - *q; p++; q++; } return *p - *q; } int km::kbp::kmx::u16icmp(const km_kbp_cp *p, const km_kbp_cp *q) { while (*p && *q) { if (toupper(*p) != toupper(*q)) return *p - *q; p++; q++; } return *p - *q; } int km::kbp::kmx::u16ncmp(const km_kbp_cp *p, const km_kbp_cp *q, size_t count) { while (*p && *q && count) { if (*p != *q) return *p - *q; p++; q++; count--; } if (count) return *p - *q; return 0; } km_kbp_cp *km::kbp::kmx::u16tok(km_kbp_cp *p, km_kbp_cp ch, km_kbp_cp **ctx) { if (!p) { p = *ctx; if (!p) return NULL; } km_kbp_cp *q = p; while (*q && *q != ch) { q++; } if (*q) { *q = 0; q++; while (*q == ch) q++; *ctx = q; } else { *ctx = NULL; } return p; } /* * int xstrlen( PKMX_BYTE p ); * * Parameters: p Pointer to string to get length of * * Returns: length of string * * Called by: various functions * * xstrlen calculates the length of a string, ignoring some special chars. */ PKMX_WCHAR km::kbp::kmx::incxstr(PKMX_WCHAR p) { int deltaptr; // how many bytes to jump over if (*p == 0) return p; if (*p != UC_SENTINEL) { if (*p >= 0xD800 && *p <= 0xDBFF && *(p + 1) >= 0xDC00 && *(p + 1) <= 0xDFFF) return p + 2; return p + 1; } else { // UC_SENTINEL(FFFF) with UC_SENTINEL_EXTENDEDEND(0x10) == variable length if (*(p + 1) == CODE_EXTENDED) { p += 2; while (*(p - 1) && *p && *p != UC_SENTINEL_EXTENDEDEND) p++; if (*p == 0) return p; if (*p == UC_SENTINEL_EXTENDEDEND) return p + 1; } // UC_SENTINEL(FFFF) followed by other special switch (*(p + 1)) { case CODE_ANY: deltaptr = 3; break; case CODE_NOTANY: deltaptr = 3; break; case CODE_INDEX: deltaptr = 4; break; case CODE_USE: deltaptr = 3; break; case CODE_DEADKEY: deltaptr = 3; break; case CODE_CLEARCONTEXT: deltaptr = 3; break; case CODE_CALL: deltaptr = 3; break; case CODE_CONTEXTEX: deltaptr = 3; break; case CODE_IFOPT: deltaptr = 5; break; case CODE_IFSYSTEMSTORE: deltaptr = 5; break; case CODE_SETOPT: deltaptr = 4; break; case CODE_SETSYSTEMSTORE: deltaptr = 4; break; case CODE_RESETOPT: deltaptr = 3; break; case CODE_SAVEOPT: deltaptr = 3; break; default: deltaptr = 2; } // check for \0 between FFFF and next printable character for (int i = 0; i < deltaptr; i++) { if (*p==0) { return p; } p++; } return p; } return p; } PKMX_WCHAR km::kbp::kmx::decxstr(PKMX_WCHAR p, PKMX_WCHAR pStart) { if(p <= pStart) { return NULL; } p--; if(*p == UC_SENTINEL_EXTENDEDEND) { int n = 0; while(*p != UC_SENTINEL && n < 10) { p--; n++; } if(p < pStart) { // May be a malformed virtual key return pStart; } return p; } if(p == pStart) return p; // Don't allow test before pStart if(*p >= 0xDC00 && *p <= 0xDFFF && *(p-1) >= 0xD800 && *(p-1) <= 0xDBFF) { return p-1; } else if(*(p-1) == UC_SENTINEL) return p-1; else if(p > pStart+1 && *(p-2) == UC_SENTINEL) { switch(*(p-1)) { case CODE_ANY: case CODE_NOTANY: case CODE_USE: case CODE_DEADKEY: case CODE_CLEARCONTEXT: case CODE_CALL: case CODE_CONTEXTEX: case CODE_RESETOPT: case CODE_SAVEOPT: return p-2; } } else if(p > pStart+2 && *(p-3) == UC_SENTINEL) { switch(*(p-2)) { case CODE_INDEX: case CODE_SETOPT: case CODE_SETSYSTEMSTORE: return p-3; } } else if(p > pStart+3 && *(p-4) == UC_SENTINEL) { switch(*(p-3)) { case CODE_IFOPT: case CODE_IFSYSTEMSTORE: // I3432 return p-4; } } return p; } int km::kbp::kmx::xstrlen_ignoreifopt(PKMX_WCHAR p) { int i; for(i = 0; *p; i++, p=incxstr(p)) { if(*p == UC_SENTINEL && (*(p+1) == CODE_IFOPT || *(p+1) == CODE_IFSYSTEMSTORE)) i--; // I3432 } return i; } int km::kbp::kmx::xstrlen(PKMX_WCHAR p) { int i; for(i = 0; *p; i++, p=incxstr(p)); return i; } int km::kbp::kmx::xstrpos(PKMX_WCHAR p1, PKMX_WCHAR p) { int i; for(i = 0; p < p1; p = incxstr(p), i++); return i; } PKMX_WCHAR km::kbp::kmx::xstrchr(PKMX_WCHAR buf, PKMX_WCHAR chr) { for(PKMX_WCHAR q = incxstr(buf); *buf; buf = q, q = incxstr(buf)) if(!u16ncmp(buf, chr, (intptr_t)(q-buf))) return buf; return NULL; } int km::kbp::kmx::xchrcmp(PKMX_WCHAR ch1, PKMX_WCHAR ch2) { PKMX_WCHAR nch1 = incxstr(ch1); if(nch1 == ch1) return *ch2 - *ch1; /* comparing *ch2 to nul */ return u16ncmp(ch1, ch2, (intptr_t)(nch1-ch1)); } PKMX_WCHAR km::kbp::kmx::strtowstr(PKMX_CHAR in) { PKMX_WCHAR result; auto s = convert<char,char16_t>(in); result = new char16_t[s.length() + 1]; s.copy(result, s.length()); result[s.length()] = 0; return result; } PKMX_CHAR km::kbp::kmx::wstrtostr(PKMX_WCHAR in) { PKMX_CHAR result; auto s = convert<char16_t,char>(in); result = new char[s.length() + 1]; s.copy(result, s.length()); result[s.length()] = 0; return result; } <commit_msg>Update kmx_xstring.cpp<commit_after>/* Copyright: Copyright (C) 2003-2018 SIL International. Authors: mcdurdin */ #include <vector>> #include <array> #include <iterator> #include <codecvt> #include <locale> #include "kmx_processevent.h" #include "utfcodec.hpp" using namespace std; using namespace km::kbp; using namespace kmx; const km_kbp_cp *km::kbp::kmx::u16chr(const km_kbp_cp *p, km_kbp_cp ch) { while (*p) { if (*p == ch) return p; p++; } return ch == 0 ? p : NULL; } const km_kbp_cp *km::kbp::kmx::u16cpy(km_kbp_cp *dst, const km_kbp_cp *src) { km_kbp_cp *o = dst; while (*src) { *dst++ = *src++; } *dst = 0; return o; } const km_kbp_cp *km::kbp::kmx::u16ncpy(km_kbp_cp *dst, const km_kbp_cp *src, size_t max) { km_kbp_cp *o = dst; while (*src && max > 0) { *dst++ = *src++; max--; } while(max > 0) { *dst++ = 0; max--; } return o; } size_t km::kbp::kmx::u16len(const km_kbp_cp *p) { int i = 0; while (*p) { p++; i++; } return i; } int km::kbp::kmx::u16cmp(const km_kbp_cp *p, const km_kbp_cp *q) { while (*p && *q) { if (*p != *q) return *p - *q; p++; q++; } return *p - *q; } int km::kbp::kmx::u16icmp(const km_kbp_cp *p, const km_kbp_cp *q) { while (*p && *q) { if (toupper(*p) != toupper(*q)) return *p - *q; p++; q++; } return *p - *q; } int km::kbp::kmx::u16ncmp(const km_kbp_cp *p, const km_kbp_cp *q, size_t count) { while (*p && *q && count) { if (*p != *q) return *p - *q; p++; q++; count--; } if (count) return *p - *q; return 0; } km_kbp_cp *km::kbp::kmx::u16tok(km_kbp_cp *p, km_kbp_cp ch, km_kbp_cp **ctx) { if (!p) { p = *ctx; if (!p) return NULL; } km_kbp_cp *q = p; while (*q && *q != ch) { q++; } if (*q) { *q = 0; q++; while (*q == ch) q++; *ctx = q; } else { *ctx = NULL; } return p; } /* * int xstrlen( PKMX_BYTE p ); * * Parameters: p Pointer to string to get length of * * Returns: length of string * * Called by: various functions * * xstrlen calculates the length of a string, ignoring some special chars. */ PKMX_WCHAR km::kbp::kmx::incxstr(PKMX_WCHAR p) { if (*p == 0) return p; if (*p != UC_SENTINEL) { if (*p >= 0xD800 && *p <= 0xDBFF && *(p + 1) >= 0xDC00 && *(p + 1) <= 0xDFFF) return p + 2; return p + 1; } // UC_SENTINEL(FFFF) with UC_SENTINEL_EXTENDEDEND(0x10) == variable length if (*(p + 1) == CODE_EXTENDED) { p += 2; while (*p && *p != UC_SENTINEL_EXTENDEDEND) p++; if (*p == 0) return p; return p + 1; } // CODE_PTR defined in kmx_processevent.h for (int i = 0; i < size(CODE_PTR[0]); i++) { if (*(p + 1) == CODE_PTR[0][i]) { deltaptr = CODE_PTR[1][i]; break; } } // check for \0 between FFFF and next printable character for (int i = 0; i < deltaptr; i++) { if (*p == 0) { return p; } p++; } return p; } PKMX_WCHAR km::kbp::kmx::decxstr(PKMX_WCHAR p, PKMX_WCHAR pStart) { if(p <= pStart) { return NULL; } p--; if(*p == UC_SENTINEL_EXTENDEDEND) { int n = 0; while(*p != UC_SENTINEL && n < 10) { p--; n++; } if(p < pStart) { // May be a malformed virtual key return pStart; } return p; } if(p == pStart) return p; // Don't allow test before pStart if(*p >= 0xDC00 && *p <= 0xDFFF && *(p-1) >= 0xD800 && *(p-1) <= 0xDBFF) { return p-1; } else if(*(p-1) == UC_SENTINEL) return p-1; else if(p > pStart+1 && *(p-2) == UC_SENTINEL) { switch(*(p-1)) { case CODE_ANY: case CODE_NOTANY: case CODE_USE: case CODE_DEADKEY: case CODE_CLEARCONTEXT: case CODE_CALL: case CODE_CONTEXTEX: case CODE_RESETOPT: case CODE_SAVEOPT: return p-2; } } else if(p > pStart+2 && *(p-3) == UC_SENTINEL) { switch(*(p-2)) { case CODE_INDEX: case CODE_SETOPT: case CODE_SETSYSTEMSTORE: return p-3; } } else if(p > pStart+3 && *(p-4) == UC_SENTINEL) { switch(*(p-3)) { case CODE_IFOPT: case CODE_IFSYSTEMSTORE: // I3432 return p-4; } } return p; } int km::kbp::kmx::xstrlen_ignoreifopt(PKMX_WCHAR p) { int i; for(i = 0; *p; i++, p=incxstr(p)) { if(*p == UC_SENTINEL && (*(p+1) == CODE_IFOPT || *(p+1) == CODE_IFSYSTEMSTORE)) i--; // I3432 } return i; } int km::kbp::kmx::xstrlen(PKMX_WCHAR p) { int i; for(i = 0; *p; i++, p=incxstr(p)); return i; } int km::kbp::kmx::xstrpos(PKMX_WCHAR p1, PKMX_WCHAR p) { int i; for(i = 0; p < p1; p = incxstr(p), i++); return i; } PKMX_WCHAR km::kbp::kmx::xstrchr(PKMX_WCHAR buf, PKMX_WCHAR chr) { for(PKMX_WCHAR q = incxstr(buf); *buf; buf = q, q = incxstr(buf)) if(!u16ncmp(buf, chr, (intptr_t)(q-buf))) return buf; return NULL; } int km::kbp::kmx::xchrcmp(PKMX_WCHAR ch1, PKMX_WCHAR ch2) { PKMX_WCHAR nch1 = incxstr(ch1); if(nch1 == ch1) return *ch2 - *ch1; /* comparing *ch2 to nul */ return u16ncmp(ch1, ch2, (intptr_t)(nch1-ch1)); } PKMX_WCHAR km::kbp::kmx::strtowstr(PKMX_CHAR in) { PKMX_WCHAR result; auto s = convert<char,char16_t>(in); result = new char16_t[s.length() + 1]; s.copy(result, s.length()); result[s.length()] = 0; return result; } PKMX_CHAR km::kbp::kmx::wstrtostr(PKMX_WCHAR in) { PKMX_CHAR result; auto s = convert<char16_t,char>(in); result = new char[s.length() + 1]; s.copy(result, s.length()); result[s.length()] = 0; return result; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/user_controller.h" #include "base/utf_string_conversions.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "grit/generated_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" namespace chromeos { TEST(UserControllerTest, GetNameTooltip) { UserController guest_user_controller(NULL, false); EXPECT_EQ(UTF16ToWide(l10n_util::GetStringUTF16(IDS_ADD_USER)), guest_user_controller.GetNameTooltip()); UserController new_user_controller(NULL, true); EXPECT_EQ(UTF16ToWide(l10n_util::GetStringUTF16(IDS_GO_INCOGNITO_BUTTON)), new_user_controller.GetNameTooltip()); UserManager::User existing_user; existing_user.set_email("[email protected]"); UserController existing_user_controller(NULL, existing_user); EXPECT_EQ(L"someordinaryuser (domain.com)", existing_user_controller.GetNameTooltip()); } } // namespace chromeos <commit_msg>Disabled UserControllerTest<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/user_controller.h" #include "base/utf_string_conversions.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "grit/generated_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" namespace chromeos { // See http://crbug.com/92871 for details. TEST(UserControllerTest, DISABLED_GetNameTooltip) { UserController guest_user_controller(NULL, false); EXPECT_EQ(UTF16ToWide(l10n_util::GetStringUTF16(IDS_ADD_USER)), guest_user_controller.GetNameTooltip()); UserController new_user_controller(NULL, true); EXPECT_EQ(UTF16ToWide(l10n_util::GetStringUTF16(IDS_GO_INCOGNITO_BUTTON)), new_user_controller.GetNameTooltip()); UserManager::User existing_user; existing_user.set_email("[email protected]"); UserController existing_user_controller(NULL, existing_user); EXPECT_EQ(L"someordinaryuser (domain.com)", existing_user_controller.GetNameTooltip()); } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/keyboard_overlay_delegate.h" #include "base/memory/scoped_ptr.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/chromeos/frame/bubble_window.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/views/html_dialog_view.h" #include "chrome/browser/ui/webui/html_dialog_ui.h" #include "chrome/common/url_constants.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" void KeyboardOverlayDelegate::ShowDialog(gfx::NativeWindow owning_window) { Browser* browser = BrowserList::GetLastActive(); KeyboardOverlayDelegate* delegate = new KeyboardOverlayDelegate( UTF16ToWide(l10n_util::GetStringUTF16(IDS_KEYBOARD_OVERLAY_TITLE))); HtmlDialogView* html_view = new HtmlDialogView(browser->profile(), delegate); html_view->InitDialog(); chromeos::BubbleWindow::Create(owning_window, gfx::Rect(), chromeos::BubbleWindow::STYLE_XSHAPE, html_view); html_view->window()->Show(); } KeyboardOverlayDelegate::KeyboardOverlayDelegate( const std::wstring& title) : title_(title) { } KeyboardOverlayDelegate::~KeyboardOverlayDelegate() { } bool KeyboardOverlayDelegate::IsDialogModal() const { return true; } std::wstring KeyboardOverlayDelegate::GetDialogTitle() const { return title_; } GURL KeyboardOverlayDelegate::GetDialogContentURL() const { std::string url_string(chrome::kChromeUIKeyboardOverlayURL); return GURL(url_string); } void KeyboardOverlayDelegate::GetWebUIMessageHandlers( std::vector<WebUIMessageHandler*>* handlers) const { } void KeyboardOverlayDelegate::GetDialogSize( gfx::Size* size) const { size->SetSize(1280, 528); } std::string KeyboardOverlayDelegate::GetDialogArgs() const { return "[]"; } void KeyboardOverlayDelegate::OnDialogClosed( const std::string& json_retval) { delete this; return; } void KeyboardOverlayDelegate::OnCloseContents(TabContents* source, bool* out_close_dialog) { } bool KeyboardOverlayDelegate::ShouldShowDialogTitle() const { return false; } <commit_msg>Fix the position of the keyboard overlay.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/keyboard_overlay_delegate.h" #include "base/memory/scoped_ptr.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/chromeos/frame/bubble_window.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/views/html_dialog_view.h" #include "chrome/browser/ui/webui/html_dialog_ui.h" #include "chrome/common/url_constants.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" void KeyboardOverlayDelegate::ShowDialog(gfx::NativeWindow owning_window) { Browser* browser = BrowserList::GetLastActive(); KeyboardOverlayDelegate* delegate = new KeyboardOverlayDelegate( UTF16ToWide(l10n_util::GetStringUTF16(IDS_KEYBOARD_OVERLAY_TITLE))); HtmlDialogView* html_view = new HtmlDialogView(browser->profile(), delegate); html_view->InitDialog(); chromeos::BubbleWindow::Create(owning_window, gfx::Rect(), chromeos::BubbleWindow::STYLE_XSHAPE, html_view); html_view->window()->Show(); } KeyboardOverlayDelegate::KeyboardOverlayDelegate( const std::wstring& title) : title_(title) { } KeyboardOverlayDelegate::~KeyboardOverlayDelegate() { } bool KeyboardOverlayDelegate::IsDialogModal() const { return true; } std::wstring KeyboardOverlayDelegate::GetDialogTitle() const { return title_; } GURL KeyboardOverlayDelegate::GetDialogContentURL() const { std::string url_string(chrome::kChromeUIKeyboardOverlayURL); return GURL(url_string); } void KeyboardOverlayDelegate::GetWebUIMessageHandlers( std::vector<WebUIMessageHandler*>* handlers) const { } void KeyboardOverlayDelegate::GetDialogSize( gfx::Size* size) const { size->SetSize(1252, 516); } std::string KeyboardOverlayDelegate::GetDialogArgs() const { return "[]"; } void KeyboardOverlayDelegate::OnDialogClosed( const std::string& json_retval) { delete this; return; } void KeyboardOverlayDelegate::OnCloseContents(TabContents* source, bool* out_close_dialog) { } bool KeyboardOverlayDelegate::ShouldShowDialogTitle() const { return false; } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/devtools/device/adb/adb_device_provider.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/devtools/device/adb/adb_client_socket.h" #include "chrome/browser/devtools/device/adb/adb_device_info_query.h" namespace { const char kHostDevicesCommand[] = "host:devices"; const char kHostTransportCommand[] = "host:transport:%s|%s"; const char kLocalAbstractCommand[] = "localabstract:%s"; const int kAdbPort = 5037; static void RunCommand(const std::string& serial, const std::string& command, const AdbDeviceProvider::CommandCallback& callback) { std::string query = base::StringPrintf( kHostTransportCommand, serial.c_str(), command.c_str()); AdbClientSocket::AdbQuery(kAdbPort, query, callback); } static void ReceivedAdbDevices( const AdbDeviceProvider::SerialsCallback& callback, int result_code, const std::string& response) { std::vector<std::string> result; std::vector<std::string> serials; Tokenize(response, "\n", &serials); for (size_t i = 0; i < serials.size(); ++i) { std::vector<std::string> tokens; Tokenize(serials[i], "\t ", &tokens); result.push_back(tokens[0]); } callback.Run(result); } } // namespace void AdbDeviceProvider::QueryDevices(const SerialsCallback& callback) { AdbClientSocket::AdbQuery( kAdbPort, kHostDevicesCommand, base::Bind(&ReceivedAdbDevices, callback)); } void AdbDeviceProvider::QueryDeviceInfo(const std::string& serial, const DeviceInfoCallback& callback) { AdbDeviceInfoQuery::Start(base::Bind(&RunCommand, serial), callback); } void AdbDeviceProvider::OpenSocket(const std::string& serial, const std::string& socket_name, const SocketCallback& callback) { std::string request = base::StringPrintf(kLocalAbstractCommand, socket_name.c_str()); AdbClientSocket::TransportQuery(kAdbPort, serial, request, callback); } AdbDeviceProvider::~AdbDeviceProvider() { } <commit_msg>DevTools: handle IO errors in AdbDeviceProvider.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/devtools/device/adb/adb_device_provider.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/devtools/device/adb/adb_client_socket.h" #include "chrome/browser/devtools/device/adb/adb_device_info_query.h" namespace { const char kHostDevicesCommand[] = "host:devices"; const char kHostTransportCommand[] = "host:transport:%s|%s"; const char kLocalAbstractCommand[] = "localabstract:%s"; const int kAdbPort = 5037; static void RunCommand(const std::string& serial, const std::string& command, const AdbDeviceProvider::CommandCallback& callback) { std::string query = base::StringPrintf( kHostTransportCommand, serial.c_str(), command.c_str()); AdbClientSocket::AdbQuery(kAdbPort, query, callback); } static void ReceivedAdbDevices( const AdbDeviceProvider::SerialsCallback& callback, int result_code, const std::string& response) { std::vector<std::string> result; if (result_code < 0) { callback.Run(result); return; } std::vector<std::string> serials; Tokenize(response, "\n", &serials); for (size_t i = 0; i < serials.size(); ++i) { std::vector<std::string> tokens; Tokenize(serials[i], "\t ", &tokens); result.push_back(tokens[0]); } callback.Run(result); } } // namespace void AdbDeviceProvider::QueryDevices(const SerialsCallback& callback) { AdbClientSocket::AdbQuery( kAdbPort, kHostDevicesCommand, base::Bind(&ReceivedAdbDevices, callback)); } void AdbDeviceProvider::QueryDeviceInfo(const std::string& serial, const DeviceInfoCallback& callback) { AdbDeviceInfoQuery::Start(base::Bind(&RunCommand, serial), callback); } void AdbDeviceProvider::OpenSocket(const std::string& serial, const std::string& socket_name, const SocketCallback& callback) { std::string request = base::StringPrintf(kLocalAbstractCommand, socket_name.c_str()); AdbClientSocket::TransportQuery(kAdbPort, serial, request, callback); } AdbDeviceProvider::~AdbDeviceProvider() { } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/string16.h" #include "base/test/test_timeouts.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { class OptionsUITest : public UITest { public: OptionsUITest() { dom_automation_enabled_ = true; } void AssertIsOptionsPage(TabProxy* tab) { std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE); // The only guarantee we can make about the title of a settings tab is that // it should contain IDS_SETTINGS_TITLE somewhere. ASSERT_FALSE(WideToUTF16Hack(title).find(expected_title) == string16::npos); } }; // Flaky: http://crbug.com/77375 TEST_F(OptionsUITest, FLAKY_LoadOptionsByURL) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); // Go to the options tab via URL. NavigateToURL(GURL(chrome::kChromeUISettingsURL)); AssertIsOptionsPage(tab); } // Flaky, and takes very long to fail. http://crbug.com/64619. TEST_F(OptionsUITest, DISABLED_CommandOpensOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); } // Flaky, and takes very long to fail. http://crbug.com/48521 TEST_F(OptionsUITest, DISABLED_CommandAgainGoesBackToOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); // Switch to first tab and run command again. ASSERT_TRUE(browser->ActivateTab(0)); ASSERT_TRUE(browser->WaitForTabToBecomeActive( 0, TestTimeouts::action_max_timeout_ms())); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); // Ensure the options ui tab is active. ASSERT_TRUE(browser->WaitForTabToBecomeActive( 1, TestTimeouts::action_max_timeout_ms())); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } // Flaky, and takes very long to fail. http://crbug.com/48521 TEST_F(OptionsUITest, DISABLED_TwoCommandsOneTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } } // namespace <commit_msg>Add a NavBarCheck test case for OptionsUITest.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/string16.h" #include "base/test/test_timeouts.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { class OptionsUITest : public UITest { public: OptionsUITest() { dom_automation_enabled_ = true; } bool WaitForOptionsUI(TabProxy* tab) { return WaitUntilJavaScriptCondition(tab, L"", L"domAutomationController.send(" L" location.protocol == 'chrome:' && " L" document.readyState == 'complete')", TestTimeouts::huge_test_timeout_ms()); } scoped_refptr<TabProxy> GetOptionsUITab() { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); EXPECT_TRUE(browser.get()); if (!browser.get()) return NULL; scoped_refptr<TabProxy> tab = browser->GetActiveTab(); EXPECT_TRUE(tab.get()); if (!tab.get()) return NULL; bool success = tab->NavigateToURL(GURL(chrome::kChromeUISettingsURL)); EXPECT_TRUE(success); if (!success) return NULL; success = WaitForOptionsUI(tab); EXPECT_TRUE(success); if (!success) return NULL; return tab; } void AssertIsOptionsPage(TabProxy* tab) { std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE); // The only guarantee we can make about the title of a settings tab is that // it should contain IDS_SETTINGS_TITLE somewhere. ASSERT_FALSE(WideToUTF16Hack(title).find(expected_title) == string16::npos); } }; TEST_F(OptionsUITest, LoadOptionsByURL) { scoped_refptr<TabProxy> tab = GetOptionsUITab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); } // Flaky, and takes very long to fail. http://crbug.com/64619. TEST_F(OptionsUITest, DISABLED_CommandOpensOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); } // Flaky, and takes very long to fail. http://crbug.com/48521 TEST_F(OptionsUITest, DISABLED_CommandAgainGoesBackToOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); // Switch to first tab and run command again. ASSERT_TRUE(browser->ActivateTab(0)); ASSERT_TRUE(browser->WaitForTabToBecomeActive( 0, TestTimeouts::action_max_timeout_ms())); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); // Ensure the options ui tab is active. ASSERT_TRUE(browser->WaitForTabToBecomeActive( 1, TestTimeouts::action_max_timeout_ms())); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } // Flaky, and takes very long to fail. http://crbug.com/48521 TEST_F(OptionsUITest, DISABLED_TwoCommandsOneTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } // Navigates to settings page and do sanity check on settings sections. TEST_F(OptionsUITest, NavBarCheck) { scoped_refptr<TabProxy> tab = GetOptionsUITab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); // Check navbar's existence. bool navbar_exist = false; ASSERT_TRUE(tab->ExecuteAndExtractBool(L"", L"domAutomationController.send(" L"!!document.getElementById('navbar'))", &navbar_exist)); ASSERT_EQ(true, navbar_exist); // Check section headers in navbar. // For ChromeOS, there should be 1 + 6: // search, basics, personal, systerm, internet, under the hood and users // For other platforms, there should 1 + 3: // search, basics, personal and under the hood. #if defined(OS_CHROMEOS) const int kExpectedSections = 1 + 6; #else const int kExpectedSections = 1 + 3; #endif int num_of_sections = 0; ASSERT_TRUE(tab->ExecuteAndExtractInt(L"", L"domAutomationController.send(" L"document.getElementById('navbar').children.length)", &num_of_sections)); ASSERT_EQ(kExpectedSections, num_of_sections); } } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/sandboxed_extension_unpacker.h" #include <set> #include "base/base64.h" #include "base/crypto/signature_verifier.h" #include "base/file_util.h" #include "base/file_util_proxy.h" #include "base/message_loop.h" #include "base/scoped_handle.h" #include "base/task.h" #include "base/utf_string_conversions.h" // TODO(viettrungluu): delete me. #include "chrome/browser/browser_thread.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/renderer_host/resource_dispatcher_host.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_l10n_util.h" #include "chrome/common/extensions/extension_unpacker.h" #include "chrome/common/json_value_serializer.h" #include "gfx/codec/png_codec.h" #include "third_party/skia/include/core/SkBitmap.h" const char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = "Cr24"; SandboxedExtensionUnpacker::SandboxedExtensionUnpacker( const FilePath& crx_path, const FilePath& temp_path, ResourceDispatcherHost* rdh, SandboxedExtensionUnpackerClient* client) : crx_path_(crx_path), temp_path_(temp_path), thread_identifier_(BrowserThread::ID_COUNT), rdh_(rdh), client_(client), got_response_(false) { } void SandboxedExtensionUnpacker::Start() { // We assume that we are started on the thread that the client wants us to do // file IO on. CHECK(BrowserThread::GetCurrentThreadIdentifier(&thread_identifier_)); // Create a temporary directory to work in. if (!temp_dir_.CreateUniqueTempDirUnderPath(temp_path_)) { ReportFailure("Could not create temporary directory."); return; } // Initialize the path that will eventually contain the unpacked extension. extension_root_ = temp_dir_.path().AppendASCII( extension_filenames::kTempExtensionName); // Extract the public key and validate the package. if (!ValidateSignature()) return; // ValidateSignature() already reported the error. // Copy the crx file into our working directory. FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName()); if (!file_util::CopyFile(crx_path_, temp_crx_path)) { ReportFailure("Failed to copy extension file to temporary directory."); return; } // If we are supposed to use a subprocess, kick off the subprocess. // // TODO(asargent) we shouldn't need to do this branch here - instead // UtilityProcessHost should handle it for us. (http://crbug.com/19192) bool use_utility_process = rdh_ && !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess); if (use_utility_process) { // The utility process will have access to the directory passed to // SandboxedExtensionUnpacker. That directory should not contain a // symlink or NTFS reparse point. When the path is used, following // the link/reparse point will cause file system access outside the // sandbox path, and the sandbox will deny the operation. FilePath link_free_crx_path; if (!file_util::NormalizeFilePath(temp_crx_path, &link_free_crx_path)) { LOG(ERROR) << "Could not get the normalized path of " << temp_crx_path.value(); #if defined (OS_WIN) // On windows, it is possible to mount a disk without the root of that // disk having a drive letter. The sandbox does not support this. // See crbug/49530 . ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that starts " "with a drive letter and does not contain a junction, mount " "point, or symlink. No such path exists for your profile."); #else ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that does " "not contain a symlink. No such path exists for your profile."); #endif return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod( this, &SandboxedExtensionUnpacker::StartProcessOnIOThread, link_free_crx_path)); } else { // Otherwise, unpack the extension in this process. ExtensionUnpacker unpacker(temp_crx_path); if (unpacker.Run() && unpacker.DumpImagesToFile() && unpacker.DumpMessageCatalogsToFile()) { OnUnpackExtensionSucceeded(*unpacker.parsed_manifest()); } else { OnUnpackExtensionFailed(unpacker.error_message()); } } } SandboxedExtensionUnpacker::~SandboxedExtensionUnpacker() { base::FileUtilProxy::Delete( BrowserThread::GetMessageLoopProxyForThread(thread_identifier_), temp_dir_.Take(), true, NULL); } void SandboxedExtensionUnpacker::StartProcessOnIOThread( const FilePath& temp_crx_path) { UtilityProcessHost* host = new UtilityProcessHost( rdh_, this, thread_identifier_); host->StartExtensionUnpacker(temp_crx_path); } void SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded( const DictionaryValue& manifest) { // Skip check for unittests. if (thread_identifier_ != BrowserThread::ID_COUNT) DCHECK(BrowserThread::CurrentlyOn(thread_identifier_)); got_response_ = true; scoped_ptr<DictionaryValue> final_manifest(RewriteManifestFile(manifest)); if (!final_manifest.get()) return; // Create an extension object that refers to the temporary location the // extension was unpacked to. We use this until the extension is finally // installed. For example, the install UI shows images from inside the // extension. // Localize manifest now, so confirm UI gets correct extension name. std::string error; if (!extension_l10n_util::LocalizeExtension(extension_root_, final_manifest.get(), &error)) { ReportFailure(error); return; } extension_ = Extension::Create( extension_root_, Extension::INTERNAL, *final_manifest, true, &error); if (!extension_.get()) { ReportFailure(std::string("Manifest is invalid: ") + error); return; } if (!RewriteImageFiles()) return; if (!RewriteCatalogFiles()) return; ReportSuccess(); } void SandboxedExtensionUnpacker::OnUnpackExtensionFailed( const std::string& error) { DCHECK(BrowserThread::CurrentlyOn(thread_identifier_)); got_response_ = true; ReportFailure(error); } void SandboxedExtensionUnpacker::OnProcessCrashed() { // Don't report crashes if they happen after we got a response. if (got_response_) return; ReportFailure("Utility process crashed while trying to install."); } bool SandboxedExtensionUnpacker::ValidateSignature() { ScopedStdioHandle file(file_util::OpenFile(crx_path_, "rb")); if (!file.get()) { ReportFailure("Could not open crx file for reading"); return false; } // Read and verify the header. ExtensionHeader header; size_t len; // TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it // appears that we don't have any endian/alignment aware serialization // code in the code base. So for now, this assumes that we're running // on a little endian machine with 4 byte alignment. len = fread(&header, 1, sizeof(ExtensionHeader), file.get()); if (len < sizeof(ExtensionHeader)) { ReportFailure("Invalid crx header"); return false; } if (strncmp(kExtensionHeaderMagic, header.magic, sizeof(header.magic))) { ReportFailure("Bad magic number"); return false; } if (header.version != kCurrentVersion) { ReportFailure("Bad version number"); return false; } if (header.key_size > kMaxPublicKeySize || header.signature_size > kMaxSignatureSize) { ReportFailure("Excessively large key or signature"); return false; } if (header.key_size == 0) { ReportFailure("Key length is zero"); return false; } std::vector<uint8> key; key.resize(header.key_size); len = fread(&key.front(), sizeof(uint8), header.key_size, file.get()); if (len < header.key_size) { ReportFailure("Invalid public key"); return false; } std::vector<uint8> signature; signature.resize(header.signature_size); len = fread(&signature.front(), sizeof(uint8), header.signature_size, file.get()); if (len < header.signature_size) { ReportFailure("Invalid signature"); return false; } base::SignatureVerifier verifier; if (!verifier.VerifyInit(extension_misc::kSignatureAlgorithm, sizeof(extension_misc::kSignatureAlgorithm), &signature.front(), signature.size(), &key.front(), key.size())) { ReportFailure("Signature verification initialization failed. " "This is most likely caused by a public key in " "the wrong format (should encode algorithm)."); return false; } unsigned char buf[1 << 12]; while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0) verifier.VerifyUpdate(buf, len); if (!verifier.VerifyFinal()) { ReportFailure("Signature verification failed"); return false; } base::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()), key.size()), &public_key_); return true; } void SandboxedExtensionUnpacker::ReportFailure(const std::string& error) { client_->OnUnpackFailure(error); } void SandboxedExtensionUnpacker::ReportSuccess() { // Client takes ownership of temporary directory and extension. client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_, extension_); extension_ = NULL; } DictionaryValue* SandboxedExtensionUnpacker::RewriteManifestFile( const DictionaryValue& manifest) { // Add the public key extracted earlier to the parsed manifest and overwrite // the original manifest. We do this to ensure the manifest doesn't contain an // exploitable bug that could be used to compromise the browser. scoped_ptr<DictionaryValue> final_manifest( static_cast<DictionaryValue*>(manifest.DeepCopy())); final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_); std::string manifest_json; JSONStringValueSerializer serializer(&manifest_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*final_manifest)) { ReportFailure("Error serializing manifest.json."); return NULL; } FilePath manifest_path = extension_root_.Append(Extension::kManifestFilename); if (!file_util::WriteFile(manifest_path, manifest_json.data(), manifest_json.size())) { ReportFailure("Error saving manifest.json."); return NULL; } return final_manifest.release(); } bool SandboxedExtensionUnpacker::RewriteImageFiles() { ExtensionUnpacker::DecodedImages images; if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) { ReportFailure("Couldn't read image data from disk."); return false; } // Delete any images that may be used by the browser. We're going to write // out our own versions of the parsed images, and we want to make sure the // originals are gone for good. std::set<FilePath> image_paths = extension_->GetBrowserImages(); if (image_paths.size() != images.size()) { ReportFailure("Decoded images don't match what's in the manifest."); return false; } for (std::set<FilePath>::iterator it = image_paths.begin(); it != image_paths.end(); ++it) { FilePath path = *it; if (path.IsAbsolute() || path.ReferencesParent()) { ReportFailure("Invalid path for browser image."); return false; } if (!file_util::Delete(extension_root_.Append(path), false)) { ReportFailure("Error removing old image file."); return false; } } // Write our parsed images back to disk as well. for (size_t i = 0; i < images.size(); ++i) { const SkBitmap& image = images[i].a; FilePath path_suffix = images[i].b; if (path_suffix.IsAbsolute() || path_suffix.ReferencesParent()) { ReportFailure("Invalid path for bitmap image."); return false; } FilePath path = extension_root_.Append(path_suffix); std::vector<unsigned char> image_data; // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even // though they may originally be .jpg, etc. Figure something out. // http://code.google.com/p/chromium/issues/detail?id=12459 if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, false, &image_data)) { ReportFailure("Error re-encoding theme image."); return false; } // Note: we're overwriting existing files that the utility process wrote, // so we can be sure the directory exists. const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) { ReportFailure("Error saving theme image."); return false; } } return true; } bool SandboxedExtensionUnpacker::RewriteCatalogFiles() { DictionaryValue catalogs; if (!ExtensionUnpacker::ReadMessageCatalogsFromFile(temp_dir_.path(), &catalogs)) { ReportFailure("Could not read catalog data from disk."); return false; } // Write our parsed catalogs back to disk. for (DictionaryValue::key_iterator key_it = catalogs.begin_keys(); key_it != catalogs.end_keys(); ++key_it) { DictionaryValue* catalog; if (!catalogs.GetDictionaryWithoutPathExpansion(*key_it, &catalog)) { ReportFailure("Invalid catalog data."); return false; } // TODO(viettrungluu): Fix the |FilePath::FromWStringHack(UTF8ToWide())| // hack and remove the corresponding #include. FilePath relative_path = FilePath::FromWStringHack(UTF8ToWide(*key_it)); relative_path = relative_path.Append(Extension::kMessagesFilename); if (relative_path.IsAbsolute() || relative_path.ReferencesParent()) { ReportFailure("Invalid path for catalog."); return false; } FilePath path = extension_root_.Append(relative_path); std::string catalog_json; JSONStringValueSerializer serializer(&catalog_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*catalog)) { ReportFailure("Error serializing catalog."); return false; } // Note: we're overwriting existing files that the utility process read, // so we can be sure the directory exists. if (!file_util::WriteFile(path, catalog_json.c_str(), catalog_json.size())) { ReportFailure("Error saving catalog."); return false; } } return true; } <commit_msg>SandboxedExtensionUnpacker::ValidateSignature should check for an empty signature<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/sandboxed_extension_unpacker.h" #include <set> #include "base/base64.h" #include "base/crypto/signature_verifier.h" #include "base/file_util.h" #include "base/file_util_proxy.h" #include "base/message_loop.h" #include "base/scoped_handle.h" #include "base/task.h" #include "base/utf_string_conversions.h" // TODO(viettrungluu): delete me. #include "chrome/browser/browser_thread.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/renderer_host/resource_dispatcher_host.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_l10n_util.h" #include "chrome/common/extensions/extension_unpacker.h" #include "chrome/common/json_value_serializer.h" #include "gfx/codec/png_codec.h" #include "third_party/skia/include/core/SkBitmap.h" const char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = "Cr24"; SandboxedExtensionUnpacker::SandboxedExtensionUnpacker( const FilePath& crx_path, const FilePath& temp_path, ResourceDispatcherHost* rdh, SandboxedExtensionUnpackerClient* client) : crx_path_(crx_path), temp_path_(temp_path), thread_identifier_(BrowserThread::ID_COUNT), rdh_(rdh), client_(client), got_response_(false) { } void SandboxedExtensionUnpacker::Start() { // We assume that we are started on the thread that the client wants us to do // file IO on. CHECK(BrowserThread::GetCurrentThreadIdentifier(&thread_identifier_)); // Create a temporary directory to work in. if (!temp_dir_.CreateUniqueTempDirUnderPath(temp_path_)) { ReportFailure("Could not create temporary directory."); return; } // Initialize the path that will eventually contain the unpacked extension. extension_root_ = temp_dir_.path().AppendASCII( extension_filenames::kTempExtensionName); // Extract the public key and validate the package. if (!ValidateSignature()) return; // ValidateSignature() already reported the error. // Copy the crx file into our working directory. FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName()); if (!file_util::CopyFile(crx_path_, temp_crx_path)) { ReportFailure("Failed to copy extension file to temporary directory."); return; } // If we are supposed to use a subprocess, kick off the subprocess. // // TODO(asargent) we shouldn't need to do this branch here - instead // UtilityProcessHost should handle it for us. (http://crbug.com/19192) bool use_utility_process = rdh_ && !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess); if (use_utility_process) { // The utility process will have access to the directory passed to // SandboxedExtensionUnpacker. That directory should not contain a // symlink or NTFS reparse point. When the path is used, following // the link/reparse point will cause file system access outside the // sandbox path, and the sandbox will deny the operation. FilePath link_free_crx_path; if (!file_util::NormalizeFilePath(temp_crx_path, &link_free_crx_path)) { LOG(ERROR) << "Could not get the normalized path of " << temp_crx_path.value(); #if defined (OS_WIN) // On windows, it is possible to mount a disk without the root of that // disk having a drive letter. The sandbox does not support this. // See crbug/49530 . ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that starts " "with a drive letter and does not contain a junction, mount " "point, or symlink. No such path exists for your profile."); #else ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that does " "not contain a symlink. No such path exists for your profile."); #endif return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod( this, &SandboxedExtensionUnpacker::StartProcessOnIOThread, link_free_crx_path)); } else { // Otherwise, unpack the extension in this process. ExtensionUnpacker unpacker(temp_crx_path); if (unpacker.Run() && unpacker.DumpImagesToFile() && unpacker.DumpMessageCatalogsToFile()) { OnUnpackExtensionSucceeded(*unpacker.parsed_manifest()); } else { OnUnpackExtensionFailed(unpacker.error_message()); } } } SandboxedExtensionUnpacker::~SandboxedExtensionUnpacker() { base::FileUtilProxy::Delete( BrowserThread::GetMessageLoopProxyForThread(thread_identifier_), temp_dir_.Take(), true, NULL); } void SandboxedExtensionUnpacker::StartProcessOnIOThread( const FilePath& temp_crx_path) { UtilityProcessHost* host = new UtilityProcessHost( rdh_, this, thread_identifier_); host->StartExtensionUnpacker(temp_crx_path); } void SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded( const DictionaryValue& manifest) { // Skip check for unittests. if (thread_identifier_ != BrowserThread::ID_COUNT) DCHECK(BrowserThread::CurrentlyOn(thread_identifier_)); got_response_ = true; scoped_ptr<DictionaryValue> final_manifest(RewriteManifestFile(manifest)); if (!final_manifest.get()) return; // Create an extension object that refers to the temporary location the // extension was unpacked to. We use this until the extension is finally // installed. For example, the install UI shows images from inside the // extension. // Localize manifest now, so confirm UI gets correct extension name. std::string error; if (!extension_l10n_util::LocalizeExtension(extension_root_, final_manifest.get(), &error)) { ReportFailure(error); return; } extension_ = Extension::Create( extension_root_, Extension::INTERNAL, *final_manifest, true, &error); if (!extension_.get()) { ReportFailure(std::string("Manifest is invalid: ") + error); return; } if (!RewriteImageFiles()) return; if (!RewriteCatalogFiles()) return; ReportSuccess(); } void SandboxedExtensionUnpacker::OnUnpackExtensionFailed( const std::string& error) { DCHECK(BrowserThread::CurrentlyOn(thread_identifier_)); got_response_ = true; ReportFailure(error); } void SandboxedExtensionUnpacker::OnProcessCrashed() { // Don't report crashes if they happen after we got a response. if (got_response_) return; ReportFailure("Utility process crashed while trying to install."); } bool SandboxedExtensionUnpacker::ValidateSignature() { ScopedStdioHandle file(file_util::OpenFile(crx_path_, "rb")); if (!file.get()) { ReportFailure("Could not open crx file for reading"); return false; } // Read and verify the header. ExtensionHeader header; size_t len; // TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it // appears that we don't have any endian/alignment aware serialization // code in the code base. So for now, this assumes that we're running // on a little endian machine with 4 byte alignment. len = fread(&header, 1, sizeof(ExtensionHeader), file.get()); if (len < sizeof(ExtensionHeader)) { ReportFailure("Invalid crx header"); return false; } if (strncmp(kExtensionHeaderMagic, header.magic, sizeof(header.magic))) { ReportFailure("Bad magic number"); return false; } if (header.version != kCurrentVersion) { ReportFailure("Bad version number"); return false; } if (header.key_size > kMaxPublicKeySize || header.signature_size > kMaxSignatureSize) { ReportFailure("Excessively large key or signature"); return false; } if (header.key_size == 0) { ReportFailure("Key length is zero"); return false; } if (header.signature_size == 0) { ReportFailure("Signature length is zero"); return false; } std::vector<uint8> key; key.resize(header.key_size); len = fread(&key.front(), sizeof(uint8), header.key_size, file.get()); if (len < header.key_size) { ReportFailure("Invalid public key"); return false; } std::vector<uint8> signature; signature.resize(header.signature_size); len = fread(&signature.front(), sizeof(uint8), header.signature_size, file.get()); if (len < header.signature_size) { ReportFailure("Invalid signature"); return false; } base::SignatureVerifier verifier; if (!verifier.VerifyInit(extension_misc::kSignatureAlgorithm, sizeof(extension_misc::kSignatureAlgorithm), &signature.front(), signature.size(), &key.front(), key.size())) { ReportFailure("Signature verification initialization failed. " "This is most likely caused by a public key in " "the wrong format (should encode algorithm)."); return false; } unsigned char buf[1 << 12]; while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0) verifier.VerifyUpdate(buf, len); if (!verifier.VerifyFinal()) { ReportFailure("Signature verification failed"); return false; } base::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()), key.size()), &public_key_); return true; } void SandboxedExtensionUnpacker::ReportFailure(const std::string& error) { client_->OnUnpackFailure(error); } void SandboxedExtensionUnpacker::ReportSuccess() { // Client takes ownership of temporary directory and extension. client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_, extension_); extension_ = NULL; } DictionaryValue* SandboxedExtensionUnpacker::RewriteManifestFile( const DictionaryValue& manifest) { // Add the public key extracted earlier to the parsed manifest and overwrite // the original manifest. We do this to ensure the manifest doesn't contain an // exploitable bug that could be used to compromise the browser. scoped_ptr<DictionaryValue> final_manifest( static_cast<DictionaryValue*>(manifest.DeepCopy())); final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_); std::string manifest_json; JSONStringValueSerializer serializer(&manifest_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*final_manifest)) { ReportFailure("Error serializing manifest.json."); return NULL; } FilePath manifest_path = extension_root_.Append(Extension::kManifestFilename); if (!file_util::WriteFile(manifest_path, manifest_json.data(), manifest_json.size())) { ReportFailure("Error saving manifest.json."); return NULL; } return final_manifest.release(); } bool SandboxedExtensionUnpacker::RewriteImageFiles() { ExtensionUnpacker::DecodedImages images; if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) { ReportFailure("Couldn't read image data from disk."); return false; } // Delete any images that may be used by the browser. We're going to write // out our own versions of the parsed images, and we want to make sure the // originals are gone for good. std::set<FilePath> image_paths = extension_->GetBrowserImages(); if (image_paths.size() != images.size()) { ReportFailure("Decoded images don't match what's in the manifest."); return false; } for (std::set<FilePath>::iterator it = image_paths.begin(); it != image_paths.end(); ++it) { FilePath path = *it; if (path.IsAbsolute() || path.ReferencesParent()) { ReportFailure("Invalid path for browser image."); return false; } if (!file_util::Delete(extension_root_.Append(path), false)) { ReportFailure("Error removing old image file."); return false; } } // Write our parsed images back to disk as well. for (size_t i = 0; i < images.size(); ++i) { const SkBitmap& image = images[i].a; FilePath path_suffix = images[i].b; if (path_suffix.IsAbsolute() || path_suffix.ReferencesParent()) { ReportFailure("Invalid path for bitmap image."); return false; } FilePath path = extension_root_.Append(path_suffix); std::vector<unsigned char> image_data; // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even // though they may originally be .jpg, etc. Figure something out. // http://code.google.com/p/chromium/issues/detail?id=12459 if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, false, &image_data)) { ReportFailure("Error re-encoding theme image."); return false; } // Note: we're overwriting existing files that the utility process wrote, // so we can be sure the directory exists. const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) { ReportFailure("Error saving theme image."); return false; } } return true; } bool SandboxedExtensionUnpacker::RewriteCatalogFiles() { DictionaryValue catalogs; if (!ExtensionUnpacker::ReadMessageCatalogsFromFile(temp_dir_.path(), &catalogs)) { ReportFailure("Could not read catalog data from disk."); return false; } // Write our parsed catalogs back to disk. for (DictionaryValue::key_iterator key_it = catalogs.begin_keys(); key_it != catalogs.end_keys(); ++key_it) { DictionaryValue* catalog; if (!catalogs.GetDictionaryWithoutPathExpansion(*key_it, &catalog)) { ReportFailure("Invalid catalog data."); return false; } // TODO(viettrungluu): Fix the |FilePath::FromWStringHack(UTF8ToWide())| // hack and remove the corresponding #include. FilePath relative_path = FilePath::FromWStringHack(UTF8ToWide(*key_it)); relative_path = relative_path.Append(Extension::kMessagesFilename); if (relative_path.IsAbsolute() || relative_path.ReferencesParent()) { ReportFailure("Invalid path for catalog."); return false; } FilePath path = extension_root_.Append(relative_path); std::string catalog_json; JSONStringValueSerializer serializer(&catalog_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*catalog)) { ReportFailure("Error serializing catalog."); return false; } // Note: we're overwriting existing files that the utility process read, // so we can be sure the directory exists. if (!file_util::WriteFile(path, catalog_json.c_str(), catalog_json.size())) { ReportFailure("Error saving catalog."); return false; } } return true; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/container/pose/pose_container.h" #include "modules/common/log.h" namespace apollo { namespace prediction { using apollo::perception::PerceptionObstacle; using apollo::perception::Point; using apollo::localization::LocalizationEstimate; std::mutex PoseContainer::g_mutex_; void PoseContainer::Insert(const ::google::protobuf::Message& message) { Update(dynamic_cast<const LocalizationEstimate&>(message)); } void PoseContainer::Update( const localization::LocalizationEstimate &localization) { if (!localization.header().has_timestamp_sec()) { AERROR << "Localization message has no timestamp [" << localization.ShortDebugString() << "]."; return; } else if (!localization.has_pose()) { AERROR << "Localization message has no pose [" << localization.ShortDebugString() << "]."; } else if (!localization.pose().has_position() || !localization.pose().has_linear_velocity()) { AERROR << "Localization message has no position or linear velocity [" << localization.ShortDebugString() << "]."; return; } std::lock_guard<std::mutex> lock(g_mutex_); if (obstacle_ptr_.get() == nullptr) { obstacle_ptr_.reset(new PerceptionObstacle()); } obstacle_ptr_->set_id(ID); Point position; position.set_x(localization.pose().position().x()); position.set_y(localization.pose().position().y()); position.set_z(localization.pose().position().z()); obstacle_ptr_->mutable_position()->CopyFrom(position); Point velocity; velocity.set_x(localization.pose().linear_velocity().x()); velocity.set_y(localization.pose().linear_velocity().y()); velocity.set_z(localization.pose().linear_velocity().z()); obstacle_ptr_->mutable_velocity()->CopyFrom(velocity); obstacle_ptr_->set_type(type_); obstacle_ptr_->set_timestamp(localization.header().timestamp_sec()); ADEBUG << "ADC obstacle [" << obstacle_ptr_->ShortDebugString() << "]."; } double PoseContainer::GetTimestamp() { if (obstacle_ptr_ != nullptr) { return obstacle_ptr_->timestamp(); } else { return 0.0; } } PerceptionObstacle* PoseContainer::ToPerceptionObstacle() { std::lock_guard<std::mutex> lock(g_mutex_); return obstacle_ptr_.get(); } } // namespace prediction } // namespace apollo <commit_msg>Prediction: fixed a small checkup<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/container/pose/pose_container.h" #include "modules/common/log.h" namespace apollo { namespace prediction { using apollo::perception::PerceptionObstacle; using apollo::perception::Point; using apollo::localization::LocalizationEstimate; std::mutex PoseContainer::g_mutex_; void PoseContainer::Insert(const ::google::protobuf::Message& message) { Update(dynamic_cast<const LocalizationEstimate&>(message)); } void PoseContainer::Update( const localization::LocalizationEstimate &localization) { if (!localization.has_header() || !localization.header().has_timestamp_sec()) { AERROR << "Localization message has no timestamp [" << localization.ShortDebugString() << "]."; return; } else if (!localization.has_pose()) { AERROR << "Localization message has no pose [" << localization.ShortDebugString() << "]."; } else if (!localization.pose().has_position() || !localization.pose().has_linear_velocity()) { AERROR << "Localization message has no position or linear velocity [" << localization.ShortDebugString() << "]."; return; } std::lock_guard<std::mutex> lock(g_mutex_); if (obstacle_ptr_.get() == nullptr) { obstacle_ptr_.reset(new PerceptionObstacle()); } obstacle_ptr_->set_id(ID); Point position; position.set_x(localization.pose().position().x()); position.set_y(localization.pose().position().y()); position.set_z(localization.pose().position().z()); obstacle_ptr_->mutable_position()->CopyFrom(position); Point velocity; velocity.set_x(localization.pose().linear_velocity().x()); velocity.set_y(localization.pose().linear_velocity().y()); velocity.set_z(localization.pose().linear_velocity().z()); obstacle_ptr_->mutable_velocity()->CopyFrom(velocity); obstacle_ptr_->set_type(type_); obstacle_ptr_->set_timestamp(localization.header().timestamp_sec()); ADEBUG << "ADC obstacle [" << obstacle_ptr_->ShortDebugString() << "]."; } double PoseContainer::GetTimestamp() { if (obstacle_ptr_ != nullptr) { return obstacle_ptr_->timestamp(); } else { return 0.0; } } PerceptionObstacle* PoseContainer::ToPerceptionObstacle() { std::lock_guard<std::mutex> lock(g_mutex_); return obstacle_ptr_.get(); } } // namespace prediction } // namespace apollo <|endoftext|>
<commit_before>#pragma once #include "blackhole/detail/stream/stream.hpp" #include "blackhole/sink/syslog.hpp" #include "blackhole/utils/underlying.hpp" namespace blackhole { namespace defaults { enum class severity { debug, notice, info, warning, error }; inline void map_severity(aux::attachable_ostringstream& stream, const severity& level) { static const char* describe[] = { "DEBUG", "NOTICE", "INFO", "WARN", "ERROR" }; typedef blackhole::aux::underlying_type<severity>::type level_type; auto value = static_cast<level_type>(level); if(value < static_cast<level_type>(sizeof(describe) / sizeof(describe[0])) && value > 0) { stream << describe[value]; } else { stream << value; } } } // namespace defaults namespace sink { template<> struct priority_traits<defaults::severity> { static inline priority_t map(defaults::severity lvl) { switch (lvl) { case defaults::severity::debug: return priority_t::debug; case defaults::severity::notice: return priority_t::info; case defaults::severity::info: return priority_t::info; case defaults::severity::warning: return priority_t::warning; case defaults::severity::error: return priority_t::err; } return priority_t::debug; } }; } // namespace sink } // namespace blackhole <commit_msg>[Defaults] Fixed mapping of debug severity to str<commit_after>#pragma once #include "blackhole/detail/stream/stream.hpp" #include "blackhole/sink/syslog.hpp" #include "blackhole/utils/underlying.hpp" namespace blackhole { namespace defaults { enum class severity { debug, notice, info, warning, error }; inline void map_severity(aux::attachable_ostringstream& stream, const severity& level) { static const char* describe[] = { "DEBUG", "NOTICE", "INFO", "WARN", "ERROR" }; typedef blackhole::aux::underlying_type<severity>::type level_type; auto value = static_cast<level_type>(level); if(value < static_cast<level_type>(sizeof(describe) / sizeof(describe[0])) && value >= 0) { stream << describe[value]; } else { stream << value; } } } // namespace defaults namespace sink { template<> struct priority_traits<defaults::severity> { static inline priority_t map(defaults::severity lvl) { switch (lvl) { case defaults::severity::debug: return priority_t::debug; case defaults::severity::notice: return priority_t::info; case defaults::severity::info: return priority_t::info; case defaults::severity::warning: return priority_t::warning; case defaults::severity::error: return priority_t::err; } return priority_t::debug; } }; } // namespace sink } // namespace blackhole <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qscopedpointer.h" QT_BEGIN_NAMESPACE /*! \class QScopedPointer \brief The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction. \since 4.6 \reentrant \ingroup misc Managing heap allocated objects manually is hard and error prone, with the common result that code leaks memory and is hard to maintain. QScopedPointer is a small utility class that heavily simplifies this by assigning stack-based memory ownership to heap allocations, more generally called resource acquisition is initialization(RAII). QScopedPointer guarantees that the object pointed to will get deleted when the current scope dissapears. Consider this function which does heap allocations, and have various exit points: \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 0 It's encumbered by the manual delete calls. With QScopedPointer, the code can be simplified to: \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 1 The code the compiler generates for QScopedPointer is the same as when writing it manually. Code that makes use of \a delete are candidates for QScopedPointer usage (and if not, possibly another type of smart pointer such as QSharedPointer). QScopedPointer intentionally has no copy constructor or assignment operator, such that ownership and lifetime is clearly communicated. The const qualification on a regular C++ pointer can also be expressed with a QScopedPointer: \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 2 \section1 Custom cleanup handlers Arrays as well as pointers that have been allocated with \c malloc must not be deleted using \c delete. QScopedPointer's second template parameter can be used for custom cleanup handlers. The following custom cleanup handlers exist: \list \i QScopedPointerDeleter - the default, deletes the pointer using \c delete \i QScopedPointerArrayDeleter - deletes the pointer using \c{delete []}. Use this handler for pointers that were allocated with \c{new []}. \i QScopedPointerPodDeleter - deletes the pointer using \c{free()}. Use this handler for pointers that were allocated with \c{malloc()}. \endlist You can pass your own classes as handlers, provided that they have a public static function \c{void cleanup(T *pointer)}. \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 5 \section1 Forward Declared Pointers Classes that are forward declared can be used within QScopedPointer, as long as the destructor of the forward declared class is available whenever a QScopedPointer needs to clean up. Concretely, this means that all classes containing a QScopedPointer that points to a forward declared class must have non-inline constructors, destructors and assignment operators: \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 4 Otherwise, the compiler output a warning about not being able to destruct \c MyPrivateClass. \sa QSharedPointer */ /*! \typedef QScopedPointer::pointer \internal */ /*! \fn QScopedPointer::QScopedPointer(T *p = 0) Constructs this QScopedPointer instance and sets its pointer to \a p. */ /*! \fn QScopedPointer::~QScopedPointer() Destroys this QScopedPointer object. Delete the object its pointer points to. */ /*! \fn T *QScopedPointer::data() const Returns the value of the pointer referenced by this object. QScopedPointer still owns the object pointed to. */ /*! \fn T &QScopedPointer::operator*() const Provides access to the scoped pointer's object. If the contained pointer is \c null, behavior is undefined. \sa isNull() */ /*! \fn T *QScopedPointer::operator->() const Provides access to the scoped pointer's object. If the contained pointer is \c null, behavior is undefined. \sa isNull() */ /*! \fn QScopedPointer::operator bool() const Returns \c true if this object is not \c null. This function is suitable for use in \tt if-constructs, like: \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 3 \sa isNull() */ /*! \fn bool QScopedPointer::operator==(const QScopedPointer<T, Cleanup> &other) const Equality operator. Returns true if the scoped pointer \a other is pointing to the same object as this pointer, otherwise returns false. */ /*! \fn bool QScopedPointer::operator!=(const QScopedPointer<T, Cleanup> &other) const Inequality operator. Returns true if the scoped pointer \a other is not pointing to the same object as this pointer, otherwise returns false. */ /*! \fn bool QScopedPointer::isNull() const Returns \c true if this object is holding a pointer that is \c null. */ /*! \fn void QScopedPointer::reset(T *other = 0) Deletes the existing object it is pointing to if any, and sets its pointer to \a other. QScopedPointer now owns \a other and will delete it in its destructor. */ /*! \fn T *QScopedPointer::take() Returns the value of the pointer referenced by this object. The pointer of this QScopedPointer object will be reset to \c null. Callers of this function take ownership of the pointer. */ /*! \fn bool QScopedPointer::operator!() const Returns \c true if the pointer referenced by this object is \c null, otherwise returns \c false. \sa isNull() */ /*! \fn void QScopedPointer::swap(QScopedPointer<T, Cleanup> &other) Swap this pointer with \a other. */ QT_END_NAMESPACE <commit_msg>doc: Fixed qdoc according to Bjarne's recommendation.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qscopedpointer.h" QT_BEGIN_NAMESPACE /*! \class QScopedPointer \brief The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction. \since 4.6 \reentrant \ingroup misc Managing heap allocated objects manually is hard and error prone, with the common result that code leaks memory and is hard to maintain. QScopedPointer is a small utility class that heavily simplifies this by assigning stack-based memory ownership to heap allocations, more generally called resource acquisition is initialization(RAII). QScopedPointer guarantees that the object pointed to will get deleted when the current scope dissapears. Consider this function which does heap allocations, and have various exit points: \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 0 It's encumbered by the manual delete calls. With QScopedPointer, the code can be simplified to: \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 1 The code the compiler generates for QScopedPointer is the same as when writing it manually. Code that makes use of \a delete are candidates for QScopedPointer usage (and if not, possibly another type of smart pointer such as QSharedPointer). QScopedPointer intentionally has no copy constructor or assignment operator, such that ownership and lifetime is clearly communicated. The const qualification on a regular C++ pointer can also be expressed with a QScopedPointer: \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 2 \section1 Custom cleanup handlers Arrays as well as pointers that have been allocated with \c malloc must not be deleted using \c delete. QScopedPointer's second template parameter can be used for custom cleanup handlers. The following custom cleanup handlers exist: \list \i QScopedPointerDeleter - the default, deletes the pointer using \c delete \i QScopedPointerArrayDeleter - deletes the pointer using \c{delete []}. Use this handler for pointers that were allocated with \c{new []}. \i QScopedPointerPodDeleter - deletes the pointer using \c{free()}. Use this handler for pointers that were allocated with \c{malloc()}. \endlist You can pass your own classes as handlers, provided that they have a public static function \c{void cleanup(T *pointer)}. \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 5 \section1 Forward Declared Pointers Classes that are forward declared can be used within QScopedPointer, as long as the destructor of the forward declared class is available whenever a QScopedPointer needs to clean up. Concretely, this means that all classes containing a QScopedPointer that points to a forward declared class must have non-inline constructors, destructors and assignment operators: \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 4 Otherwise, the compiler output a warning about not being able to destruct \c MyPrivateClass. \sa QSharedPointer */ /*! \typedef QScopedPointer::pointer \internal */ /*! \fn QScopedPointer::QScopedPointer(T *p = 0) Constructs this QScopedPointer instance and sets its pointer to \a p. */ /*! \fn QScopedPointer::~QScopedPointer() Destroys this QScopedPointer object. Delete the object its pointer points to. */ /*! \fn T *QScopedPointer::data() const Returns the value of the pointer referenced by this object. QScopedPointer still owns the object pointed to. */ /*! \fn T &QScopedPointer::operator*() const Provides access to the scoped pointer's object. If the contained pointer is \c null, behavior is undefined. \sa isNull() */ /*! \fn T *QScopedPointer::operator->() const Provides access to the scoped pointer's object. If the contained pointer is \c null, behavior is undefined. \sa isNull() */ /*! \fn QScopedPointer::operator bool() const Returns \c true if this object is not \c null. This function is suitable for use in \tt if-constructs, like: \snippet doc/src/snippets/code/src_corelib_tools_qscopedpointer.cpp 3 \sa isNull() */ /*! \fn bool operator==(const QScopedPointer<T, Cleanup> &lhs, const QScopedPointer<T, Cleanup> &rhs) Equality operator. Returns true if the scoped pointers \a lhs and \a rhs are pointing to the same object. Otherwise returns false. */ /*! \fn bool operator!=(const QScopedPointer<T, Cleanup> &lhs, const QScopedPointer<T, Cleanup> &rhs) Inequality operator. Returns true if the scoped pointers \a lhs and \a rhs are \e not pointing to the same object. Otherwise returns false. */ /*! \fn bool QScopedPointer::isNull() const Returns \c true if this object is holding a pointer that is \c null. */ /*! \fn void QScopedPointer::reset(T *other = 0) Deletes the existing object it is pointing to if any, and sets its pointer to \a other. QScopedPointer now owns \a other and will delete it in its destructor. */ /*! \fn T *QScopedPointer::take() Returns the value of the pointer referenced by this object. The pointer of this QScopedPointer object will be reset to \c null. Callers of this function take ownership of the pointer. */ /*! \fn bool QScopedPointer::operator!() const Returns \c true if the pointer referenced by this object is \c null, otherwise returns \c false. \sa isNull() */ /*! \fn void QScopedPointer::swap(QScopedPointer<T, Cleanup> &other) Swap this pointer with \a other. */ QT_END_NAMESPACE <|endoftext|>
<commit_before>// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // vector_icons.cc.template is used to generate vector_icons.cc. Edit the former // rather than the latter. #include "chrome/app/vector_icons/vector_icons.h" #include "base/logging.h" #include "ui/gfx/vector_icon_types.h" #define PATH_ELEMENT_TEMPLATE(path_name, ...) \ static constexpr gfx::PathElement path_name[] = {__VA_ARGS__}; #define VECTOR_ICON_TEMPLATE(icon_name, path_name, path_name_1x) \ const gfx::VectorIcon icon_name = { path_name , path_name_1x }; using namespace gfx; VECTOR_ICON_TEMPLATE(kBrowserToolsUpdateIcon, nullptr, nullptr) VECTOR_ICON_TEMPLATE(kUsbSecurityKeyIcon, nullptr, nullptr) <commit_msg>Moved VECTOR_ICON_TEMPLATE definitions<commit_after>// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // vector_icons.cc.template is used to generate vector_icons.cc. Edit the former // rather than the latter. #include "chrome/app/vector_icons/vector_icons.h" #include "ui/gfx/vector_icon_types.h" // Using upstream VECTOR_ICON_TEMPLATE causes compile failure on Windows. #define VECTOR_ICON_TEMPLATE(icon_name) \ const gfx::VectorIcon icon_name; VECTOR_ICON_TEMPLATE(kBrowserToolsUpdateIcon) VECTOR_ICON_TEMPLATE(kUsbSecurityKeyIcon) <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2018 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/webbrowser/properties/propertywidgetcef.h> #include <inviwo/core/properties/property.h> #include <inviwo/core/io/serialization/serialization.h> namespace inviwo { // Checks if widget html id exist in the frame and sets it if it does. // Note: Cannot use CefDOMVisitor since it requires the renderer process. class CefDOMSearchId : public CefStringVisitor { public: CefDOMSearchId(const std::string& htmlId, PropertyWidgetCEF* widget, const CefRefPtr<CefFrame> frame) : CefStringVisitor(), htmlId_(htmlId), widget_(widget), frame_(frame){}; void Visit(const CefString& string) OVERRIDE { std::string domString_ = string; // Remove any occurences of " or ' from the domString_ to remove possible variations on html // id declarations. domString_.erase(std::remove(domString_.begin(), domString_.end(), '"'), domString_.end()); domString_.erase(std::remove(domString_.begin(), domString_.end(), '\''), domString_.end()); std::stringstream ss1; ss1 << "id:" << htmlId_; std::stringstream ss2; ss2 << "id=" << htmlId_; // If the widget's html-id is in the given frame's DOM-document, set it's frame. if (domString_.find(ss1.str()) != std::string::npos || domString_.find(ss2.str()) != std::string::npos) { widget_->frame_ = frame_; widget_->updateFromProperty(); } }; private: std::string htmlId_; PropertyWidgetCEF* widget_; const CefRefPtr<CefFrame> frame_; IMPLEMENT_REFCOUNTING(CefDOMSearchId); }; PropertyWidgetCEF::PropertyWidgetCEF(Property* prop, CefRefPtr<CefFrame> frame, std::string htmlId) : PropertyWidget(prop), htmlId_(htmlId), frame_(frame) { if (prop) { prop->addObserver(this); } } void PropertyWidgetCEF::setFrame(CefRefPtr<CefFrame> frame) { setFrameIfPartOfFrame(frame); // frame_ = frame; // Make sure that we do not block synchronizations from new page. onQueryBlocker_ = 0; } void PropertyWidgetCEF::setFrameIfPartOfFrame(CefRefPtr<CefFrame> frame) { // Create a visitor from this widget and run it on the frame to see if the widget id can be // found in the frame's html code. CefRefPtr<CefDOMSearchId> visitor = new CefDOMSearchId(htmlId_, this, frame); frame->GetSource(visitor); } void PropertyWidgetCEF::deserialize(Deserializer& d) { if (onQueryBlocker_ > 0) { onQueryBlocker_--; return; } property_->setInitiatingWidget(this); d.deserialize("Property", *property_); property_->clearInitiatingWidget(); } void PropertyWidgetCEF::onSetReadOnly(Property* /*property*/, bool readonly) { std::stringstream script; script << "var property = document.getElementById(\"" << htmlId_ << "\");"; script << "if(property!=null){property.readonly=" << (readonly ? "true" : "false") << ";}"; frame_->ExecuteJavaScript(script.str(), frame_->GetURL(), 0); } } // namespace inviwo <commit_msg>WebBrowser: A variable name change and added a loop that removes html comments.<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2018 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/webbrowser/properties/propertywidgetcef.h> #include <inviwo/core/properties/property.h> #include <inviwo/core/io/serialization/serialization.h> namespace inviwo { // Checks if widget html id exist in the frame and sets it if it does. // Note: Cannot use CefDOMVisitor since it requires the renderer process. class CefDOMSearchId : public CefStringVisitor { public: CefDOMSearchId(const std::string& htmlId, PropertyWidgetCEF* widget, const CefRefPtr<CefFrame> frame) : CefStringVisitor(), htmlId_(htmlId), widget_(widget), frame_(frame){}; void Visit(const CefString& string) OVERRIDE { std::string domString = string; // Remove all the html comments to avoid finding element id's in the comments. while (true) { auto start = domString.find("<!--"); auto stop = domString.find("-->"); if (start != std::string::npos) domString = domString.substr(0, start) + domString.substr(stop + 3, domString.length()); else break; } // Remove any occurences of " or ' from the domString_ to remove possible variations on html // id declarations. domString.erase(std::remove(domString.begin(), domString.end(), '"'), domString.end()); domString.erase(std::remove(domString.begin(), domString.end(), '\''), domString.end()); std::stringstream ss1; ss1 << "id:" << htmlId_; std::stringstream ss2; ss2 << "id=" << htmlId_; // If the widget's html-id is in the given frame's DOM-document, set it's frame. if (domString.find(ss1.str()) != std::string::npos || domString.find(ss2.str()) != std::string::npos) { widget_->frame_ = frame_; widget_->updateFromProperty(); } }; private: std::string htmlId_; PropertyWidgetCEF* widget_; const CefRefPtr<CefFrame> frame_; IMPLEMENT_REFCOUNTING(CefDOMSearchId); }; PropertyWidgetCEF::PropertyWidgetCEF(Property* prop, CefRefPtr<CefFrame> frame, std::string htmlId) : PropertyWidget(prop), htmlId_(htmlId), frame_(frame) { if (prop) { prop->addObserver(this); } } void PropertyWidgetCEF::setFrame(CefRefPtr<CefFrame> frame) { setFrameIfPartOfFrame(frame); // frame_ = frame; // Make sure that we do not block synchronizations from new page. onQueryBlocker_ = 0; } void PropertyWidgetCEF::setFrameIfPartOfFrame(CefRefPtr<CefFrame> frame) { // Create a visitor from this widget and run it on the frame to see if the widget id can be // found in the frame's html code. CefRefPtr<CefDOMSearchId> visitor = new CefDOMSearchId(htmlId_, this, frame); frame->GetSource(visitor); } void PropertyWidgetCEF::deserialize(Deserializer& d) { if (onQueryBlocker_ > 0) { onQueryBlocker_--; return; } property_->setInitiatingWidget(this); d.deserialize("Property", *property_); property_->clearInitiatingWidget(); } void PropertyWidgetCEF::onSetReadOnly(Property* /*property*/, bool readonly) { std::stringstream script; script << "var property = document.getElementById(\"" << htmlId_ << "\");"; script << "if(property!=null){property.readonly=" << (readonly ? "true" : "false") << ";}"; frame_->ExecuteJavaScript(script.str(), frame_->GetURL(), 0); } } // namespace inviwo <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/bookmark_data_type_controller.h" #include "base/metrics/histogram.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/history/history_service.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h" #include "chrome/browser/sync/profile_sync_components_factory.h" #include "chrome/browser/sync/profile_sync_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" using content::BrowserThread; namespace browser_sync { BookmarkDataTypeController::BookmarkDataTypeController( ProfileSyncComponentsFactory* profile_sync_factory, Profile* profile, ProfileSyncService* sync_service) : FrontendDataTypeController( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI), base::Bind(&ChromeReportUnrecoverableError), profile_sync_factory, profile, sync_service), bookmark_model_(NULL), installed_bookmark_observer_(false) { } syncer::ModelType BookmarkDataTypeController::type() const { return syncer::BOOKMARKS; } void BookmarkDataTypeController::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_EQ(state_, MODEL_STARTING); DCHECK_EQ(chrome::NOTIFICATION_HISTORY_LOADED, type); if (!DependentsLoaded()) return; bookmark_model_->RemoveObserver(this); installed_bookmark_observer_ = false; registrar_.RemoveAll(); OnModelLoaded(); } BookmarkDataTypeController::~BookmarkDataTypeController() { if (installed_bookmark_observer_ && bookmark_model_) { DCHECK(profile_); bookmark_model_->RemoveObserver(this); } } bool BookmarkDataTypeController::StartModels() { bookmark_model_ = BookmarkModelFactory::GetForProfile(profile_); if (!DependentsLoaded()) { bookmark_model_->AddObserver(this); installed_bookmark_observer_ = true; registrar_.Add(this, chrome::NOTIFICATION_HISTORY_LOADED, content::Source<Profile>(sync_service_->profile())); return false; } return true; } // Cleanup for our extra registrar usage. void BookmarkDataTypeController::CleanUpState() { registrar_.RemoveAll(); } void BookmarkDataTypeController::CreateSyncComponents() { ProfileSyncComponentsFactory::SyncComponents sync_components = profile_sync_factory_->CreateBookmarkSyncComponents(sync_service_, this); set_model_associator(sync_components.model_associator); set_change_processor(sync_components.change_processor); } void BookmarkDataTypeController::BookmarkModelChanged() { } void BookmarkDataTypeController::BookmarkModelLoaded(BookmarkModel* model, bool ids_reassigned) { DCHECK(model->loaded()); model->RemoveObserver(this); installed_bookmark_observer_ = false; if (!DependentsLoaded()) return; registrar_.RemoveAll(); OnModelLoaded(); } void BookmarkDataTypeController::BookmarkModelBeingDeleted( BookmarkModel* model) { installed_bookmark_observer_ = false; } // Check that both the bookmark model and the history service (for favicons) // are loaded. bool BookmarkDataTypeController::DependentsLoaded() { if (!bookmark_model_ || !bookmark_model_->loaded()) return false; HistoryService* history = HistoryServiceFactory::GetForProfile( profile_, Profile::EXPLICIT_ACCESS); if (!history || !history->BackendLoaded()) return false; // All necessary services are loaded. return true; } } // namespace browser_sync <commit_msg>[Sync] Remove bookmark model observer on DTC abort<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/bookmark_data_type_controller.h" #include "base/metrics/histogram.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/history/history_service.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h" #include "chrome/browser/sync/profile_sync_components_factory.h" #include "chrome/browser/sync/profile_sync_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" using content::BrowserThread; namespace browser_sync { BookmarkDataTypeController::BookmarkDataTypeController( ProfileSyncComponentsFactory* profile_sync_factory, Profile* profile, ProfileSyncService* sync_service) : FrontendDataTypeController( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI), base::Bind(&ChromeReportUnrecoverableError), profile_sync_factory, profile, sync_service), bookmark_model_(NULL), installed_bookmark_observer_(false) { } syncer::ModelType BookmarkDataTypeController::type() const { return syncer::BOOKMARKS; } void BookmarkDataTypeController::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_EQ(state_, MODEL_STARTING); DCHECK_EQ(chrome::NOTIFICATION_HISTORY_LOADED, type); if (!DependentsLoaded()) return; bookmark_model_->RemoveObserver(this); installed_bookmark_observer_ = false; registrar_.RemoveAll(); OnModelLoaded(); } BookmarkDataTypeController::~BookmarkDataTypeController() { if (installed_bookmark_observer_ && bookmark_model_) { DCHECK(profile_); bookmark_model_->RemoveObserver(this); } } bool BookmarkDataTypeController::StartModels() { bookmark_model_ = BookmarkModelFactory::GetForProfile(profile_); if (!DependentsLoaded()) { bookmark_model_->AddObserver(this); installed_bookmark_observer_ = true; registrar_.Add(this, chrome::NOTIFICATION_HISTORY_LOADED, content::Source<Profile>(sync_service_->profile())); return false; } return true; } // Cleanup for our extra registrar usage. void BookmarkDataTypeController::CleanUpState() { registrar_.RemoveAll(); if (bookmark_model_ && installed_bookmark_observer_) { bookmark_model_->RemoveObserver(this); installed_bookmark_observer_ = false; } } void BookmarkDataTypeController::CreateSyncComponents() { ProfileSyncComponentsFactory::SyncComponents sync_components = profile_sync_factory_->CreateBookmarkSyncComponents(sync_service_, this); set_model_associator(sync_components.model_associator); set_change_processor(sync_components.change_processor); } void BookmarkDataTypeController::BookmarkModelChanged() { } void BookmarkDataTypeController::BookmarkModelLoaded(BookmarkModel* model, bool ids_reassigned) { DCHECK(model->loaded()); model->RemoveObserver(this); installed_bookmark_observer_ = false; if (!DependentsLoaded()) return; registrar_.RemoveAll(); OnModelLoaded(); } void BookmarkDataTypeController::BookmarkModelBeingDeleted( BookmarkModel* model) { installed_bookmark_observer_ = false; } // Check that both the bookmark model and the history service (for favicons) // are loaded. bool BookmarkDataTypeController::DependentsLoaded() { if (!bookmark_model_ || !bookmark_model_->loaded()) return false; HistoryService* history = HistoryServiceFactory::GetForProfile( profile_, Profile::EXPLICIT_ACCESS); if (!history || !history->BackendLoaded()) return false; // All necessary services are loaded. return true; } } // namespace browser_sync <|endoftext|>
<commit_before>/** * @file multi_wrapper_impls.hpp * * @brief Implementations of methods or functions requiring the definitions of * multiple CUDA entity proxy classes. In some cases these are declared in the * individual proxy class files, with the other classes forward-declared. */ #pragma once #ifndef MULTI_WRAPPER_IMPLS_HPP_ #define MULTI_WRAPPER_IMPLS_HPP_ #include <cuda/api/stream.hpp> #include <cuda/api/device.hpp> #include <cuda/api/event.hpp> #include <cuda/api/pointer.hpp> #include <cuda/api/unique_ptr.hpp> #include <cuda/api/array.hpp> #include <cuda/api/kernel_launch.cuh> #include <type_traits> namespace cuda { namespace array { namespace detail { template<typename T> cudaArray* allocate(device_t& device, array::dimensions_t<3> dimensions) { device::current::detail::scoped_override_t<> set_device_for_this_scope(device.id()); return allocate_on_current_device<T>(dimensions); } template<typename T> cudaArray* allocate(device_t& device, array::dimensions_t<2> dimensions) { device::current::detail::scoped_override_t<> set_device_for_this_scope(device.id()); return allocate_on_current_device<T>(dimensions); } } // namespace detail } // namespace array namespace event { /** * @brief creates a new execution stream on a device. * * @note The CUDA API runtime defaults to creating * which you synchronize on by busy-waiting. This function does * the same for compatibility. * * @param device The device on which to create the new stream * @param uses_blocking_sync When synchronizing on this new evet, * shall a thread busy-wait for it, or * @param records_timing Can this event be used to record time * values (e.g. duration between events) * @param interprocess Can multiple processes work with the constructed * event? * @return The constructed event proxy class */ inline event_t create( device_t& device, bool uses_blocking_sync, bool records_timing, bool interprocess) { auto device_id = device.id(); // Yes, we need the ID explicitly even on the current device, // because event_t's don't have an implicit device ID. return event::detail::create(device_id , uses_blocking_sync, records_timing, interprocess); } namespace ipc { inline handle_t export_(event_t& event) { return detail::export_(event.id()); } inline event_t import(device_t& device, const handle_t& handle) { bool do_not_take_ownership { false }; return event::detail::wrap(device.id(), detail::import(handle), do_not_take_ownership); } } // namespace ipc } // namespace event // device_t methods inline void device_t::synchronize(event_t& event) { scoped_setter_t set_device_for_this_scope(id_); auto status = cudaEventSynchronize(event.id()); throw_if_error(status, "Failed synchronizing the event with id " + detail::ptr_as_hex(event.id()) + " on " + device_id_as_str()); } inline void device_t::synchronize(stream_t& stream) { return synchronize_stream(stream.id()); } inline stream_t device_t::default_stream() const noexcept { // TODO: Perhaps support not-knowing our ID here as well, somehow? return stream_t(id(), stream::default_stream_id); } inline stream_t device_t::create_stream( bool will_synchronize_with_default_stream, stream::priority_t priority) { device::current::detail::scoped_override_t<> set_device_for_this_scope(id_); constexpr const auto take_ownership = true; return stream::detail::wrap(id(), stream::detail::create_on_current_device( will_synchronize_with_default_stream, priority), take_ownership); } namespace device { namespace current { inline scoped_override_t<cuda::detail::do_not_assume_device_is_current>::scoped_override_t(device_t& device) : parent(device.id()) { } inline scoped_override_t<cuda::detail::do_not_assume_device_is_current>::scoped_override_t(device_t&& device) : parent(device.id()) { } } // namespace current } // namespace device namespace detail { } // namespace detail template <typename KernelFunction, typename ... KernelParameters> void device_t::launch( bool thread_block_cooperativity, const KernelFunction& kernel_function, launch_configuration_t launch_configuration, KernelParameters ... parameters) { return default_stream().enqueue.kernel_launch( thread_block_cooperativity, kernel_function, launch_configuration, parameters...); } inline event_t device_t::create_event( bool uses_blocking_sync, bool records_timing, bool interprocess) { // The current implementation of event::create is not super-smart, // but it's probably not worth it trying to improve just this function return event::create(*this, uses_blocking_sync, records_timing, interprocess); } // event_t methods inline device_t event_t::device() const { return cuda::device::get(device_id_); } inline void event_t::record(stream_t& stream) { // Note: // TODO: Perhaps check the device ID here, rather than // have the Runtime API call fail? event::detail::enqueue(stream.id(), id_); } inline void event_t::fire(stream_t& stream) { record(stream); stream.synchronize(); } // stream_t methods inline device_t stream_t::device() const { return cuda::device::get(device_id_); } inline void stream_t::enqueue_t::wait(const event_t& event_) { #ifndef NDEBUG if (event_.device_id() != associated_stream.device_id_) { throw std::invalid_argument("Attempt to have a stream on CUDA device " + std::to_string(associated_stream.device_id_) + " wait for an event on another device (" "device " + std::to_string(event_.device_id()) + ")"); } #endif // Required by the CUDA runtime API; the flags value is // currently unused constexpr const unsigned int flags = 0; auto status = cudaStreamWaitEvent(associated_stream.id_, event_.id(), flags); throw_if_error(status, std::string("Failed scheduling a wait for event ") + cuda::detail::ptr_as_hex(event_.id()) + " on stream " + cuda::detail::ptr_as_hex(associated_stream.id_) + " on CUDA device " + std::to_string(associated_stream.device_id_)); } inline event_t& stream_t::enqueue_t::event(event_t& existing_event) { #ifndef NDEBUG if (existing_event.device_id() != associated_stream.device_id_) { throw std::invalid_argument("Attempt to have a stream on CUDA device " + std::to_string(associated_stream.device_id_) + " wait for an event on another device (" "device " + std::to_string(existing_event.device_id()) + ")"); } #endif auto status = cudaEventRecord(existing_event.id(), associated_stream.id_); throw_if_error(status, "Failed scheduling event " + cuda::detail::ptr_as_hex(existing_event.id()) + " to occur" + " on stream " + cuda::detail::ptr_as_hex(associated_stream.id_) + " on CUDA device " + std::to_string(associated_stream.device_id_)); return existing_event; } inline event_t stream_t::enqueue_t::event( bool uses_blocking_sync, bool records_timing, bool interprocess) { event_t ev { event::detail::create(associated_stream.device_id_, uses_blocking_sync, records_timing, interprocess) }; // Note that, at this point, the event is not associated with this enqueue object's stream. this->event(ev); return ev; } namespace memory { template <typename T> inline device_t pointer_t<T>::device() const { return cuda::device::get(attributes().device); } namespace async { inline void copy(void *destination, const void *source, size_t num_bytes, stream_t& stream) { detail::copy(destination, source, num_bytes, stream.id()); } template <typename T, size_t NumDimensions> inline void copy(array_t<T, NumDimensions>& destination, const void *source, stream_t& stream) { detail::copy(destination, source, stream.id()); } template <typename T, size_t NumDimensions> inline void copy(void* destination, const array_t<T, NumDimensions>& source, stream_t& stream) { detail::copy(destination, source, stream.id()); } template <typename T> inline void copy_single(T& destination, const T& source, stream_t& stream) { detail::copy(&destination, &source, sizeof(T), stream.id()); } } // namespace async namespace device { inline void* allocate(cuda::device_t device, size_t size_in_bytes) { return memory::device::allocate(device, size_in_bytes); } namespace async { inline void set(void* start, int byte_value, size_t num_bytes, stream_t& stream) { detail::set(start, byte_value, num_bytes, stream.id()); } inline void zero(void* start, size_t num_bytes, stream_t& stream) { detail::zero(start, num_bytes, stream.id()); } } // namespace async } // namespace device namespace managed { namespace async { inline void prefetch( const void* managed_ptr, size_t num_bytes, cuda::device_t destination, cuda::stream_t& stream) { detail::prefetch(managed_ptr, num_bytes, destination.id(), stream.id()); } } // namespace async inline void* allocate( cuda::device_t device, size_t num_bytes, initial_visibility_t initial_visibility) { return detail::allocate(device.id(), num_bytes, initial_visibility); } } // namespace managed namespace mapped { inline region_pair allocate( cuda::device_t device, size_t size_in_bytes, region_pair::allocation_options options) { return cuda::memory::mapped::detail::allocate(device.id(), size_in_bytes, options); } } // namespace mapped } // namespace memory /** * @brief Sets a device function's preference of either having more L1 cache or * more shared memory space when executing on some device * * @param device_id the CUDA device for execution on which the preference is set * @param preference value to set for the device function (more cache, more L1 or make the equal) */ inline void device_function_t::cache_preference( device_t device, multiprocessor_cache_preference_t preference) { device::current::detail::scoped_override_t<> set_device_for_this_context(device.id()); cache_preference(preference); } inline void device_function_t::opt_in_to_extra_dynamic_memory( cuda::memory::shared::size_t maximum_shared_memory_required_by_kernel, device_t device) { device::current::detail::scoped_override_t<> set_device_for_this_context(device.id()); opt_in_to_extra_dynamic_memory(maximum_shared_memory_required_by_kernel); } inline void device_function_t::set_shared_mem_to_l1_cache_fraction( unsigned shared_mem_percentage, device_t device) { device::current::detail::scoped_override_t<> set_device_for_this_context(device.id()); set_shared_mem_to_l1_cache_fraction(shared_mem_percentage); } namespace device_function { inline grid::dimension_t maximum_active_blocks_per_multiprocessor( const device_t device, const device_function_t& device_function, grid::block_dimension_t num_threads_per_block, memory::shared::size_t dynamic_shared_memory_per_block, bool disable_caching_override) { device::current::detail::scoped_override_t<> set_device_for_this_context(device.id()); int result; unsigned int flags = disable_caching_override ? cudaOccupancyDisableCachingOverride : cudaOccupancyDefault; auto status = cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( &result, device_function.ptr(), num_threads_per_block, dynamic_shared_memory_per_block, flags); throw_if_error(status, "Failed calculating the maximum occupancy " "of device function blocks per multiprocessor"); return result; } } // namespace device_function namespace stream { inline stream_t create( device_t device, bool synchronizes_with_default_stream, priority_t priority) { return detail::create(device.id(), synchronizes_with_default_stream, priority); } } // namespace stream template<typename KernelFunction, typename... KernelParameters> inline void enqueue_launch( bool thread_block_cooperation, KernelFunction kernel_function, stream_t& stream, launch_configuration_t launch_configuration, KernelParameters&&... parameters) { auto unwrapped_kernel_function = device_function::unwrap< KernelFunction, detail::kernel_parameter_decay_t<KernelParameters>... >(kernel_function); // Note: This helper function is necessary since we may have gotten a // device_function_t as KernelFunction, which is type-erased - in // which case we need both to obtain the raw function pointer, and determine // its type, i.e. un-type-erase it. Luckily, we have the KernelParameters pack // which - if we can trust the user - contains more-or-less the function's // parameter types; and kernels return `void`, which settles the whole signature. // // I say "more or less" because the KernelParameter pack may contain some // references, arrays and so on - which CUDA kernels cannot accept; so // we massage those a bit. detail::enqueue_launch( thread_block_cooperation, unwrapped_kernel_function, stream.id(), launch_configuration, std::forward<KernelParameters>(parameters)...); } template<typename KernelFunction, typename... KernelParameters> inline void launch( KernelFunction kernel_function, launch_configuration_t launch_configuration, KernelParameters&&... parameters) { stream_t stream = device::current::get().default_stream(); enqueue_launch( kernel_function, stream, launch_configuration, std::forward<KernelParameters>(parameters)...); } } // namespace cuda #endif // MULTI_WRAPPER_IMPLS_HPP_ <commit_msg>Added some missing `inline` markers in `multi_wrapper_impls.hpp`.<commit_after>/** * @file multi_wrapper_impls.hpp * * @brief Implementations of methods or functions requiring the definitions of * multiple CUDA entity proxy classes. In some cases these are declared in the * individual proxy class files, with the other classes forward-declared. */ #pragma once #ifndef MULTI_WRAPPER_IMPLS_HPP_ #define MULTI_WRAPPER_IMPLS_HPP_ #include <cuda/api/stream.hpp> #include <cuda/api/device.hpp> #include <cuda/api/event.hpp> #include <cuda/api/pointer.hpp> #include <cuda/api/unique_ptr.hpp> #include <cuda/api/array.hpp> #include <cuda/api/kernel_launch.cuh> #include <type_traits> namespace cuda { namespace array { namespace detail { template<typename T> inline cudaArray* allocate(device_t& device, array::dimensions_t<3> dimensions) { device::current::detail::scoped_override_t<> set_device_for_this_scope(device.id()); return allocate_on_current_device<T>(dimensions); } template<typename T> inline cudaArray* allocate(device_t& device, array::dimensions_t<2> dimensions) { device::current::detail::scoped_override_t<> set_device_for_this_scope(device.id()); return allocate_on_current_device<T>(dimensions); } } // namespace detail } // namespace array namespace event { /** * @brief creates a new execution stream on a device. * * @note The CUDA API runtime defaults to creating * which you synchronize on by busy-waiting. This function does * the same for compatibility. * * @param device The device on which to create the new stream * @param uses_blocking_sync When synchronizing on this new evet, * shall a thread busy-wait for it, or * @param records_timing Can this event be used to record time * values (e.g. duration between events) * @param interprocess Can multiple processes work with the constructed * event? * @return The constructed event proxy class */ inline event_t create( device_t& device, bool uses_blocking_sync, bool records_timing, bool interprocess) { auto device_id = device.id(); // Yes, we need the ID explicitly even on the current device, // because event_t's don't have an implicit device ID. return event::detail::create(device_id , uses_blocking_sync, records_timing, interprocess); } namespace ipc { inline handle_t export_(event_t& event) { return detail::export_(event.id()); } inline event_t import(device_t& device, const handle_t& handle) { bool do_not_take_ownership { false }; return event::detail::wrap(device.id(), detail::import(handle), do_not_take_ownership); } } // namespace ipc } // namespace event // device_t methods inline void device_t::synchronize(event_t& event) { scoped_setter_t set_device_for_this_scope(id_); auto status = cudaEventSynchronize(event.id()); throw_if_error(status, "Failed synchronizing the event with id " + detail::ptr_as_hex(event.id()) + " on " + device_id_as_str()); } inline void device_t::synchronize(stream_t& stream) { return synchronize_stream(stream.id()); } inline stream_t device_t::default_stream() const noexcept { // TODO: Perhaps support not-knowing our ID here as well, somehow? return stream_t(id(), stream::default_stream_id); } inline stream_t device_t::create_stream( bool will_synchronize_with_default_stream, stream::priority_t priority) { device::current::detail::scoped_override_t<> set_device_for_this_scope(id_); constexpr const auto take_ownership = true; return stream::detail::wrap(id(), stream::detail::create_on_current_device( will_synchronize_with_default_stream, priority), take_ownership); } namespace device { namespace current { inline scoped_override_t<cuda::detail::do_not_assume_device_is_current>::scoped_override_t(device_t& device) : parent(device.id()) { } inline scoped_override_t<cuda::detail::do_not_assume_device_is_current>::scoped_override_t(device_t&& device) : parent(device.id()) { } } // namespace current } // namespace device namespace detail { } // namespace detail template <typename KernelFunction, typename ... KernelParameters> void device_t::launch( bool thread_block_cooperativity, const KernelFunction& kernel_function, launch_configuration_t launch_configuration, KernelParameters ... parameters) { return default_stream().enqueue.kernel_launch( thread_block_cooperativity, kernel_function, launch_configuration, parameters...); } inline event_t device_t::create_event( bool uses_blocking_sync, bool records_timing, bool interprocess) { // The current implementation of event::create is not super-smart, // but it's probably not worth it trying to improve just this function return event::create(*this, uses_blocking_sync, records_timing, interprocess); } // event_t methods inline device_t event_t::device() const { return cuda::device::get(device_id_); } inline void event_t::record(stream_t& stream) { // Note: // TODO: Perhaps check the device ID here, rather than // have the Runtime API call fail? event::detail::enqueue(stream.id(), id_); } inline void event_t::fire(stream_t& stream) { record(stream); stream.synchronize(); } // stream_t methods inline device_t stream_t::device() const { return cuda::device::get(device_id_); } inline void stream_t::enqueue_t::wait(const event_t& event_) { #ifndef NDEBUG if (event_.device_id() != associated_stream.device_id_) { throw std::invalid_argument("Attempt to have a stream on CUDA device " + std::to_string(associated_stream.device_id_) + " wait for an event on another device (" "device " + std::to_string(event_.device_id()) + ")"); } #endif // Required by the CUDA runtime API; the flags value is // currently unused constexpr const unsigned int flags = 0; auto status = cudaStreamWaitEvent(associated_stream.id_, event_.id(), flags); throw_if_error(status, std::string("Failed scheduling a wait for event ") + cuda::detail::ptr_as_hex(event_.id()) + " on stream " + cuda::detail::ptr_as_hex(associated_stream.id_) + " on CUDA device " + std::to_string(associated_stream.device_id_)); } inline event_t& stream_t::enqueue_t::event(event_t& existing_event) { #ifndef NDEBUG if (existing_event.device_id() != associated_stream.device_id_) { throw std::invalid_argument("Attempt to have a stream on CUDA device " + std::to_string(associated_stream.device_id_) + " wait for an event on another device (" "device " + std::to_string(existing_event.device_id()) + ")"); } #endif auto status = cudaEventRecord(existing_event.id(), associated_stream.id_); throw_if_error(status, "Failed scheduling event " + cuda::detail::ptr_as_hex(existing_event.id()) + " to occur" + " on stream " + cuda::detail::ptr_as_hex(associated_stream.id_) + " on CUDA device " + std::to_string(associated_stream.device_id_)); return existing_event; } inline event_t stream_t::enqueue_t::event( bool uses_blocking_sync, bool records_timing, bool interprocess) { event_t ev { event::detail::create(associated_stream.device_id_, uses_blocking_sync, records_timing, interprocess) }; // Note that, at this point, the event is not associated with this enqueue object's stream. this->event(ev); return ev; } namespace memory { template <typename T> inline device_t pointer_t<T>::device() const { return cuda::device::get(attributes().device); } namespace async { inline void copy(void *destination, const void *source, size_t num_bytes, stream_t& stream) { detail::copy(destination, source, num_bytes, stream.id()); } template <typename T, size_t NumDimensions> inline void copy(array_t<T, NumDimensions>& destination, const void *source, stream_t& stream) { detail::copy(destination, source, stream.id()); } template <typename T, size_t NumDimensions> inline void copy(void* destination, const array_t<T, NumDimensions>& source, stream_t& stream) { detail::copy(destination, source, stream.id()); } template <typename T> inline void copy_single(T& destination, const T& source, stream_t& stream) { detail::copy(&destination, &source, sizeof(T), stream.id()); } } // namespace async namespace device { inline void* allocate(cuda::device_t device, size_t size_in_bytes) { return memory::device::allocate(device, size_in_bytes); } namespace async { inline void set(void* start, int byte_value, size_t num_bytes, stream_t& stream) { detail::set(start, byte_value, num_bytes, stream.id()); } inline void zero(void* start, size_t num_bytes, stream_t& stream) { detail::zero(start, num_bytes, stream.id()); } } // namespace async } // namespace device namespace managed { namespace async { inline void prefetch( const void* managed_ptr, size_t num_bytes, cuda::device_t destination, cuda::stream_t& stream) { detail::prefetch(managed_ptr, num_bytes, destination.id(), stream.id()); } } // namespace async inline void* allocate( cuda::device_t device, size_t num_bytes, initial_visibility_t initial_visibility) { return detail::allocate(device.id(), num_bytes, initial_visibility); } } // namespace managed namespace mapped { inline region_pair allocate( cuda::device_t device, size_t size_in_bytes, region_pair::allocation_options options) { return cuda::memory::mapped::detail::allocate(device.id(), size_in_bytes, options); } } // namespace mapped } // namespace memory /** * @brief Sets a device function's preference of either having more L1 cache or * more shared memory space when executing on some device * * @param device_id the CUDA device for execution on which the preference is set * @param preference value to set for the device function (more cache, more L1 or make the equal) */ inline void device_function_t::cache_preference( device_t device, multiprocessor_cache_preference_t preference) { device::current::detail::scoped_override_t<> set_device_for_this_context(device.id()); cache_preference(preference); } inline void device_function_t::opt_in_to_extra_dynamic_memory( cuda::memory::shared::size_t maximum_shared_memory_required_by_kernel, device_t device) { device::current::detail::scoped_override_t<> set_device_for_this_context(device.id()); opt_in_to_extra_dynamic_memory(maximum_shared_memory_required_by_kernel); } inline void device_function_t::set_shared_mem_to_l1_cache_fraction( unsigned shared_mem_percentage, device_t device) { device::current::detail::scoped_override_t<> set_device_for_this_context(device.id()); set_shared_mem_to_l1_cache_fraction(shared_mem_percentage); } namespace device_function { inline grid::dimension_t maximum_active_blocks_per_multiprocessor( const device_t device, const device_function_t& device_function, grid::block_dimension_t num_threads_per_block, memory::shared::size_t dynamic_shared_memory_per_block, bool disable_caching_override) { device::current::detail::scoped_override_t<> set_device_for_this_context(device.id()); int result; unsigned int flags = disable_caching_override ? cudaOccupancyDisableCachingOverride : cudaOccupancyDefault; auto status = cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( &result, device_function.ptr(), num_threads_per_block, dynamic_shared_memory_per_block, flags); throw_if_error(status, "Failed calculating the maximum occupancy " "of device function blocks per multiprocessor"); return result; } } // namespace device_function namespace stream { inline stream_t create( device_t device, bool synchronizes_with_default_stream, priority_t priority) { return detail::create(device.id(), synchronizes_with_default_stream, priority); } } // namespace stream template<typename KernelFunction, typename... KernelParameters> inline void enqueue_launch( bool thread_block_cooperation, KernelFunction kernel_function, stream_t& stream, launch_configuration_t launch_configuration, KernelParameters&&... parameters) { auto unwrapped_kernel_function = device_function::unwrap< KernelFunction, detail::kernel_parameter_decay_t<KernelParameters>... >(kernel_function); // Note: This helper function is necessary since we may have gotten a // device_function_t as KernelFunction, which is type-erased - in // which case we need both to obtain the raw function pointer, and determine // its type, i.e. un-type-erase it. Luckily, we have the KernelParameters pack // which - if we can trust the user - contains more-or-less the function's // parameter types; and kernels return `void`, which settles the whole signature. // // I say "more or less" because the KernelParameter pack may contain some // references, arrays and so on - which CUDA kernels cannot accept; so // we massage those a bit. detail::enqueue_launch( thread_block_cooperation, unwrapped_kernel_function, stream.id(), launch_configuration, std::forward<KernelParameters>(parameters)...); } template<typename KernelFunction, typename... KernelParameters> inline void launch( KernelFunction kernel_function, launch_configuration_t launch_configuration, KernelParameters&&... parameters) { stream_t stream = device::current::get().default_stream(); enqueue_launch( kernel_function, stream, launch_configuration, std::forward<KernelParameters>(parameters)...); } } // namespace cuda #endif // MULTI_WRAPPER_IMPLS_HPP_ <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief RX62N, RX621 グループ・SCI I/O 制御 @n Copyright 2013 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "sci_io.hpp" <commit_msg>remove file<commit_after><|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "IECore/TypedPrimitiveOp.h" #include "IECore/Parameter.h" #include "IECore/Object.h" #include "IECore/CompoundObject.h" #include "IECorePython/TypedPrimitiveOpBinding.h" #include "IECorePython/RunTimeTypedBinding.h" #include "IECorePython/Wrapper.h" #include "IECorePython/ScopedGILLock.h" using namespace boost; using namespace boost::python; using namespace IECore; namespace IECorePython { template<typename T> class TypedPrimitiveOpWrap : public TypedPrimitiveOp<T>, public Wrapper<TypedPrimitiveOpWrap<T> > { public : IE_CORE_DECLAREMEMBERPTR( TypedPrimitiveOpWrap<T> ) TypedPrimitiveOpWrap( PyObject *self, const std::string &description ) : TypedPrimitiveOp<T>( description ), Wrapper<TypedPrimitiveOpWrap<T> >( self, this ) { } virtual void modifyTypedPrimitive( T * object, const CompoundObject * operands ) { ScopedGILLock gilLock; this->get_override( "modifyTypedPrimitive" )( ObjectPtr( object ), CompoundObjectPtr( const_cast<CompoundObject *>( operands ) ) ); } }; template<typename T> static void bindTypedPrimitiveOp() { RunTimeTypedClass<TypedPrimitiveOp<T>, TypedPrimitiveOpWrap<T> >() .def( init<const std::string &>() ) ; } void bindTypedPrimitiveOp() { bindTypedPrimitiveOp< MeshPrimitive >(); bindTypedPrimitiveOp< ImagePrimitive >(); bindTypedPrimitiveOp< CurvesPrimitive >(); } } // namespace IECorePython <commit_msg>TypedPrimitiveOp Binding: Use RunTimeTypedClass and RunTimeTypedWrapper<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "IECore/TypedPrimitiveOp.h" #include "IECore/Parameter.h" #include "IECore/Object.h" #include "IECore/CompoundObject.h" #include "IECorePython/TypedPrimitiveOpBinding.h" #include "IECorePython/RunTimeTypedBinding.h" #include "IECorePython/ScopedGILLock.h" using namespace boost; using namespace boost::python; using namespace IECore; namespace IECorePython { template<typename T> class TypedPrimitiveOpWrapper : public RunTimeTypedWrapper<TypedPrimitiveOp<T> > { public : TypedPrimitiveOpWrapper( PyObject *self, const std::string &description ) : RunTimeTypedWrapper<TypedPrimitiveOp<T> >( self, description ) { } virtual void modifyTypedPrimitive( T * object, const CompoundObject * operands ) { ScopedGILLock gilLock; this->methodOverride( "modifyTypedPrimitive" )( ObjectPtr( object ), CompoundObjectPtr( const_cast<CompoundObject *>( operands ) ) ); } }; template<typename T> static void bindTypedPrimitiveOp() { RunTimeTypedClass<TypedPrimitiveOp<T>, TypedPrimitiveOpWrapper<T> >() .def( init<const std::string &>() ) ; } void bindTypedPrimitiveOp() { bindTypedPrimitiveOp< MeshPrimitive >(); bindTypedPrimitiveOp< ImagePrimitive >(); bindTypedPrimitiveOp< CurvesPrimitive >(); } } // namespace IECorePython <|endoftext|>
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/c/task/vision/image_classifier.h" #include <memory> #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "tensorflow_lite_support/c/task/vision/utils/frame_buffer_cpp_c_utils.h" #include "tensorflow_lite_support/cc/task/vision/image_classifier.h" #include "tensorflow_lite_support/cc/task/vision/proto/classifications_proto_inc.h" #include "tensorflow_lite_support/cc/task/vision/proto/image_classifier_options_proto_inc.h" namespace { using ::tflite::support::StatusOr; using ClassificationResultCpp = ::tflite::task::vision::ClassificationResult; using ClassificationsCpp = ::tflite::task::vision::Classifications; using ClassCpp = ::tflite::task::vision::Class; using BoundingBoxCpp = ::tflite::task::vision::BoundingBox; using ImageClassifierCpp = ::tflite::task::vision::ImageClassifier; using ImageClassifierOptionsCpp = ::tflite::task::vision::ImageClassifierOptions; using FrameBufferCpp = ::tflite::task::vision::FrameBuffer; } // namespace #ifdef __cplusplus extern "C" { #endif // __cplusplus struct TfLiteImageClassifier { std::unique_ptr<ImageClassifierCpp> impl; }; std::unique_ptr<ImageClassifierOptionsCpp> CreateImageClassifierCppOptionsFromCOptions( const TfLiteImageClassifierOptions* c_options) { std::unique_ptr<ImageClassifierOptionsCpp> cpp_options( new ImageClassifierOptionsCpp); // More file sources can be added in else ifs if (c_options->base_options.model_file.file_path) cpp_options->mutable_base_options()->mutable_model_file()->set_file_name( c_options->base_options.model_file.file_path); else return nullptr; if (c_options->base_options.compute_settings.tflite_settings.cpu_settings .num_threads > 0) cpp_options->mutable_base_options() ->mutable_compute_settings() ->mutable_tflite_settings() ->mutable_cpu_settings() ->set_num_threads(c_options->base_options.compute_settings .tflite_settings.cpu_settings.num_threads); if (c_options->classification_options.class_name_blacklist.length > 0 && c_options->classification_options.class_name_whitelist.length > 0) return nullptr; if (c_options->classification_options.class_name_blacklist.length > 0) { for (int i = 0; i < c_options->classification_options.class_name_blacklist.length; i++) cpp_options->add_class_name_blacklist( c_options->classification_options.class_name_blacklist.list[i]); } else if (c_options->classification_options.class_name_whitelist.length > 0) { for (int i = 0; i < c_options->classification_options.class_name_whitelist.length; i++) cpp_options->add_class_name_whitelist( c_options->classification_options.class_name_whitelist.list[i]); } if (c_options->classification_options.display_names_local) { cpp_options->set_display_names_locale( c_options->classification_options.display_names_local); } if (c_options->classification_options.max_results > 0) { cpp_options->set_max_results(c_options->classification_options.max_results); } if (c_options->classification_options.score_threshold >= 0) { cpp_options->set_score_threshold( c_options->classification_options.score_threshold); } return cpp_options; } TfLiteImageClassifier* TfLiteImageClassifierFromOptions( const TfLiteImageClassifierOptions* options) { std::unique_ptr<ImageClassifierOptionsCpp> cpp_options = CreateImageClassifierCppOptionsFromCOptions(options); if (cpp_options == nullptr) { return nullptr; } auto classifier_status = ImageClassifierCpp::CreateFromOptions(*cpp_options); if (classifier_status.ok()) { return new TfLiteImageClassifier{.impl = std::move(classifier_status.value())}; } else { return nullptr; } } TfLiteClassificationResult* GetClassificationResultCStruct( const ClassificationResultCpp& classification_result_cpp) { TfLiteClassifications* c_classifications = new TfLiteClassifications[classification_result_cpp .classifications_size()]; for (int head = 0; head < classification_result_cpp.classifications_size(); ++head) { const ClassificationsCpp& classifications = classification_result_cpp.classifications(head); c_classifications[head].head_index = head; TfLiteCategory* c_categories = new TfLiteCategory[classifications.classes_size()]; c_classifications->size = classifications.classes_size(); for (int rank = 0; rank < classifications.classes_size(); ++rank) { const ClassCpp& classification = classifications.classes(rank); c_categories[rank].index = classification.index(); c_categories[rank].score = classification.score(); if (classification.has_class_name()) c_categories[rank].label = strdup(classification.class_name().c_str()); else c_categories[rank].label = nullptr; if (classification.has_display_name()) c_categories[rank].display_name = strdup(classification.display_name().c_str()); else c_categories[rank].display_name = nullptr; } c_classifications[head].categories = c_categories; } TfLiteClassificationResult* c_classification_result = new TfLiteClassificationResult; c_classification_result->classifications = c_classifications; c_classification_result->size = classification_result_cpp.classifications_size(); return c_classification_result; } TfLiteClassificationResult* TfLiteImageClassifierClassifyWithRoi( const TfLiteImageClassifier* classifier, const TfLiteFrameBuffer* frame_buffer, const TfLiteBoundingBox* roi) { if (classifier == nullptr || frame_buffer == nullptr) { return nullptr; } BoundingBoxCpp cc_roi; if (roi == nullptr) { cc_roi.set_width(frame_buffer->dimension.width); cc_roi.set_height(frame_buffer->dimension.height); } else { cc_roi.set_origin_x(roi->origin_x); cc_roi.set_origin_y(roi->origin_y); cc_roi.set_width(roi->width); cc_roi.set_height(roi->height); } StatusOr<std::unique_ptr<FrameBufferCpp>> cpp_frame_buffer_status = ::tflite::task::vision::CreateCppFrameBuffer(*frame_buffer); if (!cpp_frame_buffer_status.ok()) return nullptr; // fnc_sample(cpp_frame_buffer_status); StatusOr<ClassificationResultCpp> classification_result_cpp = classifier->impl->Classify(*std::move(cpp_frame_buffer_status.value()), cc_roi); if (!classification_result_cpp.ok()) return nullptr; return GetClassificationResultCStruct(classification_result_cpp.value()); } TfLiteClassificationResult* TfLiteImageClassifierClassify( const TfLiteImageClassifier* classifier, const TfLiteFrameBuffer* frame_buffer) { return TfLiteImageClassifierClassifyWithRoi(classifier, frame_buffer, nullptr); } void TfLiteImageClassifierDelete(TfLiteImageClassifier* classifier) { delete classifier; } #ifdef __cplusplus } // extern "C" #endif // __cplusplus <commit_msg>Check if class name black list and white list are mutually exclusive<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/c/task/vision/image_classifier.h" #include <memory> #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "tensorflow_lite_support/c/task/vision/utils/frame_buffer_cpp_c_utils.h" #include "tensorflow_lite_support/cc/task/vision/image_classifier.h" #include "tensorflow_lite_support/cc/task/vision/proto/classifications_proto_inc.h" #include "tensorflow_lite_support/cc/task/vision/proto/image_classifier_options_proto_inc.h" namespace { using ::tflite::support::StatusOr; using ClassificationResultCpp = ::tflite::task::vision::ClassificationResult; using ClassificationsCpp = ::tflite::task::vision::Classifications; using ClassCpp = ::tflite::task::vision::Class; using BoundingBoxCpp = ::tflite::task::vision::BoundingBox; using ImageClassifierCpp = ::tflite::task::vision::ImageClassifier; using ImageClassifierOptionsCpp = ::tflite::task::vision::ImageClassifierOptions; using FrameBufferCpp = ::tflite::task::vision::FrameBuffer; } // namespace #ifdef __cplusplus extern "C" { #endif // __cplusplus struct TfLiteImageClassifier { std::unique_ptr<ImageClassifierCpp> impl; }; std::unique_ptr<ImageClassifierOptionsCpp> CreateImageClassifierCppOptionsFromCOptions( const TfLiteImageClassifierOptions* c_options) { std::unique_ptr<ImageClassifierOptionsCpp> cpp_options( new ImageClassifierOptionsCpp); // More file sources can be added in else ifs if (c_options->base_options.model_file.file_path) cpp_options->mutable_base_options()->mutable_model_file()->set_file_name( c_options->base_options.model_file.file_path); else return nullptr; int num_threads = c_options->base_options.compute_settings.tflite_settings.cpu_settings .num_threads if (c_options->base_options.compute_settings .tflite_settings.cpu_settings.num_threads > 0) cpp_options->mutable_base_options() ->mutable_compute_settings() ->mutable_tflite_settings() ->mutable_cpu_settings() ->set_num_threads(c_options->base_options.compute_settings .tflite_settings.cpu_settings.num_threads); else { cpp_options->mutable_base_options() ->mutable_compute_settings() ->mutable_tflite_settings() ->mutable_cpu_settings() ->set_num_threads(-1); } if (c_options->classification_options.class_name_blacklist.length > 0 && c_options->classification_options.class_name_whitelist.length > 0) return nullptr; if (c_options->classification_options.class_name_blacklist.length > 0 && c_options->classification_options.class_name_whitelist.length) return nullptr; if (c_options->classification_options.class_name_blacklist.length > 0) { for (int i = 0; i < c_options->classification_options.class_name_blacklist.length; i++) cpp_options->add_class_name_blacklist( c_options->classification_options.class_name_blacklist.list[i]); } else if (c_options->classification_options.class_name_whitelist.length > 0) { for (int i = 0; i < c_options->classification_options.class_name_whitelist.length; i++) cpp_options->add_class_name_whitelist( c_options->classification_options.class_name_whitelist.list[i]); } if (c_options->classification_options.display_names_local) { cpp_options->set_display_names_locale( c_options->classification_options.display_names_local); } if (c_options->classification_options.max_results > 0) { cpp_options->set_max_results(c_options->classification_options.max_results); } if (c_options->classification_options.score_threshold >= 0) { cpp_options->set_score_threshold( c_options->classification_options.score_threshold); } return cpp_options; } TfLiteImageClassifier* TfLiteImageClassifierFromOptions( const TfLiteImageClassifierOptions* options) { std::unique_ptr<ImageClassifierOptionsCpp> cpp_options = CreateImageClassifierCppOptionsFromCOptions(options); if (cpp_options == nullptr) { return nullptr; } auto classifier_status = ImageClassifierCpp::CreateFromOptions(*cpp_options); if (classifier_status.ok()) { return new TfLiteImageClassifier{.impl = std::move(classifier_status.value())}; } else { return nullptr; } } TfLiteClassificationResult* GetClassificationResultCStruct( const ClassificationResultCpp& classification_result_cpp) { TfLiteClassifications* c_classifications = new TfLiteClassifications[classification_result_cpp .classifications_size()]; for (int head = 0; head < classification_result_cpp.classifications_size(); ++head) { const ClassificationsCpp& classifications = classification_result_cpp.classifications(head); c_classifications[head].head_index = head; TfLiteCategory* c_categories = new TfLiteCategory[classifications.classes_size()]; c_classifications->size = classifications.classes_size(); for (int rank = 0; rank < classifications.classes_size(); ++rank) { const ClassCpp& classification = classifications.classes(rank); c_categories[rank].index = classification.index(); c_categories[rank].score = classification.score(); if (classification.has_class_name()) c_categories[rank].label = strdup(classification.class_name().c_str()); else c_categories[rank].label = nullptr; if (classification.has_display_name()) c_categories[rank].display_name = strdup(classification.display_name().c_str()); else c_categories[rank].display_name = nullptr; } c_classifications[head].categories = c_categories; } TfLiteClassificationResult* c_classification_result = new TfLiteClassificationResult; c_classification_result->classifications = c_classifications; c_classification_result->size = classification_result_cpp.classifications_size(); return c_classification_result; } TfLiteClassificationResult* TfLiteImageClassifierClassifyWithRoi( const TfLiteImageClassifier* classifier, const TfLiteFrameBuffer* frame_buffer, const TfLiteBoundingBox* roi) { if (classifier == nullptr || frame_buffer == nullptr) { return nullptr; } BoundingBoxCpp cc_roi; if (roi == nullptr) { cc_roi.set_width(frame_buffer->dimension.width); cc_roi.set_height(frame_buffer->dimension.height); } else { cc_roi.set_origin_x(roi->origin_x); cc_roi.set_origin_y(roi->origin_y); cc_roi.set_width(roi->width); cc_roi.set_height(roi->height); } StatusOr<std::unique_ptr<FrameBufferCpp>> cpp_frame_buffer_status = ::tflite::task::vision::CreateCppFrameBuffer(*frame_buffer); if (!cpp_frame_buffer_status.ok()) return nullptr; // fnc_sample(cpp_frame_buffer_status); StatusOr<ClassificationResultCpp> classification_result_cpp = classifier->impl->Classify(*std::move(cpp_frame_buffer_status.value()), cc_roi); if (!classification_result_cpp.ok()) return nullptr; return GetClassificationResultCStruct(classification_result_cpp.value()); } TfLiteClassificationResult* TfLiteImageClassifierClassify( const TfLiteImageClassifier* classifier, const TfLiteFrameBuffer* frame_buffer) { return TfLiteImageClassifierClassifyWithRoi(classifier, frame_buffer, nullptr); } void TfLiteImageClassifierDelete(TfLiteImageClassifier* classifier) { delete classifier; } #ifdef __cplusplus } // extern "C" #endif // __cplusplus <|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "amr_utils.H" #include "forestclaw2d.h" #include "amr_forestclaw.H" #include "clawpack_fort.H" /* Difference in nan values : The first one is not trapped; the second one is. (gdb) print qnan $13 = nan(0x8000000000000) (gdb) print snan $14 = nan(0x000000001) */ static void set_qnan(double& f) { /* The quiet nan from math.h */ f = NAN; } static void set_snan(double& f) { /* From : "NaNs, Uninitialized Variables, and C++" http://codingcastles.blogspot.fr/2008/12/nans-in-c.html */ *((long long*)&f) = 0x7ff0000000000001LL; } FArrayBox::FArrayBox() { m_data = NULL; m_box = Box(); m_fields = 0; m_size = 0; } FArrayBox::~FArrayBox() { if (m_data != NULL) { delete [] m_data; m_data = NULL; } } FArrayBox::FArrayBox(const FArrayBox& A) { m_box = A.m_box; m_size = A.m_size; m_fields = A.m_fields; /* A re-allocation, but should hopefully, memory management should be okay */ set_dataPtr(A.m_size); } void FArrayBox::set_dataPtr(int a_size) { if (a_size < 0) { printf("FArrayBox::set_dataPtr() : size < 0\n"); exit(1); } else if (a_size == 0) { if (m_data != NULL) { delete [] m_data; } m_data = NULL; } else { if (m_size != a_size) { delete [] m_data; m_data = new double[a_size]; } else { // Don't do anything; m_data is already the right size } double qnan, snan; set_qnan(qnan); set_snan(snan); for(int i = 0; i < a_size; i++) { m_data[i] = snan; } } } void FArrayBox::define(const Box& a_box, int a_fields) { int box_size = (a_box.bigEnd(0) - a_box.smallEnd(0) + 1)* (a_box.bigEnd(1) - a_box.smallEnd(1) + 1); if (box_size < 0) { printf("FArrayBox::define(a_box,a_fields) : size < 0\n"); printf("Box::ll = (%d %d)\n",a_box.smallEnd(0), a_box.smallEnd(1)); printf("Box::ur = (%d %d)\n",a_box.bigEnd(0), a_box.bigEnd(1)); exit(1); } set_dataPtr(box_size*a_fields); m_size = box_size*a_fields; m_fields = a_fields; m_box = a_box; } void FArrayBox::copyToMemory(double *data) { for(int i = 0; i < m_size; i++) { data[i] = m_data[i]; } } void FArrayBox::copyFromMemory(double *data) { for(int i = 0; i < m_size; i++) { m_data[i] = data[i]; } } // copy constructor void FArrayBox::operator=(const FArrayBox& fbox) { // reset pointer, if necessary set_dataPtr(fbox.m_size); m_box = fbox.m_box; m_size = fbox.m_size; m_fields = fbox.m_fields; // copy data to this pointer. for (int i = 0; i < fbox.m_size; i++) { m_data[i] = fbox.m_data[i]; } } double* FArrayBox::dataPtr() { return m_data; } Box FArrayBox::box() { return m_box; } int FArrayBox::size() { return m_size; } int FArrayBox::fields() { return m_fields; } // Rename to "IndexBox" Box::Box() { for (int idir = 0; idir < SpaceDim; idir++) { m_ll[idir] = 0; m_ur[idir] = 0; } } Box::Box(const Box& a_box) { for(int idir = 0; idir < SpaceDim; idir++) { m_ll[idir] = a_box.m_ll[idir]; m_ur[idir] = a_box.m_ur[idir]; } } Box::Box(const int ll[], const int ur[]) { for(int idir = 0; idir < 2; idir++) { m_ll[idir] = ll[idir]; m_ur[idir] = ur[idir]; } } int Box::smallEnd(int idir) const { return m_ll[idir]; } int Box::bigEnd(int idir) const { return m_ur[idir]; } <commit_msg>Added comments on quiet vs. signaling nans<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "amr_utils.H" #include "forestclaw2d.h" #include "amr_forestclaw.H" #include "clawpack_fort.H" /* Difference in nan values : The first one is not trapped; the second one is. (gdb) print qnan $13 = nan(0x8000000000000) (gdb) print snan $14 = nan(0x000000001) */ static void set_qnan(double& f) { /* The quiet nan from math.h */ f = NAN; } static void set_snan(double& f) { /* From : "NaNs, Uninitialized Variables, and C++" http://codingcastles.blogspot.fr/2008/12/nans-in-c.html */ *((long long*)&f) = 0x7ff0000000000001LL; } FArrayBox::FArrayBox() { m_data = NULL; m_box = Box(); m_fields = 0; m_size = 0; } FArrayBox::~FArrayBox() { if (m_data != NULL) { delete [] m_data; m_data = NULL; } } FArrayBox::FArrayBox(const FArrayBox& A) { m_box = A.m_box; m_size = A.m_size; m_fields = A.m_fields; /* A re-allocation, but should hopefully, memory management should be okay */ set_dataPtr(A.m_size); } void FArrayBox::set_dataPtr(int a_size) { if (a_size < 0) { printf("FArrayBox::set_dataPtr() : size < 0\n"); exit(1); } else if (a_size == 0) { if (m_data != NULL) { delete [] m_data; } m_data = NULL; } else { if (m_size != a_size) { delete [] m_data; m_data = new double[a_size]; } else { // Don't do anything; m_data is already the right size } double qnan, snan; // qnan = quiet nan // snan = signaling nan set_qnan(qnan); set_snan(snan); for(int i = 0; i < a_size; i++) { m_data[i] = snan; } } } void FArrayBox::define(const Box& a_box, int a_fields) { int box_size = (a_box.bigEnd(0) - a_box.smallEnd(0) + 1)* (a_box.bigEnd(1) - a_box.smallEnd(1) + 1); if (box_size < 0) { printf("FArrayBox::define(a_box,a_fields) : size < 0\n"); printf("Box::ll = (%d %d)\n",a_box.smallEnd(0), a_box.smallEnd(1)); printf("Box::ur = (%d %d)\n",a_box.bigEnd(0), a_box.bigEnd(1)); exit(1); } set_dataPtr(box_size*a_fields); m_size = box_size*a_fields; m_fields = a_fields; m_box = a_box; } void FArrayBox::copyToMemory(double *data) { for(int i = 0; i < m_size; i++) { data[i] = m_data[i]; } } void FArrayBox::copyFromMemory(double *data) { for(int i = 0; i < m_size; i++) { m_data[i] = data[i]; } } // copy constructor void FArrayBox::operator=(const FArrayBox& fbox) { // reset pointer, if necessary set_dataPtr(fbox.m_size); m_box = fbox.m_box; m_size = fbox.m_size; m_fields = fbox.m_fields; // copy data to this pointer. for (int i = 0; i < fbox.m_size; i++) { m_data[i] = fbox.m_data[i]; } } double* FArrayBox::dataPtr() { return m_data; } Box FArrayBox::box() { return m_box; } int FArrayBox::size() { return m_size; } int FArrayBox::fields() { return m_fields; } // Rename to "IndexBox" Box::Box() { for (int idir = 0; idir < SpaceDim; idir++) { m_ll[idir] = 0; m_ur[idir] = 0; } } Box::Box(const Box& a_box) { for(int idir = 0; idir < SpaceDim; idir++) { m_ll[idir] = a_box.m_ll[idir]; m_ur[idir] = a_box.m_ur[idir]; } } Box::Box(const int ll[], const int ur[]) { for(int idir = 0; idir < 2; idir++) { m_ll[idir] = ll[idir]; m_ur[idir] = ur[idir]; } } int Box::smallEnd(int idir) const { return m_ll[idir]; } int Box::bigEnd(int idir) const { return m_ur[idir]; } <|endoftext|>
<commit_before>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2010 Alessandro Tasora // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // /////////////////////////////////////////////////// // // Demo on low-level functionality for time // integration of differential equations. // /////////////////////////////////////////////////// #include <math.h> #include "core/ChLog.h" #include "timestepper/ChTimestepper.h" using namespace chrono; int main(int argc, char* argv[]) { GetLog() << "CHRONO demo about low-level time integration of differential equations: \n\n"; if (true) { // // EXAMPLE 1: // GetLog() << " Example 1: integrate dx/dt=e^t \n"; // Define a class inherited from ChIntegrable, // it will represent the differential equations // by implementing the StateSolve() function, and few other interfaces: class MyIntegrable : public ChIntegrable { private: public: MyIntegrable() {} /// the number of coordinates in the state: virtual int GetNcoords_y() {return 1;} /// compute dy/dt=f(y,t) virtual void StateSolve(ChStateDelta& Dy, ///< result: computed Dy ChVectorDynamic<>& L, ///< result: computed lagrangian multipliers, if any const ChState& y, ///< current state y const double T, ///< current time T const double dt, ///< timestep (if needed) bool force_state_scatter = true ///< if false, y and T are not scattered to the system, assuming that someone has done StateScatter just before ) { if(force_state_scatter) StateScatter(y,T); // state -> system (not needed here, btw.) Dy(0) = exp(T)*dt; // dx/dt=e^t then: dx=e^t * dt } }; // File to dump results ChStreamOutAsciiFile log_file1("log_timestepper_1.dat"); // Create and object from your custom integrable class: MyIntegrable mintegrable; // Create a time-integrator, class: Eulero explicit ChTimestepperEuleroExpl mystepper(mintegrable); // Execute the time integration while (mystepper.GetTime() <4) { mystepper.Advance(0.1); double exact_solution = exp(mystepper.GetTime())-1; GetLog() << " T = " << mystepper.GetTime() << " x=" << mystepper.Y()(0) << " x_exact="<< exact_solution << "\n"; log_file1 << mystepper.GetTime() << ", " << mystepper.Y()(0) << ", " << exact_solution << "\n"; } } if (true) { // // EXAMPLE 2: // GetLog() << "\n\n Example 2: integrate 2nd order oscillator: M*ddx/dtdt + R*dx/dt + K*w = F(t) with a 1st order integrator. \n"; // Define a class inherited from ChIntegrable, // it will represent the differential equations // by implementing the StateSolve() function, and few other interfaces: class MyIntegrable : public ChIntegrable { private: double M; double K; double R; double T; double x; double v; public: MyIntegrable() { T = 0; M = 10; K = 30; R = 1; x = 0; v = 0; } /// the number of coordinates in the state: virtual int GetNcoords_y() {return 2;} /// system -> state virtual void StateGather(ChState& y, double& mT) { y(0)=x; y(1)=v; mT = T; }; /// state -> system virtual void StateScatter(const ChState& y, const double mT) { x=y(0); v=y(1); T=mT; }; /// compute dy/dt=f(y,t) virtual void StateSolve(ChStateDelta& Dy, ///< result: computed Dy ChVectorDynamic<>& L, ///< result: computed lagrangian multipliers, if any const ChState& y, ///< current state y const double T, ///< current time T const double dt, ///< timestep (if needed) bool force_state_scatter = true ///< if false, y and T are not scattered to the system, assuming that someone has done StateScatter just before ) { if(force_state_scatter) StateScatter(y,T); double F = sin(T*4)*2; Dy(0) = dt*v; Dy(1) = dt*(1./M) * (F - K*x - R*v); } }; // File to dump results ChStreamOutAsciiFile log_file2("log_timestepper_2.dat"); // Try integrator Eulero explicit // Create and object from your custom integrable class: MyIntegrable mintegrable; // Create a time-integrator: ChTimestepperEuleroExpl mystepper(mintegrable); // Try integrator Runge Kutta 4st explicit // Create and object from your custom integrable class: MyIntegrable mintegrable_rk; // Create a time-integrator, class: Runge Kutta 4 explicit ChTimestepperRungeKuttaExpl mystepper_rk(mintegrable_rk); // Execute the time integration while (mystepper.GetTime() <1) { mystepper.Advance(0.01); mystepper_rk.Advance(0.01); GetLog() << " T = " << mystepper.GetTime() << " x=" << mystepper.Y()(0) << " v=" << mystepper.Y()(1) << "\n"; log_file2 << mystepper.GetTime() << ", " << mystepper.Y()(0) << ", " << mystepper.Y()(1) << ", " << mystepper_rk.Y()(0) << ", " << mystepper_rk.Y()(1) << "\n"; } } if (true) { // // EXAMPLE 3: // GetLog() << "\n\n Example 3: integrate 2nd order oscillator: M*ddx/dtdt + R*dx/dt + K*w = F(t) with a 2nd order integrator. \n"; // Define a class inherited from ChIntegrableIIorder, // it will represent the differential equations // by implementing the StateSolveA() function, and few other interfaces. // Compared to previous example 2, this is inherited from ChIntegrableIIorder, // so one can use more advanced integrators such as ChTimestepperEuleroSemiImplicit, // that can exploit the II order nature of the problem. Anyway, also all I order // integrators can still be used. class MyIntegrable : public ChIntegrableIIorder { private: double M; double K; double R; double T; double mx; double mv; public: MyIntegrable() { T = 0; M = 10; K = 30; R = 1; mx = 0; mv = 0; } /// the number of coordinates in the state, x position part: virtual int GetNcoords_x() { return 1; } /// system -> state virtual void StateGather(ChState& x, ChStateDelta& v, double& mT) { x(0) = mx; v(0) = mv; mT = T; }; /// state -> system virtual void StateScatter(const ChState& x, const ChStateDelta& v, const double mT) { mx = x(0); mv = v(0); T = mT; }; /// compute dy/dt=f(y,t) virtual void StateSolveA(ChStateDelta& Dv, ///< result: computed Dv ChVectorDynamic<>& L, ///< result: computed lagrangian multipliers, if any const ChState& x, ///< current state, x const ChStateDelta& v, ///< current state, v const double T, ///< current time T const double dt, ///< timestep (if needed) bool force_state_scatter = true ///< if false, y and T are not scattered to the system, assuming that someone has done StateScatter just before ) { if (force_state_scatter) StateScatter(x, v, T); double F = sin(T * 4) * 2; Dv(0) = dt*(1. / M) * (F - K*mx - R*mv); } }; // Create a file to dump results ChStreamOutAsciiFile log_file3("log_timestepper_3.dat"); // Create and object from your custom integrable class: MyIntegrable mintegrable1; MyIntegrable mintegrable2; MyIntegrable mintegrable3; // Create few time-integrators to be compared: ChTimestepperEuleroExpl mystepper1(mintegrable1); ChTimestepperEuleroExplIIorder mystepper2(mintegrable2); ChTimestepperEuleroSemiImplicit mystepper3(mintegrable3); // Execute the time integration while (mystepper1.GetTime() <1) { mystepper1.Advance(0.01); mystepper2.Advance(0.01); mystepper3.Advance(0.01); GetLog() << "T = " << mystepper1.GetTime() << " x=" << mystepper1.Y()(0) << " v=" << mystepper1.Y()(1) << "\n"; log_file3 << mystepper1.GetTime() << ", " << mystepper1.Y()(0) << ", " << mystepper1.Y()(1) << ", " << mystepper2.X()(0) << ", " << mystepper2.V()(0) << ", " << mystepper3.X()(0) << ", " << mystepper3.V()(0) << "\n"; } } GetLog() << "\n CHRONO execution terminated."; system("pause"); return 0; } <commit_msg>Updated tests about the ChTimestepper stuff<commit_after>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2010 Alessandro Tasora // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // /////////////////////////////////////////////////// // // Demo on low-level functionality for time // integration of differential equations. // /////////////////////////////////////////////////// #include <math.h> #include "core/ChLog.h" #include "timestepper/ChTimestepper.h" using namespace chrono; int main(int argc, char* argv[]) { GetLog() << "CHRONO demo about low-level time integration of differential equations: \n\n"; if (true) { // // EXAMPLE 1: // GetLog() << " Example 1: integrate dx/dt=e^t \n"; // Define a class inherited from ChIntegrable, // it will represent the differential equations // by implementing the StateSolve() function, and few other interfaces: class MyIntegrable : public ChIntegrable { private: public: MyIntegrable() {} /// the number of coordinates in the state: virtual int GetNcoords_y() {return 1;} /// compute dy/dt=f(y,t) virtual void StateSolve(ChStateDelta& Dy, ///< result: computed Dy ChVectorDynamic<>& L, ///< result: computed lagrangian multipliers, if any const ChState& y, ///< current state y const double T, ///< current time T const double dt, ///< timestep (if needed) bool force_state_scatter = true ///< if false, y and T are not scattered to the system, assuming that someone has done StateScatter just before ) { if(force_state_scatter) StateScatter(y,T); // state -> system (not needed here, btw.) Dy(0) = exp(T)*dt; // dx/dt=e^t then: dx=e^t * dt } }; // File to dump results ChStreamOutAsciiFile log_file1("log_timestepper_1.dat"); // Create and object from your custom integrable class: MyIntegrable mintegrable; // Create a time-integrator, class: Eulero explicit ChTimestepperEuleroExpl mystepper(mintegrable); // Execute the time integration while (mystepper.GetTime() <4) { mystepper.Advance(0.1); double exact_solution = exp(mystepper.GetTime())-1; GetLog() << " T = " << mystepper.GetTime() << " x=" << mystepper.Y()(0) << " x_exact="<< exact_solution << "\n"; log_file1 << mystepper.GetTime() << ", " << mystepper.Y()(0) << ", " << exact_solution << "\n"; } } if (true) { // // EXAMPLE 2: // GetLog() << "\n\n Example 2: integrate 2nd order oscillator: M*ddx/dtdt + R*dx/dt + K*w = F(t) with a 1st order integrator. \n"; // Define a class inherited from ChIntegrable, // it will represent the differential equations // by implementing the StateSolve() function, and few other interfaces: class MyIntegrable : public ChIntegrable { private: double M; double K; double R; double T; double x; double v; public: MyIntegrable() { T = 0; M = 10; K = 30; R = 1; x = 0; v = 0; } /// the number of coordinates in the state: virtual int GetNcoords_y() {return 2;} /// system -> state virtual void StateGather(ChState& y, double& mT) { y(0)=x; y(1)=v; mT = T; }; /// state -> system virtual void StateScatter(const ChState& y, const double mT) { x=y(0); v=y(1); T=mT; }; /// compute dy/dt=f(y,t) virtual void StateSolve(ChStateDelta& Dy, ///< result: computed Dy ChVectorDynamic<>& L, ///< result: computed lagrangian multipliers, if any const ChState& y, ///< current state y const double T, ///< current time T const double dt, ///< timestep (if needed) bool force_state_scatter = true ///< if false, y and T are not scattered to the system, assuming that someone has done StateScatter just before ) { if(force_state_scatter) StateScatter(y,T); double F = cos(T*20)*2; Dy(0) = dt*v; Dy(1) = dt*(1./M) * (F - K*x - R*v); } }; // File to dump results ChStreamOutAsciiFile log_file2("log_timestepper_2.dat"); // Try integrator Eulero explicit // Create and object from your custom integrable class: MyIntegrable mintegrable; // Create a time-integrator: ChTimestepperEuleroExpl mystepper(mintegrable); // Try integrator Runge Kutta 4st explicit // Create and object from your custom integrable class: MyIntegrable mintegrable_rk; // Create a time-integrator, class: Runge Kutta 4 explicit ChTimestepperRungeKuttaExpl mystepper_rk(mintegrable_rk); // Execute the time integration while (mystepper.GetTime() <1) { mystepper.Advance(0.01); mystepper_rk.Advance(0.01); GetLog() << " T = " << mystepper.GetTime() << " x=" << mystepper.Y()(0) << " v=" << mystepper.Y()(1) << "\n"; log_file2 << mystepper.GetTime() << ", " << mystepper.Y()(0) << ", " << mystepper.Y()(1) << ", " << mystepper_rk.Y()(0) << ", " << mystepper_rk.Y()(1) << "\n"; } } if (true) { // // EXAMPLE 3: // GetLog() << "\n\n Example 3: integrate 2nd order oscillator: M*ddx/dtdt + R*dx/dt + K*w = F(t) with a 2nd order integrator. \n"; // Define a class inherited from ChIntegrableIIorder, // it will represent the differential equations // by implementing the StateSolveA() function, and few other interfaces. // Compared to previous example 2, this is inherited from ChIntegrableIIorder, // so one can use more advanced integrators such as ChTimestepperEuleroSemiImplicit, // that can exploit the II order nature of the problem. Anyway, also all I order // integrators can still be used. class MyIntegrable : public ChIntegrableIIorder { private: double M; double K; double R; double T; double mx; double mv; public: MyIntegrable() { T = 0; M = 10; K = 30; R = 1; mx = 0; mv = 0; } /// the number of coordinates in the state, x position part: virtual int GetNcoords_x() { return 1; } /// system -> state virtual void StateGather(ChState& x, ChStateDelta& v, double& mT) { x(0) = mx; v(0) = mv; mT = T; }; /// state -> system virtual void StateScatter(const ChState& x, const ChStateDelta& v, const double mT) { mx = x(0); mv = v(0); T = mT; }; /// compute dy/dt=f(y,t) virtual void StateSolveA(ChStateDelta& Dv, ///< result: computed Dv ChVectorDynamic<>& L, ///< result: computed lagrangian multipliers, if any const ChState& x, ///< current state, x const ChStateDelta& v, ///< current state, v const double T, ///< current time T const double dt, ///< timestep (if needed) bool force_state_scatter = true ///< if false, y and T are not scattered to the system, assuming that someone has done StateScatter just before ) { if (force_state_scatter) StateScatter(x, v, T); double F = cos(T * 20) * 2; Dv(0) = dt*(1. / M) * (F - K*mx - R*mv); } }; // Create a file to dump results ChStreamOutAsciiFile log_file3("log_timestepper_3.dat"); // Create and object from your custom integrable class: MyIntegrable mintegrable1; MyIntegrable mintegrable2; MyIntegrable mintegrable3; // Create few time-integrators to be compared: ChTimestepperRungeKuttaExpl mystepper1(mintegrable1); ChTimestepperEuleroExplIIorder mystepper2(mintegrable2); ChTimestepperEuleroSemiImplicit mystepper3(mintegrable3); // Execute the time integration while (mystepper1.GetTime() <4) { mystepper1.Advance(0.01); mystepper2.Advance(0.01); mystepper3.Advance(0.01); GetLog() << "T = " << mystepper1.GetTime() << " x=" << mystepper1.Y()(0) << " v=" << mystepper1.Y()(1) << "\n"; log_file3 << mystepper1.GetTime() << ", " << mystepper1.Y()(0) << ", " << mystepper1.Y()(1) << ", " << mystepper2.X()(0) << ", " << mystepper2.V()(0) << ", " << mystepper3.X()(0) << ", " << mystepper3.V()(0) << "\n"; } } if (true) { // // EXAMPLE 4: // GetLog() << "\n\n Example 4: integrate 2nd order oscillator: M*ddx/dtdt + R*dx/dt + K*w = F(t) with an implicit integrator \n"; // Define a class inherited from ChIntegrableIIorder, // it will represent the differential equations // by implementing the interfaces to implicit solvers. // We assume M*a = F(x,v,t) class MyIntegrable : public ChIntegrableIIorder { private: double M; double K; double R; double T; double mx; double mv; public: MyIntegrable() { T = 0; M = 1; K = 30; R = 0; mx = 0; mv = 0; } /// the number of coordinates in the state, x position part: virtual int GetNcoords_x() { return 1; } /// system -> state virtual void StateGather(ChState& x, ChStateDelta& v, double& mT) { x(0) = mx; v(0) = mv; mT = T; }; /// state -> system virtual void StateScatter(const ChState& x, const ChStateDelta& v, const double mT) { mx = x(0); mv = v(0); T = mT; }; /// compute dy/dt=f(y,t) virtual void StateSolveA(ChStateDelta& Dv, ///< result: computed Dv ChVectorDynamic<>& L, ///< result: computed lagrangian multipliers, if any const ChState& x, ///< current state, x const ChStateDelta& v, ///< current state, v const double T, ///< current time T const double dt, ///< timestep (if needed) bool force_state_scatter = true ///< if false, y and T are not scattered to the system, assuming that someone has done StateScatter just before ) { if (force_state_scatter) StateScatter(x, v, T); double F = sin(T * 20) * 2; Dv(0) = dt*(1. / M) * (F - K*mx - R*mv); } /// Compute the correction with linear system /// Dv = [ c_a*M + c_v*dF/dv + c_x*dF/dx ]^-1 * R virtual void StateSolveCorrection( ChStateDelta& Dv, ///< result: computed Dv ChVectorDynamic<>& L, ///< result: computed lagrangian multipliers, if any const ChVectorDynamic<>& R, ///< the R residual const double c_a, ///< the factor in c_a*M const double c_v, ///< the factor in c_v*dF/dv const double c_x, ///< the factor in c_x*dF/dv const ChState& x, ///< current state, x part const ChStateDelta& v,///< current state, v part const double T, ///< current time T bool force_state_scatter = true ///< if false, x,v and T are not scattered to the system, assuming that someone has done StateScatter just before ) { if (force_state_scatter) this->StateScatter(x, v, T); Dv(0) = R(0) * 1.0 / (c_a*this->M + c_v *(-this->R) + c_x * (-this->K)); } /// R += c*F void LoadResidual_F( ChVectorDynamic<>& R, ///< result: the R residual, R += c*F const double c ///< a scaling factor ) { R(0) += c * (sin(T * 20) * 2 - this->K*mx - this->R*mv); }; /// R += c*M*w void LoadResidual_Mv( ChVectorDynamic<>& R, ///< result: the R residual, R += c*M*v const ChVectorDynamic<>& w, ///< the w vector const double c ///< a scaling factor ) { R(0) += c * this->M * w(0); }; /// nothing to do here- no constraints virtual void LoadResidual_CqL( ChVectorDynamic<>& R, ///< result: the R residual, R += c*Cq'*L const ChVectorDynamic<>& L, ///< the L vector const double c ///< a scaling factor ) {}; /// nothing to do here- no constraints virtual void LoadConstraint_C( ChVectorDynamic<>& Qc, ///< result: the Qc residual, Qc += c*C const double c ///< a scaling factor ) {}; /// nothing to do here- no constraints virtual void LoadConstraint_Ct( ChVectorDynamic<>& Qc, ///< result: the Qc residual, Qc += c*Ct const double c ///< a scaling factor ) {}; }; // Create a file to dump results ChStreamOutAsciiFile log_file4("log_timestepper_4.dat"); // Create and object from your custom integrable class: MyIntegrable mintegrable1; MyIntegrable mintegrable2; MyIntegrable mintegrable3; MyIntegrable mintegrable4; // Create few time-integrators to be compared: ChTimestepperEulerImplicit mystepper1(mintegrable1); ChTimestepperTrapezoidal mystepper2(mintegrable2); ChTimestepperEuleroExplIIorder mystepper3(mintegrable3); ChTimestepperEuleroSemiImplicit mystepper4(mintegrable4); // Execute the time integration while (mystepper1.GetTime() <4) { mystepper1.Advance(0.01); mystepper2.Advance(0.01); mystepper3.Advance(0.01); mystepper4.Advance(0.01); GetLog() << "T = " << mystepper1.GetTime() << " x=" << mystepper1.X()(0) << " v=" << mystepper1.V()(0) << "\n"; log_file4 << mystepper1.GetTime() << ", " << mystepper1.X()(0) << ", " << mystepper1.V()(0) << ", " << mystepper2.X()(0) << ", " << mystepper2.V()(0) << ", " << mystepper3.X()(0) << ", " << mystepper3.V()(0) << ", " << mystepper4.X()(0) << ", " << mystepper4.V()(0) << "\n"; } } GetLog() << "\n CHRONO execution terminated."; //system("pause"); return 0; } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX600 グループ・TPU I/O 制御 @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" #include "common/intr_utils.hpp" #include "common/vect.h" /// F_PCLKB は周期パラメーター計算で必要で、設定が無いとエラーにします。 #ifndef F_PCLKB # error "tpu_io.hpp requires F_PCLKB to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief TPU I/O クラス @param[in] TPU チャネルクラス @param[in] TASK タイマー動作ファンクタ・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class TPU, class TASK = utils::null_task> class tpu_io { public: //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイプ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class TYPE : uint8_t { MATCH, ///< コンペアー・マッチ }; private: uint8_t level_; ICU::VECTOR intr_vec_; static volatile uint32_t counter_; static TASK task_; static INTERRUPT_FUNC void tpu_task_() noexcept { /// if(TPU::TSR.TGFA()) TPU::TSR.TGFA = 0; ++counter_; task_(); } void sleep_() const noexcept { asm("nop"); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// tpu_io() noexcept : level_(0), intr_vec_(ICU::VECTOR::VEC0) { } //-----------------------------------------------------------------// /*! @brief タイマー動作開始 @param[in] freq タイマー周波数 @param[in] level 割り込みレベル(0ならポーリング) @return レンジオーバーなら「false」を返す */ //-----------------------------------------------------------------// bool start(uint32_t freq, uint8_t level = 0) noexcept { if(freq == 0) return false; level_ = level; uint32_t cmt = F_PCLKB / freq; uint8_t shift = 0; while(cmt > 65536) { cmt >>= 2; ++shift; } if(cmt == 0) return false; auto per = TPU::get_peripheral(); // プリスケーラーの算出と指定 (shift) // 1: 1/2, 2: 1/4, 3: 1/8, ... // TPU0: 1/1(0), 1/4(1), 1/16(2), 1/64(3) // TPU1: 1/1(0), 1/4(1), 1/16(2), 1/64(3), 1/256(4) // TPU2: 1/1(0), 1/4(1), 1/16(2), 1/64(3), 1/1024(5) // TPU3: 1/1(0), 1/4(1), 1/16(2), 1/64(3), 1/256(4), 1/1024(5), 1/4096(6) // TPU4: 1/1(0), 1/4(1), 1/16(2), 1/64(3), 1/1024(5) // TPU5: 1/1(0), 1/4(1), 1/16(2), 1/64(3), 1/256(4) uint8_t tpsc = 0; if(shift == 0) { } else if(shift == 1) { tpsc = 0b001; } else if(shift == 2) { tpsc = 0b010; } else if(shift == 3) { tpsc = 0b011; } else if(shift == 6) { if(per == peripheral::TPU3) { // 1/4096 tpsc = 0b111; } else { return false; } } else if(shift == 5) { if(per == peripheral::TPU2) { tpsc = 0b111; } else if(per == peripheral::TPU3) { tpsc = 0b101; } else if(per == peripheral::TPU4) { tpsc = 0b110; } else { return false; } } else if(shift == 4) { if(per == peripheral::TPU1 || per == peripheral::TPU3 || per == peripheral::TPU5) { tpsc = 0b110; } else { return false; } } else { return false; } power_cfg::turn(per); TPU::TCR = TPU::TCR.CCLR.b(1) | TPU::TCR.TPSC.b(tpsc); // TGRA のコンペアマッチ TPU::TGRA = cmt - 1; TPU::TCNT = 0x0000; if(level_ > 0) { // 割り込み設定 #if (defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)) intr_vec_ = ICU::VECTOR::INTB128; set_interrupt_task(tpu_task_, static_cast<uint32_t>(intr_vec_)); ICU::SLIBXR128 = TPU::get_TGIA(); ICU::IPR.INTB128 = level_; ICU::IER.INTB128 = true; #endif TPU::TIER.TGIEA = 1; // TGRA interrupt } else { TPU::TIER.TGIEA = 0; } TPU::enable(); return true; } //-----------------------------------------------------------------// /*! @brief 廃棄 */ //-----------------------------------------------------------------// void destroy() noexcept { TPU::TIER = 0; TPU::enable(false); power_cfg::turn(TPU::get_peripheral(), false); } //-----------------------------------------------------------------// /*! @brief タイマー同期 */ //-----------------------------------------------------------------// void sync() const noexcept { if(level_ > 0) { volatile uint32_t cnt = counter_; while(cnt == counter_) sleep_(); } else { while(TPU::TSR.TGFA() == 0) sleep_(); TPU::TSR.TGFA = 0; task_(); ++counter_; } } //-----------------------------------------------------------------// /*! @brief 割り込みカウンターの値を取得 @return 割り込みカウンターの値 */ //-----------------------------------------------------------------// uint32_t get_counter() const noexcept { return counter_; } //-----------------------------------------------------------------// /*! @brief TCNT レジスターの値を取得 @return TCNT レジスター */ //-----------------------------------------------------------------// uint16_t get_tcnt_count() const noexcept { return TPU::TCNT(); } //-----------------------------------------------------------------// /*! @brief 割り込みベクターの取得 @return 割り込みベクター */ //-----------------------------------------------------------------// ICU::VECTOR get_intr_vec() const noexcept { return intr_vec_; } //-----------------------------------------------------------------// /*! @brief TASK クラスの参照 @return TASK クラス */ //-----------------------------------------------------------------// static TASK& at_task() noexcept { return task_; } }; template <class TPU, class TASK> volatile uint32_t tpu_io<TPU, TASK>::counter_ = 0; template <class TPU, class TASK> TASK tpu_io<TPU, TASK>::task_; } <commit_msg>update: cleanup<commit_after>#pragma once //=====================================================================// /*! @file @brief RX600 グループ・TPU I/O 制御 @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" #include "common/intr_utils.hpp" #include "common/vect.h" /// F_PCLKB は周期パラメーター計算で必要で、設定が無いとエラーにします。 #ifndef F_PCLKB # error "tpu_io.hpp requires F_PCLKB to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief TPU I/O クラス @param[in] TPU チャネルクラス @param[in] TASK タイマー動作ファンクタ・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class TPU, class TASK = utils::null_task> class tpu_io { public: //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイプ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class TYPE : uint8_t { MATCH, ///< コンペアー・マッチ }; private: uint8_t level_; ICU::VECTOR intr_vec_; static volatile uint32_t counter_; static TASK task_; static INTERRUPT_FUNC void tpu_task_() noexcept { /// if(TPU::TSR.TGFA()) TPU::TSR.TGFA = 0; ++counter_; task_(); } void sleep_() const noexcept { asm("nop"); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// tpu_io() noexcept : level_(0), intr_vec_(ICU::VECTOR::NONE) { } //-----------------------------------------------------------------// /*! @brief タイマー動作開始 @param[in] freq タイマー周波数 @param[in] level 割り込みレベル(0ならポーリング) @return レンジオーバーなら「false」を返す */ //-----------------------------------------------------------------// bool start(uint32_t freq, uint8_t level = 0) noexcept { if(freq == 0) return false; level_ = level; uint32_t cmt = F_PCLKB / freq; uint8_t shift = 0; while(cmt > 65536) { cmt >>= 2; ++shift; } if(cmt == 0) return false; auto per = TPU::get_peripheral(); // プリスケーラーの算出と指定 (shift) // 1: 1/2, 2: 1/4, 3: 1/8, ... // TPU0: 1/1(0), 1/4(1), 1/16(2), 1/64(3) // TPU1: 1/1(0), 1/4(1), 1/16(2), 1/64(3), 1/256(4) // TPU2: 1/1(0), 1/4(1), 1/16(2), 1/64(3), 1/1024(5) // TPU3: 1/1(0), 1/4(1), 1/16(2), 1/64(3), 1/256(4), 1/1024(5), 1/4096(6) // TPU4: 1/1(0), 1/4(1), 1/16(2), 1/64(3), 1/1024(5) // TPU5: 1/1(0), 1/4(1), 1/16(2), 1/64(3), 1/256(4) uint8_t tpsc = 0; if(shift == 0) { } else if(shift == 1) { tpsc = 0b001; } else if(shift == 2) { tpsc = 0b010; } else if(shift == 3) { tpsc = 0b011; } else if(shift == 6) { if(per == peripheral::TPU3) { // 1/4096 tpsc = 0b111; } else { return false; } } else if(shift == 5) { if(per == peripheral::TPU2) { tpsc = 0b111; } else if(per == peripheral::TPU3) { tpsc = 0b101; } else if(per == peripheral::TPU4) { tpsc = 0b110; } else { return false; } } else if(shift == 4) { if(per == peripheral::TPU1 || per == peripheral::TPU3 || per == peripheral::TPU5) { tpsc = 0b110; } else { return false; } } else { return false; } power_cfg::turn(per); TPU::TCR = TPU::TCR.CCLR.b(1) | TPU::TCR.TPSC.b(tpsc); // TGRA のコンペアマッチ TPU::TGRA = cmt - 1; TPU::TCNT = 0x0000; if(level_ > 0) { // 割り込み設定 #if (defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)) intr_vec_ = ICU::VECTOR::INTB128; set_interrupt_task(tpu_task_, static_cast<uint32_t>(intr_vec_)); ICU::SLIBXR128 = TPU::get_TGIA(); ICU::IPR.INTB128 = level_; ICU::IER.INTB128 = true; #endif TPU::TIER.TGIEA = 1; // TGRA interrupt } else { TPU::TIER.TGIEA = 0; } TPU::enable(); return true; } //-----------------------------------------------------------------// /*! @brief 廃棄 */ //-----------------------------------------------------------------// void destroy() noexcept { TPU::TIER = 0; TPU::enable(false); power_cfg::turn(TPU::get_peripheral(), false); } //-----------------------------------------------------------------// /*! @brief タイマー同期 */ //-----------------------------------------------------------------// void sync() const noexcept { if(level_ > 0) { volatile uint32_t cnt = counter_; while(cnt == counter_) sleep_(); } else { while(TPU::TSR.TGFA() == 0) sleep_(); TPU::TSR.TGFA = 0; task_(); ++counter_; } } //-----------------------------------------------------------------// /*! @brief 割り込みカウンターの値を取得 @return 割り込みカウンターの値 */ //-----------------------------------------------------------------// uint32_t get_counter() const noexcept { return counter_; } //-----------------------------------------------------------------// /*! @brief TCNT レジスターの値を取得 @return TCNT レジスター */ //-----------------------------------------------------------------// uint16_t get_tcnt_count() const noexcept { return TPU::TCNT(); } //-----------------------------------------------------------------// /*! @brief 割り込みベクターの取得 @return 割り込みベクター */ //-----------------------------------------------------------------// ICU::VECTOR get_intr_vec() const noexcept { return intr_vec_; } //-----------------------------------------------------------------// /*! @brief TASK クラスの参照 @return TASK クラス */ //-----------------------------------------------------------------// static TASK& at_task() noexcept { return task_; } }; template <class TPU, class TASK> volatile uint32_t tpu_io<TPU, TASK>::counter_ = 0; template <class TPU, class TASK> TASK tpu_io<TPU, TASK>::task_; } <|endoftext|>
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2016/08/09 // // Author: Mike Ovsiannikov // // Copyright 2009 Quantcast Corp. // // This file is part of Kosmos File System (KFS). // // Licensed under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // // List files with object store blocks missing. // //---------------------------------------------------------------------------- #include "kfstree.h" #include "Checkpoint.h" #include "Restorer.h" #include "Replay.h" #include "util.h" #include "common/MdStream.h" #include "common/MsgLogger.h" #include "common/RequestParser.h" #include "kfsio/blockname.h" #include "libclient/KfsClient.h" #include <iostream> #include <string> #include <vector> #include <boost/static_assert.hpp> #include <boost/dynamic_bitset.hpp> namespace KFS { using std::cout; using std::cin; using std::cerr; using std::string; using boost::dynamic_bitset; typedef dynamic_bitset<> BlocksBitmap; inline static int RestoreCheckpoint( const string& inLockFileName) { if (! inLockFileName.empty()) { acquire_lockfile(inLockFileName, 10); } Restorer theRestorer; return (theRestorer.rebuild(LASTCP) ? 0 : -EIO); } inline static bool HasBitmapSet( const MetaFattr& theFattr) { const size_t kBits = 8 * sizeof(theFattr.subcount1); return (kBits * CHUNKSIZE <= theFattr.nextChunkOffset()); } inline static int GetFileName( const MetaFattr& inFattr, string& outFileName) { outFileName = metatree.getPathname(&inFattr); return 0; } inline static BlocksBitmap* GetBitmapPtr( const MetaFattr& inFattr) { BOOST_STATIC_ASSERT(sizeof(BlocksBitmap*) <= sizeof(inFattr.subcount1)); char* const kNullPtr = 0; return reinterpret_cast<BlocksBitmap*>(kNullPtr + inFattr.chunkcount()); } inline static void SetBitmapPtr( MetaFattr& inFattr, BlocksBitmap* inPtr) { const char* const kNullPtr = 0; inFattr.chunkcount() = reinterpret_cast<const char*>(inPtr) - kNullPtr; } static int ObjectStoreFsck( int inArgCnt, char** inArgaPtr) { int theOpt; string theCpDir; string theLockFile; ServerLocation theMetaServer; const char* theLogDirPtr = 0; const char* theConfigFileNamePtr = 0; MsgLogger::LogLevel theLogLevel = MsgLogger::kLogLevelINFO; int theStatus = 0; bool theHelpFlag = false; bool theReplayLastLogFlag = false; const char* thePtr; while ((theOpt = getopt(inArgCnt, inArgaPtr, "vhal:c:L:s:p:f:")) != -1) { switch (theOpt) { case 'a': theReplayLastLogFlag = true; break; case 'L': theLockFile = optarg; break; case 'l': theLogDirPtr = optarg; break; case 'c': theCpDir = optarg; break; case 's': theMetaServer.hostname = optarg; break; case 'p': thePtr = optarg; if (! DecIntParser::Parse( thePtr, strlen(thePtr), theMetaServer.port)) { theMetaServer.port = -1; } break; case 'v': theLogLevel = MsgLogger::kLogLevelDEBUG; break; case 'h': theHelpFlag = true; break; case 'f': theConfigFileNamePtr = optarg; break; default: theStatus = -EINVAL; break; } } if (theHelpFlag || 0 != theStatus || (! theMetaServer.hostname.empty() && ! theMetaServer.IsValid())) { cerr << "Usage: " << inArgaPtr[0] << "\n" "[-h <help>]\n" "[-v verbose]\n" "[-L <lock file>] default: no lock file\n" "[-l <transaction log directory>] default: kfslog\n" "[-c <checkpoint directory>] default: kfscp\n" "[-f <client configuration file>] default: none\n" "[-a replay last log segment] default: don't replay last segment\n" "[-s <meta server host>]\n" "[-p <meta server port>]\n" "\n" "Loads checkpoint, replays transaction logs, then" " reads object store block keys from standard in, one key per line," " and outputs \"lost\" file names on standard out (files with keys" " that were not present in standard in), if any." "\n\n" "Note that the list of object store block keys must be" " more recent than checkpoint, and transaction logs, and valid" " meta server host and port must be specified in order for" " this work correctly (no false positives) if the file system is" " \"live\" / being modified." "\n\n" "In other words, the correct procedure to check \"live\" file system" " is to copy / save checkpoint, and transaction logs, then create" " list of object store blocks, then run this tool." "\n" ; return 1; } MdStream::Init(); MsgLogger::Init(0, theLogLevel); if (! theCpDir.empty()) { checkpointer_setup_paths(theCpDir); } if (theLogDirPtr && theLogDirPtr[0]) { replayer.setLogDir(theLogDirPtr); } int64_t theLostCount = 0; KfsClient* const theClientPtr = theMetaServer.IsValid() ? KfsClient::Connect( theMetaServer.hostname, theMetaServer.port, theConfigFileNamePtr) : 0; if (theClientPtr) { // Make sure that the client is configured correctly prior to checkpoint // load and replay, by retrieving root node info. const kfsChunkId_t kChunkId = -1; chunkOff_t theOffset = -1; int64_t theVersion = 0; KfsFileAttr theCliAttr; vector<ServerLocation> theServers; theStatus = theClientPtr->GetFileOrChunkInfo( ROOTFID, kChunkId, theCliAttr, theOffset, theVersion, theServers ); } else if (theMetaServer.IsValid()) { theStatus = -ENOTCONN; } if (0 == theStatus && (theStatus = RestoreCheckpoint(theLockFile)) == 0 && (theStatus = replayer.playLogs(theReplayLastLogFlag)) == 0) { if (! theClientPtr) { // Setup back pointers, to get file names retrival working. metatree.setUpdatePathSpaceUsage(true); metatree.enableFidToPathname(); } const int64_t theFileSystemId = metatree.GetFsId(); string theExpectedKey; string theBlockKey; string theFsIdSuffix; theExpectedKey.reserve(256); theBlockKey.reserve(256); while (getline(cin, theBlockKey)) { KFS_LOG_STREAM_DEBUG << "key: " << theBlockKey << KFS_LOG_EOM; const char* thePtr = theBlockKey.data(); const char* const theEndPtr = thePtr + theBlockKey.size(); if (theEndPtr <= thePtr) { continue; } const int kSeparator = '.'; thePtr = reinterpret_cast<const char*>( memchr(thePtr, kSeparator, theEndPtr - thePtr)); fid_t theFid = -1; seq_t theVersion = 0; if (! thePtr || theEndPtr <= ++thePtr || ! DecIntParser::Parse(thePtr, theEndPtr - thePtr, theFid) || theFid < 0 || theEndPtr <= thePtr || kSeparator != (0xFF & *thePtr) || theEndPtr <= ++thePtr || ! DecIntParser::Parse( thePtr, theEndPtr - thePtr, theVersion) || 0 <= theVersion || theEndPtr <= thePtr || kSeparator != (0xFF & *thePtr)) { KFS_LOG_STREAM_ERROR << theBlockKey << ": malformed object store block key" << KFS_LOG_EOM; continue; } theExpectedKey.clear(); if (! AppendChunkFileNameOrObjectStoreBlockKey( theExpectedKey, theFileSystemId, theFid, theFid, theVersion, theFsIdSuffix)) { panic("block name generation failure"); continue; } if (theExpectedKey != theBlockKey) { KFS_LOG_STREAM_ERROR << theBlockKey << ": invalid object store block key" " expected: " << theExpectedKey << KFS_LOG_EOM; continue; } MetaFattr* const theFattrPtr = metatree.getFattr(theFid); if (! theFattrPtr) { KFS_LOG_STREAM_DEBUG << theBlockKey << ": invalid key: no such file" << KFS_LOG_EOM; continue; } if (KFS_FILE != theFattrPtr->type) { KFS_LOG_STREAM_ERROR << theBlockKey << ": invalid key:" " attribute type: " << theFattrPtr->type << KFS_LOG_EOM; continue; } if (0 != theFattrPtr->numReplicas) { KFS_LOG_STREAM_ERROR << theBlockKey << ": invalid key:" " replication: " << theFattrPtr->numReplicas << KFS_LOG_EOM; continue; } if (theFattrPtr->filesize <= 0) { KFS_LOG_STREAM_DEBUG << theBlockKey << ": skipping 0 size file" << KFS_LOG_EOM; continue; } const chunkOff_t thePos = -theVersion - 1 - theFattrPtr->minSTier; if (thePos < 0 || 0 != (thePos % (chunkOff_t)CHUNKSIZE)) { KFS_LOG_STREAM_ERROR << theBlockKey << ": invalid key:" " position: " << thePos << " tier: " << theFattrPtr->minSTier << " / " << theFattrPtr->maxSTier << KFS_LOG_EOM; continue; } if (theFattrPtr->nextChunkOffset() < thePos) { KFS_LOG_STREAM( theFattrPtr->nextChunkOffset() + (chunkOff_t)CHUNKSIZE < thePos ? MsgLogger::kLogLevelERROR : MsgLogger::kLogLevelDEBUG) << theBlockKey << ": block past last file block" " position: " << thePos << " last block: " << theFattrPtr->nextChunkOffset() << KFS_LOG_EOM; continue; } // Chunk count must be 0 for object store files. Use this field to // store bitmap of the blocks that are present in the input. If the // file has more blocks that fits into the chunk count field, then // allocate bit vector and store pointer to it. const size_t theIdx = thePos / CHUNKSIZE; if (HasBitmapSet(*theFattrPtr)) { BlocksBitmap* thePtr = GetBitmapPtr(*theFattrPtr); if (! thePtr) { thePtr = new BlocksBitmap( 1 + theFattrPtr->nextChunkOffset() / CHUNKSIZE); SetBitmapPtr(*theFattrPtr, thePtr); } else if ((*thePtr)[theIdx]) { KFS_LOG_STREAM_DEBUG << theBlockKey << ": duplicate input key" << KFS_LOG_EOM; continue; } (*thePtr)[theIdx] = true; } else { const int64_t theBit = int64_t(1) << theIdx; if (0 != (theFattrPtr->chunkcount() & theBit)) { KFS_LOG_STREAM_DEBUG << theBlockKey << ": duplicate input key" << KFS_LOG_EOM; continue; } theFattrPtr->chunkcount() |= theBit; } } // Traverse leaf nodes and query the the status for files with missing // blocks. KfsFileAttr theCliAttr; vector<ServerLocation> theServers; LeafIter theIt(metatree.firstLeaf(), 0); for (const Meta* theNPtr = 0; theIt.parent() && (theNPtr = theIt.current()); theIt.next()) { if (KFS_FATTR != theNPtr->metaType()) { continue; } const MetaFattr& theFattr = *static_cast<const MetaFattr*>(theNPtr); if (KFS_FILE != theFattr.type || 0 != theFattr.numReplicas || theFattr.filesize <= 0) { continue; } chunkOff_t theMissingIdx = 0; if (HasBitmapSet(theFattr)) { const BlocksBitmap* const thePtr = GetBitmapPtr(theFattr); if (thePtr) { for (theMissingIdx = 0; theMissingIdx < (chunkOff_t)thePtr->size() && (*thePtr)[theMissingIdx]; ++theMissingIdx) {} } } else { const int64_t theBits = theFattr.chunkcount(); const int64_t theEnd = theFattr.nextChunkOffset() / CHUNKSIZE; int64_t theBit = 1; for (theMissingIdx = 0; theMissingIdx <= theEnd && 0 != (theBits & theBit); theMissingIdx++, theBit <<= 1) {} } if (theMissingIdx * CHUNKSIZE < theFattr.filesize) { const kfsChunkId_t kChunkId = -1; chunkOff_t theOffset = -1; int64_t theVersion = 0; const int theRet = theClientPtr ? theClientPtr->GetFileOrChunkInfo( theFattr.id(), kChunkId, theCliAttr, theOffset, theVersion, theServers ) : GetFileName(theFattr, theCliAttr.filename); if (0 == theRet) { cout << theCliAttr.filename << "\n"; theLostCount++; } else if (-ENOENT != theRet) { KFS_LOG_STREAM_ERROR << "failed to get file info:" " fid: " << theFattr.id() << " " << ErrorCodeToStr(theRet) << KFS_LOG_EOM; if (0 == theStatus) { theStatus = theRet; } } } } } if (0 != theStatus) { KFS_LOG_STREAM_ERROR << ErrorCodeToStr(theStatus) << KFS_LOG_EOM; } else { KFS_LOG_STREAM_INFO << "lost files: " << theLostCount << KFS_LOG_EOM; } delete theClientPtr; MsgLogger::Stop(); MdStream::Cleanup(); return ((0 == theStatus && 0 == theLostCount) ? 0 : 1); } } // namespace KFS int main(int argc, char **argv) { return KFS::ObjectStoreFsck(argc, argv); } <commit_msg>Meta server: eliminate compiler warnings.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2016/08/09 // // Author: Mike Ovsiannikov // // Copyright 2009 Quantcast Corp. // // This file is part of Kosmos File System (KFS). // // Licensed under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // // List files with object store blocks missing. // //---------------------------------------------------------------------------- #include "kfstree.h" #include "Checkpoint.h" #include "Restorer.h" #include "Replay.h" #include "util.h" #include "common/MdStream.h" #include "common/MsgLogger.h" #include "common/RequestParser.h" #include "kfsio/blockname.h" #include "libclient/KfsClient.h" #include <iostream> #include <string> #include <vector> #include <boost/static_assert.hpp> #include <boost/dynamic_bitset.hpp> namespace KFS { using std::cout; using std::cin; using std::cerr; using std::string; using boost::dynamic_bitset; typedef dynamic_bitset<> BlocksBitmap; inline static int RestoreCheckpoint( const string& inLockFileName) { if (! inLockFileName.empty()) { acquire_lockfile(inLockFileName, 10); } Restorer theRestorer; return (theRestorer.rebuild(LASTCP) ? 0 : -EIO); } inline static bool HasBitmapSet( const MetaFattr& theFattr) { const size_t kBits = 8 * sizeof(theFattr.subcount1); return ((int64_t)(kBits * CHUNKSIZE) <= theFattr.nextChunkOffset()); } inline static int GetFileName( const MetaFattr& inFattr, string& outFileName) { outFileName = metatree.getPathname(&inFattr); return 0; } inline static BlocksBitmap* GetBitmapPtr( const MetaFattr& inFattr) { BOOST_STATIC_ASSERT(sizeof(BlocksBitmap*) <= sizeof(inFattr.subcount1)); char* const kNullPtr = 0; return reinterpret_cast<BlocksBitmap*>(kNullPtr + inFattr.chunkcount()); } inline static void SetBitmapPtr( MetaFattr& inFattr, BlocksBitmap* inPtr) { const char* const kNullPtr = 0; inFattr.chunkcount() = reinterpret_cast<const char*>(inPtr) - kNullPtr; } static int ObjectStoreFsck( int inArgCnt, char** inArgaPtr) { int theOpt; string theCpDir; string theLockFile; ServerLocation theMetaServer; const char* theLogDirPtr = 0; const char* theConfigFileNamePtr = 0; MsgLogger::LogLevel theLogLevel = MsgLogger::kLogLevelINFO; int theStatus = 0; bool theHelpFlag = false; bool theReplayLastLogFlag = false; const char* thePtr; while ((theOpt = getopt(inArgCnt, inArgaPtr, "vhal:c:L:s:p:f:")) != -1) { switch (theOpt) { case 'a': theReplayLastLogFlag = true; break; case 'L': theLockFile = optarg; break; case 'l': theLogDirPtr = optarg; break; case 'c': theCpDir = optarg; break; case 's': theMetaServer.hostname = optarg; break; case 'p': thePtr = optarg; if (! DecIntParser::Parse( thePtr, strlen(thePtr), theMetaServer.port)) { theMetaServer.port = -1; } break; case 'v': theLogLevel = MsgLogger::kLogLevelDEBUG; break; case 'h': theHelpFlag = true; break; case 'f': theConfigFileNamePtr = optarg; break; default: theStatus = -EINVAL; break; } } if (theHelpFlag || 0 != theStatus || (! theMetaServer.hostname.empty() && ! theMetaServer.IsValid())) { cerr << "Usage: " << inArgaPtr[0] << "\n" "[-h <help>]\n" "[-v verbose]\n" "[-L <lock file>] default: no lock file\n" "[-l <transaction log directory>] default: kfslog\n" "[-c <checkpoint directory>] default: kfscp\n" "[-f <client configuration file>] default: none\n" "[-a replay last log segment] default: don't replay last segment\n" "[-s <meta server host>]\n" "[-p <meta server port>]\n" "\n" "Loads checkpoint, replays transaction logs, then" " reads object store block keys from standard in, one key per line," " and outputs \"lost\" file names on standard out (files with keys" " that were not present in standard in), if any." "\n\n" "Note that the list of object store block keys must be" " more recent than checkpoint, and transaction logs, and valid" " meta server host and port must be specified in order for" " this work correctly (no false positives) if the file system is" " \"live\" / being modified." "\n\n" "In other words, the correct procedure to check \"live\" file system" " is to copy / save checkpoint, and transaction logs, then create" " list of object store blocks, then run this tool." "\n" ; return 1; } MdStream::Init(); MsgLogger::Init(0, theLogLevel); if (! theCpDir.empty()) { checkpointer_setup_paths(theCpDir); } if (theLogDirPtr && theLogDirPtr[0]) { replayer.setLogDir(theLogDirPtr); } int64_t theLostCount = 0; KfsClient* const theClientPtr = theMetaServer.IsValid() ? KfsClient::Connect( theMetaServer.hostname, theMetaServer.port, theConfigFileNamePtr) : 0; if (theClientPtr) { // Make sure that the client is configured correctly prior to checkpoint // load and replay, by retrieving root node info. const kfsChunkId_t kChunkId = -1; chunkOff_t theOffset = -1; int64_t theVersion = 0; KfsFileAttr theCliAttr; vector<ServerLocation> theServers; theStatus = theClientPtr->GetFileOrChunkInfo( ROOTFID, kChunkId, theCliAttr, theOffset, theVersion, theServers ); } else if (theMetaServer.IsValid()) { theStatus = -ENOTCONN; } if (0 == theStatus && (theStatus = RestoreCheckpoint(theLockFile)) == 0 && (theStatus = replayer.playLogs(theReplayLastLogFlag)) == 0) { if (! theClientPtr) { // Setup back pointers, to get file names retrival working. metatree.setUpdatePathSpaceUsage(true); metatree.enableFidToPathname(); } const int64_t theFileSystemId = metatree.GetFsId(); string theExpectedKey; string theBlockKey; string theFsIdSuffix; theExpectedKey.reserve(256); theBlockKey.reserve(256); while (getline(cin, theBlockKey)) { KFS_LOG_STREAM_DEBUG << "key: " << theBlockKey << KFS_LOG_EOM; const char* thePtr = theBlockKey.data(); const char* const theEndPtr = thePtr + theBlockKey.size(); if (theEndPtr <= thePtr) { continue; } const int kSeparator = '.'; thePtr = reinterpret_cast<const char*>( memchr(thePtr, kSeparator, theEndPtr - thePtr)); fid_t theFid = -1; seq_t theVersion = 0; if (! thePtr || theEndPtr <= ++thePtr || ! DecIntParser::Parse(thePtr, theEndPtr - thePtr, theFid) || theFid < 0 || theEndPtr <= thePtr || kSeparator != (0xFF & *thePtr) || theEndPtr <= ++thePtr || ! DecIntParser::Parse( thePtr, theEndPtr - thePtr, theVersion) || 0 <= theVersion || theEndPtr <= thePtr || kSeparator != (0xFF & *thePtr)) { KFS_LOG_STREAM_ERROR << theBlockKey << ": malformed object store block key" << KFS_LOG_EOM; continue; } theExpectedKey.clear(); if (! AppendChunkFileNameOrObjectStoreBlockKey( theExpectedKey, theFileSystemId, theFid, theFid, theVersion, theFsIdSuffix)) { panic("block name generation failure"); continue; } if (theExpectedKey != theBlockKey) { KFS_LOG_STREAM_ERROR << theBlockKey << ": invalid object store block key" " expected: " << theExpectedKey << KFS_LOG_EOM; continue; } MetaFattr* const theFattrPtr = metatree.getFattr(theFid); if (! theFattrPtr) { KFS_LOG_STREAM_DEBUG << theBlockKey << ": invalid key: no such file" << KFS_LOG_EOM; continue; } if (KFS_FILE != theFattrPtr->type) { KFS_LOG_STREAM_ERROR << theBlockKey << ": invalid key:" " attribute type: " << theFattrPtr->type << KFS_LOG_EOM; continue; } if (0 != theFattrPtr->numReplicas) { KFS_LOG_STREAM_ERROR << theBlockKey << ": invalid key:" " replication: " << theFattrPtr->numReplicas << KFS_LOG_EOM; continue; } if (theFattrPtr->filesize <= 0) { KFS_LOG_STREAM_DEBUG << theBlockKey << ": skipping 0 size file" << KFS_LOG_EOM; continue; } const chunkOff_t thePos = -theVersion - 1 - theFattrPtr->minSTier; if (thePos < 0 || 0 != (thePos % (chunkOff_t)CHUNKSIZE)) { KFS_LOG_STREAM_ERROR << theBlockKey << ": invalid key:" " position: " << thePos << " tier: " << theFattrPtr->minSTier << " / " << theFattrPtr->maxSTier << KFS_LOG_EOM; continue; } if (theFattrPtr->nextChunkOffset() < thePos) { KFS_LOG_STREAM( theFattrPtr->nextChunkOffset() + (chunkOff_t)CHUNKSIZE < thePos ? MsgLogger::kLogLevelERROR : MsgLogger::kLogLevelDEBUG) << theBlockKey << ": block past last file block" " position: " << thePos << " last block: " << theFattrPtr->nextChunkOffset() << KFS_LOG_EOM; continue; } // Chunk count must be 0 for object store files. Use this field to // store bitmap of the blocks that are present in the input. If the // file has more blocks that fits into the chunk count field, then // allocate bit vector and store pointer to it. const size_t theIdx = thePos / CHUNKSIZE; if (HasBitmapSet(*theFattrPtr)) { BlocksBitmap* thePtr = GetBitmapPtr(*theFattrPtr); if (! thePtr) { thePtr = new BlocksBitmap( 1 + theFattrPtr->nextChunkOffset() / CHUNKSIZE); SetBitmapPtr(*theFattrPtr, thePtr); } else if ((*thePtr)[theIdx]) { KFS_LOG_STREAM_DEBUG << theBlockKey << ": duplicate input key" << KFS_LOG_EOM; continue; } (*thePtr)[theIdx] = true; } else { const int64_t theBit = int64_t(1) << theIdx; if (0 != (theFattrPtr->chunkcount() & theBit)) { KFS_LOG_STREAM_DEBUG << theBlockKey << ": duplicate input key" << KFS_LOG_EOM; continue; } theFattrPtr->chunkcount() |= theBit; } } // Traverse leaf nodes and query the the status for files with missing // blocks. KfsFileAttr theCliAttr; vector<ServerLocation> theServers; LeafIter theIt(metatree.firstLeaf(), 0); for (const Meta* theNPtr = 0; theIt.parent() && (theNPtr = theIt.current()); theIt.next()) { if (KFS_FATTR != theNPtr->metaType()) { continue; } const MetaFattr& theFattr = *static_cast<const MetaFattr*>(theNPtr); if (KFS_FILE != theFattr.type || 0 != theFattr.numReplicas || theFattr.filesize <= 0) { continue; } chunkOff_t theMissingIdx = 0; if (HasBitmapSet(theFattr)) { const BlocksBitmap* const thePtr = GetBitmapPtr(theFattr); if (thePtr) { for (theMissingIdx = 0; theMissingIdx < (chunkOff_t)thePtr->size() && (*thePtr)[theMissingIdx]; ++theMissingIdx) {} } } else { const int64_t theBits = theFattr.chunkcount(); const int64_t theEnd = theFattr.nextChunkOffset() / CHUNKSIZE; int64_t theBit = 1; for (theMissingIdx = 0; theMissingIdx <= theEnd && 0 != (theBits & theBit); theMissingIdx++, theBit <<= 1) {} } if (theMissingIdx * (chunkOff_t)CHUNKSIZE < theFattr.filesize) { const kfsChunkId_t kChunkId = -1; chunkOff_t theOffset = -1; int64_t theVersion = 0; const int theRet = theClientPtr ? theClientPtr->GetFileOrChunkInfo( theFattr.id(), kChunkId, theCliAttr, theOffset, theVersion, theServers ) : GetFileName(theFattr, theCliAttr.filename); if (0 == theRet) { cout << theCliAttr.filename << "\n"; theLostCount++; } else if (-ENOENT != theRet) { KFS_LOG_STREAM_ERROR << "failed to get file info:" " fid: " << theFattr.id() << " " << ErrorCodeToStr(theRet) << KFS_LOG_EOM; if (0 == theStatus) { theStatus = theRet; } } } } } if (0 != theStatus) { KFS_LOG_STREAM_ERROR << ErrorCodeToStr(theStatus) << KFS_LOG_EOM; } else { KFS_LOG_STREAM_INFO << "lost files: " << theLostCount << KFS_LOG_EOM; } delete theClientPtr; MsgLogger::Stop(); MdStream::Cleanup(); return ((0 == theStatus && 0 == theLostCount) ? 0 : 1); } } // namespace KFS int main(int argc, char **argv) { return KFS::ObjectStoreFsck(argc, argv); } <|endoftext|>
<commit_before>#include "notificationcontroller.h" // QT #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #ifdef USE_SNORTIFY // SNORTIFY #include <libsnore/snore.h> #include <libsnore/notification/notification.h> #include <libsnore/log.h> #endif NotificationController::NotificationController(QObject *parent) : QObject(parent) #ifdef USE_SNORTIFY // Snortify ,core(Snore::SnoreCore::instance()), icon(QString(":/root/snore.png")), snoreApplication(Snore::Application(qApp->applicationName(), icon)), alert(Snore::Alert(QString("Default"), icon)) #endif { #ifdef USE_SNORTIFY // Snortify Snore::SnoreLog::setDebugLvl(1); //Get the core Snore::SnoreCore::instance().loadPlugins( Snore::SnorePlugin::BACKEND | Snore::SnorePlugin::SECONDARY_BACKEND ); //All notifications have to have icon, so prebuild one core.registerApplication(snoreApplication); //Also alert is mandatory, just choose the default one snoreApplication.addAlert(alert); #endif } void NotificationController::showNotification(const QString &title, const QString &text) { #ifdef USE_SNORTIFY // Inform the user of the new message Snore::Notification n(snoreApplication, alert, title, text, icon); // Optional: you can also set delivery date if you want to schedule notification //n.setDeliveryDate(QDateTime::currentDateTime().addSecs(5)); core.broadcastNotification(n); #else qDebug() << title << " => " << text; #endif } <commit_msg>No notification for files<commit_after>#include "notificationcontroller.h" // QT #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #ifdef USE_SNORTIFY // SNORTIFY #include <libsnore/snore.h> #include <libsnore/notification/notification.h> #include <libsnore/log.h> #endif NotificationController::NotificationController(QObject *parent) : QObject(parent) #ifdef USE_SNORTIFY // Snortify ,core(Snore::SnoreCore::instance()), icon(QString(":/root/snore.png")), snoreApplication(Snore::Application(qApp->applicationName(), icon)), alert(Snore::Alert(QString("Default"), icon)) #endif { #ifdef USE_SNORTIFY // Snortify Snore::SnoreLog::setDebugLvl(1); //Get the core Snore::SnoreCore::instance().loadPlugins( Snore::SnorePlugin::BACKEND | Snore::SnorePlugin::SECONDARY_BACKEND ); //All notifications have to have icon, so prebuild one core.registerApplication(snoreApplication); //Also alert is mandatory, just choose the default one snoreApplication.addAlert(alert); #endif } void NotificationController::showNotification(const QString &title, const QString &text) { // We don't want files being shown if ( text.length() > 2048 ) { return; } #ifdef USE_SNORTIFY // Inform the user of the new message Snore::Notification n(snoreApplication, alert, title, text, icon); // Optional: you can also set delivery date if you want to schedule notification //n.setDeliveryDate(QDateTime::currentDateTime().addSecs(5)); core.broadcastNotification(n); #else qDebug() << title << " => " << text; #endif } <|endoftext|>
<commit_before>#include "client/socket.h" #include <stdio.h> Socket::Socket(Context *context, int port, std::string hostname) : context(context), Number(0) { // Connect to the server Connected = (socket.Connect(port, hostname) == sf::Socket::Done); socket.SetBlocking(false); } Socket::Socket(Context *context, sf::SocketTCP socket) : context(context), socket(socket), Number(0) { socket.SetBlocking(false); } void Socket::SendChat(const std::string Line) { sf::Packet Packet; Packet << (sf::Uint8) 3 << Line; socket.Send(Packet); } void Socket::SendBlock(sf::Uint8 type, Vector3 chunkIndex, Vector3 blockIndex) { sf::Packet Packet; Packet << type << chunkIndex << blockIndex; socket.Send(Packet); } void Socket::DoStep() { sf::Packet In; while (socket.Receive(In) == sf::Socket::Done) { sf::Uint8 command; In >> command; printf("Got packet: %i\n", command); // TODO: switch to a switch if (command == 1) { In >> context->world->ChunkSize; } else if (command == 2) { In >> Number >> context->player->Name >> context->player; Players[Number] = context->player; context->world->HandleRequests(context->player->Pos); // Request new chunks immediately when connecting } else if (command == 3) { std::string Line; In >> Line; context->hud->Output(Line); } else if (command == 4) { // TODO!!! TODO!!! ((SocketStorage*) context->world->Storage)->ReadChunk(In); //int BlockCount; //Vector3 ChunkIndex; // TODO: remove from request list, add to loaded list //In >> ChunkIndex >> BlockCount; //Chunk chunk(ChunkIndex, 16); //chunk.FillWith(3); //context->world->LoadedChunks[ChunkIndex] = chunk; context->inGame = true; // Ready to play TEH GAME! ;D } else if (command == 5) { int who; In >> who; // RAH RAH RAH STL Player *player = (*((Players.insert(std::make_pair(who, new Player))).first)).second; if (who != Number) In >> player; // TODO: yea I had no idea what I was doing there... } else if (command == 6) { int PlayerCount; In >> PlayerCount; int who; std::string username; Player *player; Players.clear(); for (int i = 0; i < PlayerCount; i++) { player = new Player(); In >> who >> username >> player; player->Name = username; Players[who] = player; } Players[Number] = context->player; } else if (command == 7) { int who; std::string username; In >> who >> username; Player *player = new Player; In >> player; player->Name = username; Players[who] = player; context->hud->Output(username + " joined"); } else if (command == 8) { int who; In >> who; // RAH RAH RAH STL Player *player = (*((Players.insert(std::make_pair(who, new Player))).first)).second; context->hud->Output(player->Name + " left"); Players.erase(who); } else if (command == 9) { Vector3 chunk, block; sf::Uint8 type; In >> type >> chunk >> block; context->world->PlaceBlock(type, chunk, block); } else printf("Got strange packet: %i\n", command); } if ((context->player->Dirty && (updateTimer.GetElapsedTime() > 0.5f)) || (updateTimer.GetElapsedTime() > 5.f)) { sf::Packet Out; Out << (sf::Uint8) 5 << context->player; socket.Send(Out); context->player->Dirty = false; updateTimer.Reset(); } float ElapsedTime = Clock.GetElapsedTime(); Clock.Reset(); for (std::map<int, Player*>::iterator player = Players.begin(); player != Players.end(); player++) { player->second->LocatedOn = NULL; context->world->CheckCollision(player->second); player->second->DoStep(ElapsedTime); } } void Socket::Close() { socket.Close(); } <commit_msg>Don't process physics until at least one chunk is received. Revealed a new bug :D<commit_after>#include "client/socket.h" #include <stdio.h> Socket::Socket(Context *context, int port, std::string hostname) : context(context), Number(0) { // Connect to the server Connected = (socket.Connect(port, hostname) == sf::Socket::Done); socket.SetBlocking(false); } Socket::Socket(Context *context, sf::SocketTCP socket) : context(context), socket(socket), Number(0) { socket.SetBlocking(false); } void Socket::SendChat(const std::string Line) { sf::Packet Packet; Packet << (sf::Uint8) 3 << Line; socket.Send(Packet); } void Socket::SendBlock(sf::Uint8 type, Vector3 chunkIndex, Vector3 blockIndex) { sf::Packet Packet; Packet << type << chunkIndex << blockIndex; socket.Send(Packet); } void Socket::DoStep() { sf::Packet In; while (socket.Receive(In) == sf::Socket::Done) { sf::Uint8 command; In >> command; printf("Got packet: %i\n", command); // TODO: switch to a switch if (command == 1) { In >> context->world->ChunkSize; } else if (command == 2) { In >> Number >> context->player->Name >> context->player; Players[Number] = context->player; context->world->HandleRequests(context->player->Pos); // Request new chunks immediately when connecting } else if (command == 3) { std::string Line; In >> Line; context->hud->Output(Line); } else if (command == 4) { // TODO!!! TODO!!! ((SocketStorage*) context->world->Storage)->ReadChunk(In); //int BlockCount; //Vector3 ChunkIndex; // TODO: remove from request list, add to loaded list //In >> ChunkIndex >> BlockCount; //Chunk chunk(ChunkIndex, 16); //chunk.FillWith(3); //context->world->LoadedChunks[ChunkIndex] = chunk; context->inGame = true; // Ready to play TEH GAME! ;D } else if (command == 5) { int who; In >> who; // RAH RAH RAH STL Player *player = (*((Players.insert(std::make_pair(who, new Player))).first)).second; if (who != Number) In >> player; // TODO: yea I had no idea what I was doing there... } else if (command == 6) { int PlayerCount; In >> PlayerCount; int who; std::string username; Player *player; Players.clear(); for (int i = 0; i < PlayerCount; i++) { player = new Player(); In >> who >> username >> player; player->Name = username; Players[who] = player; } Players[Number] = context->player; } else if (command == 7) { int who; std::string username; In >> who >> username; Player *player = new Player; In >> player; player->Name = username; Players[who] = player; context->hud->Output(username + " joined"); } else if (command == 8) { int who; In >> who; // RAH RAH RAH STL Player *player = (*((Players.insert(std::make_pair(who, new Player))).first)).second; context->hud->Output(player->Name + " left"); Players.erase(who); } else if (command == 9) { Vector3 chunk, block; sf::Uint8 type; In >> type >> chunk >> block; context->world->PlaceBlock(type, chunk, block); } else printf("Got strange packet: %i\n", command); } if (!context->inGame) return; if ((context->player->Dirty && (updateTimer.GetElapsedTime() > 0.5f)) || (updateTimer.GetElapsedTime() > 5.f)) { sf::Packet Out; Out << (sf::Uint8) 5 << context->player; socket.Send(Out); context->player->Dirty = false; updateTimer.Reset(); } float ElapsedTime = Clock.GetElapsedTime(); Clock.Reset(); for (std::map<int, Player*>::iterator player = Players.begin(); player != Players.end(); player++) { player->second->LocatedOn = NULL; context->world->CheckCollision(player->second); player->second->DoStep(ElapsedTime); } } void Socket::Close() { socket.Close(); } <|endoftext|>
<commit_before>#include <iostream> #include "ext_mongo.h" #include "bson_decode.h" #include "contrib/encode.h" namespace HPHP { //////////////////////////////////////////////////////////////////////////////// // class MongoCursor static Array HHVM_METHOD(MongoCursor, current) { mongoc_cursor_t *cursor = get_cursor(this_)->get(); const bson_t *doc; doc = mongoc_cursor_current(cursor); if (doc) { auto ret = cbson_loads(doc); //TODO: We should return the translated PHP Array here return ret; } else { return Array::Create(); //Empty array means no valid document left } } static bool HHVM_METHOD(MongoCursor, hasNext) { bson_error_t error; mongoc_cursor_t *cursor = get_cursor(this_)->get(); bool ret = mongoc_cursor_more(cursor); if (!mongoc_cursor_error (cursor, &error)) { return ret; } else { throw FatalErrorException(error.message); } } static void HHVM_METHOD(MongoCursor, next) { const bson_t *doc; mongoc_cursor_t *cursor = get_cursor(this_)->get(); // if (!mongoc_cursor_next (cursor, &doc)) { // if (mongoc_cursor_error (cursor, &error)) { // throw FatalErrorException(error.message); // } // } mongoc_cursor_next (cursor, &doc); //Note: error would be catched by valid() } static void HHVM_METHOD(MongoCursor, reset) { if (get_cursor(this_)) { get_cursor(this_)->~MongocCursor(); } } static void HHVM_METHOD(MongoCursor, rewind) { HHVM_MN(MongoCursor, reset)(this_); //TODO: need to test with null value auto connection = this_->o_realProp("connection", ObjectData::RealPropUnchecked, "MongoCursor")->toObject(); auto ns = this_->o_realProp("ns", ObjectData::RealPropUnchecked, "MongoCursor")->toString(); auto query = this_->o_realProp("query", ObjectData::RealPropUnchecked, "MongoCursor")->toArray(); bson_t query_bs; query_bs = encodeToBSON(query); /* bson_init(&query_bs); if (!query->empty()) { //Currently only supports "name" query bson_append_utf8(&query_bs, "name", 4, query[String("name")].toString().c_str(), query[String("name")].toString().length()); } */ //Parameters and their types: //static void HHVM_METHOD(MongoCursor, __construct, const Object& connection, const String& ns, const Array& query, const Array& fields) /* MongocCursor(mongoc_client_t *client, const char *db_and_collection, mongoc_query_flags_t flags, uint32_t skip, uint32_t limit, uint32_t batch_size, bool is_command, const bson_t *query, const bson_t *fields, const mongoc_read_prefs_t *read_prefs); */ /* fields needed: private $flags = []; //TODO: implement this private $skip = 0; private $limit = 0; private $batchSize = 100; private $fields = []; private $read_preference = []; */ bson_t fields_bs; mongoc_read_prefs_t *read_prefs; bson_t read_prefs_tags_bs; auto flags_array = this_->o_realProp("flags", ObjectData::RealPropUnchecked, "MongoCursor")->toArray(); mongoc_query_flags_t flags = MONGOC_QUERY_NONE; //if (flags_array->exists(0)) { flags |= MONGOC_QUERY_NONE;} // if (flags_array->exists(1)) { flags = (flags | MONGOC_QUERY_TAILABLE_CURSOR);} // if (flags_array->exists(2)) { flags = (flags | MONGOC_QUERY_SLAVE_OK);} // if (flags_array->exists(3)) { flags = (flags | MONGOC_QUERY_OPLOG_REPLAY);} // if (flags_array->exists(4)) { flags = (flags | MONGOC_QUERY_NO_CURSOR_TIMEOUT);} // if (flags_array->exists(5)) { flags = (flags | MONGOC_QUERY_AWAIT_DATA);} // if (flags_array->exists(6)) { flags = (flags | MONGOC_QUERY_EXHAUST);} // if (flags_array->exists(7)) { flags = (flags | MONGOC_QUERY_PARTIAL);} uint32_t skip = this_->o_realProp("skip", ObjectData::RealPropUnchecked, "MongoCursor")->toInt32(); uint32_t limit = this_->o_realProp("limit", ObjectData::RealPropUnchecked, "MongoCursor")->toInt32(); uint32_t batchSize = this_->o_realProp("batchSize", ObjectData::RealPropUnchecked, "MongoCursor")->toInt32(); auto fields = this_->o_realProp("fields", ObjectData::RealPropUnchecked, "MongoCursor")->toArray(); auto read_prefs_array = this_->o_realProp("read_preference", ObjectData::RealPropUnchecked, "MongoCursor")->toArray(); String read_pref_type = read_prefs_array[String("type")].toString(); Array read_pref_tagsets = read_prefs_array[String("tagsets")].toArray(); read_prefs_tags_bs = encodeToBSON(read_pref_tagsets); /* MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, MongoClient::RP_NEAREST */ read_prefs = mongoc_read_prefs_new(MONGOC_READ_PRIMARY); if (read_pref_type.equal(String("RP_PRIMARY"))) { mongoc_read_prefs_set_mode(read_prefs, MONGOC_READ_PRIMARY); } else if (read_pref_type.equal(String("RP_PRIMARY_PREFERRED"))) { mongoc_read_prefs_set_mode(read_prefs, MONGOC_READ_PRIMARY_PREFERRED); } else if (read_pref_type.equal(String("RP_SECONDARY"))) { mongoc_read_prefs_set_mode(read_prefs, MONGOC_READ_SECONDARY); } else if (read_pref_type.equal(String("RP_SECONDARY_PREFERRED"))) { mongoc_read_prefs_set_mode(read_prefs, MONGOC_READ_SECONDARY_PREFERRED); } else if (read_pref_type.equal(String("RP_NEAREST"))) { mongoc_read_prefs_set_mode(read_prefs, MONGOC_READ_NEAREST); } mongoc_read_prefs_set_tags(read_prefs, &read_prefs_tags_bs); fields_bs = encodeToBSON(fields); MongocCursor *cursor = new MongocCursor(get_client(connection)->get(), ns.c_str(), flags, skip, limit, batchSize, false, &query_bs, &fields_bs, read_prefs); this_->o_set(s_mongoc_cursor, cursor, s_mongocursor); bson_destroy(&query_bs); bson_destroy(&fields_bs); bson_destroy(&read_prefs_tags_bs); this_->o_set("started_iterating", Variant(true), "MongoCursor"); HHVM_MN(MongoCursor, next)(this_); } static bool HHVM_METHOD(MongoCursor, valid) { auto cur = HHVM_MN(MongoCursor, current)(this_); return !(cur->empty()); } //////////////////////////////////////////////////////////////////////////////// void mongoExtension::_initMongoCursorClass() { HHVM_ME(MongoCursor, current); HHVM_ME(MongoCursor, hasNext); HHVM_ME(MongoCursor, next); HHVM_ME(MongoCursor, reset); HHVM_ME(MongoCursor, rewind); HHVM_ME(MongoCursor, valid); } } // namespace HPHP <commit_msg>OR operation on enum type working<commit_after>#include <iostream> #include "ext_mongo.h" #include "bson_decode.h" #include "contrib/encode.h" namespace HPHP { //////////////////////////////////////////////////////////////////////////////// // class MongoCursor static Array HHVM_METHOD(MongoCursor, current) { mongoc_cursor_t *cursor = get_cursor(this_)->get(); const bson_t *doc; doc = mongoc_cursor_current(cursor); if (doc) { auto ret = cbson_loads(doc); //TODO: We should return the translated PHP Array here return ret; } else { return Array::Create(); //Empty array means no valid document left } } static bool HHVM_METHOD(MongoCursor, hasNext) { bson_error_t error; mongoc_cursor_t *cursor = get_cursor(this_)->get(); bool ret = mongoc_cursor_more(cursor); if (!mongoc_cursor_error (cursor, &error)) { return ret; } else { throw FatalErrorException(error.message); } } static void HHVM_METHOD(MongoCursor, next) { const bson_t *doc; mongoc_cursor_t *cursor = get_cursor(this_)->get(); // if (!mongoc_cursor_next (cursor, &doc)) { // if (mongoc_cursor_error (cursor, &error)) { // throw FatalErrorException(error.message); // } // } mongoc_cursor_next (cursor, &doc); //Note: error would be catched by valid() } static void HHVM_METHOD(MongoCursor, reset) { if (get_cursor(this_)) { get_cursor(this_)->~MongocCursor(); } } static void HHVM_METHOD(MongoCursor, rewind) { HHVM_MN(MongoCursor, reset)(this_); //TODO: need to test with null value auto connection = this_->o_realProp("connection", ObjectData::RealPropUnchecked, "MongoCursor")->toObject(); auto ns = this_->o_realProp("ns", ObjectData::RealPropUnchecked, "MongoCursor")->toString(); auto query = this_->o_realProp("query", ObjectData::RealPropUnchecked, "MongoCursor")->toArray(); bson_t query_bs; query_bs = encodeToBSON(query); /* bson_init(&query_bs); if (!query->empty()) { //Currently only supports "name" query bson_append_utf8(&query_bs, "name", 4, query[String("name")].toString().c_str(), query[String("name")].toString().length()); } */ //Parameters and their types: //static void HHVM_METHOD(MongoCursor, __construct, const Object& connection, const String& ns, const Array& query, const Array& fields) /* MongocCursor(mongoc_client_t *client, const char *db_and_collection, mongoc_query_flags_t flags, uint32_t skip, uint32_t limit, uint32_t batch_size, bool is_command, const bson_t *query, const bson_t *fields, const mongoc_read_prefs_t *read_prefs); */ /* fields needed: private $flags = []; //TODO: implement this private $skip = 0; private $limit = 0; private $batchSize = 100; private $fields = []; private $read_preference = []; */ bson_t fields_bs; mongoc_read_prefs_t *read_prefs; bson_t read_prefs_tags_bs; auto flags_array = this_->o_realProp("flags", ObjectData::RealPropUnchecked, "MongoCursor")->toArray(); int flags = MONGOC_QUERY_NONE; if (flags_array->exists((int64_t)0)) { flags |= MONGOC_QUERY_NONE;} if (flags_array->exists((int64_t)1)) { flags = (flags | MONGOC_QUERY_TAILABLE_CURSOR);} if (flags_array->exists((int64_t)2)) { flags = (flags | MONGOC_QUERY_SLAVE_OK);} if (flags_array->exists((int64_t)3)) { flags = (flags | MONGOC_QUERY_OPLOG_REPLAY);} if (flags_array->exists((int64_t)4)) { flags = (flags | MONGOC_QUERY_NO_CURSOR_TIMEOUT);} if (flags_array->exists((int64_t)5)) { flags = (flags | MONGOC_QUERY_AWAIT_DATA);} if (flags_array->exists((int64_t)6)) { flags = (flags | MONGOC_QUERY_EXHAUST);} if (flags_array->exists((int64_t)7)) { flags = (flags | MONGOC_QUERY_PARTIAL);} uint32_t skip = this_->o_realProp("skip", ObjectData::RealPropUnchecked, "MongoCursor")->toInt32(); uint32_t limit = this_->o_realProp("limit", ObjectData::RealPropUnchecked, "MongoCursor")->toInt32(); uint32_t batchSize = this_->o_realProp("batchSize", ObjectData::RealPropUnchecked, "MongoCursor")->toInt32(); auto fields = this_->o_realProp("fields", ObjectData::RealPropUnchecked, "MongoCursor")->toArray(); auto read_prefs_array = this_->o_realProp("read_preference", ObjectData::RealPropUnchecked, "MongoCursor")->toArray(); String read_pref_type = read_prefs_array[String("type")].toString(); Array read_pref_tagsets = read_prefs_array[String("tagsets")].toArray(); read_prefs_tags_bs = encodeToBSON(read_pref_tagsets); /* MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, MongoClient::RP_NEAREST */ read_prefs = mongoc_read_prefs_new(MONGOC_READ_PRIMARY); if (read_pref_type.equal(String("RP_PRIMARY"))) { mongoc_read_prefs_set_mode(read_prefs, MONGOC_READ_PRIMARY); } else if (read_pref_type.equal(String("RP_PRIMARY_PREFERRED"))) { mongoc_read_prefs_set_mode(read_prefs, MONGOC_READ_PRIMARY_PREFERRED); } else if (read_pref_type.equal(String("RP_SECONDARY"))) { mongoc_read_prefs_set_mode(read_prefs, MONGOC_READ_SECONDARY); } else if (read_pref_type.equal(String("RP_SECONDARY_PREFERRED"))) { mongoc_read_prefs_set_mode(read_prefs, MONGOC_READ_SECONDARY_PREFERRED); } else if (read_pref_type.equal(String("RP_NEAREST"))) { mongoc_read_prefs_set_mode(read_prefs, MONGOC_READ_NEAREST); } mongoc_read_prefs_set_tags(read_prefs, &read_prefs_tags_bs); fields_bs = encodeToBSON(fields); MongocCursor *cursor = new MongocCursor(get_client(connection)->get(), ns.c_str(), (mongoc_query_flags_t)flags, skip, limit, batchSize, false, &query_bs, &fields_bs, read_prefs); this_->o_set(s_mongoc_cursor, cursor, s_mongocursor); bson_destroy(&query_bs); bson_destroy(&fields_bs); bson_destroy(&read_prefs_tags_bs); this_->o_set("started_iterating", Variant(true), "MongoCursor"); HHVM_MN(MongoCursor, next)(this_); } static bool HHVM_METHOD(MongoCursor, valid) { auto cur = HHVM_MN(MongoCursor, current)(this_); return !(cur->empty()); } //////////////////////////////////////////////////////////////////////////////// void mongoExtension::_initMongoCursorClass() { HHVM_ME(MongoCursor, current); HHVM_ME(MongoCursor, hasNext); HHVM_ME(MongoCursor, next); HHVM_ME(MongoCursor, reset); HHVM_ME(MongoCursor, rewind); HHVM_ME(MongoCursor, valid); } } // namespace HPHP <|endoftext|>
<commit_before>// serial.cxx -- Unix serial I/O support // // Written by Curtis Olson, started November 1998. // // Copyright (C) 1998 Curtis L. Olson - http://www.flightgear.org/~curt // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // // $Id$ #include <simgear/compiler.h> #include STL_IOSTREAM #ifdef SG_HAVE_STD_INCLUDE # include <cerrno> #else # include <errno.h> #endif #if !defined( WIN32 ) || defined( __CYGWIN__) || defined( __CYGWIN32__ ) # include <termios.h> # include <sys/types.h> # include <sys/stat.h> # include <fcntl.h> # include <unistd.h> #endif #include <simgear/debug/logstream.hxx> #include "serial.hxx" SGSerialPort::SGSerialPort() : dev_open(false) { // empty } SGSerialPort::SGSerialPort(const string& device, int baud) { open_port(device); if ( dev_open ) { set_baud(baud); } } SGSerialPort::~SGSerialPort() { // closing the port here screws us up because if we would even so // much as make a copy of an SGSerialPort object and then delete it, // the file descriptor gets closed. Doh!!! } bool SGSerialPort::open_port(const string& device) { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) fd = CreateFile( device.c_str(), GENERIC_READ | GENERIC_WRITE, 0, // dwShareMode NULL, // lpSecurityAttributes OPEN_EXISTING, 0, NULL ); if ( fd == INVALID_HANDLE_VALUE ) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Error opening serial device \"" << device << "\" " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); return false; } dev_open = true; return true; #else struct termios config; fd = open(device.c_str(), O_RDWR | O_NONBLOCK); SG_LOG( SG_EVENT, SG_DEBUG, "Serial fd created = " << fd); if ( fd == -1 ) { SG_LOG( SG_IO, SG_ALERT, "Cannot open " << device << " for serial I/O" ); return false; } else { dev_open = true; } // set required port parameters if ( tcgetattr( fd, &config ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Unable to poll port settings" ); return false; } // cfmakeraw( &config ); // cout << "config.c_iflag = " << config.c_iflag << endl; // software flow control on config.c_iflag |= IXON; // config.c_iflag |= IXOFF; // config.c_cflag |= CLOCAL; #if ! defined( sgi ) // disable hardware flow control config.c_cflag &= ~(CRTSCTS); #endif // cout << "config.c_iflag = " << config.c_iflag << endl; if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Unable to update port settings" ); return false; } return true; #endif } bool SGSerialPort::close_port() { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) CloseHandle( fd ); #else close(fd); #endif dev_open = false; return true; } bool SGSerialPort::set_baud(int baud) { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) DCB dcb; if ( GetCommState( fd, &dcb ) ) { dcb.BaudRate = baud; dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fOutX = TRUE; dcb.fInX = TRUE; if ( !SetCommState( fd, &dcb ) ) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Unable to update port settings: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); return false; } } else { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Unable to poll port settings: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); return false; } return true; #else struct termios config; speed_t speed = B9600; if ( tcgetattr( fd, &config ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Unable to poll port settings" ); return false; } if ( baud == 300 ) { speed = B300; } else if ( baud == 1200 ) { speed = B1200; } else if ( baud == 2400 ) { speed = B2400; } else if ( baud == 4800 ) { speed = B4800; } else if ( baud == 9600 ) { speed = B9600; } else if ( baud == 19200 ) { speed = B19200; } else if ( baud == 38400 ) { speed = B38400; } else if ( baud == 57600 ) { speed = B57600; } else if ( baud == 115200 ) { speed = B115200; #if defined( linux ) || defined( __FreeBSD__ ) } else if ( baud == 230400 ) { speed = B230400; #endif } else { SG_LOG( SG_IO, SG_ALERT, "Unsupported baud rate " << baud ); return false; } if ( cfsetispeed( &config, speed ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Problem setting input baud rate" ); return false; } if ( cfsetospeed( &config, speed ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Problem setting output baud rate" ); return false; } if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Unable to update port settings" ); return false; } return true; #endif } string SGSerialPort::read_port() { const int max_count = 1024; char buffer[max_count+1]; string result; #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) DWORD count; if ( ReadFile( fd, buffer, max_count, &count, 0 ) ) { buffer[count] = '\0'; result = buffer; } else { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Serial I/O read error: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); } return result; #else int count = read(fd, buffer, max_count); // cout << "read " << count << " bytes" << endl; if ( count < 0 ) { // error condition if ( errno != EAGAIN ) { SG_LOG( SG_IO, SG_ALERT, "Serial I/O on read, error number = " << errno ); } return ""; } else { buffer[count] = '\0'; result = buffer; return result; } #endif } int SGSerialPort::read_port(char *buf, int len) { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) DWORD count; if ( ReadFile( fd, buf, len, &count, 0 ) ) { buf[count] = '\0'; return count; } else { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Serial I/O read error: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); buf[0] = '\0'; return 0; } #else string result; int count = read(fd, buf, len); // cout << "read " << count << " bytes" << endl; if ( count < 0 ) { // error condition if ( errno != EAGAIN ) { SG_LOG( SG_IO, SG_ALERT, "Serial I/O on read, error number = " << errno ); } buf[0] = '\0'; return 0; } else { buf[count] = '\0'; return count; } #endif } int SGSerialPort::write_port(const string& value) { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) LPCVOID lpBuffer = value.data(); DWORD nNumberOfBytesToWrite = value.length(); DWORD lpNumberOfBytesWritten; if ( WriteFile( fd, lpBuffer, nNumberOfBytesToWrite, &lpNumberOfBytesWritten, 0 ) == 0 ) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Serial I/O write error: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); return int(lpNumberOfBytesWritten); } return int(lpNumberOfBytesWritten); #else static bool error = false; int count; if ( error ) { SG_LOG( SG_IO, SG_ALERT, "attempting serial write error recovery" ); // attempt some sort of error recovery count = write(fd, "\n", 1); if ( count == 1 ) { // cout << "Serial error recover successful!\n"; error = false; } else { return 0; } } count = write(fd, value.c_str(), value.length()); // cout << "write '" << value << "' " << count << " bytes" << endl; if ( (int)count == (int)value.length() ) { error = false; } else { if ( errno == EAGAIN ) { // ok ... in our context we don't really care if we can't // write a string, we'll just get it the next time around error = false; } else { error = true; SG_LOG( SG_IO, SG_ALERT, "Serial I/O on write, error number = " << errno ); } } return count; #endif } int SGSerialPort::write_port(const char* buf, int len) { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) LPCVOID lpBuffer = buf; DWORD nNumberOfBytesToWrite = len; DWORD lpNumberOfBytesWritten; if ( WriteFile( fd, lpBuffer, nNumberOfBytesToWrite, &lpNumberOfBytesWritten, 0 ) == 0 ) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Serial I/O write error: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); return int(lpNumberOfBytesWritten); } return int(lpNumberOfBytesWritten); #else static bool error = false; int count; if ( error ) { // attempt some sort of error recovery count = write(fd, "\n", 1); if ( count == 1 ) { // cout << "Serial error recover successful!\n"; error = false; } else { return 0; } } count = write(fd, buf, len); // cout << "write '" << buf << "' " << count << " bytes" << endl; if ( (int)count == len ) { error = false; } else { error = true; if ( errno == EAGAIN ) { // ok ... in our context we don't really care if we can't // write a string, we'll just get it the next time around } else { SG_LOG( SG_IO, SG_ALERT, "Serial I/O on write, error number = " << errno ); } } return count; #endif } <commit_msg>AIX fix<commit_after>// serial.cxx -- Unix serial I/O support // // Written by Curtis Olson, started November 1998. // // Copyright (C) 1998 Curtis L. Olson - http://www.flightgear.org/~curt // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // // $Id$ #include <simgear/compiler.h> #include STL_IOSTREAM #ifdef SG_HAVE_STD_INCLUDE # include <cerrno> #else # include <errno.h> #endif #if !defined( WIN32 ) || defined( __CYGWIN__) || defined( __CYGWIN32__ ) # include <termios.h> # include <sys/types.h> # include <sys/stat.h> # include <fcntl.h> # include <unistd.h> #endif #include <simgear/debug/logstream.hxx> #include "serial.hxx" SGSerialPort::SGSerialPort() : dev_open(false) { // empty } SGSerialPort::SGSerialPort(const string& device, int baud) { open_port(device); if ( dev_open ) { set_baud(baud); } } SGSerialPort::~SGSerialPort() { // closing the port here screws us up because if we would even so // much as make a copy of an SGSerialPort object and then delete it, // the file descriptor gets closed. Doh!!! } bool SGSerialPort::open_port(const string& device) { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) fd = CreateFile( device.c_str(), GENERIC_READ | GENERIC_WRITE, 0, // dwShareMode NULL, // lpSecurityAttributes OPEN_EXISTING, 0, NULL ); if ( fd == INVALID_HANDLE_VALUE ) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Error opening serial device \"" << device << "\" " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); return false; } dev_open = true; return true; #else struct termios config; fd = open(device.c_str(), O_RDWR | O_NONBLOCK); SG_LOG( SG_EVENT, SG_DEBUG, "Serial fd created = " << fd); if ( fd == -1 ) { SG_LOG( SG_IO, SG_ALERT, "Cannot open " << device << " for serial I/O" ); return false; } else { dev_open = true; } // set required port parameters if ( tcgetattr( fd, &config ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Unable to poll port settings" ); return false; } // cfmakeraw( &config ); // cout << "config.c_iflag = " << config.c_iflag << endl; // software flow control on config.c_iflag |= IXON; // config.c_iflag |= IXOFF; // config.c_cflag |= CLOCAL; #if !defined( sgi ) && !defined(_AIX) // disable hardware flow control config.c_cflag &= ~(CRTSCTS); #endif // cout << "config.c_iflag = " << config.c_iflag << endl; if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Unable to update port settings" ); return false; } return true; #endif } bool SGSerialPort::close_port() { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) CloseHandle( fd ); #else close(fd); #endif dev_open = false; return true; } bool SGSerialPort::set_baud(int baud) { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) DCB dcb; if ( GetCommState( fd, &dcb ) ) { dcb.BaudRate = baud; dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fOutX = TRUE; dcb.fInX = TRUE; if ( !SetCommState( fd, &dcb ) ) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Unable to update port settings: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); return false; } } else { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Unable to poll port settings: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); return false; } return true; #else struct termios config; speed_t speed = B9600; if ( tcgetattr( fd, &config ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Unable to poll port settings" ); return false; } if ( baud == 300 ) { speed = B300; } else if ( baud == 1200 ) { speed = B1200; } else if ( baud == 2400 ) { speed = B2400; } else if ( baud == 4800 ) { speed = B4800; } else if ( baud == 9600 ) { speed = B9600; } else if ( baud == 19200 ) { speed = B19200; } else if ( baud == 38400 ) { speed = B38400; #if defined( linux ) || defined( __FreeBSD__ ) } else if ( baud == 57600 ) { speed = B57600; } else if ( baud == 115200 ) { speed = B115200; } else if ( baud == 230400 ) { speed = B230400; #endif } else { SG_LOG( SG_IO, SG_ALERT, "Unsupported baud rate " << baud ); return false; } if ( cfsetispeed( &config, speed ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Problem setting input baud rate" ); return false; } if ( cfsetospeed( &config, speed ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Problem setting output baud rate" ); return false; } if ( tcsetattr( fd, TCSANOW, &config ) != 0 ) { SG_LOG( SG_IO, SG_ALERT, "Unable to update port settings" ); return false; } return true; #endif } string SGSerialPort::read_port() { const int max_count = 1024; char buffer[max_count+1]; string result; #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) DWORD count; if ( ReadFile( fd, buffer, max_count, &count, 0 ) ) { buffer[count] = '\0'; result = buffer; } else { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Serial I/O read error: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); } return result; #else int count = read(fd, buffer, max_count); // cout << "read " << count << " bytes" << endl; if ( count < 0 ) { // error condition if ( errno != EAGAIN ) { SG_LOG( SG_IO, SG_ALERT, "Serial I/O on read, error number = " << errno ); } return ""; } else { buffer[count] = '\0'; result = buffer; return result; } #endif } int SGSerialPort::read_port(char *buf, int len) { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) DWORD count; if ( ReadFile( fd, buf, len, &count, 0 ) ) { buf[count] = '\0'; return count; } else { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Serial I/O read error: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); buf[0] = '\0'; return 0; } #else string result; int count = read(fd, buf, len); // cout << "read " << count << " bytes" << endl; if ( count < 0 ) { // error condition if ( errno != EAGAIN ) { SG_LOG( SG_IO, SG_ALERT, "Serial I/O on read, error number = " << errno ); } buf[0] = '\0'; return 0; } else { buf[count] = '\0'; return count; } #endif } int SGSerialPort::write_port(const string& value) { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) LPCVOID lpBuffer = value.data(); DWORD nNumberOfBytesToWrite = value.length(); DWORD lpNumberOfBytesWritten; if ( WriteFile( fd, lpBuffer, nNumberOfBytesToWrite, &lpNumberOfBytesWritten, 0 ) == 0 ) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Serial I/O write error: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); return int(lpNumberOfBytesWritten); } return int(lpNumberOfBytesWritten); #else static bool error = false; int count; if ( error ) { SG_LOG( SG_IO, SG_ALERT, "attempting serial write error recovery" ); // attempt some sort of error recovery count = write(fd, "\n", 1); if ( count == 1 ) { // cout << "Serial error recover successful!\n"; error = false; } else { return 0; } } count = write(fd, value.c_str(), value.length()); // cout << "write '" << value << "' " << count << " bytes" << endl; if ( (int)count == (int)value.length() ) { error = false; } else { if ( errno == EAGAIN ) { // ok ... in our context we don't really care if we can't // write a string, we'll just get it the next time around error = false; } else { error = true; SG_LOG( SG_IO, SG_ALERT, "Serial I/O on write, error number = " << errno ); } } return count; #endif } int SGSerialPort::write_port(const char* buf, int len) { #if defined( WIN32 ) && !defined( __CYGWIN__) && !defined( __CYGWIN32__ ) LPCVOID lpBuffer = buf; DWORD nNumberOfBytesToWrite = len; DWORD lpNumberOfBytesWritten; if ( WriteFile( fd, lpBuffer, nNumberOfBytesToWrite, &lpNumberOfBytesWritten, 0 ) == 0 ) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); SG_LOG( SG_IO, SG_ALERT, "Serial I/O write error: " << (const char*) lpMsgBuf ); LocalFree( lpMsgBuf ); return int(lpNumberOfBytesWritten); } return int(lpNumberOfBytesWritten); #else static bool error = false; int count; if ( error ) { // attempt some sort of error recovery count = write(fd, "\n", 1); if ( count == 1 ) { // cout << "Serial error recover successful!\n"; error = false; } else { return 0; } } count = write(fd, buf, len); // cout << "write '" << buf << "' " << count << " bytes" << endl; if ( (int)count == len ) { error = false; } else { error = true; if ( errno == EAGAIN ) { // ok ... in our context we don't really care if we can't // write a string, we'll just get it the next time around } else { SG_LOG( SG_IO, SG_ALERT, "Serial I/O on write, error number = " << errno ); } } return count; #endif } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/wallclock.h" #include "fnord-base/VFS.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-http/VFSFileServlet.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-sstable/SSTableServlet.h" #include "fnord-eventdb/EventDBServlet.h" #include "fnord-eventdb/TableRepository.h" #include "fnord-eventdb/TableJanitor.h" #include "fnord-mdb/MDB.h" #include "fnord-mdb/MDBUtil.h" #include "common.h" #include "schemas.h" #include "CustomerNamespace.h" #include "FeatureSchema.h" #include "JoinedQuery.h" #include "analytics/AnalyticsServlet.h" #include "analytics/CTRByPageServlet.h" #include "analytics/CTRStatsServlet.h" #include "analytics/CTRByPositionQuery.h" #include "analytics/CTRByPageQuery.h" #include "analytics/TopSearchQueriesQuery.h" #include "analytics/DiscoveryKPIQuery.h" #include "analytics/DiscoveryCategoryStatsQuery.h" #include "analytics/AnalyticsQueryEngine.h" #include "analytics/AnalyticsQueryEngine.h" using namespace fnord; std::atomic<bool> shutdown_sig; fnord::thread::EventLoop ev; void quit(int n) { shutdown_sig = true; fnord::logInfo("cm.chunkserver", "Shutting down..."); // FIXPAUL: wait for http server stop... ev.shutdown(); } int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); /* shutdown hook */ shutdown_sig = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); fnord::cli::FlagParser flags; flags.defineFlag( "http_port", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8000", "Start the public http server on this port", "<port>"); flags.defineFlag( "replica", cli::FlagParser::T_STRING, true, NULL, NULL, "replica id", "<id>"); flags.defineFlag( "artifacts", cli::FlagParser::T_STRING, true, NULL, NULL, "artifacts path", "<path>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); WhitelistVFS vfs; /* start http server */ fnord::thread::ThreadPool tpool; fnord::http::HTTPRouter http_router; fnord::http::HTTPServer http_server(&http_router, &ev); http_server.listen(flags.getInt("http_port")); /* sstable servlet */ sstable::SSTableServlet sstable_servlet("/sstable", &vfs); http_router.addRouteByPrefixMatch("/sstable", &sstable_servlet); /* file servlet */ http::VFSFileServlet file_servlet("/file", &vfs); http_router.addRouteByPrefixMatch("/file", &file_servlet); /* add all files to whitelist vfs */ auto dir = flags.getString("artifacts"); FileUtil::ls(dir, [&vfs, &dir] (const String& file) -> bool { vfs.registerFile(file, FileUtil::joinPaths(dir, file)); fnord::logInfo("cm.chunkserver", "[VFS] Adding file: $0", file); return true; }); /* eventdb */ auto replica = flags.getString("replica"); eventdb::TableRepository table_repo; table_repo.addTable( eventdb::Table::open( "dawanda_joined_sessions", replica, dir, joinedSessionsSchema())); eventdb::TableJanitor table_janitor(&table_repo); table_janitor.start(); eventdb::EventDBServlet eventdb_servlet(&table_repo); /* analytics */ cm::AnalyticsQueryEngine analytics(8, dir); cm::AnalyticsServlet analytics_servlet(&analytics); http_router.addRouteByPrefixMatch("/analytics", &analytics_servlet, &tpool); http_router.addRouteByPrefixMatch("/eventdb", &eventdb_servlet, &tpool); analytics.registerQueryFactory("ctr_by_position", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::CTRByPositionQuery(scan, segments); }); analytics.registerQueryFactory("ctr_by_page", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::CTRByPageQuery(scan, segments); }); analytics.registerQueryFactory("discovery_kpis", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::DiscoveryKPIQuery( scan, segments, query.start_time, query.end_time); }); analytics.registerQueryFactory("discovery_category0_kpis", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::DiscoveryCategoryStatsQuery( scan, segments, "queries.category1", "queries.category1", params); }); analytics.registerQueryFactory("discovery_category1_kpis", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::DiscoveryCategoryStatsQuery( scan, segments, "queries.category1", "queries.category2", params); }); analytics.registerQueryFactory("discovery_category2_kpis", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::DiscoveryCategoryStatsQuery( scan, segments, "queries.category2", "queries.category3", params); }); analytics.registerQueryFactory("discovery_category3_kpis", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::DiscoveryCategoryStatsQuery( scan, segments, "queries.category3", "queries.category3", params); }); analytics.registerQueryFactory("top_search_queries", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::TopSearchQueriesQuery(scan, segments, params); }); ev.run(); table_janitor.stop(); table_janitor.check(); fnord::logInfo("cm.chunkserver", "Exiting..."); return 0; } <commit_msg>Table -> TableWriter<commit_after>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/wallclock.h" #include "fnord-base/VFS.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-http/VFSFileServlet.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-sstable/SSTableServlet.h" #include "fnord-eventdb/EventDBServlet.h" #include "fnord-eventdb/TableRepository.h" #include "fnord-eventdb/TableJanitor.h" #include "fnord-mdb/MDB.h" #include "fnord-mdb/MDBUtil.h" #include "common.h" #include "schemas.h" #include "CustomerNamespace.h" #include "FeatureSchema.h" #include "JoinedQuery.h" #include "analytics/AnalyticsServlet.h" #include "analytics/CTRByPageServlet.h" #include "analytics/CTRStatsServlet.h" #include "analytics/CTRByPositionQuery.h" #include "analytics/CTRByPageQuery.h" #include "analytics/TopSearchQueriesQuery.h" #include "analytics/DiscoveryKPIQuery.h" #include "analytics/DiscoveryCategoryStatsQuery.h" #include "analytics/AnalyticsQueryEngine.h" #include "analytics/AnalyticsQueryEngine.h" using namespace fnord; std::atomic<bool> shutdown_sig; fnord::thread::EventLoop ev; void quit(int n) { shutdown_sig = true; fnord::logInfo("cm.chunkserver", "Shutting down..."); // FIXPAUL: wait for http server stop... ev.shutdown(); } int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); /* shutdown hook */ shutdown_sig = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); fnord::cli::FlagParser flags; flags.defineFlag( "http_port", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8000", "Start the public http server on this port", "<port>"); flags.defineFlag( "readonly", cli::FlagParser::T_SWITCH, false, NULL, NULL, "readonly", "readonly"); flags.defineFlag( "replica", cli::FlagParser::T_STRING, true, NULL, NULL, "replica id", "<id>"); flags.defineFlag( "artifacts", cli::FlagParser::T_STRING, true, NULL, NULL, "artifacts path", "<path>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); WhitelistVFS vfs; /* start http server */ fnord::thread::ThreadPool tpool; fnord::http::HTTPRouter http_router; fnord::http::HTTPServer http_server(&http_router, &ev); http_server.listen(flags.getInt("http_port")); /* sstable servlet */ sstable::SSTableServlet sstable_servlet("/sstable", &vfs); http_router.addRouteByPrefixMatch("/sstable", &sstable_servlet); /* file servlet */ http::VFSFileServlet file_servlet("/file", &vfs); http_router.addRouteByPrefixMatch("/file", &file_servlet); /* add all files to whitelist vfs */ auto dir = flags.getString("artifacts"); FileUtil::ls(dir, [&vfs, &dir] (const String& file) -> bool { vfs.registerFile(file, FileUtil::joinPaths(dir, file)); fnord::logInfo("cm.chunkserver", "[VFS] Adding file: $0", file); return true; }); /* eventdb */ auto readonly = flags.isSet("readonly"); auto replica = flags.getString("replica"); eventdb::TableRepository table_repo; table_repo.addTable( eventdb::TableWriter::open( "dawanda_joined_sessions", replica, dir, joinedSessionsSchema())); eventdb::TableJanitor table_janitor(&table_repo); table_janitor.start(); eventdb::EventDBServlet eventdb_servlet(&table_repo); /* analytics */ cm::AnalyticsQueryEngine analytics(8, dir); cm::AnalyticsServlet analytics_servlet(&analytics); http_router.addRouteByPrefixMatch("/analytics", &analytics_servlet, &tpool); http_router.addRouteByPrefixMatch("/eventdb", &eventdb_servlet, &tpool); analytics.registerQueryFactory("ctr_by_position", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::CTRByPositionQuery(scan, segments); }); analytics.registerQueryFactory("ctr_by_page", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::CTRByPageQuery(scan, segments); }); analytics.registerQueryFactory("discovery_kpis", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::DiscoveryKPIQuery( scan, segments, query.start_time, query.end_time); }); analytics.registerQueryFactory("discovery_category0_kpis", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::DiscoveryCategoryStatsQuery( scan, segments, "queries.category1", "queries.category1", params); }); analytics.registerQueryFactory("discovery_category1_kpis", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::DiscoveryCategoryStatsQuery( scan, segments, "queries.category1", "queries.category2", params); }); analytics.registerQueryFactory("discovery_category2_kpis", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::DiscoveryCategoryStatsQuery( scan, segments, "queries.category2", "queries.category3", params); }); analytics.registerQueryFactory("discovery_category3_kpis", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::DiscoveryCategoryStatsQuery( scan, segments, "queries.category3", "queries.category3", params); }); analytics.registerQueryFactory("top_search_queries", [] ( const cm::AnalyticsQuery& query, const cm::AnalyticsQuery::SubQueryParams params, const Vector<RefPtr<cm::TrafficSegment>>& segments, cm::AnalyticsTableScan* scan) { return new cm::TopSearchQueriesQuery(scan, segments, params); }); ev.run(); table_janitor.stop(); table_janitor.check(); fnord::logInfo("cm.chunkserver", "Exiting..."); return 0; } <|endoftext|>
<commit_before>// Copyright eeGeo Ltd (2012-2014), All Rights Reserved #include "AboutPageModule.h" #include "AboutPageModel.h" #include "AboutPageViewModel.h" #include "EegeoWorld.h" namespace { const std::string AboutPageText = "Powered by eeGeo's 3D Mapping Platform\n\nEEGEO DUNDEE\n\nTechnical Director\nOliver Norton\n\nTechnical Lead\nTim Jenks\n\nSenior Software Engineers\nMalcolm Brown\nJonty Dawson\nSalvador Lopez\nScott Murray\nMark Simpson\n\nJunior Software Engineer\nIan Hutchinson\n\nSenior Artists\nMike McLarty\nGary Thomson\n\nSystem Test Lead\nDavid Murdoch\n\nSenior System Tester\nRyan Reid\n\nSystem Tester\nMichael Celej\n\n\nEEGEO SAN FRANCISCO\n\nBusiness Development Director\nBart Denny\n\n\nEEGEO LONDON\n\nExecutive Chairman\nIan Hetherington\n\nChief Financial Officer\nJeremy Copp\n"; } namespace ExampleApp { namespace AboutPage { AboutPageModule::AboutPageModule(Eegeo::Helpers::IIdentityProvider& identityProvider, Reaction::IReactionControllerModel& reactionControllerModel) { m_pAboutPageModel = Eegeo_NEW(AboutPageModel)(EEGEO_PLATFORM_VERSION_NUMBER, EEGEO_PLATFORM_VERSION_HASH, AboutPageText); m_pAboutPageViewModel = Eegeo_NEW(AboutPageViewModel)(identityProvider.GetNextIdentity(), reactionControllerModel); } AboutPageModule::~AboutPageModule() { Eegeo_DELETE m_pAboutPageViewModel; Eegeo_DELETE m_pAboutPageModel; } IAboutPageModel& AboutPageModule::GetAboutPageModel() const { return *m_pAboutPageModel; } IAboutPageViewModel& AboutPageModule::GetAboutPageViewModel() const { return *m_pAboutPageViewModel; } OpenableControlViewModel::IOpenableControlViewModel& AboutPageModule::GetObservableOpenableControl() const { return m_pAboutPageViewModel->GetOpenableControl(); } } } <commit_msg>Add data attributions to about page, and format the string to be a bit more readable.<commit_after>// Copyright eeGeo Ltd (2012-2014), All Rights Reserved #include "AboutPageModule.h" #include "AboutPageModel.h" #include "AboutPageViewModel.h" #include "EegeoWorld.h" namespace { const std::string AboutPageText = "Powered by eeGeo's 3D Mapping Platform" "\n\nEEGEO DUNDEE" "\n\nTechnical Director" "\nOliver Norton" "\n\nTechnical Lead" "\nTim Jenks" "\n\nSenior Software Engineers" "\nMalcolm Brown" "\nJonty Dawson" "\nSalvador Lopez" "\nScott Murray" "\nMark Simpson" "\n\nJunior Software Engineer" "\nIan Hutchinson" "\n\nSenior Artists" "\nMike McLarty" "\nGary Thomson" "\n\nSystem Test Lead" "\nDavid Murdoch" "\n\nSenior System Tester" "\nRyan Reid" "\n\nSystem Tester" "\nMichael Celej" "\n\n\nEEGEO SAN FRANCISCO" "\n\nBusiness Development Director" "\nBart Denny" "\n\n\nEEGEO LONDON" "\n\nExecutive Chairman" "\nIan Hetherington" "\n\nChief Financial Officer" "\nJeremy Copp\n" "\n\nSource data courtesy of:" "\n\nTomTom Global Content. ©2006-2014 TomTom." "\n\nOrdnance Survey MasterMap & NTF © Crown copyright and database rights 2014 Ordnance Survey 100050219." "\n\nNASA SRTM and Bluemarble - NASA Visible Earth." "\n\nNASA ASTER 30m DTM - ASTER Global DEM data obtained from https://lpdaac.usgs.gov, maintained by the NASA Land Processes Distributed Active Archive Center (LP DAAC) at the USGS/Earth Resources Observation and Science (EROS) Center, Sioux Falls, South Dakota. 2012. ASTER GDEM is a product of METI and NASA." "\n\nU.S. Geological Survey." "\n\nEuropean Environment Agency." "\n\nNaturalVue Copyright MDA Information Systems, Inc." "\n\nGeoNames (www.geonames.org)." "\n\nMade with Natural Earth." "\n\nSeattle Public Utilities (www.seattle.gov/gis)." "\n\nCity of Chicago (www.cityofchicago.org)." "\n\nRLIS Discovery (rlisdiscovery.oregonmetro.gov)." "\n\nGeoBase Canadian Digital Elevation Data - GeoBase®." "\n\nCanVec LCC-2000 - Natural Resources Canada." "\n\nOpen Street Map Buildings & Structures © OpenStreetMap contributors - More information at http://sdk.eegeo.com/osm." ; } namespace ExampleApp { namespace AboutPage { AboutPageModule::AboutPageModule(Eegeo::Helpers::IIdentityProvider& identityProvider, Reaction::IReactionControllerModel& reactionControllerModel) { m_pAboutPageModel = Eegeo_NEW(AboutPageModel)(EEGEO_PLATFORM_VERSION_NUMBER, EEGEO_PLATFORM_VERSION_HASH, AboutPageText); m_pAboutPageViewModel = Eegeo_NEW(AboutPageViewModel)(identityProvider.GetNextIdentity(), reactionControllerModel); } AboutPageModule::~AboutPageModule() { Eegeo_DELETE m_pAboutPageViewModel; Eegeo_DELETE m_pAboutPageModel; } IAboutPageModel& AboutPageModule::GetAboutPageModel() const { return *m_pAboutPageModel; } IAboutPageViewModel& AboutPageModule::GetAboutPageViewModel() const { return *m_pAboutPageViewModel; } OpenableControlViewModel::IOpenableControlViewModel& AboutPageModule::GetObservableOpenableControl() const { return m_pAboutPageViewModel->GetOpenableControl(); } } } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <algorithm> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/cli/flagparser.h" #include "fnord-base/util/SimpleRateLimit.h" #include "fnord-base/InternMap.h" #include "fnord-json/json.h" #include "fnord-mdb/MDB.h" #include "fnord-mdb/MDBUtil.h" #include "fnord-sstable/sstablereader.h" #include "fnord-sstable/sstablewriter.h" #include "fnord-sstable/SSTableColumnSchema.h" #include "fnord-sstable/SSTableColumnReader.h" #include "fnord-sstable/SSTableColumnWriter.h" #include "fnord-cstable/UInt16ColumnReader.h" #include "fnord-cstable/UInt16ColumnWriter.h" #include "fnord-cstable/CSTableWriter.h" #include "fnord-cstable/CSTableReader.h" #include "common.h" #include "CustomerNamespace.h" #include "FeatureSchema.h" #include "JoinedQuery.h" #include "CTRCounter.h" #include "analytics/AnalyticsQuery.h" #include "analytics/CTRByPositionQuery.h" using namespace fnord; int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); fnord::cli::FlagParser flags; flags.defineFlag( "input_file", fnord::cli::FlagParser::T_STRING, true, "i", NULL, "file", "<filename>"); flags.defineFlag( "output_file", fnord::cli::FlagParser::T_STRING, true, "o", NULL, "file", "<filename>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); size_t debug_n = 0; size_t debug_z = 0; /* query level */ cstable::UInt16ColumnWriter jq_page_col(1, 1); /* query item level */ cstable::UInt16ColumnWriter position_col(2, 2); cstable::UInt16ColumnWriter clicked_col(2, 2); uint64_t r = 0; uint64_t n = 0; auto add_session = [&] (const cm::JoinedSession& sess) { ++n; for (const auto& q : sess.queries) { auto pg_str = cm::extractAttr(q.attrs, "pg"); if (pg_str.isEmpty()) { jq_page_col.addNull(r, 1); } else { jq_page_col.addDatum(r, 1, std::stoul(pg_str.get())); } if (q.items.size() == 0) { if (r==0) ++debug_z; position_col.addNull(r, 1); clicked_col.addNull(r, 1); } for (const auto& i : q.items) { ++debug_n; if (r==0) ++debug_z; position_col.addDatum(r, 2, i.position); clicked_col.addDatum(r, 2, i.clicked); r = 2; } r = 1; } r = 0; }; /* read input tables */ int row_idx = 0; const auto& sstable = flags.getString("input_file"); fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable); /* read sstable header */ sstable::SSTableReader reader(File::openFile(sstable, File::O_READ)); if (reader.bodySize() == 0) { fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable); exit(1); } /* get sstable cursor */ auto cursor = reader.getCursor(); auto body_size = reader.bodySize(); /* status line */ util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () { fnord::logInfo( "cm.jqcolumnize", "[$0%] Reading sstable... rows=$1", (size_t) ((cursor->position() / (double) body_size) * 100), row_idx); }); /* read sstable rows */ for (; cursor->valid(); ++row_idx) { status_line.runMaybe(); auto key = cursor->getKeyString(); auto val = cursor->getDataBuffer(); Option<cm::JoinedQuery> q; try { q = Some(json::fromJSON<cm::JoinedQuery>(val)); } catch (const Exception& e) { fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString()); } if (!q.isEmpty()) { cm::JoinedSession s; s.queries.emplace_back(q.get()); add_session(s); } if (!cursor->next()) { break; } } status_line.runForce(); cstable::CSTableWriter writer(flags.getString("output_file"), n); writer.addColumn("queries.items.position", &position_col); writer.addColumn("queries.items.clicked", &clicked_col); writer.commit(); return 0; } <commit_msg>UInt32Column{Writer,Reader}<commit_after>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <algorithm> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/cli/flagparser.h" #include "fnord-base/util/SimpleRateLimit.h" #include "fnord-base/InternMap.h" #include "fnord-json/json.h" #include "fnord-mdb/MDB.h" #include "fnord-mdb/MDBUtil.h" #include "fnord-sstable/sstablereader.h" #include "fnord-sstable/sstablewriter.h" #include "fnord-sstable/SSTableColumnSchema.h" #include "fnord-sstable/SSTableColumnReader.h" #include "fnord-sstable/SSTableColumnWriter.h" #include "fnord-cstable/UInt32ColumnReader.h" #include "fnord-cstable/UInt32ColumnWriter.h" #include "fnord-cstable/CSTableWriter.h" #include "fnord-cstable/CSTableReader.h" #include "common.h" #include "CustomerNamespace.h" #include "FeatureSchema.h" #include "JoinedQuery.h" #include "CTRCounter.h" #include "analytics/AnalyticsQuery.h" #include "analytics/CTRByPositionQuery.h" using namespace fnord; int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); fnord::cli::FlagParser flags; flags.defineFlag( "input_file", fnord::cli::FlagParser::T_STRING, true, "i", NULL, "file", "<filename>"); flags.defineFlag( "output_file", fnord::cli::FlagParser::T_STRING, true, "o", NULL, "file", "<filename>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); size_t debug_n = 0; size_t debug_z = 0; /* query level */ cstable::UInt32ColumnWriter jq_page_col(1, 1); /* query item level */ cstable::UInt32ColumnWriter position_col(2, 2); cstable::UInt32ColumnWriter clicked_col(2, 2); uint64_t r = 0; uint64_t n = 0; auto add_session = [&] (const cm::JoinedSession& sess) { ++n; for (const auto& q : sess.queries) { auto pg_str = cm::extractAttr(q.attrs, "pg"); if (pg_str.isEmpty()) { jq_page_col.addNull(r, 1); } else { jq_page_col.addDatum(r, 1, std::stoul(pg_str.get())); } if (q.items.size() == 0) { if (r==0) ++debug_z; position_col.addNull(r, 1); clicked_col.addNull(r, 1); } for (const auto& i : q.items) { ++debug_n; if (r==0) ++debug_z; position_col.addDatum(r, 2, i.position); clicked_col.addDatum(r, 2, i.clicked); r = 2; } r = 1; } r = 0; }; /* read input tables */ int row_idx = 0; const auto& sstable = flags.getString("input_file"); fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable); /* read sstable header */ sstable::SSTableReader reader(File::openFile(sstable, File::O_READ)); if (reader.bodySize() == 0) { fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable); exit(1); } /* get sstable cursor */ auto cursor = reader.getCursor(); auto body_size = reader.bodySize(); /* status line */ util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () { fnord::logInfo( "cm.jqcolumnize", "[$0%] Reading sstable... rows=$1", (size_t) ((cursor->position() / (double) body_size) * 100), row_idx); }); /* read sstable rows */ for (; cursor->valid(); ++row_idx) { status_line.runMaybe(); auto key = cursor->getKeyString(); auto val = cursor->getDataBuffer(); Option<cm::JoinedQuery> q; try { q = Some(json::fromJSON<cm::JoinedQuery>(val)); } catch (const Exception& e) { fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString()); } if (!q.isEmpty()) { cm::JoinedSession s; s.queries.emplace_back(q.get()); add_session(s); } if (!cursor->next()) { break; } } status_line.runForce(); cstable::CSTableWriter writer(flags.getString("output_file"), n); writer.addColumn("queries.items.position", &position_col); writer.addColumn("queries.items.clicked", &clicked_col); writer.commit(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2008-2013 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <thrust/system/cuda/detail/bulk/detail/config.hpp> #include <thrust/system/cuda/detail/bulk/detail/pointer_traits.hpp> #include <thrust/system/cuda/detail/bulk/detail/alignment.hpp> #include <thrust/system/cuda/detail/bulk/uninitialized.hpp> #include <thrust/detail/config.h> #include <cstdlib> BULK_NAMESPACE_PREFIX namespace bulk { inline __device__ bool is_on_chip(void *ptr) { return bulk::detail::is_shared(ptr); } // end is_on_chip() template<typename T> inline __device__ T *on_chip_cast(T *ptr) { extern __shared__ char s_begin[]; void *result = (reinterpret_cast<char*>(ptr) - s_begin) + s_begin; return reinterpret_cast<T*>(result); } // end on_chip_cast() namespace detail { extern __shared__ int s_data_segment_begin[]; class os { public: __device__ __host__ inline os(size_t max_data_segment_size) : m_program_break(s_data_segment_begin), m_max_data_segment_size(max_data_segment_size) { } __device__ inline int brk(void *end_data_segment) { if(end_data_segment <= m_program_break) { m_program_break = end_data_segment; return 0; } return -1; } __device__ inline void *sbrk(size_t increment) { if(data_segment_size() + increment <= m_max_data_segment_size) { m_program_break = reinterpret_cast<char*>(m_program_break) + increment; } // end if else { return reinterpret_cast<void*>(-1); } // end else return m_program_break; } __device__ inline void *program_break() const { return m_program_break; } __device__ inline void *data_segment_begin() const { return s_data_segment_begin; } private: __device__ inline size_t data_segment_size() { return reinterpret_cast<char*>(m_program_break) - reinterpret_cast<char*>(s_data_segment_begin); } // end data_segment_size() void *m_program_break; // XXX this can safely be uint32 size_t m_max_data_segment_size; }; // only one instance of this class can logically exist per CTA, and its use is thread-unsafe class singleton_unsafe_on_chip_allocator { public: __device__ __host__ inline singleton_unsafe_on_chip_allocator(size_t max_data_segment_size) : m_os(max_data_segment_size) {} __device__ inline void *allocate(size_t size) { size_t aligned_size = align8(size); block *prev = find_first_free_insertion_point(heap_begin(), heap_end(), aligned_size); block *b; if(prev != heap_end() && (b = prev->next()) != heap_end()) { // can we split? if((b->size() - aligned_size) >= sizeof(block)) { split_block(b, aligned_size); } // end if b->set_is_free(false); } // end if else { // nothing fits, extend the heap b = extend_heap(prev, aligned_size); if(b == heap_end()) { return 0; } // end if } // end else return b->data(); } // end allocate() __device__ inline void deallocate(void *ptr) { if(ptr != 0) { block *b = get_block(ptr); // free the block b->set_is_free(true); // try to fuse the freed block the previous block if(b->prev() && b->prev()->is_free()) { b = b->prev(); fuse_block(b); } // end if // now try to fuse with the next block if(b->next() != heap_end()) { fuse_block(b); } // end if else { // the the OS know where the new break is m_os.brk(b); } // end else } // end if } // end deallocate() private: // align to two words class block : public bulk::detail::aligned_type<sizeof(size_t) + sizeof(block*)>::type { public: __device__ inline size_t size() const { return m_size; } // end size() __device__ void set_size(size_t sz) { m_size = sz; } // end set_size() __device__ inline block *prev() const { return m_prev; } // end prev() __device__ void set_prev(block *p) { m_prev = p; } // end set_prev() // returns a pointer to the indexth byte within this block's data __device__ inline void *byte_at(size_t index) const { return reinterpret_cast<char*>(data()) + index; } // end byte_at() __device__ inline block *next() const { return reinterpret_cast<block*>(byte_at(size())); } // end next() __device__ inline bool is_free() const { return m_is_free; } // end is_free() __device__ inline void set_is_free(bool f) { m_is_free = f; } // end set_is_free() __device__ inline void *data() const { return reinterpret_cast<char*>(const_cast<block*>(this)) + sizeof(block); } // end data() private: // this packing ensures that sizeof(block) is compatible with 64b alignment, because: // on a 32b platform, sizeof(block) == 64b // on a 64b platform, sizeof(block) == 128b bool m_is_free : 1; size_t m_size : 8 * sizeof(size_t) - 1; block *m_prev; }; os m_os; __device__ inline block *heap_begin() const { return reinterpret_cast<block*>(m_os.data_segment_begin()); } // end heap_begin() __device__ inline block *heap_end() const { return reinterpret_cast<block*>(m_os.program_break()); } // end heap_end(); __device__ inline void split_block(block *b, size_t size) { block *new_block; // emplace a new block within the old one's data segment new_block = reinterpret_cast<block*>(b->byte_at(size)); // the new block's size is the old block's size less the size of the split less the size of a block new_block->set_size(b->size() - size - sizeof(block)); new_block->set_prev(b); new_block->set_is_free(true); // the old block's size is the size of the split b->set_size(size); // link the old block to the new one if(new_block->next() != heap_end()) { new_block->next()->set_prev(new_block); } // end if } // end split_block() __device__ inline bool fuse_block(block *b) { if(b->next() != heap_end() && b->next()->is_free()) { // increment b's size by sizeof(block) plus the next's block's data size b->set_size(sizeof(block) + b->next()->size() + b->size()); if(b->next() != heap_end()) { b->next()->set_prev(b); } return true; } return false; } // end fuse_block() __device__ inline static block *get_block(void *data) { // the block metadata lives sizeof(block) bytes to the left of data void *ptr = reinterpret_cast<char*>(data) - sizeof(block); return reinterpret_cast<block *>(ptr); } // end get_block() __device__ inline static block *find_first_free_insertion_point(block *first, block *last, size_t size) { block *prev = last; while(first != last && !(first->is_free() && first->size() >= size)) { prev = first; first = first->next(); } return prev; } // end find_first_free_insertion_point() __device__ inline block *extend_heap(block *prev, size_t size) { // the new block goes at the current end of the heap block *new_block = heap_end(); // move the break to the right to accomodate both a block and the requested allocation if(m_os.sbrk(sizeof(block) + size) == reinterpret_cast<void*>(-1)) { // allocation failed return new_block; } on_chip_cast(new_block)->set_size(size); on_chip_cast(new_block)->set_prev(prev); on_chip_cast(new_block)->set_is_free(false); return new_block; } // end extend_heap() __device__ inline static size_t align8(size_t size) { return ((((size - 1) >> 3) << 3) + 8); } // end align4() }; // end singleton_unsafe_on_chip_allocator class singleton_on_chip_allocator { public: // XXX mark as __host__ to WAR a warning from uninitialized.construct inline __device__ __host__ singleton_on_chip_allocator(size_t max_data_segment_size) : m_mutex(), m_alloc(max_data_segment_size) {} inline __device__ void *unsafe_allocate(size_t size) { return m_alloc.allocate(size); } inline __device__ void *allocate(size_t size) { void *result; m_mutex.lock(); { result = unsafe_allocate(size); } // end critical section m_mutex.unlock(); return result; } // end allocate() inline __device__ void unsafe_deallocate(void *ptr) { m_alloc.deallocate(ptr); } // end unsafe_deallocate() inline __device__ void deallocate(void *ptr) { m_mutex.lock(); { unsafe_deallocate(ptr); } // end critical section m_mutex.unlock(); } // end deallocate() private: class mutex { public: inline __device__ __host__ mutex() : m_in_use(0) {} inline __device__ bool try_lock() { #if __CUDA_ARCH__ >= 110 return atomicCAS(&m_in_use, 0, 1) != 0; #else return false; #endif } // end try_lock() inline __device__ void lock() { // spin while waiting while(try_lock()) { ; } } // end lock() inline __device__ void unlock() { m_in_use = 0; } // end unlock() private: unsigned int m_in_use; }; // end mutex mutex m_mutex; singleton_unsafe_on_chip_allocator m_alloc; }; // end singleton_on_chip_allocator // put the object in an anonymous namespace so that non-CUDA compilers don't complain about multiple definitions namespace { __shared__ uninitialized<singleton_on_chip_allocator> s_on_chip_allocator; } // end anon namespace inline __device__ void init_on_chip_malloc(size_t max_data_segment_size) { s_on_chip_allocator.construct(max_data_segment_size); } // end init_on_chip_malloc() inline __device__ void *on_chip_malloc(size_t size) { void *result = s_on_chip_allocator.get().allocate(size); return on_chip_cast(result); } // end on_chip_malloc() inline __device__ void on_chip_free(void *ptr) { s_on_chip_allocator.get().deallocate(ptr); } // end on_chip_free() inline __device__ void *unsafe_on_chip_malloc(size_t size) { void *result = s_on_chip_allocator.get().unsafe_allocate(size); return on_chip_cast(result); } // end unsafe_on_chip_malloc() inline __device__ void unsafe_on_chip_free(void *ptr) { s_on_chip_allocator.get().unsafe_deallocate(ptr); } // end unsafe_on_chip_free() } // end detail inline __device__ void *shmalloc(size_t num_bytes) { // first try on_chip_malloc void *result = detail::on_chip_malloc(num_bytes); #if __CUDA_ARCH__ >= 200 if(!result) { result = std::malloc(num_bytes); } // end if #endif // __CUDA_ARCH__ return result; } // end shmalloc() inline __device__ void *unsafe_shmalloc(size_t num_bytes) { // first try on_chip_malloc void *result = detail::unsafe_on_chip_malloc(num_bytes); #if __CUDA_ARCH__ >= 200 if(!result) { result = std::malloc(num_bytes); } // end if #endif // __CUDA_ARCH__ return result; } // end unsafe_shmalloc() inline __device__ void shfree(void *ptr) { #if __CUDA_ARCH__ >= 200 if(bulk::is_on_chip(ptr)) { bulk::detail::on_chip_free(bulk::on_chip_cast(ptr)); } // end if else { std::free(ptr); } // end else #else bulk::detail::on_chip_free(bulk::on_chip_cast(ptr)); #endif } // end shfree() inline __device__ void unsafe_shfree(void *ptr) { #if __CUDA_ARCH__ >= 200 if(bulk::is_on_chip(ptr)) { bulk::detail::unsafe_on_chip_free(bulk::on_chip_cast(ptr)); } // end if else { std::free(ptr); } // end else #else bulk::detail::unsafe_on_chip_free(bulk::on_chip_cast(ptr)); #endif } // end unsafe_shfree() template<typename ConcurrentGroup> __device__ inline void *malloc(ConcurrentGroup &g, size_t num_bytes) { __shared__ void *s_result; // we need to guard access to s_result from other // invocations of malloc, so we put a wait at the beginning g.wait(); if(g.this_exec.index() == 0) { s_result = bulk::unsafe_shmalloc(num_bytes); } // end if g.wait(); return s_result; } // end malloc() template<typename ConcurrentGroup> __device__ inline void free(ConcurrentGroup &g, void *ptr) { if(g.this_exec.index() == 0) { bulk::unsafe_shfree(ptr); } // end if g.wait(); } // end free() } // end namespace bulk BULK_NAMESPACE_SUFFIX <commit_msg>Eliminate __host__ annotations from functions inside shmalloc implementation<commit_after>/* * Copyright 2008-2013 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <thrust/system/cuda/detail/bulk/detail/config.hpp> #include <thrust/system/cuda/detail/bulk/detail/pointer_traits.hpp> #include <thrust/system/cuda/detail/bulk/detail/alignment.hpp> #include <thrust/system/cuda/detail/bulk/uninitialized.hpp> #include <thrust/detail/config.h> #include <cstdlib> BULK_NAMESPACE_PREFIX namespace bulk { inline __device__ bool is_on_chip(void *ptr) { return bulk::detail::is_shared(ptr); } // end is_on_chip() template<typename T> inline __device__ T *on_chip_cast(T *ptr) { extern __shared__ char s_begin[]; void *result = (reinterpret_cast<char*>(ptr) - s_begin) + s_begin; return reinterpret_cast<T*>(result); } // end on_chip_cast() namespace detail { extern __shared__ int s_data_segment_begin[]; class os { public: __device__ inline os(size_t max_data_segment_size) : m_program_break(s_data_segment_begin), m_max_data_segment_size(max_data_segment_size) { } __device__ inline int brk(void *end_data_segment) { if(end_data_segment <= m_program_break) { m_program_break = end_data_segment; return 0; } return -1; } __device__ inline void *sbrk(size_t increment) { if(data_segment_size() + increment <= m_max_data_segment_size) { m_program_break = reinterpret_cast<char*>(m_program_break) + increment; } // end if else { return reinterpret_cast<void*>(-1); } // end else return m_program_break; } __device__ inline void *program_break() const { return m_program_break; } __device__ inline void *data_segment_begin() const { return s_data_segment_begin; } private: __device__ inline size_t data_segment_size() { return reinterpret_cast<char*>(m_program_break) - reinterpret_cast<char*>(s_data_segment_begin); } // end data_segment_size() void *m_program_break; // XXX this can safely be uint32 size_t m_max_data_segment_size; }; // only one instance of this class can logically exist per CTA, and its use is thread-unsafe class singleton_unsafe_on_chip_allocator { public: __device__ inline singleton_unsafe_on_chip_allocator(size_t max_data_segment_size) : m_os(max_data_segment_size) {} __device__ inline void *allocate(size_t size) { size_t aligned_size = align8(size); block *prev = find_first_free_insertion_point(heap_begin(), heap_end(), aligned_size); block *b; if(prev != heap_end() && (b = prev->next()) != heap_end()) { // can we split? if((b->size() - aligned_size) >= sizeof(block)) { split_block(b, aligned_size); } // end if b->set_is_free(false); } // end if else { // nothing fits, extend the heap b = extend_heap(prev, aligned_size); if(b == heap_end()) { return 0; } // end if } // end else return b->data(); } // end allocate() __device__ inline void deallocate(void *ptr) { if(ptr != 0) { block *b = get_block(ptr); // free the block b->set_is_free(true); // try to fuse the freed block the previous block if(b->prev() && b->prev()->is_free()) { b = b->prev(); fuse_block(b); } // end if // now try to fuse with the next block if(b->next() != heap_end()) { fuse_block(b); } // end if else { // the the OS know where the new break is m_os.brk(b); } // end else } // end if } // end deallocate() private: // align to two words class block : public bulk::detail::aligned_type<sizeof(size_t) + sizeof(block*)>::type { public: __device__ inline size_t size() const { return m_size; } // end size() __device__ void set_size(size_t sz) { m_size = sz; } // end set_size() __device__ inline block *prev() const { return m_prev; } // end prev() __device__ void set_prev(block *p) { m_prev = p; } // end set_prev() // returns a pointer to the indexth byte within this block's data __device__ inline void *byte_at(size_t index) const { return reinterpret_cast<char*>(data()) + index; } // end byte_at() __device__ inline block *next() const { return reinterpret_cast<block*>(byte_at(size())); } // end next() __device__ inline bool is_free() const { return m_is_free; } // end is_free() __device__ inline void set_is_free(bool f) { m_is_free = f; } // end set_is_free() __device__ inline void *data() const { return reinterpret_cast<char*>(const_cast<block*>(this)) + sizeof(block); } // end data() private: // this packing ensures that sizeof(block) is compatible with 64b alignment, because: // on a 32b platform, sizeof(block) == 64b // on a 64b platform, sizeof(block) == 128b bool m_is_free : 1; size_t m_size : 8 * sizeof(size_t) - 1; block *m_prev; }; os m_os; __device__ inline block *heap_begin() const { return reinterpret_cast<block*>(m_os.data_segment_begin()); } // end heap_begin() __device__ inline block *heap_end() const { return reinterpret_cast<block*>(m_os.program_break()); } // end heap_end(); __device__ inline void split_block(block *b, size_t size) { block *new_block; // emplace a new block within the old one's data segment new_block = reinterpret_cast<block*>(b->byte_at(size)); // the new block's size is the old block's size less the size of the split less the size of a block new_block->set_size(b->size() - size - sizeof(block)); new_block->set_prev(b); new_block->set_is_free(true); // the old block's size is the size of the split b->set_size(size); // link the old block to the new one if(new_block->next() != heap_end()) { new_block->next()->set_prev(new_block); } // end if } // end split_block() __device__ inline bool fuse_block(block *b) { if(b->next() != heap_end() && b->next()->is_free()) { // increment b's size by sizeof(block) plus the next's block's data size b->set_size(sizeof(block) + b->next()->size() + b->size()); if(b->next() != heap_end()) { b->next()->set_prev(b); } return true; } return false; } // end fuse_block() __device__ inline static block *get_block(void *data) { // the block metadata lives sizeof(block) bytes to the left of data void *ptr = reinterpret_cast<char*>(data) - sizeof(block); return reinterpret_cast<block *>(ptr); } // end get_block() __device__ inline static block *find_first_free_insertion_point(block *first, block *last, size_t size) { block *prev = last; while(first != last && !(first->is_free() && first->size() >= size)) { prev = first; first = first->next(); } return prev; } // end find_first_free_insertion_point() __device__ inline block *extend_heap(block *prev, size_t size) { // the new block goes at the current end of the heap block *new_block = heap_end(); // move the break to the right to accomodate both a block and the requested allocation if(m_os.sbrk(sizeof(block) + size) == reinterpret_cast<void*>(-1)) { // allocation failed return new_block; } on_chip_cast(new_block)->set_size(size); on_chip_cast(new_block)->set_prev(prev); on_chip_cast(new_block)->set_is_free(false); return new_block; } // end extend_heap() __device__ inline static size_t align8(size_t size) { return ((((size - 1) >> 3) << 3) + 8); } // end align4() }; // end singleton_unsafe_on_chip_allocator class singleton_on_chip_allocator { public: inline __device__ singleton_on_chip_allocator(size_t max_data_segment_size) : m_mutex(), m_alloc(max_data_segment_size) {} inline __device__ void *unsafe_allocate(size_t size) { return m_alloc.allocate(size); } inline __device__ void *allocate(size_t size) { void *result; m_mutex.lock(); { result = unsafe_allocate(size); } // end critical section m_mutex.unlock(); return result; } // end allocate() inline __device__ void unsafe_deallocate(void *ptr) { m_alloc.deallocate(ptr); } // end unsafe_deallocate() inline __device__ void deallocate(void *ptr) { m_mutex.lock(); { unsafe_deallocate(ptr); } // end critical section m_mutex.unlock(); } // end deallocate() private: class mutex { public: inline __device__ mutex() : m_in_use(0) {} inline __device__ bool try_lock() { #if __CUDA_ARCH__ >= 110 return atomicCAS(&m_in_use, 0, 1) != 0; #else return false; #endif } // end try_lock() inline __device__ void lock() { // spin while waiting while(try_lock()) { ; } } // end lock() inline __device__ void unlock() { m_in_use = 0; } // end unlock() private: unsigned int m_in_use; }; // end mutex mutex m_mutex; singleton_unsafe_on_chip_allocator m_alloc; }; // end singleton_on_chip_allocator // put the object in an anonymous namespace so that non-CUDA compilers don't complain about multiple definitions namespace { __shared__ uninitialized<singleton_on_chip_allocator> s_on_chip_allocator; } // end anon namespace inline __device__ void init_on_chip_malloc(size_t max_data_segment_size) { s_on_chip_allocator.construct(max_data_segment_size); } // end init_on_chip_malloc() inline __device__ void *on_chip_malloc(size_t size) { void *result = s_on_chip_allocator.get().allocate(size); return on_chip_cast(result); } // end on_chip_malloc() inline __device__ void on_chip_free(void *ptr) { s_on_chip_allocator.get().deallocate(ptr); } // end on_chip_free() inline __device__ void *unsafe_on_chip_malloc(size_t size) { void *result = s_on_chip_allocator.get().unsafe_allocate(size); return on_chip_cast(result); } // end unsafe_on_chip_malloc() inline __device__ void unsafe_on_chip_free(void *ptr) { s_on_chip_allocator.get().unsafe_deallocate(ptr); } // end unsafe_on_chip_free() } // end detail inline __device__ void *shmalloc(size_t num_bytes) { // first try on_chip_malloc void *result = detail::on_chip_malloc(num_bytes); #if __CUDA_ARCH__ >= 200 if(!result) { result = std::malloc(num_bytes); } // end if #endif // __CUDA_ARCH__ return result; } // end shmalloc() inline __device__ void *unsafe_shmalloc(size_t num_bytes) { // first try on_chip_malloc void *result = detail::unsafe_on_chip_malloc(num_bytes); #if __CUDA_ARCH__ >= 200 if(!result) { result = std::malloc(num_bytes); } // end if #endif // __CUDA_ARCH__ return result; } // end unsafe_shmalloc() inline __device__ void shfree(void *ptr) { #if __CUDA_ARCH__ >= 200 if(bulk::is_on_chip(ptr)) { bulk::detail::on_chip_free(bulk::on_chip_cast(ptr)); } // end if else { std::free(ptr); } // end else #else bulk::detail::on_chip_free(bulk::on_chip_cast(ptr)); #endif } // end shfree() inline __device__ void unsafe_shfree(void *ptr) { #if __CUDA_ARCH__ >= 200 if(bulk::is_on_chip(ptr)) { bulk::detail::unsafe_on_chip_free(bulk::on_chip_cast(ptr)); } // end if else { std::free(ptr); } // end else #else bulk::detail::unsafe_on_chip_free(bulk::on_chip_cast(ptr)); #endif } // end unsafe_shfree() template<typename ConcurrentGroup> __device__ inline void *malloc(ConcurrentGroup &g, size_t num_bytes) { __shared__ void *s_result; // we need to guard access to s_result from other // invocations of malloc, so we put a wait at the beginning g.wait(); if(g.this_exec.index() == 0) { s_result = bulk::unsafe_shmalloc(num_bytes); } // end if g.wait(); return s_result; } // end malloc() template<typename ConcurrentGroup> __device__ inline void free(ConcurrentGroup &g, void *ptr) { if(g.this_exec.index() == 0) { bulk::unsafe_shfree(ptr); } // end if g.wait(); } // end free() } // end namespace bulk BULK_NAMESPACE_SUFFIX <|endoftext|>
<commit_before>/********************************************************************* * * Copyright (C) 2007, Simon Kagstrom * * Filename: emit.hh * Author: Simon Kagstrom <[email protected]> * Description: Emitter * * $Id:$ * ********************************************************************/ #ifndef __EMIT_HH__ #define __EMIT_HH__ #include <stdint.h> #include <registerallocator.hh> class Emit { public: Emit(); void bc_comment(const char *what) { this->output("; "); this->write((char*)what); } void bc_generic(const char *what, ...); void bc_generic_insn(const char *what) { this->writeIndent(what); } void bc_label(const char *what, ...); void bc_goto(uint32_t dst) { this->writeIndent("goto L_%x", dst); } void bc_goto(const char *where) { this->writeIndent("goto %s", where); } void bc_condbranch(const char *what, ...); void bc_pushconst(int32_t nr); void bc_pushconst_u(uint32_t nr); void bc_pushregister(MIPS_register_t reg); void bc_popregister(MIPS_register_t reg); void bc_pushindex(MIPS_register_t reg, int32_t extra); void bc_pushaddress(MIPS_register_t reg, int32_t extra); void bc_getstatic(const char *what) { this->writeIndent("getstatic %s", what); } void bc_putstatic(const char *what) { this->writeIndent("putstatic %s", what); } void bc_iload(int n); void bc_istore(int n); void bc_ldc(char *str) { this->writeIndent("ldc \"%s\"", str); } void bc_iadd() { this->writeIndent("iadd"); } void bc_iinc(MIPS_register_t reg, int extra); void bc_isub() { this->writeIndent("isub"); } void bc_invokestatic(const char *what, ...); void bc_lookupswitch(int n, uint32_t *table, const char *def); void bc_iushr() { this->writeIndent("iushr"); } void bc_lushr() { this->writeIndent("lushr"); } void bc_imul() { this->writeIndent("imul"); } void bc_idiv() { this->writeIndent("idiv"); } void bc_irem() { this->writeIndent("irem"); } void bc_ineg() { this->writeIndent("ineg"); } void bc_ior() { this->writeIndent("ior"); } void bc_ixor() { this->writeIndent("ixor"); } void bc_lmul() { this->writeIndent("lmul"); } void bc_dup() { this->writeIndent("dup"); } void bc_dup2() { this->writeIndent("dup2"); } void bc_pop() { this->writeIndent("pop"); } void bc_pop2() { this->writeIndent("pop2"); } void bc_i2l() { this->writeIndent("i2l"); } void bc_l2i() { this->writeIndent("l2i"); } void bc_swap() { this->writeIndent("swap"); } void bc_iaload() { this->writeIndent("iaload"); } void bc_iastore() { this->writeIndent("iastore"); } void bc_ireturn() { this->writeIndent("ireturn"); } void bc_return() { this->writeIndent("return"); } void error(const char *dst, ...); void warning(const char *dst, ...); void setOutputFile(const char *filename); private: void bc_load_store_helper(const char *type, int nr); void write(const char *dst, ...); void writeIndent(const char *dst, ...); void output(char *what); FILE *fp; }; extern Emit *emit; #endif /* !__EMIT_HH__ */ <commit_msg>Pass FILE<commit_after>/********************************************************************* * * Copyright (C) 2007, Simon Kagstrom * * Filename: emit.hh * Author: Simon Kagstrom <[email protected]> * Description: Emitter * * $Id:$ * ********************************************************************/ #ifndef __EMIT_HH__ #define __EMIT_HH__ #include <stdint.h> #include <registerallocator.hh> class Emit { public: Emit(); void bc_comment(const char *what) { this->output("; "); this->write((char*)what); } void bc_generic(const char *what, ...); void bc_generic_insn(const char *what) { this->writeIndent(what); } void bc_label(const char *what, ...); void bc_goto(uint32_t dst) { this->writeIndent("goto L_%x", dst); } void bc_goto(const char *where) { this->writeIndent("goto %s", where); } void bc_condbranch(const char *what, ...); void bc_pushconst(int32_t nr); void bc_pushconst_u(uint32_t nr); void bc_pushregister(MIPS_register_t reg); void bc_popregister(MIPS_register_t reg); void bc_pushindex(MIPS_register_t reg, int32_t extra); void bc_pushaddress(MIPS_register_t reg, int32_t extra); void bc_getstatic(const char *what) { this->writeIndent("getstatic %s", what); } void bc_putstatic(const char *what) { this->writeIndent("putstatic %s", what); } void bc_iload(int n); void bc_istore(int n); void bc_ldc(char *str) { this->writeIndent("ldc \"%s\"", str); } void bc_iadd() { this->writeIndent("iadd"); } void bc_iinc(MIPS_register_t reg, int extra); void bc_isub() { this->writeIndent("isub"); } void bc_invokestatic(const char *what, ...); void bc_lookupswitch(int n, uint32_t *table, const char *def); void bc_iushr() { this->writeIndent("iushr"); } void bc_lushr() { this->writeIndent("lushr"); } void bc_imul() { this->writeIndent("imul"); } void bc_idiv() { this->writeIndent("idiv"); } void bc_irem() { this->writeIndent("irem"); } void bc_ineg() { this->writeIndent("ineg"); } void bc_ior() { this->writeIndent("ior"); } void bc_ixor() { this->writeIndent("ixor"); } void bc_lmul() { this->writeIndent("lmul"); } void bc_dup() { this->writeIndent("dup"); } void bc_dup2() { this->writeIndent("dup2"); } void bc_pop() { this->writeIndent("pop"); } void bc_pop2() { this->writeIndent("pop2"); } void bc_i2l() { this->writeIndent("i2l"); } void bc_l2i() { this->writeIndent("l2i"); } void bc_swap() { this->writeIndent("swap"); } void bc_iaload() { this->writeIndent("iaload"); } void bc_iastore() { this->writeIndent("iastore"); } void bc_ireturn() { this->writeIndent("ireturn"); } void bc_return() { this->writeIndent("return"); } void error(const char *dst, ...); void warning(const char *dst, ...); void setOutputFile(FILE *fp); private: void bc_load_store_helper(const char *type, int nr); void write(const char *dst, ...); void writeIndent(const char *dst, ...); void output(char *what); FILE *fp; }; extern Emit *emit; #endif /* !__EMIT_HH__ */ <|endoftext|>
<commit_before>/* * Copyright © 2011 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /** * @file brw_vec4_copy_propagation.cpp * * Implements tracking of values copied between registers, and * optimizations based on that: copy propagation and constant * propagation. */ #include "brw_vec4.h" extern "C" { #include "main/macros.h" } namespace brw { static bool is_direct_copy(vec4_instruction *inst) { return (inst->opcode == BRW_OPCODE_MOV && !inst->predicate && inst->dst.file == GRF && !inst->saturate && !inst->dst.reladdr && !inst->src[0].reladdr && inst->dst.type == inst->src[0].type); } static bool is_dominated_by_previous_instruction(vec4_instruction *inst) { return (inst->opcode != BRW_OPCODE_DO && inst->opcode != BRW_OPCODE_WHILE && inst->opcode != BRW_OPCODE_ELSE && inst->opcode != BRW_OPCODE_ENDIF); } static bool try_constant_propagation(vec4_instruction *inst, int arg, src_reg *values[4]) { /* For constant propagation, we only handle the same constant * across all 4 channels. Some day, we should handle the 8-bit * float vector format, which would let us constant propagate * vectors better. */ src_reg value = *values[0]; for (int i = 1; i < 4; i++) { if (!value.equals(values[i])) return false; } if (value.file != IMM) return false; if (inst->src[arg].abs) { if (value.type == BRW_REGISTER_TYPE_F) { value.imm.f = fabs(value.imm.f); } else if (value.type == BRW_REGISTER_TYPE_D) { if (value.imm.i < 0) value.imm.i = -value.imm.i; } } if (inst->src[arg].negate) { if (value.type == BRW_REGISTER_TYPE_F) value.imm.f = -value.imm.f; else value.imm.u = -value.imm.u; } switch (inst->opcode) { case BRW_OPCODE_MOV: inst->src[arg] = value; return true; case BRW_OPCODE_DP2: case BRW_OPCODE_DP3: case BRW_OPCODE_DP4: case BRW_OPCODE_DPH: case BRW_OPCODE_BFI1: case BRW_OPCODE_ASR: case BRW_OPCODE_SHL: case BRW_OPCODE_SHR: case BRW_OPCODE_SUBB: if (arg == 1) { inst->src[arg] = value; return true; } break; case BRW_OPCODE_MACH: case BRW_OPCODE_MUL: case BRW_OPCODE_ADD: case BRW_OPCODE_OR: case BRW_OPCODE_AND: case BRW_OPCODE_XOR: case BRW_OPCODE_ADDC: if (arg == 1) { inst->src[arg] = value; return true; } else if (arg == 0 && inst->src[1].file != IMM) { /* Fit this constant in by commuting the operands. Exception: we * can't do this for 32-bit integer MUL/MACH because it's asymmetric. */ if ((inst->opcode == BRW_OPCODE_MUL || inst->opcode == BRW_OPCODE_MACH) && (inst->src[1].type == BRW_REGISTER_TYPE_D || inst->src[1].type == BRW_REGISTER_TYPE_UD)) break; inst->src[0] = inst->src[1]; inst->src[1] = value; return true; } break; case BRW_OPCODE_CMP: if (arg == 1) { inst->src[arg] = value; return true; } else if (arg == 0 && inst->src[1].file != IMM) { uint32_t new_cmod; new_cmod = brw_swap_cmod(inst->conditional_mod); if (new_cmod != ~0u) { /* Fit this constant in by swapping the operands and * flipping the test. */ inst->src[0] = inst->src[1]; inst->src[1] = value; inst->conditional_mod = new_cmod; return true; } } break; case BRW_OPCODE_SEL: if (arg == 1) { inst->src[arg] = value; return true; } else if (arg == 0 && inst->src[1].file != IMM) { inst->src[0] = inst->src[1]; inst->src[1] = value; /* If this was predicated, flipping operands means * we also need to flip the predicate. */ if (inst->conditional_mod == BRW_CONDITIONAL_NONE) { inst->predicate_inverse = !inst->predicate_inverse; } return true; } break; default: break; } return false; } bool vec4_visitor::try_copy_propagation(vec4_instruction *inst, int arg, src_reg *values[4]) { /* For constant propagation, we only handle the same constant * across all 4 channels. Some day, we should handle the 8-bit * float vector format, which would let us constant propagate * vectors better. */ src_reg value = *values[0]; for (int i = 1; i < 4; i++) { /* This is equals() except we don't care about the swizzle. */ if (value.file != values[i]->file || value.reg != values[i]->reg || value.reg_offset != values[i]->reg_offset || value.type != values[i]->type || value.negate != values[i]->negate || value.abs != values[i]->abs) { return false; } } /* Compute the swizzle of the original register by swizzling the * component loaded from each value according to the swizzle of * operand we're going to change. */ int s[4]; for (int i = 0; i < 4; i++) { s[i] = BRW_GET_SWZ(values[i]->swizzle, BRW_GET_SWZ(inst->src[arg].swizzle, i)); } value.swizzle = BRW_SWIZZLE4(s[0], s[1], s[2], s[3]); if (value.file != UNIFORM && value.file != GRF && value.file != ATTR) return false; if (inst->src[arg].abs) { value.negate = false; value.abs = true; } if (inst->src[arg].negate) value.negate = !value.negate; bool has_source_modifiers = value.negate || value.abs; /* gen6 math and gen7+ SENDs from GRFs ignore source modifiers on * instructions. */ if ((has_source_modifiers || value.file == UNIFORM || value.swizzle != BRW_SWIZZLE_XYZW) && !can_do_source_mods(inst)) return false; if (has_source_modifiers && value.type != inst->src[arg].type) return false; bool is_3src_inst = (inst->opcode == BRW_OPCODE_LRP || inst->opcode == BRW_OPCODE_MAD || inst->opcode == BRW_OPCODE_BFE || inst->opcode == BRW_OPCODE_BFI2); if (is_3src_inst && value.file == UNIFORM) return false; if (inst->is_send_from_grf()) return false; /* We can't copy-propagate a UD negation into a condmod * instruction, because the condmod ends up looking at the 33-bit * signed accumulator value instead of the 32-bit value we wanted */ if (inst->conditional_mod && value.negate && value.type == BRW_REGISTER_TYPE_UD) return false; /* Don't report progress if this is a noop. */ if (value.equals(&inst->src[arg])) return false; value.type = inst->src[arg].type; inst->src[arg] = value; return true; } bool vec4_visitor::opt_copy_propagation() { bool progress = false; src_reg *cur_value[virtual_grf_reg_count][4]; memset(&cur_value, 0, sizeof(cur_value)); foreach_list(node, &this->instructions) { vec4_instruction *inst = (vec4_instruction *)node; /* This pass only works on basic blocks. If there's flow * control, throw out all our information and start from * scratch. * * This should really be fixed by using a structure like in * src/glsl/opt_copy_propagation.cpp to track available copies. */ if (!is_dominated_by_previous_instruction(inst)) { memset(cur_value, 0, sizeof(cur_value)); continue; } /* For each source arg, see if each component comes from a copy * from the same type file (IMM, GRF, UNIFORM), and try * optimizing out access to the copy result */ for (int i = 2; i >= 0; i--) { /* Copied values end up in GRFs, and we don't track reladdr * accesses. */ if (inst->src[i].file != GRF || inst->src[i].reladdr) continue; int reg = (virtual_grf_reg_map[inst->src[i].reg] + inst->src[i].reg_offset); /* Find the regs that each swizzle component came from. */ src_reg *values[4]; int c; for (c = 0; c < 4; c++) { values[c] = cur_value[reg][BRW_GET_SWZ(inst->src[i].swizzle, c)]; /* If there's no available copy for this channel, bail. * We could be more aggressive here -- some channels might * not get used based on the destination writemask. */ if (!values[c]) break; /* We'll only be able to copy propagate if the sources are * all from the same file -- there's no ability to swizzle * 0 or 1 constants in with source registers like in i915. */ if (c > 0 && values[c - 1]->file != values[c]->file) break; } if (c != 4) continue; if (try_constant_propagation(inst, i, values) || try_copy_propagation(inst, i, values)) progress = true; } /* Track available source registers. */ if (inst->dst.file == GRF) { const int reg = virtual_grf_reg_map[inst->dst.reg] + inst->dst.reg_offset; /* Update our destination's current channel values. For a direct copy, * the value is the newly propagated source. Otherwise, we don't know * the new value, so clear it. */ bool direct_copy = is_direct_copy(inst); for (int i = 0; i < 4; i++) { if (inst->dst.writemask & (1 << i)) { cur_value[reg][i] = direct_copy ? &inst->src[0] : NULL; } } /* Clear the records for any registers whose current value came from * our destination's updated channels, as the two are no longer equal. */ if (inst->dst.reladdr) memset(cur_value, 0, sizeof(cur_value)); else { for (int i = 0; i < virtual_grf_reg_count; i++) { for (int j = 0; j < 4; j++) { if (inst->dst.writemask & (1 << j) && cur_value[i][j] && cur_value[i][j]->file == GRF && cur_value[i][j]->reg == inst->dst.reg && cur_value[i][j]->reg_offset == inst->dst.reg_offset) { cur_value[i][j] = NULL; } } } } } } if (progress) invalidate_live_intervals(); return progress; } } /* namespace brw */ <commit_msg>i965/vec4: fix record clearing in copy propagation<commit_after>/* * Copyright © 2011 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /** * @file brw_vec4_copy_propagation.cpp * * Implements tracking of values copied between registers, and * optimizations based on that: copy propagation and constant * propagation. */ #include "brw_vec4.h" extern "C" { #include "main/macros.h" } namespace brw { static bool is_direct_copy(vec4_instruction *inst) { return (inst->opcode == BRW_OPCODE_MOV && !inst->predicate && inst->dst.file == GRF && !inst->saturate && !inst->dst.reladdr && !inst->src[0].reladdr && inst->dst.type == inst->src[0].type); } static bool is_dominated_by_previous_instruction(vec4_instruction *inst) { return (inst->opcode != BRW_OPCODE_DO && inst->opcode != BRW_OPCODE_WHILE && inst->opcode != BRW_OPCODE_ELSE && inst->opcode != BRW_OPCODE_ENDIF); } static bool is_channel_updated(vec4_instruction *inst, src_reg *values[4], int ch) { const src_reg *src = values[ch]; /* consider GRF only */ assert(inst->dst.file == GRF); if (!src || src->file != GRF) return false; return (src->reg == inst->dst.reg && src->reg_offset == inst->dst.reg_offset && inst->dst.writemask & (1 << BRW_GET_SWZ(src->swizzle, ch))); } static bool try_constant_propagation(vec4_instruction *inst, int arg, src_reg *values[4]) { /* For constant propagation, we only handle the same constant * across all 4 channels. Some day, we should handle the 8-bit * float vector format, which would let us constant propagate * vectors better. */ src_reg value = *values[0]; for (int i = 1; i < 4; i++) { if (!value.equals(values[i])) return false; } if (value.file != IMM) return false; if (inst->src[arg].abs) { if (value.type == BRW_REGISTER_TYPE_F) { value.imm.f = fabs(value.imm.f); } else if (value.type == BRW_REGISTER_TYPE_D) { if (value.imm.i < 0) value.imm.i = -value.imm.i; } } if (inst->src[arg].negate) { if (value.type == BRW_REGISTER_TYPE_F) value.imm.f = -value.imm.f; else value.imm.u = -value.imm.u; } switch (inst->opcode) { case BRW_OPCODE_MOV: inst->src[arg] = value; return true; case BRW_OPCODE_DP2: case BRW_OPCODE_DP3: case BRW_OPCODE_DP4: case BRW_OPCODE_DPH: case BRW_OPCODE_BFI1: case BRW_OPCODE_ASR: case BRW_OPCODE_SHL: case BRW_OPCODE_SHR: case BRW_OPCODE_SUBB: if (arg == 1) { inst->src[arg] = value; return true; } break; case BRW_OPCODE_MACH: case BRW_OPCODE_MUL: case BRW_OPCODE_ADD: case BRW_OPCODE_OR: case BRW_OPCODE_AND: case BRW_OPCODE_XOR: case BRW_OPCODE_ADDC: if (arg == 1) { inst->src[arg] = value; return true; } else if (arg == 0 && inst->src[1].file != IMM) { /* Fit this constant in by commuting the operands. Exception: we * can't do this for 32-bit integer MUL/MACH because it's asymmetric. */ if ((inst->opcode == BRW_OPCODE_MUL || inst->opcode == BRW_OPCODE_MACH) && (inst->src[1].type == BRW_REGISTER_TYPE_D || inst->src[1].type == BRW_REGISTER_TYPE_UD)) break; inst->src[0] = inst->src[1]; inst->src[1] = value; return true; } break; case BRW_OPCODE_CMP: if (arg == 1) { inst->src[arg] = value; return true; } else if (arg == 0 && inst->src[1].file != IMM) { uint32_t new_cmod; new_cmod = brw_swap_cmod(inst->conditional_mod); if (new_cmod != ~0u) { /* Fit this constant in by swapping the operands and * flipping the test. */ inst->src[0] = inst->src[1]; inst->src[1] = value; inst->conditional_mod = new_cmod; return true; } } break; case BRW_OPCODE_SEL: if (arg == 1) { inst->src[arg] = value; return true; } else if (arg == 0 && inst->src[1].file != IMM) { inst->src[0] = inst->src[1]; inst->src[1] = value; /* If this was predicated, flipping operands means * we also need to flip the predicate. */ if (inst->conditional_mod == BRW_CONDITIONAL_NONE) { inst->predicate_inverse = !inst->predicate_inverse; } return true; } break; default: break; } return false; } bool vec4_visitor::try_copy_propagation(vec4_instruction *inst, int arg, src_reg *values[4]) { /* For constant propagation, we only handle the same constant * across all 4 channels. Some day, we should handle the 8-bit * float vector format, which would let us constant propagate * vectors better. */ src_reg value = *values[0]; for (int i = 1; i < 4; i++) { /* This is equals() except we don't care about the swizzle. */ if (value.file != values[i]->file || value.reg != values[i]->reg || value.reg_offset != values[i]->reg_offset || value.type != values[i]->type || value.negate != values[i]->negate || value.abs != values[i]->abs) { return false; } } /* Compute the swizzle of the original register by swizzling the * component loaded from each value according to the swizzle of * operand we're going to change. */ int s[4]; for (int i = 0; i < 4; i++) { s[i] = BRW_GET_SWZ(values[i]->swizzle, BRW_GET_SWZ(inst->src[arg].swizzle, i)); } value.swizzle = BRW_SWIZZLE4(s[0], s[1], s[2], s[3]); if (value.file != UNIFORM && value.file != GRF && value.file != ATTR) return false; if (inst->src[arg].abs) { value.negate = false; value.abs = true; } if (inst->src[arg].negate) value.negate = !value.negate; bool has_source_modifiers = value.negate || value.abs; /* gen6 math and gen7+ SENDs from GRFs ignore source modifiers on * instructions. */ if ((has_source_modifiers || value.file == UNIFORM || value.swizzle != BRW_SWIZZLE_XYZW) && !can_do_source_mods(inst)) return false; if (has_source_modifiers && value.type != inst->src[arg].type) return false; bool is_3src_inst = (inst->opcode == BRW_OPCODE_LRP || inst->opcode == BRW_OPCODE_MAD || inst->opcode == BRW_OPCODE_BFE || inst->opcode == BRW_OPCODE_BFI2); if (is_3src_inst && value.file == UNIFORM) return false; if (inst->is_send_from_grf()) return false; /* We can't copy-propagate a UD negation into a condmod * instruction, because the condmod ends up looking at the 33-bit * signed accumulator value instead of the 32-bit value we wanted */ if (inst->conditional_mod && value.negate && value.type == BRW_REGISTER_TYPE_UD) return false; /* Don't report progress if this is a noop. */ if (value.equals(&inst->src[arg])) return false; value.type = inst->src[arg].type; inst->src[arg] = value; return true; } bool vec4_visitor::opt_copy_propagation() { bool progress = false; src_reg *cur_value[virtual_grf_reg_count][4]; memset(&cur_value, 0, sizeof(cur_value)); foreach_list(node, &this->instructions) { vec4_instruction *inst = (vec4_instruction *)node; /* This pass only works on basic blocks. If there's flow * control, throw out all our information and start from * scratch. * * This should really be fixed by using a structure like in * src/glsl/opt_copy_propagation.cpp to track available copies. */ if (!is_dominated_by_previous_instruction(inst)) { memset(cur_value, 0, sizeof(cur_value)); continue; } /* For each source arg, see if each component comes from a copy * from the same type file (IMM, GRF, UNIFORM), and try * optimizing out access to the copy result */ for (int i = 2; i >= 0; i--) { /* Copied values end up in GRFs, and we don't track reladdr * accesses. */ if (inst->src[i].file != GRF || inst->src[i].reladdr) continue; int reg = (virtual_grf_reg_map[inst->src[i].reg] + inst->src[i].reg_offset); /* Find the regs that each swizzle component came from. */ src_reg *values[4]; int c; for (c = 0; c < 4; c++) { values[c] = cur_value[reg][BRW_GET_SWZ(inst->src[i].swizzle, c)]; /* If there's no available copy for this channel, bail. * We could be more aggressive here -- some channels might * not get used based on the destination writemask. */ if (!values[c]) break; /* We'll only be able to copy propagate if the sources are * all from the same file -- there's no ability to swizzle * 0 or 1 constants in with source registers like in i915. */ if (c > 0 && values[c - 1]->file != values[c]->file) break; } if (c != 4) continue; if (try_constant_propagation(inst, i, values) || try_copy_propagation(inst, i, values)) progress = true; } /* Track available source registers. */ if (inst->dst.file == GRF) { const int reg = virtual_grf_reg_map[inst->dst.reg] + inst->dst.reg_offset; /* Update our destination's current channel values. For a direct copy, * the value is the newly propagated source. Otherwise, we don't know * the new value, so clear it. */ bool direct_copy = is_direct_copy(inst); for (int i = 0; i < 4; i++) { if (inst->dst.writemask & (1 << i)) { cur_value[reg][i] = direct_copy ? &inst->src[0] : NULL; } } /* Clear the records for any registers whose current value came from * our destination's updated channels, as the two are no longer equal. */ if (inst->dst.reladdr) memset(cur_value, 0, sizeof(cur_value)); else { for (int i = 0; i < virtual_grf_reg_count; i++) { for (int j = 0; j < 4; j++) { if (is_channel_updated(inst, cur_value[i], j)){ cur_value[i][j] = NULL; } } } } } } if (progress) invalidate_live_intervals(); return progress; } } /* namespace brw */ <|endoftext|>
<commit_before>#include <fcntl.h> #include <unistd.h> #include <iostream> #include <sys/mman.h> #include <stdio.h> // Physical base address of GPIO const unsigned gpio_address = 0x400d0000; // Length of memory-mapped IO window const unsigned gpio_size = 0xff; const int gpio_led1_offset = 0x12C; // Offset for LED1 const int gpio_led2_offset = 0x130; // Offset for LED2 const int gpio_led3_offset = 0x134; // Offset for LED3 const int gpio_led4_offset = 0x138; // Offset for LED4 const int gpio_led5_offset = 0x13C; // Offset for LED5 const int gpio_led6_offset = 0x140; // Offset for LED6 const int gpio_led7_offset = 0x144; // Offset for LED7 const int gpio_led8_offset = 0x148; // Offset for LED8 const int gpio_sw1_offset = 0x14C; // Offset for Switch 1 const int gpio_sw2_offset = 0x150; // Offset for Switch 2 const int gpio_sw3_offset = 0x154; // Offset for Switch 3 const int gpio_sw4_offset = 0x158; // Offset for Switch 4 const int gpio_sw5_offset = 0x15C; // Offset for Switch 5 const int gpio_sw6_offset = 0x160; // Offset for Switch 6 const int gpio_sw7_offset = 0x164; // Offset for Switch 7 const int gpio_sw8_offset = 0x168; // Offset for Switch 8 const int gpio_pbtnl_offset = 0x16C; // Offset for left push button const int gpio_pbtnr_offset = 0x170; // Offset for right push button const int gpio_pbtnu_offset = 0x174; // Offset for up push button const int gpio_pbtnd_offset = 0x178; // Offset for down push button const int gpio_pbtnc_offset = 0x17C; // Offset for center push button /** * Write a 4-byte value at the specified general-purpose I/O location. * * @param ptr Base address returned by 'mmap'. * @parem offset Offset where device is mapped. * @param value Value to be written. */ void registerWrite(char *ptr, int offset, int value) { * (int *) (ptr + offset) = value; } /** * Read a 4-byte value from the specified general-purpose I/O location. * * @param ptr Base address returned by 'mmap'. * @param offset Offset where device is mapped. * @return Value read. */ int registerRead(char *ptr, int offset) { return * (int *) (ptr + offset); } /** * Initialize general-purpose I/O * - Opens access to physical memory /dev/mem * - Maps memory at offset 'gpio_address' into virtual address space * * @param fd * File descriptor passed by reference, where the result * of function 'open' will be stored. * * @return * Address to virtual memory which is mapped to physical, * or MAP_FAILED on error. */ char *initialize(int *fd) { *fd = open( "/dev/mem", O_RDWR); return (char *) mmap( NULL, gpio_size, PROT_READ | PROT_WRITE, MAP_SHARED, *fd, gpio_address); } /** * Close general-purpose I/O. * * @param ptr Virtual address where I/O was mapped. * @param fd File descriptor previously returned by 'open'. */ void finalize(char *ptr, int fd) { munmap(ptr, gpio_size); close(fd); } /** * Show lower 8 bits of integer value on LEDs * * @param ptr Base address of I/O * @param value Value to show on LEDs */ void setLedNumber(char *ptr, int value) { registerWrite(ptr, gpio_led1_offset, value % 2); registerWrite(ptr, gpio_led2_offset, (value / 2) % 2); registerWrite(ptr, gpio_led3_offset, (value / 4) % 2); registerWrite(ptr, gpio_led4_offset, (value / 8) % 2); registerWrite(ptr, gpio_led5_offset, (value / 16) % 2); registerWrite(ptr, gpio_led6_offset, (value / 32) % 2); registerWrite(ptr, gpio_led7_offset, (value / 64) % 2); registerWrite(ptr, gpio_led8_offset, (value / 128) % 2); } /** Set the state of the LED with the given index. * * @param ptr Base address for general-purpose I/O * @parem led_index LED index between 0 and 7 * @param state Turn on (1) or off (0) */ void setLedState(char *ptr, int led_index, int state) { int offset; switch(led_index) { case 0: offset = gpio_led1_offset; break; case 1: offset = gpio_led2_offset; break; case 2: offset = gpio_led3_offset; break; case 3: offset = gpio_led4_offset; break; case 4: offset = gpio_led5_offset; break; case 5: offset = gpio_led6_offset; break; case 6: offset = gpio_led7_offset; break; case 7: offset = gpio_led8_offset; break; default: return; } * (int *) (ptr + offset) = state; } int readSwitch(char *ptr, int switch_index) { switch(switch_index) { case 0: return registerRead(ptr, gpio_sw1_offset); case 1: return registerRead(ptr, gpio_sw2_offset); case 2: return registerRead(ptr, gpio_sw3_offset); case 3: return registerRead(ptr, gpio_sw4_offset); case 4: return registerRead(ptr, gpio_sw5_offset); case 5: return registerRead(ptr, gpio_sw6_offset); case 6: return registerRead(ptr, gpio_sw7_offset); case 7: return registerRead(ptr, gpio_sw8_offset); } return -1; } int readDirection(char *ptr) { if(registerRead(ptr, gpio_pbtnu_offset)) { return 1; } if(registerRead(ptr, gpio_pbtnd_offset)) { return 2; } if(registerRead(ptr, gpio_pbtnl_offset)) { return 3; } if(registerRead(ptr, gpio_pbtnr_offset)) { return 4; } if(registerRead(ptr, gpio_pbtnc_offset)) { return 5; } return 0; } int getSwitchState(char *ptr) { int state = 0; for(int i = 0; i < 8; i++) { if(readSwitch(ptr, i)) { state += 0b1 << i; } } return state; } int main() { // Initialize int fd; char *ptr = initialize(&fd); int state = getSwitchState(ptr); bool pressed = false; while(true) { int direction = readDirection(ptr); if(!pressed && direction == 1) { pressed = true; state += 1; } else if(!pressed && direction == 2) { pressed = true; state -= 1; } else if(!pressed && direction == 3) { pressed = true; state <<= 1; } else if(!pressed && direction == 4) { pressed = true; state >>= 1; } else if(!pressed && direction == 5) { pressed = true; state = getSwitchState(ptr); } else if(direction == 0) { pressed = false; } for(int i = 0; i < 8; i++) { setLedState(ptr, i, (state >> i) & 1); } usleep(100 * 1000); } return 0; } <commit_msg>Write ZedBoard class<commit_after>#include <fcntl.h> #include <unistd.h> #include <iostream> #include <sys/mman.h> #include <stdio.h> // Physical base address of GPIO const unsigned gpio_address = 0x400d0000; // Length of memory-mapped IO window const unsigned gpio_size = 0xff; const int gpio_led1_offset = 0x12C; // Offset for LED1 const int gpio_led2_offset = 0x130; // Offset for LED2 const int gpio_led3_offset = 0x134; // Offset for LED3 const int gpio_led4_offset = 0x138; // Offset for LED4 const int gpio_led5_offset = 0x13C; // Offset for LED5 const int gpio_led6_offset = 0x140; // Offset for LED6 const int gpio_led7_offset = 0x144; // Offset for LED7 const int gpio_led8_offset = 0x148; // Offset for LED8 const int gpio_sw1_offset = 0x14C; // Offset for Switch 1 const int gpio_sw2_offset = 0x150; // Offset for Switch 2 const int gpio_sw3_offset = 0x154; // Offset for Switch 3 const int gpio_sw4_offset = 0x158; // Offset for Switch 4 const int gpio_sw5_offset = 0x15C; // Offset for Switch 5 const int gpio_sw6_offset = 0x160; // Offset for Switch 6 const int gpio_sw7_offset = 0x164; // Offset for Switch 7 const int gpio_sw8_offset = 0x168; // Offset for Switch 8 const int gpio_pbtnl_offset = 0x16C; // Offset for left push button const int gpio_pbtnr_offset = 0x170; // Offset for right push button const int gpio_pbtnu_offset = 0x174; // Offset for up push button const int gpio_pbtnd_offset = 0x178; // Offset for down push button const int gpio_pbtnc_offset = 0x17C; // Offset for center push button class ZedBoard { char *ptr; int fd; public: ZedBoard() { this->fd = open("/dev/mem", O_RDWR); this->ptr = (char *) mmap( NULL, gpio_size, PROT_READ | PROT_WRITE, MAP_SHARED, this->fd, gpio_address); } ~ZedBoard() { munmap(this->ptr, gpio_size); close(this->fd); } /** * Write a 4-byte value at the specified general-purpose I/O location. * * @param ptr Base address returned by 'mmap'. * @parem offset Offset where device is mapped. * @param value Value to be written. */ void registerWrite(int offset, int value) { * (int *) (this->ptr + offset) = value; } /** * Read a 4-byte value from the specified general-purpose I/O location. * * @param ptr Base address returned by 'mmap'. * @param offset Offset where device is mapped. * @return Value read. */ int registerRead(int offset) { return * (int *) (this->ptr + offset); } /** Set the state of the LED with the given index. * * @param ptr Base address for general-purpose I/O * @parem led_index LED index between 0 and 7 * @param state Turn on (1) or off (0) */ void setLedState(int led_index, int state) { int offset; switch(led_index) { case 0: offset = gpio_led1_offset; break; case 1: offset = gpio_led2_offset; break; case 2: offset = gpio_led3_offset; break; case 3: offset = gpio_led4_offset; break; case 4: offset = gpio_led5_offset; break; case 5: offset = gpio_led6_offset; break; case 6: offset = gpio_led7_offset; break; case 7: offset = gpio_led8_offset; break; default: return; } * (int *) (this->ptr + offset) = state; } int readSwitch(int switch_index) { switch(switch_index) { case 0: return registerRead(gpio_sw1_offset); case 1: return registerRead(gpio_sw2_offset); case 2: return registerRead(gpio_sw3_offset); case 3: return registerRead(gpio_sw4_offset); case 4: return registerRead(gpio_sw5_offset); case 5: return registerRead(gpio_sw6_offset); case 6: return registerRead(gpio_sw7_offset); case 7: return registerRead(gpio_sw8_offset); } return -1; } int readDirection() { if(registerRead(gpio_pbtnu_offset)) { return 1; } if(registerRead(gpio_pbtnd_offset)) { return 2; } if(registerRead(gpio_pbtnl_offset)) { return 3; } if(registerRead(gpio_pbtnr_offset)) { return 4; } if(registerRead(gpio_pbtnc_offset)) { return 5; } return 0; } int getSwitchState() { int state = 0; for(int i = 0; i < 8; i++) { if(readSwitch(i)) { state += 0b1 << i; } } return state; } }; int main() { // Initialize ZedBoard *z = new ZedBoard(); int state = z->getSwitchState(); bool pressed = false; while(true) { int direction = z->readDirection(); if(!pressed && direction == 1) { pressed = true; state += 1; } else if(!pressed && direction == 2) { pressed = true; state -= 1; } else if(!pressed && direction == 3) { pressed = true; state <<= 1; } else if(!pressed && direction == 4) { pressed = true; state >>= 1; } else if(!pressed && direction == 5) { pressed = true; state = z->getSwitchState(); } else if(direction == 0) { pressed = false; } for(int i = 0; i < 8; i++) { z->setLedState(i, (state >> i) & 1); } usleep(100 * 1000); } delete z; return 0; } <|endoftext|>
<commit_before>/************************************************* * Wrappers for Botan Filters * * (C) 2005-2006 Jack Lloyd <[email protected]> * *************************************************/ #include <boost/python.hpp> using namespace boost::python; #include <botan/pipe.h> #include <botan/lookup.h> using namespace Botan; Filter* return_or_raise(Filter* f, const std::string& name) { if(f) return f; throw Invalid_Argument("Filter " + name + " not found"); } Filter* make_filter1(const std::string& name) { if(have_hash(name)) return new Hash_Filter(name); else if(name == "Hex_Encoder") return new Hex_Encoder; else if(name == "Hex_Decoder") return new Hex_Decoder; throw Invalid_Argument("Filter " + name + " not found"); } Filter* make_filter2(const std::string& name, const SymmetricKey& key) { if(have_mac(name)) return new MAC_Filter(name, key); else if(have_stream_cipher(name)) return new StreamCipher_Filter(name, key); throw Invalid_Argument("Filter " + name + " not found"); } // FIXME: add new wrapper for Keyed_Filter here Filter* make_filter3(const std::string& name, const SymmetricKey& key, Cipher_Dir direction) { return return_or_raise(get_cipher(name, key, direction), name); } Filter* make_filter4(const std::string& name, const SymmetricKey& key, const InitializationVector& iv, Cipher_Dir direction) { return return_or_raise(get_cipher(name, key, iv, direction), name); } void export_filters() { class_<Filter, std::auto_ptr<Filter>, boost::noncopyable> ("FilterObj", no_init) .def("write", &Filter::write) .def("start_msg", &Filter::start_msg) .def("end_msg", &Filter::end_msg); def("make_filter", make_filter1, return_value_policy<manage_new_object>()); def("make_filter", make_filter2, return_value_policy<manage_new_object>()); def("make_filter", make_filter3, return_value_policy<manage_new_object>()); def("make_filter", make_filter4, return_value_policy<manage_new_object>()); } void append_filter(Pipe& pipe, std::auto_ptr<Filter> filter) { pipe.append(filter.get()); filter.release(); } void prepend_filter(Pipe& pipe, std::auto_ptr<Filter> filter) { pipe.prepend(filter.get()); filter.release(); } BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(rallas_ovls, read_all_as_string, 0, 1) void export_pipe() { void (Pipe::*pipe_write_str)(const std::string&) = &Pipe::write; void (Pipe::*pipe_process_str)(const std::string&) = &Pipe::process_msg; class_<Pipe, boost::noncopyable>("PipeObj") .def(init<>()) .def_readonly("LAST_MESSAGE", &Pipe::LAST_MESSAGE) .def_readonly("DEFAULT_MESSAGE", &Pipe::DEFAULT_MESSAGE) .add_property("default_msg", &Pipe::default_msg, &Pipe::set_default_msg) .add_property("msg_count", &Pipe::message_count) .def("append", append_filter) .def("prepend", prepend_filter) .def("reset", &Pipe::reset) .def("pop", &Pipe::pop) .def("end_of_data", &Pipe::end_of_data) .def("start_msg", &Pipe::start_msg) .def("end_msg", &Pipe::end_msg) .def("write", pipe_write_str) .def("process_msg", pipe_process_str) .def("read_all", &Pipe::read_all_as_string, rallas_ovls()); } <commit_msg>Remove all exports from the Filter class, so it becomes entirely opaque.<commit_after>/************************************************* * Wrappers for Botan Filters * * (C) 2005-2006 Jack Lloyd <[email protected]> * *************************************************/ #include <boost/python.hpp> using namespace boost::python; #include <botan/pipe.h> #include <botan/lookup.h> using namespace Botan; Filter* return_or_raise(Filter* f, const std::string& name) { if(f) return f; throw Invalid_Argument("Filter " + name + " not found"); } Filter* make_filter1(const std::string& name) { if(have_hash(name)) return new Hash_Filter(name); else if(name == "Hex_Encoder") return new Hex_Encoder; else if(name == "Hex_Decoder") return new Hex_Decoder; throw Invalid_Argument("Filter " + name + " not found"); } Filter* make_filter2(const std::string& name, const SymmetricKey& key) { if(have_mac(name)) return new MAC_Filter(name, key); else if(have_stream_cipher(name)) return new StreamCipher_Filter(name, key); throw Invalid_Argument("Filter " + name + " not found"); } // FIXME: add new wrapper for Keyed_Filter here Filter* make_filter3(const std::string& name, const SymmetricKey& key, Cipher_Dir direction) { return return_or_raise(get_cipher(name, key, direction), name); } Filter* make_filter4(const std::string& name, const SymmetricKey& key, const InitializationVector& iv, Cipher_Dir direction) { return return_or_raise(get_cipher(name, key, iv, direction), name); } void export_filters() { class_<Filter, std::auto_ptr<Filter>, boost::noncopyable> ("__Internal_FilterObj", no_init); def("make_filter", make_filter1, return_value_policy<manage_new_object>()); def("make_filter", make_filter2, return_value_policy<manage_new_object>()); def("make_filter", make_filter3, return_value_policy<manage_new_object>()); def("make_filter", make_filter4, return_value_policy<manage_new_object>()); } void append_filter(Pipe& pipe, std::auto_ptr<Filter> filter) { pipe.append(filter.get()); filter.release(); } void prepend_filter(Pipe& pipe, std::auto_ptr<Filter> filter) { pipe.prepend(filter.get()); filter.release(); } BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(rallas_ovls, read_all_as_string, 0, 1) void export_pipe() { void (Pipe::*pipe_write_str)(const std::string&) = &Pipe::write; void (Pipe::*pipe_process_str)(const std::string&) = &Pipe::process_msg; class_<Pipe, boost::noncopyable>("PipeObj") .def(init<>()) .def_readonly("LAST_MESSAGE", &Pipe::LAST_MESSAGE) .def_readonly("DEFAULT_MESSAGE", &Pipe::DEFAULT_MESSAGE) .add_property("default_msg", &Pipe::default_msg, &Pipe::set_default_msg) .add_property("msg_count", &Pipe::message_count) .def("append", append_filter) .def("prepend", prepend_filter) .def("reset", &Pipe::reset) .def("pop", &Pipe::pop) .def("end_of_data", &Pipe::end_of_data) .def("start_msg", &Pipe::start_msg) .def("end_msg", &Pipe::end_msg) .def("write", pipe_write_str) .def("process_msg", pipe_process_str) .def("read_all", &Pipe::read_all_as_string, rallas_ovls()); } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2015 by Contributors * \file threaded_engine_pooled.cc * \brief Pooled threaded engine * \author Yutian Li */ #include <dmlc/base.h> #include <dmlc/logging.h> #include <dmlc/concurrency.h> #include <cassert> #include <utility> #include "./threaded_engine.h" #include "./thread_pool.h" #include "./stream_manager.h" namespace mxnet { namespace engine { /*! * \brief ThreadedEngine using global thread pool across all devices. * The policy of this Engine: * - Execute Async operation immediately if pushed from Pusher. * - Use a common thread pool for normal operations on all devices. * - Use special thread pool for copy operations. */ class ThreadedEnginePooled : public ThreadedEngine { public: ThreadedEnginePooled() { this->Start(); } ~ThreadedEnginePooled() noexcept(false) { StopNoWait(); } void StopNoWait() { streams_->Finalize(); task_queue_->SignalForKill(); io_task_queue_->SignalForKill(); task_queue_ = nullptr; io_task_queue_ = nullptr; thread_pool_ = nullptr; io_thread_pool_ = nullptr; streams_ = nullptr; } void Stop() override { WaitForAll(); StopNoWait(); } void Start() override { streams_.reset(new StreamManager<kMaxNumGpus, kNumStreamsPerGpu>()); task_queue_.reset(new dmlc::ConcurrentBlockingQueue<OprBlock*>()); io_task_queue_.reset(new dmlc::ConcurrentBlockingQueue<OprBlock*>()); thread_pool_.reset(new ThreadPool(kNumWorkingThreads, [this]() { ThreadWorker(task_queue_); })); io_thread_pool_.reset(new ThreadPool(1, [this]() { ThreadWorker(io_task_queue_); })); } protected: void PushToExecute(OprBlock *opr_block, bool pusher_thread) override { if (opr_block->opr->prop == FnProperty::kAsync && pusher_thread) { DoExecute(opr_block); } else { DoPushToQueue(opr_block); } } private: /*! \brief Concurrency for thread pool */ static constexpr std::size_t kNumWorkingThreads = 16; /*! \brief Maximum number of GPUs */ static constexpr std::size_t kMaxNumGpus = 16; /*!\brief number of streams allocated for each GPU */ static constexpr std::size_t kNumStreamsPerGpu = 16; /*! * \brief Streams. */ std::unique_ptr<StreamManager<kMaxNumGpus, kNumStreamsPerGpu>> streams_; /*! * \brief Task queues. */ std::shared_ptr<dmlc::ConcurrentBlockingQueue<OprBlock*>> task_queue_; std::shared_ptr<dmlc::ConcurrentBlockingQueue<OprBlock*>> io_task_queue_; /*! * \brief Thread pools. */ std::unique_ptr<ThreadPool> thread_pool_; std::unique_ptr<ThreadPool> io_thread_pool_; /*! * \brief Worker. * \param task_queue Queue to work on. * * The method to pass to thread pool to parallelize. */ void ThreadWorker(std::shared_ptr<dmlc::ConcurrentBlockingQueue<OprBlock*>> task_queue) { OprBlock* opr_block; while (task_queue->Pop(&opr_block)) { DoExecute(opr_block); } } /*! * \brief Execute an operation. * \param opr_block The operator block. */ void DoExecute(OprBlock* opr_block) { assert(opr_block->wait.load() == 0); if (opr_block->ctx.dev_mask() == gpu::kDevMask) { #if MXNET_USE_CUDA CUDA_CALL(cudaSetDevice(opr_block->ctx.dev_id)); #else // MXNET_USE_CUDA LOG(FATAL) << "Please compile with CUDA enabled"; #endif // MXNET_USE_CUDA } bool is_copy = (opr_block->opr->prop == FnProperty::kCopyFromGPU || opr_block->opr->prop == FnProperty::kCopyToGPU); auto&& rctx = is_copy ? streams_->GetIORunContext(opr_block->ctx) : streams_->GetRunContext(opr_block->ctx); this->ExecuteOprBlock(rctx, opr_block); } /*! * \brief Push the operation to the queue. * \param opr_block The operator block. */ void DoPushToQueue(OprBlock* opr_block) { switch (opr_block->opr->prop) { case FnProperty::kCopyFromGPU: case FnProperty::kCopyToGPU: { io_task_queue_->Push(opr_block); break; } default: { task_queue_->Push(opr_block); break; } } } }; Engine *CreateThreadedEnginePooled() { return new ThreadedEnginePooled(); } } // namespace engine } // namespace mxnet <commit_msg>[MXNET-477] CI engine test bug fix test (#11065)<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2015 by Contributors * \file threaded_engine_pooled.cc * \brief Pooled threaded engine * \author Yutian Li */ #include <dmlc/base.h> #include <dmlc/logging.h> #include <dmlc/concurrency.h> #include <cassert> #include <utility> #include "./threaded_engine.h" #include "./thread_pool.h" #include "./stream_manager.h" namespace mxnet { namespace engine { /*! * \brief ThreadedEngine using global thread pool across all devices. * The policy of this Engine: * - Execute Async operation immediately if pushed from Pusher. * - Use a common thread pool for normal operations on all devices. * - Use special thread pool for copy operations. */ class ThreadedEnginePooled : public ThreadedEngine { public: ThreadedEnginePooled() { this->Start(); } ~ThreadedEnginePooled() noexcept(false) { StopNoWait(); } void StopNoWait() { streams_->Finalize(); task_queue_->SignalForKill(); io_task_queue_->SignalForKill(); task_queue_ = nullptr; io_task_queue_ = nullptr; thread_pool_ = nullptr; io_thread_pool_ = nullptr; streams_ = nullptr; } void Stop() override { WaitForAll(); StopNoWait(); } void Start() override { streams_.reset(new StreamManager<kMaxNumGpus, kNumStreamsPerGpu>()); task_queue_.reset(new dmlc::ConcurrentBlockingQueue<OprBlock*>()); io_task_queue_.reset(new dmlc::ConcurrentBlockingQueue<OprBlock*>()); thread_pool_.reset(new ThreadPool(kNumWorkingThreads, [this](std::shared_ptr<dmlc::ManualEvent> ready_event) { ThreadWorker(task_queue_, ready_event); }, true)); io_thread_pool_.reset(new ThreadPool(1, [this](std::shared_ptr<dmlc::ManualEvent> ready_event) { ThreadWorker(io_task_queue_, ready_event); }, true)); } protected: void PushToExecute(OprBlock *opr_block, bool pusher_thread) override { if (opr_block->opr->prop == FnProperty::kAsync && pusher_thread) { DoExecute(opr_block); } else { DoPushToQueue(opr_block); } } private: /*! \brief Concurrency for thread pool */ static constexpr std::size_t kNumWorkingThreads = 16; /*! \brief Maximum number of GPUs */ static constexpr std::size_t kMaxNumGpus = 16; /*!\brief number of streams allocated for each GPU */ static constexpr std::size_t kNumStreamsPerGpu = 16; /*! * \brief Streams. */ std::unique_ptr<StreamManager<kMaxNumGpus, kNumStreamsPerGpu>> streams_; /*! * \brief Task queues. */ std::shared_ptr<dmlc::ConcurrentBlockingQueue<OprBlock*>> task_queue_; std::shared_ptr<dmlc::ConcurrentBlockingQueue<OprBlock*>> io_task_queue_; /*! * \brief Thread pools. */ std::unique_ptr<ThreadPool> thread_pool_; std::unique_ptr<ThreadPool> io_thread_pool_; /*! * \brief Worker. * \param task_queue Queue to work on. * * The method to pass to thread pool to parallelize. */ void ThreadWorker(std::shared_ptr<dmlc::ConcurrentBlockingQueue<OprBlock*>> task_queue, const std::shared_ptr<dmlc::ManualEvent>& ready_event) { OprBlock* opr_block; ready_event->signal(); while (task_queue->Pop(&opr_block)) { DoExecute(opr_block); } } /*! * \brief Execute an operation. * \param opr_block The operator block. */ void DoExecute(OprBlock* opr_block) { assert(opr_block->wait.load() == 0); if (opr_block->ctx.dev_mask() == gpu::kDevMask) { #if MXNET_USE_CUDA CUDA_CALL(cudaSetDevice(opr_block->ctx.dev_id)); #else // MXNET_USE_CUDA LOG(FATAL) << "Please compile with CUDA enabled"; #endif // MXNET_USE_CUDA } bool is_copy = (opr_block->opr->prop == FnProperty::kCopyFromGPU || opr_block->opr->prop == FnProperty::kCopyToGPU); auto&& rctx = is_copy ? streams_->GetIORunContext(opr_block->ctx) : streams_->GetRunContext(opr_block->ctx); this->ExecuteOprBlock(rctx, opr_block); } /*! * \brief Push the operation to the queue. * \param opr_block The operator block. */ void DoPushToQueue(OprBlock* opr_block) { switch (opr_block->opr->prop) { case FnProperty::kCopyFromGPU: case FnProperty::kCopyToGPU: { io_task_queue_->Push(opr_block); break; } default: { task_queue_->Push(opr_block); break; } } } }; Engine *CreateThreadedEnginePooled() { return new ThreadedEnginePooled(); } } // namespace engine } // namespace mxnet <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <OpenThreads/ScopedLock> #include <osg/ImageSequence> #include <osg/Notify> #include <osg/Camera> #include <osg/NodeVisitor> #include <osg/Texture2D> #include <math.h> using namespace osg; void ImageSequence::UpdateCallback::operator () (osg::StateAttribute* attr, osg::NodeVisitor* nv) { osg::Texture* texture = attr ? attr->asTexture() : 0; // osg::notify(osg::NOTICE)<<"ImageSequence::UpdateCallback::"<<texture<<std::endl; if (texture) { for(unsigned int i=0; i<texture->getNumImages(); ++i) { texture->getImage(i)->update(nv); } } } ImageSequence::ImageSequence() { _referenceTime = DBL_MAX; _timeMultiplier = 1.0; _mode = PRE_LOAD_ALL_IMAGES; _duration = 1.0; _timePerImage = 1.0; _fileNamesIterator = _fileNames.end(); _fileNamesIteratorTime = DBL_MAX; _imageIterator = _images.end(); _imageIteratorTime = DBL_MAX; } ImageSequence::ImageSequence(const ImageSequence& is,const CopyOp& copyop): osg::ImageStream(is,copyop), _referenceTime(is._referenceTime), _timeMultiplier(is._timeMultiplier), _mode(is._mode), _duration(is._duration), _timePerImage(is._timePerImage) { _fileNamesIterator = _fileNames.end(); _fileNamesIteratorTime = DBL_MAX; _imageIteratorTime = DBL_MAX; _imageIterator = _images.end(); } int ImageSequence::compare(const Image& rhs) const { return ImageStream::compare(rhs); } void ImageSequence::setMode(Mode mode) { _mode = mode; } void ImageSequence::setDuration(double duration) { _duration = duration; computeTimePerImage(); } void ImageSequence::computeTimePerImage() { if (!_fileNames.empty()) _timePerImage = _duration / double(_fileNames.size()); else if (!_images.empty()) _timePerImage = _duration / double(_images.size()); else _timePerImage = _duration; } void ImageSequence::addImageFile(const std::string& fileName) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); _fileNames.push_back(fileName); computeTimePerImage(); if (_fileNamesIterator==_fileNames.end()) { _fileNamesIterator = _fileNames.begin(); _fileNamesIteratorTime = _referenceTime; } } void ImageSequence::addImage(osg::Image* image) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); if (!_filesRequested.empty()) { // follows is a mechanism that ensures that requested images // get merged in the correct time order. if (_filesRequested.front().first != image->getFileName()) { for(FileNameImageList::iterator itr = _filesRequested.begin(); itr != _filesRequested.end(); ++itr) { if (itr->first == image->getFileName()) { osg::notify(osg::NOTICE)<<"inserting image into waiting stake : "<<image->getFileName()<<std::endl; itr->second = image; return; } } // osg::notify(osg::NOTICE)<<"image not expected : "<<image->getFileName()<<std::endl; _images.push_back(image); } else { // osg::notify(osg::NOTICE)<<"merging image in order expected : "<<image->getFileName()<<std::endl; _images.push_back(image); _filesRequested.pop_front(); FileNameImageList::iterator itr; for(itr = _filesRequested.begin(); itr != _filesRequested.end() && itr->second.valid(); ++itr) { // osg::notify(osg::NOTICE)<<" merging previously loaded, but out of order file : "<<itr->first<<std::endl; _images.push_back(itr->second); } _filesRequested.erase(_filesRequested.begin(), itr); } } else { _images.push_back(image); } computeTimePerImage(); if (data()==0) { _imageIterator = _images.begin(); _imageIteratorTime = _referenceTime; setImageToChild(_imageIterator->get()); } } void ImageSequence::setImageToChild(const osg::Image* image) { // osg::notify(osg::NOTICE)<<"setImageToChild("<<image<<")"<<std::endl; if (image==0) return; setImage(image->s(),image->t(),image->r(), image->getInternalTextureFormat(), image->getPixelFormat(),image->getDataType(), const_cast<unsigned char*>(image->data()), osg::Image::NO_DELETE, image->getPacking()); } void ImageSequence::update(osg::NodeVisitor* nv) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); osg::NodeVisitor::ImageRequestHandler* irh = nv->getImageRequestHandler(); const osg::FrameStamp* fs = nv->getFrameStamp(); // osg::notify(osg::NOTICE)<<"ImageSequence::update("<<fs<<", "<<irh<<")"<<std::endl; if (_referenceTime == DBL_MAX) { _referenceTime = fs->getSimulationTime(); } if (_fileNamesIteratorTime == DBL_MAX) { _fileNamesIteratorTime = _referenceTime; } if (_imageIteratorTime == DBL_MAX) { _imageIteratorTime = _referenceTime; } double time = (fs->getSimulationTime() - _referenceTime)*_timeMultiplier; FileNames::iterator previous_fileNamesIterator = _fileNamesIterator; Images::iterator previous_imageIterator = _imageIterator; bool pruneOldImages = false; bool looping = getLoopingMode()==LOOPING; switch(_mode) { case(PRE_LOAD_ALL_IMAGES): { if (_fileNames.size()>_images.size()) { FileNames::iterator itr = _fileNames.begin(); for(unsigned int i=0;i<_images.size();++i) ++itr; for(; itr!=_fileNames.end(); ++itr) { osg::Image* image = irh->readImageFile(*itr); _images.push_back(image); } } irh = 0; break; } case(PAGE_AND_RETAIN_IMAGES): { break; } case(PAGE_AND_DISCARD_USED_IMAGES): { pruneOldImages = true; break; } } // osg::notify(osg::NOTICE)<<"time = "<<time<<std::endl; if (irh) { double preLoadTime = (time+irh->getPreLoadTime())*_timeMultiplier; // // Advance imageIterator // if (_fileNamesIterator!=_fileNames.end()) { //osg::notify(osg::NOTICE)<<" _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<" "<<_timePerImage<<std::endl; while(preLoadTime > (_fileNamesIteratorTime + _timePerImage)) { _fileNamesIteratorTime += _timePerImage; //osg::notify(osg::NOTICE)<<" _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<std::endl; //osg::notify(osg::NOTICE)<<" need to preLoad = "<<*_fileNamesIterator<<std::endl; ++_fileNamesIterator; if (previous_fileNamesIterator==_fileNamesIterator) break; if (_fileNamesIterator ==_fileNames.end()) { // return iterator to begining of set. _fileNamesIterator = _fileNames.begin(); } _filesRequested.push_back(FileNameImagePair(*_fileNamesIterator,0)); irh->requestImageFile(*_fileNamesIterator, this, _fileNamesIteratorTime, fs); } } if (_fileNamesIterator==_fileNames.end()) { _fileNamesIterator = _fileNames.begin(); } } { // // Advance imageIterator // if (_imageIterator!=_images.end()) { // osg::notify(osg::NOTICE)<<" _imageIteratorTime = "<<_imageIteratorTime<<std::endl; while(time > (_imageIteratorTime + _timePerImage)) { _imageIteratorTime += _timePerImage; // osg::notify(osg::NOTICE)<<" _imageIteratorTime = "<<_imageIteratorTime<<std::endl; ++_imageIterator; if (_imageIterator ==_images.end()) { if (pruneOldImages) { _images.erase(previous_imageIterator, _imageIterator); previous_imageIterator = _images.begin(); } // return iterator to begining of set. _imageIterator = _images.begin(); } } } if (_imageIterator==_images.end()) { _imageIterator = _images.begin(); } } if (_imageIterator!=_images.end() && previous_imageIterator != _imageIterator) { if (pruneOldImages) { _images.erase(previous_imageIterator, _imageIterator); } setImageToChild(_imageIterator->get()); } } <commit_msg>Improved handling of PAGE_AND_RETAIN_IMAGES<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <OpenThreads/ScopedLock> #include <osg/ImageSequence> #include <osg/Notify> #include <osg/Camera> #include <osg/NodeVisitor> #include <osg/Texture2D> #include <math.h> using namespace osg; void ImageSequence::UpdateCallback::operator () (osg::StateAttribute* attr, osg::NodeVisitor* nv) { osg::Texture* texture = attr ? attr->asTexture() : 0; // osg::notify(osg::NOTICE)<<"ImageSequence::UpdateCallback::"<<texture<<std::endl; if (texture) { for(unsigned int i=0; i<texture->getNumImages(); ++i) { texture->getImage(i)->update(nv); } } } ImageSequence::ImageSequence() { _referenceTime = DBL_MAX; _timeMultiplier = 1.0; _mode = PRE_LOAD_ALL_IMAGES; _duration = 1.0; _timePerImage = 1.0; _fileNamesIterator = _fileNames.end(); _fileNamesIteratorTime = DBL_MAX; _imageIterator = _images.end(); _imageIteratorTime = DBL_MAX; } ImageSequence::ImageSequence(const ImageSequence& is,const CopyOp& copyop): osg::ImageStream(is,copyop), _referenceTime(is._referenceTime), _timeMultiplier(is._timeMultiplier), _mode(is._mode), _duration(is._duration), _timePerImage(is._timePerImage) { _fileNamesIterator = _fileNames.end(); _fileNamesIteratorTime = DBL_MAX; _imageIteratorTime = DBL_MAX; _imageIterator = _images.end(); } int ImageSequence::compare(const Image& rhs) const { return ImageStream::compare(rhs); } void ImageSequence::setMode(Mode mode) { _mode = mode; } void ImageSequence::setDuration(double duration) { _duration = duration; computeTimePerImage(); } void ImageSequence::computeTimePerImage() { if (!_fileNames.empty()) _timePerImage = _duration / double(_fileNames.size()); else if (!_images.empty()) _timePerImage = _duration / double(_images.size()); else _timePerImage = _duration; } void ImageSequence::addImageFile(const std::string& fileName) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); _fileNames.push_back(fileName); computeTimePerImage(); if (_fileNamesIterator==_fileNames.end()) { _fileNamesIterator = _fileNames.begin(); _fileNamesIteratorTime = _referenceTime; } } void ImageSequence::addImage(osg::Image* image) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); if (!_filesRequested.empty()) { // follows is a mechanism that ensures that requested images // get merged in the correct time order. if (_filesRequested.front().first != image->getFileName()) { for(FileNameImageList::iterator itr = _filesRequested.begin(); itr != _filesRequested.end(); ++itr) { if (itr->first == image->getFileName()) { osg::notify(osg::NOTICE)<<"inserting image into waiting stake : "<<image->getFileName()<<std::endl; itr->second = image; return; } } // osg::notify(osg::NOTICE)<<"image not expected : "<<image->getFileName()<<std::endl; _images.push_back(image); } else { // osg::notify(osg::NOTICE)<<"merging image in order expected : "<<image->getFileName()<<std::endl; _images.push_back(image); _filesRequested.pop_front(); FileNameImageList::iterator itr; for(itr = _filesRequested.begin(); itr != _filesRequested.end() && itr->second.valid(); ++itr) { // osg::notify(osg::NOTICE)<<" merging previously loaded, but out of order file : "<<itr->first<<std::endl; _images.push_back(itr->second); } _filesRequested.erase(_filesRequested.begin(), itr); } } else { _images.push_back(image); } computeTimePerImage(); if (data()==0) { _imageIterator = _images.begin(); _imageIteratorTime = _referenceTime; setImageToChild(_imageIterator->get()); } } void ImageSequence::setImageToChild(const osg::Image* image) { // osg::notify(osg::NOTICE)<<"setImageToChild("<<image<<")"<<std::endl; if (image==0) return; setImage(image->s(),image->t(),image->r(), image->getInternalTextureFormat(), image->getPixelFormat(),image->getDataType(), const_cast<unsigned char*>(image->data()), osg::Image::NO_DELETE, image->getPacking()); } void ImageSequence::update(osg::NodeVisitor* nv) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); osg::NodeVisitor::ImageRequestHandler* irh = nv->getImageRequestHandler(); const osg::FrameStamp* fs = nv->getFrameStamp(); // osg::notify(osg::NOTICE)<<"ImageSequence::update("<<fs<<", "<<irh<<")"<<std::endl; if (_referenceTime == DBL_MAX) { _referenceTime = fs->getSimulationTime(); } if (_fileNamesIteratorTime == DBL_MAX) { _fileNamesIteratorTime = _referenceTime; } if (_imageIteratorTime == DBL_MAX) { _imageIteratorTime = _referenceTime; } double time = (fs->getSimulationTime() - _referenceTime)*_timeMultiplier; FileNames::iterator previous_fileNamesIterator = _fileNamesIterator; Images::iterator previous_imageIterator = _imageIterator; bool pruneOldImages = false; bool looping = getLoopingMode()==LOOPING; switch(_mode) { case(PRE_LOAD_ALL_IMAGES): { if (_fileNames.size()>_images.size()) { FileNames::iterator itr = _fileNames.begin(); for(unsigned int i=0;i<_images.size();++i) ++itr; for(; itr!=_fileNames.end(); ++itr) { osg::Image* image = irh->readImageFile(*itr); _images.push_back(image); } } irh = 0; break; } case(PAGE_AND_RETAIN_IMAGES): { break; } case(PAGE_AND_DISCARD_USED_IMAGES): { pruneOldImages = true; break; } } // osg::notify(osg::NOTICE)<<"time = "<<time<<std::endl; if (irh && _images.size()<_fileNames.size()) { double preLoadTime = (time+irh->getPreLoadTime())*_timeMultiplier; // // Advance imageIterator // if (_fileNamesIterator!=_fileNames.end()) { //osg::notify(osg::NOTICE)<<" _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<" "<<_timePerImage<<std::endl; while(preLoadTime > (_fileNamesIteratorTime + _timePerImage)) { _fileNamesIteratorTime += _timePerImage; //osg::notify(osg::NOTICE)<<" _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<std::endl; //osg::notify(osg::NOTICE)<<" need to preLoad = "<<*_fileNamesIterator<<std::endl; ++_fileNamesIterator; if (previous_fileNamesIterator==_fileNamesIterator) break; if (_fileNamesIterator ==_fileNames.end()) { // return iterator to begining of set. _fileNamesIterator = _fileNames.begin(); } _filesRequested.push_back(FileNameImagePair(*_fileNamesIterator,0)); irh->requestImageFile(*_fileNamesIterator, this, _fileNamesIteratorTime, fs); } } if (_fileNamesIterator==_fileNames.end()) { _fileNamesIterator = _fileNames.begin(); } } { // // Advance imageIterator // if (_imageIterator!=_images.end()) { // osg::notify(osg::NOTICE)<<" _imageIteratorTime = "<<_imageIteratorTime<<std::endl; while(time > (_imageIteratorTime + _timePerImage)) { _imageIteratorTime += _timePerImage; // osg::notify(osg::NOTICE)<<" _imageIteratorTime = "<<_imageIteratorTime<<std::endl; ++_imageIterator; if (_imageIterator ==_images.end()) { if (pruneOldImages) { _images.erase(previous_imageIterator, _imageIterator); previous_imageIterator = _images.begin(); } // return iterator to begining of set. _imageIterator = _images.begin(); } } } if (_imageIterator==_images.end()) { _imageIterator = _images.begin(); } } if (_imageIterator!=_images.end() && previous_imageIterator != _imageIterator) { if (pruneOldImages) { _images.erase(previous_imageIterator, _imageIterator); } setImageToChild(_imageIterator->get()); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 Rene Herthel * * This file is subject to the terms and conditions of the MIT License. * See the file LICENSE in the top level directory for more details. */ /** * @ingroup error_handler * @{ * * @brief Function declaration of the ErrorHandler. * * @author Rene Herthel <[email protected]> */ #include "ErrorHandler.h" #include "DistanceObservable.h" #include "DistanceEnum.h" #include "Signals.h" #include "CodeDefinition.h" #include "SerialProtocoll.h" #include "Signals.h" #include <iostream> using namespace std; using namespace HAL; ErrorHandler::ErrorHandler( int chid, ConveyorBeltService &conveyorBeltService, LightSystemService * lightSystemService, SerialService * serialService) : m_hasError(false) , m_resetPressed(false) , m_conveyorBeltService(conveyorBeltService) , m_lightSystemService(lightSystemService) , m_serialService(serialService) { m_lightSystemService->setWarningLevel(Level::OPERATING); } ErrorHandler::~ErrorHandler() { // Nothing todo so far. } void ErrorHandler::demultiplex(PuckManager::ManagerReturn &manager) { if (!manager.errorFlag) { return; // Do not do anything without a errorFlag. } m_hasError = true; m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); DistanceObservable &distO = DistanceObservable::getInstance(); distO.updateSpeed(DistanceSpeed::STOP); m_conveyorBeltService.changeState(ConveyorBeltState::STOP); switch (manager.errorSignal) { case PuckManager::ErrorSignal::PUCK_LOST: cout << "[ErrorHandler] PUCK_LOST - Late Timer" << endl; break; case PuckManager::ErrorSignal::PUCK_MOVED: cout << "[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer" << endl; break; case PuckManager::ErrorSignal::UNEXPECTED_SIGNAL: cout << "[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed" << endl; break; case PuckManager::ErrorSignal::MULTIPLE_ACCEPT: cout << "[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered" << endl; break; case PuckManager::ErrorSignal::MULTIPLE_WARNING: cout << "[ErrorHandler] MULTIPLE_WARNING" << endl; break; default: // Nothing todo so far. break; } } void ErrorHandler::demultiplex(rcv::msg_t event){ switch(event.code){ case CodeDefinition::SER_IN : if(event.value == Serial_n::ser_proto_msg::ESTOP_SER){ m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); m_conveyorBeltService.changeState(ConveyorBeltState::STOP); m_hasError = true; } break; case CodeDefinition::ISR : if(event.value == interrupts::BUTTON_ESTOP_IN){ m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); m_hasError = true; m_serialService->sendMsg(Serial_n::ser_proto_msg::ESTOP_SER); m_conveyorBeltService.changeState(ConveyorBeltState::STOP); } break; default : //Nothing to do break; } } bool ErrorHandler::hasError() { return m_hasError; } void ErrorHandler::handleMessage(rcv::msg_t message) { bool buttonReset = false; bool buttonStart = false; if (message.code != 5) { // 5 is hardcoded in the ISR. TODO Serial signal needs to get through when error is acknowledged on other machine return; // Do not do anything without code 5! } switch(message.value) { case interrupts::BUTTON_RESET: buttonReset = true; break; case interrupts::BUTTON_START: buttonStart = true; break; default: // Nothing todo so far. break; } if (buttonReset && m_hasError) { m_resetPressed = true; cout << "Error acknowledged" << endl; m_lightSystemService->setWarningLevel(Level::ERROR_ACKNOWLEDGED); } if (buttonStart && m_hasError) { // Only go further when reset was pressed before. if (m_resetPressed) { cout << "Clear error" << endl; m_lightSystemService->setWarningLevel(Level::CLEAR_ERROR); m_lightSystemService->setWarningLevel(Level::OPERATING); m_resetPressed = false; } else { cout << "Error gone unacknowledged" << endl; m_lightSystemService->setWarningLevel(Level::ERROR_GONE_UNACKNOWLEDGED); } m_hasError = false; } } /** @} */ <commit_msg>snap<commit_after>/* * Copyright (C) 2017 Rene Herthel * * This file is subject to the terms and conditions of the MIT License. * See the file LICENSE in the top level directory for more details. */ /** * @ingroup error_handler * @{ * * @brief Function declaration of the ErrorHandler. * * @author Rene Herthel <[email protected]> */ #include "ErrorHandler.h" #include "DistanceObservable.h" #include "DistanceEnum.h" #include "Signals.h" #include "CodeDefinition.h" #include "SerialProtocoll.h" #include "Signals.h" #include <iostream> using namespace std; using namespace HAL; ErrorHandler::ErrorHandler( int chid, ConveyorBeltService &conveyorBeltService, LightSystemService * lightSystemService, SerialService * serialService) : m_hasError(false) , m_resetPressed(false) , m_conveyorBeltService(conveyorBeltService) , m_lightSystemService(lightSystemService) , m_serialService(serialService) { m_lightSystemService->setWarningLevel(Level::OPERATING); } ErrorHandler::~ErrorHandler() { // Nothing todo so far. } void ErrorHandler::demultiplex(PuckManager::ManagerReturn &manager) { if (!manager.errorFlag) { return; // Do not do anything without a errorFlag. } m_hasError = true; m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); DistanceObservable &distO = DistanceObservable::getInstance(); distO.updateSpeed(DistanceSpeed::STOP); m_conveyorBeltService.changeState(ConveyorBeltState::STOP); switch (manager.errorSignal) { case PuckManager::ErrorSignal::PUCK_LOST: cout << "[ErrorHandler] PUCK_LOST - Late Timer" << endl; break; case PuckManager::ErrorSignal::PUCK_MOVED: cout << "[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer" << endl; break; case PuckManager::ErrorSignal::UNEXPECTED_SIGNAL: cout << "[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed" << endl; break; case PuckManager::ErrorSignal::MULTIPLE_ACCEPT: cout << "[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered" << endl; break; case PuckManager::ErrorSignal::MULTIPLE_WARNING: cout << "[ErrorHandler] MULTIPLE_WARNING" << endl; break; default: // Nothing todo so far. break; } } void ErrorHandler::demultiplex(rcv::msg_t event){ switch(event.code){ case CodeDefinition::SER_IN : if( event.value == Serial_n::ser_proto_msg::ESTOP_SER || event.value == Serial_n::ser_proto_msg::ERROR_SER || event.value == Serial_n::ser_proto_msg::NO_CON_SER ){ LOG_DEBUG << "[ErrorHandler] Got error from serial \n"; m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); m_conveyorBeltService.changeState(ConveyorBeltState::STOP); m_hasError = true; } break; case CodeDefinition::ISR : if(event.value == interrupts::BUTTON_ESTOP_IN){ m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); m_hasError = true; m_serialService->sendMsg(Serial_n::ser_proto_msg::ESTOP_SER); m_conveyorBeltService.changeState(ConveyorBeltState::STOP); } break; default : //Nothing to do break; } } bool ErrorHandler::hasError() { LOG_DEBUG << "[ErrorHandler] Error: " << m_hasError << "\n"; return m_hasError; } void ErrorHandler::handleMessage(rcv::msg_t message) { bool buttonReset = false; bool buttonStart = false; if (message.code != 5) { // 5 is hardcoded in the ISR. TODO Serial signal needs to get through when error is acknowledged on other machine return; // Do not do anything without code 5! } switch(message.value) { case interrupts::BUTTON_RESET: buttonReset = true; break; case interrupts::BUTTON_START: buttonStart = true; break; default: // Nothing todo so far. break; } if (buttonReset && m_hasError) { m_resetPressed = true; cout << "Error acknowledged" << endl; m_lightSystemService->setWarningLevel(Level::ERROR_ACKNOWLEDGED); } if (buttonStart && m_hasError) { // Only go further when reset was pressed before. if (m_resetPressed) { cout << "Clear error" << endl; m_lightSystemService->setWarningLevel(Level::CLEAR_ERROR); m_lightSystemService->setWarningLevel(Level::OPERATING); m_resetPressed = false; } else { cout << "Error gone unacknowledged" << endl; m_lightSystemService->setWarningLevel(Level::ERROR_GONE_UNACKNOWLEDGED); } m_hasError = false; } } /** @} */ <|endoftext|>
<commit_before>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*- * * Quadra, an action puzzle game * Copyright (C) 1998-2000 Ludus Design * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef HAVE_CONFIG_H #include "autoconf.h" #endif #include "SDL.h" #include "sprite.h" #include "video.h" #include "video_dumb.h" Video* video = NULL; class Video_SDL : public Video { public: Video_SDL(int w, int h, const char* wname) : Video(new Video_bitmap_SDL(this, 0, 0, w, h), w, h, w), window_(SDL_CreateWindow( "Quadra", SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED, w, h, 0)), renderer_(SDL_CreateRenderer(window_, -1, 0)), texture_(SDL_CreateTexture( renderer_, SDL_GetWindowPixelFormat(window_), SDL_TEXTUREACCESS_STREAMING, w, h)), surface_(SDL_CreateRGBSurface(0, w, h, 8, 0, 0, 0, 0)) { SDL_assert_release(window_); SDL_assert_release(renderer_); SDL_assert_release(texture_); SDL_assert_release(surface_); } ~Video_SDL() { if (surface_) SDL_FreeSurface(surface_); if (texture_) SDL_DestroyTexture(texture_); if (renderer_) SDL_DestroyRenderer(renderer_); if (window_) SDL_DestroyWindow(window_); } virtual void end_frame() { Uint32 pixel_format; int w, h; SDL_QueryTexture(texture_, &pixel_format, NULL, &w, &h); int bpp; Uint32 rmask, gmask, bmask, amask; SDL_PixelFormatEnumToMasks(pixel_format, &bpp, &rmask, &gmask, &bmask, &amask); void* pixels; int pitch; SDL_LockTexture(texture_, NULL, &pixels, &pitch); SDL_Surface* const tex_surf(SDL_CreateRGBSurfaceFrom( pixels, w, h, bpp, pitch, rmask, gmask, bmask, amask)); SDL_BlitSurface(surface_, NULL, tex_surf, NULL); SDL_FreeSurface(tex_surf); SDL_UnlockTexture(texture_); SDL_RenderCopy(renderer_, texture_, NULL, NULL); SDL_RenderPresent(renderer_); ++framecount; } virtual void setpal(const Palette& p) { p.set(); } virtual void dosetpal(const PALETTEENTRY pal[256], int size) { SDL_Color entries[256]; for (int i = 0; i < size; ++i) { entries[i].r = pal[i].peRed; entries[i].g = pal[i].peGreen; entries[i].b = pal[i].peBlue; entries[i].a = SDL_ALPHA_OPAQUE; } SDL_SetPaletteColors(surface_->format->palette, entries, 0, size); } virtual void snap_shot(int x, int y, int w, int h) { SDL_assert_release(false); } Video_bitmap* new_bitmap(int px, int py, int w, int h) { return new Video_bitmap_SDL(this, px, py, w, h); } private: class Video_bitmap_SDL : public Video_bitmap { public: Video_bitmap_SDL(Video_SDL* video, int px, int py, int w, int h) : Video_bitmap(px, py, w, h), video_(video) { } virtual void rect(const int x, const int y, const int w, const int h, const int color) const { if (clip(x, y, w, h)) return; clip_y1 += pos_y; clip_y2 += pos_y; clip_x1 += pos_x; for(uint8_t* bp = (uint8_t*)video_->surface_->pixels + (clip_y1 * video_->surface_->pitch); bp <= (uint8_t*)video_->surface_->pixels + ((clip_y2) * video_->surface_->pitch); bp += video_->surface_->pitch) { memset(&bp[clip_x1], color, clip_w); } } virtual void put_pel(const int x, const int y, const uint8_t c) const { Bitmap bitmap(get_pixels(), width, height, video_->surface_->pitch); bitmap.put_pel(x, y, c); } virtual void hline(const int y, const int x, const int w, const uint8_t c) const { Bitmap bitmap(get_pixels(), width, height, video_->surface_->pitch); bitmap.hline(y, x, w, c); } virtual void vline(const int x, const int y, const int h, const uint8_t c) const { Bitmap bitmap(get_pixels(), width, height, video_->surface_->pitch); bitmap.vline(x, y, h, c); } virtual void put_bitmap(const Bitmap& d, const int dx, const int dy) const { Bitmap bitmap(get_pixels(), width, height, video_->surface_->pitch); d.draw(bitmap, dx, dy); } virtual void put_sprite(const Sprite& d, const int dx, const int dy) const { Bitmap bitmap(get_pixels(), width, height, video_->surface_->pitch); d.draw(bitmap, dx, dy); } private: void* get_pixels() const { uint8_t* pixels(static_cast<uint8_t*>(video_->surface_->pixels)); return pixels + (pos_y * video_->surface_->pitch) + pos_x; } Video_SDL* const video_; }; SDL_Window* const window_; SDL_Renderer* const renderer_; SDL_Texture* const texture_; SDL_Surface* const surface_; }; void Video_bitmap::box(const int x, const int y, const int w, const int h, const int color) const { hline(y, x, w, color); hline(y + h - 1, x, w, color); vline(x, y, h, color); vline(x + w - 1, y, h, color); } Video* Video::New(int w, int h, const char *wname, bool dumb) { Video* obj; if (dumb) obj = new Video_Dumb(w, h, wname); else obj = new Video_SDL(w, h, wname); return obj; } <commit_msg>Enable waiting on vsync.<commit_after>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*- * * Quadra, an action puzzle game * Copyright (C) 1998-2000 Ludus Design * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef HAVE_CONFIG_H #include "autoconf.h" #endif #include "SDL.h" #include "sprite.h" #include "video.h" #include "video_dumb.h" Video* video = NULL; class Video_SDL : public Video { public: Video_SDL(int w, int h, const char* wname) : Video(new Video_bitmap_SDL(this, 0, 0, w, h), w, h, w), window_(SDL_CreateWindow( "Quadra", SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED, w, h, 0)), renderer_(SDL_CreateRenderer(window_, -1, SDL_RENDERER_PRESENTVSYNC)), texture_(SDL_CreateTexture( renderer_, SDL_GetWindowPixelFormat(window_), SDL_TEXTUREACCESS_STREAMING, w, h)), surface_(SDL_CreateRGBSurface(0, w, h, 8, 0, 0, 0, 0)) { SDL_assert_release(window_); SDL_assert_release(renderer_); SDL_assert_release(texture_); SDL_assert_release(surface_); } ~Video_SDL() { if (surface_) SDL_FreeSurface(surface_); if (texture_) SDL_DestroyTexture(texture_); if (renderer_) SDL_DestroyRenderer(renderer_); if (window_) SDL_DestroyWindow(window_); } virtual void end_frame() { Uint32 pixel_format; int w, h; SDL_QueryTexture(texture_, &pixel_format, NULL, &w, &h); int bpp; Uint32 rmask, gmask, bmask, amask; SDL_PixelFormatEnumToMasks(pixel_format, &bpp, &rmask, &gmask, &bmask, &amask); void* pixels; int pitch; SDL_LockTexture(texture_, NULL, &pixels, &pitch); SDL_Surface* const tex_surf(SDL_CreateRGBSurfaceFrom( pixels, w, h, bpp, pitch, rmask, gmask, bmask, amask)); SDL_BlitSurface(surface_, NULL, tex_surf, NULL); SDL_FreeSurface(tex_surf); SDL_UnlockTexture(texture_); SDL_RenderCopy(renderer_, texture_, NULL, NULL); SDL_RenderPresent(renderer_); ++framecount; } virtual void setpal(const Palette& p) { p.set(); } virtual void dosetpal(const PALETTEENTRY pal[256], int size) { SDL_Color entries[256]; for (int i = 0; i < size; ++i) { entries[i].r = pal[i].peRed; entries[i].g = pal[i].peGreen; entries[i].b = pal[i].peBlue; entries[i].a = SDL_ALPHA_OPAQUE; } SDL_SetPaletteColors(surface_->format->palette, entries, 0, size); } virtual void snap_shot(int x, int y, int w, int h) { SDL_assert_release(false); } Video_bitmap* new_bitmap(int px, int py, int w, int h) { return new Video_bitmap_SDL(this, px, py, w, h); } private: class Video_bitmap_SDL : public Video_bitmap { public: Video_bitmap_SDL(Video_SDL* video, int px, int py, int w, int h) : Video_bitmap(px, py, w, h), video_(video) { } virtual void rect(const int x, const int y, const int w, const int h, const int color) const { if (clip(x, y, w, h)) return; clip_y1 += pos_y; clip_y2 += pos_y; clip_x1 += pos_x; for(uint8_t* bp = (uint8_t*)video_->surface_->pixels + (clip_y1 * video_->surface_->pitch); bp <= (uint8_t*)video_->surface_->pixels + ((clip_y2) * video_->surface_->pitch); bp += video_->surface_->pitch) { memset(&bp[clip_x1], color, clip_w); } } virtual void put_pel(const int x, const int y, const uint8_t c) const { Bitmap bitmap(get_pixels(), width, height, video_->surface_->pitch); bitmap.put_pel(x, y, c); } virtual void hline(const int y, const int x, const int w, const uint8_t c) const { Bitmap bitmap(get_pixels(), width, height, video_->surface_->pitch); bitmap.hline(y, x, w, c); } virtual void vline(const int x, const int y, const int h, const uint8_t c) const { Bitmap bitmap(get_pixels(), width, height, video_->surface_->pitch); bitmap.vline(x, y, h, c); } virtual void put_bitmap(const Bitmap& d, const int dx, const int dy) const { Bitmap bitmap(get_pixels(), width, height, video_->surface_->pitch); d.draw(bitmap, dx, dy); } virtual void put_sprite(const Sprite& d, const int dx, const int dy) const { Bitmap bitmap(get_pixels(), width, height, video_->surface_->pitch); d.draw(bitmap, dx, dy); } private: void* get_pixels() const { uint8_t* pixels(static_cast<uint8_t*>(video_->surface_->pixels)); return pixels + (pos_y * video_->surface_->pitch) + pos_x; } Video_SDL* const video_; }; SDL_Window* const window_; SDL_Renderer* const renderer_; SDL_Texture* const texture_; SDL_Surface* const surface_; }; void Video_bitmap::box(const int x, const int y, const int w, const int h, const int color) const { hline(y, x, w, color); hline(y + h - 1, x, w, color); vline(x, y, h, color); vline(x + w - 1, y, h, color); } Video* Video::New(int w, int h, const char *wname, bool dumb) { Video* obj; if (dumb) obj = new Video_Dumb(w, h, wname); else obj = new Video_SDL(w, h, wname); return obj; } <|endoftext|>
<commit_before>/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************/ #include "WindowsWindow.h" DC_BEGIN_DREEMCHEST namespace platform { // ** createWindow IWindow* createWindow( u32 width, u32 height ) { WindowsWindow* window = DC_NEW WindowsWindow; if( window->create( width, height ) ) { return window; } delete window; return NULL; } WindowsWindow::Windows WindowsWindow::s_windows; u32 WindowsWindow::s_windowCount = 0; // ** WindowsWindow::WindowsWindow WindowsWindow::WindowsWindow( void ) : m_owner( NULL ), m_window( NULL ) { } // ** WindowsWindow::~WindowsWindow WindowsWindow::~WindowsWindow( void ) { } // ** WindowsWindow::close void WindowsWindow::close( void ) { DC_BREAK_IF( m_window == NULL ); // ** Destroy window if( !DestroyWindow( m_window ) ) { return; } // ** Free the window class if( !UnregisterClass( m_className.c_str(), m_applicationInstance ) ) { return; } // ** Remove window from registry int removed = s_windows.erase( m_window ); DC_BREAK_IF( removed != 1 ); m_window = NULL; m_applicationInstance = NULL; } // ** WindowsWindow::setOwner void WindowsWindow::setOwner( Window* value ) { m_owner = value; } // ** WindowsWindow::owner Window* WindowsWindow::owner( void ) const { return m_owner; } // ** WindowsWindow::width u32 WindowsWindow::width( void ) const { RECT rect; GetWindowRect( m_window, &rect ); return rect.right - rect.left; } // ** WindowsWindow::height u32 WindowsWindow::height( void ) const { RECT rect; GetWindowRect( m_window, &rect ); return rect.bottom - rect.top; } // ** WindowsWindow::mapCursorToWindow void WindowsWindow::mapCursorToWindow( s32& x, s32& y ) const { POINT point = { x, y }; ScreenToClient( m_window, &point ); x = point.x; y = point.y; } // ** WindowsWindow::setCaption void WindowsWindow::setCaption( const String& value ) { SetWindowText( m_window, value.c_str() ); } // ** WindowsWindow::caption String WindowsWindow::caption( void ) const { s8 text[128]; GetWindowText( m_window, text, 128 ); return text; } // ** WindowsWindow::handle void* WindowsWindow::handle( void ) const { return reinterpret_cast<void*>( m_window ); } // ** WindowsWindow::create bool WindowsWindow::create( u32 width, u32 height ) { m_applicationInstance = GetModuleHandle( 0 ); memset( &m_windowClass, 0, sizeof( m_windowClass ) ); m_className = "dreemchest" + format::number( s_windowCount++ ); m_windowClass.hCursor = LoadCursor( NULL, IDC_ARROW ); m_windowClass.hInstance = m_applicationInstance; m_windowClass.lpfnWndProc = ( WNDPROC )windowProc; m_windowClass.lpszClassName = m_className.c_str(); m_windowClass.style = CS_HREDRAW | CS_VREDRAW; m_windowClass.hbrBackground = ( HBRUSH )COLOR_GRAYTEXT; if( !RegisterClass( &m_windowClass ) ) { log::error( "WindowsWindow::create : failed to register window class" ); return false; } // ** Initialize the window style u32 style = WS_OVERLAPPEDWINDOW | WS_SYSMENU | WS_MINIMIZEBOX; // ** Adjust the window rect to make sure the client are size is right. adjustWindowSize( style, width, height ); // ** Caclulate the window position u32 x = ( GetSystemMetrics( SM_CXSCREEN ) / 2 ) - ( width / 2 ); u32 y = ( GetSystemMetrics( SM_CYSCREEN ) / 2 ) - ( height / 2 ); m_window = CreateWindowEx( 0, m_windowClass.lpszClassName, "", style, x, y, width, height, NULL, NULL, m_applicationInstance, NULL ); if( !m_window ) { log::error( "WindowsWindow::create : failed to create window" ); return false; } s_windows[m_window] = this; ShowWindow( m_window, SW_SHOW ); SetFocus( m_window ); return true; } // ** WindowsWindow::adjustWindowSize void WindowsWindow::adjustWindowSize( u32 style, u32& width, u32& height ) { RECT rect = { 0, 0, width, height }; AdjustWindowRect( &rect, style, FALSE ); width = rect.right - rect.left; height = rect.bottom - rect.top; } // ** WindowsWindow::windowProc LRESULT WindowsWindow::windowProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { WindowsWindow* window = s_windows[hWnd]; switch( message ) { case WM_CLOSE: window->owner()->release(); if( s_windows.size() == 0 ) { PostQuitMessage( 0 ); } break; case WM_KEYDOWN: window->owner()->notifyKeyDown( translateKey( ( u32 )wParam ) ); break; case WM_KEYUP: window->owner()->notifyKeyUp( translateKey( ( u32 )wParam ) ); break; case WM_LBUTTONDOWN: window->owner()->notifyMouseDown( LOWORD( lParam ), HIWORD( lParam ) ); break; case WM_LBUTTONUP: window->owner()->notifyMouseUp( LOWORD( lParam ), HIWORD( lParam ) ); break; case WM_RBUTTONDOWN: break; case WM_RBUTTONUP: break; case WM_CHAR: break; } return DefWindowProc( hWnd, message, wParam, lParam ); } // ** WindowsWindow::translateKey Key WindowsWindow::translateKey( u32 vkey ) { switch( vkey ) { // ** Numbers case 0x30: return Key::_0; break; // 0 case 0x31: return Key::_1; break; // 1 case 0x32: return Key::_2; break; // 2 case 0x33: return Key::_3; break; // 3 case 0x34: return Key::_4; break; // 4 case 0x35: return Key::_5; break; // 5 case 0x36: return Key::_6; break; // 6 case 0x37: return Key::_7; break; // 7 case 0x38: return Key::_8; break; // 8 case 0x39: return Key::_9; break; // 9 case VK_NUMPAD0: return Key::Num0; break; case VK_NUMPAD1: return Key::Num1; break; case VK_NUMPAD2: return Key::Num2; break; case VK_NUMPAD3: return Key::Num3; break; case VK_NUMPAD4: return Key::Num4; break; case VK_NUMPAD5: return Key::Num5; break; case VK_NUMPAD6: return Key::Num6; break; case VK_NUMPAD7: return Key::Num7; break; case VK_NUMPAD8: return Key::Num8; break; case VK_NUMPAD9: return Key::Num9; break; // ** Characters case 0x41: return Key::A; break; // A case 0x42: return Key::B; break; // B case 0x43: return Key::C; break; // C case 0x44: return Key::D; break; // D case 0x45: return Key::E; break; // E case 0x46: return Key::F; break; // F case 0x47: return Key::G; break; // G case 0x48: return Key::H; break; // H case 0x49: return Key::I; break; // I case 0x4A: return Key::J; break; // J case 0x4B: return Key::K; break; // K case 0x4C: return Key::L; break; // L case 0x4D: return Key::M; break; // M case 0x4E: return Key::N; break; // N case 0x4F: return Key::O; break; // O case 0x50: return Key::P; break; // P case 0x51: return Key::Q; break; // Q case 0x52: return Key::R; break; // R case 0x53: return Key::S; break; // S case 0x54: return Key::T; break; // T case 0x55: return Key::U; break; // U case 0x56: return Key::V; break; // V case 0x57: return Key::W; break; // W case 0x58: return Key::X; break; // X case 0x59: return Key::Y; break; // Y case 0x5A: return Key::Z; break; // Z // ** Functional case VK_F1: return Key::F1; break; case VK_F2: return Key::F2; break; case VK_F3: return Key::F3; break; case VK_F4: return Key::F4; break; case VK_F5: return Key::F5; break; case VK_F6: return Key::F6; break; case VK_F7: return Key::F7; break; case VK_F8: return Key::F8; break; case VK_F9: return Key::F9; break; case VK_F10: return Key::F10; break; case VK_F11: return Key::F11; break; case VK_F12: return Key::F12; break; case VK_ESCAPE: return Key::Escape; break; case VK_TAB: return Key::Tab; break; case VK_CAPITAL: return Key::Capital; break; case VK_SHIFT: return Key::Shift; break; case VK_CONTROL: return Key::Control; break; case VK_LWIN: return Key::Win; break; case VK_MENU: return Key::Alt; break; case VK_SPACE: return Key::Space; break; case VK_RETURN: return Key::Return; break; case VK_BACK: return Key::Back; break; case VK_PAUSE: return Key::Pause; break; case VK_SNAPSHOT: return Key::Snapshot; break; case VK_SCROLL: return Key::Scroll; break; case VK_NEXT: return Key::PgDown; break; case VK_PRIOR: return Key::PgUp; break; case VK_HOME: return Key::Home; break; case VK_END: return Key::End; break; case VK_INSERT: return Key::Insert; break; case VK_DELETE: return Key::Delete; break; case VK_UP: return Key::Up; break; case VK_DOWN: return Key::Down; break; case VK_LEFT: return Key::Left; break; case VK_RIGHT: return Key::Right; break; // ** Numpad case VK_NUMLOCK: return Key::Numlock; break; case VK_DIVIDE: return Key::Divide; break; case VK_MULTIPLY: return Key::Multiply; break; case VK_SUBTRACT: return Key::Subtract; break; case VK_ADD: return Key::Add; break; case VK_DECIMAL: return Key::Decimal; break; // ** Mouse case VK_RBUTTON: return Key::RButton; break; case VK_LBUTTON: return Key::LButton; break; case VK_MBUTTON: return Key::MButton; break; }; return Key::Total; } } // namespace platform DC_END_DREEMCHEST<commit_msg>Fixed Window::width/Window::height properties on Windows<commit_after>/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************/ #include "WindowsWindow.h" DC_BEGIN_DREEMCHEST namespace platform { // ** createWindow IWindow* createWindow( u32 width, u32 height ) { WindowsWindow* window = DC_NEW WindowsWindow; if( window->create( width, height ) ) { return window; } delete window; return NULL; } WindowsWindow::Windows WindowsWindow::s_windows; u32 WindowsWindow::s_windowCount = 0; // ** WindowsWindow::WindowsWindow WindowsWindow::WindowsWindow( void ) : m_owner( NULL ), m_window( NULL ) { } // ** WindowsWindow::~WindowsWindow WindowsWindow::~WindowsWindow( void ) { } // ** WindowsWindow::close void WindowsWindow::close( void ) { DC_BREAK_IF( m_window == NULL ); // ** Destroy window if( !DestroyWindow( m_window ) ) { return; } // ** Free the window class if( !UnregisterClass( m_className.c_str(), m_applicationInstance ) ) { return; } // ** Remove window from registry int removed = s_windows.erase( m_window ); DC_BREAK_IF( removed != 1 ); m_window = NULL; m_applicationInstance = NULL; } // ** WindowsWindow::setOwner void WindowsWindow::setOwner( Window* value ) { m_owner = value; } // ** WindowsWindow::owner Window* WindowsWindow::owner( void ) const { return m_owner; } // ** WindowsWindow::width u32 WindowsWindow::width( void ) const { RECT rect; GetClientRect( m_window, &rect ); return rect.right - rect.left; } // ** WindowsWindow::height u32 WindowsWindow::height( void ) const { RECT rect; GetClientRect( m_window, &rect ); return rect.bottom - rect.top; } // ** WindowsWindow::mapCursorToWindow void WindowsWindow::mapCursorToWindow( s32& x, s32& y ) const { POINT point = { x, y }; ScreenToClient( m_window, &point ); x = point.x; y = point.y; } // ** WindowsWindow::setCaption void WindowsWindow::setCaption( const String& value ) { SetWindowText( m_window, value.c_str() ); } // ** WindowsWindow::caption String WindowsWindow::caption( void ) const { s8 text[128]; GetWindowText( m_window, text, 128 ); return text; } // ** WindowsWindow::handle void* WindowsWindow::handle( void ) const { return reinterpret_cast<void*>( m_window ); } // ** WindowsWindow::create bool WindowsWindow::create( u32 width, u32 height ) { m_applicationInstance = GetModuleHandle( 0 ); memset( &m_windowClass, 0, sizeof( m_windowClass ) ); m_className = "dreemchest" + format::number( s_windowCount++ ); m_windowClass.hCursor = LoadCursor( NULL, IDC_ARROW ); m_windowClass.hInstance = m_applicationInstance; m_windowClass.lpfnWndProc = ( WNDPROC )windowProc; m_windowClass.lpszClassName = m_className.c_str(); m_windowClass.style = CS_HREDRAW | CS_VREDRAW; m_windowClass.hbrBackground = ( HBRUSH )COLOR_GRAYTEXT; if( !RegisterClass( &m_windowClass ) ) { log::error( "WindowsWindow::create : failed to register window class" ); return false; } // ** Initialize the window style u32 style = WS_OVERLAPPEDWINDOW | WS_SYSMENU | WS_MINIMIZEBOX; // ** Adjust the window rect to make sure the client are size is right. adjustWindowSize( style, width, height ); // ** Caclulate the window position u32 x = ( GetSystemMetrics( SM_CXSCREEN ) / 2 ) - ( width / 2 ); u32 y = ( GetSystemMetrics( SM_CYSCREEN ) / 2 ) - ( height / 2 ); m_window = CreateWindowEx( 0, m_windowClass.lpszClassName, "", style, x, y, width, height, NULL, NULL, m_applicationInstance, NULL ); if( !m_window ) { log::error( "WindowsWindow::create : failed to create window" ); return false; } s_windows[m_window] = this; ShowWindow( m_window, SW_SHOW ); SetFocus( m_window ); return true; } // ** WindowsWindow::adjustWindowSize void WindowsWindow::adjustWindowSize( u32 style, u32& width, u32& height ) { RECT rect = { 0, 0, width, height }; AdjustWindowRect( &rect, style, FALSE ); width = rect.right - rect.left; height = rect.bottom - rect.top; } // ** WindowsWindow::windowProc LRESULT WindowsWindow::windowProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { WindowsWindow* window = s_windows[hWnd]; switch( message ) { case WM_CLOSE: window->owner()->release(); if( s_windows.size() == 0 ) { PostQuitMessage( 0 ); } break; case WM_KEYDOWN: window->owner()->notifyKeyDown( translateKey( ( u32 )wParam ) ); break; case WM_KEYUP: window->owner()->notifyKeyUp( translateKey( ( u32 )wParam ) ); break; case WM_LBUTTONDOWN: window->owner()->notifyMouseDown( LOWORD( lParam ), HIWORD( lParam ) ); break; case WM_LBUTTONUP: window->owner()->notifyMouseUp( LOWORD( lParam ), HIWORD( lParam ) ); break; case WM_RBUTTONDOWN: break; case WM_RBUTTONUP: break; case WM_CHAR: break; } return DefWindowProc( hWnd, message, wParam, lParam ); } // ** WindowsWindow::translateKey Key WindowsWindow::translateKey( u32 vkey ) { switch( vkey ) { // ** Numbers case 0x30: return Key::_0; break; // 0 case 0x31: return Key::_1; break; // 1 case 0x32: return Key::_2; break; // 2 case 0x33: return Key::_3; break; // 3 case 0x34: return Key::_4; break; // 4 case 0x35: return Key::_5; break; // 5 case 0x36: return Key::_6; break; // 6 case 0x37: return Key::_7; break; // 7 case 0x38: return Key::_8; break; // 8 case 0x39: return Key::_9; break; // 9 case VK_NUMPAD0: return Key::Num0; break; case VK_NUMPAD1: return Key::Num1; break; case VK_NUMPAD2: return Key::Num2; break; case VK_NUMPAD3: return Key::Num3; break; case VK_NUMPAD4: return Key::Num4; break; case VK_NUMPAD5: return Key::Num5; break; case VK_NUMPAD6: return Key::Num6; break; case VK_NUMPAD7: return Key::Num7; break; case VK_NUMPAD8: return Key::Num8; break; case VK_NUMPAD9: return Key::Num9; break; // ** Characters case 0x41: return Key::A; break; // A case 0x42: return Key::B; break; // B case 0x43: return Key::C; break; // C case 0x44: return Key::D; break; // D case 0x45: return Key::E; break; // E case 0x46: return Key::F; break; // F case 0x47: return Key::G; break; // G case 0x48: return Key::H; break; // H case 0x49: return Key::I; break; // I case 0x4A: return Key::J; break; // J case 0x4B: return Key::K; break; // K case 0x4C: return Key::L; break; // L case 0x4D: return Key::M; break; // M case 0x4E: return Key::N; break; // N case 0x4F: return Key::O; break; // O case 0x50: return Key::P; break; // P case 0x51: return Key::Q; break; // Q case 0x52: return Key::R; break; // R case 0x53: return Key::S; break; // S case 0x54: return Key::T; break; // T case 0x55: return Key::U; break; // U case 0x56: return Key::V; break; // V case 0x57: return Key::W; break; // W case 0x58: return Key::X; break; // X case 0x59: return Key::Y; break; // Y case 0x5A: return Key::Z; break; // Z // ** Functional case VK_F1: return Key::F1; break; case VK_F2: return Key::F2; break; case VK_F3: return Key::F3; break; case VK_F4: return Key::F4; break; case VK_F5: return Key::F5; break; case VK_F6: return Key::F6; break; case VK_F7: return Key::F7; break; case VK_F8: return Key::F8; break; case VK_F9: return Key::F9; break; case VK_F10: return Key::F10; break; case VK_F11: return Key::F11; break; case VK_F12: return Key::F12; break; case VK_ESCAPE: return Key::Escape; break; case VK_TAB: return Key::Tab; break; case VK_CAPITAL: return Key::Capital; break; case VK_SHIFT: return Key::Shift; break; case VK_CONTROL: return Key::Control; break; case VK_LWIN: return Key::Win; break; case VK_MENU: return Key::Alt; break; case VK_SPACE: return Key::Space; break; case VK_RETURN: return Key::Return; break; case VK_BACK: return Key::Back; break; case VK_PAUSE: return Key::Pause; break; case VK_SNAPSHOT: return Key::Snapshot; break; case VK_SCROLL: return Key::Scroll; break; case VK_NEXT: return Key::PgDown; break; case VK_PRIOR: return Key::PgUp; break; case VK_HOME: return Key::Home; break; case VK_END: return Key::End; break; case VK_INSERT: return Key::Insert; break; case VK_DELETE: return Key::Delete; break; case VK_UP: return Key::Up; break; case VK_DOWN: return Key::Down; break; case VK_LEFT: return Key::Left; break; case VK_RIGHT: return Key::Right; break; // ** Numpad case VK_NUMLOCK: return Key::Numlock; break; case VK_DIVIDE: return Key::Divide; break; case VK_MULTIPLY: return Key::Multiply; break; case VK_SUBTRACT: return Key::Subtract; break; case VK_ADD: return Key::Add; break; case VK_DECIMAL: return Key::Decimal; break; // ** Mouse case VK_RBUTTON: return Key::RButton; break; case VK_LBUTTON: return Key::LButton; break; case VK_MBUTTON: return Key::MButton; break; }; return Key::Total; } } // namespace platform DC_END_DREEMCHEST<|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <string.h> #include <string> #include <sys/types.h> #if !defined(_WIN32) #include <unistd.h> #include <setjmp.h> #else #include <winsock2.h> #include <ws2tcpip.h> #endif #include "Address.h" #include "bzsignal.h" #include "ErrorHandler.h" #include "Pack.h" #if defined(sun) // Solaris... extern "C" int inet_aton(const char *, struct in_addr *); #endif // // Address // #if !defined( GUSI_20 ) && !defined( WIN32 ) Address Address::localAddress(""); #endif Address::Address() { InAddr tempAddr; memset(&tempAddr, 0, sizeof(tempAddr)); tempAddr.s_addr = htonl(INADDR_ANY); addr.push_back(tempAddr); } Address::Address(const std::string& name) { Address a = getHostAddress(name); addr.push_back(a.addr[0]); } Address::Address(const Address& address) : addr(address.addr) { // do nothing } Address::Address(const InAddr& _addr) { addr.push_back(_addr); } Address::Address(const struct sockaddr_in& _addr) { addr.push_back(_addr.sin_addr); } Address::~Address() { // do nothing } Address& Address::operator=(const Address& address) { addr.clear(); addr.push_back(address.addr[0]); return *this; } Address::operator InAddr() const { return addr[0]; } bool Address::operator==(const Address& address) const { return addr[0].s_addr == address.addr[0].s_addr; } bool Address::operator!=(const Address& address) const { return addr[0].s_addr != address.addr[0].s_addr; } bool Address::isAny() const { return addr[0].s_addr == htonl(INADDR_ANY); } std::string Address::getDotNotation() const { return std::string(inet_ntoa(addr[0])); } uint8_t Address::getIPVersion() const { return 4; } #if !defined(_WIN32) static jmp_buf alarmEnv; static void onAlarm(int) { // jump back to setjmp. this handles the race condition where we // set the alarm but gethostbyname() wouldn't have been called // until after the alarm goes off (resulting in an indeterminate // wait). longjmp(alarmEnv, 1); } #endif Address Address::getHostAddress(const std::string hname) { Address a; InAddr tempAddr; int j; struct hostent* hent; if (hname == "") { // local address char hostname[MAXHOSTNAMELEN+1]; if (gethostname(hostname, sizeof(hostname)) >= 0) hent = gethostbyname(hostname); else return a; } else if (inet_aton(hname.c_str(), &tempAddr) != 0) { a.addr.clear(); a.addr.push_back(tempAddr); return a; } else { // non-local address #if !defined(_WIN32) // set alarm to avoid waiting too long SIG_PF oldAlarm = bzSignal(SIGALRM, SIG_PF(onAlarm)); if (oldAlarm != SIG_ERR) { if (setjmp(alarmEnv) != 0) { // alarm went off hent = NULL; printError("Looking up host name: timeout"); return a; } // wait up to this many seconds alarm(8); } #endif hent = gethostbyname(hname.c_str()); #if !defined(_WIN32) if (oldAlarm != SIG_ERR) { alarm(0); bzSignal(SIGALRM, oldAlarm); } #endif } if (!hent) { herror("Looking up host name"); return a; } a.addr.clear(); for (j=0; hent->h_addr_list[j] != NULL; j++){ ::memcpy(&tempAddr, hent->h_addr_list[j], sizeof(tempAddr)); a.addr.push_back(tempAddr); } return a; } std::string Address::getHostByAddress(InAddr addr) { #if !defined(_WIN32) // set alarm to avoid waiting too long SIG_PF oldAlarm = bzSignal(SIGALRM, SIG_PF(onAlarm)); if (oldAlarm != SIG_ERR) { if (setjmp(alarmEnv) != 0) { // alarm went off return std::string(inet_ntoa(addr)); } // wait up to this many seconds alarm(8); } #endif int addrLen = sizeof(addr); struct hostent* hent = gethostbyaddr((char*)&addr, addrLen, AF_INET); #if !defined(_WIN32) if (oldAlarm != SIG_ERR) { alarm(0); bzSignal(SIGALRM, oldAlarm); } #endif if (!hent) { // can't lookup name -- return in standard dot notation return std::string(inet_ntoa(addr)); } return std::string(hent->h_name); } const std::string Address::getHostName(const std::string hostname) // const { char myname[MAXHOSTNAMELEN+1]; std::string name = hostname; if (name.length() <= 0) { if (gethostname(myname, sizeof(myname)) >= 0) name = std::string(myname); } if (name.length() <= 0) { return std::string(""); } struct hostent* hent = gethostbyname(name.c_str()); if (!hent) { return std::string(""); } return std::string(hent->h_name); } void* Address::pack(void* _buf) const { unsigned char* buf = (unsigned char*)_buf; buf = (unsigned char*)nboPackUByte(_buf, 4); // everything in InAddr is already in network byte order int32_t hostaddr = int32_t(addr[0].s_addr); ::memcpy(buf, &hostaddr, sizeof(int32_t)); buf += sizeof(int32_t); return (void*)buf; } void* Address::unpack(void* _buf) { unsigned char* buf = (unsigned char*)_buf; InAddr tempAddr; // FIXME - should actually parse the first byte to see if it's IPv4 or // IPv6 ++buf; // everything in InAddr should be stored in network byte order int32_t hostaddr; ::memcpy(&hostaddr, buf, sizeof(int32_t)); buf += sizeof(int32_t); tempAddr.s_addr = u_long(hostaddr); addr.clear(); addr.push_back(tempAddr); return (void*)buf; } // // ServerId // void* ServerId::pack(void* _buf) const { // everything in PlayerId is already in network byte order unsigned char* buf = (unsigned char*)_buf; int32_t hostaddr = int32_t(serverHost.s_addr); ::memcpy(buf, &hostaddr, sizeof(int32_t)); buf += sizeof(int32_t); ::memcpy(buf, &port, sizeof(int16_t)); buf += sizeof(int16_t); ::memcpy(buf, &number, sizeof(int16_t)); buf += sizeof(int16_t); return (void*)buf; } void* ServerId::unpack(void* _buf) { // everything in ServerId should be stored in network byte order unsigned char* buf = (unsigned char*)_buf; int32_t hostaddr; ::memcpy(&hostaddr, buf, sizeof(int32_t)); buf += sizeof(int32_t); ::memcpy(&port, buf, sizeof(int16_t)); buf += sizeof(int16_t); ::memcpy(&number, buf, sizeof(int16_t)); buf += sizeof(int16_t); serverHost.s_addr = u_long(hostaddr); return (void*)buf; } bool ServerId::operator==(const ServerId& id) const { return serverHost.s_addr == id.serverHost.s_addr && port == id.port && number == id.number; } bool ServerId::operator!=(const ServerId& id) const { return serverHost.s_addr != id.serverHost.s_addr || port != id.port || number != id.number; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>organize includes properly (fixes vc5 link-time warnings)<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // bzflag common header #include "common.h" // interface header #include "Address.h" // system headers #include <string.h> #include <string> #include <sys/types.h> #if !defined(_WIN32) #include <unistd.h> #include <setjmp.h> #else #include <winsock2.h> #include <ws2tcpip.h> #endif // common implementation headers #include "bzsignal.h" #include "ErrorHandler.h" // local implementation headers #include "Pack.h" #if defined(sun) // Solaris... extern "C" int inet_aton(const char *, struct in_addr *); #endif // // Address // #if !defined( GUSI_20 ) && !defined( WIN32 ) Address Address::localAddress(""); #endif Address::Address() { InAddr tempAddr; memset(&tempAddr, 0, sizeof(tempAddr)); tempAddr.s_addr = htonl(INADDR_ANY); addr.push_back(tempAddr); } Address::Address(const std::string& name) { Address a = getHostAddress(name); addr.push_back(a.addr[0]); } Address::Address(const Address& address) : addr(address.addr) { // do nothing } Address::Address(const InAddr& _addr) { addr.push_back(_addr); } Address::Address(const struct sockaddr_in& _addr) { addr.push_back(_addr.sin_addr); } Address::~Address() { // do nothing } Address& Address::operator=(const Address& address) { addr.clear(); addr.push_back(address.addr[0]); return *this; } Address::operator InAddr() const { return addr[0]; } bool Address::operator==(const Address& address) const { return addr[0].s_addr == address.addr[0].s_addr; } bool Address::operator!=(const Address& address) const { return addr[0].s_addr != address.addr[0].s_addr; } bool Address::isAny() const { return addr[0].s_addr == htonl(INADDR_ANY); } std::string Address::getDotNotation() const { return std::string(inet_ntoa(addr[0])); } uint8_t Address::getIPVersion() const { return 4; } #if !defined(_WIN32) static jmp_buf alarmEnv; static void onAlarm(int) { // jump back to setjmp. this handles the race condition where we // set the alarm but gethostbyname() wouldn't have been called // until after the alarm goes off (resulting in an indeterminate // wait). longjmp(alarmEnv, 1); } #endif Address Address::getHostAddress(const std::string hname) { Address a; InAddr tempAddr; int j; struct hostent* hent; if (hname == "") { // local address char hostname[MAXHOSTNAMELEN+1]; if (gethostname(hostname, sizeof(hostname)) >= 0) hent = gethostbyname(hostname); else return a; } else if (inet_aton(hname.c_str(), &tempAddr) != 0) { a.addr.clear(); a.addr.push_back(tempAddr); return a; } else { // non-local address #if !defined(_WIN32) // set alarm to avoid waiting too long SIG_PF oldAlarm = bzSignal(SIGALRM, SIG_PF(onAlarm)); if (oldAlarm != SIG_ERR) { if (setjmp(alarmEnv) != 0) { // alarm went off hent = NULL; printError("Looking up host name: timeout"); return a; } // wait up to this many seconds alarm(8); } #endif hent = gethostbyname(hname.c_str()); #if !defined(_WIN32) if (oldAlarm != SIG_ERR) { alarm(0); bzSignal(SIGALRM, oldAlarm); } #endif } if (!hent) { herror("Looking up host name"); return a; } a.addr.clear(); for (j=0; hent->h_addr_list[j] != NULL; j++){ ::memcpy(&tempAddr, hent->h_addr_list[j], sizeof(tempAddr)); a.addr.push_back(tempAddr); } return a; } std::string Address::getHostByAddress(InAddr addr) { #if !defined(_WIN32) // set alarm to avoid waiting too long SIG_PF oldAlarm = bzSignal(SIGALRM, SIG_PF(onAlarm)); if (oldAlarm != SIG_ERR) { if (setjmp(alarmEnv) != 0) { // alarm went off return std::string(inet_ntoa(addr)); } // wait up to this many seconds alarm(8); } #endif int addrLen = sizeof(addr); struct hostent* hent = gethostbyaddr((char*)&addr, addrLen, AF_INET); #if !defined(_WIN32) if (oldAlarm != SIG_ERR) { alarm(0); bzSignal(SIGALRM, oldAlarm); } #endif if (!hent) { // can't lookup name -- return in standard dot notation return std::string(inet_ntoa(addr)); } return std::string(hent->h_name); } const std::string Address::getHostName(const std::string hostname) // const { char myname[MAXHOSTNAMELEN+1]; std::string name = hostname; if (name.length() <= 0) { if (gethostname(myname, sizeof(myname)) >= 0) name = std::string(myname); } if (name.length() <= 0) { return std::string(""); } struct hostent* hent = gethostbyname(name.c_str()); if (!hent) { return std::string(""); } return std::string(hent->h_name); } void* Address::pack(void* _buf) const { unsigned char* buf = (unsigned char*)_buf; buf = (unsigned char*)nboPackUByte(_buf, 4); // everything in InAddr is already in network byte order int32_t hostaddr = int32_t(addr[0].s_addr); ::memcpy(buf, &hostaddr, sizeof(int32_t)); buf += sizeof(int32_t); return (void*)buf; } void* Address::unpack(void* _buf) { unsigned char* buf = (unsigned char*)_buf; InAddr tempAddr; // FIXME - should actually parse the first byte to see if it's IPv4 or // IPv6 ++buf; // everything in InAddr should be stored in network byte order int32_t hostaddr; ::memcpy(&hostaddr, buf, sizeof(int32_t)); buf += sizeof(int32_t); tempAddr.s_addr = u_long(hostaddr); addr.clear(); addr.push_back(tempAddr); return (void*)buf; } // // ServerId // void* ServerId::pack(void* _buf) const { // everything in PlayerId is already in network byte order unsigned char* buf = (unsigned char*)_buf; int32_t hostaddr = int32_t(serverHost.s_addr); ::memcpy(buf, &hostaddr, sizeof(int32_t)); buf += sizeof(int32_t); ::memcpy(buf, &port, sizeof(int16_t)); buf += sizeof(int16_t); ::memcpy(buf, &number, sizeof(int16_t)); buf += sizeof(int16_t); return (void*)buf; } void* ServerId::unpack(void* _buf) { // everything in ServerId should be stored in network byte order unsigned char* buf = (unsigned char*)_buf; int32_t hostaddr; ::memcpy(&hostaddr, buf, sizeof(int32_t)); buf += sizeof(int32_t); ::memcpy(&port, buf, sizeof(int16_t)); buf += sizeof(int16_t); ::memcpy(&number, buf, sizeof(int16_t)); buf += sizeof(int16_t); serverHost.s_addr = u_long(hostaddr); return (void*)buf; } bool ServerId::operator==(const ServerId& id) const { return serverHost.s_addr == id.serverHost.s_addr && port == id.port && number == id.number; } bool ServerId::operator!=(const ServerId& id) const { return serverHost.s_addr != id.serverHost.s_addr || port != id.port || number != id.number; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include "vec4.h" namespace fd { namespace core { namespace math { vec4::vec4() : x(0), y(0), z(0), w(0) {} vec4::vec4(float32 x, float32 y, float32 z, float32 w) : x(x), y(y), z(z), w(w) {} #pragma region vec-vec //Asss //float32 vec4& vec4::Add(const vec4& v) { __m128 vxmm = _mm_set_ps(v.w, v.z, v.y, v.x); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_add_ps(xmm, vxmm); x = xmm.m128_f32[0]; y = xmm.m128_f32[1]; z = xmm.m128_f32[2]; w = xmm.m128_f32[3]; return *this; } //sub //float32 vec4& vec4::Sub(const vec4& v) { __m128 vxmm = _mm_set_ps(v.w, v.z, v.y, v.x); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_sub_ps(xmm, vxmm); x = xmm.m128_f32[0]; y = xmm.m128_f32[1]; z = xmm.m128_f32[2]; w = xmm.m128_f32[3]; return *this; } //Mul //float32 vec4& vec4::Mul(const vec4& v) { __m128 vxmm = _mm_set_ps(v.w, v.z, v.y, v.x); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_mul_ps(xmm, vxmm); x = xmm.m128_f32[0]; y = xmm.m128_f32[1]; z = xmm.m128_f32[2]; w = xmm.m128_f32[3]; return *this; } //Div //float32 vec4& vec4::Div(const vec4& v) { __m128 vxmm = _mm_set_ps(v.w, v.z, v.y, v.x); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_div_ps(xmm, vxmm); x = xmm.m128_f32[0]; y = xmm.m128_f32[1]; z = xmm.m128_f32[2]; w = xmm.m128_f32[3]; return *this; } #pragma endregion #pragma region vec-shit //Add //float32 vec4& vec4::Add(float32 v) { __m128 vxmm = _mm_set_ps(v, v, v, v); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_add_ps(xmm, vxmm); x = xmm.m128_f32[0]; y = xmm.m128_f32[1]; z = xmm.m128_f32[2]; w = xmm.m128_f32[3]; return *this; } //Sub //float32 vec4& vec4::Sub(float32 v) { __m128 vxmm = _mm_set_ps(v, v, v, v); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_sub_ps(xmm, vxmm); x = xmm.m128_f32[0]; y = xmm.m128_f32[1]; z = xmm.m128_f32[2]; w = xmm.m128_f32[3]; return *this; } //Mul //float32 vec4& vec4::Mul(float32 v) { __m128 vxmm = _mm_set_ps(v, v, v, v); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_mul_ps(xmm, vxmm); x = xmm.m128_f32[0]; y = xmm.m128_f32[1]; z = xmm.m128_f32[2]; w = xmm.m128_f32[3]; return *this; } //Div //float32 vec4& vec4::Div(float32 v) { __m128 vxmm = _mm_set_ps(v, v, v, v); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_div_ps(xmm, vxmm); x = xmm.m128_f32[0]; y = xmm.m128_f32[1]; z = xmm.m128_f32[2]; w = xmm.m128_f32[3]; return *this; } #pragma endregion } } }<commit_msg>LNX: vec4<commit_after>#include "vec4.h" namespace fd { namespace core { namespace math { vec4::vec4() : x(0), y(0), z(0), w(0) {} vec4::vec4(float32 x, float32 y, float32 z, float32 w) : x(x), y(y), z(z), w(w) {} #pragma region vec-vec //Asss //float32 vec4& vec4::Add(const vec4& v) { __m128 vxmm = _mm_set_ps(v.w, v.z, v.y, v.x); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_add_ps(xmm, vxmm); x = M128(xmm, 0); y = M128(xmm, 1); z = M128(xmm, 2); w = M128(xmm, 3); return *this; } //sub //float32 vec4& vec4::Sub(const vec4& v) { __m128 vxmm = _mm_set_ps(v.w, v.z, v.y, v.x); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_sub_ps(xmm, vxmm); x = M128(xmm, 0); y = M128(xmm, 1); z = M128(xmm, 2); w = M128(xmm, 3); return *this; } //Mul //float32 vec4& vec4::Mul(const vec4& v) { __m128 vxmm = _mm_set_ps(v.w, v.z, v.y, v.x); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_mul_ps(xmm, vxmm); x = M128(xmm, 0); y = M128(xmm, 1); z = M128(xmm, 2); w = M128(xmm, 3); return *this; } //Div //float32 vec4& vec4::Div(const vec4& v) { __m128 vxmm = _mm_set_ps(v.w, v.z, v.y, v.x); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_div_ps(xmm, vxmm); x = M128(xmm, 0); y = M128(xmm, 1); z = M128(xmm, 2); w = M128(xmm, 3); return *this; } #pragma endregion #pragma region vec-shit //Add //float32 vec4& vec4::Add(float32 v) { __m128 vxmm = _mm_set_ps(v, v, v, v); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_add_ps(xmm, vxmm); x = M128(xmm, 0); y = M128(xmm, 1); z = M128(xmm, 2); w = M128(xmm, 3); return *this; } //Sub //float32 vec4& vec4::Sub(float32 v) { __m128 vxmm = _mm_set_ps(v, v, v, v); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_sub_ps(xmm, vxmm); x = M128(xmm, 0); y = M128(xmm, 1); z = M128(xmm, 2); w = M128(xmm, 3); return *this; } //Mul //float32 vec4& vec4::Mul(float32 v) { __m128 vxmm = _mm_set_ps(v, v, v, v); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_mul_ps(xmm, vxmm); x = M128(xmm, 0); y = M128(xmm, 1); z = M128(xmm, 2); w = M128(xmm, 3); return *this; } //Div //float32 vec4& vec4::Div(float32 v) { __m128 vxmm = _mm_set_ps(v, v, v, v); __m128 xmm = _mm_set_ps(w, z, y, x); xmm = _mm_div_ps(xmm, vxmm); x = M128(xmm, 0); y = M128(xmm, 1); z = M128(xmm, 2); w = M128(xmm, 3); return *this; } #pragma endregion } } }<|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdlib.h> // For random. #include <cstdlib> #include <iostream> #include <thread> #include <mesos/executor.hpp> #include <stout/duration.hpp> #include <stout/lambda.hpp> #include <stout/os.hpp> using namespace mesos; using std::cout; using std::endl; using std::string; void run(ExecutorDriver* driver, const TaskInfo& task) { os::sleep(Seconds(random() % 10)); TaskStatus status; status.mutable_task_id()->MergeFrom(task.task_id()); status.set_state(TASK_FINISHED); driver->sendStatusUpdate(status); } class LongLivedExecutor : public Executor { public: virtual ~LongLivedExecutor() {} virtual void registered(ExecutorDriver* driver, const ExecutorInfo& executorInfo, const FrameworkInfo& frameworkInfo, const SlaveInfo& slaveInfo) { cout << "Registered executor on " << slaveInfo.hostname() << endl; } virtual void reregistered(ExecutorDriver* driver, const SlaveInfo& slaveInfo) { cout << "Re-registered executor on " << slaveInfo.hostname() << endl; } virtual void disconnected(ExecutorDriver* driver) {} virtual void launchTask(ExecutorDriver* driver, const TaskInfo& task) { cout << "Starting task " << task.task_id().value() << endl; std::thread* thread = new std::thread([=]() { run(driver, task); }); thread->detach(); TaskStatus status; status.mutable_task_id()->MergeFrom(task.task_id()); status.set_state(TASK_RUNNING); driver->sendStatusUpdate(status); } virtual void killTask(ExecutorDriver* driver, const TaskID& taskId) {} virtual void frameworkMessage(ExecutorDriver* driver, const string& data) {} virtual void shutdown(ExecutorDriver* driver) {} virtual void error(ExecutorDriver* driver, const string& message) {} }; int main(int argc, char** argv) { LongLivedExecutor executor; MesosExecutorDriver driver(&executor); return driver.run() == DRIVER_STOPPED ? 0 : 1; } <commit_msg>Fixed a memory leak in long lived executor.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdlib.h> // For random. #include <cstdlib> #include <iostream> #include <thread> #include <mesos/executor.hpp> #include <stout/duration.hpp> #include <stout/lambda.hpp> #include <stout/os.hpp> using namespace mesos; using std::cout; using std::endl; using std::string; void run(ExecutorDriver* driver, const TaskInfo& task) { os::sleep(Seconds(random() % 10)); TaskStatus status; status.mutable_task_id()->MergeFrom(task.task_id()); status.set_state(TASK_FINISHED); driver->sendStatusUpdate(status); } class LongLivedExecutor : public Executor { public: virtual ~LongLivedExecutor() {} virtual void registered(ExecutorDriver* driver, const ExecutorInfo& executorInfo, const FrameworkInfo& frameworkInfo, const SlaveInfo& slaveInfo) { cout << "Registered executor on " << slaveInfo.hostname() << endl; } virtual void reregistered(ExecutorDriver* driver, const SlaveInfo& slaveInfo) { cout << "Re-registered executor on " << slaveInfo.hostname() << endl; } virtual void disconnected(ExecutorDriver* driver) {} virtual void launchTask(ExecutorDriver* driver, const TaskInfo& task) { cout << "Starting task " << task.task_id().value() << endl; std::thread thread([=]() { run(driver, task); }); thread.detach(); TaskStatus status; status.mutable_task_id()->MergeFrom(task.task_id()); status.set_state(TASK_RUNNING); driver->sendStatusUpdate(status); } virtual void killTask(ExecutorDriver* driver, const TaskID& taskId) {} virtual void frameworkMessage(ExecutorDriver* driver, const string& data) {} virtual void shutdown(ExecutorDriver* driver) {} virtual void error(ExecutorDriver* driver, const string& message) {} }; int main(int argc, char** argv) { LongLivedExecutor executor; MesosExecutorDriver driver(&executor); return driver.run() == DRIVER_STOPPED ? 0 : 1; } <|endoftext|>
<commit_before>#include <osgGA/Version> const char* osgGAGetVersion() { return "1.2"; } const char* osgGAGetLibraryName() { return "OpenSceneGraph Gui Adapter Library"; } <commit_msg>Fixed version function names and comment strings<commit_after>#include <osgViewer/Version> const char* osgViewerGetVersion() { return "1.2"; } const char* osgViewerGetLibraryName() { return "OpenSceneGraph Viewer Library"; } <|endoftext|>
<commit_before>#include "output_hds.h" #include <mist/stream.h> #include <unistd.h> #include <mist/amf.h> #include <mist/mp4_adobe.h> namespace Mist { void OutHDS::getTracks(){ /// \todo Why do we have only one audio track option? videoTracks.clear(); audioTrack = 0; JSON::Value & vidCapa = capa["codecs"][0u][0u]; JSON::Value & audCapa = capa["codecs"][0u][1u]; for (std::map<int,DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++){ for (JSON::ArrIter itb = vidCapa.ArrBegin(); itb != vidCapa.ArrEnd(); itb++){ if (it->second.codec == (*itb).asStringRef()){ videoTracks.insert(it->first); break; } } if (!audioTrack){ for (JSON::ArrIter itb = audCapa.ArrBegin(); itb != audCapa.ArrEnd(); itb++){ if (it->second.codec == (*itb).asStringRef()){ audioTrack = it->first; break; } } } } } ///\brief Builds a bootstrap for use in HTTP Dynamic streaming. ///\param tid The track this bootstrap is generated for. ///\return The generated bootstrap. std::string OutHDS::dynamicBootstrap(int tid){ updateMeta(); std::string empty; MP4::ASRT asrt; asrt.setUpdate(false); asrt.setVersion(1); //asrt.setQualityEntry(empty, 0); if (myMeta.live){ asrt.setSegmentRun(1, 4294967295ul, 0); }else{ asrt.setSegmentRun(1, myMeta.tracks[tid].fragments.size(), 0); } MP4::AFRT afrt; afrt.setUpdate(false); afrt.setVersion(1); afrt.setTimeScale(1000); //afrt.setQualityEntry(empty, 0); MP4::afrt_runtable afrtrun; int i = 0; int j = 0; if (myMeta.tracks[tid].fragments.size()){ unsigned int firstTime = myMeta.tracks[tid].getKey(myMeta.tracks[tid].fragments.begin()->getNumber()).getTime(); for (std::deque<DTSC::Fragment>::iterator it = myMeta.tracks[tid].fragments.begin(); it != myMeta.tracks[tid].fragments.end(); it++){ if (myMeta.vod || it->getDuration() > 0){ afrtrun.firstFragment = myMeta.tracks[tid].missedFrags + j + 1; afrtrun.firstTimestamp = myMeta.tracks[tid].getKey(it->getNumber()).getTime() - firstTime; if (it->getDuration() > 0){ afrtrun.duration = it->getDuration(); }else{ afrtrun.duration = myMeta.tracks[tid].lastms - afrtrun.firstTimestamp; } afrt.setFragmentRun(afrtrun, i); i++; } j++; } } MP4::ABST abst; abst.setVersion(1); abst.setBootstrapinfoVersion(1); abst.setProfile(0); abst.setUpdate(false); abst.setTimeScale(1000); abst.setLive(myMeta.live); abst.setCurrentMediaTime(myMeta.tracks[tid].lastms); abst.setSmpteTimeCodeOffset(0); abst.setMovieIdentifier(streamName); abst.setSegmentRunTable(asrt, 0); abst.setFragmentRunTable(afrt, 0); DEBUG_MSG(DLVL_VERYHIGH, "Sending bootstrap: %s", abst.toPrettyString(0).c_str()); return std::string((char*)abst.asBox(), (int)abst.boxedSize()); } ///\brief Builds an index file for HTTP Dynamic streaming. ///\return The index file for HTTP Dynamic Streaming. std::string OutHDS::dynamicIndex(){ getTracks(); std::stringstream Result; Result << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << std::endl; Result << " <manifest xmlns=\"http://ns.adobe.com/f4m/1.0\">" << std::endl; Result << " <id>" << streamName << "</id>" << std::endl; Result << " <mimeType>video/mp4</mimeType>" << std::endl; Result << " <deliveryType>streaming</deliveryType>" << std::endl; if (myMeta.vod){ Result << " <duration>" << myMeta.tracks[*videoTracks.begin()].lastms / 1000 << ".000</duration>" << std::endl; Result << " <streamType>recorded</streamType>" << std::endl; }else{ Result << " <duration>0.00</duration>" << std::endl; Result << " <streamType>live</streamType>" << std::endl; } for (std::set<int>::iterator it = videoTracks.begin(); it != videoTracks.end(); it++){ Result << " <bootstrapInfo " "profile=\"named\" " "id=\"boot" << (*it) << "\" " "url=\"" << (*it) << ".abst\">" "</bootstrapInfo>" << std::endl; Result << " <media " "url=\"" << (*it) << "-\" " "bitrate=\"" << myMeta.tracks[(*it)].bps * 8 << "\" " "bootstrapInfoId=\"boot" << (*it) << "\" " "width=\"" << myMeta.tracks[(*it)].width << "\" " "height=\"" << myMeta.tracks[(*it)].height << "\">" << std::endl; Result << " <metadata>AgAKb25NZXRhRGF0YQMAAAk=</metadata>" << std::endl; Result << " </media>" << std::endl; } Result << "</manifest>" << std::endl; DEBUG_MSG(DLVL_HIGH, "Sending manifest: %s", Result.str().c_str()); return Result.str(); } //BuildManifest OutHDS::OutHDS(Socket::Connection & conn) : HTTPOutput(conn) { audioTrack = 0; playUntil = 0; } OutHDS::~OutHDS() {} void OutHDS::init(Util::Config * cfg){ HTTPOutput::init(cfg); capa["name"] = "HDS"; capa["desc"] = "Enables HTTP protocol Adobe-specific dynamic streaming (also known as HDS)."; capa["url_rel"] = "/dynamic/$/manifest.f4m"; capa["url_prefix"] = "/dynamic/$/"; capa["codecs"][0u][0u].append("H264"); capa["codecs"][0u][0u].append("H263"); capa["codecs"][0u][0u].append("VP6"); capa["codecs"][0u][0u].append("VP6Alpha"); capa["codecs"][0u][0u].append("ScreenVideo2"); capa["codecs"][0u][0u].append("ScreenVideo1"); capa["codecs"][0u][0u].append("JPEG"); capa["codecs"][0u][1u].append("AAC"); capa["codecs"][0u][1u].append("MP3"); capa["codecs"][0u][1u].append("Speex"); capa["codecs"][0u][1u].append("Nellymoser"); capa["codecs"][0u][1u].append("PCM"); capa["codecs"][0u][1u].append("ADPCM"); capa["codecs"][0u][1u].append("G711a"); capa["codecs"][0u][1u].append("G711mu"); capa["methods"][0u]["handler"] = "http"; capa["methods"][0u]["type"] = "flash/11"; capa["methods"][0u]["priority"] = 7ll; } void OutHDS::sendNext(){ if (currentPacket.getTime() >= playUntil){ DEBUG_MSG(DLVL_DEVEL, "(%d) Done sending fragment", getpid() ); stop(); wantRequest = true; H.Chunkify("", 0, myConn); return; } tag.DTSCLoader(currentPacket, myMeta.tracks[currentPacket.getTrackId()]); H.Chunkify(tag.data, tag.len, myConn); } void OutHDS::onHTTP(){ if (H.url.find(".abst") != std::string::npos){ initialize(); std::string streamID = H.url.substr(streamName.size() + 10); streamID = streamID.substr(0, streamID.find(".abst")); H.Clean(); H.SetBody(dynamicBootstrap(atoll(streamID.c_str()))); H.SetHeader("Content-Type", "binary/octet"); H.SetHeader("Cache-Control", "no-cache"); H.SendResponse("200", "OK", myConn); H.Clean(); //clean for any possible next requests return; } if (H.url.find("f4m") == std::string::npos){ initialize(); std::string tmp_qual = H.url.substr(H.url.find("/", 10) + 1); unsigned int tid; unsigned int fragNum; tid = atoi(tmp_qual.substr(0, tmp_qual.find("Seg") - 1).c_str()); int temp; temp = H.url.find("Seg") + 3; temp = H.url.find("Frag") + 4; fragNum = atoi(H.url.substr(temp).c_str()) - 1; DEBUG_MSG(DLVL_MEDIUM, "Video track %d, fragment %d\n", tid, fragNum); if (!audioTrack){getTracks();} unsigned int mstime = 0; unsigned int mslen = 0; if (fragNum < (unsigned int)myMeta.tracks[tid].missedFrags){ H.Clean(); H.SetBody("The requested fragment is no longer kept in memory on the server and cannot be served.\n"); H.SendResponse("412", "Fragment out of range", myConn); H.Clean(); //clean for any possible next requests std::cout << "Fragment " << fragNum << " too old" << std::endl; return; } if (fragNum > myMeta.tracks[tid].missedFrags + myMeta.tracks[tid].fragments.size() - 1){ H.Clean(); H.SetBody("Proxy, re-request this in a second or two.\n"); H.SendResponse("208", "Ask again later", myConn); H.Clean(); //clean for any possible next requests std::cout << "Fragment after fragment " << fragNum << " not available yet" << std::endl; return; } mstime = myMeta.tracks[tid].getKey(myMeta.tracks[tid].fragments[fragNum - myMeta.tracks[tid].missedFrags].getNumber()).getTime(); mslen = myMeta.tracks[tid].fragments[fragNum - myMeta.tracks[tid].missedFrags].getDuration(); selectedTracks.clear(); selectedTracks.insert(tid); if (audioTrack){ selectedTracks.insert(audioTrack); } seek(mstime); playUntil = mstime + mslen; H.Clean(); H.SetHeader("Content-Type", "video/mp4"); H.StartResponse(H, myConn); //send the bootstrap std::string bootstrap = dynamicBootstrap(tid); H.Chunkify(bootstrap, myConn); //send a zero-size mdat, meaning it stretches until end of file. H.Chunkify("\000\000\000\000mdat", 8, myConn); //send init data, if needed. if (audioTrack > 0 && myMeta.tracks[audioTrack].init != ""){ if (tag.DTSCAudioInit(myMeta.tracks[audioTrack])){ tag.tagTime(mstime); H.Chunkify(tag.data, tag.len, myConn); } } if (tid > 0){ if (tag.DTSCVideoInit(myMeta.tracks[tid])){ tag.tagTime(mstime); H.Chunkify(tag.data, tag.len, myConn); } } parseData = true; wantRequest = false; }else{ initialize(); std::stringstream tmpstr; myMeta.toPrettyString(tmpstr); H.Clean(); H.SetHeader("Content-Type", "text/xml"); H.SetHeader("Cache-Control", "no-cache"); H.SetBody(dynamicIndex()); H.SendResponse("200", "OK", myConn); } } } <commit_msg>Some minor optimizes to HDS fragment list generation.<commit_after>#include "output_hds.h" #include <mist/stream.h> #include <unistd.h> #include <mist/amf.h> #include <mist/mp4_adobe.h> namespace Mist { void OutHDS::getTracks(){ /// \todo Why do we have only one audio track option? videoTracks.clear(); audioTrack = 0; JSON::Value & vidCapa = capa["codecs"][0u][0u]; JSON::Value & audCapa = capa["codecs"][0u][1u]; for (std::map<int,DTSC::Track>::iterator it = myMeta.tracks.begin(); it != myMeta.tracks.end(); it++){ for (JSON::ArrIter itb = vidCapa.ArrBegin(); itb != vidCapa.ArrEnd(); itb++){ if (it->second.codec == (*itb).asStringRef()){ videoTracks.insert(it->first); break; } } if (!audioTrack){ for (JSON::ArrIter itb = audCapa.ArrBegin(); itb != audCapa.ArrEnd(); itb++){ if (it->second.codec == (*itb).asStringRef()){ audioTrack = it->first; break; } } } } } ///\brief Builds a bootstrap for use in HTTP Dynamic streaming. ///\param tid The track this bootstrap is generated for. ///\return The generated bootstrap. std::string OutHDS::dynamicBootstrap(int tid){ updateMeta(); std::string empty; MP4::ASRT asrt; asrt.setUpdate(false); asrt.setVersion(1); //asrt.setQualityEntry(empty, 0); if (myMeta.live){ asrt.setSegmentRun(1, 4294967295ul, 0); }else{ asrt.setSegmentRun(1, myMeta.tracks[tid].fragments.size(), 0); } MP4::AFRT afrt; afrt.setUpdate(false); afrt.setVersion(1); afrt.setTimeScale(1000); //afrt.setQualityEntry(empty, 0); MP4::afrt_runtable afrtrun; int i = 0; int j = 0; if (myMeta.tracks[tid].fragments.size()){ std::deque<DTSC::Fragment>::iterator fragIt = myMeta.tracks[tid].fragments.begin(); unsigned int firstTime = myMeta.tracks[tid].getKey(fragIt->getNumber()).getTime(); while (fragIt != myMeta.tracks[tid].fragments.end()){ if (myMeta.vod || fragIt->getDuration() > 0){ afrtrun.firstFragment = myMeta.tracks[tid].missedFrags + j + 1; afrtrun.firstTimestamp = myMeta.tracks[tid].getKey(fragIt->getNumber()).getTime() - firstTime; if (fragIt->getDuration() > 0){ afrtrun.duration = fragIt->getDuration(); }else{ afrtrun.duration = myMeta.tracks[tid].lastms - afrtrun.firstTimestamp; } afrt.setFragmentRun(afrtrun, i); ++i; } ++j; ++fragIt; } } MP4::ABST abst; abst.setVersion(1); abst.setBootstrapinfoVersion(1); abst.setProfile(0); abst.setUpdate(false); abst.setTimeScale(1000); abst.setLive(myMeta.live); abst.setCurrentMediaTime(myMeta.tracks[tid].lastms); abst.setSmpteTimeCodeOffset(0); abst.setMovieIdentifier(streamName); abst.setSegmentRunTable(asrt, 0); abst.setFragmentRunTable(afrt, 0); DEBUG_MSG(DLVL_VERYHIGH, "Sending bootstrap: %s", abst.toPrettyString(0).c_str()); return std::string((char*)abst.asBox(), (int)abst.boxedSize()); } ///\brief Builds an index file for HTTP Dynamic streaming. ///\return The index file for HTTP Dynamic Streaming. std::string OutHDS::dynamicIndex(){ getTracks(); std::stringstream Result; Result << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << std::endl; Result << " <manifest xmlns=\"http://ns.adobe.com/f4m/1.0\">" << std::endl; Result << " <id>" << streamName << "</id>" << std::endl; Result << " <mimeType>video/mp4</mimeType>" << std::endl; Result << " <deliveryType>streaming</deliveryType>" << std::endl; if (myMeta.vod){ Result << " <duration>" << myMeta.tracks[*videoTracks.begin()].lastms / 1000 << ".000</duration>" << std::endl; Result << " <streamType>recorded</streamType>" << std::endl; }else{ Result << " <duration>0.00</duration>" << std::endl; Result << " <streamType>live</streamType>" << std::endl; } for (std::set<int>::iterator it = videoTracks.begin(); it != videoTracks.end(); it++){ Result << " <bootstrapInfo " "profile=\"named\" " "id=\"boot" << (*it) << "\" " "url=\"" << (*it) << ".abst\">" "</bootstrapInfo>" << std::endl; Result << " <media " "url=\"" << (*it) << "-\" " "bitrate=\"" << myMeta.tracks[(*it)].bps * 8 << "\" " "bootstrapInfoId=\"boot" << (*it) << "\" " "width=\"" << myMeta.tracks[(*it)].width << "\" " "height=\"" << myMeta.tracks[(*it)].height << "\">" << std::endl; Result << " <metadata>AgAKb25NZXRhRGF0YQMAAAk=</metadata>" << std::endl; Result << " </media>" << std::endl; } Result << "</manifest>" << std::endl; DEBUG_MSG(DLVL_HIGH, "Sending manifest: %s", Result.str().c_str()); return Result.str(); } //BuildManifest OutHDS::OutHDS(Socket::Connection & conn) : HTTPOutput(conn) { audioTrack = 0; playUntil = 0; } OutHDS::~OutHDS() {} void OutHDS::init(Util::Config * cfg){ HTTPOutput::init(cfg); capa["name"] = "HDS"; capa["desc"] = "Enables HTTP protocol Adobe-specific dynamic streaming (also known as HDS)."; capa["url_rel"] = "/dynamic/$/manifest.f4m"; capa["url_prefix"] = "/dynamic/$/"; capa["codecs"][0u][0u].append("H264"); capa["codecs"][0u][0u].append("H263"); capa["codecs"][0u][0u].append("VP6"); capa["codecs"][0u][0u].append("VP6Alpha"); capa["codecs"][0u][0u].append("ScreenVideo2"); capa["codecs"][0u][0u].append("ScreenVideo1"); capa["codecs"][0u][0u].append("JPEG"); capa["codecs"][0u][1u].append("AAC"); capa["codecs"][0u][1u].append("MP3"); capa["codecs"][0u][1u].append("Speex"); capa["codecs"][0u][1u].append("Nellymoser"); capa["codecs"][0u][1u].append("PCM"); capa["codecs"][0u][1u].append("ADPCM"); capa["codecs"][0u][1u].append("G711a"); capa["codecs"][0u][1u].append("G711mu"); capa["methods"][0u]["handler"] = "http"; capa["methods"][0u]["type"] = "flash/11"; capa["methods"][0u]["priority"] = 7ll; } void OutHDS::sendNext(){ if (currentPacket.getTime() >= playUntil){ DEBUG_MSG(DLVL_DEVEL, "(%d) Done sending fragment", getpid() ); stop(); wantRequest = true; H.Chunkify("", 0, myConn); return; } tag.DTSCLoader(currentPacket, myMeta.tracks[currentPacket.getTrackId()]); H.Chunkify(tag.data, tag.len, myConn); } void OutHDS::onHTTP(){ if (H.url.find(".abst") != std::string::npos){ initialize(); std::string streamID = H.url.substr(streamName.size() + 10); streamID = streamID.substr(0, streamID.find(".abst")); H.Clean(); H.SetBody(dynamicBootstrap(atoll(streamID.c_str()))); H.SetHeader("Content-Type", "binary/octet"); H.SetHeader("Cache-Control", "no-cache"); H.SendResponse("200", "OK", myConn); H.Clean(); //clean for any possible next requests return; } if (H.url.find("f4m") == std::string::npos){ initialize(); std::string tmp_qual = H.url.substr(H.url.find("/", 10) + 1); unsigned int tid; unsigned int fragNum; tid = atoi(tmp_qual.substr(0, tmp_qual.find("Seg") - 1).c_str()); int temp; temp = H.url.find("Seg") + 3; temp = H.url.find("Frag") + 4; fragNum = atoi(H.url.substr(temp).c_str()) - 1; DEBUG_MSG(DLVL_MEDIUM, "Video track %d, fragment %d\n", tid, fragNum); if (!audioTrack){getTracks();} unsigned int mstime = 0; unsigned int mslen = 0; if (fragNum < (unsigned int)myMeta.tracks[tid].missedFrags){ H.Clean(); H.SetBody("The requested fragment is no longer kept in memory on the server and cannot be served.\n"); H.SendResponse("412", "Fragment out of range", myConn); H.Clean(); //clean for any possible next requests std::cout << "Fragment " << fragNum << " too old" << std::endl; return; } if (fragNum > myMeta.tracks[tid].missedFrags + myMeta.tracks[tid].fragments.size() - 1){ H.Clean(); H.SetBody("Proxy, re-request this in a second or two.\n"); H.SendResponse("208", "Ask again later", myConn); H.Clean(); //clean for any possible next requests std::cout << "Fragment after fragment " << fragNum << " not available yet" << std::endl; return; } mstime = myMeta.tracks[tid].getKey(myMeta.tracks[tid].fragments[fragNum - myMeta.tracks[tid].missedFrags].getNumber()).getTime(); mslen = myMeta.tracks[tid].fragments[fragNum - myMeta.tracks[tid].missedFrags].getDuration(); selectedTracks.clear(); selectedTracks.insert(tid); if (audioTrack){ selectedTracks.insert(audioTrack); } seek(mstime); playUntil = mstime + mslen; H.Clean(); H.SetHeader("Content-Type", "video/mp4"); H.StartResponse(H, myConn); //send the bootstrap std::string bootstrap = dynamicBootstrap(tid); H.Chunkify(bootstrap, myConn); //send a zero-size mdat, meaning it stretches until end of file. H.Chunkify("\000\000\000\000mdat", 8, myConn); //send init data, if needed. if (audioTrack > 0 && myMeta.tracks[audioTrack].init != ""){ if (tag.DTSCAudioInit(myMeta.tracks[audioTrack])){ tag.tagTime(mstime); H.Chunkify(tag.data, tag.len, myConn); } } if (tid > 0){ if (tag.DTSCVideoInit(myMeta.tracks[tid])){ tag.tagTime(mstime); H.Chunkify(tag.data, tag.len, myConn); } } parseData = true; wantRequest = false; }else{ initialize(); std::stringstream tmpstr; myMeta.toPrettyString(tmpstr); H.Clean(); H.SetHeader("Content-Type", "text/xml"); H.SetHeader("Cache-Control", "no-cache"); H.SetBody(dynamicIndex()); H.SendResponse("200", "OK", myConn); } } } <|endoftext|>
<commit_before>#include "configmanager.h" #include "common/logger/logger.h" using namespace std; string ConfigManager::defaultPath = ""; ConfigManager::ConfigManager() { QString path = QDir::currentPath(); path += "/config.xml"; defaultPath = path.toStdString(); } bool ConfigManager::load(std::string path) { if(!path.empty()) defaultPath = path; QFile file(QString(defaultPath.c_str())); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { stringstream msg; msg << "[ConfigManager] Could not open config file: " << defaultPath; Logger::Log(LogLevel::Warning, msg.str()); return false; } if(!xmlFile.setContent(&file)) { stringstream msg; msg << "[ConfigManager] Could not parse config file: " << defaultPath; Logger::Log(LogLevel::Warning, msg.str()); xmlFile.setContent(tr("<config>\n</config>")); return false; } file.close(); StructureChanged(); return true; } bool ConfigManager::save(string path) { if(path.empty()) path = defaultPath; QFile file(QString(path.c_str())); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { stringstream msg; msg << "[ConfigManager] Could not open file for saving."; Logger::Log(LogLevel::Warning, msg.str()); return false; } QTextStream fileStream(&file); xmlFile.save(fileStream, 4); return true; } int ConfigManager::numberOfCategories() { return xmlFile.documentElement().childNodes().count(); } int ConfigManager::numberOfValues(string category) { if(!xmlFile.documentElement().firstChildElement(category.c_str()).isNull()) return xmlFile.documentElement().firstChildElement(category.c_str()).childNodes().count(); else return -1; } int ConfigManager::numberOfValues(int categoryIndex) { if(categoryIndex < 0 || categoryIndex >= xmlFile.documentElement().childNodes().count()) { return -1; } else { return xmlFile.documentElement().childNodes().at(categoryIndex).childNodes().count(); } } string ConfigManager::categoryLabel(int categoryInd) { if(categoryInd < xmlFile.documentElement().childNodes().count()) { return xmlFile.documentElement().childNodes().at(categoryInd).nodeName().toStdString(); } return ""; } string ConfigManager::valueLabel(int categoryInd, int valueInd) { QDomElement root = xmlFile.documentElement(); if(categoryInd < root.childNodes().count()) { QDomNode categoryNode = root.childNodes().at(categoryInd); if(valueInd < categoryNode.childNodes().count()) { return categoryNode.childNodes().at(valueInd).nodeName().toStdString(); } } return ""; } <commit_msg>ConfigManager now correctly fills XML structure when file could not be loaded.<commit_after>#include "configmanager.h" #include "common/logger/logger.h" using namespace std; string ConfigManager::defaultPath = ""; ConfigManager::ConfigManager() { QString path = QDir::currentPath(); path += "/config.xml"; defaultPath = path.toStdString(); } bool ConfigManager::load(std::string path) { if(!path.empty()) defaultPath = path; QFile file(QString(defaultPath.c_str())); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { stringstream msg; msg << "[ConfigManager] Could not open config file: " << defaultPath; Logger::Log(LogLevel::Warning, msg.str()); xmlFile.setContent(tr("<config>\n</config>")); return false; } if(!xmlFile.setContent(&file)) { stringstream msg; msg << "[ConfigManager] Could not parse config file: " << defaultPath; Logger::Log(LogLevel::Warning, msg.str()); xmlFile.setContent(tr("<config>\n</config>")); return false; } file.close(); StructureChanged(); return true; } bool ConfigManager::save(string path) { if(path.empty()) path = defaultPath; QFile file(QString(path.c_str())); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { stringstream msg; msg << "[ConfigManager] Could not open file for saving."; Logger::Log(LogLevel::Warning, msg.str()); return false; } QTextStream fileStream(&file); xmlFile.save(fileStream, 4); return true; } int ConfigManager::numberOfCategories() { return xmlFile.documentElement().childNodes().count(); } int ConfigManager::numberOfValues(string category) { if(!xmlFile.documentElement().firstChildElement(category.c_str()).isNull()) return xmlFile.documentElement().firstChildElement(category.c_str()).childNodes().count(); else return -1; } int ConfigManager::numberOfValues(int categoryIndex) { if(categoryIndex < 0 || categoryIndex >= xmlFile.documentElement().childNodes().count()) { return -1; } else { return xmlFile.documentElement().childNodes().at(categoryIndex).childNodes().count(); } } string ConfigManager::categoryLabel(int categoryInd) { if(categoryInd < xmlFile.documentElement().childNodes().count()) { return xmlFile.documentElement().childNodes().at(categoryInd).nodeName().toStdString(); } return ""; } string ConfigManager::valueLabel(int categoryInd, int valueInd) { QDomElement root = xmlFile.documentElement(); if(categoryInd < root.childNodes().count()) { QDomNode categoryNode = root.childNodes().at(categoryInd); if(valueInd < categoryNode.childNodes().count()) { return categoryNode.childNodes().at(valueInd).nodeName().toStdString(); } } return ""; } <|endoftext|>
<commit_before>// Copyright (c) 2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // memory_range_unittest.cc: Unit tests for google_breakpad::MemoryRange. #include "breakpad_googletest_includes.h" #include "common/memory_range.h" using google_breakpad::MemoryRange; using testing::Message; namespace { const u_int32_t kBuffer[10] = { 0 }; const size_t kBufferSize = sizeof(kBuffer); const u_int8_t* kBufferPointer = reinterpret_cast<const u_int8_t*>(kBuffer); // Test vectors for verifying Covers, GetData, and Subrange. const struct { bool valid; size_t offset; size_t length; } kSubranges[] = { { true, 0, 0 }, { true, 0, 2 }, { true, 0, kBufferSize }, { true, 2, 0 }, { true, 2, 4 }, { true, 2, kBufferSize - 2 }, { true, kBufferSize - 1, 1 }, { false, kBufferSize, 0 }, { false, kBufferSize, -1 }, { false, kBufferSize + 1, 0 }, { false, -1, 2 }, { false, 1, kBufferSize }, { false, kBufferSize - 1, 2 }, { false, 0, -1 }, { false, 1, -1 }, }; const size_t kNumSubranges = sizeof(kSubranges) / sizeof(kSubranges[0]); // Test vectors for verifying GetArrayElement. const struct { size_t offset; size_t size; size_t index; const void* const pointer; } kElements[] = { // Valid array elemenets { 0, 1, 0, kBufferPointer }, { 0, 1, 1, kBufferPointer + 1 }, { 0, 1, kBufferSize - 1, kBufferPointer + kBufferSize - 1 }, { 0, 2, 1, kBufferPointer + 2 }, { 0, 4, 2, kBufferPointer + 8 }, { 0, 4, 9, kBufferPointer + 36 }, { kBufferSize - 1, 1, 0, kBufferPointer + kBufferSize - 1 }, // Invalid array elemenets { 0, 1, kBufferSize, NULL }, { 0, 4, 10, NULL }, { kBufferSize - 1, 1, 1, NULL }, { kBufferSize - 1, 2, 0, NULL }, { kBufferSize, 1, 0, NULL }, }; const size_t kNumElements = sizeof(kElements) / sizeof(kElements[0]); } // namespace TEST(MemoryRangeTest, DefaultConstructor) { MemoryRange range; EXPECT_EQ(NULL, range.data()); EXPECT_EQ(0, range.length()); } TEST(MemoryRangeTest, ConstructorWithDataAndLength) { MemoryRange range(kBuffer, kBufferSize); EXPECT_EQ(kBufferPointer, range.data()); EXPECT_EQ(kBufferSize, range.length()); } TEST(MemoryRangeTest, Reset) { MemoryRange range; range.Reset(); EXPECT_EQ(NULL, range.data()); EXPECT_EQ(0, range.length()); range.Set(kBuffer, kBufferSize); EXPECT_EQ(kBufferPointer, range.data()); EXPECT_EQ(kBufferSize, range.length()); range.Reset(); EXPECT_EQ(NULL, range.data()); EXPECT_EQ(0, range.length()); } TEST(MemoryRangeTest, Set) { MemoryRange range; range.Set(kBuffer, kBufferSize); EXPECT_EQ(kBufferPointer, range.data()); EXPECT_EQ(kBufferSize, range.length()); range.Set(NULL, 0); EXPECT_EQ(NULL, range.data()); EXPECT_EQ(0, range.length()); } TEST(MemoryRangeTest, SubrangeOfEmptyMemoryRange) { MemoryRange range; MemoryRange subrange = range.Subrange(0, 10); EXPECT_EQ(NULL, subrange.data()); EXPECT_EQ(0, subrange.length()); } TEST(MemoryRangeTest, SubrangeAndGetData) { MemoryRange range(kBuffer, kBufferSize); for (size_t i = 0; i < kNumSubranges; ++i) { bool valid = kSubranges[i].valid; size_t sub_offset = kSubranges[i].offset; size_t sub_length = kSubranges[i].length; SCOPED_TRACE(Message() << "offset=" << sub_offset << ", length=" << sub_length); MemoryRange subrange = range.Subrange(sub_offset, sub_length); if (valid) { EXPECT_TRUE(range.Covers(sub_offset, sub_length)); EXPECT_EQ(kBufferPointer + sub_offset, range.GetData(sub_offset, sub_length)); EXPECT_EQ(kBufferPointer + sub_offset, subrange.data()); EXPECT_EQ(sub_length, subrange.length()); } else { EXPECT_FALSE(range.Covers(sub_offset, sub_length)); EXPECT_EQ(NULL, range.GetData(sub_offset, sub_length)); EXPECT_EQ(NULL, subrange.data()); EXPECT_EQ(0, subrange.length()); } } } TEST(MemoryRangeTest, GetDataWithTemplateType) { MemoryRange range(kBuffer, kBufferSize); const char* char_pointer = range.GetData<char>(0); EXPECT_EQ(reinterpret_cast<const char*>(kBufferPointer), char_pointer); const int* int_pointer = range.GetData<int>(0); EXPECT_EQ(reinterpret_cast<const int*>(kBufferPointer), int_pointer); } TEST(MemoryRangeTest, GetArrayElement) { MemoryRange range(kBuffer, kBufferSize); for (size_t i = 0; i < kNumElements; ++i) { size_t element_offset = kElements[i].offset; size_t element_size = kElements[i].size; unsigned element_index = kElements[i].index; const void* const element_pointer = kElements[i].pointer; SCOPED_TRACE(Message() << "offset=" << element_offset << ", size=" << element_size << ", index=" << element_index); EXPECT_EQ(element_pointer, range.GetArrayElement( element_offset, element_size, element_index)); } } TEST(MemoryRangeTest, GetArrayElmentWithTemplateType) { MemoryRange range(kBuffer, kBufferSize); const char* char_pointer = range.GetArrayElement<char>(0, 0); EXPECT_EQ(reinterpret_cast<const char*>(kBufferPointer), char_pointer); const int* int_pointer = range.GetArrayElement<int>(0, 0); EXPECT_EQ(reinterpret_cast<const int*>(kBufferPointer), int_pointer); } <commit_msg>Clean up warnings about narrowing conversion<commit_after>// Copyright (c) 2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // memory_range_unittest.cc: Unit tests for google_breakpad::MemoryRange. #include "breakpad_googletest_includes.h" #include "common/memory_range.h" using google_breakpad::MemoryRange; using testing::Message; namespace { const u_int32_t kBuffer[10] = { 0 }; const size_t kBufferSize = sizeof(kBuffer); const u_int8_t* kBufferPointer = reinterpret_cast<const u_int8_t*>(kBuffer); // Test vectors for verifying Covers, GetData, and Subrange. const struct { bool valid; size_t offset; size_t length; } kSubranges[] = { { true, 0, 0 }, { true, 0, 2 }, { true, 0, kBufferSize }, { true, 2, 0 }, { true, 2, 4 }, { true, 2, kBufferSize - 2 }, { true, kBufferSize - 1, 1 }, { false, kBufferSize, 0 }, { false, kBufferSize, static_cast<size_t>(-1) }, { false, kBufferSize + 1, 0 }, { false, static_cast<size_t>(-1), 2 }, { false, 1, kBufferSize }, { false, kBufferSize - 1, 2 }, { false, 0, static_cast<size_t>(-1) }, { false, 1, static_cast<size_t>(-1) }, }; const size_t kNumSubranges = sizeof(kSubranges) / sizeof(kSubranges[0]); // Test vectors for verifying GetArrayElement. const struct { size_t offset; size_t size; size_t index; const void* const pointer; } kElements[] = { // Valid array elemenets { 0, 1, 0, kBufferPointer }, { 0, 1, 1, kBufferPointer + 1 }, { 0, 1, kBufferSize - 1, kBufferPointer + kBufferSize - 1 }, { 0, 2, 1, kBufferPointer + 2 }, { 0, 4, 2, kBufferPointer + 8 }, { 0, 4, 9, kBufferPointer + 36 }, { kBufferSize - 1, 1, 0, kBufferPointer + kBufferSize - 1 }, // Invalid array elemenets { 0, 1, kBufferSize, NULL }, { 0, 4, 10, NULL }, { kBufferSize - 1, 1, 1, NULL }, { kBufferSize - 1, 2, 0, NULL }, { kBufferSize, 1, 0, NULL }, }; const size_t kNumElements = sizeof(kElements) / sizeof(kElements[0]); } // namespace TEST(MemoryRangeTest, DefaultConstructor) { MemoryRange range; EXPECT_EQ(NULL, range.data()); EXPECT_EQ(0, range.length()); } TEST(MemoryRangeTest, ConstructorWithDataAndLength) { MemoryRange range(kBuffer, kBufferSize); EXPECT_EQ(kBufferPointer, range.data()); EXPECT_EQ(kBufferSize, range.length()); } TEST(MemoryRangeTest, Reset) { MemoryRange range; range.Reset(); EXPECT_EQ(NULL, range.data()); EXPECT_EQ(0, range.length()); range.Set(kBuffer, kBufferSize); EXPECT_EQ(kBufferPointer, range.data()); EXPECT_EQ(kBufferSize, range.length()); range.Reset(); EXPECT_EQ(NULL, range.data()); EXPECT_EQ(0, range.length()); } TEST(MemoryRangeTest, Set) { MemoryRange range; range.Set(kBuffer, kBufferSize); EXPECT_EQ(kBufferPointer, range.data()); EXPECT_EQ(kBufferSize, range.length()); range.Set(NULL, 0); EXPECT_EQ(NULL, range.data()); EXPECT_EQ(0, range.length()); } TEST(MemoryRangeTest, SubrangeOfEmptyMemoryRange) { MemoryRange range; MemoryRange subrange = range.Subrange(0, 10); EXPECT_EQ(NULL, subrange.data()); EXPECT_EQ(0, subrange.length()); } TEST(MemoryRangeTest, SubrangeAndGetData) { MemoryRange range(kBuffer, kBufferSize); for (size_t i = 0; i < kNumSubranges; ++i) { bool valid = kSubranges[i].valid; size_t sub_offset = kSubranges[i].offset; size_t sub_length = kSubranges[i].length; SCOPED_TRACE(Message() << "offset=" << sub_offset << ", length=" << sub_length); MemoryRange subrange = range.Subrange(sub_offset, sub_length); if (valid) { EXPECT_TRUE(range.Covers(sub_offset, sub_length)); EXPECT_EQ(kBufferPointer + sub_offset, range.GetData(sub_offset, sub_length)); EXPECT_EQ(kBufferPointer + sub_offset, subrange.data()); EXPECT_EQ(sub_length, subrange.length()); } else { EXPECT_FALSE(range.Covers(sub_offset, sub_length)); EXPECT_EQ(NULL, range.GetData(sub_offset, sub_length)); EXPECT_EQ(NULL, subrange.data()); EXPECT_EQ(0, subrange.length()); } } } TEST(MemoryRangeTest, GetDataWithTemplateType) { MemoryRange range(kBuffer, kBufferSize); const char* char_pointer = range.GetData<char>(0); EXPECT_EQ(reinterpret_cast<const char*>(kBufferPointer), char_pointer); const int* int_pointer = range.GetData<int>(0); EXPECT_EQ(reinterpret_cast<const int*>(kBufferPointer), int_pointer); } TEST(MemoryRangeTest, GetArrayElement) { MemoryRange range(kBuffer, kBufferSize); for (size_t i = 0; i < kNumElements; ++i) { size_t element_offset = kElements[i].offset; size_t element_size = kElements[i].size; unsigned element_index = kElements[i].index; const void* const element_pointer = kElements[i].pointer; SCOPED_TRACE(Message() << "offset=" << element_offset << ", size=" << element_size << ", index=" << element_index); EXPECT_EQ(element_pointer, range.GetArrayElement( element_offset, element_size, element_index)); } } TEST(MemoryRangeTest, GetArrayElmentWithTemplateType) { MemoryRange range(kBuffer, kBufferSize); const char* char_pointer = range.GetArrayElement<char>(0, 0); EXPECT_EQ(reinterpret_cast<const char*>(kBufferPointer), char_pointer); const int* int_pointer = range.GetArrayElement<int>(0, 0); EXPECT_EQ(reinterpret_cast<const int*>(kBufferPointer), int_pointer); } <|endoftext|>
<commit_before>// v8 #include <v8.h> // node #include <node.h> #include <node_version.h> // node-mapnik #include "mapnik_vector_tile.hpp" #include "mapnik_map.hpp" #include "mapnik_color.hpp" #include "mapnik_geometry.hpp" #include "mapnik_feature.hpp" #include "mapnik_fonts.hpp" #include "mapnik_plugins.hpp" #include "mapnik_palette.hpp" #include "mapnik_projection.hpp" #include "mapnik_proj_transform.hpp" #include "mapnik_layer.hpp" #include "mapnik_datasource.hpp" #include "mapnik_featureset.hpp" //#include "mapnik_js_datasource.hpp" #include "mapnik_memory_datasource.hpp" #include "mapnik_image.hpp" #include "mapnik_image_view.hpp" #include "mapnik_grid.hpp" #include "mapnik_cairo_surface.hpp" #include "mapnik_grid_view.hpp" #include "mapnik_expression.hpp" #include "utils.hpp" #ifdef MAPNIK_DEBUG #include <libxml/parser.h> #endif // mapnik #include <mapnik/config.hpp> // for MAPNIK_DECL #include <mapnik/version.hpp> #if MAPNIK_VERSION >= 200100 #include <mapnik/marker_cache.hpp> #include <mapnik/mapped_memory_cache.hpp> #include <mapnik/image_compositing.hpp> #endif // boost #include <boost/version.hpp> // cairo #if defined(HAVE_CAIRO) #include <cairo.h> #endif namespace node_mapnik { using namespace node; using namespace v8; /** * Optional notification that the embedder is idle. * V8 uses the notification to reduce memory footprint. * This call can be used repeatedly if the embedder remains idle. * Returns true if the embedder should stop calling IdleNotification * until real work has been done. This indicates that V8 has done * as much cleanup as it will be able to do. */ static Handle<Value> gc(const Arguments& args) { HandleScope scope; return scope.Close(Boolean::New(V8::IdleNotification())); } static std::string format_version(int version) { std::ostringstream s; s << version/100000 << "." << version/100 % 1000 << "." << version % 100; return s.str(); } static Handle<Value> clearCache(const Arguments& args) { HandleScope scope; #if MAPNIK_VERSION >= 200200 mapnik::marker_cache::instance().clear(); mapnik::mapped_memory_cache::instance().clear(); #else #if MAPNIK_VERSION >= 200100 mapnik::marker_cache::instance()->clear(); mapnik::mapped_memory_cache::instance()->clear(); #endif #endif return Undefined(); } static Handle<Value> shutdown(const Arguments& args) { HandleScope scope; google::protobuf::ShutdownProtobufLibrary(); #ifdef MAPNIK_DEBUG // http://lists.fedoraproject.org/pipermail/devel/2010-January/129117.html xmlCleanupParser(); #endif return Undefined(); } extern "C" { static void InitMapnik (Handle<Object> target) { HandleScope scope; GOOGLE_PROTOBUF_VERIFY_VERSION; // module level functions NODE_SET_METHOD(target, "register_datasources", node_mapnik::register_datasources); NODE_SET_METHOD(target, "datasources", node_mapnik::available_input_plugins); NODE_SET_METHOD(target, "register_fonts", node_mapnik::register_fonts); NODE_SET_METHOD(target, "fonts", node_mapnik::available_font_faces); NODE_SET_METHOD(target, "fontFiles", node_mapnik::available_font_files); NODE_SET_METHOD(target, "clearCache", clearCache); NODE_SET_METHOD(target, "gc", gc); NODE_SET_METHOD(target, "shutdown",shutdown); // Classes VectorTile::Initialize(target); Map::Initialize(target); Color::Initialize(target); Geometry::Initialize(target); Feature::Initialize(target); Image::Initialize(target); ImageView::Initialize(target); Palette::Initialize(target); Projection::Initialize(target); ProjTransform::Initialize(target); Layer::Initialize(target); Grid::Initialize(target); GridView::Initialize(target); Datasource::Initialize(target); Featureset::Initialize(target); // Not production safe, so disabling indefinitely //JSDatasource::Initialize(target); MemoryDatasource::Initialize(target); Expression::Initialize(target); CairoSurface::Initialize(target); // versions of deps Local<Object> versions = Object::New(); versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1)); versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion())); versions->Set(String::NewSymbol("boost"), String::New(format_version(BOOST_VERSION).c_str())); versions->Set(String::NewSymbol("boost_number"), Integer::New(BOOST_VERSION)); versions->Set(String::NewSymbol("mapnik"), String::New(format_version(MAPNIK_VERSION).c_str())); versions->Set(String::NewSymbol("mapnik_number"), Integer::New(MAPNIK_VERSION)); #if defined(HAVE_CAIRO) versions->Set(String::NewSymbol("cairo"), String::New(CAIRO_VERSION_STRING)); #endif target->Set(String::NewSymbol("versions"), versions); // built in support Local<Object> supports = Object::New(); supports->Set(String::NewSymbol("grid"), True()); #if defined(HAVE_CAIRO) supports->Set(String::NewSymbol("cairo"), True()); #else supports->Set(String::NewSymbol("cairo"), False()); #endif #if defined(HAVE_JPEG) supports->Set(String::NewSymbol("jpeg"), True()); #else supports->Set(String::NewSymbol("jpeg"), False()); #endif target->Set(String::NewSymbol("supports"), supports); #if MAPNIK_VERSION >= 200100 Local<Object> composite_ops = Object::New(); NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "clear", mapnik::clear) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src", mapnik::src) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst", mapnik::dst) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_over", mapnik::src_over) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_over", mapnik::dst_over) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_in", mapnik::src_in) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_in", mapnik::dst_in) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_out", mapnik::src_out) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_out", mapnik::dst_out) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_atop", mapnik::src_atop) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_atop", mapnik::dst_atop) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "xor", mapnik::_xor) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "plus", mapnik::plus) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "minus", mapnik::minus) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "multiply", mapnik::multiply) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "screen", mapnik::screen) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "overlay", mapnik::overlay) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "darken", mapnik::darken) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "lighten", mapnik::lighten) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "color_dodge", mapnik::color_dodge) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "color_burn", mapnik::color_burn) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "hard_light", mapnik::hard_light) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "soft_light", mapnik::soft_light) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "difference", mapnik::difference) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "exclusion", mapnik::exclusion) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "contrast", mapnik::contrast) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "invert", mapnik::invert) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "invert_rgb", mapnik::invert_rgb) target->Set(String::NewSymbol("compositeOp"), composite_ops); #endif } } } // namespace node_mapnik #if NODE_VERSION_AT_LEAST(0, 9, 0) #define NODE_MAPNIK_MODULE(modname, regfunc) \ extern "C" { \ MAPNIK_EXP node::node_module_struct modname ## _module = \ { \ NODE_STANDARD_MODULE_STUFF, \ (node::addon_register_func)regfunc, \ NODE_STRINGIFY(modname) \ }; \ } #else #define NODE_MAPNIK_MODULE(modname, regfunc) \ extern "C" { \ MAPNIK_EXP node::node_module_struct modname ## _module = \ { \ NODE_STANDARD_MODULE_STUFF, \ regfunc, \ NODE_STRINGIFY(modname) \ }; \ } #endif NODE_MAPNIK_MODULE(_mapnik, node_mapnik::InitMapnik) <commit_msg>update composite ops and report image i/o availability correctly per Mapnik 2.3.x<commit_after>// v8 #include <v8.h> // node #include <node.h> #include <node_version.h> // node-mapnik #include "mapnik_vector_tile.hpp" #include "mapnik_map.hpp" #include "mapnik_color.hpp" #include "mapnik_geometry.hpp" #include "mapnik_feature.hpp" #include "mapnik_fonts.hpp" #include "mapnik_plugins.hpp" #include "mapnik_palette.hpp" #include "mapnik_projection.hpp" #include "mapnik_proj_transform.hpp" #include "mapnik_layer.hpp" #include "mapnik_datasource.hpp" #include "mapnik_featureset.hpp" //#include "mapnik_js_datasource.hpp" #include "mapnik_memory_datasource.hpp" #include "mapnik_image.hpp" #include "mapnik_image_view.hpp" #include "mapnik_grid.hpp" #include "mapnik_cairo_surface.hpp" #include "mapnik_grid_view.hpp" #include "mapnik_expression.hpp" #include "utils.hpp" #ifdef MAPNIK_DEBUG #include <libxml/parser.h> #endif // mapnik #include <mapnik/config.hpp> // for MAPNIK_DECL #include <mapnik/version.hpp> #if MAPNIK_VERSION >= 200100 #include <mapnik/marker_cache.hpp> #include <mapnik/mapped_memory_cache.hpp> #include <mapnik/image_compositing.hpp> #endif // boost #include <boost/version.hpp> // cairo #if defined(HAVE_CAIRO) #include <cairo.h> #endif namespace node_mapnik { using namespace node; using namespace v8; /** * Optional notification that the embedder is idle. * V8 uses the notification to reduce memory footprint. * This call can be used repeatedly if the embedder remains idle. * Returns true if the embedder should stop calling IdleNotification * until real work has been done. This indicates that V8 has done * as much cleanup as it will be able to do. */ static Handle<Value> gc(const Arguments& args) { HandleScope scope; return scope.Close(Boolean::New(V8::IdleNotification())); } static std::string format_version(int version) { std::ostringstream s; s << version/100000 << "." << version/100 % 1000 << "." << version % 100; return s.str(); } static Handle<Value> clearCache(const Arguments& args) { HandleScope scope; #if MAPNIK_VERSION >= 200200 mapnik::marker_cache::instance().clear(); mapnik::mapped_memory_cache::instance().clear(); #else #if MAPNIK_VERSION >= 200100 mapnik::marker_cache::instance()->clear(); mapnik::mapped_memory_cache::instance()->clear(); #endif #endif return Undefined(); } static Handle<Value> shutdown(const Arguments& args) { HandleScope scope; google::protobuf::ShutdownProtobufLibrary(); #ifdef MAPNIK_DEBUG // http://lists.fedoraproject.org/pipermail/devel/2010-January/129117.html xmlCleanupParser(); #endif return Undefined(); } extern "C" { static void InitMapnik (Handle<Object> target) { HandleScope scope; GOOGLE_PROTOBUF_VERIFY_VERSION; // module level functions NODE_SET_METHOD(target, "register_datasources", node_mapnik::register_datasources); NODE_SET_METHOD(target, "datasources", node_mapnik::available_input_plugins); NODE_SET_METHOD(target, "register_fonts", node_mapnik::register_fonts); NODE_SET_METHOD(target, "fonts", node_mapnik::available_font_faces); NODE_SET_METHOD(target, "fontFiles", node_mapnik::available_font_files); NODE_SET_METHOD(target, "clearCache", clearCache); NODE_SET_METHOD(target, "gc", gc); NODE_SET_METHOD(target, "shutdown",shutdown); // Classes VectorTile::Initialize(target); Map::Initialize(target); Color::Initialize(target); Geometry::Initialize(target); Feature::Initialize(target); Image::Initialize(target); ImageView::Initialize(target); Palette::Initialize(target); Projection::Initialize(target); ProjTransform::Initialize(target); Layer::Initialize(target); Grid::Initialize(target); GridView::Initialize(target); Datasource::Initialize(target); Featureset::Initialize(target); // Not production safe, so disabling indefinitely //JSDatasource::Initialize(target); MemoryDatasource::Initialize(target); Expression::Initialize(target); CairoSurface::Initialize(target); // versions of deps Local<Object> versions = Object::New(); versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1)); versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion())); versions->Set(String::NewSymbol("boost"), String::New(format_version(BOOST_VERSION).c_str())); versions->Set(String::NewSymbol("boost_number"), Integer::New(BOOST_VERSION)); versions->Set(String::NewSymbol("mapnik"), String::New(format_version(MAPNIK_VERSION).c_str())); versions->Set(String::NewSymbol("mapnik_number"), Integer::New(MAPNIK_VERSION)); #if defined(HAVE_CAIRO) versions->Set(String::NewSymbol("cairo"), String::New(CAIRO_VERSION_STRING)); #endif target->Set(String::NewSymbol("versions"), versions); // built in support // TODO - detect GRID_RENDERER once we require at least mapnik 2.3.x Local<Object> supports = Object::New(); supports->Set(String::NewSymbol("grid"), True()); #if defined(HAVE_CAIRO) supports->Set(String::NewSymbol("cairo"), True()); #else supports->Set(String::NewSymbol("cairo"), False()); #endif #if defined(HAVE_PNG) supports->Set(String::NewSymbol("png"), True()); #else supports->Set(String::NewSymbol("png"), False()); #endif #if defined(HAVE_JPEG) supports->Set(String::NewSymbol("jpeg"), True()); #else supports->Set(String::NewSymbol("jpeg"), False()); #endif #if defined(HAVE_TIFF) supports->Set(String::NewSymbol("tiff"), True()); #else supports->Set(String::NewSymbol("tiff"), False()); #endif #if defined(HAVE_WEBP) supports->Set(String::NewSymbol("webp"), True()); #else supports->Set(String::NewSymbol("webp"), False()); #endif target->Set(String::NewSymbol("supports"), supports); #if MAPNIK_VERSION >= 200100 Local<Object> composite_ops = Object::New(); NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "clear", mapnik::clear) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src", mapnik::src) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst", mapnik::dst) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_over", mapnik::src_over) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_over", mapnik::dst_over) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_in", mapnik::src_in) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_in", mapnik::dst_in) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_out", mapnik::src_out) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_out", mapnik::dst_out) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_atop", mapnik::src_atop) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_atop", mapnik::dst_atop) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "xor", mapnik::_xor) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "plus", mapnik::plus) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "minus", mapnik::minus) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "multiply", mapnik::multiply) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "screen", mapnik::screen) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "overlay", mapnik::overlay) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "darken", mapnik::darken) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "lighten", mapnik::lighten) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "color_dodge", mapnik::color_dodge) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "color_burn", mapnik::color_burn) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "hard_light", mapnik::hard_light) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "soft_light", mapnik::soft_light) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "difference", mapnik::difference) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "exclusion", mapnik::exclusion) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "contrast", mapnik::contrast) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "invert", mapnik::invert) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "grain_merge", mapnik::grain_merge) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "grain_extract", mapnik::grain_extract) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "hue", mapnik::hue) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "saturation", mapnik::saturation) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "color", mapnik::_color) NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "value", mapnik::_value) target->Set(String::NewSymbol("compositeOp"), composite_ops); #endif } } } // namespace node_mapnik #if NODE_VERSION_AT_LEAST(0, 9, 0) #define NODE_MAPNIK_MODULE(modname, regfunc) \ extern "C" { \ MAPNIK_EXP node::node_module_struct modname ## _module = \ { \ NODE_STANDARD_MODULE_STUFF, \ (node::addon_register_func)regfunc, \ NODE_STRINGIFY(modname) \ }; \ } #else #define NODE_MAPNIK_MODULE(modname, regfunc) \ extern "C" { \ MAPNIK_EXP node::node_module_struct modname ## _module = \ { \ NODE_STANDARD_MODULE_STUFF, \ regfunc, \ NODE_STRINGIFY(modname) \ }; \ } #endif NODE_MAPNIK_MODULE(_mapnik, node_mapnik::InitMapnik) <|endoftext|>
<commit_before>/* * PrimeNumberFinder.cpp -- This file is part of primesieve * * Copyright (C) 2011 Kim Walisch, <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "PrimeNumberFinder.h" #include "PrimeSieve.h" #include "ResetSieve.h" #include "SieveOfEratosthenes.h" #include "defs.h" #include "cpuid.h" #include "pmath.h" #include <cstdlib> #include <iostream> namespace { const uint32_t BYTE_SIZE = 256; const uint32_t END = 0xff; } const uint32_t PrimeNumberFinder::nextBitValue_[NUMBERS_PER_BYTE] = { 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 13, 0, 17, 0, 0, 0, 19, 0, 23, 0, 0, 0, 29, 0, 0, 0, 0, 0, 31 }; PrimeNumberFinder::PrimeNumberFinder(PrimeSieve* primeSieve, ResetSieve* resetSieve) : SieveOfEratosthenes( (primeSieve->startNumber_ < 7) ?7 :primeSieve->startNumber_, primeSieve->stopNumber_, primeSieve->sieveSize_, resetSieve), primeSieve_(primeSieve), primeByteCounts_(NULL), primeBitValues_(NULL) { if (isPOPCNTSupported()) primeSieve_->flags_ |= PrimeSieve::SSE4_POPCNT; this->initLookupTables(); } PrimeNumberFinder::~PrimeNumberFinder() { if (primeByteCounts_ != NULL) { for (uint32_t i = 0; i < COUNTS_SIZE; i++) delete[] primeByteCounts_[i]; delete[] primeByteCounts_; } if (primeBitValues_ != NULL) { for (uint32_t i = 0; i < BYTE_SIZE; i++) delete[] primeBitValues_[i]; delete[] primeBitValues_; } } /** * Initialize lookup tables needed to count and print primes. */ void PrimeNumberFinder::initLookupTables() { // bits and bitmasks representing the prime numbers and k-tuplets // within a byte of the sieve_ array const uint32_t bitmasks[COUNTS_SIZE][9] = { { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, END }, // prime numbers { 0x06, 0x18, 0xc0, END }, // twin primes { 0x07, 0x0e, 0x1c, 0x38, END }, // prime triplets { 0x1e, END }, // prime quadruplets { 0x1f, 0x3e, END }, // prime quintuplets { 0x3f, END }, // prime sextuplets { 0xfe, END } }; // prime septuplets if (primeSieve_->flags_ & PrimeSieve::COUNT_FLAGS) { primeByteCounts_ = new uint32_t*[COUNTS_SIZE]; for (uint32_t i = 0; i < COUNTS_SIZE; i++) { if ((primeSieve_->flags_ & (PrimeSieve::COUNT_PRIMES << i)) == 0) primeByteCounts_[i] = NULL; else { primeByteCounts_[i] = new uint32_t[BYTE_SIZE]; // save the count of bitmasks within each byte value for (uint32_t j = 0; j < BYTE_SIZE; j++) { uint32_t bitmaskCount = 0; for (const uint32_t* b = bitmasks[i]; *b != END; b++) { if ((j & *b) == *b) bitmaskCount++; } primeByteCounts_[i][j] = bitmaskCount; } } } } if (primeSieve_->flags_ & PrimeSieve::GENERATE_FLAGS) { uint32_t generateType = 0; if (primeSieve_->flags_ & PrimeSieve::PRINT_FLAGS) for (uint32_t i = PrimeSieve::PRINT_PRIMES; (i & primeSieve_->flags_) == 0; i <<= 1) generateType++; primeBitValues_ = new uint32_t*[BYTE_SIZE]; // generate the bitValues for each byte value for (uint32_t i = 0; i < BYTE_SIZE; i++) { primeBitValues_[i] = new uint32_t[9]; uint32_t bitmaskCount = 0; // save the bitValues of the current byte value for (const uint32_t* b = bitmasks[generateType]; *b != END; b++) { if ((i & *b) == *b) { primeBitValues_[i][bitmaskCount] = bitValues_[ntz(*b)]; bitmaskCount++; } } primeBitValues_[i][bitmaskCount] = END; } } } /** * Count the prime numbers and prime k-tuplets of the current segment. */ void PrimeNumberFinder::count(const uint8_t* sieve, uint32_t sieveSize) { // count prime numbers if (primeSieve_->flags_ & PrimeSieve::COUNT_PRIMES) { uint32_t primeCount = 0; uint32_t i = 0; #if defined(POPCNT64) // count bits using the SSE 4.2 POPCNT instruction if (primeSieve_->flags_ & PrimeSieve::SSE4_POPCNT) for (; i + 8 < sieveSize; i += 8) primeCount += POPCNT64(sieve, i); #endif // count bits using a lookup table for (; i < sieveSize; i++) primeCount += primeByteCounts_[0][sieve[i]]; primeSieve_->counts_[0] += primeCount; } // count prime k-tuplets for (uint32_t i = 1; i < COUNTS_SIZE; i++) { if (primeSieve_->flags_ & (PrimeSieve::COUNT_PRIMES << i)) { uint32_t kTupletCount = 0; for (uint32_t j = 0; j < sieveSize; j++) { kTupletCount += primeByteCounts_[i][sieve[j]]; } primeSieve_->counts_[i] += kTupletCount; } } } /** * Reconstructs prime numbers or prime k-tuplets (twin primes, prime * triplets, ...) from 1 bits after that all multiples have been * crossed off in the sieve array. */ void PrimeNumberFinder::generate(const uint8_t* sieve, uint32_t sieveSize) { uint64_t byteValue = this->getLowerBound(); // call a callback function (IMP) for each prime number if (primeSieve_->flags_ & PrimeSieve::CALLBACK_PRIMES_IMP) for (uint32_t i = 0; i < sieveSize; i++, byteValue += NUMBERS_PER_BYTE) for (uint32_t* bitValue = primeBitValues_[sieve[i]]; *bitValue != END; bitValue++) primeSieve_->callback_imp(byteValue + *bitValue); // call a callback function (OOP) for each prime number else if (primeSieve_->flags_ & PrimeSieve::CALLBACK_PRIMES_OOP) for (uint32_t i = 0; i < sieveSize; i++, byteValue += NUMBERS_PER_BYTE) for (uint32_t* bitValue = primeBitValues_[sieve[i]]; *bitValue != END; bitValue++) primeSieve_->callback_oop(byteValue + *bitValue, primeSieve_->cbObj_); // print the prime numbers to stdout else if (primeSieve_->flags_ & PrimeSieve::PRINT_PRIMES) for (uint32_t i = 0; i < sieveSize; i++, byteValue += NUMBERS_PER_BYTE) for (uint32_t* bitValue = primeBitValues_[sieve[i]]; *bitValue != END; bitValue++) std::cout << byteValue + *bitValue << '\n'; // print the prime k-tuplets to stdout else for (uint32_t i = 0; i < sieveSize; i++, byteValue += NUMBERS_PER_BYTE) for (uint32_t* bitValue = primeBitValues_[sieve[i]]; *bitValue != END; bitValue++) { std::cout << '('; uint32_t v = *bitValue; for (uint32_t j = PrimeSieve::PRINT_PRIMES; (j & primeSieve_->flags_) == 0; j <<= 1) { std::cout << byteValue + v << ", "; v = nextBitValue_[v]; } std::cout << byteValue + v << ")\n"; } } void PrimeNumberFinder::analyseSieve(const uint8_t* sieve, uint32_t sieveSize) { if (primeSieve_->flags_ & PrimeSieve::COUNT_FLAGS) this->count(sieve, sieveSize); if (primeSieve_->flags_ & PrimeSieve::GENERATE_FLAGS) this->generate(sieve, sieveSize); primeSieve_->parent_->doStatus(sieveSize * NUMBERS_PER_BYTE); } <commit_msg>updated documentation<commit_after>/* * PrimeNumberFinder.cpp -- This file is part of primesieve * * Copyright (C) 2011 Kim Walisch, <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "PrimeNumberFinder.h" #include "PrimeSieve.h" #include "ResetSieve.h" #include "SieveOfEratosthenes.h" #include "defs.h" #include "cpuid.h" #include "pmath.h" #include <algorithm> #include <cstdlib> #include <iostream> namespace { const uint32_t BYTE_SIZE = 256; const uint32_t END = 0xff; } const uint32_t PrimeNumberFinder::nextBitValue_[NUMBERS_PER_BYTE] = { 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 13, 0, 17, 0, 0, 0, 19, 0, 23, 0, 0, 0, 29, 0, 0, 0, 0, 0, 31 }; PrimeNumberFinder::PrimeNumberFinder(PrimeSieve* primeSieve, ResetSieve* resetSieve) : SieveOfEratosthenes( std::max<uint64_t>(primeSieve->startNumber_, 7), primeSieve->stopNumber_, primeSieve->sieveSize_, resetSieve), primeSieve_(primeSieve), primeByteCounts_(NULL), primeBitValues_(NULL) { if (isPOPCNTSupported()) primeSieve_->flags_ |= PrimeSieve::SSE4_POPCNT; this->initLookupTables(); } PrimeNumberFinder::~PrimeNumberFinder() { if (primeByteCounts_ != NULL) { for (uint32_t i = 0; i < COUNTS_SIZE; i++) delete[] primeByteCounts_[i]; delete[] primeByteCounts_; } if (primeBitValues_ != NULL) { for (uint32_t i = 0; i < BYTE_SIZE; i++) delete[] primeBitValues_[i]; delete[] primeBitValues_; } } /** * Initialize lookup tables needed to count and print primes. */ void PrimeNumberFinder::initLookupTables() { // bits and bitmasks representing the prime numbers and k-tuplets // within a byte of the sieve_ array const uint32_t bitmasks[COUNTS_SIZE][9] = { { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, END }, // prime numbers { 0x06, 0x18, 0xc0, END }, // twin primes { 0x07, 0x0e, 0x1c, 0x38, END }, // prime triplets { 0x1e, END }, // prime quadruplets { 0x1f, 0x3e, END }, // prime quintuplets { 0x3f, END }, // prime sextuplets { 0xfe, END } }; // prime septuplets if (primeSieve_->flags_ & PrimeSieve::COUNT_FLAGS) { primeByteCounts_ = new uint32_t*[COUNTS_SIZE]; for (uint32_t i = 0; i < COUNTS_SIZE; i++) { if ((primeSieve_->flags_ & (PrimeSieve::COUNT_PRIMES << i)) == 0) primeByteCounts_[i] = NULL; else { primeByteCounts_[i] = new uint32_t[BYTE_SIZE]; // save the count of bitmasks within each byte value for (uint32_t j = 0; j < BYTE_SIZE; j++) { uint32_t bitmaskCount = 0; for (const uint32_t* b = bitmasks[i]; *b != END; b++) { if ((j & *b) == *b) bitmaskCount++; } primeByteCounts_[i][j] = bitmaskCount; } } } } if (primeSieve_->flags_ & PrimeSieve::GENERATE_FLAGS) { uint32_t generateType = 0; if (primeSieve_->flags_ & PrimeSieve::PRINT_FLAGS) for (uint32_t i = PrimeSieve::PRINT_PRIMES; (i & primeSieve_->flags_) == 0; i <<= 1) generateType++; primeBitValues_ = new uint32_t*[BYTE_SIZE]; // generate the bitValues for each byte value for (uint32_t i = 0; i < BYTE_SIZE; i++) { primeBitValues_[i] = new uint32_t[9]; uint32_t bitmaskCount = 0; // save the bitValues of the current byte value for (const uint32_t* b = bitmasks[generateType]; *b != END; b++) { if ((i & *b) == *b) { primeBitValues_[i][bitmaskCount] = bitValues_[ntz(*b)]; bitmaskCount++; } } primeBitValues_[i][bitmaskCount] = END; } } } /** * Count the prime numbers and prime k-tuplets of the current segment. */ void PrimeNumberFinder::count(const uint8_t* sieve, uint32_t sieveSize) { // count prime numbers if (primeSieve_->flags_ & PrimeSieve::COUNT_PRIMES) { uint32_t primeCount = 0; uint32_t i = 0; #if defined(POPCNT64) // count bits using the SSE 4.2 POPCNT instruction if (primeSieve_->flags_ & PrimeSieve::SSE4_POPCNT) for (; i + 8 < sieveSize; i += 8) primeCount += POPCNT64(sieve, i); #endif // count bits using a lookup table for (; i < sieveSize; i++) primeCount += primeByteCounts_[0][sieve[i]]; primeSieve_->counts_[0] += primeCount; } // count prime k-tuplets for (uint32_t i = 1; i < COUNTS_SIZE; i++) { if (primeSieve_->flags_ & (PrimeSieve::COUNT_PRIMES << i)) { uint32_t kTupletCount = 0; for (uint32_t j = 0; j < sieveSize; j++) { kTupletCount += primeByteCounts_[i][sieve[j]]; } primeSieve_->counts_[i] += kTupletCount; } } } /** * Reconstructs prime numbers or prime k-tuplets (twin primes, prime * triplets, ...) from 1 bits after that all multiples have been * crossed off in the sieve array. */ void PrimeNumberFinder::generate(const uint8_t* sieve, uint32_t sieveSize) { uint64_t byteValue = this->getLowerBound(); // call a C style callback function for each prime number if (primeSieve_->flags_ & PrimeSieve::CALLBACK_PRIMES_IMP) for (uint32_t i = 0; i < sieveSize; i++, byteValue += NUMBERS_PER_BYTE) for (uint32_t* bitValue = primeBitValues_[sieve[i]]; *bitValue != END; bitValue++) primeSieve_->callback_imp(byteValue + *bitValue); // call an OOP style callback function for each prime number else if (primeSieve_->flags_ & PrimeSieve::CALLBACK_PRIMES_OOP) for (uint32_t i = 0; i < sieveSize; i++, byteValue += NUMBERS_PER_BYTE) for (uint32_t* bitValue = primeBitValues_[sieve[i]]; *bitValue != END; bitValue++) primeSieve_->callback_oop(byteValue + *bitValue, primeSieve_->cbObj_); // print the prime numbers to stdout else if (primeSieve_->flags_ & PrimeSieve::PRINT_PRIMES) for (uint32_t i = 0; i < sieveSize; i++, byteValue += NUMBERS_PER_BYTE) for (uint32_t* bitValue = primeBitValues_[sieve[i]]; *bitValue != END; bitValue++) std::cout << byteValue + *bitValue << '\n'; // print the prime k-tuplets to stdout else for (uint32_t i = 0; i < sieveSize; i++, byteValue += NUMBERS_PER_BYTE) for (uint32_t* bitValue = primeBitValues_[sieve[i]]; *bitValue != END; bitValue++) { std::cout << '('; uint32_t v = *bitValue; for (uint32_t j = PrimeSieve::PRINT_PRIMES; (j & primeSieve_->flags_) == 0; j <<= 1) { std::cout << byteValue + v << ", "; v = nextBitValue_[v]; } std::cout << byteValue + v << ")\n"; } } void PrimeNumberFinder::analyseSieve(const uint8_t* sieve, uint32_t sieveSize) { if (primeSieve_->flags_ & PrimeSieve::COUNT_FLAGS) this->count(sieve, sieveSize); if (primeSieve_->flags_ & PrimeSieve::GENERATE_FLAGS) this->generate(sieve, sieveSize); primeSieve_->parent_->doStatus(sieveSize * NUMBERS_PER_BYTE); } <|endoftext|>
<commit_before>#include <modelo/include/IEntidad.h> using namespace visualizador::modelo; // aplicacion #include <aplicacion/include/GestorIDs.h> IEntidad::IEntidad() : IReferenciable(), IAlmacenable(), IContieneJson(), IRelacionable(), esta_limpia(true) { } IEntidad::IEntidad(std::string etiqueta, std::string grupo, relaciones::IRelaciones * relaciones, IJson * json) : IReferenciable(), IAlmacenable(grupo), IContieneJson(json), IRelacionable(relaciones), etiqueta(etiqueta), esta_limpia(true) { } IEntidad::~IEntidad() { } // GETTERS std::string IEntidad::getEtiqueta() { return this->etiqueta; } // metodos IAlmacenable std::string IEntidad::getValorAlmacenable() { this->crearJson(); IJson json_almacenable; // seteo la etiqueta json_almacenable.agregarAtributoValor("etiqueta", this->getEtiqueta()); // seteo el contenido IJson* json_contenido = this->getJson(); json_almacenable.agregarAtributoJson("contenido", json_contenido); std::string string_almacenable = json_almacenable.jsonString(); return string_almacenable; } // SETTERS void IEntidad::setEtiqueta(std::string etiqueta) { this->etiqueta = etiqueta; } // metodos de IAlmacenable void IEntidad::setId(visualizador::aplicacion::ID* id) { if (NULL != this->getRelaciones()) { this->getRelaciones()->setId(id->copia()); visualizador::aplicacion::ID * id_viejo = this->getId(); this->actualizarRelaciones(id, id_viejo); } IAlmacenable::setId(id); } void IEntidad::parsearValorAlmacenable(std::string valor_almacenable) { IJson json_almacenable(valor_almacenable); // parseo etiqueta std::string etiqueta = json_almacenable.getAtributoValorString("etiqueta"); this->setEtiqueta(etiqueta); // parseo contenido IJson* json_contenido = json_almacenable.getAtributoValorJson("contenido"); this->esta_limpia = this->parsearJson(json_contenido); delete json_contenido; } std::vector<IAlmacenable*> IEntidad::comoAlmacenables(std::vector<IEntidad*> entidades) { std::vector<IAlmacenable*> almacenables; for (std::vector<IEntidad*>::iterator it = entidades.begin(); it != entidades.end(); it++) { IEntidad* entidad = *it; almacenables.push_back(entidad); } return almacenables; } bool IEntidad::estaSucia() { return !this->estaLimpia(); } bool IEntidad::estaLimpia() { return this->esta_limpia; } <commit_msg>refactorizacion de IEntidad.<commit_after>#include <modelo/include/IEntidad.h> using namespace visualizador::modelo; // aplicacion #include <aplicacion/include/GestorIDs.h> IEntidad::IEntidad() : IReferenciable(), IAlmacenable(), IContieneJson(), IRelacionable(), esta_limpia(true) { } IEntidad::IEntidad(std::string etiqueta, std::string grupo, relaciones::IRelaciones * relaciones, IJson * json) : IReferenciable(), IAlmacenable(grupo), IContieneJson(json), IRelacionable(relaciones), etiqueta(etiqueta), esta_limpia(true) { } IEntidad::~IEntidad() { } // GETTERS std::string IEntidad::getEtiqueta() { return this->etiqueta; } // metodos IAlmacenable std::string IEntidad::getValorAlmacenable() { this->crearJson(); IJson json_almacenable; // seteo la etiqueta json_almacenable.agregarAtributoValor("etiqueta", this->getEtiqueta()); // seteo el contenido IJson* json_contenido = this->getJson(); json_almacenable.agregarAtributoJson("contenido", json_contenido); std::string string_almacenable = json_almacenable.jsonString(); return string_almacenable; } // SETTERS void IEntidad::setEtiqueta(std::string etiqueta) { this->etiqueta = etiqueta; } // metodos de IAlmacenable void IEntidad::setId(visualizador::aplicacion::ID* id) { if (NULL != this->getRelaciones()) { this->getRelaciones()->setId(id->copia()); visualizador::aplicacion::ID * id_viejo = this->getId(); this->actualizarRelaciones(id, id_viejo); } IAlmacenable::setId(id); } void IEntidad::parsearValorAlmacenable(std::string valor_almacenable) { IJson json_almacenable(valor_almacenable); // parseo etiqueta std::string etiqueta = json_almacenable.getAtributoValorString("etiqueta"); this->setEtiqueta(etiqueta); // parseo contenido IJson* json_contenido = json_almacenable.getAtributoValorJson("contenido"); this->esta_limpia = this->parsearJson(json_contenido); delete json_contenido; } std::vector<IAlmacenable*> IEntidad::comoAlmacenables(std::vector<IEntidad*> entidades) { std::vector<IAlmacenable*> almacenables; for (std::vector<IEntidad*>::iterator it = entidades.begin(); it != entidades.end(); it++) { IEntidad* entidad = *it; almacenables.push_back(entidad); } return almacenables; } bool IEntidad::estaSucia() { return !this->estaLimpia(); } bool IEntidad::estaLimpia() { return this->esta_limpia; } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fnet/frt/frt.h> #include <vespa/fastos/app.h> #include <sstream> #include <vespa/log/log.h> LOG_SETUP("vespa-ping-configproxy"); class PingProxy : public FastOS_Application { private: std::unique_ptr<fnet::frt::StandaloneFRT> _server; FRT_Supervisor *_supervisor; FRT_Target *_target; PingProxy(const PingProxy &); PingProxy &operator=(const PingProxy &); public: PingProxy() : _server(), _supervisor(nullptr), _target(nullptr) {} virtual ~PingProxy(); int usage(); void initRPC(const char *spec); void finiRPC(); int Main() override; }; PingProxy::~PingProxy() { LOG_ASSERT(_supervisor == nullptr); LOG_ASSERT(_target == nullptr); } int PingProxy::usage() { fprintf(stderr, "usage: %s\n", _argv[0]); fprintf(stderr, "-s [server] (server hostname, default localhost)\n"); fprintf(stderr, "-p [port] (server port number, default 19090)\n"); return 1; } void PingProxy::initRPC(const char *spec) { _server = std::make_unique<fnet::frt::StandaloneFRT>(); _supervisor = &_server->supervisor(); _target = _supervisor->GetTarget(spec); } void PingProxy::finiRPC() { if (_target != nullptr) { _target->SubRef(); _target = nullptr; } if (_server) { _server.reset(); _supervisor = nullptr; } } int PingProxy::Main() { int retval = 0; bool debugging = false; char c = -1; const char *serverHost = "localhost"; int clientTimeout = 5; int serverPort = 19090; const char *optArg = nullptr; int optInd = 0; while ((c = GetOpt("w:s:p:dh", optArg, optInd)) != -1) { switch (c) { case 'w': clientTimeout = atoi(optArg); break; case 's': serverHost = optArg; break; case 'p': serverPort = atoi(optArg); break; case 'd': debugging = true; break; case '?': default: retval = 1; [[fallthrough]]; case 'h': usage(); return retval; } } if (serverPort == 0) { usage(); return 1; } std::ostringstream tmp; tmp << "tcp/"; tmp << serverHost; tmp << ":"; tmp << serverPort; std::string sspec = tmp.str(); const char *spec = sspec.c_str(); if (debugging) { printf("connecting to '%s'\n", spec); } initRPC(spec); FRT_RPCRequest *req = _supervisor->AllocRPCRequest(); req->SetMethodName("ping"); _target->InvokeSync(req, clientTimeout); // seconds if (req->IsError()) { retval = 1; fprintf(stderr, "error %d: %s\n", req->GetErrorCode(), req->GetErrorMessage()); } else { FRT_Values &answer = *(req->GetReturn()); const char *atypes = answer.GetTypeString(); if (strcmp(atypes, "i") == 0) { if (debugging) { printf("ping %d\n", answer[0]._intval32); } } else { fprintf(stderr, "unexpected return types in RPC answer: '%s'\n", atypes); retval = 1; } } finiRPC(); return retval; } int main(int argc, char **argv) { PingProxy app; return app.Entry(argc, argv); } <commit_msg>Simplify by not caching a member<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fnet/frt/frt.h> #include <vespa/fastos/app.h> #include <sstream> #include <vespa/log/log.h> LOG_SETUP("vespa-ping-configproxy"); class PingProxy : public FastOS_Application { private: std::unique_ptr<fnet::frt::StandaloneFRT> _server; FRT_Target *_target; PingProxy(const PingProxy &); PingProxy &operator=(const PingProxy &); public: PingProxy() : _server(), _target(nullptr) {} virtual ~PingProxy(); int usage(); void initRPC(const char *spec); void finiRPC(); int Main() override; }; PingProxy::~PingProxy() { LOG_ASSERT(!_server); LOG_ASSERT(_target == nullptr); } int PingProxy::usage() { fprintf(stderr, "usage: %s\n", _argv[0]); fprintf(stderr, "-s [server] (server hostname, default localhost)\n"); fprintf(stderr, "-p [port] (server port number, default 19090)\n"); return 1; } void PingProxy::initRPC(const char *spec) { _server = std::make_unique<fnet::frt::StandaloneFRT>(); _target = _server->supervisor().GetTarget(spec); } void PingProxy::finiRPC() { if (_target != nullptr) { _target->SubRef(); _target = nullptr; } _server.reset(); } int PingProxy::Main() { int retval = 0; bool debugging = false; char c = -1; const char *serverHost = "localhost"; int clientTimeout = 5; int serverPort = 19090; const char *optArg = nullptr; int optInd = 0; while ((c = GetOpt("w:s:p:dh", optArg, optInd)) != -1) { switch (c) { case 'w': clientTimeout = atoi(optArg); break; case 's': serverHost = optArg; break; case 'p': serverPort = atoi(optArg); break; case 'd': debugging = true; break; case '?': default: retval = 1; [[fallthrough]]; case 'h': usage(); return retval; } } if (serverPort == 0) { usage(); return 1; } std::ostringstream tmp; tmp << "tcp/"; tmp << serverHost; tmp << ":"; tmp << serverPort; std::string sspec = tmp.str(); const char *spec = sspec.c_str(); if (debugging) { printf("connecting to '%s'\n", spec); } initRPC(spec); FRT_RPCRequest *req = _server->supervisor().AllocRPCRequest(); req->SetMethodName("ping"); _target->InvokeSync(req, clientTimeout); // seconds if (req->IsError()) { retval = 1; fprintf(stderr, "error %d: %s\n", req->GetErrorCode(), req->GetErrorMessage()); } else { FRT_Values &answer = *(req->GetReturn()); const char *atypes = answer.GetTypeString(); if (strcmp(atypes, "i") == 0) { if (debugging) { printf("ping %d\n", answer[0]._intval32); } } else { fprintf(stderr, "unexpected return types in RPC answer: '%s'\n", atypes); retval = 1; } } finiRPC(); return retval; } int main(int argc, char **argv) { PingProxy app; return app.Entry(argc, argv); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include <list> #include <windows.h> #include <commctrl.h> #include "base/command_line.h" #include "base/event_recorder.h" #include "base/gfx/native_theme.h" #include "base/resource_util.h" #include "base/win_util.h" #include "webkit/tools/test_shell/foreground_helper.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_platform_delegate.h" TestShellPlatformDelegate::TestShellPlatformDelegate( const CommandLine& command_line) : command_line_(command_line) { #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #endif } TestShellPlatformDelegate::~TestShellPlatformDelegate() { #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif } void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) { } // This test approximates whether you are running the default themes for // your platform by inspecting a couple of metrics. // It does not catch all cases, but it does pick up on classic vs xp, // and normal vs large fonts. Something it misses is changes to the color // scheme (which will infact cause pixel test failures). bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() { std::list<std::string> errors; OSVERSIONINFOEX osvi; ::ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); ::GetVersionEx((OSVERSIONINFO *)&osvi); // default to XP metrics, override if on Vista int requiredVScrollSize = 17; int requiredFontSize = -11; // 8 pt const WCHAR *requiredFont = L"Tahoma"; bool isVista = false; if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0 && osvi.wProductType == VER_NT_WORKSTATION) { requiredFont = L"Segoe UI"; requiredFontSize = -12; // 9 pt isVista = true; } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 && osvi.wProductType == VER_NT_WORKSTATION) { // XP; } else { errors.push_back("Unsupported Operating System version " "(must use XP or Vista)"); } // on both XP and Vista, this metric will be 17 when font size is "Normal". // The size of drop-down menus depends on it. int vScrollSize = ::GetSystemMetrics(SM_CXVSCROLL); if (vScrollSize != requiredVScrollSize) { errors.push_back("Must use normal size fonts (96 dpi)"); } // font smoothing (including ClearType) must be disabled BOOL bFontSmoothing; SystemParametersInfo(SPI_GETFONTSMOOTHING, (UINT)0, (PVOID)&bFontSmoothing, (UINT)0); if (bFontSmoothing) { errors.push_back("Font smoothing (ClearType) must be disabled"); } // Check that we're using the default system fonts NONCLIENTMETRICS metrics; win_util::GetNonClientMetrics(&metrics); LOGFONTW* system_fonts[] = { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont }; for (size_t i = 0; i < arraysize(system_fonts); ++i) { if (system_fonts[i]->lfHeight != requiredFontSize || wcscmp(requiredFont, system_fonts[i]->lfFaceName)) { if (isVista) errors.push_back("Must use either the Aero or Basic theme"); else errors.push_back("Must use the default XP theme (Luna)"); break; } } if (!errors.empty()) { fprintf(stderr, "%s", "##################################################################\n" "## Layout test system dependencies check failed.\n" "##\n"); for (std::list<std::string>::iterator it = errors.begin(); it != errors.end(); ++it) { fprintf(stderr, "## %s\n", it->c_str()); } fprintf(stderr, "%s", "##\n" "##################################################################\n"); } return errors.empty(); } void TestShellPlatformDelegate::SuppressErrorReporting() { _set_abort_behavior(0, _WRITE_ABORT_MSG); } void TestShellPlatformDelegate::InitializeGUI() { INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrlEx); TestShell::RegisterWindowClass(); } void TestShellPlatformDelegate::SelectUnifiedTheme() { gfx::NativeTheme::instance()->DisableTheming(); } void TestShellPlatformDelegate::SetWindowPositionForRecording( TestShell *shell) { // Move the window to the upper left corner for consistent // record/playback mode. For automation, we want this to work // on build systems where the script invoking us is a background // process. So for this case, make our window the topmost window // as well. ForegroundHelper::SetForeground(shell->mainWnd()); ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0); } <commit_msg>Modify change in CL 21434 - allow standard font smoothing as well as none<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include <list> #include <windows.h> #include <commctrl.h> #include "base/command_line.h" #include "base/event_recorder.h" #include "base/gfx/native_theme.h" #include "base/resource_util.h" #include "base/win_util.h" #include "webkit/tools/test_shell/foreground_helper.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_platform_delegate.h" TestShellPlatformDelegate::TestShellPlatformDelegate( const CommandLine& command_line) : command_line_(command_line) { #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #endif } TestShellPlatformDelegate::~TestShellPlatformDelegate() { #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif } void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) { } // This test approximates whether you are running the default themes for // your platform by inspecting a couple of metrics. // It does not catch all cases, but it does pick up on classic vs xp, // and normal vs large fonts. Something it misses is changes to the color // scheme (which will infact cause pixel test failures). bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() { std::list<std::string> errors; OSVERSIONINFOEX osvi; ::ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); ::GetVersionEx((OSVERSIONINFO *)&osvi); // default to XP metrics, override if on Vista int requiredVScrollSize = 17; int requiredFontSize = -11; // 8 pt const WCHAR *requiredFont = L"Tahoma"; bool isVista = false; if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0 && osvi.wProductType == VER_NT_WORKSTATION) { requiredFont = L"Segoe UI"; requiredFontSize = -12; // 9 pt isVista = true; } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 && osvi.wProductType == VER_NT_WORKSTATION) { // XP; } else { errors.push_back("Unsupported Operating System version " "(must use XP or Vista)."); } // on both XP and Vista, this metric will be 17 when font size is "Normal". // The size of drop-down menus depends on it. int vScrollSize = ::GetSystemMetrics(SM_CXVSCROLL); if (vScrollSize != requiredVScrollSize) { errors.push_back("Must use normal size fonts (96 dpi)."); } // ClearType must be disabled, because the rendering is unpredictable. BOOL bFontSmoothing; SystemParametersInfo(SPI_GETFONTSMOOTHING, (UINT)0, (PVOID)&bFontSmoothing, (UINT)0); int fontSmoothingType; SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, (UINT)0, (PVOID)&fontSmoothingType, (UINT)0); if (bFontSmoothing && (fontSmoothingType == FE_FONTSMOOTHINGCLEARTYPE)) { errors.push_back("ClearType must be disabled."); } // Check that we're using the default system fonts NONCLIENTMETRICS metrics; win_util::GetNonClientMetrics(&metrics); LOGFONTW* system_fonts[] = { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont }; for (size_t i = 0; i < arraysize(system_fonts); ++i) { if (system_fonts[i]->lfHeight != requiredFontSize || wcscmp(requiredFont, system_fonts[i]->lfFaceName)) { if (isVista) errors.push_back("Must use either the Aero or Basic theme."); else errors.push_back("Must use the default XP theme (Luna)."); break; } } if (!errors.empty()) { fprintf(stderr, "%s", "##################################################################\n" "## Layout test system dependencies check failed.\n" "##\n"); for (std::list<std::string>::iterator it = errors.begin(); it != errors.end(); ++it) { fprintf(stderr, "## %s\n", it->c_str()); } fprintf(stderr, "%s", "##\n" "##################################################################\n"); } return errors.empty(); } void TestShellPlatformDelegate::SuppressErrorReporting() { _set_abort_behavior(0, _WRITE_ABORT_MSG); } void TestShellPlatformDelegate::InitializeGUI() { INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrlEx); TestShell::RegisterWindowClass(); } void TestShellPlatformDelegate::SelectUnifiedTheme() { gfx::NativeTheme::instance()->DisableTheming(); } void TestShellPlatformDelegate::SetWindowPositionForRecording( TestShell *shell) { // Move the window to the upper left corner for consistent // record/playback mode. For automation, we want this to work // on build systems where the script invoking us is a background // process. So for this case, make our window the topmost window // as well. ForegroundHelper::SetForeground(shell->mainWnd()); ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0); } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Andrew Manson <[email protected]> // Copyright 2013 Thibaut Gridel <[email protected]> // // Self #include "PlacemarkTextAnnotation.h" // Qt #include <QImage> // Marble #include "AbstractProjection.h" #include "GeoDataPlacemark.h" #include "GeoDataStyle.h" #include "GeoPainter.h" #include "GeoWidgetBubble.h" #include "ViewportParams.h" #include "MarbleDirs.h" #include "SceneGraphicsTypes.h" #include <QDebug> namespace Marble { PlacemarkTextAnnotation::PlacemarkTextAnnotation( GeoDataPlacemark *placemark ) : SceneGraphicsItem( placemark ), m_movingPlacemark( false ), m_iconFilename( MarbleDirs::path( "bitmaps/annotation.png" ) ) { GeoDataStyle *newStyle = new GeoDataStyle( *placemark->style() ); newStyle->iconStyle().setIcon( QImage( m_iconFilename ) ); placemark->setStyle( newStyle ); } PlacemarkTextAnnotation::~PlacemarkTextAnnotation() { // nothing to do } void PlacemarkTextAnnotation::paint( GeoPainter *painter, const ViewportParams *viewport ) { m_viewport = viewport; painter->drawImage( placemark()->coordinate(), placemark()->style()->iconStyle().icon() ); qreal x, y; viewport->currentProjection()->screenCoordinates( placemark()->coordinate(), viewport, x, y ); m_region = QRegion( x - 10 , y - 10 , 20 , 20 ); } bool PlacemarkTextAnnotation::containsPoint( const QPoint &eventPos ) const { return m_region.contains( eventPos ); } void PlacemarkTextAnnotation::dealWithItemChange( const SceneGraphicsItem *other ) { Q_UNUSED( other ); } const char *PlacemarkTextAnnotation::graphicType() const { return SceneGraphicsTypes::SceneGraphicPlacemark; } bool PlacemarkTextAnnotation::mousePressEvent( QMouseEvent* event ) { Q_UNUSED( event ); m_movingPlacemark = true; return true; } bool PlacemarkTextAnnotation::mouseMoveEvent( QMouseEvent *event ) { qreal lon, lat; m_viewport->geoCoordinates( event->pos().x(), event->pos().y(), lon, lat, GeoDataCoordinates::Radian ); if ( m_movingPlacemark ) { placemark()->setCoordinate( lon, lat ); } return true; } bool PlacemarkTextAnnotation::mouseReleaseEvent( QMouseEvent *event ) { Q_UNUSED( event ); m_movingPlacemark = false; return true; } void PlacemarkTextAnnotation::dealWithStateChange( SceneGraphicsItem::ActionState previousState ) { Q_UNUSED( previousState ); } } <commit_msg>Use the default icon<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Andrew Manson <[email protected]> // Copyright 2013 Thibaut Gridel <[email protected]> // // Self #include "PlacemarkTextAnnotation.h" // Qt #include <QImage> // Marble #include "AbstractProjection.h" #include "GeoDataPlacemark.h" #include "GeoDataStyle.h" #include "GeoPainter.h" #include "GeoWidgetBubble.h" #include "ViewportParams.h" #include "MarbleDirs.h" #include "SceneGraphicsTypes.h" #include <QDebug> namespace Marble { PlacemarkTextAnnotation::PlacemarkTextAnnotation( GeoDataPlacemark *placemark ) : SceneGraphicsItem( placemark ), m_movingPlacemark( false ), m_iconFilename( MarbleDirs::path( "bitmaps/default_location.png" ) ) { // nothing to do } PlacemarkTextAnnotation::~PlacemarkTextAnnotation() { // nothing to do } void PlacemarkTextAnnotation::paint( GeoPainter *painter, const ViewportParams *viewport ) { m_viewport = viewport; painter->drawImage( placemark()->coordinate(), placemark()->style()->iconStyle().icon() ); qreal x, y; viewport->currentProjection()->screenCoordinates( placemark()->coordinate(), viewport, x, y ); m_region = QRegion( x - 10 , y - 10 , 20 , 20 ); } bool PlacemarkTextAnnotation::containsPoint( const QPoint &eventPos ) const { return m_region.contains( eventPos ); } void PlacemarkTextAnnotation::dealWithItemChange( const SceneGraphicsItem *other ) { Q_UNUSED( other ); } const char *PlacemarkTextAnnotation::graphicType() const { return SceneGraphicsTypes::SceneGraphicPlacemark; } bool PlacemarkTextAnnotation::mousePressEvent( QMouseEvent* event ) { Q_UNUSED( event ); m_movingPlacemark = true; return true; } bool PlacemarkTextAnnotation::mouseMoveEvent( QMouseEvent *event ) { qreal lon, lat; m_viewport->geoCoordinates( event->pos().x(), event->pos().y(), lon, lat, GeoDataCoordinates::Radian ); if ( m_movingPlacemark ) { placemark()->setCoordinate( lon, lat ); } return true; } bool PlacemarkTextAnnotation::mouseReleaseEvent( QMouseEvent *event ) { Q_UNUSED( event ); m_movingPlacemark = false; return true; } void PlacemarkTextAnnotation::dealWithStateChange( SceneGraphicsItem::ActionState previousState ) { Q_UNUSED( previousState ); } } <|endoftext|>
<commit_before>/********************************************************************* * roverdomain.cpp * * Rover domain is a bounded stateful world with perfect visibility. Global * reward function determined as in <PAPER HERE> * * Copyright (C) 2016 Eric Klinkhammer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *********************************************************************/ #include "roverDomain.h" #include "poi.h" #include <random> #include <math.h> #include <iostream> RoverDomain::RoverDomain(std::vector<Actor*> actors, Location bounds) : World (actors) { this->hasBounds = true; this->upperRightCorner = bounds; } std::vector<Actor*>& RoverDomain::visibleFrom(Actor*) { return this->getActors(); } double RoverDomain::calculateG() { return World::calculateG(); } double RoverDomain::calculateG(std::vector<Actor*> actors) { double globalReward = 0; for (const auto& actor : actors) { if (actor->isPOI()) { globalReward += actor->determineReward(actors,0); // second param is not used } } return globalReward; } bool RoverDomain::inBounds(Actor* actor) { Location loc = actor->getLocation(); return loc.x < this->upperRightCorner.x && loc.y < this->upperRightCorner.y && loc.x >= 0 && loc.y >= 0; } Location RoverDomain::randomLocation() { double x = ((double) rand() / INT_MAX) * this->upperRightCorner.x; double y = ( (double) rand() / INT_MAX) * this->upperRightCorner.y; return Location::createLoc(x,y); } void RoverDomain::display() { std::vector<std::vector<Actor*> > actorsByRow; for (int i = 0; i < this->upperRightCorner.y; i++) { std::vector<Actor*> row; actorsByRow.push_back(row); } for (const auto actor : this->getActors()) { Location actorLoc = actor->getLocation(); int y = floor(actorLoc.y); actorsByRow[y].push_back(actor); } for (int i = 0; i < this->upperRightCorner.y; i++) { std::cout << "|"; for (int j = 0; j < this->upperRightCorner.x; j++) { bool actorPresent = false; for (const auto actor : actorsByRow[i]) { Location actorLoc = actor->getLocation(); if (floor(actorLoc.x) == j) { std::cout << actor->toString(); actorPresent = true; } } if (!actorPresent) { std::cout << "_"; } } std:: cout << "|\n"; } } <commit_msg>Delete roverdomain.cpp<commit_after><|endoftext|>
<commit_before>/************************************************************ * * main.cpp * */ /************************************************************ -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 * OPEN TRANSACTIONS * * Financial Cryptography and Digital Cash * Library, Protocol, API, Server, CLI, GUI * * -- Anonymous Numbered Accounts. * -- Untraceable Digital Cash. * -- Triple-Signed Receipts. * -- Cheques, Vouchers, Transfers, Inboxes. * -- Basket Currencies, Markets, Payment Plans. * -- Signed, XML, Ricardian-style Contracts. * -- Scripted smart contracts. * * Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym) * * EMAIL: * [email protected] * * BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ * * KEY FINGERPRINT (PGP Key in license file): * 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E * * OFFICIAL PROJECT WIKI(s): * https://github.com/FellowTraveler/Moneychanger * https://github.com/FellowTraveler/Open-Transactions/wiki * * WEBSITE: * http://www.OpenTransactions.org/ * * Components and licensing: * -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3 * -- otlib.........A class library.......LICENSE:...LAGPLv3 * -- otapi.........A client API..........LICENSE:...LAGPLv3 * -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3 * -- otserver......Server Application....LICENSE:....AGPLv3 * Github.com/FellowTraveler/Open-Transactions/wiki/Components * * All of the above OT components were designed and written by * Fellow Traveler, with the exception of Moneychanger, which * was contracted out to Vicky C ([email protected]). * The open-source community has since actively contributed. * * ----------------------------------------------------- * * LICENSE: * This program is free software: you can redistribute it * and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your * option) any later version. * * ADDITIONAL PERMISSION under the GNU Affero GPL version 3 * section 7: (This paragraph applies only to the LAGPLv3 * components listed above.) If you modify this Program, or * any covered work, by linking or combining it with other * code, such other code is not for that reason alone subject * to any of the requirements of the GNU Affero GPL version 3. * (==> This means if you are only using the OT API, then you * don't have to open-source your code--only your changes to * Open-Transactions itself must be open source. Similar to * LGPLv3, except it applies to software-as-a-service, not * just to distributing binaries.) * * Extra WAIVER for OpenSSL, Lucre, and all other libraries * used by Open Transactions: This program is released under * the AGPL with the additional exemption that compiling, * linking, and/or using OpenSSL is allowed. The same is true * for any other open source libraries included in this * project: complete waiver from the AGPL is hereby granted to * compile, link, and/or use them with Open-Transactions, * according to their own terms, as long as the rest of the * Open-Transactions terms remain respected, with regard to * the Open-Transactions code itself. * * Lucre License: * This code is also "dual-license", meaning that Ben Lau- * rie's license must also be included and respected, since * the code for Lucre is also included with Open Transactions. * See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt * The Laurie requirements are light, but if there is any * problem with his license, simply remove the Lucre code. * Although there are no other blind token algorithms in Open * Transactions (yet. credlib is coming), the other functions * will continue to operate. * See Lucre on Github: https://github.com/benlaurie/lucre * ----------------------------------------------------- * You should have received a copy of the GNU Affero General * Public License along with this program. If not, see: * http://www.gnu.org/licenses/ * * If you would like to use this software outside of the free * software license, please contact FellowTraveler. * (Unfortunately many will run anonymously and untraceably, * so who could really stop them?) * * DISCLAIMER: * This program is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for * more details. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1 sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd kamH0Y/n11lCvo1oQxM+ =uSzz -----END PGP SIGNATURE----- **************************************************************/ #include <opentxs/core/Version.hpp> #include <opentxs/server/ServerLoader.hpp> #include <opentxs/server/MessageProcessor.hpp> #include <opentxs/core/Log.hpp> #include <anyoption/anyoption.hpp> #include <cassert> #include <map> #include <string> int main(int argc, char* argv[]) { using namespace opentxs; bool onlyInit = false; for (int i = 1; i < argc; ++i) { std::string arg(argv[i]); if (0 == arg.compare("version") || 0 == arg.compare("--version")) { otOut << "opentxs server " << OPENTXS_SERVER_VERSION_STRING << "\n"; otOut << "opentxs library " << OPENTXS_VERSION_STRING << "\n"; otOut << "Copyright (C) 2014 Open Transactions Developers\n"; return 0; } else if (0 == arg.compare("--only-init")) { onlyInit = true; } } // ------------------------------------------------------- // Process the command-line options for creating a new server contract. // // (Not used for most server start-ups, but only used when the server // contract is first created.) /* --terms <human-readable terms of use> --externalip <externally-visible hostname> --commandport <externally-visible port where opentxs commands can be sent> --notificationport <externally-visible port where to listen for push notifications> --bindip <internal ip address where the listen sockets will be opened> --listencommand <internal port number where the opentxs listen socket will bind> --listennotification <internal port number where the push notification socket will bind> --name <server name> --onion <hidden service hostname> */ static const std::string createOptions[] = { "terms", "externalip", "commandport", "notificationport", "bindip", "listencommand", "listennotification", "name", "onion"}; AnyOption options; for (const auto& optionName : createOptions) { if (!options.findOption(optionName.c_str())) { options.setCommandOption(optionName.c_str()); } } options.processCommandArgs(argc, argv); std::map<std::string, std::string> arguments; for (const auto& optionName : createOptions) { const char* value = options.getValue(optionName.c_str()); if (nullptr != value) { arguments[optionName] = value; } } // ------------------------------------------------------- if (!Log::Init(SERVER_CONFIG_KEY, 0)) { assert(false); } ServerLoader loader(arguments); if (onlyInit) { // ServerLoader constructor has finished initializing. return 0; } MessageProcessor processor(loader); processor.run(); return 0; } <commit_msg>Add option --eep to allow an i2p eepsite name to be passed in<commit_after>/************************************************************ * * main.cpp * */ /************************************************************ -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 * OPEN TRANSACTIONS * * Financial Cryptography and Digital Cash * Library, Protocol, API, Server, CLI, GUI * * -- Anonymous Numbered Accounts. * -- Untraceable Digital Cash. * -- Triple-Signed Receipts. * -- Cheques, Vouchers, Transfers, Inboxes. * -- Basket Currencies, Markets, Payment Plans. * -- Signed, XML, Ricardian-style Contracts. * -- Scripted smart contracts. * * Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym) * * EMAIL: * [email protected] * * BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ * * KEY FINGERPRINT (PGP Key in license file): * 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E * * OFFICIAL PROJECT WIKI(s): * https://github.com/FellowTraveler/Moneychanger * https://github.com/FellowTraveler/Open-Transactions/wiki * * WEBSITE: * http://www.OpenTransactions.org/ * * Components and licensing: * -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3 * -- otlib.........A class library.......LICENSE:...LAGPLv3 * -- otapi.........A client API..........LICENSE:...LAGPLv3 * -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3 * -- otserver......Server Application....LICENSE:....AGPLv3 * Github.com/FellowTraveler/Open-Transactions/wiki/Components * * All of the above OT components were designed and written by * Fellow Traveler, with the exception of Moneychanger, which * was contracted out to Vicky C ([email protected]). * The open-source community has since actively contributed. * * ----------------------------------------------------- * * LICENSE: * This program is free software: you can redistribute it * and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your * option) any later version. * * ADDITIONAL PERMISSION under the GNU Affero GPL version 3 * section 7: (This paragraph applies only to the LAGPLv3 * components listed above.) If you modify this Program, or * any covered work, by linking or combining it with other * code, such other code is not for that reason alone subject * to any of the requirements of the GNU Affero GPL version 3. * (==> This means if you are only using the OT API, then you * don't have to open-source your code--only your changes to * Open-Transactions itself must be open source. Similar to * LGPLv3, except it applies to software-as-a-service, not * just to distributing binaries.) * * Extra WAIVER for OpenSSL, Lucre, and all other libraries * used by Open Transactions: This program is released under * the AGPL with the additional exemption that compiling, * linking, and/or using OpenSSL is allowed. The same is true * for any other open source libraries included in this * project: complete waiver from the AGPL is hereby granted to * compile, link, and/or use them with Open-Transactions, * according to their own terms, as long as the rest of the * Open-Transactions terms remain respected, with regard to * the Open-Transactions code itself. * * Lucre License: * This code is also "dual-license", meaning that Ben Lau- * rie's license must also be included and respected, since * the code for Lucre is also included with Open Transactions. * See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt * The Laurie requirements are light, but if there is any * problem with his license, simply remove the Lucre code. * Although there are no other blind token algorithms in Open * Transactions (yet. credlib is coming), the other functions * will continue to operate. * See Lucre on Github: https://github.com/benlaurie/lucre * ----------------------------------------------------- * You should have received a copy of the GNU Affero General * Public License along with this program. If not, see: * http://www.gnu.org/licenses/ * * If you would like to use this software outside of the free * software license, please contact FellowTraveler. * (Unfortunately many will run anonymously and untraceably, * so who could really stop them?) * * DISCLAIMER: * This program is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for * more details. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1 sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd kamH0Y/n11lCvo1oQxM+ =uSzz -----END PGP SIGNATURE----- **************************************************************/ #include <opentxs/core/Version.hpp> #include <opentxs/server/ServerLoader.hpp> #include <opentxs/server/MessageProcessor.hpp> #include <opentxs/core/Log.hpp> #include <anyoption/anyoption.hpp> #include <cassert> #include <map> #include <string> int main(int argc, char* argv[]) { using namespace opentxs; bool onlyInit = false; for (int i = 1; i < argc; ++i) { std::string arg(argv[i]); if (0 == arg.compare("version") || 0 == arg.compare("--version")) { otOut << "opentxs server " << OPENTXS_SERVER_VERSION_STRING << "\n"; otOut << "opentxs library " << OPENTXS_VERSION_STRING << "\n"; otOut << "Copyright (C) 2014 Open Transactions Developers\n"; return 0; } else if (0 == arg.compare("--only-init")) { onlyInit = true; } } // ------------------------------------------------------- // Process the command-line options for creating a new server contract. // // (Not used for most server start-ups, but only used when the server // contract is first created.) /* --terms <human-readable terms of use> --externalip <externally-visible hostname> --commandport <externally-visible port where opentxs commands can be sent> --notificationport <externally-visible port where to listen for push notifications> --bindip <internal ip address where the listen sockets will be opened> --listencommand <internal port number where the opentxs listen socket will bind> --listennotification <internal port number where the push notification socket will bind> --name <server name> --onion <tor hidden service hostname> --eep <i2p eepsite hostname> */ static const std::string createOptions[] = { "terms", "externalip", "commandport", "notificationport", "bindip", "listencommand", "listennotification", "name", "onion", "eep"}; AnyOption options; for (const auto& optionName : createOptions) { if (!options.findOption(optionName.c_str())) { options.setCommandOption(optionName.c_str()); } } options.processCommandArgs(argc, argv); std::map<std::string, std::string> arguments; for (const auto& optionName : createOptions) { const char* value = options.getValue(optionName.c_str()); if (nullptr != value) { arguments[optionName] = value; } } // ------------------------------------------------------- if (!Log::Init(SERVER_CONFIG_KEY, 0)) { assert(false); } ServerLoader loader(arguments); if (onlyInit) { // ServerLoader constructor has finished initializing. return 0; } MessageProcessor processor(loader); processor.run(); return 0; } <|endoftext|>
<commit_before><commit_msg>Updating picking function logic to v4.2.0-alpha.32<commit_after><|endoftext|>
<commit_before>// // Projectname: amos-ss16-proj5 // // Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5 // // This file is part of the AMOS Project 2016 @ FAU // (Friedrich-Alexander University Erlangen-Nürnberg) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public // License along with this program. If not, see // <http://www.gnu.org/licenses/>. // //local #include "detection.h" #include "element.h" using namespace std; using namespace cv; Detection::Detection(Detector * people_detector, Detector * vehicle_detector) { people_detector_ = people_detector; vehicle_detector_ = vehicle_detector; image_view_ = new ImageView(); //default resize factor value resize_factor_ = 1.0; } Detection::~Detection(){ delete image_view_; image_view_ = NULL; } FrameDetectionData* Detection::ProcessFrame(Image * image) { // resize the frame and adjust it Mat frame = image->GetRGBImage(); Mat contrast_and_brightness_adjusted_frame = AdjustContrastAndBrightness(&frame); Mat resized_frame = ResizeFrame(&contrast_and_brightness_adjusted_frame); // perform detection std::vector<Rect> detected_vehicles = vehicle_detector_->Detect(&resized_frame); std::vector<Rect> detected_people = people_detector_->DetectInROI(&resized_frame, &detected_vehicles); // write the detected people and vehicle data into frame detection data and return it // resize the positions and the boxes of detected elements to real size again FrameDetectionData* detected_objects = new FrameDetectionData(); std::vector<Element> people_elements; std::vector<Element> vehicle_elements; for(int i=0; i<detected_people.size(); i++) { Rect current_rec = detected_people.at(i); std::vector<int> position; std::vector<int> box; int pos_x_resized = current_rec.x/resize_factor_; int pos_y_resized = current_rec.y/resize_factor_; if(pos_x_resized < 0){ pos_x_resized = 0; } if(pos_x_resized > image->GetImageWidth()){ pos_x_resized = image->GetImageWidth(); } if(pos_y_resized < 0){ pos_y_resized = 0; } if(pos_y_resized > image->GetImageHeight()){ pos_y_resized = image->GetImageHeight(); } position.push_back(pos_x_resized); position.push_back(pos_y_resized); int box_width_resized = current_rec.width/resize_factor_; int box_height_resized = current_rec.height/resize_factor_; if((position.at(0) + box_width_resized) > image->GetImageWidth()){ box_width_resized = image->GetImageWidth()-position.at(0); } if((position.at(1) + box_height_resized) > image->GetImageHeight()){ box_height_resized = image->GetImageHeight()-position.at(1); } box.push_back(box_width_resized); box.push_back(box_height_resized); //std::cout << "Process Frame: position of elem: " << position.at(0) << " " << position.at(1) << std::endl; //std::cout << "Process Frame: width and height: " << box.at(0) << " " << box.at(1) << std::endl; Element current_elem(position, box); people_elements.push_back(current_elem); } detected_objects->AddElementsOfType(OBJECT_HUMAN, people_elements); for(int i=0; i<detected_vehicles.size(); i++) { Rect current_rec = detected_vehicles.at(i); std::vector<int> position; std::vector<int> box; position.push_back(current_rec.x/resize_factor_); position.push_back(current_rec.y/resize_factor_); box.push_back(current_rec.width/resize_factor_); box.push_back(current_rec.height/resize_factor_); Element current_elem(position, box); vehicle_elements.push_back(current_elem); } detected_objects->AddElementsOfType(OBJECT_VEHICLE, vehicle_elements); // display image and detections //cout<<"display detections"<<endl; //image_view_->ShowImageAndDetections(image, people_elements, vehicle_elements); return detected_objects; } Mat Detection::ResizeFrame(Mat *frame) { // resize the image to width of 400px to reduce detection time and improve detection accuracy // dynamic risizing; depending on input (min width 400px) // compute resize factor Size size = frame->size(); resize_factor_ = static_cast<float>(default_resized_frame_width)/size.width; // std::cout << "Detection: resized factor: " << resize_factor_ << std::endl; // perform resizing of the frame Mat resized_frame; resize(*frame, resized_frame, Size(0, 0), resize_factor_, resize_factor_, CV_INTER_AREA); return resized_frame; } cv::Mat Detection::AdjustContrastAndBrightness(cv::Mat *frame, double contrastValue, int brightnessValue){ Mat adjusted_image = Mat::zeros( frame->size(), frame->type() ); for( int x = 0; x < frame->rows; x++ ){ for( int y = 0; y < frame->cols; y++ ){ // c: use all colours of RGB / BGR for( int c = 0; c < 3; c++ ){ adjusted_image.at<Vec3b>(x,y)[c] = saturate_cast<uchar>(contrastValue* (frame->at<Vec3b>(x,y)[c])+brightnessValue ); } } } return adjusted_image; } cv::Mat Detection::AdjustContrastAndBrightness(cv::Mat *frame){ return AdjustContrastAndBrightness(frame, default_contrast_value, default_brightness_value); } <commit_msg>the detection is now done on a greyscale image, that is equalized<commit_after>// // Projectname: amos-ss16-proj5 // // Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5 // // This file is part of the AMOS Project 2016 @ FAU // (Friedrich-Alexander University Erlangen-Nürnberg) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public // License along with this program. If not, see // <http://www.gnu.org/licenses/>. // //local #include "detection.h" #include "element.h" using namespace std; using namespace cv; Detection::Detection(Detector * people_detector, Detector * vehicle_detector) { people_detector_ = people_detector; vehicle_detector_ = vehicle_detector; image_view_ = new ImageView(); //default resize factor value resize_factor_ = 1.0; } Detection::~Detection(){ delete image_view_; image_view_ = NULL; } FrameDetectionData* Detection::ProcessFrame(Image * image) { // resize the frame and adjust it Mat frame = image->GetRGBImage(); Mat resized_frame = ResizeFrame(&frame); // Mat contrast_and_brightness_adjusted_frame = AdjustContrastAndBrightness(&frame); Mat frame_gray; cvtColor( resized_frame, frame_gray, CV_RGB2GRAY ); equalizeHist( frame_gray, frame_gray ); imshow(" ", frame_gray); waitKey(1); // perform detection std::vector<Rect> detected_vehicles = vehicle_detector_->Detect(&frame_gray); std::vector<Rect> detected_people = people_detector_->DetectInROI(&frame_gray, &detected_vehicles); // write the detected people and vehicle data into frame detection data and return it // resize the positions and the boxes of detected elements to real size again FrameDetectionData* detected_objects = new FrameDetectionData(); std::vector<Element> people_elements; std::vector<Element> vehicle_elements; for(int i=0; i<detected_people.size(); i++) { Rect current_rec = detected_people.at(i); std::vector<int> position; std::vector<int> box; int pos_x_resized = current_rec.x/resize_factor_; int pos_y_resized = current_rec.y/resize_factor_; if(pos_x_resized < 0){ pos_x_resized = 0; } if(pos_x_resized > image->GetImageWidth()){ pos_x_resized = image->GetImageWidth(); } if(pos_y_resized < 0){ pos_y_resized = 0; } if(pos_y_resized > image->GetImageHeight()){ pos_y_resized = image->GetImageHeight(); } position.push_back(pos_x_resized); position.push_back(pos_y_resized); int box_width_resized = current_rec.width/resize_factor_; int box_height_resized = current_rec.height/resize_factor_; if((position.at(0) + box_width_resized) > image->GetImageWidth()){ box_width_resized = image->GetImageWidth()-position.at(0); } if((position.at(1) + box_height_resized) > image->GetImageHeight()){ box_height_resized = image->GetImageHeight()-position.at(1); } box.push_back(box_width_resized); box.push_back(box_height_resized); //std::cout << "Process Frame: position of elem: " << position.at(0) << " " << position.at(1) << std::endl; //std::cout << "Process Frame: width and height: " << box.at(0) << " " << box.at(1) << std::endl; Element current_elem(position, box); people_elements.push_back(current_elem); } detected_objects->AddElementsOfType(OBJECT_HUMAN, people_elements); for(int i=0; i<detected_vehicles.size(); i++) { Rect current_rec = detected_vehicles.at(i); std::vector<int> position; std::vector<int> box; position.push_back(current_rec.x/resize_factor_); position.push_back(current_rec.y/resize_factor_); box.push_back(current_rec.width/resize_factor_); box.push_back(current_rec.height/resize_factor_); Element current_elem(position, box); vehicle_elements.push_back(current_elem); } detected_objects->AddElementsOfType(OBJECT_VEHICLE, vehicle_elements); // display image and detections //cout<<"display detections"<<endl; //image_view_->ShowImageAndDetections(image, people_elements, vehicle_elements); return detected_objects; } Mat Detection::ResizeFrame(Mat *frame) { // resize the image to width of 400px to reduce detection time and improve detection accuracy // dynamic risizing; depending on input (min width 400px) // compute resize factor Size size = frame->size(); resize_factor_ = static_cast<float>(default_resized_frame_width)/size.width; resize_factor_ = 0.3125; // TODO: find out why this resize factor works better than the default? // std::cout << "Detection: resized factor: " << resize_factor_ << std::endl; // perform resizing of the frame Mat resized_frame; resize(*frame, resized_frame, Size(0, 0), resize_factor_, resize_factor_, CV_INTER_AREA); return resized_frame; } cv::Mat Detection::AdjustContrastAndBrightness(cv::Mat *frame, double contrastValue, int brightnessValue){ Mat adjusted_image = Mat::zeros( frame->size(), frame->type() ); for( int x = 0; x < frame->rows; x++ ){ for( int y = 0; y < frame->cols; y++ ){ // c: use all colours of RGB / BGR for( int c = 0; c < 3; c++ ){ adjusted_image.at<Vec3b>(x,y)[c] = saturate_cast<uchar>(contrastValue* (frame->at<Vec3b>(x,y)[c])+brightnessValue ); } } } return adjusted_image; } cv::Mat Detection::AdjustContrastAndBrightness(cv::Mat *frame){ return AdjustContrastAndBrightness(frame, default_contrast_value, default_brightness_value); } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "gtest/gtest.h" #include <iostream> // TODO: remove. #include <sstream> #include "Allocator.h" #include "BitFunnel/TermMatchNode.h" #include "QueryParser.h" #include "TextObjectFormatter.h" namespace BitFunnel { void VerifyQueryParser(std::string expected, std::string input, IAllocator& allocator) { std::stringstream s; s << input; QueryParser parser(s, allocator); std::cout << "input length: " << s.str().size() << std::endl; auto result = parser.Parse(); ASSERT_NE(nullptr, result); std::stringstream parsedOutput; TextObjectFormatter formatter(parsedOutput); result->Format(formatter); std::cout << "???: " << parsedOutput.str() << std::endl; EXPECT_EQ(expected, parsedOutput.str()); } TEST(QueryParser, Trivial) { Allocator allocator(4096); std::stringstream s; // UNIGRAM. VerifyQueryParser("Unigram(\"wat\", 0)", "wat", allocator); // STREAM:UNIGRAM. VerifyQueryParser("Unigram(\"wat\", 0)", "StreamsAreCurrentlyIgnored:wat", allocator); // (UNIGRAM). VerifyQueryParser("Unigram(\"wat\", 0)", "(wat)", allocator); // OR of two UNIGRAMs. VerifyQueryParser( "Or {\n" " Children: [\n" " Unigram(\"foo\", 0),\n" " Unigram(\"wat\", 0)\n" " ]\n" "}", "wat|foo", allocator); // OR of two UNIGRAMs with parens. VerifyQueryParser( "Or {\n" " Children: [\n" " Unigram(\"foo\", 0),\n" " Unigram(\"wat\", 0)\n" " ]\n" "}", "(wat|foo)", allocator); // NOT. VerifyQueryParser("Not {\n" " Child: Unigram(\"wat\", 0)\n" "}" , "-wat", allocator); // NOT with whitespace. VerifyQueryParser("Not {\n" " Child: Unigram(\"wat\", 0)\n" "}" , " \t- wat", allocator); // AND of 2. VerifyQueryParser("And {\n" " Children: [\n" " Unigram(\"foo\", 0),\n" " Unigram(\"wat\", 0)\n" " ]\n" "}", "wat foo", allocator); // AND of 2, explicit '&'. VerifyQueryParser("And {\n" " Children: [\n" " Unigram(\"foo\", 0),\n" " Unigram(\"wat\", 0)\n" " ]\n" "}", "wat&foo", allocator); // AND of 2, explicit '&' with whitespace. VerifyQueryParser("And {\n" " Children: [\n" " Unigram(\"foo\", 0),\n" " Unigram(\"wat\", 0)\n" " ]\n" "}", "wat\t\t& foo", allocator); VerifyQueryParser("Phrase {\n" " StreamId: 0,\n" " Grams: [\n" " \"wat\",\n" " \"foo\"\n" " ]\n" "}", "\" wat\tfoo\"", allocator); } } <commit_msg>Pull out test cases into single data strucutre.<commit_after>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "gtest/gtest.h" #include <iostream> // TODO: remove. #include <sstream> #include "Allocator.h" #include "BitFunnel/TermMatchNode.h" #include "QueryParser.h" #include "TextObjectFormatter.h" namespace BitFunnel { struct ExpectedAndInputs { public: char const * m_expected; char const * m_input; }; const ExpectedAndInputs c_testData[] = { // UNIGRAM. {"Unigram(\"wat\", 0)", "wat"}, // STREAM:UNIGRAM. {"Unigram(\"wat\", 0)", "StreamsAreCurrentlyIgnored:wat"}, // (UNIGRAM) {"Unigram(\"wat\", 0)", "(wat)"}, // OR of two UNIGRAMs. { "Or {\n" " Children: [\n" " Unigram(\"foo\", 0),\n" " Unigram(\"wat\", 0)\n" " ]\n" "}", "wat|foo" }, // OR of two UNIGRAMs with parens. { "Or {\n" " Children: [\n" " Unigram(\"foo\", 0),\n" " Unigram(\"wat\", 0)\n" " ]\n" "}", "(wat|foo)" }, // NOT. { "Not {\n" " Child: Unigram(\"wat\", 0)\n" "}" , "-wat" }, // AND of 2. { "And {\n" " Children: [\n" " Unigram(\"foo\", 0),\n" " Unigram(\"wat\", 0)\n" " ]\n" "}", "wat foo" }, // AND of 2, explicit '&'. { "And {\n" " Children: [\n" " Unigram(\"foo\", 0),\n" " Unigram(\"wat\", 0)\n" " ]\n" "}", "wat&foo" }, // AND of 2, explicit '&' with whitespace. { "And {\n" " Children: [\n" " Unigram(\"foo\", 0),\n" " Unigram(\"wat\", 0)\n" " ]\n" "}", "wat\t\t& foo" } }; void VerifyQueryParser(std::string const & expected, std::string const & input, IAllocator& allocator) { std::stringstream s; s << input; QueryParser parser(s, allocator); std::cout << "input length: " << s.str().size() << std::endl; auto result = parser.Parse(); ASSERT_NE(nullptr, result); std::stringstream parsedOutput; TextObjectFormatter formatter(parsedOutput); result->Format(formatter); std::cout << "???: " << parsedOutput.str() << std::endl; EXPECT_EQ(expected, parsedOutput.str()); allocator.Reset(); } TEST(QueryParser, Trivial) { Allocator allocator(512); for (size_t i = 0; i < sizeof(c_testData) / sizeof(ExpectedAndInputs); ++i) { VerifyQueryParser(c_testData[i].m_expected, c_testData[i].m_input, allocator); } } } <|endoftext|>
<commit_before>/** * @author andy * @copyright (c) 2016 andy. All rights reserved. */ #include "soundex/charutil.h" #include <string> namespace gherkin_demo { char CharUtil::lower(const char letter) { return std::tolower(static_cast<unsigned char>(letter)); } bool CharUtil::isVowel(const char letter) { static std::string vowels("aeiouy"); return vowels.find(lower(letter)) != std::string::npos; } } /* namespace gherkin_demo */ <commit_msg>added include for cctype<commit_after>/** * @author andy * @copyright (c) 2016 andy. All rights reserved. */ #include "soundex/charutil.h" #include <cctype> #include <string> namespace gherkin_demo { char CharUtil::lower(const char letter) { return std::tolower(static_cast<unsigned char>(letter)); } bool CharUtil::isVowel(const char letter) { static std::string vowels("aeiouy"); return vowels.find(lower(letter)) != std::string::npos; } } /* namespace gherkin_demo */ <|endoftext|>
<commit_before>/* Copyright (C) 2018 INRA * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <array> #include "debug.hpp" #include "itm.hpp" #include "private.hpp" #include "problem.hpp" #include "utils.hpp" struct manual_course { std::unique_ptr<double[]> theta; std::unique_ptr<double[]> delta; std::unique_ptr<double[]> kappa_min; std::unique_ptr<double[]> kappa_step; std::unique_ptr<double[]> init_random; std::unique_ptr<int[]> iterators; const int length; manual_course(double theta_, double delta_, double kappa_min_, double kappa_step_, double init_random_, int length_) : theta(std::make_unique<double[]>(length_)) , delta(std::make_unique<double[]>(length_)) , kappa_min(std::make_unique<double[]>(length_)) , kappa_step(std::make_unique<double[]>(length_)) , init_random(std::make_unique<double[]>(length_)) , iterators(std::make_unique<int[]>(length_)) , length(length_) { bx_ensures(length > 2); theta[0] = { 0.5 }; theta[1] = 1.0 / static_cast<double>(length); delta[0] = { -1 }; delta[1] = 0.1 / static_cast<double>(length); kappa_min[0] = { 0 }; kappa_min[1] = 1e-2 / static_cast<double>(length); kappa_step[0] = { 1e-3 }; kappa_step[1] = 1e-7 / static_cast<double>(length); init_random[0] = { 0.5 }; init_random[1] = 0.9 / static_cast<double>(length); for (int i = 2; i != length; ++i) theta[i] = theta[i - 1] + 1.0 / static_cast<double>(length); for (int i = 2; i != length; ++i) delta[i] = theta[i - 1] + 0.1 / (5.0 * static_cast<double>(length)); for (int i = 2; i != length; ++i) kappa_min[i] = theta[i - 1] + 1e-2 / static_cast<double>(length); for (int i = 2; i != length; ++i) kappa_step[i] = theta[i - 1] + 1e-7 / (5.0 * static_cast<double>(length)); for (int i = 2; i != length; ++i) init_random[i] = theta[i - 1] + 0.9 / static_cast<double>(length); reset(); } void reset() { std::fill(iterators.get(), iterators.get() + length, 0); } bool next() { for (int i = length - 1; i >= 0; --i) { if (iterators[i] + 1 >= length) { iterators[i] = 0; } else { ++iterators[i]; return true; } } return false; } }; static baryonyx::result optimize(const baryonyx::context_ptr& ctx, const baryonyx::problem& pb) { manual_course array(ctx->parameters.theta, ctx->parameters.delta, ctx->parameters.kappa_min, ctx->parameters.kappa_step, ctx->parameters.init_random, 5); auto old_log_priority = ctx->log_priority; ctx->log_priority = baryonyx::context::message_type::notice; auto best_params = std::make_unique<int[]>(array.length); double best = +HUGE_VAL; do { ctx->parameters.theta = array.theta[array.iterators[0]]; ctx->parameters.delta = array.delta[array.iterators[1]]; ctx->parameters.kappa_min = array.kappa_min[array.iterators[2]]; ctx->parameters.kappa_step = array.kappa_step[array.iterators[3]]; ctx->parameters.init_random = array.init_random[array.iterators[4]]; baryonyx::notice(ctx, " - optimization with theta:{} delta:{} " "kappa-min:{} kappa-step:{} init-random:{} ", ctx->parameters.theta, ctx->parameters.delta, ctx->parameters.kappa_min, ctx->parameters.kappa_step, ctx->parameters.init_random); auto ret = baryonyx::itm::optimize(ctx, pb); if (ret) { baryonyx::notice(ctx, "{:f}\n", ret.solutions.back().value); if (best > ret.solutions.back().value) { best = ret.solutions.back().value; std::copy(array.iterators.get(), array.iterators.get() + array.length, best_params.get()); } } else { baryonyx::notice(ctx, "no solution\n"); } } while (array.next()); baryonyx::notice( ctx, " - manual optimization found solution {:f}: with theta:{} " "delta:{} kappa-min:{} kappa-step:{} init-random:{}\n", best, array.theta[array.iterators[0]], array.delta[array.iterators[1]], array.kappa_min[array.iterators[2]], array.kappa_step[array.iterators[3]], array.init_random[array.iterators[4]]); ctx->log_priority = old_log_priority; return baryonyx::itm::optimize(ctx, pb); } namespace baryonyx { namespace itm { result manual_optimize(const baryonyx::context_ptr& ctx, const baryonyx::problem& pb) { baryonyx::notice(ctx, "- auto-tune parameters (manual) starts\n"); return ::optimize(ctx, pb); } } // namespace itm } // namespace baryonyx <commit_msg>optimizer: starts with user's parameters<commit_after>/* Copyright (C) 2018 INRA * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <array> #include "debug.hpp" #include "itm.hpp" #include "private.hpp" #include "problem.hpp" #include "utils.hpp" struct manual_course { std::unique_ptr<double[]> theta; std::unique_ptr<double[]> delta; std::unique_ptr<double[]> kappa_min; std::unique_ptr<double[]> kappa_step; std::unique_ptr<double[]> init_random; std::unique_ptr<int[]> iterators; const int length; manual_course(double theta_, double delta_, double kappa_min_, double kappa_step_, double init_random_, int length_) : theta(std::make_unique<double[]>(length_)) , delta(std::make_unique<double[]>(length_)) , kappa_min(std::make_unique<double[]>(length_)) , kappa_step(std::make_unique<double[]>(length_)) , init_random(std::make_unique<double[]>(length_)) , iterators(std::make_unique<int[]>(length_)) , length(length_) { bx_ensures(length > 2); theta[0] = theta_; theta[1] = 1.0 / static_cast<double>(length); delta[0] = delta_; delta[1] = 0.1 / static_cast<double>(length); kappa_min[0] = kappa_min_; kappa_min[1] = 1e-2 / static_cast<double>(length); kappa_step[0] = kappa_step_; kappa_step[1] = 1e-7 / static_cast<double>(length); init_random[0] = init_random_; init_random[1] = 0.9 / static_cast<double>(length); for (int i = 2; i != length; ++i) theta[i] = theta[i - 1] + 1.0 / static_cast<double>(length); for (int i = 2; i != length; ++i) delta[i] = theta[i - 1] + 0.1 / (5.0 * static_cast<double>(length)); for (int i = 2; i != length; ++i) kappa_min[i] = theta[i - 1] + 1e-2 / static_cast<double>(length); for (int i = 2; i != length; ++i) kappa_step[i] = theta[i - 1] + 1e-7 / (5.0 * static_cast<double>(length)); for (int i = 2; i != length; ++i) init_random[i] = theta[i - 1] + 0.9 / static_cast<double>(length); reset(); } void reset() { std::fill(iterators.get(), iterators.get() + length, 0); } bool next() { for (int i = length - 1; i >= 0; --i) { if (iterators[i] + 1 >= length) { iterators[i] = 0; } else { ++iterators[i]; return true; } } return false; } }; static baryonyx::result optimize(const baryonyx::context_ptr& ctx, const baryonyx::problem& pb) { manual_course array(ctx->parameters.theta, ctx->parameters.delta, ctx->parameters.kappa_min, ctx->parameters.kappa_step, ctx->parameters.init_random, 5); auto old_log_priority = ctx->log_priority; ctx->log_priority = baryonyx::context::message_type::notice; auto best_params = std::make_unique<int[]>(array.length); double best = +HUGE_VAL; do { ctx->parameters.theta = array.theta[array.iterators[0]]; ctx->parameters.delta = array.delta[array.iterators[1]]; ctx->parameters.kappa_min = array.kappa_min[array.iterators[2]]; ctx->parameters.kappa_step = array.kappa_step[array.iterators[3]]; ctx->parameters.init_random = array.init_random[array.iterators[4]]; baryonyx::notice(ctx, " - optimization with theta:{} delta:{} " "kappa-min:{} kappa-step:{} init-random:{} ", ctx->parameters.theta, ctx->parameters.delta, ctx->parameters.kappa_min, ctx->parameters.kappa_step, ctx->parameters.init_random); auto ret = baryonyx::itm::optimize(ctx, pb); if (ret) { baryonyx::notice(ctx, "{:f}\n", ret.solutions.back().value); if (best > ret.solutions.back().value) { best = ret.solutions.back().value; std::copy(array.iterators.get(), array.iterators.get() + array.length, best_params.get()); } } else { baryonyx::notice(ctx, "no solution\n"); } } while (array.next()); baryonyx::notice( ctx, " - manual optimization found solution {:f}: with theta:{} " "delta:{} kappa-min:{} kappa-step:{} init-random:{}\n", best, array.theta[array.iterators[0]], array.delta[array.iterators[1]], array.kappa_min[array.iterators[2]], array.kappa_step[array.iterators[3]], array.init_random[array.iterators[4]]); ctx->log_priority = old_log_priority; return baryonyx::itm::optimize(ctx, pb); } namespace baryonyx { namespace itm { result manual_optimize(const baryonyx::context_ptr& ctx, const baryonyx::problem& pb) { baryonyx::notice(ctx, "- auto-tune parameters (manual) starts\n"); return ::optimize(ctx, pb); } } // namespace itm } // namespace baryonyx <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <tools/debug.hxx> #include <tools/rational.hxx> #include <tools/stream.hxx> // If dVal > LONG_MAX or dVal < LONG_MIN, the rational throws a boost::bad_rational. // Otherwise, dVal and denominator are multiplied with 10, until one of them // is larger than (LONG_MAX / 10). boost::rational<long> rational_FromDouble(double dVal) { long nDen = 1; long nMAX = LONG_MAX / 10; if ( dVal > LONG_MAX || dVal < LONG_MIN ) { throw boost::bad_rational(); } while ( std::abs( (long)dVal ) < nMAX && nDen < nMAX ) { dVal *= 10; nDen *= 10; } return boost::rational<long>((long) dVal, nDen); } // Similar to clz_table that can be googled const char nbits_table[32] = { 32, 1, 23, 2, 29, 24, 14, 3, 30, 27, 25, 18, 20, 15, 10, 4, 31, 22, 28, 13, 26, 17, 19, 9, 21, 12, 16, 8, 11, 7, 6, 5 }; static int impl_NumberOfBits( unsigned long nNum ) { // http://en.wikipedia.org/wiki/De_Bruijn_sequence // background paper: Using de Bruijn Sequences to Index a 1 in a // Computer Word (1998) Charles E. Leiserson, // Harald Prokop, Keith H. Randall // (e.g. http://citeseer.ist.psu.edu/leiserson98using.html) const sal_uInt32 nDeBruijn = 0x7DCD629; if ( nNum == 0 ) return 0; // Get it to form like 0000001111111111b nNum |= ( nNum >> 1 ); nNum |= ( nNum >> 2 ); nNum |= ( nNum >> 4 ); nNum |= ( nNum >> 8 ); nNum |= ( nNum >> 16 ); sal_uInt32 nNumber; int nBonus = 0; #if SAL_TYPES_SIZEOFLONG == 4 nNumber = nNum; #elif SAL_TYPES_SIZEOFLONG == 8 nNum |= ( nNum >> 32 ); if ( nNum & 0x80000000 ) { nNumber = sal_uInt32( nNum >> 32 ); nBonus = 32; if ( nNumber == 0 ) return 32; } else nNumber = sal_uInt32( nNum & 0xFFFFFFFF ); #else #error "Unknown size of long!" #endif // De facto shift left of nDeBruijn using multiplication (nNumber // is all ones from topmost bit, thus nDeBruijn + (nDeBruijn * // nNumber) => nDeBruijn * (nNumber+1) clears all those bits to // zero, sets the next bit to one, and thus effectively shift-left // nDeBruijn by lg2(nNumber+1). This generates a distinct 5bit // sequence in the msb for each distinct position of the last // leading 0 bit - that's the property of a de Bruijn number. nNumber = nDeBruijn + ( nDeBruijn * nNumber ); // 5-bit window indexes the result return ( nbits_table[nNumber >> 27] ) + nBonus; } /** Inaccurate cancellation for a fraction. Clip both nominator and denominator to said number of bits. If either of those already have equal or less number of bits used, this method does nothing. @param nSignificantBits denotes, how many significant binary digits to maintain, in both nominator and denominator. @example ReduceInaccurate(8) has an error <1% [1/2^(8-1)] - the largest error occurs with the following pair of values: binary 1000000011111111111111111111111b/1000000000000000000000000000000b = 1082130431/1073741824 = approx. 1.007812499 A ReduceInaccurate(8) yields 1/1. */ void rational_ReduceInaccurate(boost::rational<long>& rRational, unsigned nSignificantBits) { if ( !rRational.numerator() || !rRational.denominator() ) return; // Count with unsigned longs only // http://www.boost.org/doc/libs/release/libs/rational/rational.html#Internal%20representation const bool bNeg = ( rRational < 0 ); unsigned long nMul = (unsigned long)( bNeg? -rRational.numerator(): rRational.numerator() ); unsigned long nDiv = (unsigned long)( rRational.denominator() ); DBG_ASSERT(nSignificantBits<65, "More than 64 bit of significance is overkill!"); // How much bits can we lose? const int nMulBitsToLose = std::max( ( impl_NumberOfBits( nMul ) - int( nSignificantBits ) ), 0 ); const int nDivBitsToLose = std::max( ( impl_NumberOfBits( nDiv ) - int( nSignificantBits ) ), 0 ); const int nToLose = std::min( nMulBitsToLose, nDivBitsToLose ); // Remove the bits nMul >>= nToLose; nDiv >>= nToLose; if ( !nMul || !nDiv ) { // Return without reduction OSL_FAIL( "Oops, we reduced too much..." ); return; } rRational.assign( bNeg? -long( nMul ): long( nMul ), nDiv ); } SvStream& ReadFraction(SvStream& rIStream, boost::rational<long>& rRational) { sal_Int32 nTmpNumerator(0), nTmpDenominator(0); rIStream.ReadInt32( nTmpNumerator ); rIStream.ReadInt32( nTmpDenominator ); // NOTE: use rational zero for invalid rationals - avoid boost::bad_rational() exception if (nTmpDenominator == 0) { nTmpNumerator = 0; nTmpDenominator = 1; } rRational.assign( nTmpNumerator, nTmpDenominator ); return rIStream; } SvStream& WriteFraction(SvStream& rOStream, const boost::rational<long>& rRational) { //fdo#39428 SvStream no longer supports operator<<(long) rOStream.WriteInt32( sal::static_int_cast<sal_Int32>(rRational.numerator()) ); rOStream.WriteInt32( sal::static_int_cast<sal_Int32>(rRational.denominator()) ); return rOStream; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>simplify condition<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <tools/debug.hxx> #include <tools/rational.hxx> #include <tools/stream.hxx> // If dVal > LONG_MAX or dVal < LONG_MIN, the rational throws a boost::bad_rational. // Otherwise, dVal and denominator are multiplied with 10, until one of them // is larger than (LONG_MAX / 10). boost::rational<long> rational_FromDouble(double dVal) { long nDen = 1; long nMAX = LONG_MAX / 10; if ( dVal > LONG_MAX || dVal < LONG_MIN ) { throw boost::bad_rational(); } while ( std::abs( (long)dVal ) < nMAX && nDen < nMAX ) { dVal *= 10; nDen *= 10; } return boost::rational<long>((long) dVal, nDen); } // Similar to clz_table that can be googled const char nbits_table[32] = { 32, 1, 23, 2, 29, 24, 14, 3, 30, 27, 25, 18, 20, 15, 10, 4, 31, 22, 28, 13, 26, 17, 19, 9, 21, 12, 16, 8, 11, 7, 6, 5 }; static int impl_NumberOfBits( unsigned long nNum ) { // http://en.wikipedia.org/wiki/De_Bruijn_sequence // background paper: Using de Bruijn Sequences to Index a 1 in a // Computer Word (1998) Charles E. Leiserson, // Harald Prokop, Keith H. Randall // (e.g. http://citeseer.ist.psu.edu/leiserson98using.html) const sal_uInt32 nDeBruijn = 0x7DCD629; if ( nNum == 0 ) return 0; // Get it to form like 0000001111111111b nNum |= ( nNum >> 1 ); nNum |= ( nNum >> 2 ); nNum |= ( nNum >> 4 ); nNum |= ( nNum >> 8 ); nNum |= ( nNum >> 16 ); sal_uInt32 nNumber; int nBonus = 0; #if SAL_TYPES_SIZEOFLONG == 4 nNumber = nNum; #elif SAL_TYPES_SIZEOFLONG == 8 nNum |= ( nNum >> 32 ); if ( nNum & 0x80000000 ) { nNumber = sal_uInt32( nNum >> 32 ); nBonus = 32; if ( nNumber == 0 ) return 32; } else nNumber = sal_uInt32( nNum & 0xFFFFFFFF ); #else #error "Unknown size of long!" #endif // De facto shift left of nDeBruijn using multiplication (nNumber // is all ones from topmost bit, thus nDeBruijn + (nDeBruijn * // nNumber) => nDeBruijn * (nNumber+1) clears all those bits to // zero, sets the next bit to one, and thus effectively shift-left // nDeBruijn by lg2(nNumber+1). This generates a distinct 5bit // sequence in the msb for each distinct position of the last // leading 0 bit - that's the property of a de Bruijn number. nNumber = nDeBruijn + ( nDeBruijn * nNumber ); // 5-bit window indexes the result return ( nbits_table[nNumber >> 27] ) + nBonus; } /** Inaccurate cancellation for a fraction. Clip both nominator and denominator to said number of bits. If either of those already have equal or less number of bits used, this method does nothing. @param nSignificantBits denotes, how many significant binary digits to maintain, in both nominator and denominator. @example ReduceInaccurate(8) has an error <1% [1/2^(8-1)] - the largest error occurs with the following pair of values: binary 1000000011111111111111111111111b/1000000000000000000000000000000b = 1082130431/1073741824 = approx. 1.007812499 A ReduceInaccurate(8) yields 1/1. */ void rational_ReduceInaccurate(boost::rational<long>& rRational, unsigned nSignificantBits) { if ( !rRational ) return; // Count with unsigned longs only // http://www.boost.org/doc/libs/release/libs/rational/rational.html#Internal%20representation const bool bNeg = ( rRational < 0 ); unsigned long nMul = (unsigned long)( bNeg? -rRational.numerator(): rRational.numerator() ); unsigned long nDiv = (unsigned long)( rRational.denominator() ); DBG_ASSERT(nSignificantBits<65, "More than 64 bit of significance is overkill!"); // How much bits can we lose? const int nMulBitsToLose = std::max( ( impl_NumberOfBits( nMul ) - int( nSignificantBits ) ), 0 ); const int nDivBitsToLose = std::max( ( impl_NumberOfBits( nDiv ) - int( nSignificantBits ) ), 0 ); const int nToLose = std::min( nMulBitsToLose, nDivBitsToLose ); // Remove the bits nMul >>= nToLose; nDiv >>= nToLose; if ( !nMul || !nDiv ) { // Return without reduction OSL_FAIL( "Oops, we reduced too much..." ); return; } rRational.assign( bNeg? -long( nMul ): long( nMul ), nDiv ); } SvStream& ReadFraction(SvStream& rIStream, boost::rational<long>& rRational) { sal_Int32 nTmpNumerator(0), nTmpDenominator(0); rIStream.ReadInt32( nTmpNumerator ); rIStream.ReadInt32( nTmpDenominator ); // NOTE: use rational zero for invalid rationals - avoid boost::bad_rational() exception if (nTmpDenominator == 0) { nTmpNumerator = 0; nTmpDenominator = 1; } rRational.assign( nTmpNumerator, nTmpDenominator ); return rIStream; } SvStream& WriteFraction(SvStream& rOStream, const boost::rational<long>& rRational) { //fdo#39428 SvStream no longer supports operator<<(long) rOStream.WriteInt32( sal::static_int_cast<sal_Int32>(rRational.numerator()) ); rOStream.WriteInt32( sal::static_int_cast<sal_Int32>(rRational.denominator()) ); return rOStream; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>//===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCContext.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCLabel.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSectionCOFF.h" #include "llvm/MC/MCSectionELF.h" #include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/ELF.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include <map> using namespace llvm; typedef std::pair<std::string, std::string> SectionGroupPair; typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy; typedef std::map<SectionGroupPair, const MCSectionELF *> ELFUniqueMapTy; typedef std::map<SectionGroupPair, const MCSectionCOFF *> COFFUniqueMapTy; MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri, const MCObjectFileInfo *mofi, const SourceMgr *mgr, bool DoAutoReset) : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(), Symbols(Allocator), UsedNames(Allocator), NextUniqueID(0), CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0), DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0), AllowTemporaryLabels(true), DwarfCompileUnitID(0), AutoReset(DoAutoReset) { error_code EC = llvm::sys::fs::current_path(CompilationDir); if (EC) CompilationDir.clear(); MachOUniquingMap = 0; ELFUniquingMap = 0; COFFUniquingMap = 0; SecureLogFile = getenv("AS_SECURE_LOG_FILE"); SecureLog = 0; SecureLogUsed = false; if (SrcMgr && SrcMgr->getNumBuffers() > 0) MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier(); else MainFileName = ""; } MCContext::~MCContext() { if (AutoReset) reset(); // NOTE: The symbols are all allocated out of a bump pointer allocator, // we don't need to free them here. // If the stream for the .secure_log_unique directive was created free it. delete (raw_ostream*)SecureLog; } //===----------------------------------------------------------------------===// // Module Lifetime Management //===----------------------------------------------------------------------===// void MCContext::reset() { UsedNames.clear(); Symbols.clear(); Allocator.Reset(); Instances.clear(); MCDwarfLineTablesCUMap.clear(); MCGenDwarfLabelEntries.clear(); DwarfDebugFlags = StringRef(); DwarfCompileUnitID = 0; CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0); // If we have the MachO uniquing map, free it. delete (MachOUniqueMapTy*)MachOUniquingMap; delete (ELFUniqueMapTy*)ELFUniquingMap; delete (COFFUniqueMapTy*)COFFUniquingMap; MachOUniquingMap = 0; ELFUniquingMap = 0; COFFUniquingMap = 0; NextUniqueID = 0; AllowTemporaryLabels = true; DwarfLocSeen = false; GenDwarfForAssembly = false; GenDwarfFileNumber = 0; } //===----------------------------------------------------------------------===// // Symbol Manipulation //===----------------------------------------------------------------------===// MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) { assert(!Name.empty() && "Normal symbols cannot be unnamed!"); // Do the lookup and get the entire StringMapEntry. We want access to the // key if we are creating the entry. StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name); MCSymbol *Sym = Entry.getValue(); if (Sym) return Sym; Sym = CreateSymbol(Name); Entry.setValue(Sym); return Sym; } MCSymbol *MCContext::CreateSymbol(StringRef Name) { // Determine whether this is an assembler temporary or normal label, if used. bool isTemporary = false; if (AllowTemporaryLabels) isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix()); StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name); if (NameEntry->getValue()) { assert(isTemporary && "Cannot rename non-temporary symbols"); SmallString<128> NewName = Name; do { NewName.resize(Name.size()); raw_svector_ostream(NewName) << NextUniqueID++; NameEntry = &UsedNames.GetOrCreateValue(NewName); } while (NameEntry->getValue()); } NameEntry->setValue(true); // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer // to the copy of the string that is embedded in the UsedNames entry. MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary); return Result; } MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) { SmallString<128> NameSV; return GetOrCreateSymbol(Name.toStringRef(NameSV)); } MCSymbol *MCContext::CreateTempSymbol() { SmallString<128> NameSV; raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++; return CreateSymbol(NameSV); } unsigned MCContext::NextInstance(unsigned LocalLabelVal) { MCLabel *&Label = Instances[LocalLabelVal]; if (!Label) Label = new (*this) MCLabel(0); return Label->incInstance(); } unsigned MCContext::GetInstance(unsigned LocalLabelVal) { MCLabel *&Label = Instances[LocalLabelVal]; if (!Label) Label = new (*this) MCLabel(0); return Label->getInstance(); } MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal, unsigned Instance) { MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)]; if (!Sym) Sym = CreateTempSymbol(); return Sym; } MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) { unsigned Instance = NextInstance(LocalLabelVal); return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); } MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before) { unsigned Instance = GetInstance(LocalLabelVal); if (!Before) ++Instance; return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); } MCSymbol *MCContext::LookupSymbol(StringRef Name) const { return Symbols.lookup(Name); } MCSymbol *MCContext::LookupSymbol(const Twine &Name) const { SmallString<128> NameSV; Name.toVector(NameSV); return LookupSymbol(NameSV.str()); } //===----------------------------------------------------------------------===// // Section Management //===----------------------------------------------------------------------===// const MCSectionMachO *MCContext:: getMachOSection(StringRef Segment, StringRef Section, unsigned TypeAndAttributes, unsigned Reserved2, SectionKind Kind) { // We unique sections by their segment/section pair. The returned section // may not have the same flags as the requested section, if so this should be // diagnosed by the client as an error. // Create the map if it doesn't already exist. if (MachOUniquingMap == 0) MachOUniquingMap = new MachOUniqueMapTy(); MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap; // Form the name to look up. SmallString<64> Name; Name += Segment; Name.push_back(','); Name += Section; // Do the lookup, if we have a hit, return it. const MCSectionMachO *&Entry = Map[Name.str()]; if (Entry) return Entry; // Otherwise, return a new section. return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes, Reserved2, Kind); } const MCSectionELF *MCContext:: getELFSection(StringRef Section, unsigned Type, unsigned Flags, SectionKind Kind) { return getELFSection(Section, Type, Flags, Kind, 0, ""); } const MCSectionELF *MCContext:: getELFSection(StringRef Section, unsigned Type, unsigned Flags, SectionKind Kind, unsigned EntrySize, StringRef Group) { if (ELFUniquingMap == 0) ELFUniquingMap = new ELFUniqueMapTy(); ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap; // Do the lookup, if we have a hit, return it. std::pair<ELFUniqueMapTy::iterator, bool> Entry = Map.insert( std::make_pair(SectionGroupPair(Section, Group), (MCSectionELF *)0)); if (!Entry.second) return Entry.first->second; // Possibly refine the entry size first. if (!EntrySize) { EntrySize = MCSectionELF::DetermineEntrySize(Kind); } MCSymbol *GroupSym = NULL; if (!Group.empty()) GroupSym = GetOrCreateSymbol(Group); MCSectionELF *Result = new (*this) MCSectionELF( Entry.first->first.first, Type, Flags, Kind, EntrySize, GroupSym); Entry.first->second = Result; return Result; } const MCSectionELF *MCContext::CreateELFGroupSection() { MCSectionELF *Result = new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4, NULL); return Result; } const MCSectionCOFF * MCContext::getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, const MCSectionCOFF *Assoc) { if (COFFUniquingMap == 0) COFFUniquingMap = new COFFUniqueMapTy(); COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap; // Do the lookup, if we have a hit, return it. SectionGroupPair P(Section, COMDATSymName); std::pair<COFFUniqueMapTy::iterator, bool> Entry = Map.insert(std::make_pair(P, (MCSectionCOFF *)0)); COFFUniqueMapTy::iterator Iter = Entry.first; if (!Entry.second) return Iter->second; const MCSymbol *COMDATSymbol = NULL; if (!COMDATSymName.empty()) COMDATSymbol = GetOrCreateSymbol(COMDATSymName); MCSectionCOFF *Result = new (*this) MCSectionCOFF(Iter->first.first, Characteristics, COMDATSymbol, Selection, Assoc, Kind); Iter->second = Result; return Result; } const MCSectionCOFF * MCContext::getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind) { return getCOFFSection(Section, Characteristics, Kind, "", 0); } const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) { if (COFFUniquingMap == 0) COFFUniquingMap = new COFFUniqueMapTy(); COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap; SectionGroupPair P(Section, ""); COFFUniqueMapTy::iterator Iter = Map.find(P); if (Iter == Map.end()) return 0; return Iter->second; } //===----------------------------------------------------------------------===// // Dwarf Management //===----------------------------------------------------------------------===// /// GetDwarfFile - takes a file name an number to place in the dwarf file and /// directory tables. If the file number has already been allocated it is an /// error and zero is returned and the client reports the error, else the /// allocated file number is returned. The file numbers may be in any order. unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName, unsigned FileNumber, unsigned CUID) { MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID]; return Table.getFile(Directory, FileName, FileNumber); } /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it /// currently is assigned and false otherwise. bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) { const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID); if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size()) return false; return !MCDwarfFiles[FileNumber].Name.empty(); } void MCContext::FatalError(SMLoc Loc, const Twine &Msg) { // If we have a source manager and a location, use it. Otherwise just // use the generic report_fatal_error(). if (!SrcMgr || Loc == SMLoc()) report_fatal_error(Msg); // Use the source manager to print the message. SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg); // If we reached here, we are failing ungracefully. Run the interrupt handlers // to make sure any special cleanups get done, in particular that we remove // files registered with RemoveFileOnSignal. sys::RunInterruptHandlers(); exit(1); } <commit_msg>MCContext: Remove redundant assignment<commit_after>//===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCContext.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCLabel.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSectionCOFF.h" #include "llvm/MC/MCSectionELF.h" #include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/ELF.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include <map> using namespace llvm; typedef std::pair<std::string, std::string> SectionGroupPair; typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy; typedef std::map<SectionGroupPair, const MCSectionELF *> ELFUniqueMapTy; typedef std::map<SectionGroupPair, const MCSectionCOFF *> COFFUniqueMapTy; MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri, const MCObjectFileInfo *mofi, const SourceMgr *mgr, bool DoAutoReset) : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(), Symbols(Allocator), UsedNames(Allocator), NextUniqueID(0), CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0), DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0), AllowTemporaryLabels(true), DwarfCompileUnitID(0), AutoReset(DoAutoReset) { error_code EC = llvm::sys::fs::current_path(CompilationDir); if (EC) CompilationDir.clear(); MachOUniquingMap = 0; ELFUniquingMap = 0; COFFUniquingMap = 0; SecureLogFile = getenv("AS_SECURE_LOG_FILE"); SecureLog = 0; SecureLogUsed = false; if (SrcMgr && SrcMgr->getNumBuffers() > 0) MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier(); } MCContext::~MCContext() { if (AutoReset) reset(); // NOTE: The symbols are all allocated out of a bump pointer allocator, // we don't need to free them here. // If the stream for the .secure_log_unique directive was created free it. delete (raw_ostream*)SecureLog; } //===----------------------------------------------------------------------===// // Module Lifetime Management //===----------------------------------------------------------------------===// void MCContext::reset() { UsedNames.clear(); Symbols.clear(); Allocator.Reset(); Instances.clear(); MCDwarfLineTablesCUMap.clear(); MCGenDwarfLabelEntries.clear(); DwarfDebugFlags = StringRef(); DwarfCompileUnitID = 0; CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0); // If we have the MachO uniquing map, free it. delete (MachOUniqueMapTy*)MachOUniquingMap; delete (ELFUniqueMapTy*)ELFUniquingMap; delete (COFFUniqueMapTy*)COFFUniquingMap; MachOUniquingMap = 0; ELFUniquingMap = 0; COFFUniquingMap = 0; NextUniqueID = 0; AllowTemporaryLabels = true; DwarfLocSeen = false; GenDwarfForAssembly = false; GenDwarfFileNumber = 0; } //===----------------------------------------------------------------------===// // Symbol Manipulation //===----------------------------------------------------------------------===// MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) { assert(!Name.empty() && "Normal symbols cannot be unnamed!"); // Do the lookup and get the entire StringMapEntry. We want access to the // key if we are creating the entry. StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name); MCSymbol *Sym = Entry.getValue(); if (Sym) return Sym; Sym = CreateSymbol(Name); Entry.setValue(Sym); return Sym; } MCSymbol *MCContext::CreateSymbol(StringRef Name) { // Determine whether this is an assembler temporary or normal label, if used. bool isTemporary = false; if (AllowTemporaryLabels) isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix()); StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name); if (NameEntry->getValue()) { assert(isTemporary && "Cannot rename non-temporary symbols"); SmallString<128> NewName = Name; do { NewName.resize(Name.size()); raw_svector_ostream(NewName) << NextUniqueID++; NameEntry = &UsedNames.GetOrCreateValue(NewName); } while (NameEntry->getValue()); } NameEntry->setValue(true); // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer // to the copy of the string that is embedded in the UsedNames entry. MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary); return Result; } MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) { SmallString<128> NameSV; return GetOrCreateSymbol(Name.toStringRef(NameSV)); } MCSymbol *MCContext::CreateTempSymbol() { SmallString<128> NameSV; raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++; return CreateSymbol(NameSV); } unsigned MCContext::NextInstance(unsigned LocalLabelVal) { MCLabel *&Label = Instances[LocalLabelVal]; if (!Label) Label = new (*this) MCLabel(0); return Label->incInstance(); } unsigned MCContext::GetInstance(unsigned LocalLabelVal) { MCLabel *&Label = Instances[LocalLabelVal]; if (!Label) Label = new (*this) MCLabel(0); return Label->getInstance(); } MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal, unsigned Instance) { MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)]; if (!Sym) Sym = CreateTempSymbol(); return Sym; } MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) { unsigned Instance = NextInstance(LocalLabelVal); return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); } MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before) { unsigned Instance = GetInstance(LocalLabelVal); if (!Before) ++Instance; return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); } MCSymbol *MCContext::LookupSymbol(StringRef Name) const { return Symbols.lookup(Name); } MCSymbol *MCContext::LookupSymbol(const Twine &Name) const { SmallString<128> NameSV; Name.toVector(NameSV); return LookupSymbol(NameSV.str()); } //===----------------------------------------------------------------------===// // Section Management //===----------------------------------------------------------------------===// const MCSectionMachO *MCContext:: getMachOSection(StringRef Segment, StringRef Section, unsigned TypeAndAttributes, unsigned Reserved2, SectionKind Kind) { // We unique sections by their segment/section pair. The returned section // may not have the same flags as the requested section, if so this should be // diagnosed by the client as an error. // Create the map if it doesn't already exist. if (MachOUniquingMap == 0) MachOUniquingMap = new MachOUniqueMapTy(); MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap; // Form the name to look up. SmallString<64> Name; Name += Segment; Name.push_back(','); Name += Section; // Do the lookup, if we have a hit, return it. const MCSectionMachO *&Entry = Map[Name.str()]; if (Entry) return Entry; // Otherwise, return a new section. return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes, Reserved2, Kind); } const MCSectionELF *MCContext:: getELFSection(StringRef Section, unsigned Type, unsigned Flags, SectionKind Kind) { return getELFSection(Section, Type, Flags, Kind, 0, ""); } const MCSectionELF *MCContext:: getELFSection(StringRef Section, unsigned Type, unsigned Flags, SectionKind Kind, unsigned EntrySize, StringRef Group) { if (ELFUniquingMap == 0) ELFUniquingMap = new ELFUniqueMapTy(); ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap; // Do the lookup, if we have a hit, return it. std::pair<ELFUniqueMapTy::iterator, bool> Entry = Map.insert( std::make_pair(SectionGroupPair(Section, Group), (MCSectionELF *)0)); if (!Entry.second) return Entry.first->second; // Possibly refine the entry size first. if (!EntrySize) { EntrySize = MCSectionELF::DetermineEntrySize(Kind); } MCSymbol *GroupSym = NULL; if (!Group.empty()) GroupSym = GetOrCreateSymbol(Group); MCSectionELF *Result = new (*this) MCSectionELF( Entry.first->first.first, Type, Flags, Kind, EntrySize, GroupSym); Entry.first->second = Result; return Result; } const MCSectionELF *MCContext::CreateELFGroupSection() { MCSectionELF *Result = new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4, NULL); return Result; } const MCSectionCOFF * MCContext::getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, const MCSectionCOFF *Assoc) { if (COFFUniquingMap == 0) COFFUniquingMap = new COFFUniqueMapTy(); COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap; // Do the lookup, if we have a hit, return it. SectionGroupPair P(Section, COMDATSymName); std::pair<COFFUniqueMapTy::iterator, bool> Entry = Map.insert(std::make_pair(P, (MCSectionCOFF *)0)); COFFUniqueMapTy::iterator Iter = Entry.first; if (!Entry.second) return Iter->second; const MCSymbol *COMDATSymbol = NULL; if (!COMDATSymName.empty()) COMDATSymbol = GetOrCreateSymbol(COMDATSymName); MCSectionCOFF *Result = new (*this) MCSectionCOFF(Iter->first.first, Characteristics, COMDATSymbol, Selection, Assoc, Kind); Iter->second = Result; return Result; } const MCSectionCOFF * MCContext::getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind) { return getCOFFSection(Section, Characteristics, Kind, "", 0); } const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) { if (COFFUniquingMap == 0) COFFUniquingMap = new COFFUniqueMapTy(); COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap; SectionGroupPair P(Section, ""); COFFUniqueMapTy::iterator Iter = Map.find(P); if (Iter == Map.end()) return 0; return Iter->second; } //===----------------------------------------------------------------------===// // Dwarf Management //===----------------------------------------------------------------------===// /// GetDwarfFile - takes a file name an number to place in the dwarf file and /// directory tables. If the file number has already been allocated it is an /// error and zero is returned and the client reports the error, else the /// allocated file number is returned. The file numbers may be in any order. unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName, unsigned FileNumber, unsigned CUID) { MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID]; return Table.getFile(Directory, FileName, FileNumber); } /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it /// currently is assigned and false otherwise. bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) { const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID); if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size()) return false; return !MCDwarfFiles[FileNumber].Name.empty(); } void MCContext::FatalError(SMLoc Loc, const Twine &Msg) { // If we have a source manager and a location, use it. Otherwise just // use the generic report_fatal_error(). if (!SrcMgr || Loc == SMLoc()) report_fatal_error(Msg); // Use the source manager to print the message. SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg); // If we reached here, we are failing ungracefully. Run the interrupt handlers // to make sure any special cleanups get done, in particular that we remove // files registered with RemoveFileOnSignal. sys::RunInterruptHandlers(); exit(1); } <|endoftext|>
<commit_before>#include "consolestream.h" #include <iostream> ConsoleStream::ConsoleStream(int which): _which(which) { if (which!=out&&which!=warning&&which!=error) { throw "error"; } } void ConsoleStream::print(short val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(unsigned short val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(int val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(unsigned int val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(long val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(unsigned long val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(float val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(double val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(const char* val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(const std::string& val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::flush() { switch(_which) { case out: std::cout << std::flush; break; case warning: std::cout << std::flush; break; case error: std::cerr << std::flush; break; } } ConsoleStream& ConsoleStream::operator<<(short val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(unsigned short val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(int val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(unsigned int val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(long val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(unsigned long val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(float val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(double val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(const char* val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(const std::string& val) { print(val); return *this; } <commit_msg>Modified consolestream class.<commit_after>#include "consolestream.h" #include <iostream> #include "exception.h" ConsoleStream::ConsoleStream(int which): _which(which) { if (which!=out&&which!=warning&&which!=error) { throw InvalidInput(__FILE__,__LINE__); } } void ConsoleStream::print(short val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(unsigned short val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(int val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(unsigned int val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(long val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(unsigned long val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(float val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(double val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(const char* val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::print(const std::string& val) { switch(_which) { case out: std::cout << val; break; case warning: std::cout << val; break; case error: std::cerr << val; break; } } void ConsoleStream::flush() { switch(_which) { case out: std::cout << std::flush; break; case warning: std::cout << std::flush; break; case error: std::cerr << std::flush; break; } } ConsoleStream& ConsoleStream::operator<<(short val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(unsigned short val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(int val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(unsigned int val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(long val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(unsigned long val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(float val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(double val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(const char* val) { print(val); return *this; } ConsoleStream& ConsoleStream::operator<<(const std::string& val) { print(val); return *this; } <|endoftext|>
<commit_before>/* * LexicalReordering.cpp * * Created on: 15 Dec 2015 * Author: hieu */ #include "LexicalReordering.h" #include "../System.h" #include "../Search/Manager.h" #include "../legacy/InputFileStream.h" using namespace std; namespace Moses2 { struct LexicalReorderingState : public FFState { const InputPath *path; const TargetPhrase *targetPhrase; LexicalReorderingState() { // uninitialised } size_t hash() const { // compare range address. All ranges are created in InputPath return (size_t) &path->range; } virtual bool operator==(const FFState& other) const { // compare range address. All ranges are created in InputPath const LexicalReorderingState &stateCast = static_cast<const LexicalReorderingState&>(other); return &path->range == &stateCast.path->range; } virtual std::string ToString() const { return ""; } }; /////////////////////////////////////////////////////////////////////// LexicalReordering::LexicalReordering(size_t startInd, const std::string &line) :StatefulFeatureFunction(startInd, line) { ReadParameters(); assert(m_numScores == 6); } LexicalReordering::~LexicalReordering() { // TODO Auto-generated destructor stub } void LexicalReordering::Load(System &system) { InputFileStream file(m_path); string line; size_t lineNum = 0; while(getline(file, line)) { if (++lineNum % 1000000 == 0) { cerr << lineNum << " "; } std::vector<std::string> toks = TokenizeMultiCharSeparator(line, "|||"); assert(toks.size() == 3); PhraseImpl *source = PhraseImpl::CreateFromString(system.systemPool, system.GetVocab(), system, toks[0]); PhraseImpl *target = PhraseImpl::CreateFromString(system.systemPool, system.GetVocab(), system, toks[1]); std::vector<SCORE> scores = Tokenize<SCORE>(toks[2]); std::transform(scores.begin(), scores.end(), scores.begin(), TransformScore); Key key(source, target); m_coll[key] = scores; } } void LexicalReordering::SetParameter(const std::string& key, const std::string& value) { if (key == "path") { m_path = value; } else if (key == "type") { } else if (key == "input-factor") { } else if (key == "output-factor") { } else { StatefulFeatureFunction::SetParameter(key, value); } } FFState* LexicalReordering::BlankState(const Manager &mgr, const InputType &input) const { MemPool &pool = mgr.GetPool(); return new (pool.Allocate<LexicalReorderingState>()) LexicalReorderingState(); } void LexicalReordering::EmptyHypothesisState(FFState &state, const Manager &mgr, const InputType &input, const Hypothesis &hypo) const { LexicalReorderingState &stateCast = static_cast<LexicalReorderingState&>(state); stateCast.path = &hypo.GetInputPath(); stateCast.targetPhrase = &hypo.GetTargetPhrase(); } void LexicalReordering::EvaluateInIsolation(const System &system, const Phrase &source, const TargetPhrase &targetPhrase, Scores &scores, Scores *estimatedScores) const { // cache data in target phrase const LexicalReordering::Values *values = GetValues(source, targetPhrase); if (values) { //scoreVec[orientation] = (*values)[orientation]; } } void LexicalReordering::EvaluateWhenApplied(const Manager &mgr, const Hypothesis &hypo, const FFState &prevState, Scores &scores, FFState &state) const { const LexicalReorderingState &prevStateCast = static_cast<const LexicalReorderingState&>(prevState); LexicalReorderingState &stateCast = static_cast<LexicalReorderingState&>(state); const Range &currRange = hypo.GetInputPath().range; stateCast.path = &hypo.GetInputPath(); stateCast.targetPhrase = &hypo.GetTargetPhrase(); vector<SCORE> scoreVec(m_numScores, 0); // calc orientation size_t orientation; const Range *prevRange = &prevStateCast.path->range; assert(prevRange); if (prevRange->GetStartPos() == NOT_FOUND) { orientation = GetOrientation(currRange); } else { orientation = GetOrientation(*prevRange, currRange); } // backwards const Phrase &source = hypo.GetInputPath().subPhrase; const Phrase &target = hypo.GetTargetPhrase(); const LexicalReordering::Values *values = GetValues(source, target); if (values) { scoreVec[orientation] = (*values)[orientation]; } // forwards if (prevRange->GetStartPos() != NOT_FOUND) { const Phrase &source = prevStateCast.path->subPhrase; const Phrase &target = *prevStateCast.targetPhrase; const LexicalReordering::Values *values = GetValues(source, target); if (values) { scoreVec[orientation + 3] = (*values)[orientation + 3]; } } scores.PlusEquals(mgr.system, *this, scoreVec); } const LexicalReordering::Values *LexicalReordering::GetValues(const Phrase &source, const Phrase &target) const { Key key(&source, &target); Coll::const_iterator iter; iter = m_coll.find(key); if (iter == m_coll.end()) { return NULL; } else { return &iter->second; } } size_t LexicalReordering::GetOrientation(Range const& cur) const { return (cur.GetStartPos() == 0) ? 0 : 1; } size_t LexicalReordering::GetOrientation(Range const& prev, Range const& cur) const { if (cur.GetStartPos() == prev.GetEndPos() + 1) { // monotone return 0; } else if (prev.GetStartPos() == cur.GetEndPos() + 1) { // swap return 1; } else { // discontinuous return 2; } } } /* namespace Moses2 */ <commit_msg>minor cleanup<commit_after>/* * LexicalReordering.cpp * * Created on: 15 Dec 2015 * Author: hieu */ #include "LexicalReordering.h" #include "../System.h" #include "../Search/Manager.h" #include "../legacy/InputFileStream.h" using namespace std; namespace Moses2 { struct LexicalReorderingState : public FFState { const InputPath *path; const TargetPhrase *targetPhrase; LexicalReorderingState() { // uninitialised } size_t hash() const { // compare range address. All ranges are created in InputPath return (size_t) &path->range; } virtual bool operator==(const FFState& other) const { // compare range address. All ranges are created in InputPath const LexicalReorderingState &stateCast = static_cast<const LexicalReorderingState&>(other); return &path->range == &stateCast.path->range; } virtual std::string ToString() const { return ""; } }; /////////////////////////////////////////////////////////////////////// LexicalReordering::LexicalReordering(size_t startInd, const std::string &line) :StatefulFeatureFunction(startInd, line) { ReadParameters(); assert(m_numScores == 6); } LexicalReordering::~LexicalReordering() { // TODO Auto-generated destructor stub } void LexicalReordering::Load(System &system) { InputFileStream file(m_path); string line; size_t lineNum = 0; while(getline(file, line)) { if (++lineNum % 1000000 == 0) { cerr << lineNum << " "; } std::vector<std::string> toks = TokenizeMultiCharSeparator(line, "|||"); assert(toks.size() == 3); PhraseImpl *source = PhraseImpl::CreateFromString(system.systemPool, system.GetVocab(), system, toks[0]); PhraseImpl *target = PhraseImpl::CreateFromString(system.systemPool, system.GetVocab(), system, toks[1]); std::vector<SCORE> scores = Tokenize<SCORE>(toks[2]); std::transform(scores.begin(), scores.end(), scores.begin(), TransformScore); Key key(source, target); m_coll[key] = scores; } } void LexicalReordering::SetParameter(const std::string& key, const std::string& value) { if (key == "path") { m_path = value; } else if (key == "type") { } else if (key == "input-factor") { } else if (key == "output-factor") { } else { StatefulFeatureFunction::SetParameter(key, value); } } FFState* LexicalReordering::BlankState(const Manager &mgr, const InputType &input) const { MemPool &pool = mgr.GetPool(); return new (pool.Allocate<LexicalReorderingState>()) LexicalReorderingState(); } void LexicalReordering::EmptyHypothesisState(FFState &state, const Manager &mgr, const InputType &input, const Hypothesis &hypo) const { LexicalReorderingState &stateCast = static_cast<LexicalReorderingState&>(state); stateCast.path = &hypo.GetInputPath(); stateCast.targetPhrase = &hypo.GetTargetPhrase(); } void LexicalReordering::EvaluateInIsolation(const System &system, const Phrase &source, const TargetPhrase &targetPhrase, Scores &scores, Scores *estimatedScores) const { // cache data in target phrase const Values *values = GetValues(source, targetPhrase); if (values) { //scoreVec[orientation] = (*values)[orientation]; } } void LexicalReordering::EvaluateWhenApplied(const Manager &mgr, const Hypothesis &hypo, const FFState &prevState, Scores &scores, FFState &state) const { const LexicalReorderingState &prevStateCast = static_cast<const LexicalReorderingState&>(prevState); LexicalReorderingState &stateCast = static_cast<LexicalReorderingState&>(state); const Range &currRange = hypo.GetInputPath().range; stateCast.path = &hypo.GetInputPath(); stateCast.targetPhrase = &hypo.GetTargetPhrase(); vector<SCORE> scoreVec(m_numScores, 0); // calc orientation size_t orientation; const Range *prevRange = &prevStateCast.path->range; assert(prevRange); if (prevRange->GetStartPos() == NOT_FOUND) { orientation = GetOrientation(currRange); } else { orientation = GetOrientation(*prevRange, currRange); } // backwards const Phrase &source = hypo.GetInputPath().subPhrase; const Phrase &target = hypo.GetTargetPhrase(); const Values *values = GetValues(source, target); if (values) { scoreVec[orientation] = (*values)[orientation]; } // forwards if (prevRange->GetStartPos() != NOT_FOUND) { const Phrase &source = prevStateCast.path->subPhrase; const Phrase &target = *prevStateCast.targetPhrase; const Values *values = GetValues(source, target); if (values) { scoreVec[orientation + 3] = (*values)[orientation + 3]; } } scores.PlusEquals(mgr.system, *this, scoreVec); } const LexicalReordering::Values *LexicalReordering::GetValues(const Phrase &source, const Phrase &target) const { Key key(&source, &target); Coll::const_iterator iter; iter = m_coll.find(key); if (iter == m_coll.end()) { return NULL; } else { return &iter->second; } } size_t LexicalReordering::GetOrientation(Range const& cur) const { return (cur.GetStartPos() == 0) ? 0 : 1; } size_t LexicalReordering::GetOrientation(Range const& prev, Range const& cur) const { if (cur.GetStartPos() == prev.GetEndPos() + 1) { // monotone return 0; } else if (prev.GetStartPos() == cur.GetEndPos() + 1) { // swap return 1; } else { // discontinuous return 2; } } } /* namespace Moses2 */ <|endoftext|>
<commit_before>#ifndef STAN_LANG_GENERATOR_GENERATE_FUNCTION_ARGUMENTS_HPP #define STAN_LANG_GENERATOR_GENERATE_FUNCTION_ARGUMENTS_HPP #include <stan/lang/ast.hpp> #include <stan/lang/generator/constants.hpp> #include <stan/lang/generator/generate_arg_decl.hpp> #include <boost/lexical_cast.hpp> #include <ostream> #include <string> namespace stan { namespace lang { /** * Generate the arguments for the specified function, with * precalculated flags for whether it is an RNG, uses the log * density accumulator or is a probability function, to the * specified stream. * * @param[in] fun function declaration * @param[in] is_rng true if function is an RNG * @param[in] is_lp true if function accesses log density * accumulator * @param[in] is_log true if function is log probability function * @param[in,out] o stream for generating * @param[in] double_only do not do any templating and make all arguments * based on the standard double type * @param[in] rng_type set a type of the rng argument in _rng functions * @param[in] parameter_defaults if true, default values for the standard * parameters (now only pstream__) will be generated */ void generate_function_arguments(const function_decl_def& fun, bool is_rng, bool is_lp, bool is_log, std::ostream& o, bool double_only = false, std::string rng_type = "RNG", bool parameter_defaults = false) { o << "("; for (size_t i = 0; i < fun.arg_decls_.size(); ++i) { std::string template_type_i; if (double_only) { template_type_i = "double"; } else { template_type_i = "T" + boost::lexical_cast<std::string>(i) + "__"; } generate_arg_decl(true, true, fun.arg_decls_[i], template_type_i, o); if (i + 1 < fun.arg_decls_.size()) { o << "," << EOL << INDENT; for (size_t i = 0; i <= fun.name_.size(); ++i) o << " "; } } if ((is_rng || is_lp) && fun.arg_decls_.size() > 0) o << ", "; if (is_rng) { o << rng_type << "& base_rng__"; } else if (is_lp) { if (double_only) { o << "double& lp__, stan::math::accumulator<double>& lp_accum__"; } else { o << "T_lp__& lp__, T_lp_accum__& lp_accum__"; } } if (is_rng || is_lp || fun.arg_decls_.size() > 0) o << ", "; o << "std::ostream* pstream__"; if (parameter_defaults) { o << " = 0"; } o << ")"; } } } #endif <commit_msg>Use nullptr instead of 0<commit_after>#ifndef STAN_LANG_GENERATOR_GENERATE_FUNCTION_ARGUMENTS_HPP #define STAN_LANG_GENERATOR_GENERATE_FUNCTION_ARGUMENTS_HPP #include <stan/lang/ast.hpp> #include <stan/lang/generator/constants.hpp> #include <stan/lang/generator/generate_arg_decl.hpp> #include <boost/lexical_cast.hpp> #include <cstddef> #include <ostream> #include <string> namespace stan { namespace lang { /** * Generate the arguments for the specified function, with * precalculated flags for whether it is an RNG, uses the log * density accumulator or is a probability function, to the * specified stream. * * @param[in] fun function declaration * @param[in] is_rng true if function is an RNG * @param[in] is_lp true if function accesses log density * accumulator * @param[in] is_log true if function is log probability function * @param[in,out] o stream for generating * @param[in] double_only do not do any templating and make all arguments * based on the standard double type * @param[in] rng_type set a type of the rng argument in _rng functions * @param[in] parameter_defaults if true, default values for the standard * parameters (now only pstream__) will be generated */ void generate_function_arguments(const function_decl_def& fun, bool is_rng, bool is_lp, bool is_log, std::ostream& o, bool double_only = false, std::string rng_type = "RNG", bool parameter_defaults = false) { o << "("; for (size_t i = 0; i < fun.arg_decls_.size(); ++i) { std::string template_type_i; if (double_only) { template_type_i = "double"; } else { template_type_i = "T" + boost::lexical_cast<std::string>(i) + "__"; } generate_arg_decl(true, true, fun.arg_decls_[i], template_type_i, o); if (i + 1 < fun.arg_decls_.size()) { o << "," << EOL << INDENT; for (size_t i = 0; i <= fun.name_.size(); ++i) o << " "; } } if ((is_rng || is_lp) && fun.arg_decls_.size() > 0) o << ", "; if (is_rng) { o << rng_type << "& base_rng__"; } else if (is_lp) { if (double_only) { o << "double& lp__, stan::math::accumulator<double>& lp_accum__"; } else { o << "T_lp__& lp__, T_lp_accum__& lp_accum__"; } } if (is_rng || is_lp || fun.arg_decls_.size() > 0) o << ", "; o << "std::ostream* pstream__"; if (parameter_defaults) { o << " = nullptr"; } o << ")"; } } } #endif <|endoftext|>
<commit_before>// // Created by Davide Caroselli on 27/09/16. // #include <algorithm> #include <boost/math/distributions/binomial.hpp> #include <suffixarray/SuffixArray.h> #include <util/hashutils.h> #include "PhraseTable.h" #include "UpdateManager.h" #include "TranslationOptionBuilder.h" using namespace mmt; using namespace mmt::sapt; struct PhraseTable::pt_private { SuffixArray *index; UpdateManager *updates; Aligner *aligner; size_t numberOfSamples; }; PhraseTable::PhraseTable(const string &modelPath, const Options &options, Aligner *aligner) { self = new pt_private(); self->index = new SuffixArray(modelPath, options.prefix_length); self->updates = new UpdateManager(self->index, options.update_buffer_size, options.update_max_delay); self->aligner = aligner; self->numberOfSamples = options.samples; } PhraseTable::~PhraseTable() { delete self->updates; delete self->index; delete self; } void PhraseTable::Add(const updateid_t &id, const domain_t domain, const std::vector<wid_t> &source, const std::vector<wid_t> &target, const alignment_t &alignment) { self->updates->Add(id, domain, source, target, alignment); } vector<updateid_t> PhraseTable::GetLatestUpdatesIdentifier() { const vector<seqid_t> &streams = self->index->GetStreams(); vector<updateid_t> result; result.reserve(streams.size()); for (size_t i = 0; i < streams.size(); ++i) { if (streams[i] != 0) result.push_back(updateid_t((stream_t) i, streams[i])); } return result; } /* Translation Options scoring */ static void GetLexicalScores(Aligner *aligner, const vector<wid_t> &phrase, const TranslationOption &option, float &fwdScore, float &bwdScore) { vector<vector<float>> fwdWordProb(option.targetPhrase.size()); vector<vector<float>> bwdWordProb(phrase.size()); size_t sSize = phrase.size(); size_t tSize = option.targetPhrase.size(); //computes the lexical probabilities on the best alignment only for (auto a = option.alignment.begin(); a != option.alignment.end(); ++a) { wid_t sWord = phrase[a->first]; wid_t tWord = option.targetPhrase[a->second]; fwdWordProb[a->second].push_back(aligner->GetForwardProbability(sWord, tWord)); //P(tWord | sWord) bwdWordProb[a->first].push_back(aligner->GetBackwardProbability(sWord, tWord)); //P(sWord | tWord) } fwdScore = 0.0; for (size_t ti = 0; ti < tSize; ++ti) { float tmpProb = 0.0; size_t tmpSize = fwdWordProb[ti].size(); if (tmpSize > 0) { for (size_t i = 0; i < tmpSize; ++i) { tmpProb += fwdWordProb[ti][i]; } tmpProb /= tmpSize; } else { tmpProb = aligner->GetTargetNullProbability(option.targetPhrase[ti]); } //should never happen that tmpProb <= 0 fwdScore += (tmpProb <= 0.0) ? -9 : log(tmpProb); } bwdScore = 0.0; for (size_t si = 0; si < sSize; ++si) { float tmpProb = 0.0; size_t tmpSize = bwdWordProb[si].size(); if (tmpSize > 0) { for (size_t i = 0; i < tmpSize; ++i) { tmpProb += bwdWordProb[si][i]; } tmpProb /= tmpSize; } else { tmpProb = aligner->GetSourceNullProbability(phrase[si]); } //should never happen that tmpProb <= 0 bwdScore += (tmpProb <= 0.0) ? -9 : log(tmpProb); } } static float lbop(float succ, float tries, float confidence) { if (confidence == 0) return succ / tries; else return (float) boost::math::binomial_distribution<>::find_lower_bound_on_p(tries, succ, confidence); } static void MakeTranslationOptions(SuffixArray *index, Aligner *aligner, const vector<wid_t> &phrase, vector<TranslationOptionBuilder> &builders, vector<TranslationOption> &output) { static constexpr float confidence = 0.01; size_t SampleSourceFrequency = 0; for (auto entry = builders.begin(); entry != builders.end(); ++entry) { SampleSourceFrequency += entry->GetCount(); } size_t GlobalSourceFrequency = index->CountOccurrences(true, phrase); for (auto entry = builders.begin(); entry != builders.end(); ++entry) { size_t GlobalTargetFrequency = index->CountOccurrences(false, entry->GetPhrase()); float fwdScore = log(lbop(entry->GetCount(), SampleSourceFrequency, confidence)); float bwdScore = log( lbop(entry->GetCount(), std::max((float) entry->GetCount(), (float) SampleSourceFrequency * GlobalTargetFrequency / GlobalSourceFrequency), confidence)); float fwdLexScore = 0.f; float bwdLexScore = 0.f; TranslationOption option; option.alignment = entry->GetBestAlignment(); option.targetPhrase = entry->GetPhrase(); if (aligner) GetLexicalScores(aligner, phrase, option, fwdLexScore, bwdLexScore); option.scores[kTOForwardProbability] = fwdScore; option.scores[kTOBackwardProbability] = min(0.f, bwdScore); option.scores[kTOForwardLexicalProbability] = fwdLexScore; option.scores[kTOBackwardLexicalProbability] = bwdLexScore; output.push_back(option); } } /* SAPT methods */ static void MakeOptions(SuffixArray *index, Aligner *aligner, const vector<wid_t> &phrase, const vector<sample_t> &samples, vector<TranslationOption> &output) { vector<TranslationOptionBuilder> builders; TranslationOptionBuilder::Extract(phrase, samples, builders); MakeTranslationOptions(index, aligner, phrase, builders, output); } vector<TranslationOption> PhraseTable::GetTranslationOptions(const vector<wid_t> &phrase, context_t *context) { vector<sample_t> samples; self->index->GetRandomSamples(phrase, self->numberOfSamples, samples, context); vector<TranslationOption> result; MakeOptions(self->index, self->aligner, phrase, samples, result); return result; } translation_table_t PhraseTable::GetAllTranslationOptions(const vector<wid_t> &sentence, context_t *context) { translation_table_t ttable; for (size_t start = 0; start < sentence.size(); ++start) { Collector *collector = self->index->NewCollector(context); vector<wid_t> phrase; vector<wid_t> phraseDelta; for (size_t end = start; end < sentence.size(); ++end) { wid_t word = sentence[end]; phrase.push_back(word); phraseDelta.push_back(word); if (ttable.find(phrase) == ttable.end()) { vector<sample_t> samples; collector->Extend(phraseDelta, self->numberOfSamples, samples); phraseDelta.clear(); if (samples.empty()) break; vector<TranslationOption> options; MakeOptions(self->index, self->aligner, phrase, samples, options); ttable[phrase] = options; } } delete collector; } return ttable; } <commit_msg>Code readability improved<commit_after>// // Created by Davide Caroselli on 27/09/16. // #include <algorithm> #include <boost/math/distributions/binomial.hpp> #include <suffixarray/SuffixArray.h> #include <util/hashutils.h> #include "PhraseTable.h" #include "UpdateManager.h" #include "TranslationOptionBuilder.h" using namespace mmt; using namespace mmt::sapt; struct PhraseTable::pt_private { SuffixArray *index; UpdateManager *updates; Aligner *aligner; size_t numberOfSamples; }; PhraseTable::PhraseTable(const string &modelPath, const Options &options, Aligner *aligner) { self = new pt_private(); self->index = new SuffixArray(modelPath, options.prefix_length); self->updates = new UpdateManager(self->index, options.update_buffer_size, options.update_max_delay); self->aligner = aligner; self->numberOfSamples = options.samples; } PhraseTable::~PhraseTable() { delete self->updates; delete self->index; delete self; } void PhraseTable::Add(const updateid_t &id, const domain_t domain, const std::vector<wid_t> &source, const std::vector<wid_t> &target, const alignment_t &alignment) { self->updates->Add(id, domain, source, target, alignment); } vector<updateid_t> PhraseTable::GetLatestUpdatesIdentifier() { const vector<seqid_t> &streams = self->index->GetStreams(); vector<updateid_t> result; result.reserve(streams.size()); for (size_t i = 0; i < streams.size(); ++i) { if (streams[i] != 0) result.push_back(updateid_t((stream_t) i, streams[i])); } return result; } /* Translation Options scoring */ static void GetLexicalScores(Aligner *aligner, const vector<wid_t> &phrase, const TranslationOption &option, float &fwdScore, float &bwdScore) { vector<vector<float>> fwdWordProb(option.targetPhrase.size()); vector<vector<float>> bwdWordProb(phrase.size()); size_t sSize = phrase.size(); size_t tSize = option.targetPhrase.size(); //computes the lexical probabilities on the best alignment only for (auto a = option.alignment.begin(); a != option.alignment.end(); ++a) { wid_t sWord = phrase[a->first]; wid_t tWord = option.targetPhrase[a->second]; fwdWordProb[a->second].push_back(aligner->GetForwardProbability(sWord, tWord)); //P(tWord | sWord) bwdWordProb[a->first].push_back(aligner->GetBackwardProbability(sWord, tWord)); //P(sWord | tWord) } fwdScore = 0.0; for (size_t ti = 0; ti < tSize; ++ti) { float tmpProb = 0.0; size_t tmpSize = fwdWordProb[ti].size(); if (tmpSize > 0) { for (size_t i = 0; i < tmpSize; ++i) { tmpProb += fwdWordProb[ti][i]; } tmpProb /= tmpSize; } else { tmpProb = aligner->GetTargetNullProbability(option.targetPhrase[ti]); } //should never happen that tmpProb <= 0 fwdScore += (tmpProb <= 0.0) ? -9 : log(tmpProb); } bwdScore = 0.0; for (size_t si = 0; si < sSize; ++si) { float tmpProb = 0.0; size_t tmpSize = bwdWordProb[si].size(); if (tmpSize > 0) { for (size_t i = 0; i < tmpSize; ++i) { tmpProb += bwdWordProb[si][i]; } tmpProb /= tmpSize; } else { tmpProb = aligner->GetSourceNullProbability(phrase[si]); } //should never happen that tmpProb <= 0 bwdScore += (tmpProb <= 0.0) ? -9 : log(tmpProb); } } static float lbop(float succ, float tries, float confidence) { if (confidence == 0) return succ / tries; else return (float) boost::math::binomial_distribution<>::find_lower_bound_on_p(tries, succ, confidence); } static void MakeTranslationOptions(SuffixArray *index, Aligner *aligner, const vector<wid_t> &phrase, vector<TranslationOptionBuilder> &builders, vector<TranslationOption> &output) { static constexpr float confidence = 0.01; size_t sampleSourceFrequency = 0; for (auto entry = builders.begin(); entry != builders.end(); ++entry) { sampleSourceFrequency += entry->GetCount(); } size_t globalSourceFrequency = index->CountOccurrences(true, phrase); for (auto entry = builders.begin(); entry != builders.end(); ++entry) { size_t GlobalTargetFrequency = index->CountOccurrences(false, entry->GetPhrase()); float fwdScore = log(lbop(entry->GetCount(), sampleSourceFrequency, confidence)); float bwdScore = log( lbop(entry->GetCount(), std::max((float) entry->GetCount(), (float) sampleSourceFrequency * GlobalTargetFrequency / globalSourceFrequency), confidence)); float fwdLexScore = 0.f; float bwdLexScore = 0.f; TranslationOption option; option.alignment = entry->GetBestAlignment(); option.targetPhrase = entry->GetPhrase(); if (aligner) GetLexicalScores(aligner, phrase, option, fwdLexScore, bwdLexScore); option.scores[kTOForwardProbability] = fwdScore; option.scores[kTOBackwardProbability] = min(0.f, bwdScore); option.scores[kTOForwardLexicalProbability] = fwdLexScore; option.scores[kTOBackwardLexicalProbability] = bwdLexScore; output.push_back(option); } } /* SAPT methods */ static void MakeOptions(SuffixArray *index, Aligner *aligner, const vector<wid_t> &phrase, const vector<sample_t> &samples, vector<TranslationOption> &output) { vector<TranslationOptionBuilder> builders; TranslationOptionBuilder::Extract(phrase, samples, builders); MakeTranslationOptions(index, aligner, phrase, builders, output); } vector<TranslationOption> PhraseTable::GetTranslationOptions(const vector<wid_t> &phrase, context_t *context) { vector<sample_t> samples; self->index->GetRandomSamples(phrase, self->numberOfSamples, samples, context); vector<TranslationOption> result; MakeOptions(self->index, self->aligner, phrase, samples, result); return result; } translation_table_t PhraseTable::GetAllTranslationOptions(const vector<wid_t> &sentence, context_t *context) { translation_table_t ttable; for (size_t start = 0; start < sentence.size(); ++start) { Collector *collector = self->index->NewCollector(context); vector<wid_t> phrase; vector<wid_t> phraseDelta; for (size_t end = start; end < sentence.size(); ++end) { wid_t word = sentence[end]; phrase.push_back(word); phraseDelta.push_back(word); if (ttable.find(phrase) == ttable.end()) { vector<sample_t> samples; collector->Extend(phraseDelta, self->numberOfSamples, samples); phraseDelta.clear(); if (samples.empty()) break; vector<TranslationOption> options; MakeOptions(self->index, self->aligner, phrase, samples, options); ttable[phrase] = options; } } delete collector; } return ttable; } <|endoftext|>
<commit_before>/* * Copyright (C) 2010, 2011, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <algorithm> #include <kernel/userver.hh> #include <object/symbols.hh> #include <runner/job.hh> #include <urbi/object/event.hh> #include <urbi/object/event-handler.hh> #include <urbi/object/lobby.hh> #include <urbi/sdk.hh> #include <eval/call.hh> #include <eval/exec.hh> #include <eval/send-message.hh> #include <urbi/runner/raise.hh> GD_CATEGORY(Urbi.Event); namespace urbi { namespace object { /*---------. | Waiter. | `---------*/ inline Event::Waiter::Waiter(rTag ct, runner::Job* r, rObject& p) : controlTag(ct), runner(r), pattern(p) {} /*--------. | Event. | `--------*/ Event::Event() : waiters_() , callbacks_() { proto_add(proto); slot_set_value(SYMBOL(active), to_urbi(false)); } Event::Event(rEvent model) : waiters_() , callbacks_(model->callbacks_) { proto_add(model); slot_set_value(SYMBOL(active), to_urbi(false)); } URBI_CXX_OBJECT_INIT(Event) : waiters_() , callbacks_() { BIND(onSubscribe, onSubscribe_); BIND(hasSubscribers); BIND(subscribe); BIND(subscribers, callbacks_); BIND(onEvent, onEvent, on_event_type); BIND(waituntil); BIND_VARIADIC(emit); BIND_VARIADIC(syncEmit); BIND_VARIADIC(syncTrigger); BIND_VARIADIC(trigger); } Event::~Event() { destructed_(); } /*------------. | Callbacks. | `------------*/ Event::signal_type& Event::destructed_get() { return destructed_; } Event::signal_type& Event::subscribed_get() { return subscribed_; } Event::signal_type& Event::unsubscribed_get() { return unsubscribed_; } void Event::subscribe(rSubscription s) { aver(s); GD_FINFO_TRACE("%s: New subscription %s", this, s); callbacks_ << s; if (onSubscribe_) onSubscribe_->syncEmit(); } rSubscription Event::onEvent(const callback_type& cb) { aver(!cb.empty()); rSubscription res = new Subscription(new callback_type(cb)); res->asynchronous_ = false; callbacks_ << res; if (onSubscribe_) onSubscribe_->syncEmit(); return res; } /*-----------------. | Urbi functions. | `-----------------*/ void Event::onEvent(rExecutable guard, rExecutable enter, rExecutable leave, bool sync) { rSubscription actions(new Subscription(this, guard, enter, leave, sync)); GD_FPUSH_TRACE("%s: New registration %s.", this, actions); runner::Job& r = ::kernel::runner(); actions->call_stack = r.state.call_stack_get(); const libport::Symbol& sep = SYMBOL(MINUS_MINUS_MINUS_MINUS_SP_event_SP_handler_SP_backtrace_COLON); actions->call_stack << std::make_pair(sep, boost::optional<ast::loc>()); actions->profile = r.profile_get(); actions->tag_stack = r.state.tag_stack_get(); actions->lobby = r.state.lobby_get(); foreach (object::rTag& tag, actions->tag_stack) { GD_FINFO_DEBUG("%s: Hook tag %s.", this, tag->name()); sched::rTag t = tag->value_get(); using boost::bind; actions->connections << t->stop_hook_get().connect( bind(&Subscription::unregister, actions)) << t->freeze_hook_get().connect( bind(&Subscription::freeze, actions)) << t->unfreeze_hook_get().connect( bind(&Subscription::unfreeze, actions)); } callbacks_ << actions; foreach (const actives_type::value_type& active, active_) { objects_type args; args << this << this << active->payload(); rObject pattern = nil_class; if (actions->guard) { pattern = (*actions->guard)(args); if (pattern == void_class) continue; } args << pattern; if (actions->leave_) active ->register_stop_job (EventHandler::stop_job_type(actions, args, true)); active->trigger_job(actions, true, args); } if (onSubscribe_) onSubscribe_->syncEmit(); subscribed_(); } void Event::waituntil(rObject pattern) { if (onSubscribe_) onSubscribe_->syncEmit(); // Check whether there's already a matching instance. foreach (const actives_type::value_type& active, active_) if (pattern == nil_class || pattern->call(SYMBOL(match), active->payload())->as_bool()) return; runner::Job& r = ::kernel::runner(); rTag t(new Tag); waiters_ << Waiter(t, &r, pattern); libport::Finally f; r.state.apply_tag(t, &f); f << boost::bind(&Event::waituntil_remove, this, t); t->freeze(); // Will yield. } void Event::waituntil_remove(rTag what) { for (unsigned i = 0; i < waiters_.size(); ++i) if (waiters_[i].controlTag == what) { waiters_[i] = waiters_[waiters_.size()-1]; waiters_.pop_back(); return; } } rEvent Event::source() { rObject proto = protos_get_first(); return from_urbi<rEvent>(proto); } /*-------. | Emit. | `-------*/ runner::rJob Event::spawn_actions_job(rLobby lobby, const call_stack_type& stack, rExecutable e, rProfile profile, const objects_type& args) { runner::Job& r = ::kernel::runner(); if (!lobby) lobby = r.state.lobby_get(); runner::Job* res = e->make_job(lobby, r.scheduler_get(), args, SYMBOL(event)); // Append the back-trace of the event handler (the "at") below // that of the emission back trace. res->state .call_stack_get() .insert(res->state.call_stack_get().begin(), stack.begin(), stack.end()); if (profile) res->profile_start(profile, SYMBOL(event), e.get()); return res; } void Event::emit_backend(const objects_type& pl, bool detach, EventHandler* h) { GD_FPUSH_TRACE("%s: Emit, %s subscribers.", this, callbacks_.size()); rList payload = new List(pl); if (!h) slot_update(SYMBOL(active), to_urbi(false)); waituntil_release(payload); bool empty = callbacks_.empty(); objects_type apl; callbacks_type cbcopy; // Copy active subscriptions, cleanup list for (unsigned i= 0; i<callbacks_.size(); ++i) { rSubscription& s = callbacks_[i]; if (s->disconnected_get()) { callbacks_[i] = callbacks_[callbacks_.size()-1]; callbacks_.pop_back(); --i; } else cbcopy << s; } // List was empty and we didn't notice. if (!empty && callbacks_.empty()) { GD_INFO_TRACE("No more subscribers, calling unsubscribed"); unsubscribed_(); } GD_FINFO_TRACE("%s subscribers after cleanup", callbacks_.size()); for (unsigned i = 0; i < cbcopy.size(); ++i) { rSubscription s = cbcopy[i]; aver(s); libport::utime_t now = kernel::server().getTime(); GD_FPUSH_TRACE ("Considering %s, mi %s(%s), lc %s(%s), now %s, enabl %s, async %s", s, s->minInterval_, libport::seconds_to_utime(s->minInterval_), s->lastCall_, libport::seconds_to_utime(s->lastCall_), now, s->enabled_, s->asynchronous_); if (s->disconnected_get()) { GD_INFO_TRACE("Subscriber is disconnected"); // For removal we just swap with the last for better performances. cbcopy[i] = cbcopy[cbcopy.size()-1]; cbcopy.pop_back(); --i; } else if (s->enabled_ && now - libport::seconds_to_utime(s->lastCall_) >= libport::seconds_to_utime(s->minInterval_) && (!s->maxParallelEvents_ || s->maxParallelEvents_ > s->processing_)) { // FIXME CRAP if we honor the event emit sync/at sync rule, no way // to catch changed asynchronously bool async = (s->event_ && (detach && s->asynchronous_get())) || (!s->event_ && (detach || s->asynchronous_get())); GD_FINFO_TRACE("Subscriber is live for notification" " (cb: %s e: %s), async: %s", s->cb_, s->event_, async); if (s->frozen) { GD_FINFO_TRACE("%s: Skip frozen registration %s.", this, s); continue; } objects_type args; args << this << this << payload; rObject pattern = nil_class; if (s->guard) { pattern = (*s->guard)(args); if (pattern == void_class) { GD_FINFO_TRACE("%s: Skip patters mismatch %s.", this, s); continue; } } args << pattern; if (h && s->leave_) h->register_stop_job(EventHandler::stop_job_type(s, args, detach)); if (async) { // If we create a job, it can die before executing a single line // of code. // To avoid any race condition, we just create the job without // touching any stat or holding any lock. eval::Action a = eval::exec(boost::bind(&Subscription::run_sync, s, this, pl, h, detach, false, args), this); rLobby l = s->lobby ? s->lobby.get() : kernel::runner().state.lobby_get(); runner::rJob j = new runner::Job(l, kernel::runner().scheduler_get()); j->set_action(a); j->state.tag_stack_set(s->tag_stack); GD_FINFO_DUMP("Subscriber will run in job %s", j); j->start_job(); } else s->run_sync(this, pl, h, detach, true, args); } } } void Event::syncEmit(const objects_type& pl) { emit_backend(pl, false); } void Event::emit(const objects_type& args) { emit_backend(args, true); } /*----------. | Trigger. | `----------*/ rEventHandler Event::trigger_backend(const objects_type& pl, bool detach) { rList payload = new List(pl); rEventHandler handler = new EventHandler(this, payload); waituntil_release(payload); handler->trigger(detach); return handler; } rEventHandler Event::syncTrigger(const objects_type& pl) { return trigger_backend(pl, false); } rEventHandler Event::trigger(const objects_type& pl) { return trigger_backend(pl, true); } void Event::waituntil_release(rObject payload) { // This iteration needs to remove some elements as it goes. for (unsigned i = 0; i < waiters_.size(); ) { Waiter& waiter = waiters_[i]; if (waiter.pattern == nil_class || waiter.pattern->call(SYMBOL(match), payload)->as_bool()) { // Check if any tag is frozen beside the first one. bool frozen = false; foreach (const rTag& t, waiter.runner->state.tag_stack_get_all()) if (t != waiter.controlTag && t->frozen()) { frozen = true; ++i; break; } if (!frozen) // Do not trigger a frozen at. { waiter.controlTag->unfreeze(); // Yes this is also valid for the last element. waiters_[i] = waiters_[waiters_.size()-1]; waiters_.pop_back(); } } else ++i; } } bool Event::hasSubscribers() const { return !waiters_.empty() || !callbacks_.empty(); } } } <commit_msg>Event: style changes.<commit_after>/* * Copyright (C) 2010, 2011, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <algorithm> #include <kernel/userver.hh> #include <object/symbols.hh> #include <runner/job.hh> #include <urbi/object/event.hh> #include <urbi/object/event-handler.hh> #include <urbi/object/lobby.hh> #include <urbi/sdk.hh> #include <eval/call.hh> #include <eval/exec.hh> #include <eval/send-message.hh> #include <urbi/runner/raise.hh> GD_CATEGORY(Urbi.Event); namespace urbi { namespace object { /*---------. | Waiter. | `---------*/ inline Event::Waiter::Waiter(rTag ct, runner::Job* r, rObject& p) : controlTag(ct), runner(r), pattern(p) {} /*--------. | Event. | `--------*/ Event::Event() : waiters_() , onSubscribe_(0) , callbacks_() { proto_add(proto); slot_set_value(SYMBOL(active), to_urbi(false)); } Event::Event(rEvent model) : waiters_() , onSubscribe_(0) , callbacks_(model->callbacks_) { proto_add(model); slot_set_value(SYMBOL(active), to_urbi(false)); } URBI_CXX_OBJECT_INIT(Event) : waiters_() , onSubscribe_(0) , callbacks_() { BIND(hasSubscribers); BIND(onEvent, onEvent, on_event_type); BIND(onSubscribe, onSubscribe_); BIND(subscribe); BIND(subscribers, callbacks_); BIND(waituntil); BIND_VARIADIC(emit); BIND_VARIADIC(syncEmit); BIND_VARIADIC(syncTrigger); BIND_VARIADIC(trigger); } Event::~Event() { destructed_(); } /*------------. | Callbacks. | `------------*/ Event::signal_type& Event::destructed_get() { return destructed_; } Event::signal_type& Event::subscribed_get() { return subscribed_; } Event::signal_type& Event::unsubscribed_get() { return unsubscribed_; } void Event::subscribe(rSubscription s) { aver(s); GD_FINFO_TRACE("%s: New subscription %s", this, s); callbacks_ << s; if (onSubscribe_) onSubscribe_->syncEmit(); } rSubscription Event::onEvent(const callback_type& cb) { aver(!cb.empty()); rSubscription res = new Subscription(new callback_type(cb)); res->asynchronous_ = false; callbacks_ << res; if (onSubscribe_) onSubscribe_->syncEmit(); return res; } /*-----------------. | Urbi functions. | `-----------------*/ void Event::onEvent(rExecutable guard, rExecutable enter, rExecutable leave, bool sync) { rSubscription actions(new Subscription(this, guard, enter, leave, sync)); GD_FPUSH_TRACE("%s: New registration %s.", this, actions); runner::Job& r = ::kernel::runner(); actions->call_stack = r.state.call_stack_get(); const libport::Symbol& sep = SYMBOL(MINUS_MINUS_MINUS_MINUS_SP_event_SP_handler_SP_backtrace_COLON); actions->call_stack << std::make_pair(sep, boost::optional<ast::loc>()); actions->profile = r.profile_get(); actions->tag_stack = r.state.tag_stack_get(); actions->lobby = r.state.lobby_get(); foreach (object::rTag& tag, actions->tag_stack) { GD_FINFO_DEBUG("%s: Hook tag %s.", this, tag->name()); sched::rTag t = tag->value_get(); using boost::bind; actions->connections << t->stop_hook_get().connect( bind(&Subscription::unregister, actions)) << t->freeze_hook_get().connect( bind(&Subscription::freeze, actions)) << t->unfreeze_hook_get().connect( bind(&Subscription::unfreeze, actions)); } callbacks_ << actions; foreach (const actives_type::value_type& active, active_) { objects_type args; args << this << this << active->payload(); rObject pattern = nil_class; if (actions->guard) { pattern = (*actions->guard)(args); if (pattern == void_class) continue; } args << pattern; if (actions->leave_) active ->register_stop_job (EventHandler::stop_job_type(actions, args, true)); active->trigger_job(actions, true, args); } if (onSubscribe_) onSubscribe_->syncEmit(); subscribed_(); } void Event::waituntil(rObject pattern) { if (onSubscribe_) onSubscribe_->syncEmit(); // Check whether there's already a matching instance. foreach (const actives_type::value_type& active, active_) if (pattern == nil_class || pattern->call(SYMBOL(match), active->payload())->as_bool()) return; runner::Job& r = ::kernel::runner(); rTag t(new Tag); waiters_ << Waiter(t, &r, pattern); libport::Finally f; r.state.apply_tag(t, &f); f << boost::bind(&Event::waituntil_remove, this, t); t->freeze(); // Will yield. } void Event::waituntil_remove(rTag what) { for (unsigned i = 0; i < waiters_.size(); ++i) if (waiters_[i].controlTag == what) { waiters_[i] = waiters_[waiters_.size()-1]; waiters_.pop_back(); return; } } rEvent Event::source() { rObject proto = protos_get_first(); return from_urbi<rEvent>(proto); } /*-------. | Emit. | `-------*/ runner::rJob Event::spawn_actions_job(rLobby lobby, const call_stack_type& stack, rExecutable e, rProfile profile, const objects_type& args) { runner::Job& r = ::kernel::runner(); if (!lobby) lobby = r.state.lobby_get(); runner::Job* res = e->make_job(lobby, r.scheduler_get(), args, SYMBOL(event)); // Append the back-trace of the event handler (the "at") below // that of the emission back trace. res->state .call_stack_get() .insert(res->state.call_stack_get().begin(), stack.begin(), stack.end()); if (profile) res->profile_start(profile, SYMBOL(event), e.get()); return res; } void Event::emit_backend(const objects_type& pl, bool detach, EventHandler* h) { GD_FPUSH_TRACE("%s: Emit, %s subscribers.", this, callbacks_.size()); rList payload = new List(pl); if (!h) slot_update(SYMBOL(active), to_urbi(false)); waituntil_release(payload); bool empty = callbacks_.empty(); objects_type apl; callbacks_type cbcopy; // Copy active subscriptions, cleanup list for (unsigned i= 0; i<callbacks_.size(); ++i) { rSubscription& s = callbacks_[i]; if (s->disconnected_get()) { callbacks_[i] = callbacks_[callbacks_.size()-1]; callbacks_.pop_back(); --i; } else cbcopy << s; } // List was empty and we didn't notice. if (!empty && callbacks_.empty()) { GD_INFO_TRACE("No more subscribers, calling unsubscribed"); unsubscribed_(); } GD_FINFO_TRACE("%s subscribers after cleanup", callbacks_.size()); for (unsigned i = 0; i < cbcopy.size(); ++i) { rSubscription s = cbcopy[i]; aver(s); libport::utime_t now = kernel::server().getTime(); GD_FPUSH_TRACE ("Considering %s, mi %s(%s), lc %s(%s), now %s, enabl %s, async %s", s, s->minInterval_, libport::seconds_to_utime(s->minInterval_), s->lastCall_, libport::seconds_to_utime(s->lastCall_), now, s->enabled_, s->asynchronous_); if (s->disconnected_get()) { GD_INFO_TRACE("Subscriber is disconnected"); // For removal we just swap with the last for better performances. cbcopy[i] = cbcopy[cbcopy.size()-1]; cbcopy.pop_back(); --i; } else if (s->enabled_ && now - libport::seconds_to_utime(s->lastCall_) >= libport::seconds_to_utime(s->minInterval_) && (!s->maxParallelEvents_ || s->maxParallelEvents_ > s->processing_)) { // FIXME CRAP if we honor the event emit sync/at sync rule, no way // to catch changed asynchronously bool async = (s->event_ && (detach && s->asynchronous_get())) || (!s->event_ && (detach || s->asynchronous_get())); GD_FINFO_TRACE("Subscriber is live for notification" " (cb: %s e: %s), async: %s", s->cb_, s->event_, async); if (s->frozen) { GD_FINFO_TRACE("%s: Skip frozen registration %s.", this, s); continue; } objects_type args; args << this << this << payload; rObject pattern = nil_class; if (s->guard) { pattern = (*s->guard)(args); if (pattern == void_class) { GD_FINFO_TRACE("%s: Skip patters mismatch %s.", this, s); continue; } } args << pattern; if (h && s->leave_) h->register_stop_job(EventHandler::stop_job_type(s, args, detach)); if (async) { // If we create a job, it can die before executing a single line // of code. // To avoid any race condition, we just create the job without // touching any stat or holding any lock. eval::Action a = eval::exec(boost::bind(&Subscription::run_sync, s, this, pl, h, detach, false, args), this); rLobby l = s->lobby ? s->lobby.get() : kernel::runner().state.lobby_get(); runner::rJob j = new runner::Job(l, kernel::runner().scheduler_get()); j->set_action(a); j->state.tag_stack_set(s->tag_stack); GD_FINFO_DUMP("Subscriber will run in job %s", j); j->start_job(); } else s->run_sync(this, pl, h, detach, true, args); } } } void Event::syncEmit(const objects_type& pl) { emit_backend(pl, false); } void Event::emit(const objects_type& args) { emit_backend(args, true); } /*----------. | Trigger. | `----------*/ rEventHandler Event::trigger_backend(const objects_type& pl, bool detach) { rList payload = new List(pl); rEventHandler handler = new EventHandler(this, payload); waituntil_release(payload); handler->trigger(detach); return handler; } rEventHandler Event::syncTrigger(const objects_type& pl) { return trigger_backend(pl, false); } rEventHandler Event::trigger(const objects_type& pl) { return trigger_backend(pl, true); } void Event::waituntil_release(rObject payload) { // This iteration needs to remove some elements as it goes. for (unsigned i = 0; i < waiters_.size(); ) { Waiter& waiter = waiters_[i]; if (waiter.pattern == nil_class || waiter.pattern->call(SYMBOL(match), payload)->as_bool()) { // Check if any tag is frozen beside the first one. bool frozen = false; foreach (const rTag& t, waiter.runner->state.tag_stack_get_all()) if (t != waiter.controlTag && t->frozen()) { frozen = true; ++i; break; } if (!frozen) // Do not trigger a frozen at. { waiter.controlTag->unfreeze(); // Yes this is also valid for the last element. waiters_[i] = waiters_[waiters_.size()-1]; waiters_.pop_back(); } } else ++i; } } bool Event::hasSubscribers() const { return !waiters_.empty() || !callbacks_.empty(); } } } <|endoftext|>
<commit_before>#ifndef WIN32 //===--- TerminalDisplayUnix.cpp - Output To UNIX Terminal ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface for writing to a UNIX terminal. It tries to // support all "common" terminal types. // // Axel Naumann <[email protected]>, 2011-05-12 //===----------------------------------------------------------------------===// #include "textinput/TerminalDisplayUnix.h" #include "textinput/TerminalConfigUnix.h" #include "textinput/Color.h" #include <stdio.h> // putenv not in cstdlib on Solaris #include <stdlib.h> #include <unistd.h> #include <sys/ioctl.h> #include <termios.h> #include <csignal> #include <cstring> #include <sstream> using std::signal; using std::strstr; namespace { textinput::TerminalDisplayUnix*& gTerminalDisplayUnix() { static textinput::TerminalDisplayUnix* S = 0; return S; } void InitRGB256(unsigned char rgb256[][3]) { // initialize the array with the expected standard colors: // (from http://frexx.de/xterm-256-notes) // this is not what I see, though it's supposedly the default: // rgb[0][0] = 0; rgb[0][1] = 0; rgb[0][1] = 0; // use this instead, just to be on the safe side: rgb256[0][0] = 46; rgb256[0][1] = 52; rgb256[0][1] = 64; rgb256[1][0] = 205; rgb256[1][1] = 0; rgb256[1][1] = 0; rgb256[2][0] = 0; rgb256[2][1] = 205; rgb256[2][1] = 0; rgb256[3][0] = 205; rgb256[3][1] = 205; rgb256[3][1] = 0; rgb256[4][0] = 0; rgb256[4][1] = 0; rgb256[4][1] = 238; rgb256[5][0] = 205; rgb256[5][1] = 0; rgb256[5][1] = 205; rgb256[6][0] = 0; rgb256[6][1] = 205; rgb256[6][1] = 205; rgb256[7][0] = 229; rgb256[7][1] = 229; rgb256[7][1] = 229; // this is not what I see, though it's supposedly the default: // rgb256[ 8][0] = 127; rgb256[ 8][1] = 127; rgb256[ 8][1] = 127; // use this instead, just to be on the safe side: rgb256[ 8][0] = 0; rgb256[ 8][1] = 0; rgb256[ 8][1] = 0; rgb256[ 9][0] = 255; rgb256[ 9][1] = 0; rgb256[ 9][1] = 0; rgb256[10][0] = 0; rgb256[10][1] = 255; rgb256[10][1] = 0; rgb256[11][0] = 255; rgb256[11][1] = 255; rgb256[11][1] = 0; rgb256[12][0] = 92; rgb256[12][1] = 92; rgb256[12][1] = 255; rgb256[13][0] = 255; rgb256[13][1] = 0; rgb256[13][1] = 255; rgb256[14][0] = 0; rgb256[14][1] = 255; rgb256[14][1] = 255; rgb256[15][0] = 255; rgb256[15][1] = 255; rgb256[15][1] = 255; // 6 intensity RGB static const int intensities[] = {0, 0x5f, 0x87, 0xaf, 0xd7, 0xff}; int idx = 16; for (int r = 0; r < 6; ++r) { for (int g = 0; g < 6; ++g) { for (int b = 0; b < 6; ++b) { rgb256[idx][0] = intensities[r]; rgb256[idx][1] = intensities[g]; rgb256[idx][2] = intensities[b]; ++idx; } } } // colors 232-255 are a grayscale ramp, intentionally leaving out // black and white for (unsigned char gray = 0; gray < 24; ++gray) { unsigned char level = (gray * 10) + 8; rgb256[232 + gray][0] = level; rgb256[232 + gray][1] = level; rgb256[232 + gray][2] = level; } } } // unnamed namespace extern "C" void TerminalDisplayUnix__handleResizeSignal(int) { gTerminalDisplayUnix()->HandleResizeSignal(); } namespace textinput { // If input is not a tty don't write in tty-mode either. TerminalDisplayUnix::TerminalDisplayUnix(): TerminalDisplay(TerminalConfigUnix::Get().IsInteractive()), fIsAttached(false), fNColors(16) { HandleResizeSignal(); gTerminalDisplayUnix() = this; signal(SIGWINCH, TerminalDisplayUnix__handleResizeSignal); #ifdef TCSANOW TerminalConfigUnix::Get().TIOS()->c_lflag &= ~(ECHO); TerminalConfigUnix::Get().TIOS()->c_lflag |= ECHOCTL|ECHOKE|ECHOE; #endif const char* TERM = getenv("TERM"); if (TERM && strstr(TERM, "256")) { fNColors = 256; } } TerminalDisplayUnix::~TerminalDisplayUnix() { Detach(); } void TerminalDisplayUnix::HandleResizeSignal() { #ifdef TIOCGWINSZ struct winsize sz; int ret = ioctl(fileno(stdout), TIOCGWINSZ, (char*)&sz); if (!ret && sz.ws_col) { SetWidth(sz.ws_col); // Export what we found. std::stringstream s; s << sz.ws_col; setenv("COLUMS", s.str().c_str(), 1 /*overwrite*/); s.clear(); s << sz.ws_row; setenv("LINES", s.str().c_str(), 1 /*overwrite*/); } #else // try $COLUMNS const char* COLUMNS = getenv("COLUMNS"); if (COLUMNS) { long width = atol(COLUMNS); if (width > 4 && width < 1024*16) { SetWidth(width); } } #endif } void TerminalDisplayUnix::SetColor(char CIdx, const Color& C) { if (!IsTTY()) return; // Default color, reset previous bold etc. static const char text[] = {(char)0x1b, '[', '0', 'm', 0}; WriteRawString(text, 4); if (CIdx == 0) return; if (fNColors == 256) { int ANSIIdx = GetClosestColorIdx256(C); static const char preamble[] = {'\x1b', '[', '3', '8', ';', '5', ';', 0}; std::string buf(preamble); if (ANSIIdx > 100) { buf += '0' + (ANSIIdx / 100); } if (ANSIIdx > 10) { buf += '0' + ((ANSIIdx / 10) % 10); } buf += '0' + (ANSIIdx % 10); buf += "m"; WriteRawString(buf.c_str(), buf.length()); } else { int ANSIIdx = GetClosestColorIdx16(C); char buf[] = {'\x1b', '[', '3', '0' + (ANSIIdx % 8), 'm', 0}; if (ANSIIdx > 7) buf[2] += 6; WriteRawString(buf, 5); } if (C.fModifiers & Color::kModUnderline) { WriteRawString("\033[4m", 4); } if (C.fModifiers & Color::kModBold) { WriteRawString("\033[1m", 4); } if (C.fModifiers & Color::kModInverse) { WriteRawString("\033[7m", 4); } } void TerminalDisplayUnix::MoveFront() { static const char text[] = {(char)0x1b, '[', '1', 'G', 0}; if (!IsTTY()) return; WriteRawString(text, sizeof(text)); } void TerminalDisplayUnix::MoveInternal(char What, size_t n) { static const char cmd[] = "\x1b["; if (!IsTTY()) return; std::string text; for (size_t i = 0; i < n; ++i) { text += cmd; text += What; } WriteRawString(text.c_str(), text.length()); } void TerminalDisplayUnix::MoveUp(size_t nLines /* = 1 */) { MoveInternal('A', nLines); } void TerminalDisplayUnix::MoveDown(size_t nLines /* = 1 */) { if (!IsTTY()) return; std::string moves(nLines, 0x0a); WriteRawString(moves.c_str(), nLines); } void TerminalDisplayUnix::MoveRight(size_t nCols /* = 1 */) { MoveInternal('C', nCols); } void TerminalDisplayUnix::MoveLeft(size_t nCols /* = 1 */) { MoveInternal('D', nCols); } void TerminalDisplayUnix::EraseToRight() { static const char text[] = {(char)0x1b, '[', 'K', 0}; if (!IsTTY()) return; WriteRawString(text, sizeof(text)); } void TerminalDisplayUnix::WriteRawString(const char *text, size_t len) { if (write(fileno(stdout), text, len) == -1) { // Silence Ubuntu's "unused result". We don't care if it fails. } } void TerminalDisplayUnix::ActOnEOL() { if (!IsTTY()) return; WriteRawString(" \b", 2); //MoveUp(); } void TerminalDisplayUnix::Attach() { // set to noecho if (fIsAttached) return; fflush(stdout); TerminalConfigUnix::Get().Attach(); fWritePos = Pos(); fWriteLen = 0; fIsAttached = true; } void TerminalDisplayUnix::Detach() { if (!fIsAttached) return; fflush(stdout); TerminalConfigUnix::Get().Detach(); TerminalDisplay::Detach(); fIsAttached = false; } int TerminalDisplayUnix::GetClosestColorIdx16(const Color& C) { int r = C.fR; int g = C.fG; int b = C.fB; int sum = r + g + b; r = r > sum / 4; g = g > sum / 4; b = b > sum / 4; // ANSI: return r + (g * 2) + (b * 4); // ! ANSI: // return (r * 4) + (g * 2) + b; } int TerminalDisplayUnix::GetClosestColorIdx256(const Color& C) { static unsigned char rgb256[256][3] = {{0}}; if (rgb256[0][0] == 0) { InitRGB256(rgb256); } // Find the closest index. // A: the closest color match (square of geometric distance in RGB) // B: the closest brightness match // Treat them equally, which suppresses differences // in color due to squared distance. // start with black: int idx = 0; unsigned int r = C.fR; unsigned int g = C.fG; unsigned int b = C.fB; unsigned int graylvl = (r + g + b)/3; long mindelta = (r*r + g*g + b*b) + graylvl; if (mindelta) { for (unsigned int i = 0; i < 256; ++i) { long delta = (rgb256[i][0] + rgb256[i][1] + rgb256[i][2])/3 - graylvl; if (delta < 0) delta = -delta; delta += (r-rgb256[i][0])*(r-rgb256[i][0]) + (g-rgb256[i][1])*(g-rgb256[i][1]) + (b-rgb256[i][2])*(b-rgb256[i][2]); if (delta < mindelta) { mindelta = delta; idx = i; if (mindelta == 0) break; } } } return idx; } } #endif // #ifndef WIN32 <commit_msg>Don't write out \0. Let teh compiler count (use sizeof()). Fixes problem on Windows ssh'ing to Linux.<commit_after>#ifndef WIN32 //===--- TerminalDisplayUnix.cpp - Output To UNIX Terminal ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface for writing to a UNIX terminal. It tries to // support all "common" terminal types. // // Axel Naumann <[email protected]>, 2011-05-12 //===----------------------------------------------------------------------===// #include "textinput/TerminalDisplayUnix.h" #include "textinput/TerminalConfigUnix.h" #include "textinput/Color.h" #include <stdio.h> // putenv not in cstdlib on Solaris #include <stdlib.h> #include <unistd.h> #include <sys/ioctl.h> #include <termios.h> #include <csignal> #include <cstring> #include <sstream> using std::signal; using std::strstr; namespace { textinput::TerminalDisplayUnix*& gTerminalDisplayUnix() { static textinput::TerminalDisplayUnix* S = 0; return S; } void InitRGB256(unsigned char rgb256[][3]) { // initialize the array with the expected standard colors: // (from http://frexx.de/xterm-256-notes) // this is not what I see, though it's supposedly the default: // rgb[0][0] = 0; rgb[0][1] = 0; rgb[0][1] = 0; // use this instead, just to be on the safe side: rgb256[0][0] = 46; rgb256[0][1] = 52; rgb256[0][1] = 64; rgb256[1][0] = 205; rgb256[1][1] = 0; rgb256[1][1] = 0; rgb256[2][0] = 0; rgb256[2][1] = 205; rgb256[2][1] = 0; rgb256[3][0] = 205; rgb256[3][1] = 205; rgb256[3][1] = 0; rgb256[4][0] = 0; rgb256[4][1] = 0; rgb256[4][1] = 238; rgb256[5][0] = 205; rgb256[5][1] = 0; rgb256[5][1] = 205; rgb256[6][0] = 0; rgb256[6][1] = 205; rgb256[6][1] = 205; rgb256[7][0] = 229; rgb256[7][1] = 229; rgb256[7][1] = 229; // this is not what I see, though it's supposedly the default: // rgb256[ 8][0] = 127; rgb256[ 8][1] = 127; rgb256[ 8][1] = 127; // use this instead, just to be on the safe side: rgb256[ 8][0] = 0; rgb256[ 8][1] = 0; rgb256[ 8][1] = 0; rgb256[ 9][0] = 255; rgb256[ 9][1] = 0; rgb256[ 9][1] = 0; rgb256[10][0] = 0; rgb256[10][1] = 255; rgb256[10][1] = 0; rgb256[11][0] = 255; rgb256[11][1] = 255; rgb256[11][1] = 0; rgb256[12][0] = 92; rgb256[12][1] = 92; rgb256[12][1] = 255; rgb256[13][0] = 255; rgb256[13][1] = 0; rgb256[13][1] = 255; rgb256[14][0] = 0; rgb256[14][1] = 255; rgb256[14][1] = 255; rgb256[15][0] = 255; rgb256[15][1] = 255; rgb256[15][1] = 255; // 6 intensity RGB static const int intensities[] = {0, 0x5f, 0x87, 0xaf, 0xd7, 0xff}; int idx = 16; for (int r = 0; r < 6; ++r) { for (int g = 0; g < 6; ++g) { for (int b = 0; b < 6; ++b) { rgb256[idx][0] = intensities[r]; rgb256[idx][1] = intensities[g]; rgb256[idx][2] = intensities[b]; ++idx; } } } // colors 232-255 are a grayscale ramp, intentionally leaving out // black and white for (unsigned char gray = 0; gray < 24; ++gray) { unsigned char level = (gray * 10) + 8; rgb256[232 + gray][0] = level; rgb256[232 + gray][1] = level; rgb256[232 + gray][2] = level; } } } // unnamed namespace extern "C" void TerminalDisplayUnix__handleResizeSignal(int) { gTerminalDisplayUnix()->HandleResizeSignal(); } namespace textinput { // If input is not a tty don't write in tty-mode either. TerminalDisplayUnix::TerminalDisplayUnix(): TerminalDisplay(TerminalConfigUnix::Get().IsInteractive()), fIsAttached(false), fNColors(16) { HandleResizeSignal(); gTerminalDisplayUnix() = this; signal(SIGWINCH, TerminalDisplayUnix__handleResizeSignal); #ifdef TCSANOW TerminalConfigUnix::Get().TIOS()->c_lflag &= ~(ECHO); TerminalConfigUnix::Get().TIOS()->c_lflag |= ECHOCTL|ECHOKE|ECHOE; #endif const char* TERM = getenv("TERM"); if (TERM && strstr(TERM, "256")) { fNColors = 256; } } TerminalDisplayUnix::~TerminalDisplayUnix() { Detach(); } void TerminalDisplayUnix::HandleResizeSignal() { #ifdef TIOCGWINSZ struct winsize sz; int ret = ioctl(fileno(stdout), TIOCGWINSZ, (char*)&sz); if (!ret && sz.ws_col) { SetWidth(sz.ws_col); // Export what we found. std::stringstream s; s << sz.ws_col; setenv("COLUMS", s.str().c_str(), 1 /*overwrite*/); s.clear(); s << sz.ws_row; setenv("LINES", s.str().c_str(), 1 /*overwrite*/); } #else // try $COLUMNS const char* COLUMNS = getenv("COLUMNS"); if (COLUMNS) { long width = atol(COLUMNS); if (width > 4 && width < 1024*16) { SetWidth(width); } } #endif } void TerminalDisplayUnix::SetColor(char CIdx, const Color& C) { if (!IsTTY()) return; // Default color, reset previous bold etc. static const char text[] = {(char)0x1b, '[', '0', 'm'}; WriteRawString(text, sizeof(text)); if (CIdx == 0) return; if (fNColors == 256) { int ANSIIdx = GetClosestColorIdx256(C); static const char preamble[] = {'\x1b', '[', '3', '8', ';', '5', ';', 0}; std::string buf(preamble); if (ANSIIdx > 100) { buf += '0' + (ANSIIdx / 100); } if (ANSIIdx > 10) { buf += '0' + ((ANSIIdx / 10) % 10); } buf += '0' + (ANSIIdx % 10); buf += "m"; WriteRawString(buf.c_str(), buf.length()); } else { int ANSIIdx = GetClosestColorIdx16(C); char buf[] = {'\x1b', '[', '3', '0' + (ANSIIdx % 8), 'm', 0}; if (ANSIIdx > 7) buf[2] += 6; WriteRawString(buf, 5); } if (C.fModifiers & Color::kModUnderline) { WriteRawString("\033[4m", 4); } if (C.fModifiers & Color::kModBold) { WriteRawString("\033[1m", 4); } if (C.fModifiers & Color::kModInverse) { WriteRawString("\033[7m", 4); } } void TerminalDisplayUnix::MoveFront() { static const char text[] = {(char)0x1b, '[', '1', 'G'}; if (!IsTTY()) return; WriteRawString(text, sizeof(text)); } void TerminalDisplayUnix::MoveInternal(char What, size_t n) { static const char cmd[] = "\x1b["; if (!IsTTY()) return; std::string text; for (size_t i = 0; i < n; ++i) { text += cmd; text += What; } WriteRawString(text.c_str(), text.length()); } void TerminalDisplayUnix::MoveUp(size_t nLines /* = 1 */) { MoveInternal('A', nLines); } void TerminalDisplayUnix::MoveDown(size_t nLines /* = 1 */) { if (!IsTTY()) return; std::string moves(nLines, 0x0a); WriteRawString(moves.c_str(), nLines); } void TerminalDisplayUnix::MoveRight(size_t nCols /* = 1 */) { MoveInternal('C', nCols); } void TerminalDisplayUnix::MoveLeft(size_t nCols /* = 1 */) { MoveInternal('D', nCols); } void TerminalDisplayUnix::EraseToRight() { static const char text[] = {(char)0x1b, '[', 'K'}; if (!IsTTY()) return; WriteRawString(text, sizeof(text)); } void TerminalDisplayUnix::WriteRawString(const char *text, size_t len) { if (write(fileno(stdout), text, len) == -1) { // Silence Ubuntu's "unused result". We don't care if it fails. } } void TerminalDisplayUnix::ActOnEOL() { if (!IsTTY()) return; WriteRawString(" \b", 2); //MoveUp(); } void TerminalDisplayUnix::Attach() { // set to noecho if (fIsAttached) return; fflush(stdout); TerminalConfigUnix::Get().Attach(); fWritePos = Pos(); fWriteLen = 0; fIsAttached = true; } void TerminalDisplayUnix::Detach() { if (!fIsAttached) return; fflush(stdout); TerminalConfigUnix::Get().Detach(); TerminalDisplay::Detach(); fIsAttached = false; } int TerminalDisplayUnix::GetClosestColorIdx16(const Color& C) { int r = C.fR; int g = C.fG; int b = C.fB; int sum = r + g + b; r = r > sum / 4; g = g > sum / 4; b = b > sum / 4; // ANSI: return r + (g * 2) + (b * 4); // ! ANSI: // return (r * 4) + (g * 2) + b; } int TerminalDisplayUnix::GetClosestColorIdx256(const Color& C) { static unsigned char rgb256[256][3] = {{0}}; if (rgb256[0][0] == 0) { InitRGB256(rgb256); } // Find the closest index. // A: the closest color match (square of geometric distance in RGB) // B: the closest brightness match // Treat them equally, which suppresses differences // in color due to squared distance. // start with black: int idx = 0; unsigned int r = C.fR; unsigned int g = C.fG; unsigned int b = C.fB; unsigned int graylvl = (r + g + b)/3; long mindelta = (r*r + g*g + b*b) + graylvl; if (mindelta) { for (unsigned int i = 0; i < 256; ++i) { long delta = (rgb256[i][0] + rgb256[i][1] + rgb256[i][2])/3 - graylvl; if (delta < 0) delta = -delta; delta += (r-rgb256[i][0])*(r-rgb256[i][0]) + (g-rgb256[i][1])*(g-rgb256[i][1]) + (b-rgb256[i][2])*(b-rgb256[i][2]); if (delta < mindelta) { mindelta = delta; idx = i; if (mindelta == 0) break; } } } return idx; } } #endif // #ifndef WIN32 <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 1999-2009 Soeren Sonnenburg * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #include "classifier/svm/LibSVMMultiClass.h" #include "lib/io.h" using namespace shogun; CLibSVMMultiClass::CLibSVMMultiClass(LIBSVM_SOLVER_TYPE st) : CMultiClassSVM(ONE_VS_ONE), model(NULL), solver_type(st) { } CLibSVMMultiClass::CLibSVMMultiClass(float64_t C, CKernel* k, CLabels* lab) : CMultiClassSVM(ONE_VS_ONE, C, k, lab), model(NULL), solver_type(LIBSVM_C_SVC) { } CLibSVMMultiClass::~CLibSVMMultiClass() { //SG_PRINT("deleting LibSVM\n"); } bool CLibSVMMultiClass::train(CFeatures* data) { struct svm_node* x_space; problem = svm_problem(); ASSERT(labels && labels->get_num_labels()); int32_t num_classes = labels->get_num_classes(); problem.l=labels->get_num_labels(); SG_INFO( "%d trainlabels, %d classes\n", problem.l, num_classes); if (data) { if (labels->get_num_labels() != data->get_num_vectors()) SG_ERROR("Number of training vectors does not match number of labels\n"); kernel->init(data, data); } problem.y=new float64_t[problem.l]; problem.x=new struct svm_node*[problem.l]; problem.pv=new float64_t[problem.l]; problem.C=new float64_t[problem.l]; x_space=new struct svm_node[2*problem.l]; for (int32_t i=0; i<problem.l; i++) { problem.pv[i]=-1.0; problem.y[i]=labels->get_label(i); problem.x[i]=&x_space[2*i]; x_space[2*i].index=i; x_space[2*i+1].index=-1; } ASSERT(kernel); param.svm_type=solver_type; // C SVM or NU_SVM param.kernel_type = LINEAR; param.degree = 3; param.gamma = 0; // 1/k param.coef0 = 0; param.nu = get_nu(); // Nu param.kernel=kernel; param.cache_size = kernel->get_cache_size(); param.max_train_time = max_train_time; param.C = get_C1(); param.eps = epsilon; param.p = 0.1; param.shrinking = 1; param.nr_weight = 0; param.weight_label = NULL; param.weight = NULL; param.use_bias = get_bias_enabled(); const char* error_msg = svm_check_parameter(&problem,&param); if(error_msg) SG_ERROR("Error: %s\n",error_msg); model = svm_train(&problem, &param); if (model) { ASSERT(model->nr_class==num_classes); ASSERT((model->l==0) || (model->l>0 && model->SV && model->sv_coef)); create_multiclass_svm(num_classes); int32_t* offsets=new int32_t[num_classes]; offsets[0]=0; for (int32_t i=1; i<num_classes; i++) offsets[i] = offsets[i-1]+model->nSV[i-1]; int32_t s=0; for (int32_t i=0; i<num_classes; i++) { for (int32_t j=i+1; j<num_classes; j++) { int32_t k, l; float64_t sgn=1; if (model->label[i]>model->label[j]) sgn=-1; int32_t num_sv=model->nSV[i]+model->nSV[j]; float64_t bias=-model->rho[s]; ASSERT(num_sv>0); ASSERT(model->sv_coef[i] && model->sv_coef[j-1]); CSVM* svm=new CSVM(num_sv); svm->set_bias(sgn*bias); int32_t sv_idx=0; for (k=0; k<model->nSV[i]; k++) { svm->set_support_vector(sv_idx, model->SV[offsets[i]+k]->index); svm->set_alpha(sv_idx, sgn*model->sv_coef[j-1][offsets[i]+k]); sv_idx++; } for (k=0; k<model->nSV[j]; k++) { svm->set_support_vector(sv_idx, model->SV[offsets[j]+k]->index); svm->set_alpha(sv_idx, sgn*model->sv_coef[i][offsets[j]+k]); sv_idx++; } int32_t idx=0; if (sgn>0) { for (k=0; k<model->label[i]; k++) idx+=num_classes-k-1; for (l=model->label[i]+1; l<model->label[j]; l++) idx++; } else { for (k=0; k<model->label[j]; k++) idx+=num_classes-k-1; for (l=model->label[j]+1; l<model->label[i]; l++) idx++; } // if (sgn>0) // idx=((num_classes-1)*model->label[i]+model->label[j])/2; // else // idx=((num_classes-1)*model->label[j]+model->label[i])/2; // SG_DEBUG("svm[%d] has %d sv (total: %d), b=%f label:(%d,%d) -> svm[%d]\n", s, num_sv, model->l, bias, model->label[i], model->label[j], idx); set_svm(idx, svm); s++; } } CSVM::set_objective(model->objective); delete[] offsets; delete[] problem.x; delete[] problem.y; delete[] x_space; svm_destroy_model(model); model=NULL; return true; } else return false; } <commit_msg>give a bit more useful error msg<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 1999-2009 Soeren Sonnenburg * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #include "classifier/svm/LibSVMMultiClass.h" #include "lib/io.h" using namespace shogun; CLibSVMMultiClass::CLibSVMMultiClass(LIBSVM_SOLVER_TYPE st) : CMultiClassSVM(ONE_VS_ONE), model(NULL), solver_type(st) { } CLibSVMMultiClass::CLibSVMMultiClass(float64_t C, CKernel* k, CLabels* lab) : CMultiClassSVM(ONE_VS_ONE, C, k, lab), model(NULL), solver_type(LIBSVM_C_SVC) { } CLibSVMMultiClass::~CLibSVMMultiClass() { //SG_PRINT("deleting LibSVM\n"); } bool CLibSVMMultiClass::train(CFeatures* data) { struct svm_node* x_space; problem = svm_problem(); ASSERT(labels && labels->get_num_labels()); int32_t num_classes = labels->get_num_classes(); problem.l=labels->get_num_labels(); SG_INFO( "%d trainlabels, %d classes\n", problem.l, num_classes); if (data) { if (labels->get_num_labels() != data->get_num_vectors()) SG_ERROR("Number of training vectors does not match number of labels\n"); kernel->init(data, data); } problem.y=new float64_t[problem.l]; problem.x=new struct svm_node*[problem.l]; problem.pv=new float64_t[problem.l]; problem.C=new float64_t[problem.l]; x_space=new struct svm_node[2*problem.l]; for (int32_t i=0; i<problem.l; i++) { problem.pv[i]=-1.0; problem.y[i]=labels->get_label(i); problem.x[i]=&x_space[2*i]; x_space[2*i].index=i; x_space[2*i+1].index=-1; } ASSERT(kernel); param.svm_type=solver_type; // C SVM or NU_SVM param.kernel_type = LINEAR; param.degree = 3; param.gamma = 0; // 1/k param.coef0 = 0; param.nu = get_nu(); // Nu param.kernel=kernel; param.cache_size = kernel->get_cache_size(); param.max_train_time = max_train_time; param.C = get_C1(); param.eps = epsilon; param.p = 0.1; param.shrinking = 1; param.nr_weight = 0; param.weight_label = NULL; param.weight = NULL; param.use_bias = get_bias_enabled(); const char* error_msg = svm_check_parameter(&problem,&param); if(error_msg) SG_ERROR("Error: %s\n",error_msg); model = svm_train(&problem, &param); if (model) { if (model->nr_class!=num_classes) { SG_ERROR("LibSVM model->nr_class=%d while num_classes=%d\n", model->nr_class, num_classes); } ASSERT((model->l==0) || (model->l>0 && model->SV && model->sv_coef)); create_multiclass_svm(num_classes); int32_t* offsets=new int32_t[num_classes]; offsets[0]=0; for (int32_t i=1; i<num_classes; i++) offsets[i] = offsets[i-1]+model->nSV[i-1]; int32_t s=0; for (int32_t i=0; i<num_classes; i++) { for (int32_t j=i+1; j<num_classes; j++) { int32_t k, l; float64_t sgn=1; if (model->label[i]>model->label[j]) sgn=-1; int32_t num_sv=model->nSV[i]+model->nSV[j]; float64_t bias=-model->rho[s]; ASSERT(num_sv>0); ASSERT(model->sv_coef[i] && model->sv_coef[j-1]); CSVM* svm=new CSVM(num_sv); svm->set_bias(sgn*bias); int32_t sv_idx=0; for (k=0; k<model->nSV[i]; k++) { svm->set_support_vector(sv_idx, model->SV[offsets[i]+k]->index); svm->set_alpha(sv_idx, sgn*model->sv_coef[j-1][offsets[i]+k]); sv_idx++; } for (k=0; k<model->nSV[j]; k++) { svm->set_support_vector(sv_idx, model->SV[offsets[j]+k]->index); svm->set_alpha(sv_idx, sgn*model->sv_coef[i][offsets[j]+k]); sv_idx++; } int32_t idx=0; if (sgn>0) { for (k=0; k<model->label[i]; k++) idx+=num_classes-k-1; for (l=model->label[i]+1; l<model->label[j]; l++) idx++; } else { for (k=0; k<model->label[j]; k++) idx+=num_classes-k-1; for (l=model->label[j]+1; l<model->label[i]; l++) idx++; } // if (sgn>0) // idx=((num_classes-1)*model->label[i]+model->label[j])/2; // else // idx=((num_classes-1)*model->label[j]+model->label[i])/2; // SG_DEBUG("svm[%d] has %d sv (total: %d), b=%f label:(%d,%d) -> svm[%d]\n", s, num_sv, model->l, bias, model->label[i], model->label[j], idx); set_svm(idx, svm); s++; } } CSVM::set_objective(model->objective); delete[] offsets; delete[] problem.x; delete[] problem.y; delete[] x_space; svm_destroy_model(model); model=NULL; return true; } else return false; } <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2017 David Ok <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <DO/Sara/Core/StdVectorHelpers.hpp> #include <DO/Sara/ImageProcessing/DataAugmentation.hpp> using namespace std; namespace DO { namespace Sara { Image<Rgb32f> ImageDataTransform::operator()(const Image<Rgb32f>& in) const { auto out = extract_patch(in); if (apply_transform[FancyPCA]) ColorFancyPCA{U, S}(out, alpha); return out; } VectorXf linspace(float a, float b, int num_samples) { auto range = VectorXf(num_samples); for (int i = 0; i < num_samples; ++i) range[i] = a + (b - a) * i / (num_samples - 1); return range; } VectorXf logspace(float a, float b, int num_samples) { return linspace(log(a), log(b), num_samples).array().exp().matrix(); } auto compose_with_zooms(const Vector2i& in_image_sizes, const Vector2i& out_image_sizes, float zmin, float zmax, int num_scales, const ImageDataTransform& parent_t, bool ignore_zoom_factor_one) -> vector<ImageDataTransform> { const auto zs = logspace(zmin, zmax, num_scales); const auto z_image_sizes = (in_image_sizes.cast<float>() * zs.transpose()); auto ts = vector<ImageDataTransform>{}; for (int j = 0; j < num_scales; ++j) { if (ignore_zoom_factor_one && j == num_scales / 2 && num_scales % 2 == 1) continue; if (z_image_sizes.col(j).x() < out_image_sizes.x() || z_image_sizes.col(j).y() < out_image_sizes.y()) continue; auto child_t = parent_t; child_t.set_zoom(zs[j]); ts.push_back(child_t); } return ts; } auto compose_with_shifts(const Vector2i& in_image_sizes, const Vector2i& out_image_sizes, const Vector2i& delta, const ImageDataTransform& parent_t) -> vector<ImageDataTransform> { if (in_image_sizes == out_image_sizes) return {}; auto ts = vector<ImageDataTransform>{}; for (int y = 0; y + out_image_sizes.y() < in_image_sizes.y(); y += delta.y()) { for (int x = 0; x + out_image_sizes.x() < in_image_sizes.x(); x += delta.x()) { auto child_t = parent_t; child_t.set_shift(Vector2i{x, y}); ts.push_back(child_t); } } return ts; } auto compose_with_horizontal_flip(const ImageDataTransform& parent_t) -> vector<ImageDataTransform> { auto child_t = parent_t; child_t.set_flip(ImageDataTransform::Horizontal); return {child_t}; }; auto compose_with_random_fancy_pca(const ImageDataTransform& parent_t, int num_fancy_pca, float fancy_pca_std_dev, const NormalDistribution& randn) -> vector<ImageDataTransform> { auto ts = vector<ImageDataTransform>{}; for (auto i = 0; i < num_fancy_pca; ++i) { auto alpha = Vector3f{}; randn(alpha); alpha *= fancy_pca_std_dev; auto t = parent_t; t.set_fancy_pca(alpha); ts.push_back(t); } return ts; } auto enumerate_image_data_transforms( const Vector2i& in_sz, const Vector2i& out_sz, bool zoom, float zmin, float zmax, int num_scales, bool shift, const Vector2i& delta, bool flip, bool fancy_pca, int num_fancy_pca_alpha, float fancy_pca_std_dev, const NormalDistribution& randn) -> vector<ImageDataTransform> { auto ts = vector<ImageDataTransform>{}; // Put the identity data transform. auto t0 = ImageDataTransform{}; t0.out_sizes = out_sz; ts.push_back(t0); auto range = make_pair(decltype(ts.size()){0}, ts.size()); if (fancy_pca) { const auto f_o_ts = compose_with_random_fancy_pca(t0, num_fancy_pca_alpha, fancy_pca_std_dev, randn); append(ts, f_o_ts); range = make_pair(range.first, ts.size()); } if (zoom) { for (auto t = range.first, t_end = range.second; t != t_end; ++t) { const auto z_o_ts = compose_with_zooms(in_sz, out_sz, zmin, zmax, num_scales, ts[t]); append(ts, z_o_ts); } range = make_pair(range.first, ts.size()); } if (shift) { for (auto t = range.first, t_end = range.second; t != t_end; ++t) { const auto s_o_ts = compose_with_shifts(in_sz, out_sz, delta, ts[t]); append(ts, s_o_ts); } range = make_pair(range.first, ts.size()); } if (flip) { for (auto t = range.first, t_end = range.second; t != t_end; ++t) { const auto f_o_ts = compose_with_horizontal_flip(ts[t]); append(ts, f_o_ts); } } return ts; } auto augment_data(const std::vector<int>& data_indices, const Vector2i& in_sz, const Vector2i& out_sz, bool zoom, float zmin, float zmax, int num_scales, bool shift, const Vector2i& delta, bool flip, bool fancy_pca, int num_fancy_pca, float fancy_pca_std_dev, const NormalDistribution& randn) -> vector<pair<int, ImageDataTransform>> { auto augmented_data = vector<pair<int, ImageDataTransform>>{}; for (const auto i : data_indices) { const auto data_transforms = enumerate_image_data_transforms( in_sz, out_sz, zoom, zmin, zmax, num_scales, shift, delta, flip, fancy_pca, num_fancy_pca, fancy_pca_std_dev, randn); for (const auto t : data_transforms) augmented_data.push_back(make_pair(i, t)); } return augmented_data; } } /* namespace Sara */ } /* namespace DO */ <commit_msg>MAINT: avoid data copy.<commit_after>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2017 David Ok <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <DO/Sara/Core/StdVectorHelpers.hpp> #include <DO/Sara/ImageProcessing/DataAugmentation.hpp> using namespace std; namespace DO { namespace Sara { Image<Rgb32f> ImageDataTransform::operator()(const Image<Rgb32f>& in) const { auto out = extract_patch(in); if (apply_transform[FancyPCA]) ColorFancyPCA{U, S}(out, alpha); return out; } VectorXf linspace(float a, float b, int num_samples) { auto range = VectorXf(num_samples); for (int i = 0; i < num_samples; ++i) range[i] = a + (b - a) * i / (num_samples - 1); return range; } VectorXf logspace(float a, float b, int num_samples) { return linspace(log(a), log(b), num_samples).array().exp().matrix(); } auto compose_with_zooms(const Vector2i& in_image_sizes, const Vector2i& out_image_sizes, float zmin, float zmax, int num_scales, const ImageDataTransform& parent_t, bool ignore_zoom_factor_one) -> vector<ImageDataTransform> { const auto zs = logspace(zmin, zmax, num_scales); const auto z_image_sizes = (in_image_sizes.cast<float>() * zs.transpose()); auto ts = vector<ImageDataTransform>{}; for (int j = 0; j < num_scales; ++j) { if (ignore_zoom_factor_one && j == num_scales / 2 && num_scales % 2 == 1) continue; if (z_image_sizes.col(j).x() < out_image_sizes.x() || z_image_sizes.col(j).y() < out_image_sizes.y()) continue; auto child_t = parent_t; child_t.set_zoom(zs[j]); ts.push_back(child_t); } return ts; } auto compose_with_shifts(const Vector2i& in_image_sizes, const Vector2i& out_image_sizes, const Vector2i& delta, const ImageDataTransform& parent_t) -> vector<ImageDataTransform> { if (in_image_sizes == out_image_sizes) return {}; auto ts = vector<ImageDataTransform>{}; for (int y = 0; y + out_image_sizes.y() < in_image_sizes.y(); y += delta.y()) { for (int x = 0; x + out_image_sizes.x() < in_image_sizes.x(); x += delta.x()) { auto child_t = parent_t; child_t.set_shift(Vector2i{x, y}); ts.push_back(child_t); } } return ts; } auto compose_with_horizontal_flip(const ImageDataTransform& parent_t) -> vector<ImageDataTransform> { auto child_t = parent_t; child_t.set_flip(ImageDataTransform::Horizontal); return {child_t}; }; auto compose_with_random_fancy_pca(const ImageDataTransform& parent_t, int num_fancy_pca, float fancy_pca_std_dev, const NormalDistribution& randn) -> vector<ImageDataTransform> { auto ts = vector<ImageDataTransform>{}; for (auto i = 0; i < num_fancy_pca; ++i) { auto alpha = Vector3f{}; randn(alpha); alpha *= fancy_pca_std_dev; auto t = parent_t; t.set_fancy_pca(alpha); ts.push_back(t); } return ts; } auto enumerate_image_data_transforms( const Vector2i& in_sz, const Vector2i& out_sz, bool zoom, float zmin, float zmax, int num_scales, bool shift, const Vector2i& delta, bool flip, bool fancy_pca, int num_fancy_pca_alpha, float fancy_pca_std_dev, const NormalDistribution& randn) -> vector<ImageDataTransform> { auto ts = vector<ImageDataTransform>{}; // Put the identity data transform. auto t0 = ImageDataTransform{}; t0.out_sizes = out_sz; ts.push_back(t0); auto range = make_pair(decltype(ts.size()){0}, ts.size()); if (fancy_pca) { const auto f_o_ts = compose_with_random_fancy_pca(t0, num_fancy_pca_alpha, fancy_pca_std_dev, randn); append(ts, f_o_ts); range = make_pair(range.first, ts.size()); } if (zoom) { for (auto t = range.first, t_end = range.second; t != t_end; ++t) { const auto z_o_ts = compose_with_zooms(in_sz, out_sz, zmin, zmax, num_scales, ts[t]); append(ts, z_o_ts); } range = make_pair(range.first, ts.size()); } if (shift) { for (auto t = range.first, t_end = range.second; t != t_end; ++t) { const auto s_o_ts = compose_with_shifts(in_sz, out_sz, delta, ts[t]); append(ts, s_o_ts); } range = make_pair(range.first, ts.size()); } if (flip) { for (auto t = range.first, t_end = range.second; t != t_end; ++t) { const auto f_o_ts = compose_with_horizontal_flip(ts[t]); append(ts, f_o_ts); } } return ts; } auto augment_data(const std::vector<int>& data_indices, const Vector2i& in_sz, const Vector2i& out_sz, bool zoom, float zmin, float zmax, int num_scales, bool shift, const Vector2i& delta, bool flip, bool fancy_pca, int num_fancy_pca, float fancy_pca_std_dev, const NormalDistribution& randn) -> vector<pair<int, ImageDataTransform>> { auto augmented_data = vector<pair<int, ImageDataTransform>>{}; for (const auto i : data_indices) { const auto data_transforms = enumerate_image_data_transforms( in_sz, out_sz, zoom, zmin, zmax, num_scales, shift, delta, flip, fancy_pca, num_fancy_pca, fancy_pca_std_dev, randn); for (const auto& t : data_transforms) augmented_data.push_back(make_pair(i, t)); } return augmented_data; } } /* namespace Sara */ } /* namespace DO */ <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin-explorer. * * libbitcoin-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/explorer/primitives/btc160.hpp> #include <iostream> #include <sstream> #include <string> #include <boost/program_options.hpp> #include <bitcoin/bitcoin.hpp> #include <bitcoin/explorer/define.hpp> #include <bitcoin/explorer/primitives/base16.hpp> using namespace po; namespace libbitcoin { namespace explorer { namespace primitives { // This is not a libbitcoin utility similar to that for hash_digest // because it's just a simple base16 conversion. static bool decode_hash(short_hash& out, const std::string& in) { if (in.size() != 2 * out.size()) return false; if (!decode_base16_raw(out.data(), out.size(), in.data())) return false; return true; } btc160::btc160() : value_() { } btc160::btc160(const std::string& hexcode) { std::stringstream(hexcode) >> *this; } btc160::btc160(const short_hash& value) : value_(value) { } // This drops the address version number. btc160::btc160(const payment_address& address) : btc160(address.hash()) { } btc160::btc160(const btc160& other) : btc160(other.value_) { } btc160::operator const short_hash&() const { return value_; } std::istream& operator>>(std::istream& input, btc160& argument) { std::string hexcode; input >> hexcode; if (!decode_hash(argument.value_, hexcode)) BOOST_THROW_EXCEPTION(invalid_option_value(hexcode)); return input; } std::ostream& operator<<(std::ostream& output, const btc160& argument) { output << base16(argument.value_); return output; } } // namespace explorer } // namespace primitives } // namespace libbitcoin <commit_msg>Remove private decode_hash(short) in favor of bc::decode_hash(short).<commit_after>/** * Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin-explorer. * * libbitcoin-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/explorer/primitives/btc160.hpp> #include <iostream> #include <sstream> #include <string> #include <boost/program_options.hpp> #include <bitcoin/bitcoin.hpp> #include <bitcoin/explorer/define.hpp> #include <bitcoin/explorer/primitives/base16.hpp> using namespace po; namespace libbitcoin { namespace explorer { namespace primitives { btc160::btc160() : value_() { } btc160::btc160(const std::string& hexcode) { std::stringstream(hexcode) >> *this; } btc160::btc160(const short_hash& value) : value_(value) { } // This drops the address version number. btc160::btc160(const payment_address& address) : btc160(address.hash()) { } btc160::btc160(const btc160& other) : btc160(other.value_) { } btc160::operator const short_hash&() const { return value_; } std::istream& operator>>(std::istream& input, btc160& argument) { std::string hexcode; input >> hexcode; if (!decode_hash(argument.value_, hexcode)) BOOST_THROW_EXCEPTION(invalid_option_value(hexcode)); return input; } std::ostream& operator<<(std::ostream& output, const btc160& argument) { output << base16(argument.value_); return output; } } // namespace explorer } // namespace primitives } // namespace libbitcoin <|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS visibility03 (1.11.66); FILE MERGED 2005/04/04 11:39:23 mhu 1.11.66.2: #i45006# Removed obsolete include. 2005/03/26 16:31:47 mhu 1.11.66.1: #i45006# subst includes svtools/sbx with basic/sbx<commit_after><|endoftext|>
<commit_before><commit_msg>Bitmap Tree Cleanup - calc<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include <com/sun/star/table/CellAddress.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #include <svl/itemprop.hxx> #include "docsh.hxx" #include "unonames.hxx" #include "unoguard.hxx" #include "miscuno.hxx" #include "convuno.hxx" #include "addruno.hxx" using namespace com::sun::star; //------------------------------------------------------------------------ ScAddressConversionObj::ScAddressConversionObj(ScDocShell* pDocSh, sal_Bool bForRange) : pDocShell( pDocSh ), nRefSheet( 0 ), bIsRange( bForRange ) { pDocShell->GetDocument()->AddUnoObject(*this); } ScAddressConversionObj::~ScAddressConversionObj() { if (pDocShell) pDocShell->GetDocument()->RemoveUnoObject(*this); } void ScAddressConversionObj::Notify( SfxBroadcaster&, const SfxHint& rHint ) { if ( rHint.ISA( SfxSimpleHint ) && ((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING ) { pDocShell = NULL; // invalid } } sal_Bool ScAddressConversionObj::ParseUIString( const String& rUIString, ::formula::FormulaGrammar::AddressConvention eConv ) { if (!pDocShell) return sal_False; ScDocument* pDoc = pDocShell->GetDocument(); sal_Bool bSuccess = sal_False; if ( bIsRange ) { sal_uInt16 nResult = aRange.ParseAny( rUIString, pDoc, eConv ); if ( nResult & SCA_VALID ) { if ( ( nResult & SCA_TAB_3D ) == 0 ) aRange.aStart.SetTab( static_cast<SCTAB>(nRefSheet) ); if ( ( nResult & SCA_TAB2_3D ) == 0 ) aRange.aEnd.SetTab( aRange.aStart.Tab() ); // different sheets are not supported in CellRangeAddress if ( aRange.aStart.Tab() == aRange.aEnd.Tab() ) bSuccess = sal_True; } } else { sal_uInt16 nResult = aRange.aStart.Parse( rUIString, pDoc, eConv ); if ( nResult & SCA_VALID ) { if ( ( nResult & SCA_TAB_3D ) == 0 ) aRange.aStart.SetTab( static_cast<SCTAB>(nRefSheet) ); bSuccess = sal_True; } } return bSuccess; } // XPropertySet uno::Reference<beans::XPropertySetInfo> SAL_CALL ScAddressConversionObj::getPropertySetInfo() throw(uno::RuntimeException) { ScUnoGuard aGuard; if ( bIsRange ) { static SfxItemPropertyMapEntry aPropertyMap[] = { {MAP_CHAR_LEN(SC_UNONAME_ADDRESS), 0, &getCppuType((table::CellRangeAddress*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_PERSREPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_REFSHEET), 0, &getCppuType((sal_Int32*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_UIREPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_XLA1REPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {0,0,0,0,0,0} }; static uno::Reference<beans::XPropertySetInfo> aRef(new SfxItemPropertySetInfo( aPropertyMap )); return aRef; } else { static SfxItemPropertyMapEntry aPropertyMap[] = { {MAP_CHAR_LEN(SC_UNONAME_ADDRESS), 0, &getCppuType((table::CellAddress*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_PERSREPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_REFSHEET), 0, &getCppuType((sal_Int32*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_UIREPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_XLA1REPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {0,0,0,0,0,0} }; static uno::Reference<beans::XPropertySetInfo> aRef(new SfxItemPropertySetInfo( aPropertyMap )); return aRef; } } void SAL_CALL ScAddressConversionObj::setPropertyValue( const rtl::OUString& aPropertyName, const uno::Any& aValue ) throw(beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException, lang::WrappedTargetException, uno::RuntimeException) { if ( !pDocShell ) throw uno::RuntimeException(); sal_Bool bSuccess = sal_False; String aNameStr(aPropertyName); if ( aNameStr.EqualsAscii( SC_UNONAME_ADDRESS ) ) { // read the cell/range address from API struct if ( bIsRange ) { table::CellRangeAddress aRangeAddress; if ( aValue >>= aRangeAddress ) { ScUnoConversion::FillScRange( aRange, aRangeAddress ); bSuccess = sal_True; } } else { table::CellAddress aCellAddress; if ( aValue >>= aCellAddress ) { ScUnoConversion::FillScAddress( aRange.aStart, aCellAddress ); bSuccess = sal_True; } } } else if ( aNameStr.EqualsAscii( SC_UNONAME_REFSHEET ) ) { // set the reference sheet sal_Int32 nIntVal = 0; if ( aValue >>= nIntVal ) { nRefSheet = nIntVal; bSuccess = sal_True; } } else if ( aNameStr.EqualsAscii( SC_UNONAME_UIREPR ) ) { // parse the UI representation string rtl::OUString sRepresentation; if (aValue >>= sRepresentation) { String aUIString = sRepresentation; bSuccess = ParseUIString( aUIString ); } } else if ( aNameStr.EqualsAscii( SC_UNONAME_PERSREPR ) || aNameStr.EqualsAscii( SC_UNONAME_XLA1REPR ) ) { ::formula::FormulaGrammar::AddressConvention eConv = aNameStr.EqualsAscii( SC_UNONAME_XLA1REPR ) ? ::formula::FormulaGrammar::CONV_OOO : ::formula::FormulaGrammar::CONV_XL_A1; // parse the file format string rtl::OUString sRepresentation; if (aValue >>= sRepresentation) { String aUIString(sRepresentation); // cell or range: strip a single "." at the start if ( aUIString.GetChar(0) == (sal_Unicode) '.' ) aUIString.Erase( 0, 1 ); if ( bIsRange ) { // range: also strip a "." after the last colon sal_Int32 nColon = rtl::OUString(aUIString).lastIndexOf( (sal_Unicode) ':' ); if ( nColon >= 0 && nColon < aUIString.Len() - 1 && aUIString.GetChar((xub_StrLen)nColon+1) == (sal_Unicode) '.' ) aUIString.Erase( (xub_StrLen)nColon+1, 1 ); } // parse the rest like a UI string bSuccess = ParseUIString( aUIString, eConv ); } } else throw beans::UnknownPropertyException(); if ( !bSuccess ) throw lang::IllegalArgumentException(); } uno::Any SAL_CALL ScAddressConversionObj::getPropertyValue( const rtl::OUString& aPropertyName ) throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException) { if ( !pDocShell ) throw uno::RuntimeException(); ScDocument* pDoc = pDocShell->GetDocument(); uno::Any aRet; String aNameStr(aPropertyName); if ( aNameStr.EqualsAscii( SC_UNONAME_ADDRESS ) ) { if ( bIsRange ) { table::CellRangeAddress aRangeAddress; ScUnoConversion::FillApiRange( aRangeAddress, aRange ); aRet <<= aRangeAddress; } else { table::CellAddress aCellAddress; ScUnoConversion::FillApiAddress( aCellAddress, aRange.aStart ); aRet <<= aCellAddress; } } else if ( aNameStr.EqualsAscii( SC_UNONAME_REFSHEET ) ) { aRet <<= nRefSheet; } else if ( aNameStr.EqualsAscii( SC_UNONAME_UIREPR ) ) { // generate UI representation string - include sheet only if different from ref sheet String aFormatStr; sal_uInt16 nFlags = SCA_VALID; if ( aRange.aStart.Tab() != nRefSheet ) nFlags |= SCA_TAB_3D; if ( bIsRange ) aRange.Format( aFormatStr, nFlags, pDoc ); else aRange.aStart.Format( aFormatStr, nFlags, pDoc ); aRet <<= rtl::OUString( aFormatStr ); } else if ( aNameStr.EqualsAscii( SC_UNONAME_PERSREPR ) || aNameStr.EqualsAscii( SC_UNONAME_XLA1REPR ) ) { ::formula::FormulaGrammar::AddressConvention eConv = aNameStr.EqualsAscii( SC_UNONAME_XLA1REPR ) ? ::formula::FormulaGrammar::CONV_OOO : ::formula::FormulaGrammar::CONV_XL_A1; // generate file format string - always include sheet String aFormatStr; aRange.aStart.Format( aFormatStr, SCA_VALID | SCA_TAB_3D, pDoc, eConv ); if ( bIsRange ) { // manually concatenate range so both parts always have the sheet name aFormatStr.Append( (sal_Unicode) ':' ); String aSecond; sal_uInt16 nFlags = SCA_VALID; if( eConv != ::formula::FormulaGrammar::CONV_XL_A1 ) nFlags |= SCA_TAB_3D; aRange.aEnd.Format( aSecond, nFlags, pDoc, eConv ); aFormatStr.Append( aSecond ); } aRet <<= rtl::OUString( aFormatStr ); } else throw beans::UnknownPropertyException(); return aRet; } SC_IMPL_DUMMY_PROPERTY_LISTENER( ScAddressConversionObj ) // lang::XServiceInfo rtl::OUString SAL_CALL ScAddressConversionObj::getImplementationName() throw(uno::RuntimeException) { return rtl::OUString::createFromAscii( "ScAddressConversionObj" ); } sal_Bool SAL_CALL ScAddressConversionObj::supportsService( const rtl::OUString& rServiceName ) throw(uno::RuntimeException) { String aServiceStr( rServiceName ); return aServiceStr.EqualsAscii( bIsRange ? SC_SERVICENAME_RANGEADDRESS : SC_SERVICENAME_CELLADDRESS ); } uno::Sequence<rtl::OUString> SAL_CALL ScAddressConversionObj::getSupportedServiceNames() throw(uno::RuntimeException) { uno::Sequence<rtl::OUString> aRet(1); rtl::OUString* pArray = aRet.getArray(); pArray[0] = rtl::OUString::createFromAscii( bIsRange ? SC_SERVICENAME_RANGEADDRESS : SC_SERVICENAME_CELLADDRESS ); return aRet; } <commit_msg>Automated merge with ssh://[email protected]/cws/dba34c<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include <com/sun/star/table/CellAddress.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #include <svl/itemprop.hxx> #include "docsh.hxx" #include "unonames.hxx" #include "unoguard.hxx" #include "miscuno.hxx" #include "convuno.hxx" #include "addruno.hxx" using namespace com::sun::star; //------------------------------------------------------------------------ ScAddressConversionObj::ScAddressConversionObj(ScDocShell* pDocSh, sal_Bool bForRange) : pDocShell( pDocSh ), nRefSheet( 0 ), bIsRange( bForRange ) { pDocShell->GetDocument()->AddUnoObject(*this); } ScAddressConversionObj::~ScAddressConversionObj() { if (pDocShell) pDocShell->GetDocument()->RemoveUnoObject(*this); } void ScAddressConversionObj::Notify( SfxBroadcaster&, const SfxHint& rHint ) { if ( rHint.ISA( SfxSimpleHint ) && ((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING ) { pDocShell = NULL; // invalid } } sal_Bool ScAddressConversionObj::ParseUIString( const String& rUIString, ::formula::FormulaGrammar::AddressConvention eConv ) { if (!pDocShell) return sal_False; ScDocument* pDoc = pDocShell->GetDocument(); sal_Bool bSuccess = sal_False; if ( bIsRange ) { sal_uInt16 nResult = aRange.ParseAny( rUIString, pDoc, eConv ); if ( nResult & SCA_VALID ) { if ( ( nResult & SCA_TAB_3D ) == 0 ) aRange.aStart.SetTab( static_cast<SCTAB>(nRefSheet) ); if ( ( nResult & SCA_TAB2_3D ) == 0 ) aRange.aEnd.SetTab( aRange.aStart.Tab() ); // different sheets are not supported in CellRangeAddress if ( aRange.aStart.Tab() == aRange.aEnd.Tab() ) bSuccess = sal_True; } } else { sal_uInt16 nResult = aRange.aStart.Parse( rUIString, pDoc, eConv ); if ( nResult & SCA_VALID ) { if ( ( nResult & SCA_TAB_3D ) == 0 ) aRange.aStart.SetTab( static_cast<SCTAB>(nRefSheet) ); bSuccess = sal_True; } } return bSuccess; } // XPropertySet uno::Reference<beans::XPropertySetInfo> SAL_CALL ScAddressConversionObj::getPropertySetInfo() throw(uno::RuntimeException) { ScUnoGuard aGuard; if ( bIsRange ) { static SfxItemPropertyMapEntry aPropertyMap[] = { {MAP_CHAR_LEN(SC_UNONAME_ADDRESS), 0, &getCppuType((table::CellRangeAddress*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_PERSREPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_REFSHEET), 0, &getCppuType((sal_Int32*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_UIREPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_XLA1REPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {0,0,0,0,0,0} }; static uno::Reference<beans::XPropertySetInfo> aRef(new SfxItemPropertySetInfo( aPropertyMap )); return aRef; } else { static SfxItemPropertyMapEntry aPropertyMap[] = { {MAP_CHAR_LEN(SC_UNONAME_ADDRESS), 0, &getCppuType((table::CellAddress*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_PERSREPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_REFSHEET), 0, &getCppuType((sal_Int32*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_UIREPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNONAME_XLA1REPR), 0, &getCppuType((rtl::OUString*)0), 0, 0 }, {0,0,0,0,0,0} }; static uno::Reference<beans::XPropertySetInfo> aRef(new SfxItemPropertySetInfo( aPropertyMap )); return aRef; } } void SAL_CALL ScAddressConversionObj::setPropertyValue( const rtl::OUString& aPropertyName, const uno::Any& aValue ) throw(beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException, lang::WrappedTargetException, uno::RuntimeException) { if ( !pDocShell ) throw uno::RuntimeException(); sal_Bool bSuccess = sal_False; String aNameStr(aPropertyName); if ( aNameStr.EqualsAscii( SC_UNONAME_ADDRESS ) ) { // read the cell/range address from API struct if ( bIsRange ) { table::CellRangeAddress aRangeAddress; if ( aValue >>= aRangeAddress ) { ScUnoConversion::FillScRange( aRange, aRangeAddress ); bSuccess = sal_True; } } else { table::CellAddress aCellAddress; if ( aValue >>= aCellAddress ) { ScUnoConversion::FillScAddress( aRange.aStart, aCellAddress ); bSuccess = sal_True; } } } else if ( aNameStr.EqualsAscii( SC_UNONAME_REFSHEET ) ) { // set the reference sheet sal_Int32 nIntVal = 0; if ( aValue >>= nIntVal ) { nRefSheet = nIntVal; bSuccess = sal_True; } } else if ( aNameStr.EqualsAscii( SC_UNONAME_UIREPR ) ) { // parse the UI representation string rtl::OUString sRepresentation; if (aValue >>= sRepresentation) { String aUIString = sRepresentation; bSuccess = ParseUIString( aUIString ); } } else if ( aNameStr.EqualsAscii( SC_UNONAME_PERSREPR ) || aNameStr.EqualsAscii( SC_UNONAME_XLA1REPR ) ) { ::formula::FormulaGrammar::AddressConvention eConv = aNameStr.EqualsAscii( SC_UNONAME_XLA1REPR ) ? ::formula::FormulaGrammar::CONV_XL_A1 : ::formula::FormulaGrammar::CONV_OOO; // parse the file format string rtl::OUString sRepresentation; if (aValue >>= sRepresentation) { String aUIString(sRepresentation); // cell or range: strip a single "." at the start if ( aUIString.GetChar(0) == (sal_Unicode) '.' ) aUIString.Erase( 0, 1 ); if ( bIsRange ) { // range: also strip a "." after the last colon sal_Int32 nColon = rtl::OUString(aUIString).lastIndexOf( (sal_Unicode) ':' ); if ( nColon >= 0 && nColon < aUIString.Len() - 1 && aUIString.GetChar((xub_StrLen)nColon+1) == (sal_Unicode) '.' ) aUIString.Erase( (xub_StrLen)nColon+1, 1 ); } // parse the rest like a UI string bSuccess = ParseUIString( aUIString, eConv ); } } else throw beans::UnknownPropertyException(); if ( !bSuccess ) throw lang::IllegalArgumentException(); } uno::Any SAL_CALL ScAddressConversionObj::getPropertyValue( const rtl::OUString& aPropertyName ) throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException) { if ( !pDocShell ) throw uno::RuntimeException(); ScDocument* pDoc = pDocShell->GetDocument(); uno::Any aRet; String aNameStr(aPropertyName); if ( aNameStr.EqualsAscii( SC_UNONAME_ADDRESS ) ) { if ( bIsRange ) { table::CellRangeAddress aRangeAddress; ScUnoConversion::FillApiRange( aRangeAddress, aRange ); aRet <<= aRangeAddress; } else { table::CellAddress aCellAddress; ScUnoConversion::FillApiAddress( aCellAddress, aRange.aStart ); aRet <<= aCellAddress; } } else if ( aNameStr.EqualsAscii( SC_UNONAME_REFSHEET ) ) { aRet <<= nRefSheet; } else if ( aNameStr.EqualsAscii( SC_UNONAME_UIREPR ) ) { // generate UI representation string - include sheet only if different from ref sheet String aFormatStr; sal_uInt16 nFlags = SCA_VALID; if ( aRange.aStart.Tab() != nRefSheet ) nFlags |= SCA_TAB_3D; if ( bIsRange ) aRange.Format( aFormatStr, nFlags, pDoc ); else aRange.aStart.Format( aFormatStr, nFlags, pDoc ); aRet <<= rtl::OUString( aFormatStr ); } else if ( aNameStr.EqualsAscii( SC_UNONAME_PERSREPR ) || aNameStr.EqualsAscii( SC_UNONAME_XLA1REPR ) ) { ::formula::FormulaGrammar::AddressConvention eConv = aNameStr.EqualsAscii( SC_UNONAME_XLA1REPR ) ? ::formula::FormulaGrammar::CONV_XL_A1 : ::formula::FormulaGrammar::CONV_OOO; // generate file format string - always include sheet String aFormatStr; aRange.aStart.Format( aFormatStr, SCA_VALID | SCA_TAB_3D, pDoc, eConv ); if ( bIsRange ) { // manually concatenate range so both parts always have the sheet name aFormatStr.Append( (sal_Unicode) ':' ); String aSecond; sal_uInt16 nFlags = SCA_VALID; if( eConv != ::formula::FormulaGrammar::CONV_XL_A1 ) nFlags |= SCA_TAB_3D; aRange.aEnd.Format( aSecond, nFlags, pDoc, eConv ); aFormatStr.Append( aSecond ); } aRet <<= rtl::OUString( aFormatStr ); } else throw beans::UnknownPropertyException(); return aRet; } SC_IMPL_DUMMY_PROPERTY_LISTENER( ScAddressConversionObj ) // lang::XServiceInfo rtl::OUString SAL_CALL ScAddressConversionObj::getImplementationName() throw(uno::RuntimeException) { return rtl::OUString::createFromAscii( "ScAddressConversionObj" ); } sal_Bool SAL_CALL ScAddressConversionObj::supportsService( const rtl::OUString& rServiceName ) throw(uno::RuntimeException) { String aServiceStr( rServiceName ); return aServiceStr.EqualsAscii( bIsRange ? SC_SERVICENAME_RANGEADDRESS : SC_SERVICENAME_CELLADDRESS ); } uno::Sequence<rtl::OUString> SAL_CALL ScAddressConversionObj::getSupportedServiceNames() throw(uno::RuntimeException) { uno::Sequence<rtl::OUString> aRet(1); rtl::OUString* pArray = aRet.getArray(); pArray[0] = rtl::OUString::createFromAscii( bIsRange ? SC_SERVICENAME_RANGEADDRESS : SC_SERVICENAME_CELLADDRESS ); return aRet; } <|endoftext|>
<commit_before>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2010-08-13 Markus Litz <[email protected]> * Changed: $Id$ * * Version: $Revision$ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * @brief Implementation of the TIGL UID manager. */ #include "CTiglUIDManager.h" #include "CTiglError.h" namespace tigl { // Constructor CTiglUIDManager::CTiglUIDManager(void) : invalidated(true), rootComponent(0) { } // Destructor CTiglUIDManager::~CTiglUIDManager(void) { Clear(); } // Update internal UID manager data. void CTiglUIDManager::Update(void) { if (!invalidated) { return; } FindRootComponent(); BuildParentChildTree(); invalidated = false; } // Function to add a UID and a geometric component to the uid store. void CTiglUIDManager::AddUID(const std::string& uid, ITiglGeometricComponent* componentPtr) { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::AddUID", TIGL_XML_ERROR); } if (HasUID(uid)) { throw CTiglError("UID already exist in CTiglUIDManager::AddUID", TIGL_XML_ERROR); } if (componentPtr == 0) { throw CTiglError("Null pointer for component in CTiglUIDManager::AddUID", TIGL_NULL_POINTER); } CTiglAbstractPhysicalComponent* tmp = dynamic_cast<CTiglAbstractPhysicalComponent*>(componentPtr); if (tmp && (componentPtr->GetComponentType() | TIGL_COMPONENT_PHYSICAL) ) { physicalShapes[uid] = tmp; } allShapes[uid] = componentPtr; invalidated = true; } // Checks if a UID already exists. bool CTiglUIDManager::HasUID(const std::string& uid) const { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::HasUID", TIGL_XML_ERROR); } return (allShapes.find(uid) != allShapes.end()); } // Returns a pointer to the geometric component for the given unique id. ITiglGeometricComponent* CTiglUIDManager::GetComponent(const std::string& uid) { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::GetComponent", TIGL_UID_ERROR); } if (!HasUID(uid)) { std::stringstream stream; stream << "UID " << uid << " not found in CTiglUIDManager::GetComponent"; throw CTiglError(stream.str(), TIGL_UID_ERROR); } return allShapes[uid]; } // Returns a pointer to the geometric component for the given unique id. CTiglAbstractPhysicalComponent* CTiglUIDManager::GetPhysicalComponent(const std::string& uid) { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::GetComponent", TIGL_XML_ERROR); } if (physicalShapes.find(uid) == physicalShapes.end()) { throw CTiglError("UID not found in CTiglUIDManager::GetComponent", TIGL_XML_ERROR); } return physicalShapes[uid]; } // Clears the uid store void CTiglUIDManager::Clear(void) { physicalShapes.clear(); rootComponent = 0; invalidated = true; } // Returns the parent component for a component or a null pointer // if there is no parent. CTiglAbstractPhysicalComponent* CTiglUIDManager::GetParentComponent(const std::string& uid) { CTiglAbstractPhysicalComponent* component = GetPhysicalComponent(uid); std::string parentUID = component->GetParentUID(); return (parentUID.empty() ? 0 : GetPhysicalComponent(parentUID)); } // Returns the root component of the geometric topology. CTiglAbstractPhysicalComponent* CTiglUIDManager::GetRootComponent(void) { Update(); return rootComponent; } // Returns the root component of the geometric topology. void CTiglUIDManager::FindRootComponent(void) { rootComponent = 0; UIDStoreContainerType::iterator pIter; int parentCnt = 0; for (pIter = physicalShapes.begin(); pIter != physicalShapes.end(); ++pIter) { CTiglAbstractPhysicalComponent* component = pIter->second; if (component->GetParentUID().empty()) { if (parentCnt != 0) { throw CTiglError("Error: More than one root component found in CTiglUIDManager::FindRootComponent", TIGL_ERROR); } parentCnt++; rootComponent = component; } } if (parentCnt == 0) { throw CTiglError("Error: No root component found in CTiglUIDManager::FindRootComponent", TIGL_ERROR); } } // Builds the parent child relationships. void CTiglUIDManager::BuildParentChildTree(void) { UIDStoreContainerType::iterator pIter; for (pIter = physicalShapes.begin(); pIter != physicalShapes.end(); ++pIter) { CTiglAbstractPhysicalComponent* component = pIter->second; if (!component->GetParentUID().empty()) { CTiglAbstractPhysicalComponent* parent = GetPhysicalComponent(component->GetParentUID()); parent->AddChild(component); } } } const ShapeContainerType& CTiglUIDManager::GetShapeContainer() { return allShapes; } } // end namespace tigl <commit_msg>Better error message in CTiglUIDManager<commit_after>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2010-08-13 Markus Litz <[email protected]> * Changed: $Id$ * * Version: $Revision$ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * @brief Implementation of the TIGL UID manager. */ #include "CTiglUIDManager.h" #include "CTiglError.h" namespace tigl { // Constructor CTiglUIDManager::CTiglUIDManager(void) : invalidated(true), rootComponent(0) { } // Destructor CTiglUIDManager::~CTiglUIDManager(void) { Clear(); } // Update internal UID manager data. void CTiglUIDManager::Update(void) { if (!invalidated) { return; } FindRootComponent(); BuildParentChildTree(); invalidated = false; } // Function to add a UID and a geometric component to the uid store. void CTiglUIDManager::AddUID(const std::string& uid, ITiglGeometricComponent* componentPtr) { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::AddUID", TIGL_XML_ERROR); } if (HasUID(uid)) { throw CTiglError(("UID " + uid + " already exist in CTiglUIDManager::AddUID").c_str(), TIGL_XML_ERROR); } if (componentPtr == 0) { throw CTiglError("Null pointer for component in CTiglUIDManager::AddUID", TIGL_NULL_POINTER); } CTiglAbstractPhysicalComponent* tmp = dynamic_cast<CTiglAbstractPhysicalComponent*>(componentPtr); if (tmp && (componentPtr->GetComponentType() | TIGL_COMPONENT_PHYSICAL) ) { physicalShapes[uid] = tmp; } allShapes[uid] = componentPtr; invalidated = true; } // Checks if a UID already exists. bool CTiglUIDManager::HasUID(const std::string& uid) const { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::HasUID", TIGL_XML_ERROR); } return (allShapes.find(uid) != allShapes.end()); } // Returns a pointer to the geometric component for the given unique id. ITiglGeometricComponent* CTiglUIDManager::GetComponent(const std::string& uid) { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::GetComponent", TIGL_UID_ERROR); } if (!HasUID(uid)) { std::stringstream stream; stream << "UID " << uid << " not found in CTiglUIDManager::GetComponent"; throw CTiglError(stream.str(), TIGL_UID_ERROR); } return allShapes[uid]; } // Returns a pointer to the geometric component for the given unique id. CTiglAbstractPhysicalComponent* CTiglUIDManager::GetPhysicalComponent(const std::string& uid) { if (uid.empty()) { throw CTiglError("Empty UID in CTiglUIDManager::GetComponent", TIGL_XML_ERROR); } if (physicalShapes.find(uid) == physicalShapes.end()) { throw CTiglError("UID not found in CTiglUIDManager::GetComponent", TIGL_XML_ERROR); } return physicalShapes[uid]; } // Clears the uid store void CTiglUIDManager::Clear(void) { physicalShapes.clear(); rootComponent = 0; invalidated = true; } // Returns the parent component for a component or a null pointer // if there is no parent. CTiglAbstractPhysicalComponent* CTiglUIDManager::GetParentComponent(const std::string& uid) { CTiglAbstractPhysicalComponent* component = GetPhysicalComponent(uid); std::string parentUID = component->GetParentUID(); return (parentUID.empty() ? 0 : GetPhysicalComponent(parentUID)); } // Returns the root component of the geometric topology. CTiglAbstractPhysicalComponent* CTiglUIDManager::GetRootComponent(void) { Update(); return rootComponent; } // Returns the root component of the geometric topology. void CTiglUIDManager::FindRootComponent(void) { rootComponent = 0; UIDStoreContainerType::iterator pIter; int parentCnt = 0; for (pIter = physicalShapes.begin(); pIter != physicalShapes.end(); ++pIter) { CTiglAbstractPhysicalComponent* component = pIter->second; if (component->GetParentUID().empty()) { if (parentCnt != 0) { throw CTiglError("Error: More than one root component found in CTiglUIDManager::FindRootComponent", TIGL_ERROR); } parentCnt++; rootComponent = component; } } if (parentCnt == 0) { throw CTiglError("Error: No root component found in CTiglUIDManager::FindRootComponent", TIGL_ERROR); } } // Builds the parent child relationships. void CTiglUIDManager::BuildParentChildTree(void) { UIDStoreContainerType::iterator pIter; for (pIter = physicalShapes.begin(); pIter != physicalShapes.end(); ++pIter) { CTiglAbstractPhysicalComponent* component = pIter->second; if (!component->GetParentUID().empty()) { CTiglAbstractPhysicalComponent* parent = GetPhysicalComponent(component->GetParentUID()); parent->AddChild(component); } } } const ShapeContainerType& CTiglUIDManager::GetShapeContainer() { return allShapes; } } // end namespace tigl <|endoftext|>
<commit_before>#include "cantera/oneD/refine.h" #include "cantera/oneD/Domain1D.h" #include <algorithm> #include <limits> using namespace std; namespace Cantera { static void r_drawline() { string s(78,'#'); s += '\n'; writelog(s.c_str()); } Refiner::Refiner(Domain1D& domain) : m_ratio(10.0), m_slope(0.8), m_curve(0.8), m_prune(-0.001), m_min_range(0.01), m_domain(&domain), m_npmax(3000), m_gridmin(5e-6) { m_nv = m_domain->nComponents(); m_active.resize(m_nv, true); m_thresh = std::sqrt(std::numeric_limits<double>::epsilon()); } int Refiner::analyze(size_t n, const doublereal* z, const doublereal* x) { if (n >= m_npmax) { writelog("max number of grid points reached ("+int2str(m_npmax)+".\n"); return -2; } if (m_domain->nPoints() <= 1) { return 0; } m_loc.clear(); m_c.clear(); m_keep.clear(); m_keep[0] = 1; m_keep[n-1] = 1; m_nv = m_domain->nComponents(); // check consistency if (n != m_domain->nPoints()) { throw CanteraError("analyze","inconsistent"); } // find locations where cell size ratio is too large. vector_fp v(n), s(n-1); vector_fp dz(n-1); for (size_t j = 0; j < n-1; j++) { dz[j] = z[j+1] - z[j]; } for (size_t i = 0; i < m_nv; i++) { if (m_active[i]) { string name = m_domain->componentName(i); // get component i at all points for (size_t j = 0; j < n; j++) { v[j] = value(x, i, j); } // slope of component i for (size_t j = 0; j < n-1; j++) { s[j] = (value(x, i, j+1) - value(x, i, j))/(z[j+1] - z[j]); } // find the range of values and slopes doublereal vmin = *min_element(v.begin(), v.end()); doublereal vmax = *max_element(v.begin(), v.end()); doublereal smin = *min_element(s.begin(), s.end()); doublereal smax = *max_element(s.begin(), s.end()); // max absolute values of v and s doublereal aa = std::max(fabs(vmax), fabs(vmin)); doublereal ss = std::max(fabs(smax), fabs(smin)); // refine based on component i only if the range of v is // greater than a fraction 'min_range' of max |v|. This // eliminates components that consist of small fluctuations // on a constant background. if ((vmax - vmin) > m_min_range*aa) { // maximum allowable difference in value between adjacent // points. doublereal dmax = m_slope*(vmax - vmin) + m_thresh; for (size_t j = 0; j < n-1; j++) { doublereal r = fabs(v[j+1] - v[j])/dmax; if (r > 1.0 && dz[j] >= 2 * m_gridmin) { m_loc[j] = 1; m_c[name] = 1; } if (r >= m_prune) { m_keep[j] = 1; m_keep[j+1] = 1; } else if (m_keep[j] == 0) { m_keep[j] = -1; } } } // refine based on the slope of component i only if the // range of s is greater than a fraction 'min_range' of max // |s|. This eliminates components that consist of small // fluctuations on a constant slope background. if ((smax - smin) > m_min_range*ss) { // maximum allowable difference in slope between // adjacent points. doublereal dmax = m_curve*(smax - smin); for (size_t j = 0; j < n-2; j++) { doublereal r = fabs(s[j+1] - s[j]) / (dmax + m_thresh/dz[j]); if (r > 1.0 && dz[j] >= 2 * m_gridmin && dz[j+1] >= 2 * m_gridmin) { m_c[name] = 1; m_loc[j] = 1; m_loc[j+1] = 1; } if (r >= m_prune) { m_keep[j+1] = 1; } else if (m_keep[j+1] == 0) { m_keep[j+1] = -1; } } } } } for (size_t j = 1; j < n-1; j++) { if (dz[j] > m_ratio*dz[j-1]) { m_loc[j] = 1; m_c["point "+int2str(j)] = 1; } if (dz[j] < dz[j-1]/m_ratio) { m_loc[j-1] = 1; m_c["point "+int2str(j-1)] = 1; } if (j > 1 && z[j+1]-z[j] > m_ratio * dz[j-2]) { m_keep[j] = 1; } if (j < n-2 && z[j+1]-z[j] > m_ratio * dz[j+1]) { m_keep[j] = 1; } // Keep the point where the temperature is fixed if (z[j] == m_domain->m_zfixed) { m_keep[j] = 1; } } // Don't allow pruning to remove multiple adjacent grid points // in a single pass. for (size_t j = 2; j < n-1; j++) { if (m_keep[j] == -1 && m_keep[j-1] == -1) { m_keep[j] = 1; } } return int(m_loc.size()); } double Refiner::value(const double* x, size_t i, size_t j) { return x[m_domain->index(i,j)]; } void Refiner::show() { if (!m_loc.empty()) { r_drawline(); writelog(string("Refining grid in ") + m_domain->id()+".\n" +" New points inserted after grid points "); map<size_t, int>::const_iterator b = m_loc.begin(); for (; b != m_loc.end(); ++b) { writelog(int2str(b->first)+" "); } writelog("\n"); writelog(" to resolve "); map<string, int>::const_iterator bb = m_c.begin(); for (; bb != m_c.end(); ++bb) { writelog(string(bb->first)+" "); } writelog("\n"); r_drawline(); } else if (m_domain->nPoints() > 1) { writelog("no new points needed in "+m_domain->id()+"\n"); } } int Refiner::getNewGrid(int n, const doublereal* z, int nn, doublereal* zn) { int nnew = static_cast<int>(m_loc.size()); if (nnew + n > nn) { throw CanteraError("Refine::getNewGrid", "array size too small."); } if (m_loc.empty()) { copy(z, z + n, zn); return 0; } int jn = 0; for (int j = 0; j < n - 1; j++) { zn[jn] = z[j]; jn++; if (m_loc.count(j)) { zn[jn] = 0.5*(z[j] + z[j+1]); jn++; } } zn[jn] = z[n-1]; return 0; } } <commit_msg>[1D] Fixed infinite loops in grid refinement / pruning<commit_after>#include "cantera/oneD/refine.h" #include "cantera/oneD/Domain1D.h" #include <algorithm> #include <limits> using namespace std; namespace Cantera { static void r_drawline() { string s(78,'#'); s += '\n'; writelog(s.c_str()); } Refiner::Refiner(Domain1D& domain) : m_ratio(10.0), m_slope(0.8), m_curve(0.8), m_prune(-0.001), m_min_range(0.01), m_domain(&domain), m_npmax(3000), m_gridmin(5e-6) { m_nv = m_domain->nComponents(); m_active.resize(m_nv, true); m_thresh = std::sqrt(std::numeric_limits<double>::epsilon()); } int Refiner::analyze(size_t n, const doublereal* z, const doublereal* x) { if (n >= m_npmax) { writelog("max number of grid points reached ("+int2str(m_npmax)+".\n"); return -2; } if (m_domain->nPoints() <= 1) { return 0; } m_loc.clear(); m_c.clear(); m_keep.clear(); m_keep[0] = 1; m_keep[n-1] = 1; m_nv = m_domain->nComponents(); // check consistency if (n != m_domain->nPoints()) { throw CanteraError("analyze","inconsistent"); } // find locations where cell size ratio is too large. vector_fp v(n), s(n-1); vector_fp dz(n-1); for (size_t j = 0; j < n-1; j++) { dz[j] = z[j+1] - z[j]; } for (size_t i = 0; i < m_nv; i++) { if (m_active[i]) { string name = m_domain->componentName(i); // get component i at all points for (size_t j = 0; j < n; j++) { v[j] = value(x, i, j); } // slope of component i for (size_t j = 0; j < n-1; j++) { s[j] = (value(x, i, j+1) - value(x, i, j))/(z[j+1] - z[j]); } // find the range of values and slopes doublereal vmin = *min_element(v.begin(), v.end()); doublereal vmax = *max_element(v.begin(), v.end()); doublereal smin = *min_element(s.begin(), s.end()); doublereal smax = *max_element(s.begin(), s.end()); // max absolute values of v and s doublereal aa = std::max(fabs(vmax), fabs(vmin)); doublereal ss = std::max(fabs(smax), fabs(smin)); // refine based on component i only if the range of v is // greater than a fraction 'min_range' of max |v|. This // eliminates components that consist of small fluctuations // on a constant background. if ((vmax - vmin) > m_min_range*aa) { // maximum allowable difference in value between adjacent // points. doublereal dmax = m_slope*(vmax - vmin) + m_thresh; for (size_t j = 0; j < n-1; j++) { doublereal r = fabs(v[j+1] - v[j])/dmax; if (r > 1.0 && dz[j] >= 2 * m_gridmin) { m_loc[j] = 1; m_c[name] = 1; } if (r >= m_prune) { m_keep[j] = 1; m_keep[j+1] = 1; } else if (m_keep[j] == 0) { m_keep[j] = -1; } } } // refine based on the slope of component i only if the // range of s is greater than a fraction 'min_range' of max // |s|. This eliminates components that consist of small // fluctuations on a constant slope background. if ((smax - smin) > m_min_range*ss) { // maximum allowable difference in slope between // adjacent points. doublereal dmax = m_curve*(smax - smin); for (size_t j = 0; j < n-2; j++) { doublereal r = fabs(s[j+1] - s[j]) / (dmax + m_thresh/dz[j]); if (r > 1.0 && dz[j] >= 2 * m_gridmin && dz[j+1] >= 2 * m_gridmin) { m_c[name] = 1; m_loc[j] = 1; m_loc[j+1] = 1; } if (r >= m_prune) { m_keep[j+1] = 1; } else if (m_keep[j+1] == 0) { m_keep[j+1] = -1; } } } } } // Refine based on properties of the grid itself for (size_t j = 1; j < n-1; j++) { // Add a new point if the ratio with left interval is too large if (dz[j] > m_ratio*dz[j-1]) { m_loc[j] = 1; m_c["point "+int2str(j)] = 1; m_keep[j-1] = 1; m_keep[j] = 1; m_keep[j+1] = 1; m_keep[j+2] = 1; } // Add a point if the ratio with right interval is too large if (dz[j] < dz[j-1]/m_ratio) { m_loc[j-1] = 1; m_c["point "+int2str(j-1)] = 1; m_keep[j-2] = 1; m_keep[j-1] = 1; m_keep[j] = 1; m_keep[j+1] = 1; } // Keep the point if removing would make the ratio with the left // interval too large. if (j > 1 && z[j+1]-z[j-1] > m_ratio * dz[j-2]) { m_keep[j] = 1; } // Keep the point if removing would make the ratio with the right // interval too large. if (j < n-2 && z[j+1]-z[j-1] > m_ratio * dz[j+1]) { m_keep[j] = 1; } // Keep the point where the temperature is fixed if (z[j] == m_domain->m_zfixed) { m_keep[j] = 1; } } // Don't allow pruning to remove multiple adjacent grid points // in a single pass. for (size_t j = 2; j < n-1; j++) { if (m_keep[j] == -1 && m_keep[j-1] == -1) { m_keep[j] = 1; } } return int(m_loc.size()); } double Refiner::value(const double* x, size_t i, size_t j) { return x[m_domain->index(i,j)]; } void Refiner::show() { if (!m_loc.empty()) { r_drawline(); writelog(string("Refining grid in ") + m_domain->id()+".\n" +" New points inserted after grid points "); map<size_t, int>::const_iterator b = m_loc.begin(); for (; b != m_loc.end(); ++b) { writelog(int2str(b->first)+" "); } writelog("\n"); writelog(" to resolve "); map<string, int>::const_iterator bb = m_c.begin(); for (; bb != m_c.end(); ++bb) { writelog(string(bb->first)+" "); } writelog("\n"); r_drawline(); } else if (m_domain->nPoints() > 1) { writelog("no new points needed in "+m_domain->id()+"\n"); } } int Refiner::getNewGrid(int n, const doublereal* z, int nn, doublereal* zn) { int nnew = static_cast<int>(m_loc.size()); if (nnew + n > nn) { throw CanteraError("Refine::getNewGrid", "array size too small."); } if (m_loc.empty()) { copy(z, z + n, zn); return 0; } int jn = 0; for (int j = 0; j < n - 1; j++) { zn[jn] = z[j]; jn++; if (m_loc.count(j)) { zn[jn] = 0.5*(z[j] + z[j+1]); jn++; } } zn[jn] = z[n-1]; return 0; } } <|endoftext|>
<commit_before>#include "elm/layers/mlp.h" #include "elm/core/boost/translators/transl_str_cvtermcriteria.h" #include "elm/core/boost/translators/transl_str_veci.h" #include "elm/core/layerconfig.h" #include "elm/core/signal.h" #include "elm/ts/layerattr_.h" using namespace std; using namespace cv; using namespace elm; const string MLP::PARAM_ARCH; const string MLP::PARAM_TERM_CRITERIA; const string MLP::PARAM_TRAIN_METHOD; const string MLP::PARAM_BP_DW_SCALE; const string MLP::PARAM_BP_MOMENT_SCALE; #include <boost/assign/list_of.hpp> template <> elm::MapIONames LayerAttr_<MLP>::io_pairs = boost::assign::map_list_of ELM_ADD_INPUT_PAIR(detail::BASE_SINGLE_INPUT_FEATURE_LAYER__KEY_INPUT_STIMULUS) ELM_ADD_OUTPUT_PAIR(detail::BASE_MATOUTPUT_LAYER__KEY_OUTPUT_RESPONSE) ; MLP::~MLP() { } MLP::MLP() : base_SupervisedBatch() { Clear(); } MLP::MLP(const LayerConfig &cfg) : base_SupervisedBatch(cfg) { Reset(cfg); } void MLP::Clear() { mlp_.clear(); } void MLP::Reset(const LayerConfig &config) { PTree p = config.Params(); VecI arch = p.get<VecI >(PARAM_ARCH); const int NB_LAYERS = static_cast<int>(arch.size()); ELM_THROW_BAD_DIMS_IF(NB_LAYERS < 2, "Need at least 2 layers for mlp."); Mat1i layers(arch); layers = layers.reshape(1, NB_LAYERS); // resize to column matrix, row per layer mlp_.create(layers); Reconfigure(config); } void MLP::Reconfigure(const LayerConfig &config) { PTree p = config.Params(); params_.train_method = p.get<int>(PARAM_TRAIN_METHOD, CvANN_MLP_TrainParams::BACKPROP); params_.bp_dw_scale = p.get<float>(PARAM_BP_DW_SCALE, 0.05f); params_.bp_moment_scale = p.get<float>(PARAM_BP_MOMENT_SCALE, 0.05f); params_.term_crit = p.get<CvTermCriteria>(PARAM_TERM_CRITERIA); } void MLP::Activate(const Signal &signal) { Mat1f sample = signal.MostRecentMat1f(name_input_); mlp_.predict(sample, m_); } void MLP::Learn(const Mat1f &features, const Mat1f &labels) { mlp_.train(features, labels, Mat(), Mat(), params_); } <commit_msg>add missing strings<commit_after>#include "elm/layers/mlp.h" #include "elm/core/boost/translators/transl_str_cvtermcriteria.h" #include "elm/core/boost/translators/transl_str_veci.h" #include "elm/core/layerconfig.h" #include "elm/core/signal.h" #include "elm/ts/layerattr_.h" using namespace std; using namespace cv; using namespace elm; const string MLP::PARAM_ARCH = "arch"; const string MLP::PARAM_TERM_CRITERIA = "term_crit"; const string MLP::PARAM_TRAIN_METHOD = "train_method"; const string MLP::PARAM_BP_DW_SCALE = "bp_dw_scale"; const string MLP::PARAM_BP_MOMENT_SCALE = "bp_moment_scale"; #include <boost/assign/list_of.hpp> template <> elm::MapIONames LayerAttr_<MLP>::io_pairs = boost::assign::map_list_of ELM_ADD_INPUT_PAIR(detail::BASE_SINGLE_INPUT_FEATURE_LAYER__KEY_INPUT_STIMULUS) ELM_ADD_OUTPUT_PAIR(detail::BASE_MATOUTPUT_LAYER__KEY_OUTPUT_RESPONSE) ; MLP::~MLP() { } MLP::MLP() : base_SupervisedBatch() { Clear(); } MLP::MLP(const LayerConfig &cfg) : base_SupervisedBatch(cfg) { Reset(cfg); } void MLP::Clear() { mlp_.clear(); } void MLP::Reset(const LayerConfig &config) { PTree p = config.Params(); VecI arch = p.get<VecI >(PARAM_ARCH); const int NB_LAYERS = static_cast<int>(arch.size()); ELM_THROW_BAD_DIMS_IF(NB_LAYERS < 2, "Need at least 2 layers for mlp."); Mat1i layers(arch); layers = layers.reshape(1, NB_LAYERS); // resize to column matrix, row per layer mlp_.create(layers); Reconfigure(config); } void MLP::Reconfigure(const LayerConfig &config) { PTree p = config.Params(); params_.train_method = p.get<int>(PARAM_TRAIN_METHOD, CvANN_MLP_TrainParams::BACKPROP); params_.bp_dw_scale = p.get<float>(PARAM_BP_DW_SCALE, 0.05f); params_.bp_moment_scale = p.get<float>(PARAM_BP_MOMENT_SCALE, 0.05f); params_.term_crit = p.get<CvTermCriteria>(PARAM_TERM_CRITERIA); } void MLP::Activate(const Signal &signal) { Mat1f sample = signal.MostRecentMat1f(name_input_); mlp_.predict(sample, m_); } void MLP::Learn(const Mat1f &features, const Mat1f &labels) { mlp_.train(features, labels, Mat(), Mat(), params_); } <|endoftext|>
<commit_before>#ifndef OPERATOR_MAP_HPP #define OPERATOR_MAP_HPP #include <string> #include <vector> #include <unordered_map> #include <functional> #include "util.hpp" #include "object.hpp" #include "operator.hpp" typedef std::vector<std::string> OperandTypeList; // The types of the operands typedef std::vector<Object::Link> OperandList; // The list of actual operands typedef std::function<Object::Link(OperandList)> OperatorFunction; // The code that runs for a specific operand list typedef std::unordered_map<OperandTypeList, OperatorFunction, VectorHash<std::string>> Operations; // Maps specific operand types to their respective code /* Dereference all PtrUtil<Reference> in the operand list, by replacing them with the value they reference. Use if the operator does not mutate the referenced thing. */ void dereferenceAll(OperandList& list) { std::for_each(ALL(list), [](Object::Link& element) { if (element->getTypeName() == "Reference") { element = PtrUtil<Reference>::dynPtrCast(element)->getValue(); } }); } #define OPERATION [](OperandList operands) -> Object::Link #define CAST(what, type) PtrUtil<type>::dynPtrCast(what) /* Example result for integer addition: {{"Integer", "Integer"}, OPERATION { return PtrUtil<Integer>::make(CAST(operands[0], Integer)->getValue() + CAST(operands[1], Integer)->getValue()); }} */ #define BINARY_ARITHMETIC_OP(type1, type2, resultType, op) \ {{#type1, #type2}, OPERATION {\ dereferenceAll(operands);\ return PtrUtil<resultType>::make(CAST(operands[0], type1)->getValue() op CAST(operands[1], type2)->getValue());\ }} #define BINARY_ARITHMETIC_SET(op) \ BINARY_ARITHMETIC_OP(Integer, Integer, Integer, op),\ BINARY_ARITHMETIC_OP(Integer, Float, Float, op),\ BINARY_ARITHMETIC_OP(Float, Integer, Float, op),\ BINARY_ARITHMETIC_OP(Float, Float, Float, op) // Maps an operator name to the operations that use it std::unordered_map<std::string, Operations> operatorMap { {"Add", { BINARY_ARITHMETIC_SET(+), }}, {"Substract", { BINARY_ARITHMETIC_SET(-), }}, {"Multiply", { BINARY_ARITHMETIC_SET(*), }}, {"Divide", { BINARY_ARITHMETIC_SET(/), }} }; #undef BINARY_ARITHMETIC_SET #undef BINARY_ARITHMETIC_OP #undef CAST #undef OPERATION OperandTypeList typeListFrom(OperandList list) { OperandTypeList t {}; t.resize(list.size()); std::transform(ALL(list), t.begin(), [](const Object::Link& operand) { return operand->getTypeName(); }); return t; } Object::Link executeOperator(OperatorName opName, OperandList list) { OperandTypeList tl = typeListFrom(list); OperatorFunction func = operatorMap[opName][tl]; return func(list); } #endif <commit_msg>Improved operator func resolution, added assignment<commit_after>#ifndef OPERATOR_MAP_HPP #define OPERATOR_MAP_HPP #include <string> #include <vector> #include <unordered_map> #include <functional> #include "util.hpp" #include "object.hpp" #include "operator.hpp" typedef std::vector<std::string> OperandTypeList; // The types of the operands typedef std::vector<Object::Link> OperandList; // The list of actual operands typedef std::function<Object::Link(OperandList)> OperatorFunction; // The code that runs for a specific operand list /* Maps specific operand types to their respective code. Using an empty vector as a key sets it as the default operation. */ typedef std::unordered_map<OperandTypeList, OperatorFunction, VectorHash<std::string>> Operations; /* Dereference all PtrUtil<Reference> in the operand list, by replacing them with the value they reference. Use if the operator does not mutate the referenced thing. */ void dereferenceAll(OperandList& list) { std::for_each(ALL(list), [](Object::Link& element) { if (element->getTypeName() == "Reference") { element = PtrUtil<Reference>::dynPtrCast(element)->getValue(); } }); } #define OPERATION [](OperandList operands) -> Object::Link #define CAST(what, type) PtrUtil<type>::dynPtrCast(what) /* Example result for integer addition: {{"Integer", "Integer"}, OPERATION { return PtrUtil<Integer>::make(CAST(operands[0], Integer)->getValue() + CAST(operands[1], Integer)->getValue()); }} */ #define BINARY_ARITHMETIC_OP(type1, type2, resultType, op) \ {{#type1, #type2}, OPERATION {\ dereferenceAll(operands);\ return PtrUtil<resultType>::make(CAST(operands[0], type1)->getValue() op CAST(operands[1], type2)->getValue());\ }} #define BINARY_ARITHMETIC_SET(op) \ BINARY_ARITHMETIC_OP(Integer, Integer, Integer, op),\ BINARY_ARITHMETIC_OP(Integer, Float, Float, op),\ BINARY_ARITHMETIC_OP(Float, Integer, Float, op),\ BINARY_ARITHMETIC_OP(Float, Float, Float, op) // Maps an operator name to the operations that use it std::unordered_map<std::string, Operations> operatorMap { {"Assignment", { {{}, OPERATION { PtrUtil<Reference>::Link ref = PtrUtil<Reference>::dynPtrCast(operands[0]); ref->setValue(operands[1]); return ref; }} }}, {"Add", { BINARY_ARITHMETIC_SET(+), }}, {"Substract", { BINARY_ARITHMETIC_SET(-), }}, {"Multiply", { BINARY_ARITHMETIC_SET(*), }}, {"Divide", { BINARY_ARITHMETIC_SET(/), }} }; #undef BINARY_ARITHMETIC_SET #undef BINARY_ARITHMETIC_OP #undef CAST #undef OPERATION OperandTypeList typeListFrom(OperandList list) { OperandTypeList t {}; t.resize(list.size()); std::transform(ALL(list), t.begin(), [](const Object::Link& operand) { return operand->getTypeName(); }); return t; } inline OperatorFunction tryFindingDefault(OperatorName opName, Operations ops) { try { return ops.at({}); } catch (std::out_of_range& oor) { throw InternalError("No specific or default operation found", { METADATA_PAIRS, {"operator name", opName} }); } } Object::Link executeOperator(OperatorName opName, OperandList list) { OperandTypeList tl = typeListFrom(list); Operations ops; OperatorFunction func; try { ops = operatorMap.at(opName); try { func = ops.at(tl); } catch (std::out_of_range& oor) { func = tryFindingDefault(opName, ops); } } catch (std::out_of_range& oor) { throw InternalError("Unknown operator", { METADATA_PAIRS, {"operator name", opName} }); } return func(list); } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2010 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "User.h" #include "Chan.h" #include "znc.h" using std::map; using std::pair; using std::multimap; class CLastSeenMod : public CGlobalModule { private: time_t GetTime(const CUser *pUser) { return GetNV(pUser->GetUserName()).ToULong(); } void SetTime(const CUser *pUser) { SetNV(pUser->GetUserName(), CString(time(NULL))); } typedef multimap<time_t, CUser*> MTimeMulti; typedef map<CString, CUser*> MUsers; public: GLOBALMODCONSTRUCTOR(CLastSeenMod) { } virtual ~CLastSeenMod() {} // IRC stuff: virtual void OnModCommand(const CString& sLine) { const CString sCommand = sLine.Token(0).AsLower(); if (!GetUser()->IsAdmin()) { PutModule("Access denied"); return; } if (sCommand == "show") { char buf[1024]; const MUsers& mUsers = CZNC::Get().GetUserMap(); MUsers::const_iterator it; CTable Table; Table.AddColumn("User"); Table.AddColumn("Last Seen"); for (it = mUsers.begin(); it != mUsers.end(); ++it) { CUser *pUser = it->second; time_t last = GetTime(pUser); Table.AddRow(); Table.SetCell("User", it->first); if (last == 0) Table.SetCell("Last Seen", "never"); else { strftime(buf, sizeof(buf), "%c", localtime(&last)); Table.SetCell("Last Seen", buf); } } PutModule(Table); } else { PutModule("This module only supports 'show'"); } } // Event stuff: virtual void OnClientLogin() { SetTime(GetUser()); } virtual void OnClientDisconnect() { SetTime(GetUser()); } virtual EModRet OnDeleteUser(CUser& User) { DelNV(User.GetUserName()); return CONTINUE; } // Web stuff: virtual bool WebRequiresLogin() { return true; } virtual bool WebRequiresAdmin() { return false; } virtual CString GetWebMenuTitle() { return "Last Seen"; } virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { if (sPageName.empty() || sPageName == "index") { MTimeMulti mmSorted; const MUsers& mUsers = CZNC::Get().GetUserMap(); for (MUsers::const_iterator uit = mUsers.begin(); uit != mUsers.end(); ++uit) { mmSorted.insert(pair<time_t, CUser*>(GetTime(uit->second), uit->second)); } char buf[1024] = {0}; for (MTimeMulti::const_iterator it = mmSorted.begin(); it != mmSorted.end(); ++it) { CUser *pUser = it->second; CTemplate& Row = Tmpl.AddRow("UserLoop"); Row["Username"] = pUser->GetUserName(); Row["IsSelf"] = CString(pUser == WebSock.GetSession()->GetUser()); if(it->first > 0) { strftime(buf, sizeof(buf), "%c", localtime(&it->first)); Row["LastSeen"] = buf; } Row["Info"] = CString(pUser->GetClients().size()) + " client(s)"; if(!pUser->GetCurrentServer()) { Row["Info"] += ", not connected to IRC"; } else { unsigned int uChans = 0; const vector<CChan*>& vChans = pUser->GetChans(); for (unsigned int a = 0; a < vChans.size(); a++) { if (vChans[a]->IsOn()) uChans++; } Row["Info"] += ", joined to " + CString(uChans) + " channel(s)"; } } return true; } return false; } }; GLOBALMODULEDEFS(CLastSeenMod, "Collects data about when a user last logged in") <commit_msg>Following revision 1880 the lastseen web page should only be visible for admin users. Thanks to psychon for noticing! :)<commit_after>/* * Copyright (C) 2004-2010 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "User.h" #include "Chan.h" #include "znc.h" using std::map; using std::pair; using std::multimap; class CLastSeenMod : public CGlobalModule { private: time_t GetTime(const CUser *pUser) { return GetNV(pUser->GetUserName()).ToULong(); } void SetTime(const CUser *pUser) { SetNV(pUser->GetUserName(), CString(time(NULL))); } typedef multimap<time_t, CUser*> MTimeMulti; typedef map<CString, CUser*> MUsers; public: GLOBALMODCONSTRUCTOR(CLastSeenMod) { } virtual ~CLastSeenMod() {} // IRC stuff: virtual void OnModCommand(const CString& sLine) { const CString sCommand = sLine.Token(0).AsLower(); if (!GetUser()->IsAdmin()) { PutModule("Access denied"); return; } if (sCommand == "show") { char buf[1024]; const MUsers& mUsers = CZNC::Get().GetUserMap(); MUsers::const_iterator it; CTable Table; Table.AddColumn("User"); Table.AddColumn("Last Seen"); for (it = mUsers.begin(); it != mUsers.end(); ++it) { CUser *pUser = it->second; time_t last = GetTime(pUser); Table.AddRow(); Table.SetCell("User", it->first); if (last == 0) Table.SetCell("Last Seen", "never"); else { strftime(buf, sizeof(buf), "%c", localtime(&last)); Table.SetCell("Last Seen", buf); } } PutModule(Table); } else { PutModule("This module only supports 'show'"); } } // Event stuff: virtual void OnClientLogin() { SetTime(GetUser()); } virtual void OnClientDisconnect() { SetTime(GetUser()); } virtual EModRet OnDeleteUser(CUser& User) { DelNV(User.GetUserName()); return CONTINUE; } // Web stuff: virtual bool WebRequiresLogin() { return true; } virtual bool WebRequiresAdmin() { return true; } virtual CString GetWebMenuTitle() { return "Last Seen"; } virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { if (sPageName.empty() || sPageName == "index") { MTimeMulti mmSorted; const MUsers& mUsers = CZNC::Get().GetUserMap(); for (MUsers::const_iterator uit = mUsers.begin(); uit != mUsers.end(); ++uit) { mmSorted.insert(pair<time_t, CUser*>(GetTime(uit->second), uit->second)); } char buf[1024] = {0}; for (MTimeMulti::const_iterator it = mmSorted.begin(); it != mmSorted.end(); ++it) { CUser *pUser = it->second; CTemplate& Row = Tmpl.AddRow("UserLoop"); Row["Username"] = pUser->GetUserName(); Row["IsSelf"] = CString(pUser == WebSock.GetSession()->GetUser()); if(it->first > 0) { strftime(buf, sizeof(buf), "%c", localtime(&it->first)); Row["LastSeen"] = buf; } Row["Info"] = CString(pUser->GetClients().size()) + " client(s)"; if(!pUser->GetCurrentServer()) { Row["Info"] += ", not connected to IRC"; } else { unsigned int uChans = 0; const vector<CChan*>& vChans = pUser->GetChans(); for (unsigned int a = 0; a < vChans.size(); ++a) { if (vChans[a]->IsOn()) ++uChans; } Row["Info"] += ", joined to " + CString(uChans) + " channel(s)"; } } return true; } return false; } }; GLOBALMODULEDEFS(CLastSeenMod, "Collects data about when a user last logged in") <|endoftext|>