text
stringlengths
54
60.6k
<commit_before>// Copyright 2014 Alessio Sclocco <[email protected]> // // 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 <cmath> #ifndef STATS_HPP #define STATS_HPP namespace isa { namespace utils { template< typename T > class Stats { public: Stats(); ~Stats(); inline void addElement(T element); inline void reset(); inline long long unsigned int getNrElements() const; inline double getAverage() const; inline double getVariance() const; inline double getStdDev() const; private: long long unsigned int nrElements; double average; double variance; }; // Implementations template< typename T > Stats< T >::Stats() : nrElements(0), average(0.0), variance(0.0) {} template< typename T > Stats< T >::~Stats() {} template< typename T > inline void Stats< T >::addElement(T element) { double oldAverage = average; nrElements++; if ( nrElements == 1 ) { average = static_cast< double >(element); return; } average = oldAverage + ((element - oldAverage) / nrElements); variance += (element - oldAverage) * (element - average); } template< typename T > inline void Stats< T >::reset() { nrElements = 0; average = 0.0; variance = 0.0; } template< typename T > inline long long unsigned int Stats< T >::getNrElements() const { return nrElements; } template< typename T > inline double Stats< T >::getAverage() const { return average; } template< typename T > inline double Stats< T >::getVariance() const { return variance; } template< typename T > inline double Stats< T >::getStdDev() const { return sqrt(variance / nrElements); } } // utils } // isa #endif <commit_msg>Terminology change, use mean instead of average. This breaks the API.<commit_after>// Copyright 2014 Alessio Sclocco <[email protected]> // // 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 <cmath> #ifndef STATS_HPP #define STATS_HPP namespace isa { namespace utils { template< typename T > class Stats { public: Stats(); ~Stats(); inline void addElement(T element); inline void reset(); inline long long unsigned int getNrElements() const; inline double getMean() const; inline double getVariance() const; inline double getStdDev() const; private: long long unsigned int nrElements; double mean; double variance; }; // Implementations template< typename T > Stats< T >::Stats() : nrElements(0), mean(0.0), variance(0.0) {} template< typename T > Stats< T >::~Stats() {} template< typename T > inline void Stats< T >::addElement(T element) { double oldMean = mean; nrElements++; if ( nrElements == 1 ) { mean = static_cast< double >(element); return; } mean = oldMean + ((element - oldMean) / nrElements); variance += (element - oldMean) * (element - mean); } template< typename T > inline void Stats< T >::reset() { nrElements = 0; mean = 0.0; variance = 0.0; } template< typename T > inline long long unsigned int Stats< T >::getNrElements() const { return nrElements; } template< typename T > inline double Stats< T >::getMean() const { return mean; } template< typename T > inline double Stats< T >::getVariance() const { return variance; } template< typename T > inline double Stats< T >::getStdDev() const { return sqrt(variance / nrElements); } } // utils } // isa #endif <|endoftext|>
<commit_before>/* -*-c++-*- citygml2vrml - Copyright (c) 2010 Joachim Pouderoux, BRGM * * This file is part of libcitygml library * http://code.google.com/p/libcitygml * * libcitygml 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. * * libcitygml 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. */ #include <iostream> #include <fstream> #include <time.h> #include <algorithm> #include <citygml/citygml.h> #include <citygml/citymodel.h> #include <citygml/cityobject.h> void analyzeObject( const citygml::CityObject*, unsigned int ); void usage() { std::cout << "Usage: citygmltest [-options...] <filename>" << std::endl; std::cout << " Options:" << std::endl; std::cout << " -log Print some information during parsing" << std::endl; std::cout << " -filter <mask> CityGML objects to parse (default:All)" << std::endl << " The mask is composed of:" << std::endl << " GenericCityObject, Building, Room," << std::endl << " BuildingInstallation, BuildingFurniture, IntBuildingInstallation, Door, Window, " << std::endl << " CityFurniture, Track, Road, Railway, Square, PlantCover," << std::endl << " SolitaryVegetationObject, WaterBody, TINRelief, LandUse," << std::endl << " Tunnel, Bridge, BridgeConstructionElement," << std::endl << " BridgeInstallation, BridgePart, All" << std::endl << " and seperators |,&,~." << std::endl << " Examples:" << std::endl << " \"All&~Track&~Room\" to parse everything but tracks & rooms" << std::endl << " \"Road&Railway\" to parse only roads & railways" << std::endl; std::cout << " -destSRS <srs> Destination SRS (default: no transform)" << std::endl; exit( EXIT_FAILURE ); } int main( int argc, char **argv ) { if ( argc < 2 ) usage(); int fargc = 1; bool log = false; citygml::ParserParams params; for ( int i = 1; i < argc; i++ ) { std::string param = std::string( argv[i] ); std::transform( param.begin(), param.end(), param.begin(), tolower ); if ( param == "-log" ) { log = true; fargc = i+1; } //if ( param == "-filter" ) { if ( i == argc - 1 ) usage(); params.objectsMask = argv[i+1]; i++; fargc = i+1; } if ( param == "-destsrs" ) { if ( i == argc - 1 ) usage(); params.destSRS = argv[i+1]; i++; fargc = i+1; } if ( param == "-srcsrs" ) { if ( i == argc - 1 ) usage(); params.srcSRS = argv[i+1]; i++; fargc = i+1; } } if ( argc - fargc < 1 ) usage(); std::cout << "Parsing CityGML file " << argv[fargc] << " using libcitygml v." << LIBCITYGML_VERSIONSTR << "..." << std::endl; time_t start; time( &start ); #if 0 std::ifstream file; file.open( argv[fargc], std::ifstream::in ); std::shared_ptr<const citygml::CityModel> city = citygml::load( file, params ); #else std::shared_ptr<const citygml::CityModel> city; try{ city = citygml::load( argv[fargc], params ); }catch(const std::runtime_error& e){ } #endif time_t end; time( &end ); if ( !city ) return EXIT_FAILURE; std::cout << "Done in " << difftime( end, start ) << " seconds." << std::endl; /* std::cout << "Analyzing the city objects..." << std::endl; citygml::CityObjectsMap::const_iterator it = cityObjectsMap.begin(); for ( ; it != cityObjectsMap.end(); ++it ) { const citygml::CityObjects& v = it->second; std::cout << ( log ? " Analyzing " : " Found " ) << v.size() << " " << citygml::getCityObjectsClassName( it->first ) << ( ( v.size() > 1 ) ? "s" : "" ) << "..." << std::endl; if ( log ) { for ( unsigned int i = 0; i < v.size(); i++ ) { std::cout << " + found object " << v[i]->getId(); if ( v[i]->getChildCount() > 0 ) std::cout << " with " << v[i]->getChildCount() << " children"; std::cout << " with " << v[i]->size() << " geometr" << ( ( v[i]->size() > 1 ) ? "ies" : "y" ); std::cout << std::endl; } } } */ if ( log ) { std::cout << std::endl << "Objects hierarchy:" << std::endl; // const citygml::ConstCityObjects& roots = city->getRootCityObjects(); // for ( unsigned int i = 0; i < roots.size(); i++ ) analyzeObject( roots[ i ], 2 ); } std::cout << "Done." << std::endl; return EXIT_SUCCESS; } void analyzeObject( const citygml::CityObject* object, unsigned int indent ) { // for ( unsigned int i = 0; i < indent; i++ ) std::cout << " "; // std::cout << "Object " << citygml::getCityObjectsClassName( object->getType() ) << ": " << object->getId() << std::endl; // for ( unsigned int i = 0; i < object->getChildCount(); i++ ) // analyzeObject( object->getChild(i), indent+1 ); } <commit_msg>Fix spelling errors.<commit_after>/* -*-c++-*- citygml2vrml - Copyright (c) 2010 Joachim Pouderoux, BRGM * * This file is part of libcitygml library * http://code.google.com/p/libcitygml * * libcitygml 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. * * libcitygml 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. */ #include <iostream> #include <fstream> #include <time.h> #include <algorithm> #include <citygml/citygml.h> #include <citygml/citymodel.h> #include <citygml/cityobject.h> void analyzeObject( const citygml::CityObject*, unsigned int ); void usage() { std::cout << "Usage: citygmltest [-options...] <filename>" << std::endl; std::cout << " Options:" << std::endl; std::cout << " -log Print some information during parsing" << std::endl; std::cout << " -filter <mask> CityGML objects to parse (default:All)" << std::endl << " The mask is composed of:" << std::endl << " GenericCityObject, Building, Room," << std::endl << " BuildingInstallation, BuildingFurniture, IntBuildingInstallation, Door, Window, " << std::endl << " CityFurniture, Track, Road, Railway, Square, PlantCover," << std::endl << " SolitaryVegetationObject, WaterBody, TINRelief, LandUse," << std::endl << " Tunnel, Bridge, BridgeConstructionElement," << std::endl << " BridgeInstallation, BridgePart, All" << std::endl << " and separators |,&,~." << std::endl << " Examples:" << std::endl << " \"All&~Track&~Room\" to parse everything but tracks & rooms" << std::endl << " \"Road&Railway\" to parse only roads & railways" << std::endl; std::cout << " -destSRS <srs> Destination SRS (default: no transform)" << std::endl; exit( EXIT_FAILURE ); } int main( int argc, char **argv ) { if ( argc < 2 ) usage(); int fargc = 1; bool log = false; citygml::ParserParams params; for ( int i = 1; i < argc; i++ ) { std::string param = std::string( argv[i] ); std::transform( param.begin(), param.end(), param.begin(), tolower ); if ( param == "-log" ) { log = true; fargc = i+1; } //if ( param == "-filter" ) { if ( i == argc - 1 ) usage(); params.objectsMask = argv[i+1]; i++; fargc = i+1; } if ( param == "-destsrs" ) { if ( i == argc - 1 ) usage(); params.destSRS = argv[i+1]; i++; fargc = i+1; } if ( param == "-srcsrs" ) { if ( i == argc - 1 ) usage(); params.srcSRS = argv[i+1]; i++; fargc = i+1; } } if ( argc - fargc < 1 ) usage(); std::cout << "Parsing CityGML file " << argv[fargc] << " using libcitygml v." << LIBCITYGML_VERSIONSTR << "..." << std::endl; time_t start; time( &start ); #if 0 std::ifstream file; file.open( argv[fargc], std::ifstream::in ); std::shared_ptr<const citygml::CityModel> city = citygml::load( file, params ); #else std::shared_ptr<const citygml::CityModel> city; try{ city = citygml::load( argv[fargc], params ); }catch(const std::runtime_error& e){ } #endif time_t end; time( &end ); if ( !city ) return EXIT_FAILURE; std::cout << "Done in " << difftime( end, start ) << " seconds." << std::endl; /* std::cout << "Analyzing the city objects..." << std::endl; citygml::CityObjectsMap::const_iterator it = cityObjectsMap.begin(); for ( ; it != cityObjectsMap.end(); ++it ) { const citygml::CityObjects& v = it->second; std::cout << ( log ? " Analyzing " : " Found " ) << v.size() << " " << citygml::getCityObjectsClassName( it->first ) << ( ( v.size() > 1 ) ? "s" : "" ) << "..." << std::endl; if ( log ) { for ( unsigned int i = 0; i < v.size(); i++ ) { std::cout << " + found object " << v[i]->getId(); if ( v[i]->getChildCount() > 0 ) std::cout << " with " << v[i]->getChildCount() << " children"; std::cout << " with " << v[i]->size() << " geometr" << ( ( v[i]->size() > 1 ) ? "ies" : "y" ); std::cout << std::endl; } } } */ if ( log ) { std::cout << std::endl << "Objects hierarchy:" << std::endl; // const citygml::ConstCityObjects& roots = city->getRootCityObjects(); // for ( unsigned int i = 0; i < roots.size(); i++ ) analyzeObject( roots[ i ], 2 ); } std::cout << "Done." << std::endl; return EXIT_SUCCESS; } void analyzeObject( const citygml::CityObject* object, unsigned int indent ) { // for ( unsigned int i = 0; i < indent; i++ ) std::cout << " "; // std::cout << "Object " << citygml::getCityObjectsClassName( object->getType() ) << ": " << object->getId() << std::endl; // for ( unsigned int i = 0; i < object->getChildCount(); i++ ) // analyzeObject( object->getChild(i), indent+1 ); } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief SEEDA03 client クラス @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "GR/core/ethernet_client.hpp" #include "sample.hpp" #include "main.hpp" namespace seeda { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief client クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class client { net::ethernet_client client_; enum class task { startup, connect, main_loop, disconnect, }; task task_; net::ip_address ip_; uint16_t port_; uint32_t delay_; uint32_t timeout_; time_t time_; typedef utils::basic_format<net::eth_chaout> format; public: //-----------------------------------------------------------------// /*! @brief コンストラクタ */ //-----------------------------------------------------------------// client(net::ethernet& eth) : client_(eth), task_(task::startup), #ifdef SEEDA ip_(192, 168, 1, 3), #else ip_(192, 168, 3, 7), #endif port_(3000), delay_(0), timeout_(0), time_(0) { } //-----------------------------------------------------------------// /*! @brief IP アドレスの取得 @return IP アドレス */ //-----------------------------------------------------------------// const net::ip_address& get_ip() const { return ip_; } //-----------------------------------------------------------------// /*! @brief IP アドレスの参照 @return IP アドレス */ //-----------------------------------------------------------------// net::ip_address& at_ip() { return ip_; } //-----------------------------------------------------------------// /*! @brief ポートの取得 @return ポート */ //-----------------------------------------------------------------// uint16_t get_port() const { return port_; } //-----------------------------------------------------------------// /*! @brief ポートの設定 @param[in] port ポート */ //-----------------------------------------------------------------// void set_port(uint16_t port) { port_ = port; } //-----------------------------------------------------------------// /*! @brief 接続開始 */ //-----------------------------------------------------------------// void start_connect() { task_ = task::connect; } //-----------------------------------------------------------------// /*! @brief 再接続 */ //-----------------------------------------------------------------// void restart() { task_ = task::disconnect; } //-----------------------------------------------------------------// /*! @brief サービス */ //-----------------------------------------------------------------// void service() { time_t t; switch(task_) { case task::startup: break; case task::connect: if(client_.connect(ip_, port_, TMO_NBLK)) { utils::format("Start SEEDA03 Client: %s port(%d), fd(%d)\n") % ip_.c_str() % port_ % client_.get_cepid(); timeout_ = 5 * 100; // 5 sec task_ = task::main_loop; time_ = get_time(); } break; case task::main_loop: if(!client_.connected()) { task_ = task::disconnect; break; } t = get_time(); if(time_ == t) break; time_ = t; { struct tm *m = localtime(&t); char data[1024]; uint32_t l = 0; l += (utils::format("%04d/%02d/%02d,%02d:%02d:%02d", &data[l], sizeof(data) - l) % static_cast<uint32_t>(m->tm_year + 1900) % static_cast<uint32_t>(m->tm_mon + 1) % static_cast<uint32_t>(m->tm_mday) % static_cast<uint32_t>(m->tm_hour) % static_cast<uint32_t>(m->tm_min) % static_cast<uint32_t>(m->tm_sec)).get_length(); for(int ch = 0; ch < 8; ++ch) { const auto& smp = get_sample(ch); data[l] = ','; ++l; l += smp.make_csv2(&data[l], sizeof(data) - l); } data[l] = '\n'; ++l; data[l] = 0; ++l; char tmp[2048]; utils::str::url_decode_to_str(data, tmp, sizeof(tmp)); auto fd = client_.get_cepid(); format("POST /api/?val=%s HTTP/1.1\n", fd) % tmp; format("Host: %d.%d.%d.%d\n", fd) % static_cast<int>(ip_[0]) % static_cast<int>(ip_[1]) % static_cast<int>(ip_[2]) % static_cast<int>(ip_[3]); format("Content-Type: application/x-www-form-urlencoded\n", fd); format("User-Agent: SEEDA03 Post Client\n", fd); format("Connection: close\n\n", fd); } task_ = task::disconnect; break; case task::disconnect: client_.stop(); utils::format("Client disconnected: %s\n") % ip_.c_str(); task_ = task::connect; break; } } }; } <commit_msg>update startup client port<commit_after>#pragma once //=====================================================================// /*! @file @brief SEEDA03 client クラス @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "GR/core/ethernet_client.hpp" #include "sample.hpp" #include "main.hpp" namespace seeda { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief client クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class client { static const uint16_t PORT = 3000; ///< クライアント・ポート net::ethernet_client client_; enum class task { startup, connect, main_loop, disconnect, }; task task_; net::ip_address ip_; uint16_t port_; uint32_t delay_; uint32_t timeout_; time_t time_; typedef utils::basic_format<net::eth_chaout> format; public: //-----------------------------------------------------------------// /*! @brief コンストラクタ */ //-----------------------------------------------------------------// client(net::ethernet& eth) : client_(eth, PORT), task_(task::startup), #ifdef SEEDA ip_(192, 168, 1, 3), #else ip_(192, 168, 3, 7), #endif port_(PORT), delay_(0), timeout_(0), time_(0) { } //-----------------------------------------------------------------// /*! @brief IP アドレスの取得 @return IP アドレス */ //-----------------------------------------------------------------// const net::ip_address& get_ip() const { return ip_; } //-----------------------------------------------------------------// /*! @brief IP アドレスの参照 @return IP アドレス */ //-----------------------------------------------------------------// net::ip_address& at_ip() { return ip_; } //-----------------------------------------------------------------// /*! @brief ポートの取得 @return ポート */ //-----------------------------------------------------------------// uint16_t get_port() const { return port_; } //-----------------------------------------------------------------// /*! @brief ポートの設定 @param[in] port ポート */ //-----------------------------------------------------------------// void set_port(uint16_t port) { port_ = port; } //-----------------------------------------------------------------// /*! @brief 接続開始 */ //-----------------------------------------------------------------// void start_connect() { task_ = task::connect; } //-----------------------------------------------------------------// /*! @brief 再接続 */ //-----------------------------------------------------------------// void restart() { task_ = task::disconnect; } //-----------------------------------------------------------------// /*! @brief サービス */ //-----------------------------------------------------------------// void service() { time_t t; switch(task_) { case task::startup: break; case task::connect: if(client_.connect(ip_, port_, TMO_NBLK)) { utils::format("Start SEEDA03 Client: %s port(%d), fd(%d)\n") % ip_.c_str() % port_ % client_.get_cepid(); timeout_ = 5 * 100; // 5 sec task_ = task::main_loop; time_ = get_time(); } break; case task::main_loop: if(!client_.connected()) { task_ = task::disconnect; break; } t = get_time(); if(time_ == t) break; time_ = t; { struct tm *m = localtime(&t); char data[1024]; uint32_t l = 0; l += (utils::format("%04d/%02d/%02d,%02d:%02d:%02d", &data[l], sizeof(data) - l) % static_cast<uint32_t>(m->tm_year + 1900) % static_cast<uint32_t>(m->tm_mon + 1) % static_cast<uint32_t>(m->tm_mday) % static_cast<uint32_t>(m->tm_hour) % static_cast<uint32_t>(m->tm_min) % static_cast<uint32_t>(m->tm_sec)).get_length(); for(int ch = 0; ch < 8; ++ch) { const auto& smp = get_sample(ch); data[l] = ','; ++l; l += smp.make_csv2(&data[l], sizeof(data) - l); } data[l] = '\n'; ++l; data[l] = 0; ++l; char tmp[2048]; utils::str::url_decode_to_str(data, tmp, sizeof(tmp)); auto fd = client_.get_cepid(); format("POST /api/?val=%s HTTP/1.1\n", fd) % tmp; format("Host: %d.%d.%d.%d\n", fd) % static_cast<int>(ip_[0]) % static_cast<int>(ip_[1]) % static_cast<int>(ip_[2]) % static_cast<int>(ip_[3]); format("Content-Type: application/x-www-form-urlencoded\n", fd); format("User-Agent: SEEDA03 Post Client\n", fd); format("Connection: close\n\n", fd); } task_ = task::disconnect; break; case task::disconnect: client_.stop(); utils::format("Client disconnected: %s\n") % ip_.c_str(); task_ = task::connect; break; } } }; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: label.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: os $ $Date: 2002-09-09 08:42:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _LABEL_HXX #define _LABEL_HXX #ifndef _SVSTDARR_HXX #define _SVSTDARR_STRINGSDTOR #define _SVSTDARR_USHORTS #include <svtools/svstdarr.hxx> #endif #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _LABELCFG_HXX #include <labelcfg.hxx> #endif class SwLabRec; class SwLabRecs; class SwLabItem; class SwLabPrtPage; class SwNewDBMgr; class Printer; class SwLabDlg : public SfxTabDialog { SwLabelConfig aLabelsCfg; SwNewDBMgr* pNewDBMgr; SwLabPrtPage* pPrtPage; SvUShorts aTypeIds; SvStringsDtor aMakes; SwLabRecs* pRecs; String aLstGroup; String sBusinessCardDlg; String sFormat; String sMedium; BOOL m_bLabel; void _ReplaceGroup( const String &rMake ); virtual void PageCreated( USHORT nId, SfxTabPage &rPage ); public: SwLabDlg( Window* pParent, const SfxItemSet& rSet, SwNewDBMgr* pNewDBMgr, BOOL bLabel); ~SwLabDlg(); void MakeConfigItem(SwLabItem& rItem) const; SwLabRec* GetRecord(const String &rRecName, BOOL bCont); void GetLabItem(SwLabItem &rItem); SwLabRecs &Recs() { return *pRecs; } const SwLabRecs &Recs() const { return *pRecs; } SvUShorts &TypeIds() { return aTypeIds; } const SvUShorts &TypeIds() const { return aTypeIds; } SvStringsDtor &Makes() { return aMakes; } const SvStringsDtor &Makes() const { return aMakes; } Printer *GetPrt(); inline void ReplaceGroup( const String &rMake ); void UpdateGroup( const String &rMake ) {_ReplaceGroup( rMake );} static void UpdateFieldInformation(::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& xModel, const SwLabItem& rItem); const String& GetBusinessCardStr() const {return sBusinessCardDlg;} SwLabelConfig& GetLabelsConfig() {return aLabelsCfg;} }; inline void SwLabDlg::ReplaceGroup( const String &rMake ) { if ( rMake != aLstGroup ) _ReplaceGroup( rMake ); } #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.4.1420); FILE MERGED 2005/09/05 13:45:19 rt 1.4.1420.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: label.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 09:23:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _LABEL_HXX #define _LABEL_HXX #ifndef _SVSTDARR_HXX #define _SVSTDARR_STRINGSDTOR #define _SVSTDARR_USHORTS #include <svtools/svstdarr.hxx> #endif #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _LABELCFG_HXX #include <labelcfg.hxx> #endif class SwLabRec; class SwLabRecs; class SwLabItem; class SwLabPrtPage; class SwNewDBMgr; class Printer; class SwLabDlg : public SfxTabDialog { SwLabelConfig aLabelsCfg; SwNewDBMgr* pNewDBMgr; SwLabPrtPage* pPrtPage; SvUShorts aTypeIds; SvStringsDtor aMakes; SwLabRecs* pRecs; String aLstGroup; String sBusinessCardDlg; String sFormat; String sMedium; BOOL m_bLabel; void _ReplaceGroup( const String &rMake ); virtual void PageCreated( USHORT nId, SfxTabPage &rPage ); public: SwLabDlg( Window* pParent, const SfxItemSet& rSet, SwNewDBMgr* pNewDBMgr, BOOL bLabel); ~SwLabDlg(); void MakeConfigItem(SwLabItem& rItem) const; SwLabRec* GetRecord(const String &rRecName, BOOL bCont); void GetLabItem(SwLabItem &rItem); SwLabRecs &Recs() { return *pRecs; } const SwLabRecs &Recs() const { return *pRecs; } SvUShorts &TypeIds() { return aTypeIds; } const SvUShorts &TypeIds() const { return aTypeIds; } SvStringsDtor &Makes() { return aMakes; } const SvStringsDtor &Makes() const { return aMakes; } Printer *GetPrt(); inline void ReplaceGroup( const String &rMake ); void UpdateGroup( const String &rMake ) {_ReplaceGroup( rMake );} static void UpdateFieldInformation(::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& xModel, const SwLabItem& rItem); const String& GetBusinessCardStr() const {return sBusinessCardDlg;} SwLabelConfig& GetLabelsConfig() {return aLabelsCfg;} }; inline void SwLabDlg::ReplaceGroup( const String &rMake ) { if ( rMake != aLstGroup ) _ReplaceGroup( rMake ); } #endif <|endoftext|>
<commit_before> #include "DuktapeObjectWrapper.h" #include <cppassist/logging/logging.h> #include <cppexpose/reflection/Object.h> #include "DuktapeScriptBackend.h" using namespace cppassist; namespace cppexpose { extern const char * s_duktapeFunctionPointerKey; extern const char * s_duktapeObjectPointerKey; extern const char * s_duktapePropertyNameKey; DuktapeObjectWrapper::DuktapeObjectWrapper(DuktapeScriptBackend * scriptBackend, Object * obj) : m_context(scriptBackend->m_context) , m_scriptBackend(scriptBackend) , m_obj(obj) , m_stashIndex(-1) { } DuktapeObjectWrapper::~DuktapeObjectWrapper() { } void DuktapeObjectWrapper::wrapObject() { // Create empty object on the stack duk_idx_t objIndex = duk_push_object(m_context); // Save object in stash m_stashIndex = m_scriptBackend->getNextStashIndex(); duk_push_global_stash(m_context); duk_push_int(m_context, m_stashIndex); duk_dup(m_context, -3); duk_put_prop(m_context, -3); duk_pop(m_context); // Save pointer to wrapped object in javascript object duk_push_pointer(m_context, static_cast<void *>(this)); duk_put_prop_string(m_context, -2, s_duktapeObjectPointerKey); // Register object properties for (unsigned int i=0; i<m_obj->numSubValues(); i++) { // Get property AbstractProperty * prop = m_obj->property(i); std::string propName = prop->name(); // Register property (ignore sub-objects, they are added later) if (!prop->isObject()) { // Key (for accessor) duk_push_string(m_context, propName.c_str()); // Getter function object duk_push_c_function(m_context, &DuktapeObjectWrapper::getPropertyValue, 0); duk_push_string(m_context, propName.c_str()); duk_put_prop_string(m_context, -2, s_duktapePropertyNameKey); // Setter function object duk_push_c_function(m_context, &DuktapeObjectWrapper::setPropertyValue, 1); duk_push_string(m_context, propName.c_str()); duk_put_prop_string(m_context, -2, s_duktapePropertyNameKey); // Define property with getter/setter duk_def_prop(m_context, objIndex, DUK_DEFPROP_HAVE_CONFIGURABLE | DUK_DEFPROP_CONFIGURABLE // configurable (can be deleted) | DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_ENUMERABLE // enumerable | DUK_DEFPROP_HAVE_GETTER | DUK_DEFPROP_HAVE_SETTER // use getter and setter functions ); // Add empty sub-object placeholder for value properties m_subObjects.push_back(nullptr); } } // Register object functions const std::vector<Method> & funcs = m_obj->functions(); for (std::vector<Method>::const_iterator it = funcs.begin(); it != funcs.end(); ++it) { const Method & method = *it; auto & func = static_cast<const Function &>(method); duk_push_c_function(m_context, callObjectFunction, DUK_VARARGS); duk_push_pointer(m_context, const_cast<Function *>(&func)); duk_put_prop_string(m_context, -2, s_duktapeFunctionPointerKey); duk_put_prop_string(m_context, objIndex, method.name().c_str()); } // Register sub-objects for (unsigned int i=0; i<m_obj->numSubValues(); i++) { // Get property AbstractProperty * prop = m_obj->property(i); std::string name = prop->name(); // Check if it is an object if (prop->isObject()) { // Wrap sub object auto subObj = static_cast<Object *>(prop); auto objWrapper = m_scriptBackend->getOrCreateObjectWrapper(subObj); objWrapper->pushToDukStack(); // Register sub-object in parent object duk_put_prop_string(m_context, objIndex, m_obj->name().c_str()); // Add wrapper to sub-object m_subObjects.push_back(objWrapper); } } // Register callbacks for script engine update m_afterAddConnection = m_obj->afterAdd.connect([this](size_t index, cppexpose::AbstractProperty * property) { // [TODO] Provide an UNUSED() macro in cppassist (void)(index); // Check if property is an object or a value property if (property->isObject()) { assert(m_subObjects.size() == index); // Get object Object * obj = static_cast<Object *>(property); // Get parent object from stash duk_push_global_stash(m_context); duk_get_prop_index(m_context, -1, m_stashIndex); const auto parentIndex = duk_get_top_index(m_context); // Wrap object const auto objWrapper = m_scriptBackend->getOrCreateObjectWrapper(obj); objWrapper->pushToDukStack(); // Register object in parent object duk_put_prop_string(m_context, parentIndex, obj->name().c_str()); // Clean up duk_pop(m_context); duk_pop(m_context); // Add wrapper to sub-object m_subObjects.push_back(objWrapper); } else { // Get property std::string propName = property->name(); // Add empty sub-object placeholder for value properties m_subObjects.push_back(nullptr); // Expose property to scripting duk_push_global_stash(m_context); duk_get_prop_index(m_context, -1, m_stashIndex); duk_push_string(m_context, propName.c_str()); duk_push_c_function(m_context, &DuktapeObjectWrapper::getPropertyValue, 0); duk_push_string(m_context, propName.c_str()); duk_put_prop_string(m_context, -2, s_duktapePropertyNameKey); duk_push_c_function(m_context, &DuktapeObjectWrapper::setPropertyValue, 1); duk_push_string(m_context, propName.c_str()); duk_put_prop_string(m_context, -2, s_duktapePropertyNameKey); duk_def_prop(m_context, -4, DUK_DEFPROP_HAVE_CONFIGURABLE | DUK_DEFPROP_CONFIGURABLE // configurable (can be deleted) | DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_ENUMERABLE // enumerable | DUK_DEFPROP_HAVE_GETTER | DUK_DEFPROP_HAVE_SETTER // use getter and setter functions ); duk_pop(m_context); duk_pop(m_context); } }); m_beforeRemoveConnection = m_obj->beforeRemove.connect([this](size_t index, cppexpose::AbstractProperty * property) { // Remove property duk_push_global_stash(m_context); duk_get_prop_index(m_context, -1, m_stashIndex); duk_del_prop_string(m_context, -1, property->name().c_str()); duk_pop(m_context); duk_pop(m_context); // Delete object wrapper auto it = m_subObjects.begin() + index; m_subObjects.erase(it); }); m_beforeDestroyConnection = m_obj->beforeDestroy.connect([this](cppexpose::AbstractProperty * property) { // [TODO] Provide an UNUSED() macro in cppassist assert(property == m_obj); (void)(property); // Get wrapper object duk_push_global_stash(m_context); duk_get_prop_index(m_context, -1, m_stashIndex); // Enumerate properties of wrapper object std::vector<std::string> keys; duk_enum(m_context, -1, DUK_ENUM_OWN_PROPERTIES_ONLY); while (duk_next(m_context, -1, 0)) { std::string key = duk_get_string(m_context, -1); keys.push_back(key); duk_pop(m_context); } duk_pop(m_context); // Clear wrapper object for (auto key : keys) { duk_del_prop_string(m_context, -1, key.c_str()); } // Release wrapper object duk_pop(m_context); duk_pop(m_context); }); } void DuktapeObjectWrapper::pushToDukStack() { // If object has not been wrapped before ... if (m_stashIndex == -1) { // Wrap object, leaves wrapper object on top of the stack wrapObject(); return; } // Push placeholder object duk_push_object(m_context); // Get object from stash duk_push_global_stash(m_context); duk_get_prop_index(m_context, -1, m_stashIndex); // Replace placeholder duk_replace(m_context, -3); // Pop global stash duk_pop(m_context); } duk_ret_t DuktapeObjectWrapper::getPropertyValue(duk_context * context) { // Get script backend auto scriptBackend = DuktapeScriptBackend::getScriptBackend(context); // Get object wrapper duk_push_this(context); duk_get_prop_string(context, -1, s_duktapeObjectPointerKey); auto objWrapper = static_cast<DuktapeObjectWrapper *>( duk_get_pointer(context, -1) ); duk_pop_2(context); // Check if object wrapper was found if (objWrapper) { // Get object Object * obj = objWrapper->m_obj; // Get property name duk_push_current_function(context); duk_get_prop_string(context, -1, s_duktapePropertyNameKey); std::string propName = duk_get_string(context, -1); duk_pop_2(context); // Get property AbstractProperty * property = obj->property(propName); if (property) { // Return property value Variant value = property->toVariant(); scriptBackend->pushToDukStack(value); } } // Return status // 1: return value at top // 0: return 'undefined' // < 0: return error (use DUK_RET_xxx constants) return 1; } duk_ret_t DuktapeObjectWrapper::setPropertyValue(duk_context * context) { // Get script backend auto scriptBackend = DuktapeScriptBackend::getScriptBackend(context); // Get value from stack Variant value = scriptBackend->fromDukStack(-1); duk_pop(context); // Get object wrapper duk_push_this(context); duk_get_prop_string(context, -1, s_duktapeObjectPointerKey); auto objWrapper = static_cast<DuktapeObjectWrapper *>( duk_get_pointer(context, -1) ); duk_pop_2(context); // Check if object wrapper was found if (objWrapper) { // Get object Object * obj = objWrapper->m_obj; // Get property name duk_push_current_function(context); duk_get_prop_string(context, -1, s_duktapePropertyNameKey); std::string propName = duk_get_string(context, -1); duk_pop_2(context); // Get property AbstractProperty * property = obj->property(propName); if (property) { // Set property value property->fromVariant(value); } } // Return status // 1: return value at top // 0: return 'undefined' // < 0: return error (use DUK_RET_xxx constants) return 0; } duk_ret_t DuktapeObjectWrapper::callObjectFunction(duk_context * context) { // Get script backend auto scriptBackend = DuktapeScriptBackend::getScriptBackend(context); // Determine number of arguments duk_idx_t nargs = duk_get_top(context); // Get function pointer duk_push_current_function(context); duk_get_prop_string(context, -1, s_duktapeFunctionPointerKey); Function * func = reinterpret_cast<Function *>( duk_get_pointer(context, -1) ); duk_pop_2(context); // Is function valid? if (func) { // Get all arguments from the stack and convert them into variants std::vector<Variant> arguments(nargs); for (int i = 0; i < nargs; ++i){ arguments[i] = scriptBackend->fromDukStack(0); duk_remove(context, 0); } // Call function Variant value = func->call(arguments); // Check return value if (!value.isNull()) { // Push return value to stack scriptBackend->pushToDukStack(value); return 1; } else { // No return value return 0; } } // No valid function found warning() << "Error: No valid function pointer found." << std::endl; return DUK_RET_ERROR; } } // namespace cppexpose <commit_msg>Fix subobject property name<commit_after> #include "DuktapeObjectWrapper.h" #include <cppassist/logging/logging.h> #include <cppexpose/reflection/Object.h> #include "DuktapeScriptBackend.h" using namespace cppassist; namespace cppexpose { extern const char * s_duktapeFunctionPointerKey; extern const char * s_duktapeObjectPointerKey; extern const char * s_duktapePropertyNameKey; DuktapeObjectWrapper::DuktapeObjectWrapper(DuktapeScriptBackend * scriptBackend, Object * obj) : m_context(scriptBackend->m_context) , m_scriptBackend(scriptBackend) , m_obj(obj) , m_stashIndex(-1) { } DuktapeObjectWrapper::~DuktapeObjectWrapper() { } void DuktapeObjectWrapper::wrapObject() { // Create empty object on the stack duk_idx_t objIndex = duk_push_object(m_context); // Save object in stash m_stashIndex = m_scriptBackend->getNextStashIndex(); duk_push_global_stash(m_context); duk_push_int(m_context, m_stashIndex); duk_dup(m_context, -3); duk_put_prop(m_context, -3); duk_pop(m_context); // Save pointer to wrapped object in javascript object duk_push_pointer(m_context, static_cast<void *>(this)); duk_put_prop_string(m_context, -2, s_duktapeObjectPointerKey); // Register object properties for (unsigned int i=0; i<m_obj->numSubValues(); i++) { // Get property AbstractProperty * prop = m_obj->property(i); std::string propName = prop->name(); // Register property (ignore sub-objects, they are added later) if (!prop->isObject()) { // Key (for accessor) duk_push_string(m_context, propName.c_str()); // Getter function object duk_push_c_function(m_context, &DuktapeObjectWrapper::getPropertyValue, 0); duk_push_string(m_context, propName.c_str()); duk_put_prop_string(m_context, -2, s_duktapePropertyNameKey); // Setter function object duk_push_c_function(m_context, &DuktapeObjectWrapper::setPropertyValue, 1); duk_push_string(m_context, propName.c_str()); duk_put_prop_string(m_context, -2, s_duktapePropertyNameKey); // Define property with getter/setter duk_def_prop(m_context, objIndex, DUK_DEFPROP_HAVE_CONFIGURABLE | DUK_DEFPROP_CONFIGURABLE // configurable (can be deleted) | DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_ENUMERABLE // enumerable | DUK_DEFPROP_HAVE_GETTER | DUK_DEFPROP_HAVE_SETTER // use getter and setter functions ); // Add empty sub-object placeholder for value properties m_subObjects.push_back(nullptr); } } // Register object functions const std::vector<Method> & funcs = m_obj->functions(); for (std::vector<Method>::const_iterator it = funcs.begin(); it != funcs.end(); ++it) { const Method & method = *it; auto & func = static_cast<const Function &>(method); duk_push_c_function(m_context, callObjectFunction, DUK_VARARGS); duk_push_pointer(m_context, const_cast<Function *>(&func)); duk_put_prop_string(m_context, -2, s_duktapeFunctionPointerKey); duk_put_prop_string(m_context, objIndex, method.name().c_str()); } // Register sub-objects for (unsigned int i=0; i<m_obj->numSubValues(); i++) { // Get property AbstractProperty * prop = m_obj->property(i); std::string name = prop->name(); // Check if it is an object if (prop->isObject()) { // Wrap sub object auto subObj = static_cast<Object *>(prop); auto objWrapper = m_scriptBackend->getOrCreateObjectWrapper(subObj); objWrapper->pushToDukStack(); // Register sub-object in parent object duk_put_prop_string(m_context, objIndex, subObj->name().c_str()); // Add wrapper to sub-object m_subObjects.push_back(objWrapper); } } // Register callbacks for script engine update m_afterAddConnection = m_obj->afterAdd.connect([this](size_t index, cppexpose::AbstractProperty * property) { // [TODO] Provide an UNUSED() macro in cppassist (void)(index); // Check if property is an object or a value property if (property->isObject()) { assert(m_subObjects.size() == index); // Get object Object * obj = static_cast<Object *>(property); // Get parent object from stash duk_push_global_stash(m_context); duk_get_prop_index(m_context, -1, m_stashIndex); const auto parentIndex = duk_get_top_index(m_context); // Wrap object const auto objWrapper = m_scriptBackend->getOrCreateObjectWrapper(obj); objWrapper->pushToDukStack(); // Register object in parent object duk_put_prop_string(m_context, parentIndex, obj->name().c_str()); // Clean up duk_pop(m_context); duk_pop(m_context); // Add wrapper to sub-object m_subObjects.push_back(objWrapper); } else { // Get property std::string propName = property->name(); // Add empty sub-object placeholder for value properties m_subObjects.push_back(nullptr); // Expose property to scripting duk_push_global_stash(m_context); duk_get_prop_index(m_context, -1, m_stashIndex); duk_push_string(m_context, propName.c_str()); duk_push_c_function(m_context, &DuktapeObjectWrapper::getPropertyValue, 0); duk_push_string(m_context, propName.c_str()); duk_put_prop_string(m_context, -2, s_duktapePropertyNameKey); duk_push_c_function(m_context, &DuktapeObjectWrapper::setPropertyValue, 1); duk_push_string(m_context, propName.c_str()); duk_put_prop_string(m_context, -2, s_duktapePropertyNameKey); duk_def_prop(m_context, -4, DUK_DEFPROP_HAVE_CONFIGURABLE | DUK_DEFPROP_CONFIGURABLE // configurable (can be deleted) | DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_ENUMERABLE // enumerable | DUK_DEFPROP_HAVE_GETTER | DUK_DEFPROP_HAVE_SETTER // use getter and setter functions ); duk_pop(m_context); duk_pop(m_context); } }); m_beforeRemoveConnection = m_obj->beforeRemove.connect([this](size_t index, cppexpose::AbstractProperty * property) { // Remove property duk_push_global_stash(m_context); duk_get_prop_index(m_context, -1, m_stashIndex); duk_del_prop_string(m_context, -1, property->name().c_str()); duk_pop(m_context); duk_pop(m_context); // Delete object wrapper auto it = m_subObjects.begin() + index; m_subObjects.erase(it); }); m_beforeDestroyConnection = m_obj->beforeDestroy.connect([this](cppexpose::AbstractProperty * property) { // [TODO] Provide an UNUSED() macro in cppassist assert(property == m_obj); (void)(property); // Get wrapper object duk_push_global_stash(m_context); duk_get_prop_index(m_context, -1, m_stashIndex); // Enumerate properties of wrapper object std::vector<std::string> keys; duk_enum(m_context, -1, DUK_ENUM_OWN_PROPERTIES_ONLY); while (duk_next(m_context, -1, 0)) { std::string key = duk_get_string(m_context, -1); keys.push_back(key); duk_pop(m_context); } duk_pop(m_context); // Clear wrapper object for (auto key : keys) { duk_del_prop_string(m_context, -1, key.c_str()); } // Release wrapper object duk_pop(m_context); duk_pop(m_context); }); } void DuktapeObjectWrapper::pushToDukStack() { // If object has not been wrapped before ... if (m_stashIndex == -1) { // Wrap object, leaves wrapper object on top of the stack wrapObject(); return; } // Push placeholder object duk_push_object(m_context); // Get object from stash duk_push_global_stash(m_context); duk_get_prop_index(m_context, -1, m_stashIndex); // Replace placeholder duk_replace(m_context, -3); // Pop global stash duk_pop(m_context); } duk_ret_t DuktapeObjectWrapper::getPropertyValue(duk_context * context) { // Get script backend auto scriptBackend = DuktapeScriptBackend::getScriptBackend(context); // Get object wrapper duk_push_this(context); duk_get_prop_string(context, -1, s_duktapeObjectPointerKey); auto objWrapper = static_cast<DuktapeObjectWrapper *>( duk_get_pointer(context, -1) ); duk_pop_2(context); // Check if object wrapper was found if (objWrapper) { // Get object Object * obj = objWrapper->m_obj; // Get property name duk_push_current_function(context); duk_get_prop_string(context, -1, s_duktapePropertyNameKey); std::string propName = duk_get_string(context, -1); duk_pop_2(context); // Get property AbstractProperty * property = obj->property(propName); if (property) { // Return property value Variant value = property->toVariant(); scriptBackend->pushToDukStack(value); } } // Return status // 1: return value at top // 0: return 'undefined' // < 0: return error (use DUK_RET_xxx constants) return 1; } duk_ret_t DuktapeObjectWrapper::setPropertyValue(duk_context * context) { // Get script backend auto scriptBackend = DuktapeScriptBackend::getScriptBackend(context); // Get value from stack Variant value = scriptBackend->fromDukStack(-1); duk_pop(context); // Get object wrapper duk_push_this(context); duk_get_prop_string(context, -1, s_duktapeObjectPointerKey); auto objWrapper = static_cast<DuktapeObjectWrapper *>( duk_get_pointer(context, -1) ); duk_pop_2(context); // Check if object wrapper was found if (objWrapper) { // Get object Object * obj = objWrapper->m_obj; // Get property name duk_push_current_function(context); duk_get_prop_string(context, -1, s_duktapePropertyNameKey); std::string propName = duk_get_string(context, -1); duk_pop_2(context); // Get property AbstractProperty * property = obj->property(propName); if (property) { // Set property value property->fromVariant(value); } } // Return status // 1: return value at top // 0: return 'undefined' // < 0: return error (use DUK_RET_xxx constants) return 0; } duk_ret_t DuktapeObjectWrapper::callObjectFunction(duk_context * context) { // Get script backend auto scriptBackend = DuktapeScriptBackend::getScriptBackend(context); // Determine number of arguments duk_idx_t nargs = duk_get_top(context); // Get function pointer duk_push_current_function(context); duk_get_prop_string(context, -1, s_duktapeFunctionPointerKey); Function * func = reinterpret_cast<Function *>( duk_get_pointer(context, -1) ); duk_pop_2(context); // Is function valid? if (func) { // Get all arguments from the stack and convert them into variants std::vector<Variant> arguments(nargs); for (int i = 0; i < nargs; ++i){ arguments[i] = scriptBackend->fromDukStack(0); duk_remove(context, 0); } // Call function Variant value = func->call(arguments); // Check return value if (!value.isNull()) { // Push return value to stack scriptBackend->pushToDukStack(value); return 1; } else { // No return value return 0; } } // No valid function found warning() << "Error: No valid function pointer found." << std::endl; return DUK_RET_ERROR; } } // namespace cppexpose <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2012 \file simulator/compiler/parser/rdo_logic.inl \authors \authors ([email protected]) \authors ([email protected]) \date 31.01.2012 \brief \indent 4T */ // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE template<class RTLogic, class Activity> inline typename RDOLogic<RTLogic, Activity>::LPActivity RDOLogic<RTLogic,Activity>::addNewActivity(CREF(RDOParserSrcInfo) activity_src_info, CREF(RDOParserSrcInfo) pattern_src_info) { LPActivity pAactivity = rdo::Factory<Activity>::create(m_pRuntimeLogic, activity_src_info, pattern_src_info); ASSERT(pAactivity); m_activityList.push_back(pAactivity); return pAactivity; } template<class RTLogic, class Activity> inline typename RDOLogic<RTLogic, Activity>::LPActivity RDOLogic<RTLogic,Activity>::getLastActivity() const { return !m_activityList.empty() ? m_activityList.back() : LPActivity(NULL); } template<class RTLogic, class Activity> inline const typename RDOLogic<RTLogic, Activity>::ActivityList& RDOLogic<RTLogic,Activity>::getActivities() const { return m_activityList; } template<class RTLogic, class Activity> inline RDOLogic<RTLogic, Activity>::RDOLogic(CREF(RDOParserSrcInfo) src_info) : RDOLogicBase(src_info) {} template<class RTLogic, class Activity> inline RDOLogic<RTLogic, Activity>::~RDOLogic() {} CLOSE_RDO_PARSER_NAMESPACE <commit_msg> - форматирование<commit_after>/*! \copyright (c) RDO-Team, 2012 \file simulator/compiler/parser/rdo_logic.inl \authors \authors ([email protected]) \authors ([email protected]) \date 31.01.2012 \brief \indent 4T */ // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE template<class RTLogic, class Activity> inline RDOLogic<RTLogic, Activity>::RDOLogic(CREF(RDOParserSrcInfo) src_info) : RDOLogicBase(src_info) {} template<class RTLogic, class Activity> inline RDOLogic<RTLogic, Activity>::~RDOLogic() {} template<class RTLogic, class Activity> inline typename RDOLogic<RTLogic, Activity>::LPActivity RDOLogic<RTLogic,Activity>::addNewActivity(CREF(RDOParserSrcInfo) activity_src_info, CREF(RDOParserSrcInfo) pattern_src_info) { LPActivity pAactivity = rdo::Factory<Activity>::create(m_pRuntimeLogic, activity_src_info, pattern_src_info); ASSERT(pAactivity); m_activityList.push_back(pAactivity); return pAactivity; } template<class RTLogic, class Activity> inline typename RDOLogic<RTLogic, Activity>::LPActivity RDOLogic<RTLogic,Activity>::getLastActivity() const { return !m_activityList.empty() ? m_activityList.back() : LPActivity(NULL); } template<class RTLogic, class Activity> inline const typename RDOLogic<RTLogic, Activity>::ActivityList& RDOLogic<RTLogic,Activity>::getActivities() const { return m_activityList; } CLOSE_RDO_PARSER_NAMESPACE <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/vespalib/util/slaveproc.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/searchcommon/common/schema.h> #include <vespa/searchlib/fef/indexproperties.h> #include <string> #include <vector> #include <map> #include <initializer_list> const char *prog = "../../../apps/verify_ranksetup/verify_ranksetup-bin"; const std::string gen_dir("generated"); const char *valid_feature = "value(0)"; const char *invalid_feature = "invalid_feature_name and format"; using namespace search::fef::indexproperties; using namespace search::index; struct Writer { FILE *file; Writer(const std::string &file_name) { file = fopen(file_name.c_str(), "w"); ASSERT_TRUE(file != 0); } void fmt(const char *format, ...) const #ifdef __GNUC__ __attribute__ ((format (printf,2,3))) #endif { va_list ap; va_start(ap, format); vfprintf(file, format, ap); va_end(ap); } ~Writer() { fclose(file); } }; void verify_dir() { std::string pwd(getenv("PWD")); ASSERT_NOT_EQUAL(pwd.find("searchcore/src/tests/proton/verify_ranksetup"), pwd.npos); } //----------------------------------------------------------------------------- struct Model { std::map<std::string,std::pair<std::string,std::string> > indexes; std::map<std::string,std::pair<std::string,std::string> > attributes; std::map<std::string,std::string> properties; std::map<std::string,std::string> constants; std::vector<bool> extra_profiles; Model() : indexes(), attributes(), properties(), extra_profiles() { verify_dir(); } void index(const std::string &name, schema::DataType data_type, schema::CollectionType collection_type) { indexes[name].first = schema::getTypeName(data_type); indexes[name].second = schema::getTypeName(collection_type); } void attribute(const std::string &name, schema::DataType data_type, schema::CollectionType collection_type) { attributes[name].first = schema::getTypeName(data_type); attributes[name].second = schema::getTypeName(collection_type); } void property(const std::string &name, const std::string &val) { properties[name] = val; } void first_phase(const std::string &feature) { property(rank::FirstPhase::NAME, feature); } void second_phase(const std::string &feature) { property(rank::SecondPhase::NAME, feature); } void summary_feature(const std::string &feature) { property(summary::Feature::NAME, feature); } void dump_feature(const std::string &feature) { property(dump::Feature::NAME, feature); } void good_profile() { extra_profiles.push_back(true); } void bad_profile() { extra_profiles.push_back(false); } void write_attributes(const Writer &out) { out.fmt("attribute[%zu]\n", attributes.size()); std::map<std::string,std::pair<std::string,std::string> >::const_iterator pos = attributes.begin(); for (size_t i = 0; pos != attributes.end(); ++pos, ++i) { out.fmt("attribute[%zu].name \"%s\"\n", i, pos->first.c_str()); out.fmt("attribute[%zu].datatype %s\n", i, pos->second.first.c_str()); out.fmt("attribute[%zu].collectiontype %s\n", i, pos->second.second.c_str()); } } void write_indexschema(const Writer &out) { out.fmt("indexfield[%zu]\n", indexes.size()); std::map<std::string,std::pair<std::string,std::string> >::const_iterator pos = indexes.begin(); for (size_t i = 0; pos != indexes.end(); ++pos, ++i) { out.fmt("indexfield[%zu].name \"%s\"\n", i, pos->first.c_str()); out.fmt("indexfield[%zu].datatype %s\n", i, pos->second.first.c_str()); out.fmt("indexfield[%zu].collectiontype %s\n", i, pos->second.second.c_str()); } } void write_rank_profiles(const Writer &out) { out.fmt("rankprofile[%zu]\n", extra_profiles.size() + 1); out.fmt("rankprofile[0].name \"default\"\n"); std::map<std::string,std::string>::const_iterator pos = properties.begin(); for (size_t i = 0; pos != properties.end(); ++pos, ++i) { out.fmt("rankprofile[0].fef.property[%zu]\n", properties.size()); out.fmt("rankprofile[0].fef.property[%zu].name \"%s\"\n", i, pos->first.c_str()); out.fmt("rankprofile[0].fef.property[%zu].value \"%s\"\n", i, pos->second.c_str()); } for (size_t i = 1; i < (extra_profiles.size() + 1); ++i) { out.fmt("rankprofile[%zu].name \"extra_%zu\"\n", i, i); out.fmt("rankprofile[%zu].fef.property[%zu].name \"%s\"\n", i, i, rank::FirstPhase::NAME.c_str()); out.fmt("rankprofile[%zu].fef.property[%zu].value \"%s\"\n", i, i, extra_profiles[i-1]?valid_feature:invalid_feature); } } void write_ranking_constants(const Writer &out) { size_t idx = 0; for (const auto &entry: constants) { out.fmt("constant[%zu].name \"%s\"\n", idx, entry.first.c_str()); out.fmt("constant[%zu].fileref \"12345\"\n", idx); out.fmt("constant[%zu].type \"%s\"\n", idx, entry.second.c_str()); ++idx; } } void generate() { write_attributes(Writer(gen_dir + "/attributes.cfg")); write_indexschema(Writer(gen_dir + "/indexschema.cfg")); write_rank_profiles(Writer(gen_dir + "/rank-profiles.cfg")); write_ranking_constants(Writer(gen_dir + "/ranking-constants.cfg")); } bool verify() { generate(); return vespalib::SlaveProc::run(vespalib::make_string("%s dir:%s", prog, gen_dir.c_str()).c_str()); } void verify_valid(std::initializer_list<std::string> features) { for (const std::string &f: features) { first_phase(f); if (!EXPECT_TRUE(verify())) { fprintf(stderr, "--> feature '%s' was invalid (should be valid)\n", f.c_str()); } } } void verify_invalid(std::initializer_list<std::string> features) { for (const std::string &f: features) { first_phase(f); if (!EXPECT_FALSE(verify())) { fprintf(stderr, "--> feature '%s' was valid (should be invalid)\n", f.c_str()); } } } }; //----------------------------------------------------------------------------- struct EmptyModel : Model {}; struct SimpleModel : Model { SimpleModel() : Model() { index("title", schema::STRING, schema::SINGLE); index("list", schema::STRING, schema::ARRAY); index("keywords", schema::STRING, schema::WEIGHTEDSET); attribute("date", schema::INT32, schema::SINGLE); constants["my_tensor"] = "tensor(x{},y{})"; } }; struct ShadowModel : Model { ShadowModel() : Model() { index("both", schema::STRING, schema::SINGLE); attribute("both", schema::STRING, schema::SINGLE); } }; TEST_F("print usage", Model()) { EXPECT_FALSE(vespalib::SlaveProc::run(vespalib::make_string("%s", prog).c_str())); } TEST_F("setup output directory", Model()) { ASSERT_TRUE(vespalib::SlaveProc::run(vespalib::make_string("rm -rf %s", gen_dir.c_str()).c_str())); ASSERT_TRUE(vespalib::SlaveProc::run(vespalib::make_string("mkdir %s", gen_dir.c_str()).c_str())); } //----------------------------------------------------------------------------- TEST_F("require that empty setup passes validation", EmptyModel()) { EXPECT_TRUE(f.verify()); } TEST_F("require that we can verify multiple rank profiles", SimpleModel()) { f.first_phase(valid_feature); f.good_profile(); EXPECT_TRUE(f.verify()); f.bad_profile(); EXPECT_FALSE(f.verify()); } TEST_F("require that first phase can break validation", SimpleModel()) { f.first_phase(invalid_feature); EXPECT_FALSE(f.verify()); } TEST_F("require that second phase can break validation", SimpleModel()) { f.second_phase(invalid_feature); EXPECT_FALSE(f.verify()); } TEST_F("require that summary features can break validation", SimpleModel()) { f.summary_feature(invalid_feature); EXPECT_FALSE(f.verify()); } TEST_F("require that dump features can break validation", SimpleModel()) { f.dump_feature(invalid_feature); EXPECT_FALSE(f.verify()); } TEST_F("require that fieldMatch feature requires single value field", SimpleModel()) { f.first_phase("fieldMatch(keywords)"); EXPECT_FALSE(f.verify()); f.first_phase("fieldMatch(list)"); EXPECT_FALSE(f.verify()); f.first_phase("fieldMatch(title)"); EXPECT_TRUE(f.verify()); } TEST_F("require that age feature requires attribute parameter", SimpleModel()) { f.first_phase("age(unknown)"); EXPECT_FALSE(f.verify()); f.first_phase("age(title)"); EXPECT_FALSE(f.verify()); f.first_phase("age(date)"); EXPECT_TRUE(f.verify()); } TEST_F("require that nativeRank can be used on any valid field", SimpleModel()) { f.verify_invalid({"nativeRank(unknown)"}); f.verify_valid({"nativeRank", "nativeRank(title)", "nativeRank(date)", "nativeRank(title,date)"}); } TEST_F("require that nativeAttributeMatch requires attribute parameter", SimpleModel()) { f.verify_invalid({"nativeAttributeMatch(unknown)", "nativeAttributeMatch(title)", "nativeAttributeMatch(title,date)"}); f.verify_valid({"nativeAttributeMatch", "nativeAttributeMatch(date)"}); } TEST_F("require that shadowed attributes can be used", ShadowModel()) { f.first_phase("attribute(both)"); EXPECT_TRUE(f.verify()); } TEST_F("require that ranking constants can be used", SimpleModel()) { f.first_phase("constant(my_tensor)"); EXPECT_TRUE(f.verify()); } TEST_F("require that undefined ranking constants cannot be used", SimpleModel()) { f.first_phase("constant(bogus_tensor)"); EXPECT_FALSE(f.verify()); } TEST_F("require that ranking expressions can be verified", SimpleModel()) { f.first_phase("rankingExpression(\\\"constant(my_tensor)+attribute(date)\\\")"); EXPECT_TRUE(f.verify()); } //----------------------------------------------------------------------------- TEST_F("require that tensor join is not yet supported", SimpleModel()) { f.first_phase("rankingExpression(\\\"join(constant(my_tensor),attribute(date),f(t,d)(t+d))\\\")"); EXPECT_FALSE(f.verify()); } //----------------------------------------------------------------------------- TEST_F("cleanup files", Model()) { ASSERT_TRUE(vespalib::SlaveProc::run(vespalib::make_string("rm -rf %s", gen_dir.c_str()).c_str())); } TEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); } <commit_msg>update test<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/vespalib/util/slaveproc.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/searchcommon/common/schema.h> #include <vespa/searchlib/fef/indexproperties.h> #include <string> #include <vector> #include <map> #include <initializer_list> const char *prog = "../../../apps/verify_ranksetup/verify_ranksetup-bin"; const std::string gen_dir("generated"); const char *valid_feature = "value(0)"; const char *invalid_feature = "invalid_feature_name and format"; using namespace search::fef::indexproperties; using namespace search::index; struct Writer { FILE *file; Writer(const std::string &file_name) { file = fopen(file_name.c_str(), "w"); ASSERT_TRUE(file != 0); } void fmt(const char *format, ...) const #ifdef __GNUC__ __attribute__ ((format (printf,2,3))) #endif { va_list ap; va_start(ap, format); vfprintf(file, format, ap); va_end(ap); } ~Writer() { fclose(file); } }; void verify_dir() { std::string pwd(getenv("PWD")); ASSERT_NOT_EQUAL(pwd.find("searchcore/src/tests/proton/verify_ranksetup"), pwd.npos); } //----------------------------------------------------------------------------- struct Model { std::map<std::string,std::pair<std::string,std::string> > indexes; std::map<std::string,std::pair<std::string,std::string> > attributes; std::map<std::string,std::string> properties; std::map<std::string,std::string> constants; std::vector<bool> extra_profiles; Model() : indexes(), attributes(), properties(), extra_profiles() { verify_dir(); } void index(const std::string &name, schema::DataType data_type, schema::CollectionType collection_type) { indexes[name].first = schema::getTypeName(data_type); indexes[name].second = schema::getTypeName(collection_type); } void attribute(const std::string &name, schema::DataType data_type, schema::CollectionType collection_type) { attributes[name].first = schema::getTypeName(data_type); attributes[name].second = schema::getTypeName(collection_type); } void property(const std::string &name, const std::string &val) { properties[name] = val; } void first_phase(const std::string &feature) { property(rank::FirstPhase::NAME, feature); } void second_phase(const std::string &feature) { property(rank::SecondPhase::NAME, feature); } void summary_feature(const std::string &feature) { property(summary::Feature::NAME, feature); } void dump_feature(const std::string &feature) { property(dump::Feature::NAME, feature); } void good_profile() { extra_profiles.push_back(true); } void bad_profile() { extra_profiles.push_back(false); } void write_attributes(const Writer &out) { out.fmt("attribute[%zu]\n", attributes.size()); std::map<std::string,std::pair<std::string,std::string> >::const_iterator pos = attributes.begin(); for (size_t i = 0; pos != attributes.end(); ++pos, ++i) { out.fmt("attribute[%zu].name \"%s\"\n", i, pos->first.c_str()); out.fmt("attribute[%zu].datatype %s\n", i, pos->second.first.c_str()); out.fmt("attribute[%zu].collectiontype %s\n", i, pos->second.second.c_str()); } } void write_indexschema(const Writer &out) { out.fmt("indexfield[%zu]\n", indexes.size()); std::map<std::string,std::pair<std::string,std::string> >::const_iterator pos = indexes.begin(); for (size_t i = 0; pos != indexes.end(); ++pos, ++i) { out.fmt("indexfield[%zu].name \"%s\"\n", i, pos->first.c_str()); out.fmt("indexfield[%zu].datatype %s\n", i, pos->second.first.c_str()); out.fmt("indexfield[%zu].collectiontype %s\n", i, pos->second.second.c_str()); } } void write_rank_profiles(const Writer &out) { out.fmt("rankprofile[%zu]\n", extra_profiles.size() + 1); out.fmt("rankprofile[0].name \"default\"\n"); std::map<std::string,std::string>::const_iterator pos = properties.begin(); for (size_t i = 0; pos != properties.end(); ++pos, ++i) { out.fmt("rankprofile[0].fef.property[%zu]\n", properties.size()); out.fmt("rankprofile[0].fef.property[%zu].name \"%s\"\n", i, pos->first.c_str()); out.fmt("rankprofile[0].fef.property[%zu].value \"%s\"\n", i, pos->second.c_str()); } for (size_t i = 1; i < (extra_profiles.size() + 1); ++i) { out.fmt("rankprofile[%zu].name \"extra_%zu\"\n", i, i); out.fmt("rankprofile[%zu].fef.property[%zu].name \"%s\"\n", i, i, rank::FirstPhase::NAME.c_str()); out.fmt("rankprofile[%zu].fef.property[%zu].value \"%s\"\n", i, i, extra_profiles[i-1]?valid_feature:invalid_feature); } } void write_ranking_constants(const Writer &out) { size_t idx = 0; for (const auto &entry: constants) { out.fmt("constant[%zu].name \"%s\"\n", idx, entry.first.c_str()); out.fmt("constant[%zu].fileref \"12345\"\n", idx); out.fmt("constant[%zu].type \"%s\"\n", idx, entry.second.c_str()); ++idx; } } void generate() { write_attributes(Writer(gen_dir + "/attributes.cfg")); write_indexschema(Writer(gen_dir + "/indexschema.cfg")); write_rank_profiles(Writer(gen_dir + "/rank-profiles.cfg")); write_ranking_constants(Writer(gen_dir + "/ranking-constants.cfg")); } bool verify() { generate(); return vespalib::SlaveProc::run(vespalib::make_string("%s dir:%s", prog, gen_dir.c_str()).c_str()); } void verify_valid(std::initializer_list<std::string> features) { for (const std::string &f: features) { first_phase(f); if (!EXPECT_TRUE(verify())) { fprintf(stderr, "--> feature '%s' was invalid (should be valid)\n", f.c_str()); } } } void verify_invalid(std::initializer_list<std::string> features) { for (const std::string &f: features) { first_phase(f); if (!EXPECT_TRUE(!verify())) { fprintf(stderr, "--> feature '%s' was valid (should be invalid)\n", f.c_str()); } } } }; //----------------------------------------------------------------------------- struct EmptyModel : Model {}; struct SimpleModel : Model { SimpleModel() : Model() { index("title", schema::STRING, schema::SINGLE); index("list", schema::STRING, schema::ARRAY); index("keywords", schema::STRING, schema::WEIGHTEDSET); attribute("date", schema::INT32, schema::SINGLE); constants["my_tensor"] = "tensor(x{},y{})"; } }; struct ShadowModel : Model { ShadowModel() : Model() { index("both", schema::STRING, schema::SINGLE); attribute("both", schema::STRING, schema::SINGLE); } }; TEST_F("print usage", Model()) { EXPECT_TRUE(!vespalib::SlaveProc::run(vespalib::make_string("%s", prog).c_str())); } TEST_F("setup output directory", Model()) { ASSERT_TRUE(vespalib::SlaveProc::run(vespalib::make_string("rm -rf %s", gen_dir.c_str()).c_str())); ASSERT_TRUE(vespalib::SlaveProc::run(vespalib::make_string("mkdir %s", gen_dir.c_str()).c_str())); } //----------------------------------------------------------------------------- TEST_F("require that empty setup passes validation", EmptyModel()) { EXPECT_TRUE(f.verify()); } TEST_F("require that we can verify multiple rank profiles", SimpleModel()) { f.first_phase(valid_feature); f.good_profile(); EXPECT_TRUE(f.verify()); f.bad_profile(); EXPECT_TRUE(!f.verify()); } TEST_F("require that first phase can break validation", SimpleModel()) { f.first_phase(invalid_feature); EXPECT_TRUE(!f.verify()); } TEST_F("require that second phase can break validation", SimpleModel()) { f.second_phase(invalid_feature); EXPECT_TRUE(!f.verify()); } TEST_F("require that summary features can break validation", SimpleModel()) { f.summary_feature(invalid_feature); EXPECT_TRUE(!f.verify()); } TEST_F("require that dump features can break validation", SimpleModel()) { f.dump_feature(invalid_feature); EXPECT_TRUE(!f.verify()); } TEST_F("require that fieldMatch feature requires single value field", SimpleModel()) { f.first_phase("fieldMatch(keywords)"); EXPECT_TRUE(!f.verify()); f.first_phase("fieldMatch(list)"); EXPECT_TRUE(!f.verify()); f.first_phase("fieldMatch(title)"); EXPECT_TRUE(f.verify()); } TEST_F("require that age feature requires attribute parameter", SimpleModel()) { f.first_phase("age(unknown)"); EXPECT_TRUE(!f.verify()); f.first_phase("age(title)"); EXPECT_TRUE(!f.verify()); f.first_phase("age(date)"); EXPECT_TRUE(f.verify()); } TEST_F("require that nativeRank can be used on any valid field", SimpleModel()) { f.verify_invalid({"nativeRank(unknown)"}); f.verify_valid({"nativeRank", "nativeRank(title)", "nativeRank(date)", "nativeRank(title,date)"}); } TEST_F("require that nativeAttributeMatch requires attribute parameter", SimpleModel()) { f.verify_invalid({"nativeAttributeMatch(unknown)", "nativeAttributeMatch(title)", "nativeAttributeMatch(title,date)"}); f.verify_valid({"nativeAttributeMatch", "nativeAttributeMatch(date)"}); } TEST_F("require that shadowed attributes can be used", ShadowModel()) { f.first_phase("attribute(both)"); EXPECT_TRUE(f.verify()); } TEST_F("require that ranking constants can be used", SimpleModel()) { f.first_phase("constant(my_tensor)"); EXPECT_TRUE(f.verify()); } TEST_F("require that undefined ranking constants cannot be used", SimpleModel()) { f.first_phase("constant(bogus_tensor)"); EXPECT_TRUE(!f.verify()); } TEST_F("require that ranking expressions can be verified", SimpleModel()) { f.first_phase("rankingExpression(\\\"constant(my_tensor)+attribute(date)\\\")"); EXPECT_TRUE(f.verify()); } //----------------------------------------------------------------------------- TEST_F("require that tensor join is supported", SimpleModel()) { f.first_phase("rankingExpression(\\\"join(constant(my_tensor),attribute(date),f(t,d)(t+d))\\\")"); EXPECT_TRUE(f.verify()); } TEST_F("require that nested tensor join is not supported", SimpleModel()) { f.first_phase("rankingExpression(\\\"join(constant(my_tensor),attribute(date),f(t,d)(join(t,d,f(x,y)(x+y))))\\\")"); EXPECT_TRUE(!f.verify()); } //----------------------------------------------------------------------------- TEST_F("cleanup files", Model()) { ASSERT_TRUE(vespalib::SlaveProc::run(vespalib::make_string("rm -rf %s", gen_dir.c_str()).c_str())); } TEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>// Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #if defined(_MSC_VER) || defined(__BORLANDC__) #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #include <math.h> // MSVC versions prior to 12 did not provided acosh, asinh, atanh functions in standard library #if (defined(_MSC_VER) && (_MSC_VER < 1800)) || defined(__BORLANDC__) __Standard_API double __cdecl acosh ( double ); __Standard_API double __cdecl asinh ( double ); __Standard_API double __cdecl atanh ( double ); #endif #endif /* _MSC_VER */ <commit_msg>Re-add math defines for MinGW<commit_after>// Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__) #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #include <math.h> // MSVC versions prior to 12 did not provided acosh, asinh, atanh functions in standard library #if (defined(_MSC_VER) && (_MSC_VER < 1800)) || defined(__BORLANDC__) __Standard_API double __cdecl acosh ( double ); __Standard_API double __cdecl asinh ( double ); __Standard_API double __cdecl atanh ( double ); #endif // if __STRICT_ANSI__ is defined when using MinGW, no math defines will be defined #ifdef __MINGW32__ # undef M_SQRT1_2 # define M_SQRT1_2 0.707106781186547524401 # undef M_PI_2 # define M_PI_2 1.57079632679489661923 # undef M_PI # define M_PI 3.14159265358979323846 #endif /* __MINGW32__ */ #endif /* _MSC_VER, __BORLANDC__, or __MINGW32__ */ <|endoftext|>
<commit_before>#ifndef OPERATOR_HPP #define OPERATOR_HPP #include <string> #include <vector> #include <functional> #include "utils/error.hpp" enum Associativity: int { ASSOCIATE_FROM_LEFT, ASSOCIATE_FROM_RIGHT }; enum Arity: int { NULLARY = 0, UNARY = 1, BINARY = 2, TERNARY = 3 }; enum Fixity: int { INFIX = 0, PREFIX = -1, POSTFIX = 1 }; class Operator { private: std::string name; int precedence; Associativity associativity; Arity arity; Fixity fixity; public: Operator(std::string name, int precedence, Associativity associativity = ASSOCIATE_FROM_LEFT, Arity arity = BINARY, Fixity fixity = INFIX): name(name), precedence(precedence), associativity(associativity), arity(arity), fixity(fixity) { if (arity == UNARY && fixity == INFIX) { throw InternalError("There are no unary infix operators", {METADATA_PAIRS}); } } std::string getName() const {return name;} int getPrecedence() const {return precedence;} Associativity getAssociativity() const {return associativity;} Arity getArity() const {return arity;} Fixity getFixity() const {return fixity;} bool operator==(const Operator& rhs) const { return name == rhs.name && precedence == rhs.precedence && associativity == rhs.associativity && arity == rhs.arity && fixity == rhs.fixity; } bool operator!=(const Operator& rhs) const { return !operator==(rhs); } }; const std::vector<Operator> operatorList { Operator("==", 7), Operator("!=", 7), // 1 // TODO: Ternary "?:" Operator("=", 1, ASSOCIATE_FROM_RIGHT), Operator("+=", 1, ASSOCIATE_FROM_RIGHT), Operator("-=", 1, ASSOCIATE_FROM_RIGHT), Operator("*=", 1, ASSOCIATE_FROM_RIGHT), Operator("/=", 1, ASSOCIATE_FROM_RIGHT), Operator("%=", 1, ASSOCIATE_FROM_RIGHT), Operator("<<=", 1, ASSOCIATE_FROM_RIGHT), Operator(">>=", 1, ASSOCIATE_FROM_RIGHT), Operator("&=", 1, ASSOCIATE_FROM_RIGHT), Operator("^=", 1, ASSOCIATE_FROM_RIGHT), Operator("|=", 1, ASSOCIATE_FROM_RIGHT), // 12 Operator(">>", 9), Operator("<<", 9), // 14 Operator("<=", 8), Operator("<", 8), Operator(">=", 8), Operator(">", 8), // 18 // Postfix Operator("--", 13, ASSOCIATE_FROM_LEFT, UNARY, POSTFIX), Operator("++", 13, ASSOCIATE_FROM_LEFT, UNARY, POSTFIX), // 20 // Operator("[]", 13), // TODO: find subscript better Operator(".", 13), // 21 // Prefix Operator("--", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), Operator("++", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), Operator("-", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), Operator("+", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), Operator("~", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), // Bitwise NOT Operator("!", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), // Logical NOT // 27 Operator("*", 11), Operator("/", 11), Operator("%", 11), // 30 Operator("+", 10), Operator("-", 10), // 32 Operator("&&", 3), // Logical AND Operator("||", 2), // Logical OR // 34 Operator("&", 6), // Bitwise AND Operator("^", 5), // Bitwise XOR Operator("|", 4), // Bitwise OR // 37 Operator(",", 0) // 38 }; typedef std::string OperatorName; std::map<OperatorName, uint> operatorNameMap { {"Equality", 0}, {"Inequality", 1}, {"Assignment", 2}, {"+Assignment", 3}, {"-Assignment", 4}, {"*Assignment", 5}, {"/Assignment", 6}, {"%Assignment", 7}, {"<<Assignment", 8}, {">>Assignment", 9}, {"&Assignment", 10}, {"^Assignment", 11}, {"|Assignment", 12}, {"Bitshift >>", 13}, {"Bitshift <<", 14}, {"Less or equal", 15}, {"Less", 16}, {"Greater or equal", 17}, {"Greater", 18}, {"Postfix --", 19}, {"Postfix ++", 20}, {"Member access", 21}, {"Prefix --", 22}, {"Prefix ++", 23}, {"Unary -", 24}, {"Unary +", 25}, {"Bitwise NOT", 26}, {"Logical NOT", 27}, {"Multiply", 28}, {"Divide", 29}, {"Modulo", 30}, {"Add", 31}, {"Substract", 32}, {"Logical AND", 33}, {"Logical OR", 34}, {"Bitwise AND", 35}, {"Bitwise XOR", 36}, {"Bitwise OR", 37}, {"Comma", 38}, }; std::vector<char> getOperatorCharacters() { static std::vector<char> chars {}; if (chars.size() == 0) { std::string mashed = std::accumulate(operatorList.begin(), operatorList.end(), std::string {}, [](const std::string& previous, const Operator& op) { return previous + op.getName(); }); std::sort(mashed.begin(), mashed.end()); mashed.erase(std::unique(mashed.begin(), mashed.end()), mashed.end()); for (auto c : mashed) chars.push_back(c); } return chars; } std::vector<char> getConstructCharacters() { const static std::vector<char> chars {' ', '\n', '\0', '(', ')', '[', ']', '?', ';', ':'}; return chars; } const Operator& operatorFrom(const OperatorName& name) { return operatorList[operatorNameMap[name]]; } OperatorName operatorNameFrom(uint64 index) { auto it = std::find_if(ALL(operatorNameMap), [=](auto mapPair) { return mapPair.second == index; }); if (it == operatorNameMap.end()) throw InternalError("No such operator index", {METADATA_PAIRS, {"index", std::to_string(index)}}); return it->first; } #endif <commit_msg>Fixed type of map value<commit_after>#ifndef OPERATOR_HPP #define OPERATOR_HPP #include <string> #include <vector> #include <functional> #include "utils/error.hpp" enum Associativity: int { ASSOCIATE_FROM_LEFT, ASSOCIATE_FROM_RIGHT }; enum Arity: int { NULLARY = 0, UNARY = 1, BINARY = 2, TERNARY = 3 }; enum Fixity: int { INFIX = 0, PREFIX = -1, POSTFIX = 1 }; class Operator { private: std::string name; int precedence; Associativity associativity; Arity arity; Fixity fixity; public: Operator(std::string name, int precedence, Associativity associativity = ASSOCIATE_FROM_LEFT, Arity arity = BINARY, Fixity fixity = INFIX): name(name), precedence(precedence), associativity(associativity), arity(arity), fixity(fixity) { if (arity == UNARY && fixity == INFIX) { throw InternalError("There are no unary infix operators", {METADATA_PAIRS}); } } std::string getName() const {return name;} int getPrecedence() const {return precedence;} Associativity getAssociativity() const {return associativity;} Arity getArity() const {return arity;} Fixity getFixity() const {return fixity;} bool operator==(const Operator& rhs) const { return name == rhs.name && precedence == rhs.precedence && associativity == rhs.associativity && arity == rhs.arity && fixity == rhs.fixity; } bool operator!=(const Operator& rhs) const { return !operator==(rhs); } }; const std::vector<Operator> operatorList { Operator("==", 7), Operator("!=", 7), // 1 // TODO: Ternary "?:" Operator("=", 1, ASSOCIATE_FROM_RIGHT), Operator("+=", 1, ASSOCIATE_FROM_RIGHT), Operator("-=", 1, ASSOCIATE_FROM_RIGHT), Operator("*=", 1, ASSOCIATE_FROM_RIGHT), Operator("/=", 1, ASSOCIATE_FROM_RIGHT), Operator("%=", 1, ASSOCIATE_FROM_RIGHT), Operator("<<=", 1, ASSOCIATE_FROM_RIGHT), Operator(">>=", 1, ASSOCIATE_FROM_RIGHT), Operator("&=", 1, ASSOCIATE_FROM_RIGHT), Operator("^=", 1, ASSOCIATE_FROM_RIGHT), Operator("|=", 1, ASSOCIATE_FROM_RIGHT), // 12 Operator(">>", 9), Operator("<<", 9), // 14 Operator("<=", 8), Operator("<", 8), Operator(">=", 8), Operator(">", 8), // 18 // Postfix Operator("--", 13, ASSOCIATE_FROM_LEFT, UNARY, POSTFIX), Operator("++", 13, ASSOCIATE_FROM_LEFT, UNARY, POSTFIX), // 20 // Operator("[]", 13), // TODO: find subscript better Operator(".", 13), // 21 // Prefix Operator("--", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), Operator("++", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), Operator("-", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), Operator("+", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), Operator("~", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), // Bitwise NOT Operator("!", 12, ASSOCIATE_FROM_RIGHT, UNARY, PREFIX), // Logical NOT // 27 Operator("*", 11), Operator("/", 11), Operator("%", 11), // 30 Operator("+", 10), Operator("-", 10), // 32 Operator("&&", 3), // Logical AND Operator("||", 2), // Logical OR // 34 Operator("&", 6), // Bitwise AND Operator("^", 5), // Bitwise XOR Operator("|", 4), // Bitwise OR // 37 Operator(",", 0) // 38 }; typedef std::string OperatorName; std::map<OperatorName, int> operatorNameMap { {"Equality", 0}, {"Inequality", 1}, {"Assignment", 2}, {"+Assignment", 3}, {"-Assignment", 4}, {"*Assignment", 5}, {"/Assignment", 6}, {"%Assignment", 7}, {"<<Assignment", 8}, {">>Assignment", 9}, {"&Assignment", 10}, {"^Assignment", 11}, {"|Assignment", 12}, {"Bitshift >>", 13}, {"Bitshift <<", 14}, {"Less or equal", 15}, {"Less", 16}, {"Greater or equal", 17}, {"Greater", 18}, {"Postfix --", 19}, {"Postfix ++", 20}, {"Member access", 21}, {"Prefix --", 22}, {"Prefix ++", 23}, {"Unary -", 24}, {"Unary +", 25}, {"Bitwise NOT", 26}, {"Logical NOT", 27}, {"Multiply", 28}, {"Divide", 29}, {"Modulo", 30}, {"Add", 31}, {"Substract", 32}, {"Logical AND", 33}, {"Logical OR", 34}, {"Bitwise AND", 35}, {"Bitwise XOR", 36}, {"Bitwise OR", 37}, {"Comma", 38}, }; std::vector<char> getOperatorCharacters() { static std::vector<char> chars {}; if (chars.size() == 0) { std::string mashed = std::accumulate(operatorList.begin(), operatorList.end(), std::string {}, [](const std::string& previous, const Operator& op) { return previous + op.getName(); }); std::sort(mashed.begin(), mashed.end()); mashed.erase(std::unique(mashed.begin(), mashed.end()), mashed.end()); for (auto c : mashed) chars.push_back(c); } return chars; } std::vector<char> getConstructCharacters() { const static std::vector<char> chars {' ', '\n', '\0', '(', ')', '[', ']', '?', ';', ':'}; return chars; } const Operator& operatorFrom(const OperatorName& name) { return operatorList[operatorNameMap[name]]; } OperatorName operatorNameFrom(int64 index) { auto it = std::find_if(ALL(operatorNameMap), [=](auto mapPair) { return mapPair.second == index; }); if (it == operatorNameMap.end()) throw InternalError("No such operator index", {METADATA_PAIRS, {"index", std::to_string(index)}}); return it->first; } #endif <|endoftext|>
<commit_before>#include <memory.h> #include "vtrc-hash-iface.h" #include "hash/sha2-traits.h" namespace vtrc { namespace common { namespace hash { namespace { template <typename HashTraits> struct hasher_sha: public hash_iface { size_t hash_size( ) const { return HashTraits::digest_length; } std::string get_data_hash(const void *data, size_t length ) const { typename HashTraits::context_type context; HashTraits::init( &context ); HashTraits::update( &context, reinterpret_cast<const uint8_t *>(data), length ); return HashTraits::fin( &context ); } void get_data_hash(const void *data, size_t length, void *result_hash ) const { typename HashTraits::context_type context; HashTraits::init( &context ); HashTraits::update( &context, reinterpret_cast<const uint8_t *>(data), length ); HashTraits::fin( &context, reinterpret_cast<uint8_t *>(result_hash)); } bool check_data_hash( const void * data , size_t length, const void * hash ) const { std::string h = get_data_hash( data, length ); return memcmp( h.c_str( ), hash, HashTraits::digest_length ) == 0; } }; } namespace sha2 { hash_iface *create256( ) { return new hasher_sha<vtrc::hash::hash_SHA256_traits>; } hash_iface *create348( ) { return new hasher_sha<vtrc::hash::hash_SHA384_traits>; } hash_iface *create512( ) { return new hasher_sha<vtrc::hash::hash_SHA512_traits>; } } }}} <commit_msg>hash finish->fin<commit_after>#include <memory.h> #include "vtrc-hash-iface.h" #include "hash/sha2-traits.h" namespace vtrc { namespace common { namespace hash { namespace { template <typename HashTraits> struct hasher_sha: public hash_iface { size_t hash_size( ) const { return HashTraits::digest_length; } std::string get_data_hash(const void *data, size_t length ) const { typename HashTraits::context_type context; HashTraits::init( &context ); HashTraits::update( &context, reinterpret_cast<const u_int8_t *>(data), length ); return HashTraits::fin( &context ); } void get_data_hash(const void *data, size_t length, void *result_hash ) const { typename HashTraits::context_type context; HashTraits::init( &context ); HashTraits::update( &context, reinterpret_cast<const u_int8_t *>(data), length ); HashTraits::fin( &context, reinterpret_cast<u_int8_t *>(result_hash)); } bool check_data_hash( const void * data , size_t length, const void * hash ) const { std::string h = get_data_hash( data, length ); return memcmp( h.c_str( ), hash, HashTraits::digest_length ) == 0; } }; } namespace sha2 { hash_iface *create256( ) { return new hasher_sha<vtrc::hash::hash_SHA256_traits>; } hash_iface *create348( ) { return new hasher_sha<vtrc::hash::hash_SHA384_traits>; } hash_iface *create512( ) { return new hasher_sha<vtrc::hash::hash_SHA512_traits>; } } }}} <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, 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 Willow Garage, 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. * * $id $ */ #ifndef PCL_SEGMENTATION_IMPL_SEEDED_HUE_SEGMENTATION_H_ #define PCL_SEGMENTATION_IMPL_SEEDED_HUE_SEGMENTATION_H_ #include "pcl/segmentation/seeded_hue_segmentation.h" ////////////////////////////////////////////////////////////////////////////////////////////// void pcl::seededHueSegmentation ( const PointCloud<PointXYZRGB> &cloud, const boost::shared_ptr<search::Search<PointXYZRGB> > &tree, float tolerance, PointIndices &indices_in, PointIndices &indices_out, float delta_hue) { if (tree->getInputCloud ()->points.size () != cloud.points.size ()) { PCL_ERROR ("[pcl::seededHueSegmentation] Tree built for a different point cloud dataset (%lu) than the input cloud (%lu)!\n", (unsigned long)tree->getInputCloud ()->points.size (), (unsigned long)cloud.points.size ()); return; } // Create a bool vector of processed point indices, and initialize it to false std::vector<bool> processed (cloud.points.size (), false); std::vector<int> nn_indices; std::vector<float> nn_distances; // Process all points in the indices vector for (size_t k = 0; k < indices_in.indices.size (); ++k) { int i = indices_in.indices[k]; if (processed[i]) continue; processed[i] = true; std::vector<int> seed_queue; int sq_idx = 0; seed_queue.push_back (i); PointXYZRGB p; p = cloud.points[i]; PointXYZHSV h; PointXYZRGBtoXYZHSV(p, h); while (sq_idx < (int)seed_queue.size ()) { int ret = tree->radiusSearch (seed_queue[sq_idx], tolerance, nn_indices, nn_distances, std::numeric_limits<int>::max()); if(ret == -1) PCL_ERROR("[pcl::seededHueSegmentation] radiusSearch returned error code -1"); // Search for sq_idx if (!ret) { sq_idx++; continue; } for (size_t j = 1; j < nn_indices.size (); ++j) // nn_indices[0] should be sq_idx { if (processed[nn_indices[j]]) // Has this point been processed before ? continue; PointXYZRGB p_l; p_l = cloud.points[nn_indices[j]]; PointXYZHSV h_l; PointXYZRGBtoXYZHSV(p_l, h_l); if (fabs(h_l.h - h.h) < delta_hue) { seed_queue.push_back (nn_indices[j]); processed[nn_indices[j]] = true; } } sq_idx++; } // Copy the seed queue into the output indices for (size_t l = 0; l < seed_queue.size (); ++l) indices_out.indices.push_back(seed_queue[l]); } // This is purely esthetical, can be removed for speed purposes std::sort (indices_out.indices.begin (), indices_out.indices.end ()); } ////////////////////////////////////////////////////////////////////////////////////////////// void pcl::seededHueSegmentation ( const PointCloud<PointXYZRGB> &cloud, const boost::shared_ptr<search::Search<PointXYZRGBL> > &tree, float tolerance, PointIndices &indices_in, PointIndices &indices_out, float delta_hue) { if (tree->getInputCloud ()->points.size () != cloud.points.size ()) { PCL_ERROR ("[pcl::seededHueSegmentation] Tree built for a different point cloud dataset (%lu) than the input cloud (%lu)!\n", (unsigned long)tree->getInputCloud ()->points.size (), (unsigned long)cloud.points.size ()); return; } // Create a bool vector of processed point indices, and initialize it to false std::vector<bool> processed (cloud.points.size (), false); std::vector<int> nn_indices; std::vector<float> nn_distances; // Process all points in the indices vector for (size_t k = 0; k < indices_in.indices.size (); ++k) { int i = indices_in.indices[k]; if (processed[i]) continue; processed[i] = true; std::vector<int> seed_queue; int sq_idx = 0; seed_queue.push_back (i); PointXYZRGB p; p = cloud.points[i]; PointXYZHSV h; PointXYZRGBtoXYZHSV(p, h); while (sq_idx < (int)seed_queue.size ()) { // Search for sq_idx if (!tree->radiusSearch (seed_queue[sq_idx], tolerance, nn_indices, nn_distances)) { sq_idx++; continue; } for (size_t j = 1; j < nn_indices.size (); ++j) // nn_indices[0] should be sq_idx { if (processed[nn_indices[j]]) // Has this point been processed before ? continue; PointXYZRGB p_l; p_l = cloud.points[nn_indices[j]]; PointXYZHSV h_l; PointXYZRGBtoXYZHSV(p_l, h_l); if (fabs(h_l.h - h.h) < delta_hue) { seed_queue.push_back (nn_indices[j]); processed[nn_indices[j]] = true; } } sq_idx++; } // Copy the seed queue into the output indices for (size_t l = 0; l < seed_queue.size (); ++l) indices_out.indices.push_back(seed_queue[l]); } // This is purely esthetical, can be removed for speed purposes std::sort (indices_out.indices.begin (), indices_out.indices.end ()); } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// void pcl::SeededHueSegmentation::segment (PointIndices &indices_in, PointIndices &indices_out) { if (!initCompute () || (input_ != 0 && input_->points.empty ()) || (indices_ != 0 && indices_->empty ())) { indices_out.indices.clear (); return; } // Initialize the spatial locator if (!tree_) { if (input_->isOrganized ()) tree_.reset (new pcl::search::OrganizedNeighbor<PointXYZRGB> ()); else tree_.reset (new pcl::search::KdTree<PointXYZRGB> (false)); } // Send the input dataset to the spatial locator tree_->setInputCloud (input_); seededHueSegmentation (*input_, tree_, cluster_tolerance_, indices_in, indices_out, delta_hue_); deinitCompute (); } #endif // PCL_EXTRACT_CLUSTERS_IMPL_H_ <commit_msg>* bugfix seeded_hue_segmentation fetch the return value of radiusSearch<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, 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 Willow Garage, 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. * * $id $ */ #ifndef PCL_SEGMENTATION_IMPL_SEEDED_HUE_SEGMENTATION_H_ #define PCL_SEGMENTATION_IMPL_SEEDED_HUE_SEGMENTATION_H_ #include "pcl/segmentation/seeded_hue_segmentation.h" ////////////////////////////////////////////////////////////////////////////////////////////// void pcl::seededHueSegmentation ( const PointCloud<PointXYZRGB> &cloud, const boost::shared_ptr<search::Search<PointXYZRGB> > &tree, float tolerance, PointIndices &indices_in, PointIndices &indices_out, float delta_hue) { if (tree->getInputCloud ()->points.size () != cloud.points.size ()) { PCL_ERROR ("[pcl::seededHueSegmentation] Tree built for a different point cloud dataset (%lu) than the input cloud (%lu)!\n", (unsigned long)tree->getInputCloud ()->points.size (), (unsigned long)cloud.points.size ()); return; } // Create a bool vector of processed point indices, and initialize it to false std::vector<bool> processed (cloud.points.size (), false); std::vector<int> nn_indices; std::vector<float> nn_distances; // Process all points in the indices vector for (size_t k = 0; k < indices_in.indices.size (); ++k) { int i = indices_in.indices[k]; if (processed[i]) continue; processed[i] = true; std::vector<int> seed_queue; int sq_idx = 0; seed_queue.push_back (i); PointXYZRGB p; p = cloud.points[i]; PointXYZHSV h; PointXYZRGBtoXYZHSV(p, h); while (sq_idx < (int)seed_queue.size ()) { int ret = tree->radiusSearch (seed_queue[sq_idx], tolerance, nn_indices, nn_distances, std::numeric_limits<int>::max()); if(ret == -1) PCL_ERROR("[pcl::seededHueSegmentation] radiusSearch returned error code -1"); // Search for sq_idx if (!ret) { sq_idx++; continue; } for (size_t j = 1; j < nn_indices.size (); ++j) // nn_indices[0] should be sq_idx { if (processed[nn_indices[j]]) // Has this point been processed before ? continue; PointXYZRGB p_l; p_l = cloud.points[nn_indices[j]]; PointXYZHSV h_l; PointXYZRGBtoXYZHSV(p_l, h_l); if (fabs(h_l.h - h.h) < delta_hue) { seed_queue.push_back (nn_indices[j]); processed[nn_indices[j]] = true; } } sq_idx++; } // Copy the seed queue into the output indices for (size_t l = 0; l < seed_queue.size (); ++l) indices_out.indices.push_back(seed_queue[l]); } // This is purely esthetical, can be removed for speed purposes std::sort (indices_out.indices.begin (), indices_out.indices.end ()); } ////////////////////////////////////////////////////////////////////////////////////////////// void pcl::seededHueSegmentation ( const PointCloud<PointXYZRGB> &cloud, const boost::shared_ptr<search::Search<PointXYZRGBL> > &tree, float tolerance, PointIndices &indices_in, PointIndices &indices_out, float delta_hue) { if (tree->getInputCloud ()->points.size () != cloud.points.size ()) { PCL_ERROR ("[pcl::seededHueSegmentation] Tree built for a different point cloud dataset (%lu) than the input cloud (%lu)!\n", (unsigned long)tree->getInputCloud ()->points.size (), (unsigned long)cloud.points.size ()); return; } // Create a bool vector of processed point indices, and initialize it to false std::vector<bool> processed (cloud.points.size (), false); std::vector<int> nn_indices; std::vector<float> nn_distances; // Process all points in the indices vector for (size_t k = 0; k < indices_in.indices.size (); ++k) { int i = indices_in.indices[k]; if (processed[i]) continue; processed[i] = true; std::vector<int> seed_queue; int sq_idx = 0; seed_queue.push_back (i); PointXYZRGB p; p = cloud.points[i]; PointXYZHSV h; PointXYZRGBtoXYZHSV(p, h); while (sq_idx < (int)seed_queue.size ()) { int ret = tree->radiusSearch (seed_queue[sq_idx], tolerance, nn_indices, nn_distances, std::numeric_limits<int>::max()); if(ret == -1) PCL_ERROR("[pcl::seededHueSegmentation] radiusSearch returned error code -1"); // Search for sq_idx if (!ret) { sq_idx++; continue; } for (size_t j = 1; j < nn_indices.size (); ++j) // nn_indices[0] should be sq_idx { if (processed[nn_indices[j]]) // Has this point been processed before ? continue; PointXYZRGB p_l; p_l = cloud.points[nn_indices[j]]; PointXYZHSV h_l; PointXYZRGBtoXYZHSV(p_l, h_l); if (fabs(h_l.h - h.h) < delta_hue) { seed_queue.push_back (nn_indices[j]); processed[nn_indices[j]] = true; } } sq_idx++; } // Copy the seed queue into the output indices for (size_t l = 0; l < seed_queue.size (); ++l) indices_out.indices.push_back(seed_queue[l]); } // This is purely esthetical, can be removed for speed purposes std::sort (indices_out.indices.begin (), indices_out.indices.end ()); } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// void pcl::SeededHueSegmentation::segment (PointIndices &indices_in, PointIndices &indices_out) { if (!initCompute () || (input_ != 0 && input_->points.empty ()) || (indices_ != 0 && indices_->empty ())) { indices_out.indices.clear (); return; } // Initialize the spatial locator if (!tree_) { if (input_->isOrganized ()) tree_.reset (new pcl::search::OrganizedNeighbor<PointXYZRGB> ()); else tree_.reset (new pcl::search::KdTree<PointXYZRGB> (false)); } // Send the input dataset to the spatial locator tree_->setInputCloud (input_); seededHueSegmentation (*input_, tree_, cluster_tolerance_, indices_in, indices_out, delta_hue_); deinitCompute (); } #endif // PCL_EXTRACT_CLUSTERS_IMPL_H_ <|endoftext|>
<commit_before>#include "CubemapExtractionPlugin.h" #include "CubemapFaceD3D11.h" #if SUPPORT_D3D11 CubemapFaceD3D11::CubemapFaceD3D11( boost::uint32_t width, boost::uint32_t height, ID3D11Texture2D* gpuTexturePtr, ID3D11Texture2D* cpuTexturePtr, D3D11_MAPPED_SUBRESOURCE resource ) : CubemapFace(width, height), gpuTexturePtr(gpuTexturePtr), cpuTexturePtr(cpuTexturePtr), resource(resource) { } CubemapFaceD3D11* CubemapFaceD3D11::create(ID3D11Texture2D* texturePtr) { ID3D11Texture2D* gpuTexturePtr = (ID3D11Texture2D*)texturePtr; D3D11_TEXTURE2D_DESC textureDescription; gpuTexturePtr->GetDesc(&textureDescription); UINT width = textureDescription.Width; UINT height = textureDescription.Height; textureDescription.BindFlags = 0; textureDescription.CPUAccessFlags = D3D11_CPU_ACCESS_READ; textureDescription.Usage = D3D11_USAGE_STAGING; ID3D11Texture2D* cpuTexturePtr; HRESULT hr = g_D3D11Device->CreateTexture2D(&textureDescription, NULL, &cpuTexturePtr); ID3D11DeviceContext* g_D3D11DeviceContext = NULL; g_D3D11Device->GetImmediateContext(&g_D3D11DeviceContext); //HRESULT hr2 = g_D3D11Device->CreateDeferredContext(0, &g_D3D11DeviceContext); D3D11_MAPPED_SUBRESOURCE resource; ZeroMemory(&resource, sizeof(D3D11_MAPPED_SUBRESOURCE)); unsigned int subresource = D3D11CalcSubresource(0, 0, 0); hr = g_D3D11DeviceContext->Map(cpuTexturePtr, subresource, D3D11_MAP_READ, 0, &resource); g_D3D11DeviceContext->Unmap(cpuTexturePtr, subresource); return new CubemapFaceD3D11(width, height, gpuTexturePtr, cpuTexturePtr, resource); } void CubemapFaceD3D11::copyFromGPUToCPU() { ID3D11DeviceContext* g_D3D11DeviceContext = NULL; g_D3D11Device->GetImmediateContext(&g_D3D11DeviceContext); // copy data from GPU to CPU g_D3D11DeviceContext->CopyResource(this->cpuTexturePtr, this->gpuTexturePtr); //ZeroMemory(&cubemapFaceD3D11->resource, sizeof(D3D11_MAPPED_SUBRESOURCE)); //unsigned int subresource = D3D11CalcSubresource(0, 0, 0); //HRESULT hr = g_D3D11DeviceContext->Map(cubemapFaceD3D11->cpuTexturePtr, subresource, D3D11_MAP_READ, 0, &cubemapFaceD3D11->resource); memcpy(this->pixels, this->resource.pData, this->width * this->height * 4); //g_D3D11DeviceContext->Unmap(cubemapFaceD3D11->cpuTexturePtr, subresource); } #endif<commit_msg>Corrected color order in pixels when using DirectX 11<commit_after>#include "CubemapExtractionPlugin.h" #include "CubemapFaceD3D11.h" #if SUPPORT_D3D11 CubemapFaceD3D11::CubemapFaceD3D11( boost::uint32_t width, boost::uint32_t height, ID3D11Texture2D* gpuTexturePtr, ID3D11Texture2D* cpuTexturePtr, D3D11_MAPPED_SUBRESOURCE resource ) : CubemapFace(width, height), gpuTexturePtr(gpuTexturePtr), cpuTexturePtr(cpuTexturePtr), resource(resource) { } CubemapFaceD3D11* CubemapFaceD3D11::create(ID3D11Texture2D* texturePtr) { ID3D11Texture2D* gpuTexturePtr = (ID3D11Texture2D*)texturePtr; D3D11_TEXTURE2D_DESC textureDescription; gpuTexturePtr->GetDesc(&textureDescription); UINT width = textureDescription.Width; UINT height = textureDescription.Height; textureDescription.BindFlags = 0; textureDescription.CPUAccessFlags = D3D11_CPU_ACCESS_READ; textureDescription.Usage = D3D11_USAGE_STAGING; ID3D11Texture2D* cpuTexturePtr; HRESULT hr = g_D3D11Device->CreateTexture2D(&textureDescription, NULL, &cpuTexturePtr); ID3D11DeviceContext* g_D3D11DeviceContext = NULL; g_D3D11Device->GetImmediateContext(&g_D3D11DeviceContext); //HRESULT hr2 = g_D3D11Device->CreateDeferredContext(0, &g_D3D11DeviceContext); D3D11_MAPPED_SUBRESOURCE resource; ZeroMemory(&resource, sizeof(D3D11_MAPPED_SUBRESOURCE)); unsigned int subresource = D3D11CalcSubresource(0, 0, 0); hr = g_D3D11DeviceContext->Map(cpuTexturePtr, subresource, D3D11_MAP_READ, 0, &resource); g_D3D11DeviceContext->Unmap(cpuTexturePtr, subresource); return new CubemapFaceD3D11(width, height, gpuTexturePtr, cpuTexturePtr, resource); } void CubemapFaceD3D11::copyFromGPUToCPU() { ID3D11DeviceContext* g_D3D11DeviceContext = NULL; g_D3D11Device->GetImmediateContext(&g_D3D11DeviceContext); // copy data from GPU to CPU g_D3D11DeviceContext->CopyResource(this->cpuTexturePtr, this->gpuTexturePtr); //ZeroMemory(&cubemapFaceD3D11->resource, sizeof(D3D11_MAPPED_SUBRESOURCE)); //unsigned int subresource = D3D11CalcSubresource(0, 0, 0); //HRESULT hr = g_D3D11DeviceContext->Map(cubemapFaceD3D11->cpuTexturePtr, subresource, D3D11_MAP_READ, 0, &cubemapFaceD3D11->resource); // DirectX 11 is using wrong order of colors in a pixel -> correcting it for (unsigned int i = 0; i < this->width * this->height * 4; i += 4) { for (int j = 0; j < 3; j++) { ((char*)this->pixels)[i + j] = ((char*)this->resource.pData)[i + 2 - j]; } } //g_D3D11DeviceContext->Unmap(cubemapFaceD3D11->cpuTexturePtr, subresource); } #endif<|endoftext|>
<commit_before><commit_msg>cast_benchmarks: Fix broken behavior<commit_after><|endoftext|>
<commit_before>#include "erlkaf_config.h" #include "nif_utils.h" #include "erlkaf_nif.h" #include "rdkafka.h" #include <functional> #include <signal.h> namespace { template <typename T> struct set_config_fun { std::function<rd_kafka_conf_res_t (T *conf, const char *name, const char *value, char *errstr, size_t errstr_size)> set_value; }; const set_config_fun<rd_kafka_topic_conf_t> kTopicConfFuns = { rd_kafka_topic_conf_set }; const set_config_fun<rd_kafka_conf_t> kKafkaConfFuns = { rd_kafka_conf_set }; template <typename T> ERL_NIF_TERM parse_config(ErlNifEnv* env, ERL_NIF_TERM list, T* conf, set_config_fun<T> fun) { if(!enif_is_list(env, list)) return make_bad_options(env, list); char errstr[512]; ERL_NIF_TERM head; const ERL_NIF_TERM *items; int arity; while(enif_get_list_cell(env, list, &head, &list)) { if(!enif_get_tuple(env, head, &arity, &items) || arity != 2) return make_bad_options(env, head); std::string key; std::string value; if(!get_string(env, items[0], &key)) return make_bad_options(env, head); if(!get_string(env, items[1], &value)) return make_bad_options(env, head); if(fun.set_value(conf, key.c_str(), value.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) return make_error(env, errstr); } return ATOMS.atomOk; } bool appy_kafka_default_config(rd_kafka_conf_t* config) { if(rd_kafka_conf_set(config, "enable.auto.commit", "true", NULL, 0) != RD_KAFKA_CONF_OK) return false; if(rd_kafka_conf_set(config, "enable.auto.offset.store", "false", NULL, 0) != RD_KAFKA_CONF_OK) return false; if(rd_kafka_conf_set(config, "enable.partition.eof", "false", NULL, 0) != RD_KAFKA_CONF_OK) return false; #ifdef SIGIO //quick termination char tmp[128]; snprintf(tmp, sizeof(tmp), "%i", SIGIO); if(rd_kafka_conf_set(config, "internal.termination.signal", tmp, NULL, 0) != RD_KAFKA_CONF_OK) return false; #endif return true; } bool appy_topic_default_config(rd_kafka_topic_conf_t* config) { return true; } } ERL_NIF_TERM parse_topic_config(ErlNifEnv* env, ERL_NIF_TERM list, rd_kafka_topic_conf_t* conf) { if(!appy_topic_default_config(conf)) return make_error(env, "failed to apply default topic config"); return parse_config(env, list, conf, kTopicConfFuns); } ERL_NIF_TERM parse_kafka_config(ErlNifEnv* env, ERL_NIF_TERM list, rd_kafka_conf_t* conf) { if(!appy_kafka_default_config(conf)) return make_error(env, "failed to apply default kafka config"); return parse_config(env, list, conf, kKafkaConfFuns); } <commit_msg>Fix build<commit_after>#include "erlkaf_config.h" #include "nif_utils.h" #include "erlkaf_nif.h" #include "rdkafka.h" #include "macros.h" #include <functional> #include <signal.h> namespace { template <typename T> struct set_config_fun { std::function<rd_kafka_conf_res_t (T *conf, const char *name, const char *value, char *errstr, size_t errstr_size)> set_value; }; const set_config_fun<rd_kafka_topic_conf_t> kTopicConfFuns = { rd_kafka_topic_conf_set }; const set_config_fun<rd_kafka_conf_t> kKafkaConfFuns = { rd_kafka_conf_set }; template <typename T> ERL_NIF_TERM parse_config(ErlNifEnv* env, ERL_NIF_TERM list, T* conf, set_config_fun<T> fun) { if(!enif_is_list(env, list)) return make_bad_options(env, list); char errstr[512]; ERL_NIF_TERM head; const ERL_NIF_TERM *items; int arity; while(enif_get_list_cell(env, list, &head, &list)) { if(!enif_get_tuple(env, head, &arity, &items) || arity != 2) return make_bad_options(env, head); std::string key; std::string value; if(!get_string(env, items[0], &key)) return make_bad_options(env, head); if(!get_string(env, items[1], &value)) return make_bad_options(env, head); if(fun.set_value(conf, key.c_str(), value.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) return make_error(env, errstr); } return ATOMS.atomOk; } bool appy_kafka_default_config(rd_kafka_conf_t* config) { if(rd_kafka_conf_set(config, "enable.auto.commit", "true", NULL, 0) != RD_KAFKA_CONF_OK) return false; if(rd_kafka_conf_set(config, "enable.auto.offset.store", "false", NULL, 0) != RD_KAFKA_CONF_OK) return false; if(rd_kafka_conf_set(config, "enable.partition.eof", "false", NULL, 0) != RD_KAFKA_CONF_OK) return false; #ifdef SIGIO //quick termination char tmp[128]; snprintf(tmp, sizeof(tmp), "%i", SIGIO); if(rd_kafka_conf_set(config, "internal.termination.signal", tmp, NULL, 0) != RD_KAFKA_CONF_OK) return false; #endif return true; } bool appy_topic_default_config(rd_kafka_topic_conf_t* config) { UNUSED(config); return true; } } ERL_NIF_TERM parse_topic_config(ErlNifEnv* env, ERL_NIF_TERM list, rd_kafka_topic_conf_t* conf) { if(!appy_topic_default_config(conf)) return make_error(env, "failed to apply default topic config"); return parse_config(env, list, conf, kTopicConfFuns); } ERL_NIF_TERM parse_kafka_config(ErlNifEnv* env, ERL_NIF_TERM list, rd_kafka_conf_t* conf) { if(!appy_kafka_default_config(conf)) return make_error(env, "failed to apply default kafka config"); return parse_config(env, list, conf, kKafkaConfFuns); } <|endoftext|>
<commit_before>#include "common.hpp" #include <boost/filesystem/fstream.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/serialization/set.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/string.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/shared_ptr.hpp> #include "muzdb.hpp" #include "parser.hpp" using namespace boost::filesystem; namespace boost { namespace serialization { template<class Archive> inline void serialize(Archive &ar, muzdb::TimeInfo &t, const unsigned int) { ar & t.start; ar & t.duration; ar & t.end; } struct track { path filename; path ref_filename; std::map<std::string, std::string> fields; muzdb::TimeInfo time; template<class Archive> inline void serialize(Archive &ar, const unsigned int) { ar & filename; ar & ref_filename; ar & fields; ar & time; } }; template<class Archive> inline void save(Archive &ar, const path &t, const unsigned int) { ar << t.wstring(); } template<class Archive> inline void load(Archive &ar, path &t, const unsigned int) { std::wstring str; ar >> str; t = str; } template<class Archive> inline void serialize(Archive &ar, path &t, const unsigned int file_version) { boost::serialization::split_free(ar, t, file_version); } template<class Archive> inline void save(Archive &ar, const muzdb::Metadata &t, const unsigned int) { std::vector<track> tmp; BOOST_FOREACH(BOOST_TYPEOF(*t.begin()) it, t) { tmp.push_back((track) { it->filename(), it->ref_filename(), it->fields(), it->time() }); } ar << tmp; } template<class Archive> inline void load(Archive &ar, muzdb::Metadata &t, const unsigned int) { std::vector<track> tmp; ar >> tmp; BOOST_FOREACH(track &m, tmp) { BOOST_AUTO(trk, boost::make_shared<muzdb::MTrack>(m.filename, m.ref_filename)); trk->set(m.fields); trk->set_time(m.time); t.push_back(trk); } } template<class Archive> inline void serialize(Archive &ar, muzdb::Metadata &t, const unsigned int file_version) { boost::serialization::split_free(ar, t, file_version); } } // namespace serialization } // namespace boost namespace muzdb { static Metadata parse(const ParserGen &pg) { Metadata meta; BOOST_AUTO(ps, pg()); BOOST_FOREACH(boost::shared_ptr<Parser> par, ps) { try { par->parse(); BOOST_AUTO(res, par->metadata()); meta.insert(meta.end(), res.begin(), res.end()); } catch (...) { } } return meta; } MDB::MDB(const Path &root) : root_path(root) { av_register_all(); } const Path &MDB::root() const { return root_path; } void MDB::new_file(const Path &p) { BOOST_AUTO(meta, parse(ParserGen(p))); BOOST_AUTO(file, std::make_pair(p, meta)); if (mcallback) { mcallback->new_file(file); } metadata.insert(file); } void MDB::del_file(const Path &p) { BOOST_AUTO(file, metadata.find(p)); if (file == metadata.end()) { return; } if (mcallback) { mcallback->del_file(*file); } metadata.erase(file); } void MDB::mod_file(const Path &p) { BOOST_AUTO(meta, parse(ParserGen(p))); BOOST_AUTO(file, std::make_pair(p, meta)); BOOST_AUTO(prev, metadata.find(p)); if (prev == metadata.end()) { if (mcallback) { mcallback->new_file(file); } metadata.insert(file); } else { if (mcallback) { mcallback->mod_file(*prev, file); } metadata.erase(prev); metadata.insert(file); } } void MDB::update() { BOOST_TYPEOF(mtimes) ntimes; for (BOOST_AUTO(it, recursive_directory_iterator(root_path, symlink_option::recurse)); it != recursive_directory_iterator(); ++it) { BOOST_AUTO(p, it->path()); if (!exists(p)) { continue; } BOOST_AUTO(ext, boost::locale::to_lower(p.extension().string())); if (config.extensions.find(ext) == config.extensions.end()) continue; ntimes.insert(std::make_pair(p, last_write_time(p))); } BOOST_AUTO(mit, mtimes.begin()); BOOST_AUTO(nit, ntimes.begin()); while (!(mit == mtimes.end() && nit == ntimes.end())) { if (mit == mtimes.end()) { new_file(nit->first); ++nit; } else if (nit == ntimes.end()) { del_file(mit->first); ++mit; } else { int cmp = nit->first.compare(mit->first); if (cmp > 0) { del_file(mit->first); ++mit; } else if (cmp < 0) { new_file(nit->first); ++nit; } else { if (nit->second != mit->second) { mod_file(nit->first); } ++mit; ++nit; } } } mtimes.swap(ntimes); } void MDB::save(const Path &p) { ofstream ofs(p, std::ios_base::out | std::ios_base::binary); boost::archive::binary_oarchive oa(ofs); oa << mtimes; oa << metadata; } void MDB::load(const Path &p) { ifstream ifs(p, std::ios_base::in | std::ios_base::binary); boost::archive::binary_iarchive ia(ifs); ia >> mtimes; ia >> metadata; } void MDB::callback(boost::shared_ptr<MuzdbCallback> cb) { this->mcallback = cb; } const std::map<Path, Metadata> &MDB::get() const { return metadata; } MuzdbConfig &MDB::get_config() { return config; } boost::shared_ptr<Muzdb> muzdb_init(const Path &p) { return boost::make_shared<MDB>(p); } } // namespace muzdb <commit_msg>Fix locale<commit_after>#include "common.hpp" #include <boost/filesystem/fstream.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/serialization/set.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/string.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/shared_ptr.hpp> #include "muzdb.hpp" #include "parser.hpp" using namespace boost::filesystem; namespace boost { namespace serialization { template<class Archive> inline void serialize(Archive &ar, muzdb::TimeInfo &t, const unsigned int) { ar & t.start; ar & t.duration; ar & t.end; } struct track { path filename; path ref_filename; std::map<std::string, std::string> fields; muzdb::TimeInfo time; template<class Archive> inline void serialize(Archive &ar, const unsigned int) { ar & filename; ar & ref_filename; ar & fields; ar & time; } }; template<class Archive> inline void save(Archive &ar, const path &t, const unsigned int) { ar << t.wstring(); } template<class Archive> inline void load(Archive &ar, path &t, const unsigned int) { std::wstring str; ar >> str; t = str; } template<class Archive> inline void serialize(Archive &ar, path &t, const unsigned int file_version) { boost::serialization::split_free(ar, t, file_version); } template<class Archive> inline void save(Archive &ar, const muzdb::Metadata &t, const unsigned int) { std::vector<track> tmp; BOOST_FOREACH(BOOST_TYPEOF(*t.begin()) it, t) { tmp.push_back((track) { it->filename(), it->ref_filename(), it->fields(), it->time() }); } ar << tmp; } template<class Archive> inline void load(Archive &ar, muzdb::Metadata &t, const unsigned int) { std::vector<track> tmp; ar >> tmp; BOOST_FOREACH(track &m, tmp) { BOOST_AUTO(trk, boost::make_shared<muzdb::MTrack>(m.filename, m.ref_filename)); trk->set(m.fields); trk->set_time(m.time); t.push_back(trk); } } template<class Archive> inline void serialize(Archive &ar, muzdb::Metadata &t, const unsigned int file_version) { boost::serialization::split_free(ar, t, file_version); } } // namespace serialization } // namespace boost namespace muzdb { static Metadata parse(const ParserGen &pg) { Metadata meta; BOOST_AUTO(ps, pg()); BOOST_FOREACH(boost::shared_ptr<Parser> par, ps) { try { par->parse(); BOOST_AUTO(res, par->metadata()); meta.insert(meta.end(), res.begin(), res.end()); } catch (...) { } } return meta; } MDB::MDB(const Path &root) : root_path(root) { av_register_all(); std::locale::global(boost::locale::generator()("")); } const Path &MDB::root() const { return root_path; } void MDB::new_file(const Path &p) { BOOST_AUTO(meta, parse(ParserGen(p))); BOOST_AUTO(file, std::make_pair(p, meta)); if (mcallback) { mcallback->new_file(file); } metadata.insert(file); } void MDB::del_file(const Path &p) { BOOST_AUTO(file, metadata.find(p)); if (file == metadata.end()) { return; } if (mcallback) { mcallback->del_file(*file); } metadata.erase(file); } void MDB::mod_file(const Path &p) { BOOST_AUTO(meta, parse(ParserGen(p))); BOOST_AUTO(file, std::make_pair(p, meta)); BOOST_AUTO(prev, metadata.find(p)); if (prev == metadata.end()) { if (mcallback) { mcallback->new_file(file); } metadata.insert(file); } else { if (mcallback) { mcallback->mod_file(*prev, file); } metadata.erase(prev); metadata.insert(file); } } void MDB::update() { BOOST_TYPEOF(mtimes) ntimes; for (BOOST_AUTO(it, recursive_directory_iterator(root_path, symlink_option::recurse)); it != recursive_directory_iterator(); ++it) { BOOST_AUTO(p, it->path()); if (!exists(p)) { continue; } BOOST_AUTO(ext, boost::locale::to_lower(p.extension().string())); if (config.extensions.find(ext) == config.extensions.end()) continue; ntimes.insert(std::make_pair(p, last_write_time(p))); } BOOST_AUTO(mit, mtimes.begin()); BOOST_AUTO(nit, ntimes.begin()); while (!(mit == mtimes.end() && nit == ntimes.end())) { if (mit == mtimes.end()) { new_file(nit->first); ++nit; } else if (nit == ntimes.end()) { del_file(mit->first); ++mit; } else { int cmp = nit->first.compare(mit->first); if (cmp > 0) { del_file(mit->first); ++mit; } else if (cmp < 0) { new_file(nit->first); ++nit; } else { if (nit->second != mit->second) { mod_file(nit->first); } ++mit; ++nit; } } } mtimes.swap(ntimes); } void MDB::save(const Path &p) { ofstream ofs(p, std::ios_base::out | std::ios_base::binary); boost::archive::binary_oarchive oa(ofs); oa << mtimes; oa << metadata; } void MDB::load(const Path &p) { ifstream ifs(p, std::ios_base::in | std::ios_base::binary); boost::archive::binary_iarchive ia(ifs); ia >> mtimes; ia >> metadata; } void MDB::callback(boost::shared_ptr<MuzdbCallback> cb) { this->mcallback = cb; } const std::map<Path, Metadata> &MDB::get() const { return metadata; } MuzdbConfig &MDB::get_config() { return config; } boost::shared_ptr<Muzdb> muzdb_init(const Path &p) { return boost::make_shared<MDB>(p); } } // namespace muzdb <|endoftext|>
<commit_before>/* * the/utils.cpp * * Copyright (c) 2012, TheLib Team (http://www.thelib.org/license) * 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 TheLib, TheLib Team, 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 THELIB TEAM 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 THELIB TEAM 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. */ /* * utils.cpp * * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten. */ #include "mmcore/thecam/utility/utils.h" #include "mmcore/thecam/utility/assert.h" // TEST-includes #include "mmcore/thecam/arcball_manipulator.h" #include "mmcore/thecam/camera.h" #include "mmcore/thecam/camera_maths.h" #include "mmcore/thecam/camera_snapshot.h" #include "mmcore/thecam/functions.h" #include "mmcore/thecam/head_tracking_manipulator.h" #include "mmcore/thecam/manipulator_base.h" #include "mmcore/thecam/minimal_camera_state.h" #include "mmcore/thecam/processed_synchronisable_property.h" #include "mmcore/thecam/property.h" #include "mmcore/thecam/property_base.h" #include "mmcore/thecam/synchronisable_property.h" #include "mmcore/thecam/translate_manipulator.h" #include "mmcore/thecam/types.h" #include "mmcore/thecam/view_frustum.h" /* * megamol::core::thecam::utility::uint_rle_encode */ bool megamol::core::thecam::utility::uint_rle_encode(unsigned char *dst, unsigned int &len, uint64_t src) { unsigned int pos = 0; if (src == 0) { if (len == 0) return false; // dst insufficient dst[0] = 0; pos = 1; } else while (src > 0) { if (pos == len) return false; // dst insufficient dst[pos++] = (src & 0x7F) + ((src > 128) ? 128 : 0); src >>= 7; } len = pos; return true; } /* * megamol::core::thecam::utility::uint_rle_decode */ bool megamol::core::thecam::utility::uint_rle_decode(uint64_t &dst, unsigned char *src, unsigned int &len) { unsigned int pos = 0; uint64_t mult = 0; dst = 0; do { if ((pos == 10) // would be reading the 11th byte || (pos == len)) return false; // insufficient data dst += (static_cast<uint64_t>(src[pos++] & 0x7F) << mult); mult += 7; } while (src[pos - 1] >= 128); len = pos; return true; } <commit_msg>remove unnecessary includes<commit_after>/* * the/utils.cpp * * Copyright (c) 2012, TheLib Team (http://www.thelib.org/license) * 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 TheLib, TheLib Team, 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 THELIB TEAM 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 THELIB TEAM 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. */ /* * utils.cpp * * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten. */ #include "mmcore/thecam/utility/utils.h" #include "mmcore/thecam/utility/assert.h" /* * megamol::core::thecam::utility::uint_rle_encode */ bool megamol::core::thecam::utility::uint_rle_encode(unsigned char *dst, unsigned int &len, uint64_t src) { unsigned int pos = 0; if (src == 0) { if (len == 0) return false; // dst insufficient dst[0] = 0; pos = 1; } else while (src > 0) { if (pos == len) return false; // dst insufficient dst[pos++] = (src & 0x7F) + ((src > 128) ? 128 : 0); src >>= 7; } len = pos; return true; } /* * megamol::core::thecam::utility::uint_rle_decode */ bool megamol::core::thecam::utility::uint_rle_decode(uint64_t &dst, unsigned char *src, unsigned int &len) { unsigned int pos = 0; uint64_t mult = 0; dst = 0; do { if ((pos == 10) // would be reading the 11th byte || (pos == len)) return false; // insufficient data dst += (static_cast<uint64_t>(src[pos++] & 0x7F) << mult); mult += 7; } while (src[pos - 1] >= 128); len = pos; return true; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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 2015 Scylla DB */ #include "systemwide_memory_barrier.hh" #include "cacheline.hh" #include "../util/log.hh" #include <sys/mman.h> #include <unistd.h> #include <cassert> #include <atomic> #include <mutex> #if SEASTAR_HAS_MEMBARRIER #include <linux/membarrier.h> #include <sys/syscall.h> #include <unistd.h> #endif namespace seastar { #ifdef SEASTAR_HAS_MEMBARRIER static bool has_native_membarrier = [] { auto r = syscall(SYS_membarrier, MEMBARRIER_CMD_QUERY, 0); if (r == -1) { return false; } int needed = MEMBARRIER_CMD_PRIVATE_EXPEDITED | MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED; if ((r & needed) != needed) { return false; } syscall(SYS_membarrier, MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED, 0); return true; }(); static bool try_native_membarrier() { if (has_native_membarrier) { syscall(SYS_membarrier, MEMBARRIER_CMD_PRIVATE_EXPEDITED, 0); return true; } return false; } #else static bool try_native_membarrier() { return false; } #endif // cause all threads to invoke a full memory barrier void systemwide_memory_barrier() { if (try_native_membarrier()) { return; } // FIXME: use sys_membarrier() when available static thread_local char* mem = [] { void* mem = mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) ; assert(mem != MAP_FAILED); return reinterpret_cast<char*>(mem); }(); int r1 = mprotect(mem, getpagesize(), PROT_READ | PROT_WRITE); assert(r1 == 0); // Force page into memory to avoid next mprotect() attempting to be clever *mem = 3; // Force page into memory // lower permissions to force kernel to send IPI to all threads, with // a side effect of executing a memory barrier on those threads // FIXME: does this work on ARM? int r2 = mprotect(mem, getpagesize(), PROT_READ); assert(r2 == 0); } struct alignas(cache_line_size) aligned_flag { std::atomic<bool> flag; bool try_lock() { return !flag.exchange(true, std::memory_order_relaxed); } void unlock() { flag.store(false, std::memory_order_relaxed); } }; static aligned_flag membarrier_lock; bool try_systemwide_memory_barrier() { if (try_native_membarrier()) { return true; } #ifdef __aarch64__ // Some (not all) ARM processors can broadcast TLB invalidations using the // TLBI instruction. On those, the mprotect trick won't work. static std::once_flag warn_once; extern logger seastar_logger; std::call_once(warn_once, [] { seastar_logger.warn("membarrier(MEMBARRIER_CMD_PRIVATE_EXPEDITED) is not available, reactor will not sleep when idle. Upgrade to Linux 4.14 or later"); }); return false; #endif if (!membarrier_lock.try_lock()) { return false; } systemwide_memory_barrier(); membarrier_lock.unlock(); return true; } } <commit_msg>systemwide_memory_barrier: use madvise(MADV_DONTNEED) instead of mprotect()<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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 2015 Scylla DB */ #include "systemwide_memory_barrier.hh" #include "cacheline.hh" #include "../util/log.hh" #include <sys/mman.h> #include <unistd.h> #include <cassert> #include <atomic> #include <mutex> #if SEASTAR_HAS_MEMBARRIER #include <linux/membarrier.h> #include <sys/syscall.h> #include <unistd.h> #endif namespace seastar { #ifdef SEASTAR_HAS_MEMBARRIER static bool has_native_membarrier = [] { auto r = syscall(SYS_membarrier, MEMBARRIER_CMD_QUERY, 0); if (r == -1) { return false; } int needed = MEMBARRIER_CMD_PRIVATE_EXPEDITED | MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED; if ((r & needed) != needed) { return false; } syscall(SYS_membarrier, MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED, 0); return true; }(); static bool try_native_membarrier() { if (has_native_membarrier) { syscall(SYS_membarrier, MEMBARRIER_CMD_PRIVATE_EXPEDITED, 0); return true; } return false; } #else static bool try_native_membarrier() { return false; } #endif // cause all threads to invoke a full memory barrier void systemwide_memory_barrier() { if (try_native_membarrier()) { return; } // FIXME: use sys_membarrier() when available static thread_local char* mem = [] { void* mem = mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) ; assert(mem != MAP_FAILED); return reinterpret_cast<char*>(mem); }(); // Force page into memory to make madvise() have real work to do *mem = 3; // Evict page to force kernel to send IPI to all threads, with // a side effect of executing a memory barrier on those threads // FIXME: does this work on ARM? int r2 = madvise(mem, getpagesize(), MADV_DONTNEED); assert(r2 == 0); } bool try_systemwide_memory_barrier() { if (try_native_membarrier()) { return true; } #ifdef __aarch64__ // Some (not all) ARM processors can broadcast TLB invalidations using the // TLBI instruction. On those, the mprotect trick won't work. static std::once_flag warn_once; extern logger seastar_logger; std::call_once(warn_once, [] { seastar_logger.warn("membarrier(MEMBARRIER_CMD_PRIVATE_EXPEDITED) is not available, reactor will not sleep when idle. Upgrade to Linux 4.14 or later"); }); return false; #endif systemwide_memory_barrier(); return true; } } <|endoftext|>
<commit_before>#include <franka_gripper/franka_gripper.h> #include <cmath> #include <functional> #include <thread> #include <ros/node_handle.h> #include <franka/exception.h> #include <franka/gripper_state.h> #include <franka_gripper/GraspAction.h> #include <franka_gripper/HomingAction.h> #include <franka_gripper/MoveAction.h> #include <franka_gripper/StopAction.h> namespace franka_gripper { using actionlib::SimpleActionServer; GripperServer::GripperServer(franka::Gripper& gripper, ros::NodeHandle& node_handle, double width_tolerance, double default_speed, double newton_to_m_ampere_factor) : gripper_(&gripper), gripper_command_action_server_( node_handle, "gripper_action", std::bind(&GripperServer::gripperCommandexecuteCallback, this, std::placeholders::_1), false), width_tolerance_(width_tolerance), default_speed_(default_speed), newton_to_m_ampere_factor_(newton_to_m_ampere_factor) { gripper_command_action_server_.start(); } bool GripperServer::getGripperState(franka::GripperState* state) { try { *state = gripper_->readOnce(); } catch (const franka::Exception& ex) { ROS_ERROR_STREAM( "GripperServer: Exception reading gripper state: " << ex.what()); return false; } return true; } bool GripperServer::gripperCommandHandler( const control_msgs::GripperCommandGoalConstPtr& goal, franka::GripperState* state) { *state = gripper_->readOnce(); if (goal->command.position > state->max_width || goal->command.position < 0.0) { ROS_ERROR_STREAM( "GripperServer: Commanding out of range width! max_width = " << state->max_width << " command = " << goal->command.position); return false; } if (goal->command.position >= state->width) { gripper_->move(goal->command.position, default_speed_); *state = gripper_->readOnce(); if (std::fabs(state->width - goal->command.position) < width_tolerance_) { return true; } ROS_WARN("GripperServer: Move failed"); } else { gripper_->grasp(goal->command.position, default_speed_, goal->command.max_effort * newton_to_m_ampere_factor_); *state = gripper_->readOnce(); if (state->is_grasped) { return true; } gripper_->stop(); ROS_WARN("GripperServer: Grasp failed"); } return false; } void GripperServer::gripperCommandexecuteCallback( const control_msgs::GripperCommandGoalConstPtr& goal) { franka::GripperState state; try { if (gripperCommandHandler(goal, &state)) { control_msgs::GripperCommandResult result; result.effort = 0.0; result.position = state.width; result.reached_goal = true; result.stalled = false; gripper_command_action_server_.setSucceeded(result); return; } } catch (const franka::Exception& ex) { ROS_ERROR_STREAM("" << ex.what()); } gripper_command_action_server_.setAborted(); } bool move(franka::Gripper* gripper, double width_tolerance, const MoveGoalConstPtr& goal) { gripper->move(goal->width, goal->speed); if (std::fabs(gripper->readOnce().width - goal->width) < width_tolerance) { return true; } return false; } bool homing(franka::Gripper* gripper, const HomingGoalConstPtr& /*goal*/) { gripper->homing(); return true; } bool stop(franka::Gripper* gripper, const StopGoalConstPtr& /*goal*/) { gripper->stop(); return true; } bool grasp(franka::Gripper* gripper, const GraspGoalConstPtr& goal) { gripper->grasp(goal->width, goal->speed, goal->max_current); return gripper->readOnce().is_grasped; } } // namespace franka_gripper <commit_msg>linter fix<commit_after>#include <franka_gripper/franka_gripper.h> #include <cmath> #include <functional> #include <thread> #include <ros/node_handle.h> #include <franka/exception.h> #include <franka/gripper_state.h> #include <franka_gripper/GraspAction.h> #include <franka_gripper/HomingAction.h> #include <franka_gripper/MoveAction.h> #include <franka_gripper/StopAction.h> namespace franka_gripper { using actionlib::SimpleActionServer; GripperServer::GripperServer(franka::Gripper& gripper, ros::NodeHandle& node_handle, double width_tolerance, double default_speed, double newton_to_m_ampere_factor) : gripper_(&gripper), gripper_command_action_server_( node_handle, "gripper_action", std::bind(&GripperServer::gripperCommandexecuteCallback, this, std::placeholders::_1), false), width_tolerance_(width_tolerance), default_speed_(default_speed), newton_to_m_ampere_factor_(newton_to_m_ampere_factor) { gripper_command_action_server_.start(); } bool GripperServer::getGripperState(franka::GripperState* state) { try { *state = gripper_->readOnce(); } catch (const franka::Exception& ex) { ROS_ERROR_STREAM( "GripperServer: Exception reading gripper state: " << ex.what()); return false; } return true; } bool GripperServer::gripperCommandHandler( const control_msgs::GripperCommandGoalConstPtr& goal, franka::GripperState* state) { *state = gripper_->readOnce(); if (goal->command.position > state->max_width || goal->command.position < 0.0) { ROS_ERROR_STREAM( "GripperServer: Commanding out of range width! max_width = " << state->max_width << " command = " << goal->command.position); return false; } if (goal->command.position >= state->width) { gripper_->move(goal->command.position, default_speed_); *state = gripper_->readOnce(); if (std::fabs(state->width - goal->command.position) < width_tolerance_) { return true; } ROS_WARN("GripperServer: Move failed"); } else { gripper_->grasp(goal->command.position, default_speed_, goal->command.max_effort * newton_to_m_ampere_factor_); *state = gripper_->readOnce(); if (state->is_grasped) { return true; } gripper_->stop(); ROS_WARN("GripperServer: Grasp failed"); } return false; } void GripperServer::gripperCommandexecuteCallback( const control_msgs::GripperCommandGoalConstPtr& goal) { franka::GripperState state; try { if (gripperCommandHandler(goal, &state)) { control_msgs::GripperCommandResult result; result.effort = 0.0; result.position = state.width; result.reached_goal = static_cast<decltype(result.reached_goal)>(true); result.stalled = static_cast<decltype(result.stalled)>(false); gripper_command_action_server_.setSucceeded(result); return; } } catch (const franka::Exception& ex) { ROS_ERROR_STREAM("" << ex.what()); } gripper_command_action_server_.setAborted(); } bool move(franka::Gripper* gripper, double width_tolerance, const MoveGoalConstPtr& goal) { gripper->move(goal->width, goal->speed); if (std::fabs(gripper->readOnce().width - goal->width) < width_tolerance) { return true; } return false; } bool homing(franka::Gripper* gripper, const HomingGoalConstPtr& /*goal*/) { gripper->homing(); return true; } bool stop(franka::Gripper* gripper, const StopGoalConstPtr& /*goal*/) { gripper->stop(); return true; } bool grasp(franka::Gripper* gripper, const GraspGoalConstPtr& goal) { gripper->grasp(goal->width, goal->speed, goal->max_current); return gripper->readOnce().is_grasped; } } // namespace franka_gripper <|endoftext|>
<commit_before>#include "ninja.h" #include <getopt.h> #include <limits.h> #include <stdio.h> #include "build.h" #include "build_log.h" #include "parsers.h" #include "graphviz.h" option options[] = { { "help", no_argument, NULL, 'h' }, { } }; void usage() { fprintf(stderr, "usage: ninja [options] target\n" "\n" "options:\n" " -g output graphviz dot file for targets and exit\n" " -i FILE specify input build file [default=build.ninja]\n" " -n dry run (don't run commands but pretend they succeeded)\n" " -v show all command lines\n" ); } struct RealFileReader : public ManifestParser::FileReader { bool ReadFile(const string& path, string* content, string* err) { return ::ReadFile(path, content, err) == 0; } }; int main(int argc, char** argv) { BuildConfig config; const char* input_file = "build.ninja"; bool graph = false; int opt; while ((opt = getopt_long(argc, argv, "ghi:nv", options, NULL)) != -1) { switch (opt) { case 'g': graph = true; break; case 'i': input_file = optarg; break; case 'n': config.dry_run = true; break; case 'v': config.verbosity = BuildConfig::VERBOSE; break; case 'h': default: usage(); return 1; } } if (optind >= argc) { fprintf(stderr, "expected target to build\n"); usage(); return 1; } argv += optind; argc -= optind; char cwd[PATH_MAX]; if (!getcwd(cwd, sizeof(cwd))) { perror("getcwd"); return 1; } State state; RealFileReader file_reader; ManifestParser parser(&state, &file_reader); string err; if (!parser.Load(input_file, &err)) { fprintf(stderr, "error loading '%s': %s\n", input_file, err.c_str()); return 1; } if (graph) { GraphViz graph; graph.Start(); for (int i = 0; i < argc; ++i) graph.AddTarget(state.GetNode(argv[i])); graph.Finish(); return 0; } const char* kLogPath = ".ninja_log"; if (!state.build_log_->Load(kLogPath, &err)) { fprintf(stderr, "error loading build log: %s\n", err.c_str()); return 1; } if (!state.build_log_->OpenForWrite(kLogPath, &err)) { fprintf(stderr, "error opening build log: %s\n", err.c_str()); return 1; } Builder builder(&state, config); for (int i = 0; i < argc; ++i) { if (!builder.AddTarget(argv[i], &err)) { if (!err.empty()) { fprintf(stderr, "%s\n", err.c_str()); return 1; } else { // Added a target that is already up-to-date; not really // an error. } } } bool success = builder.Build(&err); if (!err.empty()) { printf("build stopped: %s.\n", err.c_str()); } return success ? 0 : 1; } <commit_msg>don't log commands in dry-run mode<commit_after>#include "ninja.h" #include <getopt.h> #include <limits.h> #include <stdio.h> #include "build.h" #include "build_log.h" #include "parsers.h" #include "graphviz.h" option options[] = { { "help", no_argument, NULL, 'h' }, { } }; void usage() { fprintf(stderr, "usage: ninja [options] target\n" "\n" "options:\n" " -g output graphviz dot file for targets and exit\n" " -i FILE specify input build file [default=build.ninja]\n" " -n dry run (don't run commands but pretend they succeeded)\n" " -v show all command lines\n" ); } struct RealFileReader : public ManifestParser::FileReader { bool ReadFile(const string& path, string* content, string* err) { return ::ReadFile(path, content, err) == 0; } }; int main(int argc, char** argv) { BuildConfig config; const char* input_file = "build.ninja"; bool graph = false; int opt; while ((opt = getopt_long(argc, argv, "ghi:nv", options, NULL)) != -1) { switch (opt) { case 'g': graph = true; break; case 'i': input_file = optarg; break; case 'n': config.dry_run = true; break; case 'v': config.verbosity = BuildConfig::VERBOSE; break; case 'h': default: usage(); return 1; } } if (optind >= argc) { fprintf(stderr, "expected target to build\n"); usage(); return 1; } argv += optind; argc -= optind; char cwd[PATH_MAX]; if (!getcwd(cwd, sizeof(cwd))) { perror("getcwd"); return 1; } State state; RealFileReader file_reader; ManifestParser parser(&state, &file_reader); string err; if (!parser.Load(input_file, &err)) { fprintf(stderr, "error loading '%s': %s\n", input_file, err.c_str()); return 1; } if (graph) { GraphViz graph; graph.Start(); for (int i = 0; i < argc; ++i) graph.AddTarget(state.GetNode(argv[i])); graph.Finish(); return 0; } const char* kLogPath = ".ninja_log"; if (!state.build_log_->Load(kLogPath, &err)) { fprintf(stderr, "error loading build log: %s\n", err.c_str()); return 1; } if (!config.dry_run && !state.build_log_->OpenForWrite(kLogPath, &err)) { fprintf(stderr, "error opening build log: %s\n", err.c_str()); return 1; } Builder builder(&state, config); for (int i = 0; i < argc; ++i) { if (!builder.AddTarget(argv[i], &err)) { if (!err.empty()) { fprintf(stderr, "%s\n", err.c_str()); return 1; } else { // Added a target that is already up-to-date; not really // an error. } } } bool success = builder.Build(&err); if (!err.empty()) { printf("build stopped: %s.\n", err.c_str()); } return success ? 0 : 1; } <|endoftext|>
<commit_before>// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh 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 <iostream> #include <fstream> #include <sstream> #include "boost/filesystem/operations.hpp" // includes boost/filesystem/path.hpp #include "boost/filesystem/fstream.hpp" // ditto #include <boost/algorithm/string.hpp> #include "Parameter.h" #include "Util.h" #include "InputFileStream.h" #include "UserMessage.h" using namespace std; PARAM_VEC &Parameter::AddParam(const string &paramName) { return m_setting[paramName]; } // default parameter values Parameter::Parameter() { AddParam("ttable-file"); AddParam("dtable-file"); AddParam("lmodel-file"); AddParam("ttable-limit"); AddParam("weight-d"); AddParam("weight-l"); AddParam("weight-t"); AddParam("weight-w"); AddParam("weight-generation"); AddParam("mapping"); AddParam("n-best-list"); AddParam("beam-threshold"); AddParam("distortion-limit"); AddParam("input-factors"); AddParam("mysql"); AddParam("input-file"); AddParam("cache-path"); AddParam("input-file"); AddParam("stack"); AddParam("verbose"); } // check if parameter settings make sense bool Parameter::Validate() { bool ret = true; // required parameters if (m_setting["ttable-file"].size() == 0) { UserMessage::Add("No phrase translation table (ttable-file)"); ret = false; } if (m_setting["lmodel-file"].size() == 0) { UserMessage::Add("No language model (lmodel-file)"); ret = false; } if (m_setting["lmodel-file"].size() != m_setting["weight-l"].size()) { stringstream errorMsg(""); errorMsg << static_cast<int>(m_setting["lmodel-file"].size()) << " language model files given (lmodel-file), but " << static_cast<int>(m_setting["weight-l"].size()) << " weights (weight-l)"; UserMessage::Add(errorMsg.str()); ret = false; } // do files exist? // phrase tables if (ret) ret = FilesExist("ttable-file", 3); // generation tables if (ret) ret = FilesExist("generation-file", 2); // language model if (ret) ret = FilesExist("lmodel-file", 3); return ret; } bool Parameter::FilesExist(const string &paramName, size_t tokenizeIndex) { using namespace boost::filesystem; typedef std::vector<std::string> StringVec; StringVec::const_iterator iter; PARAM_MAP::const_iterator iterParam = m_setting.find(paramName); if (iterParam == m_setting.end()) { // no param. therefore nothing to check return true; } const StringVec &pathVec = (*iterParam).second; for (iter = pathVec.begin() ; iter != pathVec.end() ; ++iter) { StringVec vec = Tokenize(*iter); if (tokenizeIndex > vec.size()) { stringstream errorMsg(""); errorMsg << "Expected " << tokenizeIndex << " tokens per" << " entry in '" << paramName << "', but only found " << vec.size(); UserMessage::Add(errorMsg.str()); return false; } const string &pathStr = vec[tokenizeIndex]; path filePath(pathStr, native); if (!exists(filePath)) { stringstream errorMsg(""); errorMsg << "File " << pathStr << " does not exists"; UserMessage::Add(errorMsg.str()); return false; } } return true; } // TODO arg parsing like this does not belong in the library, it belongs // in moses-cmd string Parameter::FindParam(const string &paramSwitch, int argc, char* argv[]) { for (int i = 0 ; i < argc ; i++) { if (string(argv[i]) == paramSwitch) { if (i+1 < argc) { return argv[i+1]; } else { stringstream errorMsg(""); errorMsg << "Option " << paramSwitch << " requires a parameter!"; UserMessage::Add(errorMsg.str()); // TODO return some sort of error, not the empty string } } } return ""; } void Parameter::OverwriteParam(const string &paramSwitch, const string &paramName, int argc, char* argv[]) { int startPos = -1; for (int i = 0 ; i < argc ; i++) { if (string(argv[i]) == paramSwitch) { startPos = i+1; break; } } if (startPos < 0) return; int index = 0; while (startPos < argc && string(argv[startPos]).substr(0,1) != "-") { if (m_setting[paramName].size() > (size_t)index) m_setting[paramName][index] = argv[startPos]; else m_setting[paramName].push_back(argv[startPos]); index++; startPos++; } } bool Parameter::LoadParam(int argc, char* argv[]) { // config file (-f) arg mandatory string configPath; if ( (configPath = FindParam("-f", argc, argv)) == "" && (configPath = FindParam("-config", argc, argv)) == "") { UserMessage::Add("No configuration file was specified. Use -config or -f"); return false; } else { if (!ReadConfigFile(configPath)) { UserMessage::Add("Could not read "+configPath); return false; } } string inFile = FindParam("-i", argc, argv); if (inFile != "") m_setting["input-file"].push_back(inFile); // overwrite weights OverwriteParam("-dl", "distortion-limit", argc, argv); OverwriteParam("-d", "weight-d", argc, argv); OverwriteParam("-lm", "weight-l", argc, argv); OverwriteParam("-tm", "weight-t", argc, argv); OverwriteParam("-w", "weight-w", argc, argv); OverwriteParam("-g", "weight-generation", argc, argv); OverwriteParam("-n-best-list", "n-best-list", argc, argv); OverwriteParam("-s", "stack", argc, argv); OverwriteParam("-v", "verbose", argc, argv); // check if parameters make sense return Validate(); } // read parameters from a configuration file bool Parameter::ReadConfigFile( string filePath ) { InputFileStream inFile(filePath); string line, paramName; while(getline(inFile, line)) { // comments size_t comPos = line.find_first_of("#"); if (comPos != string::npos) line = line.substr(0, comPos); // trim leading and trailing spaces/tabs boost::trim(line); if (line[0]=='[') { // new parameter for (size_t currPos = 0 ; currPos < line.size() ; currPos++) { if (line[currPos] == ']') { paramName = line.substr(1, currPos - 1); break; } } } else if (line != "") { // add value to parameter m_setting[paramName].push_back(line); } } return true; } <commit_msg>add some comments. test commit email<commit_after>// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh 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 <iostream> #include <fstream> #include <sstream> #include "boost/filesystem/operations.hpp" // includes boost/filesystem/path.hpp #include "boost/filesystem/fstream.hpp" // ditto #include <boost/algorithm/string.hpp> #include "Parameter.h" #include "Util.h" #include "InputFileStream.h" #include "UserMessage.h" using namespace std; PARAM_VEC &Parameter::AddParam(const string &paramName) { return m_setting[paramName]; } // default parameter values Parameter::Parameter() { AddParam("ttable-file"); AddParam("dtable-file"); AddParam("lmodel-file"); AddParam("ttable-limit"); AddParam("weight-d"); AddParam("weight-l"); AddParam("weight-t"); AddParam("weight-w"); AddParam("weight-generation"); AddParam("mapping"); AddParam("n-best-list"); AddParam("beam-threshold"); AddParam("distortion-limit"); AddParam("input-factors"); AddParam("mysql"); AddParam("input-file"); AddParam("cache-path"); AddParam("input-file"); AddParam("stack"); AddParam("verbose"); } // check if parameter settings make sense bool Parameter::Validate() { bool ret = true; // required parameters if (m_setting["ttable-file"].size() == 0) { UserMessage::Add("No phrase translation table (ttable-file)"); ret = false; } if (m_setting["lmodel-file"].size() == 0) { UserMessage::Add("No language model (lmodel-file)"); ret = false; } if (m_setting["lmodel-file"].size() != m_setting["weight-l"].size()) { stringstream errorMsg(""); errorMsg << static_cast<int>(m_setting["lmodel-file"].size()) << " language model files given (lmodel-file), but " << static_cast<int>(m_setting["weight-l"].size()) << " weights (weight-l)"; UserMessage::Add(errorMsg.str()); ret = false; } // do files exist? // phrase tables if (ret) ret = FilesExist("ttable-file", 3); // generation tables if (ret) ret = FilesExist("generation-file", 2); // language model if (ret) ret = FilesExist("lmodel-file", 3); return ret; } bool Parameter::FilesExist(const string &paramName, size_t tokenizeIndex) { using namespace boost::filesystem; typedef std::vector<std::string> StringVec; StringVec::const_iterator iter; PARAM_MAP::const_iterator iterParam = m_setting.find(paramName); if (iterParam == m_setting.end()) { // no param. therefore nothing to check return true; } const StringVec &pathVec = (*iterParam).second; for (iter = pathVec.begin() ; iter != pathVec.end() ; ++iter) { StringVec vec = Tokenize(*iter); if (tokenizeIndex > vec.size()) { stringstream errorMsg(""); errorMsg << "Expected " << tokenizeIndex << " tokens per" << " entry in '" << paramName << "', but only found " << vec.size(); UserMessage::Add(errorMsg.str()); return false; } const string &pathStr = vec[tokenizeIndex]; path filePath(pathStr, native); if (!exists(filePath)) { stringstream errorMsg(""); errorMsg << "File " << pathStr << " does not exists"; UserMessage::Add(errorMsg.str()); return false; } } return true; } // TODO arg parsing like this does not belong in the library, it belongs // in moses-cmd string Parameter::FindParam(const string &paramSwitch, int argc, char* argv[]) { for (int i = 0 ; i < argc ; i++) { if (string(argv[i]) == paramSwitch) { if (i+1 < argc) { return argv[i+1]; } else { stringstream errorMsg(""); errorMsg << "Option " << paramSwitch << " requires a parameter!"; UserMessage::Add(errorMsg.str()); // TODO return some sort of error, not the empty string } } } return ""; } void Parameter::OverwriteParam(const string &paramSwitch, const string &paramName, int argc, char* argv[]) { int startPos = -1; for (int i = 0 ; i < argc ; i++) { if (string(argv[i]) == paramSwitch) { startPos = i+1; break; } } if (startPos < 0) return; int index = 0; while (startPos < argc && string(argv[startPos]).substr(0,1) != "-") { if (m_setting[paramName].size() > (size_t)index) m_setting[paramName][index] = argv[startPos]; else m_setting[paramName].push_back(argv[startPos]); index++; startPos++; } } // TODO this should be renamed to have at least a plural name bool Parameter::LoadParam(int argc, char* argv[]) { // config file (-f) arg mandatory string configPath; if ( (configPath = FindParam("-f", argc, argv)) == "" && (configPath = FindParam("-config", argc, argv)) == "") { UserMessage::Add("No configuration file was specified. Use -config or -f"); return false; } else { if (!ReadConfigFile(configPath)) { UserMessage::Add("Could not read "+configPath); return false; } } string inFile = FindParam("-i", argc, argv); if (inFile != "") m_setting["input-file"].push_back(inFile); // overwrite weights OverwriteParam("-dl", "distortion-limit", argc, argv); OverwriteParam("-d", "weight-d", argc, argv); OverwriteParam("-lm", "weight-l", argc, argv); OverwriteParam("-tm", "weight-t", argc, argv); OverwriteParam("-w", "weight-w", argc, argv); OverwriteParam("-g", "weight-generation", argc, argv); OverwriteParam("-n-best-list", "n-best-list", argc, argv); OverwriteParam("-s", "stack", argc, argv); OverwriteParam("-v", "verbose", argc, argv); // check if parameters make sense return Validate(); } // read parameters from a configuration file bool Parameter::ReadConfigFile( string filePath ) { InputFileStream inFile(filePath); string line, paramName; while(getline(inFile, line)) { // comments size_t comPos = line.find_first_of("#"); if (comPos != string::npos) line = line.substr(0, comPos); // trim leading and trailing spaces/tabs boost::trim(line); if (line[0]=='[') { // new parameter for (size_t currPos = 0 ; currPos < line.size() ; currPos++) { if (line[currPos] == ']') { paramName = line.substr(1, currPos - 1); break; } } } else if (line != "") { // add value to parameter m_setting[paramName].push_back(line); } } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "noui.h" #include "ui_interface.h" #include "util.h" #include <cstdio> #include <stdint.h> #include <string> static bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { bool fSecure = style & CClientUIInterface::SECURE; style &= ~CClientUIInterface::SECURE; std::string strCaption; // Check for usage of predefined caption switch (style) { case CClientUIInterface::MSG_ERROR: strCaption += _("Error"); break; case CClientUIInterface::MSG_WARNING: strCaption += _("Warning"); break; case CClientUIInterface::MSG_INFORMATION: strCaption += _("Information"); break; default: strCaption += caption; // Use supplied caption (can be empty) } if (!fSecure) LogPrintf("%s: %s\n", strCaption, message); fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str()); return false; } static bool noui_ThreadSafeQuestion(const std::string& /* ignored interactive message */, const std::string& message, const std::string& caption, unsigned int style) { return noui_ThreadSafeMessageBox(message, caption, style); } static void noui_InitMessage(const std::string& message) { LogPrintf("init message: %s\n", message); } void noui_connect() { // Connect bitcoind signal handlers uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox); uiInterface.ThreadSafeQuestion.connect(noui_ThreadSafeQuestion); uiInterface.InitMessage.connect(noui_InitMessage); } <commit_msg>Fix an issue with upgrading encrypted 1.5.5 wallets from GuldenD. Because GuldenD has no UI the password prompt didn't show, log a message telling people how to work around this case.<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "noui.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <cstdio> #include <stdint.h> #include <string> static bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { bool fSecure = style & CClientUIInterface::SECURE; style &= ~CClientUIInterface::SECURE; std::string strCaption; // Check for usage of predefined caption switch (style) { case CClientUIInterface::MSG_ERROR: strCaption += _("Error"); break; case CClientUIInterface::MSG_WARNING: strCaption += _("Warning"); break; case CClientUIInterface::MSG_INFORMATION: strCaption += _("Information"); break; default: strCaption += caption; // Use supplied caption (can be empty) } if (!fSecure) LogPrintf("%s: %s\n", strCaption, message); fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str()); return false; } static bool noui_ThreadSafeQuestion(const std::string& /* ignored interactive message */, const std::string& message, const std::string& caption, unsigned int style) { return noui_ThreadSafeMessageBox(message, caption, style); } static void noui_InitMessage(const std::string& message) { LogPrintf("init message: %s\n", message); } #ifdef ENABLE_WALLET static void NotifyRequestUnlockS(CWallet* wallet, std::string reason) { SecureString passwd = GetArg("-unlockpasswd", "").c_str(); if (!passwd.empty()) { if (!wallet->Unlock(passwd)) { fprintf(stderr, "Wallet requested unlock but -unlockpasswd was invalid - please unlock via RPC or in the case of an upgrade temporarily set -unlockpasswd in Gulden.conf: reason [%s]\n", reason.c_str()); return; } } fprintf(stderr, "Wallet requested unlock but could not unlock - please unlock via RPC or in the case of an upgrade temporarily set -unlockpasswd in Gulden.conf: reason [%s]\n", reason.c_str()); } #endif void noui_connect() { // Connect bitcoind signal handlers uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox); uiInterface.ThreadSafeQuestion.connect(noui_ThreadSafeQuestion); uiInterface.InitMessage.connect(noui_InitMessage); #ifdef ENABLE_WALLET uiInterface.RequestUnlock.connect(boost::bind(NotifyRequestUnlockS, _1, _2)); #endif } <|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/sync/notifier/chrome_invalidation_client.h" #include <string> #include <vector> #include "base/compiler_specific.h" #include "base/logging.h" #include "chrome/browser/sync/notifier/cache_invalidation_packet_handler.h" #include "chrome/browser/sync/notifier/invalidation_util.h" #include "chrome/browser/sync/notifier/registration_manager.h" #include "chrome/browser/sync/syncable/model_type.h" #include "google/cacheinvalidation/invalidation-client-impl.h" namespace sync_notifier { ChromeInvalidationClient::Listener::~Listener() {} ChromeInvalidationClient::ChromeInvalidationClient() : chrome_system_resources_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), scoped_callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), handle_outbound_packet_callback_( scoped_callback_factory_.NewCallback( &ChromeInvalidationClient::HandleOutboundPacket)), listener_(NULL), state_writer_(NULL) { DCHECK(non_thread_safe_.CalledOnValidThread()); } ChromeInvalidationClient::~ChromeInvalidationClient() { DCHECK(non_thread_safe_.CalledOnValidThread()); Stop(); DCHECK(!listener_); DCHECK(!state_writer_); } void ChromeInvalidationClient::Start( const std::string& client_id, const std::string& state, Listener* listener, StateWriter* state_writer, base::WeakPtr<talk_base::Task> base_task) { DCHECK(non_thread_safe_.CalledOnValidThread()); Stop(); chrome_system_resources_.StartScheduler(); DCHECK(!listener_); DCHECK(listener); listener_ = listener; DCHECK(!state_writer_); DCHECK(state_writer); state_writer_ = state_writer; invalidation::ClientType client_type; client_type.set_type(invalidation::ClientType::CHROME_SYNC); // TODO(akalin): Use InvalidationClient::Create() once it supports // taking a ClientConfig. invalidation::ClientConfig client_config; // Bump up limits so that we reduce the number of registration // replies we get. client_config.max_registrations_per_message = 20; client_config.max_ops_per_message = 40; invalidation_client_.reset( new invalidation::InvalidationClientImpl( &chrome_system_resources_, client_type, client_id, client_config, this)); invalidation_client_->Start(state); invalidation::NetworkEndpoint* network_endpoint = invalidation_client_->network_endpoint(); CHECK(network_endpoint); network_endpoint->RegisterOutboundListener( handle_outbound_packet_callback_.get()); ChangeBaseTask(base_task); registration_manager_.reset( new RegistrationManager(invalidation_client_.get())); RegisterTypes(); } void ChromeInvalidationClient::ChangeBaseTask( base::WeakPtr<talk_base::Task> base_task) { DCHECK(invalidation_client_.get()); DCHECK(base_task.get()); cache_invalidation_packet_handler_.reset( new CacheInvalidationPacketHandler(base_task, invalidation_client_.get())); } void ChromeInvalidationClient::Stop() { DCHECK(non_thread_safe_.CalledOnValidThread()); if (!invalidation_client_.get()) { DCHECK(!cache_invalidation_packet_handler_.get()); return; } chrome_system_resources_.StopScheduler(); registration_manager_.reset(); cache_invalidation_packet_handler_.reset(); invalidation_client_.reset(); state_writer_ = NULL; listener_ = NULL; } void ChromeInvalidationClient::RegisterTypes() { DCHECK(non_thread_safe_.CalledOnValidThread()); // TODO(akalin): Make this configurable instead of listening to // notifications for all possible types. for (int i = syncable::FIRST_REAL_MODEL_TYPE; i < syncable::MODEL_TYPE_COUNT; ++i) { registration_manager_->RegisterType(syncable::ModelTypeFromInt(i)); } // TODO(akalin): This is a hack to make new sync data types work // with server-issued notifications. Remove this when it's not // needed anymore. registration_manager_->RegisterType(syncable::UNSPECIFIED); } void ChromeInvalidationClient::Invalidate( const invalidation::Invalidation& invalidation, invalidation::Closure* callback) { DCHECK(non_thread_safe_.CalledOnValidThread()); DCHECK(invalidation::IsCallbackRepeatable(callback)); VLOG(1) << "Invalidate: " << InvalidationToString(invalidation); syncable::ModelType model_type; if (ObjectIdToRealModelType(invalidation.object_id(), &model_type)) { listener_->OnInvalidate(model_type); } else { LOG(WARNING) << "Could not get invalidation model type; " << "invalidating everything"; listener_->OnInvalidateAll(); } RunAndDeleteClosure(callback); } void ChromeInvalidationClient::InvalidateAll( invalidation::Closure* callback) { DCHECK(non_thread_safe_.CalledOnValidThread()); DCHECK(invalidation::IsCallbackRepeatable(callback)); VLOG(1) << "InvalidateAll"; listener_->OnInvalidateAll(); RunAndDeleteClosure(callback); } void ChromeInvalidationClient::RegistrationStateChanged( const invalidation::ObjectId& object_id, invalidation::RegistrationState new_state, const invalidation::UnknownHint& unknown_hint) { DCHECK(non_thread_safe_.CalledOnValidThread()); VLOG(1) << "RegistrationStateChanged to " << new_state; if (new_state == invalidation::RegistrationState_UNKNOWN) { VLOG(1) << "is_transient=" << unknown_hint.is_transient() << ", message=" << unknown_hint.message(); } // TODO(akalin): Figure out something else to do if the failure // isn't transient. Even if it is transient, we may still want to // add exponential back-off or limit the number of attempts. syncable::ModelType model_type; if (ObjectIdToRealModelType(object_id, &model_type) && (new_state != invalidation::RegistrationState_REGISTERED)) { registration_manager_->MarkRegistrationLost(model_type); } else { LOG(WARNING) << "Could not get object id model type; ignoring"; } } void ChromeInvalidationClient::AllRegistrationsLost( invalidation::Closure* callback) { DCHECK(non_thread_safe_.CalledOnValidThread()); DCHECK(invalidation::IsCallbackRepeatable(callback)); VLOG(1) << "AllRegistrationsLost"; registration_manager_->MarkAllRegistrationsLost(); RunAndDeleteClosure(callback); } void ChromeInvalidationClient::RegistrationLost( const invalidation::ObjectId& object_id, invalidation::Closure* callback) { DCHECK(non_thread_safe_.CalledOnValidThread()); DCHECK(invalidation::IsCallbackRepeatable(callback)); VLOG(1) << "RegistrationLost: " << ObjectIdToString(object_id); syncable::ModelType model_type; if (ObjectIdToRealModelType(object_id, &model_type)) { registration_manager_->MarkRegistrationLost(model_type); } else { LOG(WARNING) << "Could not get object id model type; ignoring"; } RunAndDeleteClosure(callback); } void ChromeInvalidationClient::WriteState(const std::string& state) { DCHECK(non_thread_safe_.CalledOnValidThread()); CHECK(state_writer_); state_writer_->WriteState(state); } void ChromeInvalidationClient::HandleOutboundPacket( invalidation::NetworkEndpoint* const& network_endpoint) { DCHECK(non_thread_safe_.CalledOnValidThread()); CHECK(cache_invalidation_packet_handler_.get()); cache_invalidation_packet_handler_-> HandleOutboundPacket(network_endpoint); } } // namespace sync_notifier <commit_msg>[Sync] Fixed spurious warning being generated on registration loss<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/sync/notifier/chrome_invalidation_client.h" #include <string> #include <vector> #include "base/compiler_specific.h" #include "base/logging.h" #include "chrome/browser/sync/notifier/cache_invalidation_packet_handler.h" #include "chrome/browser/sync/notifier/invalidation_util.h" #include "chrome/browser/sync/notifier/registration_manager.h" #include "chrome/browser/sync/syncable/model_type.h" #include "google/cacheinvalidation/invalidation-client-impl.h" namespace sync_notifier { ChromeInvalidationClient::Listener::~Listener() {} ChromeInvalidationClient::ChromeInvalidationClient() : chrome_system_resources_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), scoped_callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), handle_outbound_packet_callback_( scoped_callback_factory_.NewCallback( &ChromeInvalidationClient::HandleOutboundPacket)), listener_(NULL), state_writer_(NULL) { DCHECK(non_thread_safe_.CalledOnValidThread()); } ChromeInvalidationClient::~ChromeInvalidationClient() { DCHECK(non_thread_safe_.CalledOnValidThread()); Stop(); DCHECK(!listener_); DCHECK(!state_writer_); } void ChromeInvalidationClient::Start( const std::string& client_id, const std::string& state, Listener* listener, StateWriter* state_writer, base::WeakPtr<talk_base::Task> base_task) { DCHECK(non_thread_safe_.CalledOnValidThread()); Stop(); chrome_system_resources_.StartScheduler(); DCHECK(!listener_); DCHECK(listener); listener_ = listener; DCHECK(!state_writer_); DCHECK(state_writer); state_writer_ = state_writer; invalidation::ClientType client_type; client_type.set_type(invalidation::ClientType::CHROME_SYNC); // TODO(akalin): Use InvalidationClient::Create() once it supports // taking a ClientConfig. invalidation::ClientConfig client_config; // Bump up limits so that we reduce the number of registration // replies we get. client_config.max_registrations_per_message = 20; client_config.max_ops_per_message = 40; invalidation_client_.reset( new invalidation::InvalidationClientImpl( &chrome_system_resources_, client_type, client_id, client_config, this)); invalidation_client_->Start(state); invalidation::NetworkEndpoint* network_endpoint = invalidation_client_->network_endpoint(); CHECK(network_endpoint); network_endpoint->RegisterOutboundListener( handle_outbound_packet_callback_.get()); ChangeBaseTask(base_task); registration_manager_.reset( new RegistrationManager(invalidation_client_.get())); RegisterTypes(); } void ChromeInvalidationClient::ChangeBaseTask( base::WeakPtr<talk_base::Task> base_task) { DCHECK(invalidation_client_.get()); DCHECK(base_task.get()); cache_invalidation_packet_handler_.reset( new CacheInvalidationPacketHandler(base_task, invalidation_client_.get())); } void ChromeInvalidationClient::Stop() { DCHECK(non_thread_safe_.CalledOnValidThread()); if (!invalidation_client_.get()) { DCHECK(!cache_invalidation_packet_handler_.get()); return; } chrome_system_resources_.StopScheduler(); registration_manager_.reset(); cache_invalidation_packet_handler_.reset(); invalidation_client_.reset(); state_writer_ = NULL; listener_ = NULL; } void ChromeInvalidationClient::RegisterTypes() { DCHECK(non_thread_safe_.CalledOnValidThread()); // TODO(akalin): Make this configurable instead of listening to // notifications for all possible types. for (int i = syncable::FIRST_REAL_MODEL_TYPE; i < syncable::MODEL_TYPE_COUNT; ++i) { registration_manager_->RegisterType(syncable::ModelTypeFromInt(i)); } // TODO(akalin): This is a hack to make new sync data types work // with server-issued notifications. Remove this when it's not // needed anymore. registration_manager_->RegisterType(syncable::UNSPECIFIED); } void ChromeInvalidationClient::Invalidate( const invalidation::Invalidation& invalidation, invalidation::Closure* callback) { DCHECK(non_thread_safe_.CalledOnValidThread()); DCHECK(invalidation::IsCallbackRepeatable(callback)); VLOG(1) << "Invalidate: " << InvalidationToString(invalidation); syncable::ModelType model_type; if (ObjectIdToRealModelType(invalidation.object_id(), &model_type)) { listener_->OnInvalidate(model_type); } else { LOG(WARNING) << "Could not get invalidation model type; " << "invalidating everything"; listener_->OnInvalidateAll(); } RunAndDeleteClosure(callback); } void ChromeInvalidationClient::InvalidateAll( invalidation::Closure* callback) { DCHECK(non_thread_safe_.CalledOnValidThread()); DCHECK(invalidation::IsCallbackRepeatable(callback)); VLOG(1) << "InvalidateAll"; listener_->OnInvalidateAll(); RunAndDeleteClosure(callback); } void ChromeInvalidationClient::RegistrationStateChanged( const invalidation::ObjectId& object_id, invalidation::RegistrationState new_state, const invalidation::UnknownHint& unknown_hint) { DCHECK(non_thread_safe_.CalledOnValidThread()); VLOG(1) << "RegistrationStateChanged: " << ObjectIdToString(object_id) << " " << new_state; if (new_state == invalidation::RegistrationState_UNKNOWN) { VLOG(1) << "is_transient=" << unknown_hint.is_transient() << ", message=" << unknown_hint.message(); } syncable::ModelType model_type; if (!ObjectIdToRealModelType(object_id, &model_type)) { LOG(WARNING) << "Could not get object id model type; ignoring"; return; } if (new_state != invalidation::RegistrationState_REGISTERED) { // TODO(akalin): Figure out something else to do if the failure // isn't transient. Even if it is transient, we may still want to // add exponential back-off or limit the number of attempts. registration_manager_->MarkRegistrationLost(model_type); } } void ChromeInvalidationClient::AllRegistrationsLost( invalidation::Closure* callback) { DCHECK(non_thread_safe_.CalledOnValidThread()); DCHECK(invalidation::IsCallbackRepeatable(callback)); VLOG(1) << "AllRegistrationsLost"; registration_manager_->MarkAllRegistrationsLost(); RunAndDeleteClosure(callback); } void ChromeInvalidationClient::RegistrationLost( const invalidation::ObjectId& object_id, invalidation::Closure* callback) { DCHECK(non_thread_safe_.CalledOnValidThread()); DCHECK(invalidation::IsCallbackRepeatable(callback)); VLOG(1) << "RegistrationLost: " << ObjectIdToString(object_id); syncable::ModelType model_type; if (ObjectIdToRealModelType(object_id, &model_type)) { registration_manager_->MarkRegistrationLost(model_type); } else { LOG(WARNING) << "Could not get object id model type; ignoring"; } RunAndDeleteClosure(callback); } void ChromeInvalidationClient::WriteState(const std::string& state) { DCHECK(non_thread_safe_.CalledOnValidThread()); CHECK(state_writer_); state_writer_->WriteState(state); } void ChromeInvalidationClient::HandleOutboundPacket( invalidation::NetworkEndpoint* const& network_endpoint) { DCHECK(non_thread_safe_.CalledOnValidThread()); CHECK(cache_invalidation_packet_handler_.get()); cache_invalidation_packet_handler_-> HandleOutboundPacket(network_endpoint); } } // namespace sync_notifier <|endoftext|>
<commit_before>#include "gtest/gtest.h" namespace { TEST(ProjectTest, ShouldSucceed) { EXPECT_EQ(1, 1); } } <commit_msg>Removed dummy project_test.cc<commit_after><|endoftext|>
<commit_before>/***************************************************************************** * common.hpp: Basic shared types & helpers ***************************************************************************** * Copyright © 2015 libvlcpp authors & VideoLAN * * Authors: Hugo Beauzée-Luyssen <[email protected]> * Jonathan Calmels <[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.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 program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef LIBVLC_CXX_COMMON_H #define LIBVLC_CXX_COMMON_H #include <vlc/vlc.h> #include <cassert> #include <memory> namespace VLC { class Media; using MediaPtr = std::shared_ptr<Media>; // Work around cross class dependencies // Class A needs to access B's internal pointer // Class B needs to access A's internal pointer // By using a template function to do this, we're delegating // the access to both classes' guts to a later point, when the compiler // already knows everything it needs. // The only drawback is that we can't return decltype(ptr->get()), since when // the compiler checks for the prototype, it hasn't parsed all the declarations yet. template <typename TYPE, typename REF> TYPE* getInternalPtr(const REF& ref) { return ref.get(); } inline std::unique_ptr<char, void (*)(void*)> wrapCStr(char* str) { return std::unique_ptr<char, void(*)(void*)>( str, [](void* ptr) { libvlc_free(ptr); } ); } // Kudos to 3xxO for the signature_match helper template <typename, typename, typename = void> struct signature_match : std::false_type {}; template <typename Func, typename Ret, typename... Args> struct signature_match<Func, Ret(Args...), typename std::enable_if< std::is_convertible< decltype(std::declval<Func>()(std::declval<Args>()...)), Ret >::value // true or false >::type // void or SFINAE > : std::true_type {}; template <typename Func, typename Ret, typename... Args> struct signature_match_or_nullptr : std::integral_constant<bool, signature_match<Func, Ret, Args...>::value || std::is_same<Func, std::nullptr_t>::value > { }; struct CallbackHandlerBase { virtual ~CallbackHandlerBase() = default; }; template <typename Func> struct CallbackHandler : public CallbackHandlerBase { CallbackHandler(Func&& f) : func( std::forward<Func>( f ) ) {} Func func; }; template <int NbEvent> struct EventOwner { std::array<std::shared_ptr<CallbackHandlerBase>, NbEvent> callbacks; protected: EventOwner() = default; }; template <int Idx, typename Func, typename... Args> struct CallbackWrapper; // We assume that any callback will take a void* opaque as its first parameter. // We intercept this parameter, and use it to fetch the list of user provided // functions. Once we know what function to call, we forward the rest of the // parameters. // Using partial specialization also allows us to get the list of the expected // callback parameters automatically, rather than having to specify them. template <int Idx, typename Func, typename Ret, typename... Args> struct CallbackWrapper<Idx, Func, Ret(*)(void*, Args...)> { using Wrapped = Ret(void*, Args...); template <int NbEvents> static Wrapped* wrap(EventOwner<NbEvents>* owner, Func&& func) { owner->callbacks[Idx] = std::shared_ptr<CallbackHandlerBase>( new CallbackHandler<Func>( std::forward<Func>( func ) ) ); return [](void* opaque, Args... args) -> Ret { auto self = reinterpret_cast<EventOwner<NbEvents>*>(opaque); assert(self->callbacks[Idx].get()); auto cbHandler = static_cast<CallbackHandler<Func>*>( self->callbacks[Idx].get() ); return cbHandler->func( std::forward<Args>(args)... ); }; } }; // Special handling for events with a void** opaque first parameter. // We fetch it and do our business with it, then forward the parameters // to the user callback, without this opaque param. template <int Idx, typename Func, typename Ret, typename... Args> struct CallbackWrapper<Idx, Func, Ret(*)(void**, Args...)> { using Wrapped = Ret(void**, Args...); template <int NbEvents> static Wrapped* wrap(EventOwner<NbEvents>* owner, Func&& func) { owner->callbacks[Idx] = std::shared_ptr<CallbackHandlerBase>( new CallbackHandler<Func>( std::forward<Func>( func ) ) ); return [](void** opaque, Args... args) -> Ret { auto self = reinterpret_cast<EventOwner<NbEvents>*>(*opaque); assert(self->callbacks[Idx].get()); auto cbHandler = static_cast<CallbackHandler<Func>*>( self->callbacks[Idx].get() ); return cbHandler->func( std::forward<Args>(args)... ); }; } }; // Specialization to handle null callbacks at build time. // We could try to compare any "Func" against nullptr at runtime, though // since Func is a template type, which roughly has to satisfy the "Callable" concept, // it could be an instance of a function object, which doesn't compare nicely against nullptr. // Using the specialization at build time is easier and performs better. template <int Idx, typename... Args> struct CallbackWrapper<Idx, std::nullptr_t, void(*)(void*, Args...)> { template <int NbEvents> static std::nullptr_t wrap(EventOwner<NbEvents>*, std::nullptr_t) { return nullptr; } }; } #endif <commit_msg>common.hpp: Add missing include<commit_after>/***************************************************************************** * common.hpp: Basic shared types & helpers ***************************************************************************** * Copyright © 2015 libvlcpp authors & VideoLAN * * Authors: Hugo Beauzée-Luyssen <[email protected]> * Jonathan Calmels <[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.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 program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef LIBVLC_CXX_COMMON_H #define LIBVLC_CXX_COMMON_H #include <vlc/vlc.h> #include <array> #include <cassert> #include <memory> namespace VLC { class Media; using MediaPtr = std::shared_ptr<Media>; // Work around cross class dependencies // Class A needs to access B's internal pointer // Class B needs to access A's internal pointer // By using a template function to do this, we're delegating // the access to both classes' guts to a later point, when the compiler // already knows everything it needs. // The only drawback is that we can't return decltype(ptr->get()), since when // the compiler checks for the prototype, it hasn't parsed all the declarations yet. template <typename TYPE, typename REF> TYPE* getInternalPtr(const REF& ref) { return ref.get(); } inline std::unique_ptr<char, void (*)(void*)> wrapCStr(char* str) { return std::unique_ptr<char, void(*)(void*)>( str, [](void* ptr) { libvlc_free(ptr); } ); } // Kudos to 3xxO for the signature_match helper template <typename, typename, typename = void> struct signature_match : std::false_type {}; template <typename Func, typename Ret, typename... Args> struct signature_match<Func, Ret(Args...), typename std::enable_if< std::is_convertible< decltype(std::declval<Func>()(std::declval<Args>()...)), Ret >::value // true or false >::type // void or SFINAE > : std::true_type {}; template <typename Func, typename Ret, typename... Args> struct signature_match_or_nullptr : std::integral_constant<bool, signature_match<Func, Ret, Args...>::value || std::is_same<Func, std::nullptr_t>::value > { }; struct CallbackHandlerBase { virtual ~CallbackHandlerBase() = default; }; template <typename Func> struct CallbackHandler : public CallbackHandlerBase { CallbackHandler(Func&& f) : func( std::forward<Func>( f ) ) {} Func func; }; template <int NbEvent> struct EventOwner { std::array<std::shared_ptr<CallbackHandlerBase>, NbEvent> callbacks; protected: EventOwner() = default; }; template <int Idx, typename Func, typename... Args> struct CallbackWrapper; // We assume that any callback will take a void* opaque as its first parameter. // We intercept this parameter, and use it to fetch the list of user provided // functions. Once we know what function to call, we forward the rest of the // parameters. // Using partial specialization also allows us to get the list of the expected // callback parameters automatically, rather than having to specify them. template <int Idx, typename Func, typename Ret, typename... Args> struct CallbackWrapper<Idx, Func, Ret(*)(void*, Args...)> { using Wrapped = Ret(void*, Args...); template <int NbEvents> static Wrapped* wrap(EventOwner<NbEvents>* owner, Func&& func) { owner->callbacks[Idx] = std::shared_ptr<CallbackHandlerBase>( new CallbackHandler<Func>( std::forward<Func>( func ) ) ); return [](void* opaque, Args... args) -> Ret { auto self = reinterpret_cast<EventOwner<NbEvents>*>(opaque); assert(self->callbacks[Idx].get()); auto cbHandler = static_cast<CallbackHandler<Func>*>( self->callbacks[Idx].get() ); return cbHandler->func( std::forward<Args>(args)... ); }; } }; // Special handling for events with a void** opaque first parameter. // We fetch it and do our business with it, then forward the parameters // to the user callback, without this opaque param. template <int Idx, typename Func, typename Ret, typename... Args> struct CallbackWrapper<Idx, Func, Ret(*)(void**, Args...)> { using Wrapped = Ret(void**, Args...); template <int NbEvents> static Wrapped* wrap(EventOwner<NbEvents>* owner, Func&& func) { owner->callbacks[Idx] = std::shared_ptr<CallbackHandlerBase>( new CallbackHandler<Func>( std::forward<Func>( func ) ) ); return [](void** opaque, Args... args) -> Ret { auto self = reinterpret_cast<EventOwner<NbEvents>*>(*opaque); assert(self->callbacks[Idx].get()); auto cbHandler = static_cast<CallbackHandler<Func>*>( self->callbacks[Idx].get() ); return cbHandler->func( std::forward<Args>(args)... ); }; } }; // Specialization to handle null callbacks at build time. // We could try to compare any "Func" against nullptr at runtime, though // since Func is a template type, which roughly has to satisfy the "Callable" concept, // it could be an instance of a function object, which doesn't compare nicely against nullptr. // Using the specialization at build time is easier and performs better. template <int Idx, typename... Args> struct CallbackWrapper<Idx, std::nullptr_t, void(*)(void*, Args...)> { template <int NbEvents> static std::nullptr_t wrap(EventOwner<NbEvents>*, std::nullptr_t) { return nullptr; } }; } #endif <|endoftext|>
<commit_before>#include "buffer.hh" #include "buffer_manager.hh" #include "window.hh" #include "assert.hh" #include "utils.hh" #include "context.hh" #include <algorithm> namespace Kakoune { template<typename T> T clamp(T min, T max, T val) { if (val < min) return min; if (val > max) return max; return val; } Buffer::Buffer(String name, Type type, String initial_content) : m_name(std::move(name)), m_type(type), m_history(1), m_history_cursor(m_history.begin()), m_last_save_undo_index(0), m_hook_manager(GlobalHookManager::instance()), m_option_manager(GlobalOptionManager::instance()) { BufferManager::instance().register_buffer(*this); if (not initial_content.empty()) apply_modification(Modification::make_insert(begin(), std::move(initial_content))); Editor editor_for_hooks(*this); Context context(editor_for_hooks); if (type == Type::NewFile) m_hook_manager.run_hook("BufNew", m_name, context); else if (type == Type::File) m_hook_manager.run_hook("BufOpen", m_name, context); m_hook_manager.run_hook("BufCreate", m_name, context); } Buffer::~Buffer() { m_hook_manager.run_hook("BufClose", m_name, Context(Editor(*this))); m_windows.clear(); BufferManager::instance().unregister_buffer(*this); assert(m_change_listeners.empty()); } BufferIterator Buffer::iterator_at(const BufferCoord& line_and_column) const { return BufferIterator(*this, clamp(line_and_column)); } BufferCoord Buffer::line_and_column_at(const BufferIterator& iterator) const { return iterator.m_coord; } BufferPos Buffer::line_at(const BufferIterator& iterator) const { return iterator.line(); } BufferSize Buffer::line_length(BufferPos line) const { assert(line < line_count()); BufferPos end = (line < m_lines.size() - 1) ? m_lines[line + 1].start : character_count(); return end - m_lines[line].start; } BufferCoord Buffer::clamp(const BufferCoord& line_and_column) const { if (m_lines.empty()) return BufferCoord(); BufferCoord result(line_and_column.line, line_and_column.column); result.line = Kakoune::clamp<int>(0, m_lines.size() - 1, result.line); int max_col = std::max(0, line_length(result.line) - 2); result.column = Kakoune::clamp<int>(0, max_col, result.column); return result; } BufferIterator Buffer::iterator_at_line_begin(const BufferIterator& iterator) const { return BufferIterator(*this, { iterator.line(), 0 }); } BufferIterator Buffer::iterator_at_line_end(const BufferIterator& iterator) const { BufferPos line = iterator.line(); return ++BufferIterator(*this, { line, std::max(line_length(line) - 1, 0) }); } BufferIterator Buffer::begin() const { return BufferIterator(*this, { 0, 0 }); } BufferIterator Buffer::end() const { if (m_lines.empty()) return BufferIterator(*this, { 0, 0 }); return BufferIterator(*this, { (int)line_count()-1, (int)m_lines.back().length() }); } BufferSize Buffer::character_count() const { if (m_lines.empty()) return 0; return m_lines.back().start + m_lines.back().length(); } BufferSize Buffer::line_count() const { return m_lines.size(); } String Buffer::string(const BufferIterator& begin, const BufferIterator& end) const { String res; for (BufferPos line = begin.line(); line <= end.line(); ++line) { size_t start = 0; if (line == begin.line()) start = begin.column(); size_t count = -1; if (line == end.line()) count = end.column() - start; res += m_lines[line].content.substr(start, count); } return res; } void Buffer::begin_undo_group() { assert(m_current_undo_group.empty()); m_history.erase(m_history_cursor, m_history.end()); if (m_history.size() < m_last_save_undo_index) m_last_save_undo_index = -1; m_history_cursor = m_history.end(); } void Buffer::end_undo_group() { if (m_current_undo_group.empty()) return; m_history.push_back(std::move(m_current_undo_group)); m_history_cursor = m_history.end(); m_current_undo_group.clear(); } Modification Modification::inverse() const { Type inverse_type; switch (type) { case Insert: inverse_type = Erase; break; case Erase: inverse_type = Insert; break; default: assert(false); } return Modification(inverse_type, position, content); } bool Buffer::undo() { if (m_history_cursor == m_history.begin()) return false; --m_history_cursor; for (const Modification& modification : reversed(*m_history_cursor)) apply_modification(modification.inverse()); return true; } bool Buffer::redo() { if (m_history_cursor == m_history.end()) return false; for (const Modification& modification : *m_history_cursor) apply_modification(modification); ++m_history_cursor; return true; } void Buffer::reset_undo_data() { m_history.clear(); m_history_cursor = m_history.end(); m_current_undo_group.clear(); } void Buffer::check_invariant() const { BufferSize start = 0; for (auto& line : m_lines) { assert(line.start == start); assert(line.length() > 0); start += line.length(); } } void Buffer::insert(const BufferIterator& pos, const String& content) { BufferSize offset = pos.offset(); // all following lines advanced by length for (size_t i = pos.line()+1; i < line_count(); ++i) m_lines[i].start += content.length(); BufferIterator begin_it; BufferIterator end_it; // if we inserted at the end of the buffer, we may have created a new // line without inserting a '\n' if (pos == end() and (pos == begin() or *(pos-1) == '\n')) { int start = 0; for (int i = 0; i < content.length(); ++i) { if (content[i] == '\n') { m_lines.push_back({ offset + start, content.substr(start, i + 1 - start) }); start = i + 1; } } if (start != content.length()) m_lines.push_back({ offset + start, content.substr(start) }); begin_it = pos; end_it = end(); } else { String prefix = m_lines[pos.line()].content.substr(0, pos.column()); String suffix = m_lines[pos.line()].content.substr(pos.column()); auto line_it = m_lines.begin() + pos.line(); line_it = m_lines.erase(line_it); int start = 0; for (int i = 0; i < content.length(); ++i) { if (content[i] == '\n') { String line_content = content.substr(start, i + 1 - start); if (start == 0) { line_content = prefix + line_content; line_it = m_lines.insert(line_it, { offset + start - (int)prefix.length(), std::move(line_content) }); } else line_it = m_lines.insert(line_it, { offset + start, std::move(line_content) }); ++line_it; start = i + 1; } } if (start == 0) line_it = m_lines.insert(line_it, { offset + start - (int)prefix.length(), prefix + content + suffix }); else line_it = m_lines.insert(line_it, { offset + start, content.substr(start) + suffix }); begin_it = pos; end_it = BufferIterator(*this, { int(line_it - m_lines.begin()), int(line_it->length() - suffix.length()) }); } check_invariant(); for (auto listener : m_change_listeners) listener->on_insert(begin_it, end_it); } void Buffer::erase(const BufferIterator& pos, BufferSize length) { BufferIterator end = pos + length; assert(end.is_valid()); String prefix = m_lines[pos.line()].content.substr(0, pos.column()); String suffix = m_lines[end.line()].content.substr(end.column()); Line new_line = { m_lines[pos.line()].start, prefix + suffix }; m_lines.erase(m_lines.begin() + pos.line(), m_lines.begin() + end.line() + 1); if (new_line.length()) m_lines.insert(m_lines.begin() + pos.line(), std::move(new_line)); for (size_t i = pos.line()+1; i < line_count(); ++i) m_lines[i].start -= length; check_invariant(); for (auto listener : m_change_listeners) listener->on_erase(pos, end); } void Buffer::apply_modification(const Modification& modification) { const String& content = modification.content; const BufferIterator& pos = modification.position; switch (modification.type) { case Modification::Insert: { BufferIterator pos = modification.position < end() ? modification.position : end(); insert(pos, modification.content); break; } case Modification::Erase: { size_t count = modification.content.length(); assert(string(modification.position, modification.position + count) == modification.content); erase(modification.position, count); break; } default: assert(false); } } void Buffer::modify(Modification&& modification) { if (modification.content.empty()) return; apply_modification(modification); m_current_undo_group.push_back(std::move(modification)); } Window* Buffer::get_or_create_window() { if (m_windows.empty()) m_windows.push_front(std::unique_ptr<Window>(new Window(*this))); return m_windows.front().get(); } void Buffer::delete_window(Window* window) { assert(&window->buffer() == this); auto window_it = std::find(m_windows.begin(), m_windows.end(), window); assert(window_it != m_windows.end()); m_windows.erase(window_it); } bool Buffer::is_modified() const { size_t history_cursor_index = m_history_cursor - m_history.begin(); return m_last_save_undo_index != history_cursor_index or not m_current_undo_group.empty(); } void Buffer::notify_saved() { size_t history_cursor_index = m_history_cursor - m_history.begin(); m_last_save_undo_index = history_cursor_index; } void Buffer::add_change_listener(BufferChangeListener& listener) { assert(not contains(m_change_listeners, &listener)); m_change_listeners.push_back(&listener); } void Buffer::remove_change_listener(BufferChangeListener& listener) { auto it = std::find(m_change_listeners.begin(), m_change_listeners.end(), &listener); assert(it != m_change_listeners.end()); m_change_listeners.erase(it); } } <commit_msg>Buffer: fix corner case in insert<commit_after>#include "buffer.hh" #include "buffer_manager.hh" #include "window.hh" #include "assert.hh" #include "utils.hh" #include "context.hh" #include <algorithm> namespace Kakoune { template<typename T> T clamp(T min, T max, T val) { if (val < min) return min; if (val > max) return max; return val; } Buffer::Buffer(String name, Type type, String initial_content) : m_name(std::move(name)), m_type(type), m_history(1), m_history_cursor(m_history.begin()), m_last_save_undo_index(0), m_hook_manager(GlobalHookManager::instance()), m_option_manager(GlobalOptionManager::instance()) { BufferManager::instance().register_buffer(*this); if (not initial_content.empty()) apply_modification(Modification::make_insert(begin(), std::move(initial_content))); Editor editor_for_hooks(*this); Context context(editor_for_hooks); if (type == Type::NewFile) m_hook_manager.run_hook("BufNew", m_name, context); else if (type == Type::File) m_hook_manager.run_hook("BufOpen", m_name, context); m_hook_manager.run_hook("BufCreate", m_name, context); } Buffer::~Buffer() { m_hook_manager.run_hook("BufClose", m_name, Context(Editor(*this))); m_windows.clear(); BufferManager::instance().unregister_buffer(*this); assert(m_change_listeners.empty()); } BufferIterator Buffer::iterator_at(const BufferCoord& line_and_column) const { return BufferIterator(*this, clamp(line_and_column)); } BufferCoord Buffer::line_and_column_at(const BufferIterator& iterator) const { return iterator.m_coord; } BufferPos Buffer::line_at(const BufferIterator& iterator) const { return iterator.line(); } BufferSize Buffer::line_length(BufferPos line) const { assert(line < line_count()); BufferPos end = (line < m_lines.size() - 1) ? m_lines[line + 1].start : character_count(); return end - m_lines[line].start; } BufferCoord Buffer::clamp(const BufferCoord& line_and_column) const { if (m_lines.empty()) return BufferCoord(); BufferCoord result(line_and_column.line, line_and_column.column); result.line = Kakoune::clamp<int>(0, m_lines.size() - 1, result.line); int max_col = std::max(0, line_length(result.line) - 2); result.column = Kakoune::clamp<int>(0, max_col, result.column); return result; } BufferIterator Buffer::iterator_at_line_begin(const BufferIterator& iterator) const { return BufferIterator(*this, { iterator.line(), 0 }); } BufferIterator Buffer::iterator_at_line_end(const BufferIterator& iterator) const { BufferPos line = iterator.line(); return ++BufferIterator(*this, { line, std::max(line_length(line) - 1, 0) }); } BufferIterator Buffer::begin() const { return BufferIterator(*this, { 0, 0 }); } BufferIterator Buffer::end() const { if (m_lines.empty()) return BufferIterator(*this, { 0, 0 }); return BufferIterator(*this, { (int)line_count()-1, (int)m_lines.back().length() }); } BufferSize Buffer::character_count() const { if (m_lines.empty()) return 0; return m_lines.back().start + m_lines.back().length(); } BufferSize Buffer::line_count() const { return m_lines.size(); } String Buffer::string(const BufferIterator& begin, const BufferIterator& end) const { String res; for (BufferPos line = begin.line(); line <= end.line(); ++line) { size_t start = 0; if (line == begin.line()) start = begin.column(); size_t count = -1; if (line == end.line()) count = end.column() - start; res += m_lines[line].content.substr(start, count); } return res; } void Buffer::begin_undo_group() { assert(m_current_undo_group.empty()); m_history.erase(m_history_cursor, m_history.end()); if (m_history.size() < m_last_save_undo_index) m_last_save_undo_index = -1; m_history_cursor = m_history.end(); } void Buffer::end_undo_group() { if (m_current_undo_group.empty()) return; m_history.push_back(std::move(m_current_undo_group)); m_history_cursor = m_history.end(); m_current_undo_group.clear(); } Modification Modification::inverse() const { Type inverse_type; switch (type) { case Insert: inverse_type = Erase; break; case Erase: inverse_type = Insert; break; default: assert(false); } return Modification(inverse_type, position, content); } bool Buffer::undo() { if (m_history_cursor == m_history.begin()) return false; --m_history_cursor; for (const Modification& modification : reversed(*m_history_cursor)) apply_modification(modification.inverse()); return true; } bool Buffer::redo() { if (m_history_cursor == m_history.end()) return false; for (const Modification& modification : *m_history_cursor) apply_modification(modification); ++m_history_cursor; return true; } void Buffer::reset_undo_data() { m_history.clear(); m_history_cursor = m_history.end(); m_current_undo_group.clear(); } void Buffer::check_invariant() const { BufferSize start = 0; for (auto& line : m_lines) { assert(line.start == start); assert(line.length() > 0); start += line.length(); } } void Buffer::insert(const BufferIterator& pos, const String& content) { BufferSize offset = pos.offset(); // all following lines advanced by length for (size_t i = pos.line()+1; i < line_count(); ++i) m_lines[i].start += content.length(); BufferIterator begin_it; BufferIterator end_it; // if we inserted at the end of the buffer, we may have created a new // line without inserting a '\n' if (pos == end() and (pos == begin() or *(pos-1) == '\n')) { int start = 0; for (int i = 0; i < content.length(); ++i) { if (content[i] == '\n') { m_lines.push_back({ offset + start, content.substr(start, i + 1 - start) }); start = i + 1; } } if (start != content.length()) m_lines.push_back({ offset + start, content.substr(start) }); begin_it = pos; end_it = end(); } else { String prefix = m_lines[pos.line()].content.substr(0, pos.column()); String suffix = m_lines[pos.line()].content.substr(pos.column()); auto line_it = m_lines.begin() + pos.line(); line_it = m_lines.erase(line_it); int start = 0; for (int i = 0; i < content.length(); ++i) { if (content[i] == '\n') { String line_content = content.substr(start, i + 1 - start); if (start == 0) { line_content = prefix + line_content; line_it = m_lines.insert(line_it, { offset + start - (int)prefix.length(), std::move(line_content) }); } else line_it = m_lines.insert(line_it, { offset + start, std::move(line_content) }); ++line_it; start = i + 1; } } if (start == 0) line_it = m_lines.insert(line_it, { offset + start - (int)prefix.length(), prefix + content + suffix }); else if (start != content.length() or not suffix.empty()) line_it = m_lines.insert(line_it, { offset + start, content.substr(start) + suffix }); else --line_it; begin_it = pos; end_it = BufferIterator(*this, { int(line_it - m_lines.begin()), int(line_it->length() - suffix.length()) }); } check_invariant(); for (auto listener : m_change_listeners) listener->on_insert(begin_it, end_it); } void Buffer::erase(const BufferIterator& pos, BufferSize length) { BufferIterator end = pos + length; assert(end.is_valid()); String prefix = m_lines[pos.line()].content.substr(0, pos.column()); String suffix = m_lines[end.line()].content.substr(end.column()); Line new_line = { m_lines[pos.line()].start, prefix + suffix }; m_lines.erase(m_lines.begin() + pos.line(), m_lines.begin() + end.line() + 1); if (new_line.length()) m_lines.insert(m_lines.begin() + pos.line(), std::move(new_line)); for (size_t i = pos.line()+1; i < line_count(); ++i) m_lines[i].start -= length; check_invariant(); for (auto listener : m_change_listeners) listener->on_erase(pos, end); } void Buffer::apply_modification(const Modification& modification) { const String& content = modification.content; const BufferIterator& pos = modification.position; switch (modification.type) { case Modification::Insert: { BufferIterator pos = modification.position < end() ? modification.position : end(); insert(pos, modification.content); break; } case Modification::Erase: { size_t count = modification.content.length(); assert(string(modification.position, modification.position + count) == modification.content); erase(modification.position, count); break; } default: assert(false); } } void Buffer::modify(Modification&& modification) { if (modification.content.empty()) return; apply_modification(modification); m_current_undo_group.push_back(std::move(modification)); } Window* Buffer::get_or_create_window() { if (m_windows.empty()) m_windows.push_front(std::unique_ptr<Window>(new Window(*this))); return m_windows.front().get(); } void Buffer::delete_window(Window* window) { assert(&window->buffer() == this); auto window_it = std::find(m_windows.begin(), m_windows.end(), window); assert(window_it != m_windows.end()); m_windows.erase(window_it); } bool Buffer::is_modified() const { size_t history_cursor_index = m_history_cursor - m_history.begin(); return m_last_save_undo_index != history_cursor_index or not m_current_undo_group.empty(); } void Buffer::notify_saved() { size_t history_cursor_index = m_history_cursor - m_history.begin(); m_last_save_undo_index = history_cursor_index; } void Buffer::add_change_listener(BufferChangeListener& listener) { assert(not contains(m_change_listeners, &listener)); m_change_listeners.push_back(&listener); } void Buffer::remove_change_listener(BufferChangeListener& listener) { auto it = std::find(m_change_listeners.begin(), m_change_listeners.end(), &listener); assert(it != m_change_listeners.end()); m_change_listeners.erase(it); } } <|endoftext|>
<commit_before>#ifndef _MEMORY_HH_ #define _MEMORY_HH_ #include <cstdio> #include <memory> #include <type_traits> namespace std { template <typename T> constexpr auto is_aligned(T x, size_t a) noexcept -> typename std::enable_if<std::is_integral<T>::value, bool>::type { return (x & (a-1)) == 0; } template <typename T> constexpr auto align_up(T x, size_t a) noexcept -> typename std::enable_if<std::is_integral<T>::value, T>::type { return (x + (a-1)) & -a; } template <typename T> constexpr auto align_down(T x, size_t a) noexcept -> typename std::enable_if<std::is_integral<T>::value, T>::type { return x & (-a); } template <typename T> inline auto is_aligned(T p, size_t a) -> typename std::enable_if<std::is_pointer<T>::value, bool>::type { return is_aligned(reinterpret_cast<uintptr_t>(p), a); } inline bool is_aligned(nullptr_t, size_t) { return true; } template <typename T> inline auto align_up(T p, size_t a) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { return reinterpret_cast<T>(align_up(reinterpret_cast<uintptr_t>(p), a)); } inline nullptr_t align_up(nullptr_t, size_t) { return nullptr; } template <typename T> inline auto align_down(T p, size_t a) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { return reinterpret_cast<T>(align_down(reinterpret_cast<uintptr_t>(p), a)); } inline nullptr_t align_down(nullptr_t, size_t) { return nullptr; } template <typename T, typename U> inline auto align_up_cast(U* p, size_t a=alignof(typename std::remove_pointer<T>::type)) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { return reinterpret_cast<T>(align_up(p, a)); } template <typename T> inline auto align_up_cast(nullptr_t p, size_t a=1) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { (void)a; nullptr; } template <typename T, typename U> inline auto align_down_cast(U* p, size_t a=alignof(typename std::remove_pointer<T>::type)) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { return reinterpret_cast<T>(align_down(p, a)); } template <typename T> inline auto align_down_cast(nullptr_t p, size_t a=1) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { (void)a; nullptr; } } //namespace std #endif <commit_msg>update header<commit_after>#ifndef _MEMORY_HH_ #define _MEMORY_HH_ #include <cstdio> #include <memory> #include <type_traits> namespace std { template <typename T> constexpr auto is_aligned(T x, size_t a) noexcept -> typename std::enable_if<std::is_integral<T>::value, bool>::type { return (x & (a-1)) == 0; } template <typename T> constexpr auto align_up(T x, size_t a) noexcept -> typename std::enable_if<std::is_integral<T>::value, T>::type { return (x + (a-1)) & -a; } template <typename T> constexpr auto align_down(T x, size_t a) noexcept -> typename std::enable_if<std::is_integral<T>::value, T>::type { return x & (-a); } inline bool is_aligned(void* p, size_t a) { return is_aligned(reinterpret_cast<uintptr_t>(p)); } inline bool is_aligned(const void* p, size_t a) { return is_aligned(reinterpret_cast<uintptr_t>(p)); } inline bool is_aligned(volatile void* p, size_t a) { return is_aligned(reinterpret_cast<uintptr_t>(p)); } inline bool is_aligned(const volatile void* p, size_t a) { return is_aligned(reinterpret_cast<uintptr_t>(p)); } template <typename T> inline auto align_up(T p, size_t a) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { return reinterpret_cast<T>(align_up(reinterpret_cast<uintptr_t>(p), a)); } inline nullptr_t align_up(nullptr_t, size_t) { return nullptr; } template <typename T> inline auto align_down(T p, size_t a) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { return reinterpret_cast<T>(align_down(reinterpret_cast<uintptr_t>(p), a)); } inline nullptr_t align_down(nullptr_t, size_t) { return nullptr; } template <typename T, typename U> inline auto align_up_cast(U* p, size_t a=alignof(typename std::remove_pointer<T>::type)) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { return reinterpret_cast<T>(align_up(p, a)); } template <typename T> inline auto align_up_cast(nullptr_t p, size_t a=1) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { (void)a; nullptr; } template <typename T, typename U> inline auto align_down_cast(U* p, size_t a=alignof(typename std::remove_pointer<T>::type)) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { return reinterpret_cast<T>(align_down(p, a)); } template <typename T> inline auto align_down_cast(nullptr_t p, size_t a=1) -> typename std::enable_if<std::is_pointer<T>::value, T>::type { (void)a; nullptr; } } //namespace std #endif <|endoftext|>
<commit_before>#include <omp.h> #include <stdio.h> #include <opencv2/opencv.hpp> #include <fstream> #include <iostream> #include <armadillo> #include <iomanip> #include <vector> #include <hdf5.h> #include "omp.h" using namespace std; using namespace arma; // #include "aux-functions-def.hpp" // #include "aux-functions-impl.hpp" // #include "riemannian-metrics-def.hpp" // #include "riemannian-metrics-impl.hpp" #include "grassmann-metrics-def.hpp" #include "grassmann-metrics-impl.hpp" #include "kth-cross-validation-one-def.hpp" #include "kth-cross-validation-one-impl.hpp" //Home //const std::string path = "/media/johanna/HD1T/codes/datasets_codes/KTH/"; //WANDA const std::string path = "/home/johanna/codes/codes-git/study-paper/trunk/"; const std::string peopleList = "people_list.txt"; const std::string actionNames = "actionNames.txt"; ///kth // int ori_col = 160; // int ori_row = 120; int main(int argc, char** argv) { if(argc < 3 ) { cout << "usage: " << argv[0] << " scale_factor " << " shift_factor " << endl; return -1; } int scale_factor = atoi( argv[1] ); int shift = atoi( argv[2] ); int total_scenes = 1; //Only for Scenario 1. int dim = 14; int p = 12;//PQ NO SE> POR BOBA> FUE UN ERROR :( field<string> all_people; all_people.load(peopleList); //Cross Validation kth_cv_omp kth_CV_omp_onesegment(path, actionNames, all_people, scale_factor, shift, total_scenes, dim); //kth_CV_omp_onesegment.logEucl(); kth_CV_omp_onesegment.SteinDiv(); //kth_CV_omp.proj_grass(p); //kth_CV_omp.BC_grass(); return 0; } <commit_msg>Run Stein_Div. One cov matrix per video<commit_after>#include <omp.h> #include <stdio.h> #include <opencv2/opencv.hpp> #include <fstream> #include <iostream> #include <armadillo> #include <iomanip> #include <vector> #include <hdf5.h> #include "omp.h" using namespace std; using namespace arma; // #include "aux-functions-def.hpp" // #include "aux-functions-impl.hpp" // #include "riemannian-metrics-def.hpp" // #include "riemannian-metrics-impl.hpp" #include "grassmann-metrics-def.hpp" #include "grassmann-metrics-impl.hpp" #include "kth-cross-validation-one-def.hpp" #include "kth-cross-validation-one-impl.hpp" //Home //const std::string path = "/media/johanna/HD1T/codes/datasets_codes/KTH/"; //WANDA const std::string path = "/home/johanna/codes/codes-git/study-paper/trunk/"; const std::string peopleList = "people_list.txt"; const std::string actionNames = "actionNames.txt"; ///kth // int ori_col = 160; // int ori_row = 120; int main(int argc, char** argv) { if(argc < 3 ) { cout << "usage: " << argv[0] << " scale_factor " << " shift_factor " << endl; return -1; } int scale_factor = atoi( argv[1] ); int shift = atoi( argv[2] ); int total_scenes = 1; //Only for Scenario 1. int dim = 14; int p = 12;//PQ NO SE> POR BOBA> FUE UN ERROR :( field<string> all_people; all_people.load(peopleList); //Cross Validation kth_cv_omp kth_CV_omp_onesegment(path, actionNames, all_people, scale_factor, shift, total_scenes, dim); kth_CV_omp_onesegment.logEucl(); //kth_CV_omp_onesegment.SteinDiv(); //kth_CV_omp.proj_grass(p); //kth_CV_omp.BC_grass(); return 0; } <|endoftext|>
<commit_before>#include "SuffixMatchManager.hpp" #include <document-manager/DocumentManager.h> #include <boost/filesystem.hpp> #include <glog/logging.h> namespace sf1r { SuffixMatchManager::SuffixMatchManager( const std::string& homePath, const std::string& property, boost::shared_ptr<DocumentManager>& document_manager) : fm_index_path_(homePath + "/" + property + ".fm_idx") , property_(property) , document_manager_(document_manager) { if (!boost::filesystem::exists(homePath)) { boost::filesystem::create_directories(homePath); } else { std::ifstream ifs(fm_index_path_.c_str()); if (ifs) { fmi_.reset(new FMIndexType(32)); fmi_->load(ifs); } } } SuffixMatchManager::~SuffixMatchManager() { } void SuffixMatchManager::buildCollection() { FMIndexType* new_fmi = new FMIndexType(32); size_t last_docid = fmi_ ? fmi_->docCount() : 0; if (last_docid) { std::vector<uint16_t> orig_text; std::vector<uint32_t> del_docid_list; document_manager_->getDeletedDocIdList(del_docid_list); fmi_->reconstructText(del_docid_list, orig_text); new_fmi->setOrigText(orig_text); } for (size_t i = last_docid + 1; i <= document_manager_->getMaxDocId(); ++i) { if (i % 100000 == 0) { LOG(INFO) << "inserted docs: " << i; } Document doc; document_manager_->getDocument(i, doc); Document::property_const_iterator it = doc.findProperty(property_); if (it == doc.propertyEnd()) { new_fmi->addDoc(NULL, 0); continue; } const izenelib::util::UString& text = it->second.get<UString>(); new_fmi->addDoc(text.data(), text.length()); } LOG(INFO) << "inserted docs: " << document_manager_->getMaxDocId(); LOG(INFO) << "building fm-index"; new_fmi->build(); { WriteLock lock(mutex_); fmi_.reset(new_fmi); } std::ofstream ofs(fm_index_path_.c_str()); fmi_->save(ofs); } size_t SuffixMatchManager::longestSuffixMatch(const izenelib::util::UString& pattern, size_t max_docs, std::vector<uint32_t>& docid_list, std::vector<float>& score_list) const { if (!fmi_) return 0; std::vector<std::pair<size_t, size_t> >match_ranges; std::vector<size_t> doclen_list; size_t max_match; { ReadLock lock(mutex_); if ((max_match = fmi_->longestSuffixMatch(pattern.data(), pattern.length(), match_ranges)) == 0) return 0; fmi_->getMatchedDocIdList(match_ranges, max_docs, docid_list, doclen_list); } std::vector<std::pair<float, uint32_t> > res_list(docid_list.size()); for (size_t i = 0; i < res_list.size(); ++i) { res_list[i].first = float(max_match) / float(doclen_list[i]); res_list[i].second = docid_list[i]; } std::sort(res_list.begin(), res_list.end(), std::greater<std::pair<float, uint32_t> >()); score_list.resize(doclen_list.size()); for (size_t i = 0; i < res_list.size(); ++i) { docid_list[i] = res_list[i].second; score_list[i] = res_list[i].first; } size_t total_match = 0; for (size_t i = 0; i < match_ranges.size(); ++i) { total_match += match_ranges[i].second - match_ranges[i].first; } return total_match; } } <commit_msg>fix for new fm-index<commit_after>#include "SuffixMatchManager.hpp" #include <document-manager/DocumentManager.h> #include <boost/filesystem.hpp> #include <glog/logging.h> namespace sf1r { SuffixMatchManager::SuffixMatchManager( const std::string& homePath, const std::string& property, boost::shared_ptr<DocumentManager>& document_manager) : fm_index_path_(homePath + "/" + property + ".fm_idx") , property_(property) , document_manager_(document_manager) { if (!boost::filesystem::exists(homePath)) { boost::filesystem::create_directories(homePath); } else { std::ifstream ifs(fm_index_path_.c_str()); if (ifs) { fmi_.reset(new FMIndexType); fmi_->load(ifs); } } } SuffixMatchManager::~SuffixMatchManager() { } void SuffixMatchManager::buildCollection() { FMIndexType* new_fmi = new FMIndexType; size_t last_docid = fmi_ ? fmi_->docCount() : 0; if (last_docid) { std::vector<uint16_t> orig_text; std::vector<uint32_t> del_docid_list; document_manager_->getDeletedDocIdList(del_docid_list); fmi_->reconstructText(del_docid_list, orig_text); new_fmi->setOrigText(orig_text); } for (size_t i = last_docid + 1; i <= document_manager_->getMaxDocId(); ++i) { if (i % 100000 == 0) { LOG(INFO) << "inserted docs: " << i; } Document doc; document_manager_->getDocument(i, doc); Document::property_const_iterator it = doc.findProperty(property_); if (it == doc.propertyEnd()) { new_fmi->addDoc(NULL, 0); continue; } const izenelib::util::UString& text = it->second.get<UString>(); new_fmi->addDoc(text.data(), text.length()); } LOG(INFO) << "inserted docs: " << document_manager_->getMaxDocId(); LOG(INFO) << "building fm-index"; new_fmi->build(); { WriteLock lock(mutex_); fmi_.reset(new_fmi); } std::ofstream ofs(fm_index_path_.c_str()); fmi_->save(ofs); } size_t SuffixMatchManager::longestSuffixMatch(const izenelib::util::UString& pattern, size_t max_docs, std::vector<uint32_t>& docid_list, std::vector<float>& score_list) const { if (!fmi_) return 0; std::vector<std::pair<size_t, size_t> >match_ranges; std::vector<size_t> doclen_list; size_t max_match; { ReadLock lock(mutex_); if ((max_match = fmi_->longestSuffixMatch(pattern.data(), pattern.length(), match_ranges)) == 0) return 0; fmi_->getMatchedDocIdList(match_ranges, max_docs, docid_list, doclen_list); } std::vector<std::pair<float, uint32_t> > res_list(docid_list.size()); for (size_t i = 0; i < res_list.size(); ++i) { res_list[i].first = float(max_match) / float(doclen_list[i]); res_list[i].second = docid_list[i]; } std::sort(res_list.begin(), res_list.end(), std::greater<std::pair<float, uint32_t> >()); score_list.resize(doclen_list.size()); for (size_t i = 0; i < res_list.size(); ++i) { docid_list[i] = res_list[i].second; score_list[i] = res_list[i].first; } size_t total_match = 0; for (size_t i = 0; i < match_ranges.size(); ++i) { total_match += match_ranges[i].second - match_ranges[i].first; } return total_match; } } <|endoftext|>
<commit_before>#include "arc_factored.h" #include <iostream> #include "config.h" using namespace std; #if HAVE_EIGEN #include <Eigen/Dense> typedef Eigen::Matrix<prob_t, Eigen::Dynamic, Eigen::Dynamic> ArcMatrix; typedef Eigen::Matrix<prob_t, Eigen::Dynamic, 1> RootVector; void ArcFactoredForest::EdgeMarginals(prob_t *plog_z) { ArcMatrix A(num_words_,num_words_); RootVector r(num_words_); for (int h = 0; h < num_words_; ++h) { for (int m = 0; m < num_words_; ++m) { if (h != m) A(h,m) = edges_(h,m).edge_prob; else A(h,m) = prob_t::Zero(); } r(h) = root_edges_[h].edge_prob; } ArcMatrix L = -A; L.diagonal() = A.colwise().sum(); L.row(0) = r; ArcMatrix Linv = L.inverse(); if (plog_z) *plog_z = Linv.determinant(); RootVector rootMarginals = r.cwiseProduct(Linv.col(0)); static const prob_t ZERO(0); static const prob_t ONE(1); // ArcMatrix T = Linv; for (int h = 0; h < num_words_; ++h) { for (int m = 0; m < num_words_; ++m) { const prob_t marginal = (m == 0 ? ZERO : ONE) * A(h,m) * Linv(m,m) - (h == 0 ? ZERO : ONE) * A(h,m) * Linv(m,h); edges_(h,m).edge_prob = marginal; // T(h,m) = marginal; } root_edges_[h].edge_prob = rootMarginals(h); } // cerr << "ROOT MARGINALS: " << rootMarginals.transpose() << endl; // cerr << "M:\n" << T << endl; } #else void ArcFactoredForest::EdgeMarginals(double*) { cerr << "EdgeMarginals() requires --with-eigen!\n"; abort(); } #endif <commit_msg>fix for marginals<commit_after>#include "arc_factored.h" #include <iostream> #include "config.h" using namespace std; #if HAVE_EIGEN #include <Eigen/Dense> typedef Eigen::Matrix<prob_t, Eigen::Dynamic, Eigen::Dynamic> ArcMatrix; typedef Eigen::Matrix<prob_t, Eigen::Dynamic, 1> RootVector; void ArcFactoredForest::EdgeMarginals(prob_t *plog_z) { ArcMatrix A(num_words_,num_words_); RootVector r(num_words_); for (int h = 0; h < num_words_; ++h) { for (int m = 0; m < num_words_; ++m) { if (h != m) A(h,m) = edges_(h,m).edge_prob; else A(h,m) = prob_t::Zero(); } r(h) = root_edges_[h].edge_prob; } ArcMatrix L = -A; L.diagonal() = A.colwise().sum(); L.row(0) = r; ArcMatrix Linv = L.inverse(); if (plog_z) *plog_z = Linv.determinant(); RootVector rootMarginals = r.cwiseProduct(Linv.col(0)); static const prob_t ZERO(0); static const prob_t ONE(1); // ArcMatrix T = Linv; for (int h = 0; h < num_words_; ++h) { for (int m = 0; m < num_words_; ++m) { const prob_t marginal = (m == 0 ? ZERO : ONE) * A(h,m) * Linv(m,m) - (h == 0 ? ZERO : ONE) * A(h,m) * Linv(m,h); edges_(h,m).edge_prob = marginal; // T(h,m) = marginal; } root_edges_[h].edge_prob = rootMarginals(h); } // cerr << "ROOT MARGINALS: " << rootMarginals.transpose() << endl; // cerr << "M:\n" << T << endl; } #else void ArcFactoredForest::EdgeMarginals(prob_t *) { cerr << "EdgeMarginals() requires --with-eigen!\n"; abort(); } #endif <|endoftext|>
<commit_before>#include "ServerSocket.h" #include "SocketUtils.h" #include "WdtOptions.h" #include <glog/logging.h> #include <sys/socket.h> #include <poll.h> #include <folly/Conv.h> #include <fcntl.h> #include <chrono> #include <algorithm> namespace facebook { namespace wdt { using std::swap; typedef std::chrono::high_resolution_clock Clock; template <typename T> int durationMillis(T d) { return std::chrono::duration_cast<std::chrono::milliseconds>(d).count(); } using std::string; ServerSocket::ServerSocket(int32_t port, int backlog) : port_(port), backlog_(backlog), listeningFd_(-1), fd_(-1) { memset(&sa_, 0, sizeof(sa_)); const auto &options = WdtOptions::get(); if (options.ipv6) { sa_.ai_family = AF_INET6; } if (options.ipv4) { sa_.ai_family = AF_INET; } sa_.ai_socktype = SOCK_STREAM; sa_.ai_flags = AI_PASSIVE; } ServerSocket::ServerSocket(ServerSocket &&that) noexcept : backlog_(that.backlog_) { port_ = that.port_; sa_ = that.sa_; listeningFd_ = that.listeningFd_; fd_ = that.fd_; // A temporary ServerSocket should be changed such that // the fd doesn't get closed when it (temp obj) is getting // destructed and "this" object will remain intact that.listeningFd_ = -1; that.fd_ = -1; } ServerSocket &ServerSocket::operator=(ServerSocket &&that) { swap(port_, that.port_); swap(sa_, that.sa_); swap(listeningFd_, that.listeningFd_); swap(fd_, that.fd_); return *this; } void ServerSocket::closeAll() { VLOG(1) << "Destroying server socket (port, listen fd, fd)" << port_ << ", " << listeningFd_ << ", " << fd_; if (listeningFd_ >= 0) { ::close(listeningFd_); listeningFd_ = -1; } if (fd_ >= 0) { ::close(fd_); // this probably fails because it's already closed by client fd_ = -1; } } ServerSocket::~ServerSocket() { closeAll(); } ErrorCode ServerSocket::listen() { if (listeningFd_ > 0) { return OK; } // Lookup struct addrinfo *infoList; int res = getaddrinfo(nullptr, folly::to<std::string>(port_).c_str(), &sa_, &infoList); if (res) { // not errno, can't use PLOG (perror) LOG(ERROR) << "Failed getaddrinfo ai_passive on " << port_ << " : " << res << " : " << gai_strerror(res); return CONN_ERROR; } for (struct addrinfo *info = infoList; info != nullptr; info = info->ai_next) { VLOG(1) << "Will listen on " << SocketUtils::getNameInfo(info->ai_addr, info->ai_addrlen); // TODO: set sock options : SO_REUSEADDR,... listeningFd_ = socket(info->ai_family, info->ai_socktype, info->ai_protocol); if (listeningFd_ == -1) { PLOG(WARNING) << "Error making server socket"; continue; } if (bind(listeningFd_, info->ai_addr, info->ai_addrlen)) { PLOG(WARNING) << "Error binding"; ::close(listeningFd_); listeningFd_ = -1; continue; } VLOG(1) << "Successful bind on " << listeningFd_; sa_ = *info; break; } freeaddrinfo(infoList); if (listeningFd_ <= 0) { LOG(ERROR) << "Unable to bind"; return CONN_ERROR_RETRYABLE; } if (::listen(listeningFd_, backlog_)) { PLOG(ERROR) << "listen error"; ::close(listeningFd_); listeningFd_ = -1; return CONN_ERROR_RETRYABLE; } return OK; } ErrorCode ServerSocket::acceptNextConnection(int timeoutMillis) { ErrorCode code = listen(); if (code != OK) { return code; } if (timeoutMillis > 0) { // zero value disables timeout auto startTime = Clock::now(); while (true) { // we need this loop because poll() can return before any file handles // have changes or before timing out. In that case, we check whether it // is becuse of EINTR or not. If true, we have to try poll with // reduced timeout int timeElapsed = durationMillis(Clock::now() - startTime); if (timeElapsed >= timeoutMillis) { LOG(ERROR) << "accept() timed out"; return CONN_ERROR; } int pollTimeout = timeoutMillis - timeElapsed; struct pollfd pollFds[] = {{listeningFd_, POLLIN}}; int retValue; if ((retValue = poll(pollFds, 1, pollTimeout)) <= 0) { if (errno == EINTR) { VLOG(1) << "poll() call interrupted. retrying..."; continue; } if (retValue == 0) { VLOG(1) << "poll() timed out" << port_ << " " << listeningFd_; } else { PLOG(ERROR) << "poll() failed " << port_ << " " << listeningFd_; } return CONN_ERROR; } break; } } struct sockaddr addr; socklen_t addrLen = sizeof(addr); fd_ = accept(listeningFd_, &addr, &addrLen); if (fd_ < 0) { PLOG(ERROR) << "accept error"; return CONN_ERROR; } VLOG(1) << "new connection " << fd_ << " from " << SocketUtils::getNameInfo(&addr, addrLen); SocketUtils::setReadTimeout(fd_); SocketUtils::setWriteTimeout(fd_); return OK; } int ServerSocket::read(char *buf, int nbyte) const { while (true) { int retValue = ::read(fd_, buf, nbyte); if (retValue < 0 && errno == EINTR) { VLOG(2) << "received EINTR. continuing..."; continue; } return retValue; } } int ServerSocket::write(char *buf, int nbyte) const { return ::write(fd_, buf, nbyte); } int ServerSocket::closeCurrentConnection() { int retValue = 0; if (fd_ >= 0) { retValue = ::close(fd_); fd_ = -1; } return retValue; } int ServerSocket::getListenFd() const { return listeningFd_; } int ServerSocket::getFd() const { VLOG(1) << "fd is " << fd_; return fd_; } int32_t ServerSocket::getPort() const { return port_; } int ServerSocket::getBackLog() const { return backlog_; } } } // end namespace facebook::wtd <commit_msg>bug fixes: shows which port fails to bind, warn about bad config, allow ipv6<commit_after>#include "ServerSocket.h" #include "SocketUtils.h" #include "WdtOptions.h" #include <glog/logging.h> #include <sys/socket.h> #include <poll.h> #include <folly/Conv.h> #include <fcntl.h> #include <chrono> #include <algorithm> namespace facebook { namespace wdt { using std::swap; typedef std::chrono::high_resolution_clock Clock; template <typename T> int durationMillis(T d) { return std::chrono::duration_cast<std::chrono::milliseconds>(d).count(); } using std::string; ServerSocket::ServerSocket(int32_t port, int backlog) : port_(port), backlog_(backlog), listeningFd_(-1), fd_(-1) { memset(&sa_, 0, sizeof(sa_)); const auto &options = WdtOptions::get(); if (options.ipv6) { sa_.ai_family = AF_INET6; } if (options.ipv4) { sa_.ai_family = AF_INET; } sa_.ai_socktype = SOCK_STREAM; sa_.ai_flags = AI_PASSIVE; } ServerSocket::ServerSocket(ServerSocket &&that) noexcept : backlog_(that.backlog_) { port_ = that.port_; sa_ = that.sa_; listeningFd_ = that.listeningFd_; fd_ = that.fd_; // A temporary ServerSocket should be changed such that // the fd doesn't get closed when it (temp obj) is getting // destructed and "this" object will remain intact that.listeningFd_ = -1; that.fd_ = -1; } ServerSocket &ServerSocket::operator=(ServerSocket &&that) { swap(port_, that.port_); swap(sa_, that.sa_); swap(listeningFd_, that.listeningFd_); swap(fd_, that.fd_); return *this; } void ServerSocket::closeAll() { VLOG(1) << "Destroying server socket (port, listen fd, fd)" << port_ << ", " << listeningFd_ << ", " << fd_; if (listeningFd_ >= 0) { ::close(listeningFd_); listeningFd_ = -1; } if (fd_ >= 0) { ::close(fd_); // this probably fails because it's already closed by client fd_ = -1; } } ServerSocket::~ServerSocket() { closeAll(); } ErrorCode ServerSocket::listen() { if (listeningFd_ > 0) { return OK; } // Lookup struct addrinfo *infoList; int res = getaddrinfo(nullptr, folly::to<std::string>(port_).c_str(), &sa_, &infoList); if (res) { // not errno, can't use PLOG (perror) LOG(ERROR) << "Failed getaddrinfo ai_passive on " << port_ << " : " << res << " : " << gai_strerror(res); return CONN_ERROR; } for (struct addrinfo *info = infoList; info != nullptr; info = info->ai_next) { VLOG(1) << "Will listen on " << SocketUtils::getNameInfo(info->ai_addr, info->ai_addrlen); // TODO: set sock options : SO_REUSEADDR,... listeningFd_ = socket(info->ai_family, info->ai_socktype, info->ai_protocol); if (listeningFd_ == -1) { PLOG(WARNING) << "Error making server socket"; continue; } if (bind(listeningFd_, info->ai_addr, info->ai_addrlen)) { PLOG(WARNING) << "Error binding " << port_; ::close(listeningFd_); listeningFd_ = -1; continue; } VLOG(1) << "Successful bind on " << listeningFd_; sa_ = *info; break; } freeaddrinfo(infoList); if (listeningFd_ <= 0) { LOG(ERROR) << "Unable to bind"; return CONN_ERROR_RETRYABLE; } if (::listen(listeningFd_, backlog_)) { PLOG(ERROR) << "listen error"; ::close(listeningFd_); listeningFd_ = -1; return CONN_ERROR_RETRYABLE; } return OK; } ErrorCode ServerSocket::acceptNextConnection(int timeoutMillis) { ErrorCode code = listen(); if (code != OK) { return code; } if (timeoutMillis > 0) { // zero value disables timeout auto startTime = Clock::now(); while (true) { // we need this loop because poll() can return before any file handles // have changes or before timing out. In that case, we check whether it // is becuse of EINTR or not. If true, we have to try poll with // reduced timeout int timeElapsed = durationMillis(Clock::now() - startTime); if (timeElapsed >= timeoutMillis) { LOG(ERROR) << "accept() timed out"; return CONN_ERROR; } int pollTimeout = timeoutMillis - timeElapsed; struct pollfd pollFds[] = {{listeningFd_, POLLIN}}; int retValue; if ((retValue = poll(pollFds, 1, pollTimeout)) <= 0) { if (errno == EINTR) { VLOG(1) << "poll() call interrupted. retrying..."; continue; } if (retValue == 0) { VLOG(1) << "poll() timed out" << port_ << " " << listeningFd_; } else { PLOG(ERROR) << "poll() failed " << port_ << " " << listeningFd_; } return CONN_ERROR; } break; } } struct sockaddr addr; socklen_t addrLen = sizeof(addr); fd_ = accept(listeningFd_, &addr, &addrLen); if (fd_ < 0) { PLOG(ERROR) << "accept error"; return CONN_ERROR; } VLOG(1) << "new connection " << fd_ << " from " << SocketUtils::getNameInfo(&addr, addrLen); SocketUtils::setReadTimeout(fd_); SocketUtils::setWriteTimeout(fd_); return OK; } int ServerSocket::read(char *buf, int nbyte) const { while (true) { int retValue = ::read(fd_, buf, nbyte); if (retValue < 0 && errno == EINTR) { VLOG(2) << "received EINTR. continuing..."; continue; } return retValue; } } int ServerSocket::write(char *buf, int nbyte) const { return ::write(fd_, buf, nbyte); } int ServerSocket::closeCurrentConnection() { int retValue = 0; if (fd_ >= 0) { retValue = ::close(fd_); fd_ = -1; } return retValue; } int ServerSocket::getListenFd() const { return listeningFd_; } int ServerSocket::getFd() const { VLOG(1) << "fd is " << fd_; return fd_; } int32_t ServerSocket::getPort() const { return port_; } int ServerSocket::getBackLog() const { return backlog_; } } } // end namespace facebook::wtd <|endoftext|>
<commit_before>// Copyright 2008, 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. // // Author: [email protected] (Zhanyong Wan) // Tests Google Mock's output in various scenarios. This ensures that // Google Mock's messages are readable and useful. #include "gmock/gmock.h" #include <stdio.h> #include <string> #include "gtest/gtest.h" // Silence C4100 (unreferenced formal parameter) for MSVC #ifdef _MSC_VER # if _MSC_VER <= 1900 # pragma warning(push) # pragma warning(disable:4100) # endif #endif using testing::_; using testing::AnyNumber; using testing::Ge; using testing::InSequence; using testing::NaggyMock; using testing::Ref; using testing::Return; using testing::Sequence; using testing::Value; class MockFoo { public: MockFoo() {} MOCK_METHOD3(Bar, char(const std::string& s, int i, double x)); MOCK_METHOD2(Bar2, bool(int x, int y)); MOCK_METHOD2(Bar3, void(int x, int y)); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); }; class GMockOutputTest : public testing::Test { protected: NaggyMock<MockFoo> foo_; }; TEST_F(GMockOutputTest, ExpectedCall) { testing::GMOCK_FLAG(verbose) = "info"; EXPECT_CALL(foo_, Bar2(0, _)); foo_.Bar2(0, 0); // Expected call testing::GMOCK_FLAG(verbose) = "warning"; } TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) { testing::GMOCK_FLAG(verbose) = "info"; EXPECT_CALL(foo_, Bar3(0, _)); foo_.Bar3(0, 0); // Expected call testing::GMOCK_FLAG(verbose) = "warning"; } TEST_F(GMockOutputTest, ExplicitActionsRunOut) { EXPECT_CALL(foo_, Bar2(_, _)) .Times(2) .WillOnce(Return(false)); foo_.Bar2(2, 2); foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. } TEST_F(GMockOutputTest, UnexpectedCall) { EXPECT_CALL(foo_, Bar2(0, _)); foo_.Bar2(1, 0); // Unexpected call foo_.Bar2(0, 0); // Expected call } TEST_F(GMockOutputTest, UnexpectedCallToVoidFunction) { EXPECT_CALL(foo_, Bar3(0, _)); foo_.Bar3(1, 0); // Unexpected call foo_.Bar3(0, 0); // Expected call } TEST_F(GMockOutputTest, ExcessiveCall) { EXPECT_CALL(foo_, Bar2(0, _)); foo_.Bar2(0, 0); // Expected call foo_.Bar2(0, 1); // Excessive call } TEST_F(GMockOutputTest, ExcessiveCallToVoidFunction) { EXPECT_CALL(foo_, Bar3(0, _)); foo_.Bar3(0, 0); // Expected call foo_.Bar3(0, 1); // Excessive call } TEST_F(GMockOutputTest, UninterestingCall) { foo_.Bar2(0, 1); // Uninteresting call } TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) { foo_.Bar3(0, 1); // Uninteresting call } TEST_F(GMockOutputTest, RetiredExpectation) { EXPECT_CALL(foo_, Bar2(_, _)) .RetiresOnSaturation(); EXPECT_CALL(foo_, Bar2(0, 0)); foo_.Bar2(1, 1); foo_.Bar2(1, 1); // Matches a retired expectation foo_.Bar2(0, 0); } TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) { { InSequence s; EXPECT_CALL(foo_, Bar(_, 0, _)); EXPECT_CALL(foo_, Bar2(0, 0)); EXPECT_CALL(foo_, Bar2(1, _)); } foo_.Bar2(1, 0); // Has one immediate unsatisfied pre-requisite foo_.Bar("Hi", 0, 0); foo_.Bar2(0, 0); foo_.Bar2(1, 0); } TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) { Sequence s1, s2; EXPECT_CALL(foo_, Bar(_, 0, _)) .InSequence(s1); EXPECT_CALL(foo_, Bar2(0, 0)) .InSequence(s2); EXPECT_CALL(foo_, Bar2(1, _)) .InSequence(s1, s2); foo_.Bar2(1, 0); // Has two immediate unsatisfied pre-requisites foo_.Bar("Hi", 0, 0); foo_.Bar2(0, 0); foo_.Bar2(1, 0); } TEST_F(GMockOutputTest, UnsatisfiedWith) { EXPECT_CALL(foo_, Bar2(_, _)).With(Ge()); } TEST_F(GMockOutputTest, UnsatisfiedExpectation) { EXPECT_CALL(foo_, Bar(_, _, _)); EXPECT_CALL(foo_, Bar2(0, _)) .Times(2); foo_.Bar2(0, 1); } TEST_F(GMockOutputTest, MismatchArguments) { const std::string s = "Hi"; EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0))); foo_.Bar("Ho", 0, -0.1); // Mismatch arguments foo_.Bar(s, 0, 0); } TEST_F(GMockOutputTest, MismatchWith) { EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) .With(Ge()); foo_.Bar2(2, 3); // Mismatch With() foo_.Bar2(2, 1); } TEST_F(GMockOutputTest, MismatchArgumentsAndWith) { EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) .With(Ge()); foo_.Bar2(1, 3); // Mismatch arguments and mismatch With() foo_.Bar2(2, 1); } TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)) .WillByDefault(Return(false)); // Default action #2 EXPECT_CALL(foo_, Bar2(2, 2)); foo_.Bar2(1, 0); // Unexpected call, takes default action #2. foo_.Bar2(0, 0); // Unexpected call, takes default action #1. foo_.Bar2(2, 2); // Expected call. } TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)) .WillByDefault(Return(false)); // Default action #2 EXPECT_CALL(foo_, Bar2(2, 2)); EXPECT_CALL(foo_, Bar2(1, 1)); foo_.Bar2(2, 2); // Expected call. foo_.Bar2(2, 2); // Excessive call, takes default action #1. foo_.Bar2(1, 1); // Expected call. foo_.Bar2(1, 1); // Excessive call, takes default action #2. } TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)) .WillByDefault(Return(false)); // Default action #2 foo_.Bar2(2, 2); // Uninteresting call, takes default action #1. foo_.Bar2(1, 1); // Uninteresting call, takes default action #2. } TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 EXPECT_CALL(foo_, Bar2(_, _)) .Times(2) .WillOnce(Return(false)); foo_.Bar2(2, 2); foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. } TEST_F(GMockOutputTest, CatchesLeakedMocks) { MockFoo* foo1 = new MockFoo; MockFoo* foo2 = new MockFoo; // Invokes ON_CALL on foo1. ON_CALL(*foo1, Bar(_, _, _)).WillByDefault(Return('a')); // Invokes EXPECT_CALL on foo2. EXPECT_CALL(*foo2, Bar2(_, _)); EXPECT_CALL(*foo2, Bar2(1, _)); EXPECT_CALL(*foo2, Bar3(_, _)).Times(AnyNumber()); foo2->Bar2(2, 1); foo2->Bar2(1, 1); // Both foo1 and foo2 are deliberately leaked. } MATCHER_P2(IsPair, first, second, "") { return Value(arg.first, first) && Value(arg.second, second); } TEST_F(GMockOutputTest, PrintsMatcher) { const testing::Matcher<int> m1 = Ge(48); EXPECT_THAT((std::pair<int, bool>(42, true)), IsPair(m1, true)); } void TestCatchesLeakedMocksInAdHocTests() { MockFoo* foo = new MockFoo; // Invokes EXPECT_CALL on foo. EXPECT_CALL(*foo, Bar2(_, _)); foo->Bar2(2, 1); // foo is deliberately leaked. } int main(int argc, char **argv) { testing::InitGoogleMock(&argc, argv); // Ensures that the tests pass no matter what value of // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. testing::GMOCK_FLAG(catch_leaked_mocks) = true; testing::GMOCK_FLAG(verbose) = "warning"; TestCatchesLeakedMocksInAdHocTests(); return RUN_ALL_TESTS(); } #ifdef _MSC_VER # if _MSC_VER <= 1900 # pragma warning(pop) # endif #endif <commit_msg><commit_after>// Copyright 2008, 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. // // Author: [email protected] (Zhanyong Wan) // Tests Google Mock's output in various scenarios. This ensures that // Google Mock's messages are readable and useful. #include "gmock/gmock.h" #include <stdio.h> #include <string> #include "gtest/gtest.h" // Silence C4100 (unreferenced formal parameter) for MSVC 14 and 15 #ifdef _MSC_VER # if _MSC_VER <= 1900 # pragma warning(push) # pragma warning(disable:4100) # endif #endif using testing::_; using testing::AnyNumber; using testing::Ge; using testing::InSequence; using testing::NaggyMock; using testing::Ref; using testing::Return; using testing::Sequence; using testing::Value; class MockFoo { public: MockFoo() {} MOCK_METHOD3(Bar, char(const std::string& s, int i, double x)); MOCK_METHOD2(Bar2, bool(int x, int y)); MOCK_METHOD2(Bar3, void(int x, int y)); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); }; class GMockOutputTest : public testing::Test { protected: NaggyMock<MockFoo> foo_; }; TEST_F(GMockOutputTest, ExpectedCall) { testing::GMOCK_FLAG(verbose) = "info"; EXPECT_CALL(foo_, Bar2(0, _)); foo_.Bar2(0, 0); // Expected call testing::GMOCK_FLAG(verbose) = "warning"; } TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) { testing::GMOCK_FLAG(verbose) = "info"; EXPECT_CALL(foo_, Bar3(0, _)); foo_.Bar3(0, 0); // Expected call testing::GMOCK_FLAG(verbose) = "warning"; } TEST_F(GMockOutputTest, ExplicitActionsRunOut) { EXPECT_CALL(foo_, Bar2(_, _)) .Times(2) .WillOnce(Return(false)); foo_.Bar2(2, 2); foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. } TEST_F(GMockOutputTest, UnexpectedCall) { EXPECT_CALL(foo_, Bar2(0, _)); foo_.Bar2(1, 0); // Unexpected call foo_.Bar2(0, 0); // Expected call } TEST_F(GMockOutputTest, UnexpectedCallToVoidFunction) { EXPECT_CALL(foo_, Bar3(0, _)); foo_.Bar3(1, 0); // Unexpected call foo_.Bar3(0, 0); // Expected call } TEST_F(GMockOutputTest, ExcessiveCall) { EXPECT_CALL(foo_, Bar2(0, _)); foo_.Bar2(0, 0); // Expected call foo_.Bar2(0, 1); // Excessive call } TEST_F(GMockOutputTest, ExcessiveCallToVoidFunction) { EXPECT_CALL(foo_, Bar3(0, _)); foo_.Bar3(0, 0); // Expected call foo_.Bar3(0, 1); // Excessive call } TEST_F(GMockOutputTest, UninterestingCall) { foo_.Bar2(0, 1); // Uninteresting call } TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) { foo_.Bar3(0, 1); // Uninteresting call } TEST_F(GMockOutputTest, RetiredExpectation) { EXPECT_CALL(foo_, Bar2(_, _)) .RetiresOnSaturation(); EXPECT_CALL(foo_, Bar2(0, 0)); foo_.Bar2(1, 1); foo_.Bar2(1, 1); // Matches a retired expectation foo_.Bar2(0, 0); } TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) { { InSequence s; EXPECT_CALL(foo_, Bar(_, 0, _)); EXPECT_CALL(foo_, Bar2(0, 0)); EXPECT_CALL(foo_, Bar2(1, _)); } foo_.Bar2(1, 0); // Has one immediate unsatisfied pre-requisite foo_.Bar("Hi", 0, 0); foo_.Bar2(0, 0); foo_.Bar2(1, 0); } TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) { Sequence s1, s2; EXPECT_CALL(foo_, Bar(_, 0, _)) .InSequence(s1); EXPECT_CALL(foo_, Bar2(0, 0)) .InSequence(s2); EXPECT_CALL(foo_, Bar2(1, _)) .InSequence(s1, s2); foo_.Bar2(1, 0); // Has two immediate unsatisfied pre-requisites foo_.Bar("Hi", 0, 0); foo_.Bar2(0, 0); foo_.Bar2(1, 0); } TEST_F(GMockOutputTest, UnsatisfiedWith) { EXPECT_CALL(foo_, Bar2(_, _)).With(Ge()); } TEST_F(GMockOutputTest, UnsatisfiedExpectation) { EXPECT_CALL(foo_, Bar(_, _, _)); EXPECT_CALL(foo_, Bar2(0, _)) .Times(2); foo_.Bar2(0, 1); } TEST_F(GMockOutputTest, MismatchArguments) { const std::string s = "Hi"; EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0))); foo_.Bar("Ho", 0, -0.1); // Mismatch arguments foo_.Bar(s, 0, 0); } TEST_F(GMockOutputTest, MismatchWith) { EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) .With(Ge()); foo_.Bar2(2, 3); // Mismatch With() foo_.Bar2(2, 1); } TEST_F(GMockOutputTest, MismatchArgumentsAndWith) { EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) .With(Ge()); foo_.Bar2(1, 3); // Mismatch arguments and mismatch With() foo_.Bar2(2, 1); } TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)) .WillByDefault(Return(false)); // Default action #2 EXPECT_CALL(foo_, Bar2(2, 2)); foo_.Bar2(1, 0); // Unexpected call, takes default action #2. foo_.Bar2(0, 0); // Unexpected call, takes default action #1. foo_.Bar2(2, 2); // Expected call. } TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)) .WillByDefault(Return(false)); // Default action #2 EXPECT_CALL(foo_, Bar2(2, 2)); EXPECT_CALL(foo_, Bar2(1, 1)); foo_.Bar2(2, 2); // Expected call. foo_.Bar2(2, 2); // Excessive call, takes default action #1. foo_.Bar2(1, 1); // Expected call. foo_.Bar2(1, 1); // Excessive call, takes default action #2. } TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)) .WillByDefault(Return(false)); // Default action #2 foo_.Bar2(2, 2); // Uninteresting call, takes default action #1. foo_.Bar2(1, 1); // Uninteresting call, takes default action #2. } TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 EXPECT_CALL(foo_, Bar2(_, _)) .Times(2) .WillOnce(Return(false)); foo_.Bar2(2, 2); foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. } TEST_F(GMockOutputTest, CatchesLeakedMocks) { MockFoo* foo1 = new MockFoo; MockFoo* foo2 = new MockFoo; // Invokes ON_CALL on foo1. ON_CALL(*foo1, Bar(_, _, _)).WillByDefault(Return('a')); // Invokes EXPECT_CALL on foo2. EXPECT_CALL(*foo2, Bar2(_, _)); EXPECT_CALL(*foo2, Bar2(1, _)); EXPECT_CALL(*foo2, Bar3(_, _)).Times(AnyNumber()); foo2->Bar2(2, 1); foo2->Bar2(1, 1); // Both foo1 and foo2 are deliberately leaked. } MATCHER_P2(IsPair, first, second, "") { return Value(arg.first, first) && Value(arg.second, second); } TEST_F(GMockOutputTest, PrintsMatcher) { const testing::Matcher<int> m1 = Ge(48); EXPECT_THAT((std::pair<int, bool>(42, true)), IsPair(m1, true)); } void TestCatchesLeakedMocksInAdHocTests() { MockFoo* foo = new MockFoo; // Invokes EXPECT_CALL on foo. EXPECT_CALL(*foo, Bar2(_, _)); foo->Bar2(2, 1); // foo is deliberately leaked. } int main(int argc, char **argv) { testing::InitGoogleMock(&argc, argv); // Ensures that the tests pass no matter what value of // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. testing::GMOCK_FLAG(catch_leaked_mocks) = true; testing::GMOCK_FLAG(verbose) = "warning"; TestCatchesLeakedMocksInAdHocTests(); return RUN_ALL_TESTS(); } #ifdef _MSC_VER # if _MSC_VER <= 1900 # pragma warning(pop) # endif #endif <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <stdexcept> template <typename T> class stack { public: stack(); ~stack()noexcept; stack(stack<T> const&)noexcept; stack& operator=(stack<T> const&)noexcept; size_t count()const noexcept; size_t array_size()const noexcept; void push(T const&)noexcept; void pop()noexcept; T top()noexcept; void print(std::ostream&stream)const noexcept; friend std::ostream&operator << (std::ostream&stream, const stack<T>&)noexcept; void swap(stack<T>&)noexcept; bool empty()noexcept; private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {} template <typename T> stack<T>::~stack()noexcept { delete[] array_; } template <typename T> stack<T>::stack(stack<T> const& other)noexcept { array_size_ = other.array_size_; count_ = other.count_; std::copy(other.array_, other.array_ + count_, array_); } template <typename T> stack<T>& stack<T>::operator=(stack<T> const & other)noexcept { if (&other != this) stack(other).swap(*this); return *this; } template <typename T> size_t stack<T>::array_size()const noexcept { return array_size_; } template <typename T> size_t stack<T>::count()const noexcept { return count_; } template <typename T> void stack<T>::push(T const & value)noexcept { if (empty()) { array_size_ = 1; array_ = new T[array_size_](); } else if (array_size_ == count_) { array_size_ *= 2; T * new_array = new T[array_size_](); std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } array_[count_++] = value; } template <typename T> void stack<T>::pop()noexcept { if (empty()) throw std::logic_error("Stack is empty"); else { T * new_array = new T[array_size_](); --count_; std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } } template <typename T> T stack<T>::top()noexcept { if (empty()) throw std::logic_error("Stack is empty"); else return array_[count - 1]; } template <typename T> void stack<T>::print(std::ostream&stream)const noexcept { for (unsigned int i = 0; i < count_; ++i) stream << array_[i] << " "; stream << std::endl; } template <typename T> std::ostream& operator << (std::ostream&stream, const stack<T>&stack_)noexcept { return stack_.print(stream); } template <typename T> void stack<T>::swap(stack<T>& other)noexcept { std::swap(array_, other.array_); std::swap(array_size_, other.array_size_); std::swap(count_, other.count_); } template <typename T> bool stack<T>::empty()noexcept { return (count_ == 0) ? true : false; } <commit_msg>Update stack.hpp<commit_after>#include <iostream> #include <algorithm> #include <stdexcept> template <typename T> class stack { public: stack(); ~stack()noexcept; stack(stack<T> const&)noexcept; stack& operator=(stack<T> const&)noexcept; size_t count()const noexcept; size_t array_size()const noexcept; void push(T const&)noexcept; void pop()noexcept; T top()noexcept; void print(std::ostream&stream)const noexcept; friend std::ostream&operator << (std::ostream&stream, const stack<T>&)noexcept; void swap(stack<T>&)noexcept; bool empty()noexcept; private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {} template <typename T> stack<T>::~stack()noexcept { delete[] array_; } template <typename T> stack<T>::stack(stack<T> const& other)noexcept { array_size_ = other.array_size_; count_ = other.count_; std::copy(other.array_, other.array_ + count_, array_); } template <typename T> stack<T>& stack<T>::operator=(stack<T> const & other)noexcept { if (&other != this) stack(other).swap(*this); return *this; } template <typename T> size_t stack<T>::array_size()const noexcept { return array_size_; } template <typename T> size_t stack<T>::count()const noexcept { return count_; } template <typename T> void stack<T>::push(T const & value)noexcept { if (empty()) { array_size_ = 1; array_ = new T[array_size_](); } else if (array_size_ == count_) { array_size_ *= 2; T * new_array = new T[array_size_](); std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } array_[count_++] = value; } template <typename T> void stack<T>::pop()noexcept { if (empty()) throw std::logic_error("Stack is empty"); else { T * new_array = new T[array_size_](); --count_; std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } } template <typename T> T stack<T>::top()noexcept { if (empty()) throw std::logic_error("Stack is empty"); else return array_[count_ - 1]; } template <typename T> void stack<T>::print(std::ostream&stream)const noexcept { for (unsigned int i = 0; i < count_; ++i) stream << array_[i] << " "; stream << std::endl; } template <typename T> std::ostream& operator << (std::ostream&stream, const stack<T>&stack_)noexcept { return stack_.print(stream); } template <typename T> void stack<T>::swap(stack<T>& other)noexcept { std::swap(array_, other.array_); std::swap(array_size_, other.array_size_); std::swap(count_, other.count_); } template <typename T> bool stack<T>::empty()noexcept { return (count_ == 0) ? true : false; } <|endoftext|>
<commit_before>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2021 Antti Nuortimo. // // 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 <https://www.gnu.org/licenses/>. #include "gtest/gtest.h" #include "code/ylikuutio/ontology/glyph_struct.hpp" // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif TEST(glyph_struct_must_be_initialized_appropriately, glyph_struct) { const yli::ontology::GlyphStruct test_glyph_struct; ASSERT_EQ(test_glyph_struct.light_position, glm::vec3(0.0f, 0.0f, 0.0f)); ASSERT_EQ(test_glyph_struct.glyph_vertex_data, nullptr); ASSERT_EQ(test_glyph_struct.glyph_name_pointer, nullptr); ASSERT_EQ(test_glyph_struct.unicode_char_pointer, nullptr); ASSERT_EQ(test_glyph_struct.universe, nullptr); ASSERT_EQ(test_glyph_struct.shader, nullptr); ASSERT_EQ(test_glyph_struct.parent, nullptr); ASSERT_EQ(test_glyph_struct.opengl_in_use, true); } <commit_msg>Remove obsolete unit test file.<commit_after><|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test.hpp" TEST_CASE("shuffle/0", "[shuffle]") { const size_t N = 137; float* a_cpu = new float[N]; for (size_t i = 0; i < N; ++i) { a_cpu[i] = i; } float* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * sizeof(float))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); egblas_shuffle(N, a_gpu, sizeof(float)); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); // Make sure we find each number in [0,N[ for (size_t i = 0; i < N; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N, float(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("shuffle/1", "[shuffle]") { const size_t N = 129; double* a_cpu = new double[N]; for (size_t i = 0; i < N; ++i) { a_cpu[i] = i; } double* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * sizeof(double))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * sizeof(double), cudaMemcpyHostToDevice)); egblas_shuffle(N, a_gpu, sizeof(double)); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * sizeof(double), cudaMemcpyDeviceToHost)); // Make sure we find each number in [0,N[ for (size_t i = 0; i < N; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N, double(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("shuffle/2", "[shuffle]") { const size_t N = 129; double* a_cpu = new double[N]; for (size_t i = 0; i < N; ++i) { a_cpu[i] = i; } double* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * sizeof(double))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * sizeof(double), cudaMemcpyHostToDevice)); egblas_shuffle_seed(N, a_gpu, sizeof(double), 123); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * sizeof(double), cudaMemcpyDeviceToHost)); // Make sure we find each number in [0,N[ for (size_t i = 0; i < N; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N, double(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("shuffle/3", "[shuffle]") { const size_t N = 129; const size_t S = 16; double* a_cpu = new double[N * S]; for (size_t i = 0; i < N * S; ++i) { a_cpu[i] = i; } double* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * S * sizeof(double))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * S * sizeof(double), cudaMemcpyHostToDevice)); egblas_shuffle_seed(N, a_gpu, S * sizeof(double), 123); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * S * sizeof(double), cudaMemcpyDeviceToHost)); // Make sure the sub order is correct for (size_t i = 0; i < N; ++i) { for(size_t j = 1; j < S; ++j){ REQUIRE(a_cpu[(i * S) + j] == 1 + a_cpu[(i * S) + j - 1]); } } // Make sure we find each number in [0,N[ for (size_t i = 0; i < N * S; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N * S, double(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("shuffle/4", "[shuffle]") { const size_t N = 129; const size_t S = 23; double* a_cpu = new double[N * S]; for (size_t i = 0; i < N * S; ++i) { a_cpu[i] = i; } double* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * S * sizeof(double))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * S * sizeof(double), cudaMemcpyHostToDevice)); egblas_shuffle_seed(N, a_gpu, S * sizeof(double), 123); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * S * sizeof(double), cudaMemcpyDeviceToHost)); // Make sure the sub order is correct for (size_t i = 0; i < N; ++i) { for(size_t j = 1; j < S; ++j){ REQUIRE(a_cpu[(i * S) + j] == 1 + a_cpu[(i * S) + j - 1]); } } // Make sure we find each number in [0,N[ for (size_t i = 0; i < N * S; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N * S, double(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("shuffle/5", "[shuffle]") { const size_t N = 129; const size_t S = 23; float* a_cpu = new float[N * S]; for (size_t i = 0; i < N * S; ++i) { a_cpu[i] = i; } float* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * S * sizeof(float))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * S * sizeof(float), cudaMemcpyHostToDevice)); egblas_shuffle_seed(N, a_gpu, S * sizeof(float), 123); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * S * sizeof(float), cudaMemcpyDeviceToHost)); // Make sure the sub order is correct for (size_t i = 0; i < N; ++i) { for(size_t j = 1; j < S; ++j){ REQUIRE(a_cpu[(i * S) + j] == 1 + a_cpu[(i * S) + j - 1]); } } // Make sure we find each number in [0,N[ for (size_t i = 0; i < N * S; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N * S, double(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("par_shuffle/0", "[shuffle]") { const size_t N = 137; float* a_cpu = new float[N]; float* b_cpu = new float[N]; for (size_t i = 0; i < N; ++i) { a_cpu[i] = float(i); b_cpu[i] = float(i) + 1.0f; } float* a_gpu; float* b_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * sizeof(float))); cuda_check(cudaMalloc((void**)&b_gpu, N * sizeof(float))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); cuda_check(cudaMemcpy(b_gpu, b_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); egblas_par_shuffle(N, a_gpu, sizeof(float), b_gpu, sizeof(float)); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(b_cpu, b_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); for (size_t i = 0; i < N; ++i) { REQUIRE(a_cpu[i] + 1.0f == b_cpu[i]); for (size_t j = i + 1; j < N; ++j) { REQUIRE(a_cpu[i] != a_cpu[j]); REQUIRE(b_cpu[i] != b_cpu[j]); } } cuda_check(cudaFree(a_gpu)); cuda_check(cudaFree(b_gpu)); delete[] a_cpu; delete[] b_cpu; } TEST_CASE("par_shuffle/1", "[shuffle]") { const size_t N = 137; float* a_cpu = new float[N]; double* b_cpu = new double[N]; for (size_t i = 0; i < N; ++i) { a_cpu[i] = float(i); b_cpu[i] = double(i) + 1.0; } float* a_gpu; double* b_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * sizeof(float))); cuda_check(cudaMalloc((void**)&b_gpu, N * sizeof(double))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); cuda_check(cudaMemcpy(b_gpu, b_cpu, N * sizeof(double), cudaMemcpyHostToDevice)); egblas_par_shuffle(N, a_gpu, sizeof(float), b_gpu, sizeof(double)); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(b_cpu, b_gpu, N * sizeof(double), cudaMemcpyDeviceToHost)); for (size_t i = 0; i < N; ++i) { REQUIRE(double(a_cpu[i] + 1.0) == b_cpu[i]); for (size_t j = i + 1; j < N; ++j) { REQUIRE(a_cpu[i] != a_cpu[j]); REQUIRE(b_cpu[i] != b_cpu[j]); } } cuda_check(cudaFree(a_gpu)); cuda_check(cudaFree(b_gpu)); delete[] a_cpu; delete[] b_cpu; } <commit_msg>Complete par_shuffle tests<commit_after>//======================================================================= // Copyright (c) 2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test.hpp" TEST_CASE("shuffle/0", "[shuffle]") { const size_t N = 137; float* a_cpu = new float[N]; for (size_t i = 0; i < N; ++i) { a_cpu[i] = i; } float* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * sizeof(float))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); egblas_shuffle(N, a_gpu, sizeof(float)); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); // Make sure we find each number in [0,N[ for (size_t i = 0; i < N; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N, float(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("shuffle/1", "[shuffle]") { const size_t N = 129; double* a_cpu = new double[N]; for (size_t i = 0; i < N; ++i) { a_cpu[i] = i; } double* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * sizeof(double))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * sizeof(double), cudaMemcpyHostToDevice)); egblas_shuffle(N, a_gpu, sizeof(double)); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * sizeof(double), cudaMemcpyDeviceToHost)); // Make sure we find each number in [0,N[ for (size_t i = 0; i < N; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N, double(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("shuffle/2", "[shuffle]") { const size_t N = 129; double* a_cpu = new double[N]; for (size_t i = 0; i < N; ++i) { a_cpu[i] = i; } double* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * sizeof(double))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * sizeof(double), cudaMemcpyHostToDevice)); egblas_shuffle_seed(N, a_gpu, sizeof(double), 123); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * sizeof(double), cudaMemcpyDeviceToHost)); // Make sure we find each number in [0,N[ for (size_t i = 0; i < N; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N, double(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("shuffle/3", "[shuffle]") { const size_t N = 129; const size_t S = 16; double* a_cpu = new double[N * S]; for (size_t i = 0; i < N * S; ++i) { a_cpu[i] = i; } double* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * S * sizeof(double))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * S * sizeof(double), cudaMemcpyHostToDevice)); egblas_shuffle_seed(N, a_gpu, S * sizeof(double), 123); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * S * sizeof(double), cudaMemcpyDeviceToHost)); // Make sure the sub order is correct for (size_t i = 0; i < N; ++i) { for(size_t j = 1; j < S; ++j){ REQUIRE(a_cpu[(i * S) + j] == 1 + a_cpu[(i * S) + j - 1]); } } // Make sure we find each number in [0,N[ for (size_t i = 0; i < N * S; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N * S, double(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("shuffle/4", "[shuffle]") { const size_t N = 129; const size_t S = 23; double* a_cpu = new double[N * S]; for (size_t i = 0; i < N * S; ++i) { a_cpu[i] = i; } double* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * S * sizeof(double))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * S * sizeof(double), cudaMemcpyHostToDevice)); egblas_shuffle_seed(N, a_gpu, S * sizeof(double), 123); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * S * sizeof(double), cudaMemcpyDeviceToHost)); // Make sure the sub order is correct for (size_t i = 0; i < N; ++i) { for(size_t j = 1; j < S; ++j){ REQUIRE(a_cpu[(i * S) + j] == 1 + a_cpu[(i * S) + j - 1]); } } // Make sure we find each number in [0,N[ for (size_t i = 0; i < N * S; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N * S, double(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("shuffle/5", "[shuffle]") { const size_t N = 129; const size_t S = 23; float* a_cpu = new float[N * S]; for (size_t i = 0; i < N * S; ++i) { a_cpu[i] = i; } float* a_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * S * sizeof(float))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * S * sizeof(float), cudaMemcpyHostToDevice)); egblas_shuffle_seed(N, a_gpu, S * sizeof(float), 123); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * S * sizeof(float), cudaMemcpyDeviceToHost)); // Make sure the sub order is correct for (size_t i = 0; i < N; ++i) { for(size_t j = 1; j < S; ++j){ REQUIRE(a_cpu[(i * S) + j] == 1 + a_cpu[(i * S) + j - 1]); } } // Make sure we find each number in [0,N[ for (size_t i = 0; i < N * S; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N * S, double(i)) == 1); } cuda_check(cudaFree(a_gpu)); delete[] a_cpu; } TEST_CASE("par_shuffle/0", "[shuffle]") { const size_t N = 137; float* a_cpu = new float[N]; float* b_cpu = new float[N]; for (size_t i = 0; i < N; ++i) { a_cpu[i] = float(i); b_cpu[i] = float(i) + 1.0f; } float* a_gpu; float* b_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * sizeof(float))); cuda_check(cudaMalloc((void**)&b_gpu, N * sizeof(float))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); cuda_check(cudaMemcpy(b_gpu, b_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); egblas_par_shuffle(N, a_gpu, sizeof(float), b_gpu, sizeof(float)); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(b_cpu, b_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); for (size_t i = 0; i < N; ++i) { REQUIRE(a_cpu[i] + 1.0f == b_cpu[i]); for (size_t j = i + 1; j < N; ++j) { REQUIRE(a_cpu[i] != a_cpu[j]); REQUIRE(b_cpu[i] != b_cpu[j]); } } cuda_check(cudaFree(a_gpu)); cuda_check(cudaFree(b_gpu)); delete[] a_cpu; delete[] b_cpu; } TEST_CASE("par_shuffle/1", "[shuffle]") { const size_t N = 137; float* a_cpu = new float[N]; double* b_cpu = new double[N]; for (size_t i = 0; i < N; ++i) { a_cpu[i] = float(i); b_cpu[i] = double(i) + 1.0; } float* a_gpu; double* b_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * sizeof(float))); cuda_check(cudaMalloc((void**)&b_gpu, N * sizeof(double))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); cuda_check(cudaMemcpy(b_gpu, b_cpu, N * sizeof(double), cudaMemcpyHostToDevice)); egblas_par_shuffle(N, a_gpu, sizeof(float), b_gpu, sizeof(double)); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(b_cpu, b_gpu, N * sizeof(double), cudaMemcpyDeviceToHost)); for (size_t i = 0; i < N; ++i) { REQUIRE(double(a_cpu[i] + 1.0) == b_cpu[i]); for (size_t j = i + 1; j < N; ++j) { REQUIRE(a_cpu[i] != a_cpu[j]); REQUIRE(b_cpu[i] != b_cpu[j]); } } cuda_check(cudaFree(a_gpu)); cuda_check(cudaFree(b_gpu)); delete[] a_cpu; delete[] b_cpu; } TEST_CASE("par_shuffle/2", "[shuffle]") { const size_t N = 137; float* a_cpu = new float[N]; float* b_cpu = new float[N]; for (size_t i = 0; i < N; ++i) { a_cpu[i] = float(i); b_cpu[i] = float(i); } float* a_gpu; float* b_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * sizeof(float))); cuda_check(cudaMalloc((void**)&b_gpu, N * sizeof(float))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); cuda_check(cudaMemcpy(b_gpu, b_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); egblas_par_shuffle(N, a_gpu, sizeof(float), b_gpu, sizeof(float)); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(b_cpu, b_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); for (size_t i = 0; i < N; ++i) { REQUIRE(a_cpu[i] == b_cpu[i]); REQUIRE(std::count(a_cpu, a_cpu + N, float(i)) == 1); REQUIRE(std::count(b_cpu, b_cpu + N, float(i)) == 1); } cuda_check(cudaFree(a_gpu)); cuda_check(cudaFree(b_gpu)); delete[] a_cpu; delete[] b_cpu; } TEST_CASE("par_shuffle/3", "[shuffle]") { const size_t N = 137; const size_t S = 17; float* a_cpu = new float[N * S]; float* b_cpu = new float[N * S]; for (size_t i = 0; i < N * S; ++i) { a_cpu[i] = float(i); b_cpu[i] = 1.0f + float(i); } float* a_gpu; float* b_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * S * sizeof(float))); cuda_check(cudaMalloc((void**)&b_gpu, N * S * sizeof(float))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * S * sizeof(float), cudaMemcpyHostToDevice)); cuda_check(cudaMemcpy(b_gpu, b_cpu, N * S * sizeof(float), cudaMemcpyHostToDevice)); egblas_par_shuffle(N, a_gpu, S * sizeof(float), b_gpu, S * sizeof(float)); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * S * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(b_cpu, b_gpu, N * S * sizeof(float), cudaMemcpyDeviceToHost)); // Make sure the sub order is correct for (size_t i = 0; i < N; ++i) { for(size_t j = 1; j < S; ++j){ REQUIRE(a_cpu[(i * S) + j] == 1 + a_cpu[(i * S) + j - 1]); REQUIRE(b_cpu[(i * S) + j] == 1 + b_cpu[(i * S) + j - 1]); } } for (size_t i = 0; i < N; ++i) { REQUIRE(a_cpu[i] + 1.0f == b_cpu[i]); REQUIRE(std::count(a_cpu, a_cpu + N * S, float(i)) == 1); REQUIRE(std::count(b_cpu, b_cpu + N * S, float(i+1)) == 1); } cuda_check(cudaFree(a_gpu)); cuda_check(cudaFree(b_gpu)); delete[] a_cpu; delete[] b_cpu; } TEST_CASE("par_shuffle/4", "[shuffle]") { const size_t N = 137; const size_t S1 = 19; const size_t S2 = 7; float* a_cpu = new float[N * S1]; float* b_cpu = new float[N * S2]; for (size_t i = 0; i < N * S1; ++i) { a_cpu[i] = float(i); } for (size_t i = 0; i < N * S2; ++i) { b_cpu[i] = 1.0f + float(i); } float* a_gpu; float* b_gpu; cuda_check(cudaMalloc((void**)&a_gpu, N * S1 * sizeof(float))); cuda_check(cudaMalloc((void**)&b_gpu, N * S2 * sizeof(float))); cuda_check(cudaMemcpy(a_gpu, a_cpu, N * S1 * sizeof(float), cudaMemcpyHostToDevice)); cuda_check(cudaMemcpy(b_gpu, b_cpu, N * S2 * sizeof(float), cudaMemcpyHostToDevice)); egblas_par_shuffle(N, a_gpu, S1 * sizeof(float), b_gpu, S2 * sizeof(float)); cuda_check(cudaMemcpy(a_cpu, a_gpu, N * S1 * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(b_cpu, b_gpu, N * S2 * sizeof(float), cudaMemcpyDeviceToHost)); // Make sure the sub order is correct for (size_t i = 0; i < N; ++i) { for(size_t j = 1; j < S1; ++j){ REQUIRE(a_cpu[(i * S1) + j] == 1 + a_cpu[(i * S1) + j - 1]); } for(size_t j = 1; j < S2; ++j){ REQUIRE(b_cpu[(i * S2) + j] == 1 + b_cpu[(i * S2) + j - 1]); } } for (size_t i = 0; i < N * S1; ++i) { REQUIRE(std::count(a_cpu, a_cpu + N * S1, float(i)) == 1); } for (size_t i = 0; i < N * S2; ++i) { REQUIRE(std::count(b_cpu, b_cpu + N * S2, float(i+1)) == 1); } cuda_check(cudaFree(a_gpu)); cuda_check(cudaFree(b_gpu)); delete[] a_cpu; delete[] b_cpu; } <|endoftext|>
<commit_before>/* Reproducing xfstest generic/106 1. Create file foo, create a link foo_link and sync 2. Unlink foo_link, drop caches and fsync foo After a crash, after the file foo is removed, the directory should be removeable. https://github.com/kdave/xfstests/blob/master/tests/generic/106 */ #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <iostream> #include <dirent.h> #include <cstring> #include <errno.h> #include "BaseTestCase.h" #include "../user_tools/api/workload.h" #include "../user_tools/api/actions.h" #define TEST_FILE_FOO "foo" #define TEST_FILE_FOO_LINK "foo_link_" #define TEST_DIR_A "test_dir_a" using fs_testing::tests::DataTestResult; using fs_testing::user_tools::api::WriteData; using fs_testing::user_tools::api::WriteDataMmap; using fs_testing::user_tools::api::Checkpoint; using std::string; #define TEST_FILE_PERMS ((mode_t) (S_IRWXU | S_IRWXG | S_IRWXO)) namespace fs_testing { namespace tests { class Generic106: public BaseTestCase { public: virtual int setup() override { init_paths(); // Create test directory A. string dir_path = mnt_dir_ + "/" TEST_DIR_A; int res = mkdir(dir_path.c_str(), 0777); if (res < 0) { return -1; } //Create file foo in TEST_DIR_A const int fd_foo = open(foo_path.c_str(), O_RDWR | O_CREAT, TEST_FILE_PERMS); if (fd_foo < 0) { return -1; } // Create a new hard link if(link(foo_path.c_str(), foo_link_path.c_str()) < 0){ return -2; } sync(); close(fd_foo); return 0; } virtual int run() override { init_paths(); // Unlink foo_link if(unlink(foo_link_path.c_str()) < 0){ return -3; } // drop caches if (system("echo 2 > /proc/sys/vm/drop_caches") < 0) { return -4; } const int fd_foo = open(foo_path.c_str(), O_RDWR | O_CREAT, TEST_FILE_PERMS); if (fd_foo < 0) { return -5; } if (fsync(fd_foo) < 0) { return -6; } // Make a user checkpoint here if (Checkpoint() < 0){ return -7; } //Close open files close(fd_foo); return 0; } virtual int check_test(unsigned int last_checkpoint, DataTestResult *test_result) override { init_paths(); string dir = mnt_dir_ + "/" TEST_DIR_A; string rm_cmd = "rm -f " + dir + "/*"; // Remove files within the directory system(rm_cmd.c_str()); // Directory should be removeable if (rmdir(dir.c_str()) < 0) { test_result->SetError(DataTestResult::kFileMetadataCorrupted); test_result->error_description = " : Unable to remove directory after deleting files"; } return 0; } private: string foo_path; string foo_link_path; void init_paths() { foo_path = mnt_dir_ + "/" TEST_DIR_A "/" TEST_FILE_FOO; foo_link_path = mnt_dir_ + "/" TEST_DIR_A "/" TEST_FILE_FOO_LINK; } }; } // namespace tests } // namespace fs_testing extern "C" fs_testing::tests::BaseTestCase *test_case_get_instance() { return new fs_testing::tests::Generic106; } extern "C" void test_case_delete_instance(fs_testing::tests::BaseTestCase *tc) { delete tc; } <commit_msg>Modify standalone to reproduce bug on 3.13<commit_after>/* Reproducing xfstest generic/106 1. Create file foo, create a link foo_link and sync 2. Unlink foo_link, drop caches and fsync foo After a crash, after the file foo is removed, the directory should be removeable. https://github.com/kdave/xfstests/blob/master/tests/generic/106 */ #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <iostream> #include <dirent.h> #include <cstring> #include <errno.h> #include "BaseTestCase.h" #include "../user_tools/api/workload.h" #include "../user_tools/api/actions.h" #define TEST_FILE_FOO "foo" #define TEST_FILE_FOO_LINK "foo_link_" #define TEST_DIR_A "test_dir_a" using fs_testing::tests::DataTestResult; using fs_testing::user_tools::api::WriteData; using fs_testing::user_tools::api::WriteDataMmap; using fs_testing::user_tools::api::Checkpoint; using std::string; #define TEST_FILE_PERMS ((mode_t) (S_IRWXU | S_IRWXG | S_IRWXO)) namespace fs_testing { namespace tests { class Generic106: public BaseTestCase { public: virtual int setup() override { init_paths(); // Create test directory A. string dir_path = mnt_dir_ + "/" TEST_DIR_A; int res = mkdir(dir_path.c_str(), 0777); if (res < 0) { return -1; } //Create file foo in TEST_DIR_A int fd_foo = open(foo_path.c_str(), O_RDWR | O_CREAT, TEST_FILE_PERMS); if (fd_foo < 0) { return -1; } close(fd_foo); sync(); return 0; } virtual int run() override { init_paths(); // Create a new hard link if(link(foo_path.c_str(), foo_link_path.c_str()) < 0){ return -2; } sync(); // Unlink foo_link if(unlink(foo_link_path.c_str()) < 0){ return -3; } // drop caches if (system("echo 2 > /proc/sys/vm/drop_caches") < 0) { return -4; } int fd_foo = open(foo_path.c_str(), O_RDWR | O_CREAT, TEST_FILE_PERMS); if (fd_foo < 0) { return -5; } if (fsync(fd_foo) < 0) { return -6; } // Make a user checkpoint here if (Checkpoint() < 0){ return -7; } //Close open files close(fd_foo); return 0; } virtual int check_test(unsigned int last_checkpoint, DataTestResult *test_result) override { init_paths(); string dir = mnt_dir_ + "/" TEST_DIR_A; string rm_cmd = "rm -f " + dir + "/*"; // Remove files within the directory system(rm_cmd.c_str()); // Directory should be removeable if (rmdir(dir.c_str()) < 0 && errno == ENOTEMPTY ) { test_result->SetError(DataTestResult::kFileMetadataCorrupted); test_result->error_description = " : Unable to remove directory after deleting files - Stale link file unremovable"; } return 0; } private: string foo_path; string foo_link_path; void init_paths() { foo_path = mnt_dir_ + "/" TEST_DIR_A "/" TEST_FILE_FOO; foo_link_path = mnt_dir_ + "/" TEST_DIR_A "/" TEST_FILE_FOO_LINK; } }; } // namespace tests } // namespace fs_testing extern "C" fs_testing::tests::BaseTestCase *test_case_get_instance() { return new fs_testing::tests::Generic106; } extern "C" void test_case_delete_instance(fs_testing::tests::BaseTestCase *tc) { delete tc; } <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <string> #include <fstream> #include <iterator> #include <vector> #include <algorithm> #include <limits> #include <arrayfire.h> #include <af/dim4.hpp> #include <af/array.h> typedef unsigned char uchar; typedef unsigned int uint; template<typename inType, typename outType, typename FileElementType> void readTests(const std::string &FileName, std::vector<af::dim4> &inputDims, std::vector<std::vector<inType> > &testInputs, std::vector<std::vector<outType> > &testOutputs) { using std::vector; std::ifstream testFile(FileName.c_str()); if(testFile.good()) { unsigned inputCount; testFile >> inputCount; for(unsigned i=0; i<inputCount; i++) { af::dim4 temp(1); testFile >> temp; inputDims.push_back(temp); } unsigned testCount; testFile >> testCount; testOutputs.resize(testCount); vector<unsigned> testSizes(testCount); for(unsigned i = 0; i < testCount; i++) { testFile >> testSizes[i]; } testInputs.resize(inputCount,vector<inType>(0)); for(unsigned k=0; k<inputCount; k++) { unsigned nElems = inputDims[k].elements(); testInputs[k].resize(nElems); FileElementType tmp; for(unsigned i = 0; i < nElems; i++) { testFile >> tmp; testInputs[k][i] = tmp; } } testOutputs.resize(testCount, vector<outType>(0)); for(unsigned i = 0; i < testCount; i++) { testOutputs[i].resize(testSizes[i]); FileElementType tmp; for(unsigned j = 0; j < testSizes[i]; j++) { testFile >> tmp; testOutputs[i][j] = tmp; } } } else { FAIL() << "TEST FILE NOT FOUND"; } } template<typename inType, typename outType> void readTestsFromFile(const std::string &FileName, std::vector<af::dim4> &inputDims, std::vector<std::vector<inType> > &testInputs, std::vector<std::vector<outType> > &testOutputs) { using std::vector; std::ifstream testFile(FileName.c_str()); if(testFile.good()) { unsigned inputCount; testFile >> inputCount; for(unsigned i=0; i<inputCount; i++) { af::dim4 temp(1); testFile >> temp; inputDims.push_back(temp); } unsigned testCount; testFile >> testCount; testOutputs.resize(testCount); vector<unsigned> testSizes(testCount); for(unsigned i = 0; i < testCount; i++) { testFile >> testSizes[i]; } testInputs.resize(inputCount,vector<inType>(0)); for(unsigned k=0; k<inputCount; k++) { unsigned nElems = inputDims[k].elements(); testInputs[k].resize(nElems); inType tmp; for(unsigned i = 0; i < nElems; i++) { testFile >> tmp; testInputs[k][i] = tmp; } } testOutputs.resize(testCount, vector<outType>(0)); for(unsigned i = 0; i < testCount; i++) { testOutputs[i].resize(testSizes[i]); outType tmp; for(unsigned j = 0; j < testSizes[i]; j++) { testFile >> tmp; testOutputs[i][j] = tmp; } } } else { FAIL() << "TEST FILE NOT FOUND"; } } void readImageTests(const std::string &pFileName, std::vector<af::dim4> &pInputDims, std::vector<std::string> &pTestInputs, std::vector<dim_t> &pTestOutSizes, std::vector<std::string> &pTestOutputs) { using std::vector; std::ifstream testFile(pFileName.c_str()); if(testFile.good()) { unsigned inputCount; testFile >> inputCount; for(unsigned i=0; i<inputCount; i++) { af::dim4 temp(1); testFile >> temp; pInputDims.push_back(temp); } unsigned testCount; testFile >> testCount; pTestOutputs.resize(testCount); pTestOutSizes.resize(testCount); for(unsigned i = 0; i < testCount; i++) { testFile >> pTestOutSizes[i]; } pTestInputs.resize(inputCount, ""); for(unsigned k=0; k<inputCount; k++) { std::string temp = ""; while(std::getline(testFile, temp)) { if (temp!="") break; } if (temp=="") throw std::runtime_error("Test file might not be per format, please check."); pTestInputs[k] = temp; } pTestOutputs.resize(testCount, ""); for(unsigned i = 0; i < testCount; i++) { std::string temp = ""; while(std::getline(testFile, temp)) { if (temp!="") break; } if (temp=="") throw std::runtime_error("Test file might not be per format, please check."); pTestOutputs[i] = temp; } } else { FAIL() << "TEST FILE NOT FOUND"; } } template<typename outType> void readImageTests(const std::string &pFileName, std::vector<af::dim4> &pInputDims, std::vector<std::string> &pTestInputs, std::vector<std::vector<outType> > &pTestOutputs) { using std::vector; std::ifstream testFile(pFileName.c_str()); if(testFile.good()) { unsigned inputCount; testFile >> inputCount; for(unsigned i=0; i<inputCount; i++) { af::dim4 temp(1); testFile >> temp; pInputDims.push_back(temp); } unsigned testCount; testFile >> testCount; pTestOutputs.resize(testCount); vector<unsigned> testSizes(testCount); for(unsigned i = 0; i < testCount; i++) { testFile >> testSizes[i]; } pTestInputs.resize(inputCount, ""); for(unsigned k=0; k<inputCount; k++) { std::string temp = ""; while(std::getline(testFile, temp)) { if (temp!="") break; } if (temp=="") throw std::runtime_error("Test file might not be per format, please check."); pTestInputs[k] = temp; } pTestOutputs.resize(testCount, vector<outType>(0)); for(unsigned i = 0; i < testCount; i++) { pTestOutputs[i].resize(testSizes[i]); outType tmp; for(unsigned j = 0; j < testSizes[i]; j++) { testFile >> tmp; pTestOutputs[i][j] = tmp; } } } else { FAIL() << "TEST FILE NOT FOUND"; } } template<typename descType> void readImageFeaturesDescriptors(const std::string &pFileName, std::vector<af::dim4> &pInputDims, std::vector<std::string> &pTestInputs, std::vector<std::vector<float> > &pTestFeats, std::vector<std::vector<descType> > &pTestDescs) { using std::vector; std::ifstream testFile(pFileName.c_str()); if(testFile.good()) { unsigned inputCount; testFile >> inputCount; for(unsigned i=0; i<inputCount; i++) { af::dim4 temp(1); testFile >> temp; pInputDims.push_back(temp); } unsigned attrCount, featCount, descLen; testFile >> featCount; testFile >> attrCount; testFile >> descLen; pTestFeats.resize(attrCount); pTestInputs.resize(inputCount, ""); for(unsigned k=0; k<inputCount; k++) { std::string temp = ""; while(std::getline(testFile, temp)) { if (temp!="") break; } if (temp=="") throw std::runtime_error("Test file might not be per format, please check."); pTestInputs[k] = temp; } pTestFeats.resize(attrCount, vector<float>(0)); for(unsigned i = 0; i < attrCount; i++) { pTestFeats[i].resize(featCount); float tmp; for(unsigned j = 0; j < featCount; j++) { testFile >> tmp; pTestFeats[i][j] = tmp; } } pTestDescs.resize(featCount, vector<descType>(0)); for(unsigned i = 0; i < featCount; i++) { pTestDescs[i].resize(descLen); descType tmp; for(unsigned j = 0; j < descLen; j++) { testFile >> tmp; pTestDescs[i][j] = tmp; } } } else { FAIL() << "TEST FILE NOT FOUND"; } } /** * Below is not a pair wise comparition method, rather * it computes the accumulated error of the computed * output and gold output. * * The cut off is decided based on root mean square * deviation from cpu result * * For images, the maximum possible error will happen if all * the observed values are zeros and all the predicted values * are 255's. In such case, the value of NRMSD will be 1.0 * Similarly, we can deduce that 0.0 will be the minimum * value of NRMSD. Hence, the range of RMSD is [0,255] for image inputs. */ template<typename T> bool compareArraysRMSD(dim_t data_size, T *gold, T *data, double tolerance) { double accum = 0.0; double maxion = FLT_MAX;//(double)std::numeric_limits<T>::lowest(); double minion = FLT_MAX;//(double)std::numeric_limits<T>::max(); for(dim_t i=0;i<data_size;i++) { double dTemp = (double)data[i]; double gTemp = (double)gold[i]; double diff = gTemp-dTemp; double err = std::abs(diff) > 1.0e-4 ? diff : 0.0f; accum += std::pow(err,2.0); maxion = std::max(maxion, dTemp); minion = std::min(minion, dTemp); } accum /= data_size; double NRMSD = std::sqrt(accum)/(maxion-minion); std::cout<<"NRMSD = "<<NRMSD<<std::endl; if (NRMSD > tolerance) return false; return true; } template<typename T, typename Other> struct is_same_type{ static const bool value = false; }; template<typename T> struct is_same_type<T, T> { static const bool value = true; }; template<bool, typename T, typename O> struct cond_type; template<typename T, typename Other> struct cond_type<true, T, Other> { typedef T type; }; template<typename T, typename Other> struct cond_type<false, T, Other> { typedef Other type; }; template<typename T> double real(T val) { return (double)val; } template<> double real<af::cdouble>(af::cdouble val) { return real(val); } template<> double real<af::cfloat> (af::cfloat val) { return real(val); } template<typename T> double imag(T val) { return (double)val; } template<> double imag<af::cdouble>(af::cdouble val) { return imag(val); } template<> double imag<af::cfloat> (af::cfloat val) { return imag(val); } template<typename T> bool noDoubleTests() { bool isTypeDouble = is_same_type<T, double>::value || is_same_type<T, af::cdouble>::value; int dev = af::getDevice(); bool isDoubleSupported = af::isDoubleAvailable(dev); return ((isTypeDouble && !isDoubleSupported) ? true : false); } // TODO: perform conversion on device for CUDA and OpenCL template<typename T> af_err conv_image(af_array *out, af_array in) { af_array outArray; dim_t d0, d1, d2, d3; af_get_dims(&d0, &d1, &d2, &d3, in); af::dim4 idims(d0, d1, d2, d3); dim_t nElems = 0; af_get_elements(&nElems, in); float *in_data = new float[nElems]; af_get_data_ptr(in_data, in); T *out_data = new T[nElems]; for (int i = 0; i < (int)nElems; i++) out_data[i] = (T)in_data[i]; af_create_array(&outArray, out_data, idims.ndims(), idims.get(), (af_dtype) af::dtype_traits<T>::af_type); std::swap(*out, outArray); delete [] in_data; delete [] out_data; return AF_SUCCESS; } template<typename T> af::array cpu_randu(const af::dim4 dims) { typedef typename af::dtype_traits<T>::base_type BT; bool isTypeCplx = is_same_type<T, af::cfloat>::value || is_same_type<T, af::cdouble>::value; bool isTypeFloat = is_same_type<BT, float>::value || is_same_type<BT, double>::value; dim_t elements = (isTypeCplx ? 2 : 1) * dims.elements(); std::vector<BT> out(elements); for(int i = 0; i < (int)elements; i++) { out[i] = isTypeFloat ? (BT)(rand())/RAND_MAX : rand() % 100; } return af::array(dims, (T *)&out[0]); } <commit_msg>Add typedef for ushort in tests<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <string> #include <fstream> #include <iterator> #include <vector> #include <algorithm> #include <limits> #include <arrayfire.h> #include <af/dim4.hpp> #include <af/array.h> typedef unsigned char uchar; typedef unsigned int uint; typedef unsigned short ushort; template<typename inType, typename outType, typename FileElementType> void readTests(const std::string &FileName, std::vector<af::dim4> &inputDims, std::vector<std::vector<inType> > &testInputs, std::vector<std::vector<outType> > &testOutputs) { using std::vector; std::ifstream testFile(FileName.c_str()); if(testFile.good()) { unsigned inputCount; testFile >> inputCount; for(unsigned i=0; i<inputCount; i++) { af::dim4 temp(1); testFile >> temp; inputDims.push_back(temp); } unsigned testCount; testFile >> testCount; testOutputs.resize(testCount); vector<unsigned> testSizes(testCount); for(unsigned i = 0; i < testCount; i++) { testFile >> testSizes[i]; } testInputs.resize(inputCount,vector<inType>(0)); for(unsigned k=0; k<inputCount; k++) { unsigned nElems = inputDims[k].elements(); testInputs[k].resize(nElems); FileElementType tmp; for(unsigned i = 0; i < nElems; i++) { testFile >> tmp; testInputs[k][i] = tmp; } } testOutputs.resize(testCount, vector<outType>(0)); for(unsigned i = 0; i < testCount; i++) { testOutputs[i].resize(testSizes[i]); FileElementType tmp; for(unsigned j = 0; j < testSizes[i]; j++) { testFile >> tmp; testOutputs[i][j] = tmp; } } } else { FAIL() << "TEST FILE NOT FOUND"; } } template<typename inType, typename outType> void readTestsFromFile(const std::string &FileName, std::vector<af::dim4> &inputDims, std::vector<std::vector<inType> > &testInputs, std::vector<std::vector<outType> > &testOutputs) { using std::vector; std::ifstream testFile(FileName.c_str()); if(testFile.good()) { unsigned inputCount; testFile >> inputCount; for(unsigned i=0; i<inputCount; i++) { af::dim4 temp(1); testFile >> temp; inputDims.push_back(temp); } unsigned testCount; testFile >> testCount; testOutputs.resize(testCount); vector<unsigned> testSizes(testCount); for(unsigned i = 0; i < testCount; i++) { testFile >> testSizes[i]; } testInputs.resize(inputCount,vector<inType>(0)); for(unsigned k=0; k<inputCount; k++) { unsigned nElems = inputDims[k].elements(); testInputs[k].resize(nElems); inType tmp; for(unsigned i = 0; i < nElems; i++) { testFile >> tmp; testInputs[k][i] = tmp; } } testOutputs.resize(testCount, vector<outType>(0)); for(unsigned i = 0; i < testCount; i++) { testOutputs[i].resize(testSizes[i]); outType tmp; for(unsigned j = 0; j < testSizes[i]; j++) { testFile >> tmp; testOutputs[i][j] = tmp; } } } else { FAIL() << "TEST FILE NOT FOUND"; } } void readImageTests(const std::string &pFileName, std::vector<af::dim4> &pInputDims, std::vector<std::string> &pTestInputs, std::vector<dim_t> &pTestOutSizes, std::vector<std::string> &pTestOutputs) { using std::vector; std::ifstream testFile(pFileName.c_str()); if(testFile.good()) { unsigned inputCount; testFile >> inputCount; for(unsigned i=0; i<inputCount; i++) { af::dim4 temp(1); testFile >> temp; pInputDims.push_back(temp); } unsigned testCount; testFile >> testCount; pTestOutputs.resize(testCount); pTestOutSizes.resize(testCount); for(unsigned i = 0; i < testCount; i++) { testFile >> pTestOutSizes[i]; } pTestInputs.resize(inputCount, ""); for(unsigned k=0; k<inputCount; k++) { std::string temp = ""; while(std::getline(testFile, temp)) { if (temp!="") break; } if (temp=="") throw std::runtime_error("Test file might not be per format, please check."); pTestInputs[k] = temp; } pTestOutputs.resize(testCount, ""); for(unsigned i = 0; i < testCount; i++) { std::string temp = ""; while(std::getline(testFile, temp)) { if (temp!="") break; } if (temp=="") throw std::runtime_error("Test file might not be per format, please check."); pTestOutputs[i] = temp; } } else { FAIL() << "TEST FILE NOT FOUND"; } } template<typename outType> void readImageTests(const std::string &pFileName, std::vector<af::dim4> &pInputDims, std::vector<std::string> &pTestInputs, std::vector<std::vector<outType> > &pTestOutputs) { using std::vector; std::ifstream testFile(pFileName.c_str()); if(testFile.good()) { unsigned inputCount; testFile >> inputCount; for(unsigned i=0; i<inputCount; i++) { af::dim4 temp(1); testFile >> temp; pInputDims.push_back(temp); } unsigned testCount; testFile >> testCount; pTestOutputs.resize(testCount); vector<unsigned> testSizes(testCount); for(unsigned i = 0; i < testCount; i++) { testFile >> testSizes[i]; } pTestInputs.resize(inputCount, ""); for(unsigned k=0; k<inputCount; k++) { std::string temp = ""; while(std::getline(testFile, temp)) { if (temp!="") break; } if (temp=="") throw std::runtime_error("Test file might not be per format, please check."); pTestInputs[k] = temp; } pTestOutputs.resize(testCount, vector<outType>(0)); for(unsigned i = 0; i < testCount; i++) { pTestOutputs[i].resize(testSizes[i]); outType tmp; for(unsigned j = 0; j < testSizes[i]; j++) { testFile >> tmp; pTestOutputs[i][j] = tmp; } } } else { FAIL() << "TEST FILE NOT FOUND"; } } template<typename descType> void readImageFeaturesDescriptors(const std::string &pFileName, std::vector<af::dim4> &pInputDims, std::vector<std::string> &pTestInputs, std::vector<std::vector<float> > &pTestFeats, std::vector<std::vector<descType> > &pTestDescs) { using std::vector; std::ifstream testFile(pFileName.c_str()); if(testFile.good()) { unsigned inputCount; testFile >> inputCount; for(unsigned i=0; i<inputCount; i++) { af::dim4 temp(1); testFile >> temp; pInputDims.push_back(temp); } unsigned attrCount, featCount, descLen; testFile >> featCount; testFile >> attrCount; testFile >> descLen; pTestFeats.resize(attrCount); pTestInputs.resize(inputCount, ""); for(unsigned k=0; k<inputCount; k++) { std::string temp = ""; while(std::getline(testFile, temp)) { if (temp!="") break; } if (temp=="") throw std::runtime_error("Test file might not be per format, please check."); pTestInputs[k] = temp; } pTestFeats.resize(attrCount, vector<float>(0)); for(unsigned i = 0; i < attrCount; i++) { pTestFeats[i].resize(featCount); float tmp; for(unsigned j = 0; j < featCount; j++) { testFile >> tmp; pTestFeats[i][j] = tmp; } } pTestDescs.resize(featCount, vector<descType>(0)); for(unsigned i = 0; i < featCount; i++) { pTestDescs[i].resize(descLen); descType tmp; for(unsigned j = 0; j < descLen; j++) { testFile >> tmp; pTestDescs[i][j] = tmp; } } } else { FAIL() << "TEST FILE NOT FOUND"; } } /** * Below is not a pair wise comparition method, rather * it computes the accumulated error of the computed * output and gold output. * * The cut off is decided based on root mean square * deviation from cpu result * * For images, the maximum possible error will happen if all * the observed values are zeros and all the predicted values * are 255's. In such case, the value of NRMSD will be 1.0 * Similarly, we can deduce that 0.0 will be the minimum * value of NRMSD. Hence, the range of RMSD is [0,255] for image inputs. */ template<typename T> bool compareArraysRMSD(dim_t data_size, T *gold, T *data, double tolerance) { double accum = 0.0; double maxion = FLT_MAX;//(double)std::numeric_limits<T>::lowest(); double minion = FLT_MAX;//(double)std::numeric_limits<T>::max(); for(dim_t i=0;i<data_size;i++) { double dTemp = (double)data[i]; double gTemp = (double)gold[i]; double diff = gTemp-dTemp; double err = std::abs(diff) > 1.0e-4 ? diff : 0.0f; accum += std::pow(err,2.0); maxion = std::max(maxion, dTemp); minion = std::min(minion, dTemp); } accum /= data_size; double NRMSD = std::sqrt(accum)/(maxion-minion); std::cout<<"NRMSD = "<<NRMSD<<std::endl; if (NRMSD > tolerance) return false; return true; } template<typename T, typename Other> struct is_same_type{ static const bool value = false; }; template<typename T> struct is_same_type<T, T> { static const bool value = true; }; template<bool, typename T, typename O> struct cond_type; template<typename T, typename Other> struct cond_type<true, T, Other> { typedef T type; }; template<typename T, typename Other> struct cond_type<false, T, Other> { typedef Other type; }; template<typename T> double real(T val) { return (double)val; } template<> double real<af::cdouble>(af::cdouble val) { return real(val); } template<> double real<af::cfloat> (af::cfloat val) { return real(val); } template<typename T> double imag(T val) { return (double)val; } template<> double imag<af::cdouble>(af::cdouble val) { return imag(val); } template<> double imag<af::cfloat> (af::cfloat val) { return imag(val); } template<typename T> bool noDoubleTests() { bool isTypeDouble = is_same_type<T, double>::value || is_same_type<T, af::cdouble>::value; int dev = af::getDevice(); bool isDoubleSupported = af::isDoubleAvailable(dev); return ((isTypeDouble && !isDoubleSupported) ? true : false); } // TODO: perform conversion on device for CUDA and OpenCL template<typename T> af_err conv_image(af_array *out, af_array in) { af_array outArray; dim_t d0, d1, d2, d3; af_get_dims(&d0, &d1, &d2, &d3, in); af::dim4 idims(d0, d1, d2, d3); dim_t nElems = 0; af_get_elements(&nElems, in); float *in_data = new float[nElems]; af_get_data_ptr(in_data, in); T *out_data = new T[nElems]; for (int i = 0; i < (int)nElems; i++) out_data[i] = (T)in_data[i]; af_create_array(&outArray, out_data, idims.ndims(), idims.get(), (af_dtype) af::dtype_traits<T>::af_type); std::swap(*out, outArray); delete [] in_data; delete [] out_data; return AF_SUCCESS; } template<typename T> af::array cpu_randu(const af::dim4 dims) { typedef typename af::dtype_traits<T>::base_type BT; bool isTypeCplx = is_same_type<T, af::cfloat>::value || is_same_type<T, af::cdouble>::value; bool isTypeFloat = is_same_type<BT, float>::value || is_same_type<BT, double>::value; dim_t elements = (isTypeCplx ? 2 : 1) * dims.elements(); std::vector<BT> out(elements); for(int i = 0; i < (int)elements; i++) { out[i] = isTypeFloat ? (BT)(rand())/RAND_MAX : rand() % 100; } return af::array(dims, (T *)&out[0]); } <|endoftext|>
<commit_before>/* Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin 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 Rasterbar Software 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. */ #include <cassert> #include <boost/timer.hpp> #include <iostream> #include <vector> #include <utility> #include <set> #include "libtorrent/buffer.hpp" #include "libtorrent/chained_buffer.hpp" #include "libtorrent/socket.hpp" #include "test.hpp" using libtorrent::buffer; using libtorrent::chained_buffer; /* template<class T> T const& min_(T const& x, T const& y) { return x < y ? x : y; } void test_speed() { buffer b; char data[32]; srand(0); boost::timer t; int const iterations = 5000000; int const step = iterations / 20; for (int i = 0; i < iterations; ++i) { int x = rand(); if (i % step == 0) std::cerr << "."; std::size_t n = rand() % 32; n = 32; if (x % 2) { b.insert(data, data + n); } else { b.erase(min_(b.size(), n)); } } float t1 = t.elapsed(); std::cerr << "buffer elapsed: " << t.elapsed() << "\n"; std::vector<char> v; srand(0); t.restart(); for (int i = 0; i < iterations; ++i) { int x = rand(); if (i % step == 0) std::cerr << "."; std::size_t n = rand() % 32; n = 32; if (x % 2) { v.insert(v.end(), data, data + n); } else { v.erase(v.begin(), v.begin() + min_(v.size(), n)); } } float t2 = t.elapsed(); std::cerr << "std::vector elapsed: " << t.elapsed() << "\n"; assert(t1 < t2); } */ // -- test buffer -- void test_buffer() { char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; buffer b; TEST_CHECK(b.size() == 0); TEST_CHECK(b.capacity() == 0); TEST_CHECK(b.empty()); b.resize(10); TEST_CHECK(b.size() == 10); TEST_CHECK(b.capacity() == 10); std::memcpy(b.begin(), data, 10); b.reserve(50); TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0); TEST_CHECK(b.capacity() == 50); b.erase(b.begin() + 6, b.end()); TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0); TEST_CHECK(b.capacity() == 50); TEST_CHECK(b.size() == 6); b.insert(b.begin(), data + 5, data + 10); TEST_CHECK(b.capacity() == 50); TEST_CHECK(b.size() == 11); TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0); b.clear(); TEST_CHECK(b.size() == 0); TEST_CHECK(b.capacity() == 50); b.insert(b.end(), data, data + 10); TEST_CHECK(b.size() == 10); TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0); b.erase(b.begin(), b.end()); TEST_CHECK(b.capacity() == 50); TEST_CHECK(b.size() == 0); buffer().swap(b); TEST_CHECK(b.capacity() == 0); } // -- test chained buffer -- std::set<char*> buffer_list; void free_buffer(char* m) { std::set<char*>::iterator i = buffer_list.find(m); TEST_CHECK(i != buffer_list.end()); buffer_list.erase(i); std::free(m); } char* allocate_buffer(int size) { char* mem = (char*)std::malloc(size); buffer_list.insert(mem); return mem; } template <class T> int copy_buffers(T const& b, char* target) { int copied = 0; for (typename T::const_iterator i = b.begin() , end(b.end()); i != end; ++i) { memcpy(target, asio::buffer_cast<char const*>(*i), asio::buffer_size(*i)); target += asio::buffer_size(*i); copied += asio::buffer_size(*i); } return copied; } bool compare_chained_buffer(chained_buffer& b, char const* mem, int size) { if (size == 0) return true; std::vector<char> flat(size); std::list<asio::const_buffer> const& iovec2 = b.build_iovec(size); int copied = copy_buffers(iovec2, &flat[0]); TEST_CHECK(copied == size); return std::memcmp(&flat[0], mem, size) == 0; } void test_chained_buffer() { char data[] = "foobar"; { chained_buffer b; TEST_CHECK(b.empty()); TEST_CHECK(b.capacity() == 0); TEST_CHECK(b.size() == 0); TEST_CHECK(b.space_in_last_buffer() == 0); TEST_CHECK(buffer_list.empty()); char* b1 = allocate_buffer(512); std::memcpy(b1, data, 6); b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer); TEST_CHECK(buffer_list.size() == 1); TEST_CHECK(b.capacity() == 512); TEST_CHECK(b.size() == 6); TEST_CHECK(!b.empty()); TEST_CHECK(b.space_in_last_buffer() == 512 - 6); b.pop_front(3); TEST_CHECK(b.capacity() == 512); TEST_CHECK(b.size() == 3); TEST_CHECK(!b.empty()); TEST_CHECK(b.space_in_last_buffer() == 512 - 6); bool ret = b.append(data, 6); TEST_CHECK(ret == true); TEST_CHECK(b.capacity() == 512); TEST_CHECK(b.size() == 9); TEST_CHECK(!b.empty()); TEST_CHECK(b.space_in_last_buffer() == 512 - 12); ret = b.append(data, 1024); TEST_CHECK(ret == false); char* b2 = allocate_buffer(512); std::memcpy(b2, data, 6); b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer); TEST_CHECK(buffer_list.size() == 2); char* b3 = allocate_buffer(512); std::memcpy(b3, data, 6); b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer); TEST_CHECK(buffer_list.size() == 3); TEST_CHECK(b.capacity() == 512 * 3); TEST_CHECK(b.size() == 21); TEST_CHECK(!b.empty()); TEST_CHECK(b.space_in_last_buffer() == 512 - 6); TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9)); for (int i = 1; i < 21; ++i) TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i)); b.pop_front(5 + 6); TEST_CHECK(buffer_list.size() == 2); TEST_CHECK(b.capacity() == 512 * 2); TEST_CHECK(b.size() == 10); TEST_CHECK(!b.empty()); TEST_CHECK(b.space_in_last_buffer() == 512 - 6); char const* str = "obarfooba"; TEST_CHECK(compare_chained_buffer(b, str, 9)); for (int i = 0; i < 9; ++i) { b.pop_front(1); ++str; TEST_CHECK(compare_chained_buffer(b, str, 8 - i)); TEST_CHECK(b.size() == 9 - i); } char* b4 = allocate_buffer(20); std::memcpy(b4, data, 6); std::memcpy(b4 + 6, data, 6); b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer); TEST_CHECK(b.space_in_last_buffer() == 8); ret = b.append(data, 6); TEST_CHECK(ret == true); TEST_CHECK(b.space_in_last_buffer() == 2); std::cout << b.space_in_last_buffer() << std::endl; ret = b.append(data, 2); TEST_CHECK(ret == true); TEST_CHECK(b.space_in_last_buffer() == 0); std::cout << b.space_in_last_buffer() << std::endl; char* b5 = allocate_buffer(20); std::memcpy(b4, data, 6); b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer); b.pop_front(22); TEST_CHECK(b.size() == 5); } TEST_CHECK(buffer_list.empty()); } int test_main() { test_buffer(); test_chained_buffer(); return 0; } <commit_msg>boost 1.35 fix in test_buffer<commit_after>/* Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin 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 Rasterbar Software 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. */ #include <cassert> #include <boost/timer.hpp> #include <iostream> #include <vector> #include <utility> #include <set> #include "libtorrent/buffer.hpp" #include "libtorrent/chained_buffer.hpp" #include "libtorrent/socket.hpp" #include "test.hpp" using namespace libtorrent; /* template<class T> T const& min_(T const& x, T const& y) { return x < y ? x : y; } void test_speed() { buffer b; char data[32]; srand(0); boost::timer t; int const iterations = 5000000; int const step = iterations / 20; for (int i = 0; i < iterations; ++i) { int x = rand(); if (i % step == 0) std::cerr << "."; std::size_t n = rand() % 32; n = 32; if (x % 2) { b.insert(data, data + n); } else { b.erase(min_(b.size(), n)); } } float t1 = t.elapsed(); std::cerr << "buffer elapsed: " << t.elapsed() << "\n"; std::vector<char> v; srand(0); t.restart(); for (int i = 0; i < iterations; ++i) { int x = rand(); if (i % step == 0) std::cerr << "."; std::size_t n = rand() % 32; n = 32; if (x % 2) { v.insert(v.end(), data, data + n); } else { v.erase(v.begin(), v.begin() + min_(v.size(), n)); } } float t2 = t.elapsed(); std::cerr << "std::vector elapsed: " << t.elapsed() << "\n"; assert(t1 < t2); } */ // -- test buffer -- void test_buffer() { char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; buffer b; TEST_CHECK(b.size() == 0); TEST_CHECK(b.capacity() == 0); TEST_CHECK(b.empty()); b.resize(10); TEST_CHECK(b.size() == 10); TEST_CHECK(b.capacity() == 10); std::memcpy(b.begin(), data, 10); b.reserve(50); TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0); TEST_CHECK(b.capacity() == 50); b.erase(b.begin() + 6, b.end()); TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0); TEST_CHECK(b.capacity() == 50); TEST_CHECK(b.size() == 6); b.insert(b.begin(), data + 5, data + 10); TEST_CHECK(b.capacity() == 50); TEST_CHECK(b.size() == 11); TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0); b.clear(); TEST_CHECK(b.size() == 0); TEST_CHECK(b.capacity() == 50); b.insert(b.end(), data, data + 10); TEST_CHECK(b.size() == 10); TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0); b.erase(b.begin(), b.end()); TEST_CHECK(b.capacity() == 50); TEST_CHECK(b.size() == 0); buffer().swap(b); TEST_CHECK(b.capacity() == 0); } // -- test chained buffer -- std::set<char*> buffer_list; void free_buffer(char* m) { std::set<char*>::iterator i = buffer_list.find(m); TEST_CHECK(i != buffer_list.end()); buffer_list.erase(i); std::free(m); } char* allocate_buffer(int size) { char* mem = (char*)std::malloc(size); buffer_list.insert(mem); return mem; } template <class T> int copy_buffers(T const& b, char* target) { int copied = 0; for (typename T::const_iterator i = b.begin() , end(b.end()); i != end; ++i) { memcpy(target, asio::buffer_cast<char const*>(*i), asio::buffer_size(*i)); target += asio::buffer_size(*i); copied += asio::buffer_size(*i); } return copied; } bool compare_chained_buffer(chained_buffer& b, char const* mem, int size) { if (size == 0) return true; std::vector<char> flat(size); std::list<asio::const_buffer> const& iovec2 = b.build_iovec(size); int copied = copy_buffers(iovec2, &flat[0]); TEST_CHECK(copied == size); return std::memcmp(&flat[0], mem, size) == 0; } void test_chained_buffer() { char data[] = "foobar"; { chained_buffer b; TEST_CHECK(b.empty()); TEST_CHECK(b.capacity() == 0); TEST_CHECK(b.size() == 0); TEST_CHECK(b.space_in_last_buffer() == 0); TEST_CHECK(buffer_list.empty()); char* b1 = allocate_buffer(512); std::memcpy(b1, data, 6); b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer); TEST_CHECK(buffer_list.size() == 1); TEST_CHECK(b.capacity() == 512); TEST_CHECK(b.size() == 6); TEST_CHECK(!b.empty()); TEST_CHECK(b.space_in_last_buffer() == 512 - 6); b.pop_front(3); TEST_CHECK(b.capacity() == 512); TEST_CHECK(b.size() == 3); TEST_CHECK(!b.empty()); TEST_CHECK(b.space_in_last_buffer() == 512 - 6); bool ret = b.append(data, 6); TEST_CHECK(ret == true); TEST_CHECK(b.capacity() == 512); TEST_CHECK(b.size() == 9); TEST_CHECK(!b.empty()); TEST_CHECK(b.space_in_last_buffer() == 512 - 12); ret = b.append(data, 1024); TEST_CHECK(ret == false); char* b2 = allocate_buffer(512); std::memcpy(b2, data, 6); b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer); TEST_CHECK(buffer_list.size() == 2); char* b3 = allocate_buffer(512); std::memcpy(b3, data, 6); b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer); TEST_CHECK(buffer_list.size() == 3); TEST_CHECK(b.capacity() == 512 * 3); TEST_CHECK(b.size() == 21); TEST_CHECK(!b.empty()); TEST_CHECK(b.space_in_last_buffer() == 512 - 6); TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9)); for (int i = 1; i < 21; ++i) TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i)); b.pop_front(5 + 6); TEST_CHECK(buffer_list.size() == 2); TEST_CHECK(b.capacity() == 512 * 2); TEST_CHECK(b.size() == 10); TEST_CHECK(!b.empty()); TEST_CHECK(b.space_in_last_buffer() == 512 - 6); char const* str = "obarfooba"; TEST_CHECK(compare_chained_buffer(b, str, 9)); for (int i = 0; i < 9; ++i) { b.pop_front(1); ++str; TEST_CHECK(compare_chained_buffer(b, str, 8 - i)); TEST_CHECK(b.size() == 9 - i); } char* b4 = allocate_buffer(20); std::memcpy(b4, data, 6); std::memcpy(b4 + 6, data, 6); b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer); TEST_CHECK(b.space_in_last_buffer() == 8); ret = b.append(data, 6); TEST_CHECK(ret == true); TEST_CHECK(b.space_in_last_buffer() == 2); std::cout << b.space_in_last_buffer() << std::endl; ret = b.append(data, 2); TEST_CHECK(ret == true); TEST_CHECK(b.space_in_last_buffer() == 0); std::cout << b.space_in_last_buffer() << std::endl; char* b5 = allocate_buffer(20); std::memcpy(b4, data, 6); b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer); b.pop_front(22); TEST_CHECK(b.size() == 5); } TEST_CHECK(buffer_list.empty()); } int test_main() { test_buffer(); test_chained_buffer(); return 0; } <|endoftext|>
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8: /* The MIT License Copyright (c) 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) 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 "flusspferd/create.hpp" #include "flusspferd/create/object.hpp" #include "flusspferd/create/array.hpp" #include "flusspferd/create/function.hpp" #include "flusspferd/create/native_object.hpp" #include "flusspferd/create/native_function.hpp" #include "flusspferd/value_io.hpp" #include "flusspferd/init.hpp" #include "flusspferd/native_function_base.hpp" #include "test_environment.hpp" #include <boost/assign/list_of.hpp> #include <boost/fusion/container/generation/make_vector.hpp> using namespace flusspferd::param; using namespace boost::assign; FLUSSPFERD_CLASS_DESCRIPTION( my_class, (constructor_name, "MyClass") (full_name, "test_create.MyClass") ) { public: enum constructor_choice_t { obj_only, ab }; constructor_choice_t constructor_choice; int a; std::string b; my_class(object const &obj) : base_type(obj), constructor_choice(obj_only) {} my_class(object const &obj, int a, std::string const &b) : base_type(obj), constructor_choice(ab), a(a), b(b) {} }; struct my_functor : flusspferd::native_function_base { bool x; my_functor() : x(true) {} my_functor(int) : x(false) {} void call(flusspferd::call_context &) { set_property("called", x); } }; BOOST_FIXTURE_TEST_SUITE( with_context, context_fixture ) BOOST_AUTO_TEST_CASE( object ) { flusspferd::local_root_scope scope; flusspferd::object o1(flusspferd::create<flusspferd::object>()); BOOST_CHECK(!o1.is_null()); BOOST_CHECK_EQUAL( o1.prototype(), flusspferd::current_context().prototype("")); flusspferd::object o2( flusspferd::create<flusspferd::object>(_prototype = o1)); BOOST_CHECK(!o2.is_null()); BOOST_CHECK_EQUAL(o2.prototype(), o1); o2 = flusspferd::create<flusspferd::object>(o1); BOOST_CHECK(!o2.is_null()); BOOST_CHECK_EQUAL(o2.prototype(), o1); flusspferd::object o3( flusspferd::create<flusspferd::object>(_parent = o2)); BOOST_CHECK(!o3.is_null()); BOOST_CHECK_EQUAL(o3.parent(), o2); flusspferd::object o4( flusspferd::create<flusspferd::object>(o1, o2)); BOOST_CHECK(!o4.is_null()); BOOST_CHECK_EQUAL(o4.prototype(), o1); BOOST_CHECK_EQUAL(o4.parent(), o2); o4 = flusspferd::create<flusspferd::object>(_parent = o2, _prototype = o1); BOOST_CHECK(!o4.is_null()); BOOST_CHECK_EQUAL(o4.prototype(), o1); BOOST_CHECK_EQUAL(o4.parent(), o2); } BOOST_AUTO_TEST_CASE( array ) { flusspferd::local_root_scope scope; flusspferd::array a(flusspferd::create<flusspferd::array>()); BOOST_CHECK_EQUAL(a.length(), 0); a = flusspferd::create<flusspferd::array>(_length = 5); BOOST_CHECK_EQUAL(a.length(), 5); a = flusspferd::create<flusspferd::array>(3); BOOST_CHECK_EQUAL(a.length(), 3); a = flusspferd::create<flusspferd::array>(_contents = list_of(1)(2)); BOOST_CHECK_EQUAL(a.length(), 2); BOOST_CHECK_EQUAL(a.get_element(0), flusspferd::value(1)); BOOST_CHECK_EQUAL(a.get_element(1), flusspferd::value(2)); a = flusspferd::create<flusspferd::array>(list_of(9)); BOOST_CHECK_EQUAL(a.length(), 1); BOOST_CHECK_EQUAL(a.get_element(0), flusspferd::value(9)); } BOOST_AUTO_TEST_CASE( function ) { flusspferd::local_root_scope scope; flusspferd::function f = flusspferd::create<flusspferd::function>(); flusspferd::value v; BOOST_CHECK_NO_THROW(v = f.call(flusspferd::global())); BOOST_CHECK_EQUAL(v, flusspferd::value()); f = flusspferd::create<flusspferd::function>( _argument_names = list_of("a"), _source = "return a * 2"); BOOST_CHECK_NO_THROW(v = f.call(flusspferd::global(), 4)); BOOST_CHECK_EQUAL(v, flusspferd::value(8)); f = flusspferd::create<flusspferd::function>( "name", "return x + y", list_of("x")("y"), "file", 666); BOOST_CHECK_EQUAL(f.name(), "name"); BOOST_CHECK_EQUAL(f.arity(), 2); BOOST_CHECK_NO_THROW(v = f.call(flusspferd::global(), 1, 2)); BOOST_CHECK_EQUAL(v, flusspferd::value(3)); } BOOST_AUTO_TEST_CASE( MyClass ) { flusspferd::local_root_scope scope; my_class &obj = flusspferd::create<my_class>(); BOOST_CHECK(!obj.is_null()); BOOST_CHECK_EQUAL( &obj, &flusspferd::get_native<my_class>(flusspferd::object(obj))); BOOST_CHECK_EQUAL(obj.constructor_choice, my_class::obj_only); my_class &obj2 = flusspferd::create<my_class>( boost::fusion::make_vector(5, "hey")); BOOST_CHECK(!obj2.is_null()); BOOST_CHECK_EQUAL(obj2.constructor_choice, my_class::ab); BOOST_CHECK_EQUAL(obj2.a, 5); BOOST_CHECK_EQUAL(obj2.b, "hey"); } BOOST_AUTO_TEST_CASE( MyFunctor ) { flusspferd::local_root_scope scope; flusspferd::object f; BOOST_CHECK_NO_THROW(f = flusspferd::create<my_functor>()); BOOST_CHECK(!f.is_null()); BOOST_CHECK_EQUAL(f.get_property("called"), flusspferd::value()); BOOST_CHECK_NO_THROW(f.call(flusspferd::global())); BOOST_CHECK_EQUAL(f.get_property("called"), flusspferd::value(true)); BOOST_CHECK_NO_THROW( f = flusspferd::create<my_functor>(boost::fusion::make_vector(0))); BOOST_CHECK(!f.is_null()); BOOST_CHECK_EQUAL(f.get_property("called"), flusspferd::value()); BOOST_CHECK_NO_THROW(f.call(flusspferd::global())); BOOST_CHECK_EQUAL(f.get_property("called"), flusspferd::value(false)); } BOOST_AUTO_TEST_CASE( container ) { flusspferd::local_root_scope scope; flusspferd::property_attributes attr; flusspferd::object cont = flusspferd::create<flusspferd::object>(); BOOST_CHECK(!cont.is_null()); flusspferd::object o = flusspferd::create<flusspferd::object>( _container = cont, _name = "o" ); BOOST_CHECK(!o.is_null()); BOOST_CHECK_EQUAL(cont.get_property_object("o"), o); BOOST_CHECK(cont.get_property_attributes("o", attr)); BOOST_CHECK_EQUAL(attr.flags, flusspferd::dont_enumerate); flusspferd::array a = flusspferd::create<flusspferd::array>( _name = "a", 5, _container = cont, _attributes = flusspferd::no_property_flag); BOOST_CHECK_EQUAL(a.length(), 5); BOOST_CHECK_EQUAL(cont.get_property_object("a"), a); BOOST_CHECK(cont.get_property_attributes("a", attr)); BOOST_CHECK_EQUAL(attr.flags, flusspferd::no_property_flag); flusspferd::function f = flusspferd::create<flusspferd::function>( "f", _container = cont, _source = "return x+1", _argument_names = list_of("x")); BOOST_CHECK_EQUAL(f.call(flusspferd::global(), 1), flusspferd::value(2)); BOOST_CHECK_EQUAL(cont.get_property("f"), f); BOOST_CHECK_EQUAL(cont.call("f", 2), flusspferd::value(3)); BOOST_CHECK(cont.get_property_attributes("f", attr)); BOOST_CHECK_EQUAL(attr.flags, flusspferd::dont_enumerate); my_class &m = flusspferd::create<my_class>(_name = "m", _container = cont); BOOST_CHECK(!m.is_null()); BOOST_CHECK_EQUAL(cont.get_property("m"), m); BOOST_CHECK(cont.get_property_attributes("m", attr)); BOOST_CHECK_EQUAL(attr.flags, flusspferd::dont_enumerate); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>new_create: adapt tests to ruediger-API<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8: /* The MIT License Copyright (c) 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) 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 "flusspferd/create.hpp" #include "flusspferd/create/object.hpp" #include "flusspferd/create/array.hpp" #include "flusspferd/create/function.hpp" #include "flusspferd/create/native_object.hpp" #include "flusspferd/create/native_function.hpp" #include "flusspferd/value_io.hpp" #include "flusspferd/init.hpp" #include "flusspferd/native_function_base.hpp" #include "test_environment.hpp" #include <boost/assign/list_of.hpp> #include <boost/fusion/container/generation/make_vector.hpp> using namespace flusspferd::param; using namespace boost::assign; FLUSSPFERD_CLASS_DESCRIPTION( my_class, (constructor_name, "MyClass") (full_name, "test_create.MyClass") ) { public: enum constructor_choice_t { obj_only, ab }; constructor_choice_t constructor_choice; int a; std::string b; my_class(object const &obj) : base_type(obj), constructor_choice(obj_only) {} my_class(object const &obj, int a, std::string const &b) : base_type(obj), constructor_choice(ab), a(a), b(b) {} }; struct my_functor : flusspferd::native_function_base { bool x; my_functor() : x(true) {} my_functor(int) : x(false) {} void call(flusspferd::call_context &) { set_property("called", x); } }; BOOST_FIXTURE_TEST_SUITE( with_context, context_fixture ) BOOST_AUTO_TEST_CASE( object ) { flusspferd::local_root_scope scope; flusspferd::object o1(flusspferd::create<flusspferd::object>()); BOOST_CHECK(!o1.is_null()); BOOST_CHECK_EQUAL( o1.prototype(), flusspferd::current_context().prototype("")); flusspferd::object o2( flusspferd::create<flusspferd::object>(_prototype = o1)); BOOST_CHECK(!o2.is_null()); BOOST_CHECK_EQUAL(o2.prototype(), o1); o2 = flusspferd::create<flusspferd::object>(o1); BOOST_CHECK(!o2.is_null()); BOOST_CHECK_EQUAL(o2.prototype(), o1); flusspferd::object o3( flusspferd::create<flusspferd::object>(_parent = o2)); BOOST_CHECK(!o3.is_null()); BOOST_CHECK_EQUAL(o3.parent(), o2); flusspferd::object o4( flusspferd::create<flusspferd::object>(o1, o2)); BOOST_CHECK(!o4.is_null()); BOOST_CHECK_EQUAL(o4.prototype(), o1); BOOST_CHECK_EQUAL(o4.parent(), o2); o4 = flusspferd::create<flusspferd::object>(_parent = o2, _prototype = o1); BOOST_CHECK(!o4.is_null()); BOOST_CHECK_EQUAL(o4.prototype(), o1); BOOST_CHECK_EQUAL(o4.parent(), o2); } BOOST_AUTO_TEST_CASE( array ) { flusspferd::local_root_scope scope; flusspferd::array a(flusspferd::create<flusspferd::array>()); BOOST_CHECK_EQUAL(a.length(), 0); a = flusspferd::create<flusspferd::array>(_length = 5); BOOST_CHECK_EQUAL(a.length(), 5); a = flusspferd::create<flusspferd::array>(3); BOOST_CHECK_EQUAL(a.length(), 3); a = flusspferd::create<flusspferd::array>(_contents = list_of(1)(2)); BOOST_CHECK_EQUAL(a.length(), 2); BOOST_CHECK_EQUAL(a.get_element(0), flusspferd::value(1)); BOOST_CHECK_EQUAL(a.get_element(1), flusspferd::value(2)); a = flusspferd::create<flusspferd::array>(list_of(9)); BOOST_CHECK_EQUAL(a.length(), 1); BOOST_CHECK_EQUAL(a.get_element(0), flusspferd::value(9)); } BOOST_AUTO_TEST_CASE( function ) { flusspferd::local_root_scope scope; flusspferd::function f = flusspferd::create<flusspferd::function>(); flusspferd::value v; BOOST_CHECK_NO_THROW(v = f.call(flusspferd::global())); BOOST_CHECK_EQUAL(v, flusspferd::value()); f = flusspferd::create<flusspferd::function>( _argument_names = list_of("a"), _source = "return a * 2"); BOOST_CHECK_NO_THROW(v = f.call(flusspferd::global(), 4)); BOOST_CHECK_EQUAL(v, flusspferd::value(8)); f = flusspferd::create<flusspferd::function>( "name", "return x + y", list_of("x")("y"), "file", 666); BOOST_CHECK_EQUAL(f.name(), "name"); BOOST_CHECK_EQUAL(f.arity(), 2); BOOST_CHECK_NO_THROW(v = f.call(flusspferd::global(), 1, 2)); BOOST_CHECK_EQUAL(v, flusspferd::value(3)); } BOOST_AUTO_TEST_CASE( MyClass ) { flusspferd::local_root_scope scope; my_class &obj = flusspferd::create<my_class>(); BOOST_CHECK(!obj.is_null()); BOOST_CHECK_EQUAL( &obj, &flusspferd::get_native<my_class>(flusspferd::object(obj))); BOOST_CHECK_EQUAL(obj.constructor_choice, my_class::obj_only); my_class &obj2 = flusspferd::create<my_class>( boost::fusion::make_vector(5, "hey")); BOOST_CHECK(!obj2.is_null()); BOOST_CHECK_EQUAL(obj2.constructor_choice, my_class::ab); BOOST_CHECK_EQUAL(obj2.a, 5); BOOST_CHECK_EQUAL(obj2.b, "hey"); } BOOST_AUTO_TEST_CASE( MyFunctor ) { flusspferd::local_root_scope scope; flusspferd::object f; BOOST_CHECK_NO_THROW(f = flusspferd::create<my_functor>()); BOOST_CHECK(!f.is_null()); BOOST_CHECK_EQUAL(f.get_property("called"), flusspferd::value()); BOOST_CHECK_NO_THROW(f.call(flusspferd::global())); BOOST_CHECK_EQUAL(f.get_property("called"), flusspferd::value(true)); BOOST_CHECK_NO_THROW( f = flusspferd::create<my_functor>(boost::fusion::make_vector(0))); BOOST_CHECK(!f.is_null()); BOOST_CHECK_EQUAL(f.get_property("called"), flusspferd::value()); BOOST_CHECK_NO_THROW(f.call(flusspferd::global())); BOOST_CHECK_EQUAL(f.get_property("called"), flusspferd::value(false)); } BOOST_AUTO_TEST_CASE( container ) { flusspferd::local_root_scope scope; boost::optional<flusspferd::property_attributes> attr; flusspferd::object cont = flusspferd::create<flusspferd::object>(); BOOST_CHECK(!cont.is_null()); flusspferd::object o = flusspferd::create<flusspferd::object>( _container = cont, _name = "o" ); BOOST_CHECK(!o.is_null()); BOOST_CHECK_EQUAL(cont.get_property_object("o"), o); BOOST_CHECK(attr = cont.get_property_attributes("o")); BOOST_CHECK_EQUAL(attr->flags, flusspferd::dont_enumerate); flusspferd::array a = flusspferd::create<flusspferd::array>( _name = "a", 5, _container = cont, _attributes = flusspferd::no_property_flag); BOOST_CHECK_EQUAL(a.length(), 5); BOOST_CHECK_EQUAL(cont.get_property_object("a"), a); BOOST_CHECK(attr = cont.get_property_attributes("a")); BOOST_CHECK_EQUAL(attr->flags, flusspferd::no_property_flag); flusspferd::function f = flusspferd::create<flusspferd::function>( "f", _container = cont, _source = "return x+1", _argument_names = list_of("x")); BOOST_CHECK_EQUAL(f.call(flusspferd::global(), 1), flusspferd::value(2)); BOOST_CHECK_EQUAL(cont.get_property("f"), f); BOOST_CHECK_EQUAL(cont.call("f", 2), flusspferd::value(3)); BOOST_CHECK(attr = cont.get_property_attributes("f")); BOOST_CHECK_EQUAL(attr->flags, flusspferd::dont_enumerate); my_class &m = flusspferd::create<my_class>(_name = "m", _container = cont); BOOST_CHECK(!m.is_null()); BOOST_CHECK_EQUAL(cont.get_property("m"), m); BOOST_CHECK(attr = cont.get_property_attributes("m")); BOOST_CHECK_EQUAL(attr->flags, flusspferd::dont_enumerate); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include <Engine/Scrollable.hpp> #include <Engine/Factory.hpp> #include <Engine/ParticleSystem.hpp> #include <Engine/Text.hpp> #include <Engine/Button.hpp> #include <Engine/ObjectPlacer.hpp> #include <Engine/ParallaxBackground.hpp> namespace engine { std::map<std::string, std::function<Node*(Json::Value& root, Node* parent) >> Factory::m_types = { std::make_pair(std::string("node"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<Node>)), std::make_pair(std::string("sprite"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<SpriteNode>)), std::make_pair(std::string("light"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<Light>)), std::make_pair(std::string("text"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<Text>)), std::make_pair(std::string("button"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<Button>)), std::make_pair(std::string("objectPlacer"), std::function<Node*(Json::Value& root, Node* parent)>( Factory::CreateChildNode<ObjectPlacer>)), std::make_pair(std::string("parallaxBackground"), std::function<Node*(Json::Value& root, Node* parent)>( Factory::CreateChildNode<ParallaxBackground>)), std::make_pair(std::string("scrollable"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<Scrollable>)), std::make_pair(std::string("particlesystem"), std::function<Node*(Json::Value& root, Node* parent)>( Factory::CreateChildNode<ParticleSystem>)) }; void Factory::RegisterType(std::string name, std::function<Node*(Json::Value& root, Node* parent)> callback) { m_types.insert(std::make_pair(name, callback)); } void Factory::RemoveType(std::string name) { m_types.erase(name); } bool Factory::LoadJson(std::string filename, Json::Value& root) { Json::Reader reader; sf::FileInputStream jconfig; if (!jconfig.open(filename)) { std::cerr << "Could not open config file '" << filename << "': " << strerror(errno) << std::endl; return false; } std::vector<char> tmp; tmp.reserve(jconfig.getSize()); jconfig.read(tmp.data(), jconfig.getSize()); if (!reader.parse(tmp.data(), tmp.data() + jconfig.getSize(), root)) { std::cerr << "Couldn't parse config" << std::endl << reader.getFormattedErrorMessages() << std::endl; return false; } return true; } Node* Factory::CreateChild(Json::Value root, Node* parent) { Json::Value childData; if (root["childData"].isString()) { if (!LoadJson(root["childData"].asString(), childData)) { std::cerr << "Couldn't load childData from file" << std::endl; return nullptr; } } else { childData = root["childData"]; } MergeJson(childData, root); std::string type = childData.get("type", "node").asString(); auto it = m_types.find(type); if (it == m_types.end()) { std::cerr << "Type '" << type << "' was not registered. Cant load child." << std::endl; return nullptr; } Node* c = it->second(childData, parent); if (!c) { return nullptr; } if (root["childData"].isString()) { c->SetFilename(root["childData"].asString()); } parent->AddNode(c); c->OnInitializeDone(); return c; } Node* Factory::CreateChildFromFile(std::string file, Node* parent) { Json::Value root; if (!Factory::LoadJson(file, root)) { return nullptr; } std::string type = root.get("type", "node").asString(); auto it = m_types.find(type); if (it == m_types.end()) { std::cerr << "Type '" << type << "' was not registered. Cant load child." << std::endl; return nullptr; } Node* c = it->second(root, parent); if (!c) { return nullptr; } c->SetFilename(file); parent->AddNode(c); c->OnInitializeDone(); return c; } bool Factory::MakeChildren(Json::Value& children, Node* parent) { if (!children.isArray()) { std::cerr << "Children is expected to be an array"; return false; } for (size_t i = 0; i < children.size(); i++) { auto child = children[i]; if (!child.isObject()) { std::cerr << "Child has to be object" << std::endl; continue; } Node* nchild = CreateChild(child, parent->GetScene()); if (nchild) { parent->AddNode(nchild); nchild->OnInitializeDone(); } } return true; } void Factory::MergeJson(Json::Value& a, Json::Value& b) { // http://stackoverflow.com/a/23860017/1318435 if (!b.isObject()) return; for (const auto& key : b.getMemberNames()) { if (a[key].isObject()) { MergeJson(a[key], b[key]); } else { a[key] = b[key]; } } } } <commit_msg>Fixes MakeChildren to set parent correctly<commit_after>#include <Engine/Scrollable.hpp> #include <Engine/Factory.hpp> #include <Engine/ParticleSystem.hpp> #include <Engine/Text.hpp> #include <Engine/Button.hpp> #include <Engine/ObjectPlacer.hpp> #include <Engine/ParallaxBackground.hpp> namespace engine { std::map<std::string, std::function<Node*(Json::Value& root, Node* parent) >> Factory::m_types = { std::make_pair(std::string("node"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<Node>)), std::make_pair(std::string("sprite"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<SpriteNode>)), std::make_pair(std::string("light"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<Light>)), std::make_pair(std::string("text"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<Text>)), std::make_pair(std::string("button"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<Button>)), std::make_pair(std::string("objectPlacer"), std::function<Node*(Json::Value& root, Node* parent)>( Factory::CreateChildNode<ObjectPlacer>)), std::make_pair(std::string("parallaxBackground"), std::function<Node*(Json::Value& root, Node* parent)>( Factory::CreateChildNode<ParallaxBackground>)), std::make_pair(std::string("scrollable"), std::function<Node*(Json::Value& root, Node* parent)>(Factory::CreateChildNode<Scrollable>)), std::make_pair(std::string("particlesystem"), std::function<Node*(Json::Value& root, Node* parent)>( Factory::CreateChildNode<ParticleSystem>)) }; void Factory::RegisterType(std::string name, std::function<Node*(Json::Value& root, Node* parent)> callback) { m_types.insert(std::make_pair(name, callback)); } void Factory::RemoveType(std::string name) { m_types.erase(name); } bool Factory::LoadJson(std::string filename, Json::Value& root) { Json::Reader reader; sf::FileInputStream jconfig; if (!jconfig.open(filename)) { std::cerr << "Could not open config file '" << filename << "': " << strerror(errno) << std::endl; return false; } std::vector<char> tmp; tmp.reserve(jconfig.getSize()); jconfig.read(tmp.data(), jconfig.getSize()); if (!reader.parse(tmp.data(), tmp.data() + jconfig.getSize(), root)) { std::cerr << "Couldn't parse config" << std::endl << reader.getFormattedErrorMessages() << std::endl; return false; } return true; } Node* Factory::CreateChild(Json::Value root, Node* parent) { Json::Value childData; if (root["childData"].isString()) { if (!LoadJson(root["childData"].asString(), childData)) { std::cerr << "Couldn't load childData from file" << std::endl; return nullptr; } } else { childData = root["childData"]; } MergeJson(childData, root); std::string type = childData.get("type", "node").asString(); auto it = m_types.find(type); if (it == m_types.end()) { std::cerr << "Type '" << type << "' was not registered. Cant load child." << std::endl; return nullptr; } Node* c = it->second(childData, parent); if (!c) { return nullptr; } if (root["childData"].isString()) { c->SetFilename(root["childData"].asString()); } parent->AddNode(c); c->OnInitializeDone(); return c; } Node* Factory::CreateChildFromFile(std::string file, Node* parent) { Json::Value root; if (!Factory::LoadJson(file, root)) { return nullptr; } std::string type = root.get("type", "node").asString(); auto it = m_types.find(type); if (it == m_types.end()) { std::cerr << "Type '" << type << "' was not registered. Cant load child." << std::endl; return nullptr; } Node* c = it->second(root, parent); if (!c) { return nullptr; } c->SetFilename(file); parent->AddNode(c); c->OnInitializeDone(); return c; } bool Factory::MakeChildren(Json::Value& children, Node* parent) { if (!children.isArray()) { std::cerr << "Children is expected to be an array"; return false; } for (size_t i = 0; i < children.size(); i++) { auto child = children[i]; if (!child.isObject()) { std::cerr << "Child has to be object" << std::endl; continue; } CreateChild(child, parent); } return true; } void Factory::MergeJson(Json::Value& a, Json::Value& b) { // http://stackoverflow.com/a/23860017/1318435 if (!b.isObject()) return; for (const auto& key : b.getMemberNames()) { if (a[key].isObject()) { MergeJson(a[key], b[key]); } else { a[key] = b[key]; } } } } <|endoftext|>
<commit_before>#include <stdlib.h> #include <algorithm> #include <iostream> #include <vector> #include <unistd.h> #include <dirent.h> #include "omp.h" void helpCheck(char *argv[]) { if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) { std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl; exit(0); } } void findAll(int *numFiles, const char *cwd) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); findAll(numFiles, filePath.c_str()); } else { *numFiles += 1; } } } closedir(dir); } } void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/"); } else { filePaths->push_back(rootPath + fileBuff); } } } closedir(dir); } } void compress(std::vector<std::string> *filePaths) { unsigned long long int filePathSize = filePaths->size(); unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1; std::vector<std::string> *tarNames = new std::vector<std::string>(); #pragma omp parallel for schedule(dynamic) for (int i = 0; i < omp_get_max_threads() * 10; ++i) { unsigned long long int start = blockSize * i; if (start < filePathSize) { std::string command = "XZ_OPT=-1 tar cJf test." + std::to_string(i) + ".tar.xz"; for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) { command += " " + filePaths->at(j); } system(command.c_str()); #pragma omp crtical { tarNames->push_back("test." + std::to_string(i) + ".tar.xz"); } } } std::string command = "tar cvf ptxz.output.tar"; for (int i = 0; i < tarNames->size(); ++i) { command += " " + tarNames->at(i); } system(command.c_str()); } char cwd [PATH_MAX]; int main(int argc, char *argv[]) { int *numFiles = new int(0); if (argc > 1) { helpCheck(argv); } getcwd(cwd, PATH_MAX); findAll(numFiles, cwd); // std::cout << *numFiles << std::endl; std::vector<std::string> *filePaths = new std::vector<std::string>(); getPaths(filePaths, cwd, ""); compress(filePaths); delete(numFiles); return 0; } <commit_msg>removing tarballs after tar merge<commit_after>#include <stdlib.h> #include <algorithm> #include <iostream> #include <vector> #include <unistd.h> #include <dirent.h> #include "omp.h" void helpCheck(char *argv[]) { if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) { std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl; exit(0); } } void findAll(int *numFiles, const char *cwd) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); findAll(numFiles, filePath.c_str()); } else { *numFiles += 1; } } } closedir(dir); } } void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/"); } else { filePaths->push_back(rootPath + fileBuff); } } } closedir(dir); } } void compress(std::vector<std::string> *filePaths) { unsigned long long int filePathSize = filePaths->size(); unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1; std::vector<std::string> *tarNames = new std::vector<std::string>(); #pragma omp parallel for schedule(dynamic) for (int i = 0; i < omp_get_max_threads() * 10; ++i) { unsigned long long int start = blockSize * i; if (start < filePathSize) { std::string command = "XZ_OPT=-1 tar cJf test." + std::to_string(i) + ".tar.xz"; for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) { command += " " + filePaths->at(j); } system(command.c_str()); #pragma omp crtical { tarNames->push_back("test." + std::to_string(i) + ".tar.xz"); } } } std::string command = "tar cvf ptxz.output.tar"; for (int i = 0; i < tarNames->size(); ++i) { command += " " + tarNames->at(i); } system(command.c_str()); std::string command = "rm"; for (int i = 0; i < tarNames->size(); ++i) { command += " " + tarNames->at(i); } system(command.c_str()); delete(tarNames); } char cwd [PATH_MAX]; int main(int argc, char *argv[]) { int *numFiles = new int(0); if (argc > 1) { helpCheck(argv); } getcwd(cwd, PATH_MAX); findAll(numFiles, cwd); // std::cout << *numFiles << std::endl; std::vector<std::string> *filePaths = new std::vector<std::string>(); getPaths(filePaths, cwd, ""); compress(filePaths); delete(numFiles); delete(filePaths); return 0; } <|endoftext|>
<commit_before>/*************************************************************************** * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration) * and Cosylab 2002, All rights reserved * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * "@(#) $Id: onchangeMonitorTest.cpp,v 1.40 2008/10/01 02:33:31 cparedes Exp $" * * who when what * -------- -------- ---------------------------------------------- * bjeram 2002/11/14 created */ static char *rcsId="@(#) $Id: onchangeMonitorTest.cpp,v 1.40 2008/10/01 02:33:31 cparedes Exp $"; static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId); #include <baciS.h> #include <baciCORBA.h> #include <enumpropTestDeviceC.h> #include <logging.h> class TestCBpattern: public virtual POA_ACS::CBpattern { private: ENUMPROP_TEST::ROStates_var rostates; ACE_CString prop; ACS::stringSeq_var description; public: TestCBpattern(ENUMPROP_TEST::ROStates_ptr _rostates) : rostates(_rostates) { prop = rostates->description(); description = rostates->statesDescription(); } void working (ACS::pattern value, const ACSErr::Completion & c, const ACS::CBDescOut & desc ) { if (c.code!=0) ACS_SHORT_LOG ((LM_DEBUG, "(%s::CBStates::working) Value: %s (%llu) Completion type: %d code: %d", prop.c_str(), description[value].in(), value, c.type, c.code)); } void done ( ACS::pattern value, const ACSErr::Completion & c, const ACS::CBDescOut & desc ) { ACS_SHORT_LOG ((LM_DEBUG, "(%s::CBStates::done) Value: %s (%llu)", prop.c_str(),description[value].in(), value)); } CORBA::Boolean negotiate ( ACS::TimeInterval time_to_transmit, const ACS::CBDescOut & desc ) { return 1; } }; int main(int argc, char* argv[]) { try { // create logging proxy LoggingProxy *m_logger = new LoggingProxy(0, 0, 31, 0); LoggingProxy::init(m_logger); LoggingProxy::ProcessName(argv[0]); LoggingProxy::ThreadName("main"); ACS_SHORT_LOG((LM_INFO, "Logging proxy successfully created !")); ACE_CString g_strCmdLn; for (int i=argc-1; i>=0; i--) g_strCmdLn = ACE_CString(argv[i])+ " " + g_strCmdLn; if (g_strCmdLn.find("-ORBDottedDecimalAddresses")==ACE_CString::npos) g_strCmdLn += " -ORBDottedDecimalAddresses 1"; ACE_TCHAR **m_argv = argv; int m_argc = argc; ACE_OS::string_to_argv((ACE_TCHAR*)g_strCmdLn.c_str(), m_argc, m_argv); BACI_CORBA::InitCORBA(m_argc, m_argv); /** * Get reference to a device */ char fileName[64]; sprintf(fileName, "file://%s.ior", argv[1]); CORBA::Object_var object = BACI_CORBA::getORB()->string_to_object (fileName); if (CORBA::is_nil(object.in())) { ACS_SHORT_LOG ((LM_DEBUG, "Cannot get Object")); return -1; } // Try to narrow the object reference to a PowerSupply reference. ENUMPROP_TEST::enumpropTestDevice_var dev = ENUMPROP_TEST::enumpropTestDevice::_narrow (object.in ()); if (CORBA::is_nil(dev.in())) { ACS_SHORT_LOG((LM_DEBUG, "Failed to narrow enumnTestDevice")); return 0; } ACS_SHORT_LOG((LM_DEBUG, "Device narrowed.")); // Get current stat ENUMPROP_TEST::ROStates_var currentState = dev->currentState(); // get states description ACS::stringSeq_var description = currentState->statesDescription( ); TestCBpattern cbStates (currentState.in()); ACS::CBpattern_var cbStatesObj = cbStates._this(); ACS::CBDescIn desc; desc.id_tag = 1; ACS::Monitorpattern_var monitor = currentState->create_monitor(cbStatesObj.in(), desc); monitor->set_timer_trigger(50000000); //=disable monitor->set_value_trigger(1, true); //=set on change /** * Enter main loop and stays there for a * fixed amount of time */ ACS_SHORT_LOG((LM_DEBUG, "(BACIClient main thread) Going in main loop sleep...")); ACE_Time_Value t(20); BACI_CORBA::getORB()->run(t); monitor->destroy(); /* Allow time for the done() callback to come back */ ACE_Time_Value t5(5); BACI_CORBA::getORB()->run(t5); BACI_CORBA::DoneCORBA(); // Delete the logger last. delete m_logger; } catch( CORBA::Exception &ex ) { ACE_PRINT_EXCEPTION (ex,"Error!"); return -1; } ACE_CHECK_RETURN (-1); return 0; } <commit_msg>fixed crash<commit_after>/*************************************************************************** * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration) * and Cosylab 2002, All rights reserved * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * "@(#) $Id: onchangeMonitorTest.cpp,v 1.41 2013/03/05 16:17:36 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * bjeram 2002/11/14 created */ static char *rcsId="@(#) $Id: onchangeMonitorTest.cpp,v 1.41 2013/03/05 16:17:36 bjeram Exp $"; static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId); #include <baciS.h> #include <baciCORBA.h> #include <enumpropTestDeviceC.h> #include <logging.h> class TestCBpattern: public virtual POA_ACS::CBpattern { private: ENUMPROP_TEST::ROStates_var rostates; ACE_CString prop; ACS::stringSeq_var description; public: TestCBpattern(ENUMPROP_TEST::ROStates_ptr _rostates) : rostates(_rostates) { prop = rostates->description(); description = rostates->statesDescription(); } void working (ACS::pattern value, const ACSErr::Completion & c, const ACS::CBDescOut & desc ) { if (c.code!=0) ACS_SHORT_LOG ((LM_DEBUG, "(%s::CBStates::working) Value: %s (%llu) Completion type: %d code: %d", prop.c_str(), description[value].in(), value, c.type, c.code)); } void done ( ACS::pattern value, const ACSErr::Completion & c, const ACS::CBDescOut & desc ) { ACS_SHORT_LOG ((LM_DEBUG, "(%s::CBStates::done) Value: %s (%llu)", prop.c_str(),description[value].in(), value)); } CORBA::Boolean negotiate ( ACS::TimeInterval time_to_transmit, const ACS::CBDescOut & desc ) { return 1; } }; int main(int argc, char* argv[]) { try { // create logging proxy LoggingProxy *m_logger = new LoggingProxy(0, 0, 31, 0); LoggingProxy::init(m_logger); LoggingProxy::ProcessName(argv[0]); LoggingProxy::ThreadName("main"); ACS_SHORT_LOG((LM_INFO, "Logging proxy successfully created !")); ACE_CString g_strCmdLn; for (int i=argc-1; i>=0; i--) g_strCmdLn = ACE_CString(argv[i])+ " " + g_strCmdLn; if (g_strCmdLn.find("-ORBDottedDecimalAddresses")==ACE_CString::npos) g_strCmdLn += " -ORBDottedDecimalAddresses 1"; ACE_TCHAR **m_argv = argv; int m_argc = argc; ACE_OS::string_to_argv((ACE_TCHAR*)g_strCmdLn.c_str(), m_argc, m_argv); BACI_CORBA::InitCORBA(m_argc, m_argv); /** * Get reference to a device */ char fileName[64]; sprintf(fileName, "file://%s.ior", argv[1]); CORBA::Object_var object = BACI_CORBA::getORB()->string_to_object (fileName); if (CORBA::is_nil(object.in())) { ACS_SHORT_LOG ((LM_DEBUG, "Cannot get Object")); return -1; } // Try to narrow the object reference to a PowerSupply reference. ENUMPROP_TEST::enumpropTestDevice_var dev = ENUMPROP_TEST::enumpropTestDevice::_narrow (object.in ()); if (CORBA::is_nil(dev.in())) { ACS_SHORT_LOG((LM_DEBUG, "Failed to narrow enumnTestDevice")); return 0; } ACS_SHORT_LOG((LM_DEBUG, "Device narrowed.")); // Get current stat ENUMPROP_TEST::ROStates_var currentState = dev->currentState(); // get states description ACS::stringSeq_var description = currentState->statesDescription( ); TestCBpattern *cbStates =new TestCBpattern(currentState.in()); ACS::CBpattern_var cbStatesObj = cbStates->_this(); ACS::CBDescIn desc; desc.id_tag = 1; ACS::Monitorpattern_var monitor = currentState->create_monitor(cbStatesObj.in(), desc); monitor->set_timer_trigger(50000000); //=disable monitor->set_value_trigger(1, true); //=set on change /** * Enter main loop and stays there for a * fixed amount of time */ ACS_SHORT_LOG((LM_DEBUG, "(BACIClient main thread) Going in main loop sleep...")); ACE_Time_Value t(20); BACI_CORBA::getORB()->run(t); monitor->destroy(); /* Allow time for the done() callback to come back */ ACE_Time_Value t5(5); BACI_CORBA::getORB()->run(t5); //currentState->_remove_ref(); BACI_CORBA::DoneCORBA(); LoggingProxy::done(); // Delete the logger last. delete m_logger; } catch( CORBA::Exception &ex ) { ACE_PRINT_EXCEPTION (ex,"Error!"); return -1; } ACE_CHECK_RETURN (-1); return 0; } <|endoftext|>
<commit_before>// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include "sys_io_ser_native.h" /////////////////////////////////////////////////////////////////////////// // memory allocated here for the buffer has to be released by the caller // /////////////////////////////////////////////////////////////////////////// HRESULT Library_sys_io_ser_native_System_IO_Ports_SerialPort::SetupWriteLine( CLR_RT_StackFrame &stack, char **buffer, uint32_t *length, bool *isNewAllocation) { NANOCLR_HEADER(); const char *text; const char *newLine; uint32_t textLength; uint32_t newLineLength; bool addNewLine; // get a pointer to the managed object instance (no need to check as this has already been done by the caller) CLR_RT_HeapBlock *pThis = stack.This(); // get pointer to string text = stack.Arg1().RecoverString(); // check for NULL string if (text != NULL) { // get length textLength = hal_strlen_s(text); // set buffer length *length = textLength; // new line parameter addNewLine = (bool)stack.Arg2().NumericByRefConst().u1; // should a new line be added? if (addNewLine) { // get string for new line newLine = pThis[FIELD___newLine].RecoverString(); newLineLength = hal_strlen_s(newLine); // allocate memory for buffer *buffer = (char *)platform_malloc(textLength + newLineLength); // sanity check for successful allocation if (*buffer) { // clear buffer memset(*buffer, 0, *length); // flag allocation *isNewAllocation = true; // update buffer length *length += newLineLength; // concatenate both strings strcat(*buffer, text); strcat(*buffer, newLine); } else { NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_MEMORY); } } else { // buffer pointing to text *buffer = (char *)text; // flag NO allocation *isNewAllocation = false; } } NANOCLR_NOCLEANUP(); } bool Library_sys_io_ser_native_System_IO_Ports_SerialPort::GetLineFromRxBuffer( CLR_RT_HeapBlock *serialDevice, HAL_RingBuffer<uint8_t> *ringBuffer, uint8_t *&line) { const char *newLine; uint32_t newLineLength; uint32_t newLineIndex; int32_t compareIndex; uint8_t *buffer; uint8_t *comparison; uint32_t matchCount = 0; uint32_t index = 0; // clear line line = NULL; // check for anything in the buffer if (ringBuffer->Length() > 0) { // get "new line" from field newLine = serialDevice[FIELD___newLine].RecoverString(); newLineLength = hal_strlen_s(newLine); // need to subtract one because we are 0 indexed newLineIndex = newLineLength - 1; // better optimize to speed up search ringBuffer->OptimizeSequence(); // grab pointer to buffer start buffer = ringBuffer->Reader(); // search for latest new line char in the buffer do { if (*buffer == newLine[newLineIndex]) { matchCount = 1; if (newLineIndex == 0) { // found and nothing else to compare break; } else { // get pointer to the index before the last one comparison = buffer; comparison--; // subtract one position, we've already check the last one compareIndex = newLineIndex - 1; do { if (*comparison == newLine[compareIndex]) { // found another match matchCount++; // } // move comparer to position before comparison--; } while (--compareIndex > 0); } } // move to next position in the buffer buffer++; index++; } while (index < ringBuffer->Length() || matchCount < newLineLength); // sequence found? if (matchCount == newLineLength) { // allocate memory for the string, including the new line char(s) // the new line char allow enough room in the buffer for for the terminator line = (uint8_t *)platform_malloc(index + newLineLength); if (line != NULL) { // pop string AND new line from buffer ringBuffer->Pop(line, index + newLineLength); // the returned string DOES NOT include the new line char(s) // put a terminator at index 0 where the new line char(s) are, so the real string ends there line[index] = 0; } } } return line; } <commit_msg>Fixing ReadLine() for multi characters (#2232)<commit_after>// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include "sys_io_ser_native.h" /////////////////////////////////////////////////////////////////////////// // memory allocated here for the buffer has to be released by the caller // /////////////////////////////////////////////////////////////////////////// HRESULT Library_sys_io_ser_native_System_IO_Ports_SerialPort::SetupWriteLine( CLR_RT_StackFrame &stack, char **buffer, uint32_t *length, bool *isNewAllocation) { NANOCLR_HEADER(); const char *text; const char *newLine; uint32_t textLength; uint32_t newLineLength; bool addNewLine; // get a pointer to the managed object instance (no need to check as this has already been done by the caller) CLR_RT_HeapBlock *pThis = stack.This(); // get pointer to string text = stack.Arg1().RecoverString(); // check for NULL string if (text != NULL) { // get length textLength = hal_strlen_s(text); // set buffer length *length = textLength; // new line parameter addNewLine = (bool)stack.Arg2().NumericByRefConst().u1; // should a new line be added? if (addNewLine) { // get string for new line newLine = pThis[FIELD___newLine].RecoverString(); newLineLength = hal_strlen_s(newLine); // allocate memory for buffer *buffer = (char *)platform_malloc(textLength + newLineLength); // sanity check for successful allocation if (*buffer) { // clear buffer memset(*buffer, 0, *length); // flag allocation *isNewAllocation = true; // update buffer length *length += newLineLength; // concatenate both strings strcat(*buffer, text); strcat(*buffer, newLine); } else { NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_MEMORY); } } else { // buffer pointing to text *buffer = (char *)text; // flag NO allocation *isNewAllocation = false; } } NANOCLR_NOCLEANUP(); } bool Library_sys_io_ser_native_System_IO_Ports_SerialPort::GetLineFromRxBuffer( CLR_RT_HeapBlock *serialDevice, HAL_RingBuffer<uint8_t> *ringBuffer, uint8_t *&line) { const char *newLine; uint32_t newLineLength; uint32_t newLineIndex; int32_t compareIndex; uint8_t *buffer; uint8_t *comparison; uint32_t matchCount = 0; uint32_t index = 0; // clear line line = NULL; // check for anything in the buffer if (ringBuffer->Length() > 0) { // get "new line" from field newLine = serialDevice[FIELD___newLine].RecoverString(); newLineLength = hal_strlen_s(newLine); // need to subtract one because we are 0 indexed newLineIndex = newLineLength - 1; // better optimize to speed up search ringBuffer->OptimizeSequence(); // grab pointer to buffer start buffer = ringBuffer->Reader(); // search for latest new line char in the buffer do { if (*buffer == newLine[newLineIndex]) { matchCount = 1; if (newLineIndex == 0) { // found and nothing else to compare index++; break; } else { // get pointer to the index before the last one comparison = buffer; comparison--; // subtract one position, we've already check the last one compareIndex = newLineIndex - 1; do { if (*comparison == newLine[compareIndex]) { // found another match matchCount++; // } // move comparer to position before comparison--; } while (--compareIndex > 0); } } // move to next position in the buffer buffer++; index++; } while (index < ringBuffer->Length() || matchCount < newLineLength); // sequence found? if (matchCount == newLineLength) { // allocate memory for the string, including the new line char(s) // the new line char allow enough room in the buffer for for the terminator line = (uint8_t *)platform_malloc(index); if (line != NULL) { // pop string AND new line from buffer ringBuffer->Pop(line, index); // the returned string DOES NOT include the new line char(s) // put a terminator at index 0 where the new line char(s) are, so the real string ends there line[index - newLineLength] = 0; } } } return line; } <|endoftext|>
<commit_before>#include "GraphML.h" #include "DirectedGraph.h" #include "UndirectedGraph.h" #include <tinyxml2.h> #include <Table.h> #include <cassert> #include <map> #include <iostream> using namespace std; using namespace tinyxml2; GraphML::GraphML() : FileTypeHandler("GraphML", true) { addExtension("graphml"); } std::shared_ptr<Graph> GraphML::openGraph(const char * filename, const std::shared_ptr<NodeArray> & initial_nodes) { RenderMode mode = RENDERMODE_3D; XMLDocument doc; doc.LoadFile(filename); XMLElement * graphml_element = doc.FirstChildElement("graphml"); assert(graphml_element); XMLElement * graph_element = graphml_element->FirstChildElement("graph"); assert(graph_element); map<string, int> nodes_by_id; const char * edgedefault = graph_element->Attribute("edgedefault"); bool directed = true; if (edgedefault && strcmp(edgedefault, "undirected") == 0) { directed = false; } std::shared_ptr<Graph> graph; if (directed) { graph = std::make_shared<DirectedGraph>(); graph->setNodeArray(initial_nodes); graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_INDEGREE)); } else { graph = std::make_shared<UndirectedGraph>(); graph->setNodeArray(initial_nodes); graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_DEGREE)); } graph->getNodeArray().setDynamic(true); graph->getNodeArray().setFlattenHierarchy(true); auto & node_table = graph->getNodeArray().getTable(); auto & edge_table = graph->getFaceData(); XMLElement * key_element = graphml_element->FirstChildElement("key"); for ( ; key_element ; key_element = key_element->NextSiblingElement("key") ) { const char * key_type = key_element->Attribute("attr.type"); const char * key_id = key_element->Attribute("id"); const char * for_type = key_element->Attribute("for"); const char * name = key_element->Attribute("attr.name"); assert(key_type && key_id && for_type); std::shared_ptr<table::Column> column; if (strcmp(key_type, "string") == 0) { column = std::make_shared<table::TextColumn>(key_id ? key_id : ""); } else if (strcmp(key_type, "double") == 0 || strcmp(key_type, "float") == 0) { column = std::make_shared<table::DoubleColumn>(key_id ? key_id : ""); } else if (strcmp(key_type, "int") == 0) { column = std::make_shared<table::IntColumn>(key_id ? key_id : ""); } else { assert(0); } if (strcmp(for_type, "node") == 0) { node_table.addColumn(column); } else if (strcmp(for_type, "edge") == 0) { edge_table.addColumn(column); } else { assert(0); } } createGraphFromElement(*graph, *graphml_element, *graph_element, nodes_by_id, directed); graph->updateFaceAppearance(); graph->randomizeGeometry(); // graph->setComplexGraph(is_complex); // graph->setHasSubGraphs(is_complex); return graph; } void GraphML::createGraphFromElement(Graph & graph, XMLElement & graphml_element, XMLElement & graph_element, map<string, int> & nodes_by_id, bool is_directed, int parent_node_id) const { auto & node_table = graph.getNodeArray().getTable(); auto & edge_table = graph.getFaceData(); auto & node_id_column = node_table.addTextColumn("id"); auto & edge_id_column = edge_table.addTextColumn("id"); XMLElement * node_element = graph_element.FirstChildElement("node"); for ( ; node_element ; node_element = node_element->NextSiblingElement("node") ) { const char * node_id_text = node_element->Attribute("id"); assert(node_id_text); int node_id = graph.addNode(); node_id_column.pushValue(node_id_text); nodes_by_id[node_id_text] = node_id + 1; if (parent_node_id != -1) graph.addChild(parent_node_id, node_id); XMLElement * data_element = node_element->FirstChildElement("data"); for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) { const char * key = data_element->Attribute("key"); assert(key); const char * text = data_element->GetText(); if (text) { node_table[key].setValue(node_id, text); } } XMLElement * nested_graph_element = node_element->FirstChildElement("graph"); if (nested_graph_element) { createGraphFromElement(graph, graphml_element, *nested_graph_element, nodes_by_id, is_directed, node_id); } } XMLElement * edge_element = graph_element.FirstChildElement("edge"); for ( ; edge_element ; edge_element = edge_element->NextSiblingElement("edge") ) { const char * edge_id_text = edge_element->Attribute("id"); const char * source = edge_element->Attribute("source"); const char * target = edge_element->Attribute("target"); assert(source && target); if (strcmp(source, target) == 0) { cerr << "GraphML: skipping self link for " << source << endl; continue; } int source_node = nodes_by_id[source]; int target_node = nodes_by_id[target]; if (source_node && target_node) { int face_id = graph.addFace(-1); int edge_id1 = graph.addEdge(source_node - 1, target_node - 1, face_id); if (!is_directed) { int edge_id2 = graph.addEdge(target_node - 1, source_node - 1, face_id); graph.connectEdgePair(edge_id1, edge_id2); } if (edge_id_text && strlen(edge_id_text) != 0) { edge_id_column.setValue(face_id, edge_id_text); } XMLElement * data_element = edge_element->FirstChildElement("data"); for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) { const char * key = data_element->Attribute("key"); assert(key); const char * text = data_element->GetText(); if (text) { edge_table[key].setValue(face_id, text); } } } else { if (!source_node) { // cerr << "cannot find node " << source << endl; } if (!target_node) { // cerr << "cannot find node " << target << endl; } } } } bool GraphML::saveGraph(const Graph & graph, const std::string & filename) { XMLDocument doc; doc.LinkEndChild(doc.NewDeclaration()); XMLElement * graphml_element = doc.NewElement("graphml"); graphml_element->SetAttribute("xmlns", "http://graphml.graphdrawing.org/xmlns"); bool directed = graph.isDirected(); auto & node_table = graph.getNodeArray().getTable(); auto & edge_table = graph.getFaceData(); for (auto & col : node_table.getColumns()) { XMLElement * key_element = doc.NewElement("key"); key_element->SetAttribute("attr.name", col.first.c_str()); key_element->SetAttribute("id", col.first.c_str()); key_element->SetAttribute("attr.type", col.second->getTypeText()); key_element->SetAttribute("for", "node"); graphml_element->LinkEndChild(key_element); } for (auto & col : edge_table.getColumns()) { XMLElement * key_element = doc.NewElement("key"); key_element->SetAttribute("attr.name", col.first.c_str()); key_element->SetAttribute("id", col.first.c_str()); key_element->SetAttribute("attr.type", col.second->getTypeText()); key_element->SetAttribute("for", "edge"); graphml_element->LinkEndChild(key_element); } XMLElement * graph_element = doc.NewElement("graph"); graphml_element->LinkEndChild(graph_element); if (!directed) { graph_element->SetAttribute("edgedefault", "undirected"); } for (unsigned int i = 0; i < graph.getNodeArray().size(); i++) { XMLElement * node_element = doc.NewElement("node"); string node_id = "n" + to_string(i); node_element->SetAttribute("id", node_id.c_str()); for (auto & col : node_table.getColumns()) { XMLElement * data_element = doc.NewElement("data"); data_element->SetAttribute("key", col.first.c_str()); data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str())); node_element->LinkEndChild(data_element); } graph_element->LinkEndChild(node_element); } for (unsigned int i = 0; i < graph.getFaceCount(); i++) { XMLElement * edge_element = doc.NewElement("edge"); #if 0 auto edge = graph.getEdgeAttributes(i); string node_id1 = "n" + to_string(edge.tail); string node_id2 = "n" + to_string(edge.head); // timestamp, sentiment edge_element->SetAttribute("source", node_id1.c_str()); edge_element->SetAttribute("target", node_id2.c_str()); #endif for (auto & col : edge_table.getColumns()) { XMLElement * data_element = doc.NewElement("data"); data_element->SetAttribute("key", col.first.c_str()); data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str())); edge_element->LinkEndChild(data_element); } graph_element->LinkEndChild(edge_element); } doc.LinkEndChild(graphml_element); doc.SaveFile(filename.c_str()); return true; } <commit_msg>refactor<commit_after>#include "GraphML.h" #include "DirectedGraph.h" #include "UndirectedGraph.h" #include <tinyxml2.h> #include <Table.h> #include <cassert> #include <map> #include <iostream> using namespace std; using namespace tinyxml2; GraphML::GraphML() : FileTypeHandler("GraphML", true) { addExtension("graphml"); } static void createColumn(table::Table & table, const char * type, const char * id) { if (strcmp(type, "string") == 0) { table.addCompressedTextColumn(id ? id : ""); } else if (strcmp(type, "double") == 0 || strcmp(type, "float") == 0) { table.addDoubleColumn(id ? id : ""); } else if (strcmp(type, "int") == 0) { table.addIntColumn(id ? id : ""); } else { assert(0); } } std::shared_ptr<Graph> GraphML::openGraph(const char * filename, const std::shared_ptr<NodeArray> & initial_nodes) { RenderMode mode = RENDERMODE_3D; XMLDocument doc; doc.LoadFile(filename); XMLElement * graphml_element = doc.FirstChildElement("graphml"); assert(graphml_element); XMLElement * graph_element = graphml_element->FirstChildElement("graph"); assert(graph_element); map<string, int> nodes_by_id; const char * edgedefault = graph_element->Attribute("edgedefault"); bool directed = true; if (edgedefault && strcmp(edgedefault, "undirected") == 0) { directed = false; } std::shared_ptr<Graph> graph; if (directed) { graph = std::make_shared<DirectedGraph>(); graph->setNodeArray(initial_nodes); graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_INDEGREE)); } else { graph = std::make_shared<UndirectedGraph>(); graph->setNodeArray(initial_nodes); graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_DEGREE)); } graph->getNodeArray().setDynamic(true); graph->getNodeArray().setFlattenHierarchy(true); auto & node_table = graph->getNodeArray().getTable(); auto & edge_table = graph->getFaceData(); XMLElement * key_element = graphml_element->FirstChildElement("key"); for ( ; key_element ; key_element = key_element->NextSiblingElement("key") ) { const char * key_type = key_element->Attribute("attr.type"); const char * key_id = key_element->Attribute("id"); const char * for_type = key_element->Attribute("for"); // const char * name = key_element->Attribute("attr.name"); assert(key_type && key_id && for_type); if (strcmp(for_type, "node") == 0) { createColumn(node_table, key_type, key_id); } else if (strcmp(for_type, "edge") == 0) { createColumn(edge_table, key_type, key_id); } else { assert(0); } } createGraphFromElement(*graph, *graphml_element, *graph_element, nodes_by_id, directed); graph->updateFaceAppearance(); graph->randomizeGeometry(); // graph->setComplexGraph(is_complex); // graph->setHasSubGraphs(is_complex); return graph; } void GraphML::createGraphFromElement(Graph & graph, XMLElement & graphml_element, XMLElement & graph_element, map<string, int> & nodes_by_id, bool is_directed, int parent_node_id) const { auto & node_table = graph.getNodeArray().getTable(); auto & edge_table = graph.getFaceData(); auto & node_id_column = node_table.addTextColumn("id"); auto & edge_id_column = edge_table.addTextColumn("id"); XMLElement * node_element = graph_element.FirstChildElement("node"); for ( ; node_element ; node_element = node_element->NextSiblingElement("node") ) { const char * node_id_text = node_element->Attribute("id"); assert(node_id_text); int node_id = graph.addNode(); node_id_column.pushValue(node_id_text); nodes_by_id[node_id_text] = node_id + 1; if (parent_node_id != -1) graph.addChild(parent_node_id, node_id); XMLElement * data_element = node_element->FirstChildElement("data"); for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) { const char * key = data_element->Attribute("key"); assert(key); const char * text = data_element->GetText(); if (text) { node_table[key].setValue(node_id, text); } } XMLElement * nested_graph_element = node_element->FirstChildElement("graph"); if (nested_graph_element) { createGraphFromElement(graph, graphml_element, *nested_graph_element, nodes_by_id, is_directed, node_id); } } XMLElement * edge_element = graph_element.FirstChildElement("edge"); for ( ; edge_element ; edge_element = edge_element->NextSiblingElement("edge") ) { const char * edge_id_text = edge_element->Attribute("id"); const char * source = edge_element->Attribute("source"); const char * target = edge_element->Attribute("target"); assert(source && target); if (strcmp(source, target) == 0) { cerr << "GraphML: skipping self link for " << source << endl; continue; } int source_node = nodes_by_id[source]; int target_node = nodes_by_id[target]; if (source_node && target_node) { int face_id = graph.addFace(-1); int edge_id1 = graph.addEdge(source_node - 1, target_node - 1, face_id); if (!is_directed) { int edge_id2 = graph.addEdge(target_node - 1, source_node - 1, face_id); graph.connectEdgePair(edge_id1, edge_id2); } if (edge_id_text && strlen(edge_id_text) != 0) { edge_id_column.setValue(face_id, edge_id_text); } XMLElement * data_element = edge_element->FirstChildElement("data"); for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) { const char * key = data_element->Attribute("key"); assert(key); const char * text = data_element->GetText(); if (text) { edge_table[key].setValue(face_id, text); } } } else { if (!source_node) { // cerr << "cannot find node " << source << endl; } if (!target_node) { // cerr << "cannot find node " << target << endl; } } } } bool GraphML::saveGraph(const Graph & graph, const std::string & filename) { XMLDocument doc; doc.LinkEndChild(doc.NewDeclaration()); XMLElement * graphml_element = doc.NewElement("graphml"); graphml_element->SetAttribute("xmlns", "http://graphml.graphdrawing.org/xmlns"); bool directed = graph.isDirected(); auto & node_table = graph.getNodeArray().getTable(); auto & edge_table = graph.getFaceData(); for (auto & col : node_table.getColumns()) { XMLElement * key_element = doc.NewElement("key"); key_element->SetAttribute("attr.name", col.first.c_str()); key_element->SetAttribute("id", col.first.c_str()); key_element->SetAttribute("attr.type", col.second->getTypeText()); key_element->SetAttribute("for", "node"); graphml_element->LinkEndChild(key_element); } for (auto & col : edge_table.getColumns()) { XMLElement * key_element = doc.NewElement("key"); key_element->SetAttribute("attr.name", col.first.c_str()); key_element->SetAttribute("id", col.first.c_str()); key_element->SetAttribute("attr.type", col.second->getTypeText()); key_element->SetAttribute("for", "edge"); graphml_element->LinkEndChild(key_element); } XMLElement * graph_element = doc.NewElement("graph"); graphml_element->LinkEndChild(graph_element); if (!directed) { graph_element->SetAttribute("edgedefault", "undirected"); } for (unsigned int i = 0; i < graph.getNodeArray().size(); i++) { XMLElement * node_element = doc.NewElement("node"); string node_id = "n" + to_string(i); node_element->SetAttribute("id", node_id.c_str()); for (auto & col : node_table.getColumns()) { XMLElement * data_element = doc.NewElement("data"); data_element->SetAttribute("key", col.first.c_str()); data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str())); node_element->LinkEndChild(data_element); } graph_element->LinkEndChild(node_element); } for (unsigned int i = 0; i < graph.getFaceCount(); i++) { XMLElement * edge_element = doc.NewElement("edge"); #if 0 auto edge = graph.getEdgeAttributes(i); string node_id1 = "n" + to_string(edge.tail); string node_id2 = "n" + to_string(edge.head); // timestamp, sentiment edge_element->SetAttribute("source", node_id1.c_str()); edge_element->SetAttribute("target", node_id2.c_str()); #endif for (auto & col : edge_table.getColumns()) { XMLElement * data_element = doc.NewElement("data"); data_element->SetAttribute("key", col.first.c_str()); data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str())); edge_element->LinkEndChild(data_element); } graph_element->LinkEndChild(edge_element); } doc.LinkEndChild(graphml_element); doc.SaveFile(filename.c_str()); return true; } <|endoftext|>
<commit_before>// // data.cpp // EpiGenMCMC // // Created by Lucy Li on 13/04/2016. // Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved. // #include "data.h" // // TimeSeriesData // TimeSeriesData::TimeSeriesData(){}; TimeSeriesData::TimeSeriesData(std::string filename) { std::ifstream file (filename); double num; file >> num_time_steps >> time_step_size >> num_groups; bool first_found = false; if (num_groups == 1) { while (file >> num) { data.push_back(num); if (!first_found & (num > 0)) { first_data_time = data.size()-1.0; first_found = true; } } } else { int pos=0; int data_pos; data.resize(num_time_steps*num_groups); while (file >> num) { data_pos = (pos%num_groups)*num_time_steps+pos/num_groups; data[data_pos] = num; ++pos; if (!first_found & (num > 0)) { first_data_time = pos/num_groups; first_found = true; } } } file.close(); } int TimeSeriesData::get_T() const { return (num_time_steps); } double TimeSeriesData::get_dt() const { return (time_step_size); } int TimeSeriesData::get_num_group() const { return (num_groups); } int TimeSeriesData::get_first() const { return(first_data_time); } double TimeSeriesData::get(int index) const { return (data[index]); } double TimeSeriesData::get(int time_index, int group_index) const { return (data[group_index*num_time_steps+time_index]); } std::vector<double>::iterator TimeSeriesData::get_data_ptr(int index) { return (data.begin()); } // // TreeData // TreeData::TreeData(){} TreeData::TreeData(std::string filename) { std::ifstream file (filename); std::string line; file >> num_time_steps >> time_step_size; bool first_found = false; // Read in binomial data for (int t=0; t!=num_time_steps; ++t) { std::getline(file, line); if (line.empty()) std::getline(file, line); std::istringstream input(line); if (t==0) starts.push_back(0); else { starts.push_back(binomials.size()); } while (std::getline(input, line, ' ')) { binomials.push_back (std::stod(line)); if (!first_found & (std::stod(line) > 1.0)) { first_data_time = t; first_found = true; } } ends.push_back(binomials.size()-1.0); } // Read in intervals data for (int t=0; t!=num_time_steps; ++t) { std::getline(file, line); std::istringstream input(line); while (std::getline(input, line, ' ')) { intervals.push_back (std::stod(line)); } } file.close(); } int TreeData::get_T() const { return (num_time_steps); } double TreeData::get_dt() const { return (time_step_size); } int TreeData::get_first() const { return(first_data_time); } int TreeData::get_num_events(int time_index) const { return (ends[time_index]-starts[time_index]+1); } void TreeData::get_binomial (int time_index, std::vector <double>& output) const { for (int i=starts[time_index]; i<=ends[time_index]; ++i) { output[i-starts[time_index]] = binomials[i]; } } void TreeData::get_binomial (int start_time, int end_time, std::vector <double>& output) const { for (int i=starts[start_time]; i<=ends[end_time-1]; ++i) { output[i-starts[start_time]] = binomials[i]; } } double TreeData::get_binomial (int time_index, int event_index) const { return (binomials[starts[time_index]+event_index]); } std::vector<double>::iterator TreeData::get_binomial_ptr(int index) { return (binomials.begin()+starts[index]); } void TreeData::get_interval (int time_index, std::vector <double>& output) const { for (int i=starts[time_index]; i<=ends[time_index]; ++i) { output[i-starts[time_index]] = intervals[i]; } } double TreeData::get_interval (int time_index, int event_index) const { return (intervals[starts[time_index]+event_index]); } void TreeData::get_interval (int start_time, int end_time, std::vector <double>& output) const { for (int i=starts[start_time]; i<=ends[end_time-1]; ++i) { output[i-starts[start_time]] = intervals[i]; } } std::vector<double>::iterator TreeData::get_interval_ptr(int index) { return (intervals.begin()+starts[index]); } std::vector<double>::iterator TreeData::get_starts_ptr(int index) { return(starts.begin()+index); } std::vector<double>::iterator TreeData::get_ends_ptr(int index) { return(ends.begin()+index); } // // MultiTreeData // MultiTreeData::MultiTreeData(){} MultiTreeData::MultiTreeData(std::string filename) { std::ifstream file (filename); std::string tree_filename; file >> num_trees; for (int i=0; i!=num_trees; ++i) { file >> tree_filename; TreeData *ptr = new TreeData(tree_filename); tree_ptrs.push_back(ptr); } file.close(); num_time_steps = tree_ptrs[0]->get_T(); time_step_size = tree_ptrs[0]->get_dt(); for (int i=0; i!=num_trees; ++i) { first_data_time = std::min(first_data_time, tree_ptrs[i]->get_first()); } }; int MultiTreeData::get_num_tree() const { return (num_trees); } int MultiTreeData::get_T() const { return (num_time_steps); } double MultiTreeData::get_dt() const { return (time_step_size); } int MultiTreeData::get_first() const { return (first_data_time); } <commit_msg>ensure lines are read in correctly<commit_after>// // data.cpp // EpiGenMCMC // // Created by Lucy Li on 13/04/2016. // Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved. // #include "data.h" // // TimeSeriesData // TimeSeriesData::TimeSeriesData(){}; TimeSeriesData::TimeSeriesData(std::string filename) { std::ifstream file (filename); double num; file >> num_time_steps >> time_step_size >> num_groups; bool first_found = false; if (num_groups == 1) { while (file >> num) { data.push_back(num); if (!first_found & (num > 0)) { first_data_time = data.size()-1.0; first_found = true; } } } else { int pos=0; int data_pos; data.resize(num_time_steps*num_groups); while (file >> num) { data_pos = (pos%num_groups)*num_time_steps+pos/num_groups; data[data_pos] = num; ++pos; if (!first_found & (num > 0)) { first_data_time = pos/num_groups; first_found = true; } } } file.close(); } int TimeSeriesData::get_T() const { return (num_time_steps); } double TimeSeriesData::get_dt() const { return (time_step_size); } int TimeSeriesData::get_num_group() const { return (num_groups); } int TimeSeriesData::get_first() const { return(first_data_time); } double TimeSeriesData::get(int index) const { return (data[index]); } double TimeSeriesData::get(int time_index, int group_index) const { return (data[group_index*num_time_steps+time_index]); } std::vector<double>::iterator TimeSeriesData::get_data_ptr(int index) { return (data.begin()); } // // TreeData // TreeData::TreeData(){} TreeData::TreeData(std::string filename) { std::ifstream file (filename); std::string line; file >> num_time_steps >> time_step_size; bool first_found = false; std::getline(file, line); // Read in binomial data for (int t=0; t!=num_time_steps; ++t) { std::getline(file, line); std::istringstream input(line); if (t==0) starts.push_back(0); else { starts.push_back(binomials.size()); } while (std::getline(input, line, ' ')) { binomials.push_back (std::stod(line)); if (!first_found & (std::stod(line) > 1.0)) { first_data_time = t; first_found = true; } } ends.push_back(binomials.size()-1.0); } // Read in intervals data for (int t=0; t!=num_time_steps; ++t) { std::getline(file, line); std::istringstream input(line); while (std::getline(input, line, ' ')) { intervals.push_back (std::stod(line)); } } file.close(); } int TreeData::get_T() const { return (num_time_steps); } double TreeData::get_dt() const { return (time_step_size); } int TreeData::get_first() const { return(first_data_time); } int TreeData::get_num_events(int time_index) const { return (ends[time_index]-starts[time_index]+1); } void TreeData::get_binomial (int time_index, std::vector <double>& output) const { for (int i=starts[time_index]; i<=ends[time_index]; ++i) { output[i-starts[time_index]] = binomials[i]; } } void TreeData::get_binomial (int start_time, int end_time, std::vector <double>& output) const { for (int i=starts[start_time]; i<=ends[end_time-1]; ++i) { output[i-starts[start_time]] = binomials[i]; } } double TreeData::get_binomial (int time_index, int event_index) const { return (binomials[starts[time_index]+event_index]); } std::vector<double>::iterator TreeData::get_binomial_ptr(int index) { return (binomials.begin()+starts[index]); } void TreeData::get_interval (int time_index, std::vector <double>& output) const { for (int i=starts[time_index]; i<=ends[time_index]; ++i) { output[i-starts[time_index]] = intervals[i]; } } double TreeData::get_interval (int time_index, int event_index) const { return (intervals[starts[time_index]+event_index]); } void TreeData::get_interval (int start_time, int end_time, std::vector <double>& output) const { for (int i=starts[start_time]; i<=ends[end_time-1]; ++i) { output[i-starts[start_time]] = intervals[i]; } } std::vector<double>::iterator TreeData::get_interval_ptr(int index) { return (intervals.begin()+starts[index]); } std::vector<double>::iterator TreeData::get_starts_ptr(int index) { return(starts.begin()+index); } std::vector<double>::iterator TreeData::get_ends_ptr(int index) { return(ends.begin()+index); } // // MultiTreeData // MultiTreeData::MultiTreeData(){} MultiTreeData::MultiTreeData(std::string filename) { std::ifstream file (filename); std::string tree_filename; file >> num_trees; for (int i=0; i!=num_trees; ++i) { file >> tree_filename; TreeData *ptr = new TreeData(tree_filename); tree_ptrs.push_back(ptr); } file.close(); num_time_steps = tree_ptrs[0]->get_T(); time_step_size = tree_ptrs[0]->get_dt(); for (int i=0; i!=num_trees; ++i) { first_data_time = std::min(first_data_time, tree_ptrs[i]->get_first()); } }; int MultiTreeData::get_num_tree() const { return (num_trees); } int MultiTreeData::get_T() const { return (num_time_steps); } double MultiTreeData::get_dt() const { return (time_step_size); } int MultiTreeData::get_first() const { return (first_data_time); } <|endoftext|>
<commit_before>#include <vector> #include <list> #include <map> #include <string> #include <iostream> #include <cstring> #include <unistd.h> #include <stdint.h> #include <cstdlib> #include <cassert> #include "rinalite/rinalite-common.h" #include "rinalite/rinalite-utils.h" #include "rinalite/rina-conf-msg.h" #include "rinalite-appl.h" #include "cdap.hpp" #include "uipcp-container.h" #include "uipcp-codecs.hpp" using namespace std; namespace obj_class { static string dft = "dft"; static string neighbors = "neighbors"; static string enrollment = "enrollment"; static string status = "operational_status"; static string address = "address"; }; namespace obj_name { static string dft = "/dif/mgmt/fa/" + obj_class::dft; static string neighbors = "/daf/mgmt/" + obj_class::neighbors; static string enrollment = "/def/mgmt/" + obj_class::enrollment; static string status = "/daf/mgmt/" + obj_class::status; static string address = "/def/mgmt/naming" + obj_class::address; static string whatevercast = "/daf/mgmt/naming/whatevercast"; }; struct Neighbor { struct rina_name ipcp_name; int flow_fd; unsigned int port_id; CDAPConn *conn; struct uipcp_rib *rib; enum { NONE = 0, I_CONNECT_SENT, S_CONNECT_RCVD, } enrollment_state; Neighbor(struct uipcp_rib *rib, const struct rina_name *name, int fd, unsigned int port_id); Neighbor(const Neighbor &other); ~Neighbor(); int send_to_port_id(CDAPMessage *m); int fsm_run(const CDAPMessage *rm); }; Neighbor::Neighbor(struct uipcp_rib *rib_, const struct rina_name *name, int fd, unsigned int port_id_) { rib = rib_; rina_name_copy(&ipcp_name, name); flow_fd = fd; port_id = port_id_; conn = NULL; enrollment_state = NONE; } Neighbor::Neighbor(const Neighbor& other) { rib = other.rib; rina_name_copy(&ipcp_name, &other.ipcp_name); flow_fd = other.flow_fd; port_id = other.port_id; enrollment_state = enrollment_state; conn = NULL; } Neighbor::~Neighbor() { rina_name_free(&ipcp_name); if (conn) { delete conn; } } typedef int (*rib_handler_t)(struct uipcp_rib *); struct uipcp_rib { /* Backpointer to parent data structure. */ struct uipcp *uipcp; map< string, rib_handler_t > handlers; /* Neighbors. */ list< Neighbor > neighbors; /* Directory Forwarding Table. */ map< string, uint64_t > dft; uipcp_rib(struct uipcp *_u) : uipcp(_u) {} list<Neighbor>::iterator lookup_neigh_by_port_id(unsigned int port_id); }; list<Neighbor>::iterator uipcp_rib::lookup_neigh_by_port_id(unsigned int port_id) { for (list<Neighbor>::iterator neigh = neighbors.begin(); neigh != neighbors.end(); neigh++) { if (neigh->port_id == port_id) { return neigh; } } return neighbors.end(); } static int dft_handler(struct uipcp_rib *) { return 0; } static int whatevercast_handler(struct uipcp_rib *) { return 0; } extern "C" struct uipcp_rib * rib_create(struct uipcp *uipcp) { struct uipcp_rib *rib = new uipcp_rib(uipcp); if (!rib) { return NULL; } /* Insert the handlers for the RIB objects. */ rib->handlers.insert(make_pair(obj_name::dft, dft_handler)); rib->handlers.insert(make_pair(obj_name::whatevercast, whatevercast_handler)); return rib; } extern "C" void rib_destroy(struct uipcp_rib *rib) { int ret; for (list<Neighbor>::iterator neigh = rib->neighbors.begin(); neigh != rib->neighbors.end(); neigh++) { ret = close(neigh->flow_fd); if (ret) { PE("%s: Error deallocating N-1 flow fd %d\n", __func__, neigh->flow_fd); } } delete rib; } static int rib_remote_sync(struct uipcp_rib *rib, bool create, const string& obj_class, const string& obj_name, int x) { struct enrolled_neighbor *neigh; #if 0 CDAPMessage m; int invoke_id; list_for_each_entry(neigh, &rib->uipcp->enrolled_neighbors, node) { if (create) { m.m_create(gpb::F_NO_FLAGS, obj_class, obj_name, 0, 0, ""); } else { m.m_delete(gpb::F_NO_FLAGS, obj_class, obj_name, 0, 0, ""); } } conn.msg_send(&m, 0); #endif } int Neighbor::send_to_port_id(CDAPMessage *m) { char *serbuf; size_t serlen; int ret; ret = conn->msg_ser(m, 0, &serbuf, &serlen); if (ret) { delete serbuf; return -1; } return mgmt_write_to_local_port(rib->uipcp, port_id, serbuf, serlen); } int Neighbor::fsm_run(const CDAPMessage *rm) { unsigned int old_state = enrollment_state; struct uipcp *uipcp = rib->uipcp; struct rinalite_ipcp *ipcp; CDAPMessage m; int ret; ipcp = rinalite_lookup_ipcp_by_id(&uipcp->appl.loop, uipcp->ipcp_id); assert(ipcp); switch (enrollment_state) { case NONE: if (rm == NULL) { CDAPAuthValue av; /* We are the enrollment initiator, let's send an * M_CONNECT message. */ conn = new CDAPConn(flow_fd, 1); if (conn) { PE("%s: Out of memory\n", __func__); break; } ret = m.m_connect(gpb::AUTH_NONE, &av, &ipcp->ipcp_name, &ipcp_name); if (ret) { PE("%s: M_CONNECT creation failed\n", __func__); break; } } break; default: assert(0); return -1; break; } if (ret) { return ret; } if (old_state != enrollment_state) { PI("%s: switching state %u --> %u\n", __func__, old_state, enrollment_state); } return send_to_port_id(&m); } extern "C" int uipcp_enroll(struct uipcp_rib *rib, struct rina_cmsg_ipcp_enroll *req) { struct uipcp *uipcp = rib->uipcp; unsigned int port_id; int flow_fd; int ret; for (list<Neighbor>::iterator neigh = rib->neighbors.begin(); neigh != rib->neighbors.end(); neigh++) { if (rina_name_cmp(&neigh->ipcp_name, &req->neigh_ipcp_name) == 0) { char *ipcp_s = rina_name_to_string(&req->neigh_ipcp_name); PI("[uipcp %u] Already enrolled to %s", uipcp->ipcp_id, ipcp_s); if (ipcp_s) { free(ipcp_s); } return -1; } } /* Allocate a flow for the enrollment. */ ret = rinalite_flow_allocate(&uipcp->appl, &req->supp_dif_name, 0, NULL, &req->ipcp_name, &req->neigh_ipcp_name, NULL, &port_id, 2000, uipcp->ipcp_id); if (ret) { goto err; } flow_fd = rinalite_open_appl_port(port_id); if (flow_fd < 0) { goto err; } /* Start the enrollment procedure as initiator. */ rib->neighbors.push_back(Neighbor(rib, &req->neigh_ipcp_name, flow_fd, port_id)); //return uipcp_enroll_send_mgmtsdu(uipcp, port_id); ret = rib->neighbors.back().fsm_run(NULL); if (ret == 0) { return 0; } close(flow_fd); err: return -1; } extern "C" int rib_neighbor_flow(struct uipcp_rib *rib, const struct rina_name *neigh_name, int neigh_fd, unsigned int neigh_port_id) { struct uipcp *uipcp = rib->uipcp; for (list<Neighbor>::iterator neigh = rib->neighbors.begin(); neigh != rib->neighbors.end(); neigh++) { if (rina_name_cmp(&neigh->ipcp_name, neigh_name) == 0) { char *ipcp_s = rina_name_to_string(neigh_name); PI("[uipcp %u] Already enrolled to %s", uipcp->ipcp_id, ipcp_s); if (ipcp_s) { free(ipcp_s); } return -1; } } /* Start the enrollment procedure as slave. */ rib->neighbors.push_back(Neighbor(rib, neigh_name, neigh_fd, neigh_port_id)); return 0; } extern "C" int rib_msg_rcvd(struct uipcp_rib *rib, struct rina_mgmt_hdr *mhdr, char *serbuf, int serlen) { list<Neighbor>::iterator neigh = rib->lookup_neigh_by_port_id(mhdr->local_port); if (neigh == rib->neighbors.end()) { PE("%s: Received message from unknown port id %d\n", __func__, mhdr->local_port); return -1; } return 0; } extern "C" int rib_application_register(struct uipcp_rib *rib, int reg, const struct rina_name *appl_name) { char *name_s = rina_name_to_string(appl_name); map< string, uint64_t >::iterator mit; struct uipcp *uipcp = rib->uipcp; uint64_t local_addr; string name_str; int ret; bool create = true; ret = rinalite_lookup_ipcp_addr_by_id(&uipcp->appl.loop, uipcp->ipcp_id, &local_addr); assert(!ret); if (!name_s) { PE("%s: Out of memory\n", __func__); return -1; } name_str = name_s; free(name_s); mit = rib->dft.find(name_str); if (reg) { if (mit != rib->dft.end()) { PE("%s: Application %s already registered on uipcp with address " "[%llu], my address being [%llu]\n", __func__, name_str.c_str(), (long long unsigned)mit->second, (long long unsigned)local_addr); return -1; } /* Insert the object into the RIB. */ rib->dft.insert(make_pair(name_str, local_addr)); } else { if (mit == rib->dft.end()) { PE("%s: Application %s was not registered here\n", __func__, name_str.c_str()); return -1; } /* Remove the object from the RIB. */ rib->dft.erase(mit); create = false; } rib_remote_sync(rib, create, obj_class::dft, obj_name::dft, 10329); PD("%s: Application %s %sregistered %s uipcp %d\n", __func__, name_str.c_str(), reg ? "" : "un", reg ? "to" : "from", uipcp->ipcp_id); return 0; } <commit_msg>uipcp: rib_msg_rcvd: feed the enrollment state machine<commit_after>#include <vector> #include <list> #include <map> #include <string> #include <iostream> #include <cstring> #include <unistd.h> #include <stdint.h> #include <cstdlib> #include <cassert> #include "rinalite/rinalite-common.h" #include "rinalite/rinalite-utils.h" #include "rinalite/rina-conf-msg.h" #include "rinalite-appl.h" #include "cdap.hpp" #include "uipcp-container.h" #include "uipcp-codecs.hpp" using namespace std; namespace obj_class { static string dft = "dft"; static string neighbors = "neighbors"; static string enrollment = "enrollment"; static string status = "operational_status"; static string address = "address"; }; namespace obj_name { static string dft = "/dif/mgmt/fa/" + obj_class::dft; static string neighbors = "/daf/mgmt/" + obj_class::neighbors; static string enrollment = "/def/mgmt/" + obj_class::enrollment; static string status = "/daf/mgmt/" + obj_class::status; static string address = "/def/mgmt/naming" + obj_class::address; static string whatevercast = "/daf/mgmt/naming/whatevercast"; }; struct Neighbor { struct rina_name ipcp_name; int flow_fd; unsigned int port_id; CDAPConn *conn; struct uipcp_rib *rib; enum { NONE = 0, I_CONNECT_SENT, S_CONNECT_RCVD, } enrollment_state; Neighbor(struct uipcp_rib *rib, const struct rina_name *name, int fd, unsigned int port_id); Neighbor(const Neighbor &other); ~Neighbor(); int send_to_port_id(CDAPMessage *m); int fsm_run(const CDAPMessage *rm); }; Neighbor::Neighbor(struct uipcp_rib *rib_, const struct rina_name *name, int fd, unsigned int port_id_) { rib = rib_; rina_name_copy(&ipcp_name, name); flow_fd = fd; port_id = port_id_; conn = NULL; enrollment_state = NONE; } Neighbor::Neighbor(const Neighbor& other) { rib = other.rib; rina_name_copy(&ipcp_name, &other.ipcp_name); flow_fd = other.flow_fd; port_id = other.port_id; enrollment_state = enrollment_state; conn = NULL; } Neighbor::~Neighbor() { rina_name_free(&ipcp_name); if (conn) { delete conn; } } typedef int (*rib_handler_t)(struct uipcp_rib *); struct uipcp_rib { /* Backpointer to parent data structure. */ struct uipcp *uipcp; map< string, rib_handler_t > handlers; /* Neighbors. */ list< Neighbor > neighbors; /* Directory Forwarding Table. */ map< string, uint64_t > dft; uipcp_rib(struct uipcp *_u) : uipcp(_u) {} list<Neighbor>::iterator lookup_neigh_by_port_id(unsigned int port_id); }; list<Neighbor>::iterator uipcp_rib::lookup_neigh_by_port_id(unsigned int port_id) { for (list<Neighbor>::iterator neigh = neighbors.begin(); neigh != neighbors.end(); neigh++) { if (neigh->port_id == port_id) { return neigh; } } return neighbors.end(); } static int dft_handler(struct uipcp_rib *) { return 0; } static int whatevercast_handler(struct uipcp_rib *) { return 0; } extern "C" struct uipcp_rib * rib_create(struct uipcp *uipcp) { struct uipcp_rib *rib = new uipcp_rib(uipcp); if (!rib) { return NULL; } /* Insert the handlers for the RIB objects. */ rib->handlers.insert(make_pair(obj_name::dft, dft_handler)); rib->handlers.insert(make_pair(obj_name::whatevercast, whatevercast_handler)); return rib; } extern "C" void rib_destroy(struct uipcp_rib *rib) { int ret; for (list<Neighbor>::iterator neigh = rib->neighbors.begin(); neigh != rib->neighbors.end(); neigh++) { ret = close(neigh->flow_fd); if (ret) { PE("%s: Error deallocating N-1 flow fd %d\n", __func__, neigh->flow_fd); } } delete rib; } static int rib_remote_sync(struct uipcp_rib *rib, bool create, const string& obj_class, const string& obj_name, int x) { struct enrolled_neighbor *neigh; #if 0 CDAPMessage m; int invoke_id; list_for_each_entry(neigh, &rib->uipcp->enrolled_neighbors, node) { if (create) { m.m_create(gpb::F_NO_FLAGS, obj_class, obj_name, 0, 0, ""); } else { m.m_delete(gpb::F_NO_FLAGS, obj_class, obj_name, 0, 0, ""); } } conn.msg_send(&m, 0); #endif } int Neighbor::send_to_port_id(CDAPMessage *m) { char *serbuf; size_t serlen; int ret; ret = conn->msg_ser(m, 0, &serbuf, &serlen); if (ret) { delete serbuf; return -1; } return mgmt_write_to_local_port(rib->uipcp, port_id, serbuf, serlen); } int Neighbor::fsm_run(const CDAPMessage *rm) { unsigned int old_state = enrollment_state; struct uipcp *uipcp = rib->uipcp; struct rinalite_ipcp *ipcp; CDAPMessage m; int ret; ipcp = rinalite_lookup_ipcp_by_id(&uipcp->appl.loop, uipcp->ipcp_id); assert(ipcp); switch (enrollment_state) { case NONE: if (rm == NULL) { CDAPAuthValue av; /* We are the enrollment initiator, let's send an * M_CONNECT message. */ conn = new CDAPConn(flow_fd, 1); if (conn) { PE("%s: Out of memory\n", __func__); break; } ret = m.m_connect(gpb::AUTH_NONE, &av, &ipcp->ipcp_name, &ipcp_name); if (ret) { PE("%s: M_CONNECT creation failed\n", __func__); break; } } break; default: assert(0); return -1; break; } if (ret) { return ret; } if (old_state != enrollment_state) { PI("%s: switching state %u --> %u\n", __func__, old_state, enrollment_state); } return send_to_port_id(&m); } extern "C" int uipcp_enroll(struct uipcp_rib *rib, struct rina_cmsg_ipcp_enroll *req) { struct uipcp *uipcp = rib->uipcp; unsigned int port_id; int flow_fd; int ret; for (list<Neighbor>::iterator neigh = rib->neighbors.begin(); neigh != rib->neighbors.end(); neigh++) { if (rina_name_cmp(&neigh->ipcp_name, &req->neigh_ipcp_name) == 0) { char *ipcp_s = rina_name_to_string(&req->neigh_ipcp_name); PI("[uipcp %u] Already enrolled to %s", uipcp->ipcp_id, ipcp_s); if (ipcp_s) { free(ipcp_s); } return -1; } } /* Allocate a flow for the enrollment. */ ret = rinalite_flow_allocate(&uipcp->appl, &req->supp_dif_name, 0, NULL, &req->ipcp_name, &req->neigh_ipcp_name, NULL, &port_id, 2000, uipcp->ipcp_id); if (ret) { goto err; } flow_fd = rinalite_open_appl_port(port_id); if (flow_fd < 0) { goto err; } /* Start the enrollment procedure as initiator. */ rib->neighbors.push_back(Neighbor(rib, &req->neigh_ipcp_name, flow_fd, port_id)); //return uipcp_enroll_send_mgmtsdu(uipcp, port_id); ret = rib->neighbors.back().fsm_run(NULL); if (ret == 0) { return 0; } close(flow_fd); err: return -1; } extern "C" int rib_neighbor_flow(struct uipcp_rib *rib, const struct rina_name *neigh_name, int neigh_fd, unsigned int neigh_port_id) { struct uipcp *uipcp = rib->uipcp; for (list<Neighbor>::iterator neigh = rib->neighbors.begin(); neigh != rib->neighbors.end(); neigh++) { if (rina_name_cmp(&neigh->ipcp_name, neigh_name) == 0) { char *ipcp_s = rina_name_to_string(neigh_name); PI("[uipcp %u] Already enrolled to %s", uipcp->ipcp_id, ipcp_s); if (ipcp_s) { free(ipcp_s); } return -1; } } /* Start the enrollment procedure as slave. */ rib->neighbors.push_back(Neighbor(rib, neigh_name, neigh_fd, neigh_port_id)); return 0; } extern "C" int rib_msg_rcvd(struct uipcp_rib *rib, struct rina_mgmt_hdr *mhdr, char *serbuf, int serlen) { list<Neighbor>::iterator neigh; CDAPMessage *m; /* Lookup neighbor by port id. */ neigh = rib->lookup_neigh_by_port_id(mhdr->local_port); if (neigh == rib->neighbors.end()) { PE("%s: Received message from unknown port id %d\n", __func__, mhdr->local_port); return -1; } /* Deserialize the received CDAP message. */ m = neigh->conn->msg_deser(serbuf, serlen); if (!m) { PE("%s: msg_deser() failed\n", __func__); return -1; } /* Feed the enrollment state machine. */ return neigh->fsm_run(m); } extern "C" int rib_application_register(struct uipcp_rib *rib, int reg, const struct rina_name *appl_name) { char *name_s = rina_name_to_string(appl_name); map< string, uint64_t >::iterator mit; struct uipcp *uipcp = rib->uipcp; uint64_t local_addr; string name_str; int ret; bool create = true; ret = rinalite_lookup_ipcp_addr_by_id(&uipcp->appl.loop, uipcp->ipcp_id, &local_addr); assert(!ret); if (!name_s) { PE("%s: Out of memory\n", __func__); return -1; } name_str = name_s; free(name_s); mit = rib->dft.find(name_str); if (reg) { if (mit != rib->dft.end()) { PE("%s: Application %s already registered on uipcp with address " "[%llu], my address being [%llu]\n", __func__, name_str.c_str(), (long long unsigned)mit->second, (long long unsigned)local_addr); return -1; } /* Insert the object into the RIB. */ rib->dft.insert(make_pair(name_str, local_addr)); } else { if (mit == rib->dft.end()) { PE("%s: Application %s was not registered here\n", __func__, name_str.c_str()); return -1; } /* Remove the object from the RIB. */ rib->dft.erase(mit); create = false; } rib_remote_sync(rib, create, obj_class::dft, obj_name::dft, 10329); PD("%s: Application %s %sregistered %s uipcp %d\n", __func__, name_str.c_str(), reg ? "" : "un", reg ? "to" : "from", uipcp->ipcp_id); return 0; } <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2019 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/HDF5.hpp> #include <DO/Sara/FeatureMatching.hpp> #include <DO/Sara/FileSystem.hpp> #include <DO/Sara/Graphics.hpp> #include <DO/Sara/ImageIO.hpp> #include <DO/Sara/ImageProcessing.hpp> #include <DO/Sara/Match.hpp> #include <DO/Sara/MultiViewGeometry.hpp> #include <DO/Sara/SfM/Detectors/SIFT.hpp> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; namespace sara = DO::Sara; using namespace std; namespace DO::Sara { auto read_internal_camera_parameters(const std::string& filepath) -> Matrix3d { std::ifstream file{filepath}; if (!file) throw std::runtime_error{"File " + filepath + "does not exist!"}; Matrix3d K; file >> K; return K; } auto match(const KeypointList<OERegion, float>& keys1, const KeypointList<OERegion, float>& keys2) -> std::vector<Match> { AnnMatcher matcher{keys1, keys2, 0.6f}; return matcher.compute_matches(); } auto estimate_fundamental_matrix(const std::vector<Match>& Mij, const KeypointList<OERegion, float>& ki, const KeypointList<OERegion, float>& kj, int num_samples, double err_thres) { const auto to_double = [](const float& src) { return double(src); }; const auto& fi = features(ki); const auto& fj = features(kj); const auto pi = extract_centers(fi).cwise_transform(to_double); const auto pj = extract_centers(fj).cwise_transform(to_double); const auto Pi = homogeneous(pi); const auto Pj = homogeneous(pj); const auto Mij_tensor = to_tensor(Mij); auto estimator = EightPointAlgorithm{}; auto distance = EpipolarDistance{}; const auto [F, num_inliers, sample_best] = ransac(Mij_tensor, Pi, Pj, estimator, distance, num_samples, err_thres); SARA_CHECK(F); SARA_CHECK(num_inliers); SARA_CHECK(Mij.size()); return std::make_tuple(F, num_inliers, sample_best); } auto estimate_essential_matrix(const std::vector<Match>& Mij, const KeypointList<OERegion, float>& ki, const KeypointList<OERegion, float>& kj, const Matrix3d& Ki_inv, const Matrix3d& Kj_inv, int num_samples, double err_thres) { const auto to_double = [](const float& src) { return double(src); }; const auto& fi = features(ki); const auto& fj = features(kj); const auto pi = extract_centers(fi).cwise_transform(to_double); const auto pj = extract_centers(fj).cwise_transform(to_double); const auto Pi = apply_transform(Ki_inv, homogeneous(pi)); const auto Pj = apply_transform(Kj_inv, homogeneous(pj)); const auto Mij_tensor = to_tensor(Mij); auto estimator = NisterFivePointAlgorithm{}; auto distance = EpipolarDistance{}; const auto [E, num_inliers, sample_best] = ransac(Mij_tensor, Pi, Pj, estimator, distance, num_samples, err_thres); SARA_CHECK(E); SARA_CHECK(num_inliers); SARA_CHECK(Mij.size()); return std::make_tuple(E, num_inliers, sample_best); } auto check_epipolar_constraints(const Image<Rgb8>& Ii, const Image<Rgb8>& Ij, const FundamentalMatrix& F, const vector<Match>& Mij, const Tensor_<int, 1>& sample_best, double err_thres, int display_step) { const auto scale = 0.25f; const auto w = int((Ii.width() + Ij.width()) * scale + 0.5f); const auto h = int(max(Ii.height(), Ij.height()) * scale + 0.5f); const auto off = sara::Point2f{float(Ii.width()), 0.f}; if (!sara::active_window()) { sara::create_window(w, h); sara::set_antialiasing(); } if (sara::get_sizes(sara::active_window()) != Eigen::Vector2i(w, h)) sara::resize_window(w, h); PairWiseDrawer drawer(Ii, Ij); drawer.set_viz_params(scale, scale, PairWiseDrawer::CatH); drawer.display_images(); auto distance = EpipolarDistance{F.matrix()}; for (size_t m = 0; m < Mij.size(); ++m) { const Vector3d X1 = Mij[m].x_pos().cast<double>().homogeneous(); const Vector3d X2 = Mij[m].y_pos().cast<double>().homogeneous(); if (distance(X1, X2) > err_thres) continue; if (m % display_step == 0) { drawer.draw_match(Mij[m], Blue8, false); const auto proj_X1 = F.right_epipolar_line(X1); const auto proj_X2 = F.left_epipolar_line(X2); drawer.draw_line_from_eqn(0, proj_X2.cast<float>(), Cyan8, 1); drawer.draw_line_from_eqn(1, proj_X1.cast<float>(), Cyan8, 1); } } for (size_t m = 0; m < sample_best.size(); ++m) { // Draw the best elemental subset drawn by RANSAC. drawer.draw_match(Mij[sample_best(m)], Red8, true); const Vector3d X1 = Mij[sample_best(m)].x_pos().cast<double>().homogeneous(); const Vector3d X2 = Mij[sample_best(m)].y_pos().cast<double>().homogeneous(); const auto proj_X1 = F.right_epipolar_line(X1); const auto proj_X2 = F.left_epipolar_line(X2); // Draw the corresponding epipolar lines. drawer.draw_line_from_eqn(1, proj_X1.cast<float>(), Magenta8, 1); drawer.draw_line_from_eqn(0, proj_X2.cast<float>(), Magenta8, 1); } //get_key(); } struct IndexMatch { int i; int j; float score; }; struct EpipolarEdge { int i; // left int j; // right Matrix3d m; }; template <> struct CalculateH5Type<IndexMatch> { static inline auto value() -> H5::CompType { auto h5_comp_type = H5::CompType{sizeof(IndexMatch)}; INSERT_MEMBER(h5_comp_type, IndexMatch, i); INSERT_MEMBER(h5_comp_type, IndexMatch, j); INSERT_MEMBER(h5_comp_type, IndexMatch, score); return h5_comp_type; } }; template <> struct CalculateH5Type<EpipolarEdge> { static inline auto value() -> H5::CompType { auto h5_comp_type = H5::CompType{sizeof(EpipolarEdge)}; INSERT_MEMBER(h5_comp_type, EpipolarEdge, i); INSERT_MEMBER(h5_comp_type, EpipolarEdge, j); INSERT_MEMBER(h5_comp_type, EpipolarEdge, m); return h5_comp_type; } }; KeypointList<OERegion, float> read_keypoints(H5File& h5_file, const std::string& group_name) { auto features = std::vector<sara::OERegion>{}; auto descriptors = sara::Tensor_<float, 2>{}; SARA_DEBUG << "Read features..." << std::endl; h5_file.read_dataset(group_name + "/" + "features", features); SARA_DEBUG << "Read descriptors..." << std::endl; h5_file.read_dataset(group_name + "/" + "descriptors", descriptors); return {features, descriptors}; } auto read_matches(H5File& file, const std::string& name) { auto matches = std::vector<IndexMatch>{}; file.read_dataset(name, matches); return matches; } } // namespace DO::Sara GRAPHICS_MAIN() { const auto dataset = std::string{"castle_int"}; //const auto dataset = std::string{"herzjesu_int"}; #if defined(__APPLE__) const auto dirpath = fs::path{"/Users/david/Desktop/Datasets/sfm/" + dataset}; auto h5_file = sara::H5File{ "/Users/david/Desktop/Datasets/sfm/" + dataset + ".h5", H5F_ACC_RDWR}; #else const auto dirpath = fs::path{"/home/david/Desktop/Datasets/sfm/" + dataset}; auto h5_file = sara::H5File{ "/home/david/Desktop/Datasets/sfm/" + dataset + ".h5", H5F_ACC_RDWR}; #endif auto image_paths = sara::ls(dirpath.string(), ".png"); std::sort(image_paths.begin(), image_paths.end()); const auto N = int(image_paths.size()); for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { // Specify the image pair to process. const auto& fi = image_paths[i]; const auto& fj = image_paths[j]; const auto gi = sara::basename(fi); const auto gj = sara::basename(fj); SARA_DEBUG << gi << std::endl; SARA_DEBUG << gj << std::endl; const auto Ii = sara::imread<sara::Rgb8>(fi); const auto Ij = sara::imread<sara::Rgb8>(fj); const auto Ki = sara::read_internal_camera_parameters( dirpath.string() + "/" + gi + ".png.K"); const auto Kj = sara::read_internal_camera_parameters( dirpath.string() + "/" + gj + ".png.K"); const Eigen::Matrix3d Ki_inv = Ki.inverse(); const Eigen::Matrix3d Kj_inv = Kj.inverse(); // Load the keypoints. const auto ki = sara::read_keypoints(h5_file, gi); const auto kj = sara::read_keypoints(h5_file, gj); //const auto ki = sara::compute_sift_keypoints(Ii.convert<float>()); //const auto kj = sara::compute_sift_keypoints(Ij.convert<float>()); // Match keypoints. const auto Mij = match(ki, kj); //// Save the keypoints to HDF5 //auto Mij2 = std::vector<sara::IndexMatch>{}; //std::transform( // Mij.begin(), Mij.end(), std::back_inserter(Mij2), [](const auto& m) { // return sara::IndexMatch{m.x_index(), m.y_index(), m.score()}; // }); //const auto group_name = std::string{"matches"}; //h5_file.group(group_name); //const auto match_dataset = // group_name + "/" + std::to_string(i) + "_" + std::to_string(j); //h5_file.write_dataset(match_dataset, tensor_view(Mij2)); const auto num_samples = 1000; const auto err_thres = 5e-3; // Estimate the fundamental matrix. const auto [F, num_inliers, sample_best] = sara::estimate_fundamental_matrix(Mij, ki, kj, num_samples, err_thres); //const auto [E, num_inliers_e, sample_best_e] = // sara::estimate_essential_matrix(Mij, ki, kj, Ki_inv, Kj_inv, // num_samples, err_thres); //auto F1 = sara::FundamentalMatrix{}; //F1.matrix() = Kj_inv.transpose() * E.matrix() * Ki_inv; // Visualize the estimated fundamental matrix. const int display_step = 20; sara::check_epipolar_constraints(Ii, Ij, F, Mij, sample_best, err_thres, display_step); //sara::check_epipolar_constraints(Ii, Ij, F1, Mij, sample_best_e, // err_thres, display_step); } } return 0; } <commit_msg>ENH: add program options.<commit_after>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2019 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/HDF5.hpp> #include <DO/Sara/FeatureMatching.hpp> #include <DO/Sara/FileSystem.hpp> #include <DO/Sara/Graphics.hpp> #include <DO/Sara/ImageIO.hpp> #include <DO/Sara/Match.hpp> #include <DO/Sara/MultiViewGeometry.hpp> #include <DO/Sara/SfM/Detectors/SIFT.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; namespace fs = boost::filesystem; namespace sara = DO::Sara; using namespace std; namespace DO::Sara { auto read_internal_camera_parameters(const std::string& filepath) -> Matrix3d { std::ifstream file{filepath}; if (!file) throw std::runtime_error{"File " + filepath + "does not exist!"}; Matrix3d K; file >> K; return K; } auto match(const KeypointList<OERegion, float>& keys1, const KeypointList<OERegion, float>& keys2) -> std::vector<Match> { AnnMatcher matcher{keys1, keys2, 0.6f}; return matcher.compute_matches(); } auto estimate_fundamental_matrix(const std::vector<Match>& Mij, const KeypointList<OERegion, float>& ki, const KeypointList<OERegion, float>& kj, int num_samples, double err_thres) { const auto to_double = [](const float& src) { return double(src); }; const auto& fi = features(ki); const auto& fj = features(kj); const auto pi = extract_centers(fi).cwise_transform(to_double); const auto pj = extract_centers(fj).cwise_transform(to_double); const auto Pi = homogeneous(pi); const auto Pj = homogeneous(pj); const auto Mij_tensor = to_tensor(Mij); auto estimator = EightPointAlgorithm{}; auto distance = EpipolarDistance{}; const auto [F, num_inliers, sample_best] = ransac(Mij_tensor, Pi, Pj, estimator, distance, num_samples, err_thres); SARA_CHECK(F); SARA_CHECK(num_inliers); SARA_CHECK(Mij.size()); return std::make_tuple(F, num_inliers, sample_best); } auto estimate_essential_matrix(const std::vector<Match>& Mij, const KeypointList<OERegion, float>& ki, const KeypointList<OERegion, float>& kj, const Matrix3d& Ki_inv, const Matrix3d& Kj_inv, int num_samples, double err_thres) { const auto to_double = [](const float& src) { return double(src); }; const auto& fi = features(ki); const auto& fj = features(kj); const auto pi = extract_centers(fi).cwise_transform(to_double); const auto pj = extract_centers(fj).cwise_transform(to_double); const auto Pi = apply_transform(Ki_inv, homogeneous(pi)); const auto Pj = apply_transform(Kj_inv, homogeneous(pj)); const auto Mij_tensor = to_tensor(Mij); auto estimator = NisterFivePointAlgorithm{}; auto distance = EpipolarDistance{}; const auto [E, num_inliers, sample_best] = ransac(Mij_tensor, Pi, Pj, estimator, distance, num_samples, err_thres); SARA_CHECK(E); SARA_CHECK(num_inliers); SARA_CHECK(Mij.size()); return std::make_tuple(E, num_inliers, sample_best); } auto check_epipolar_constraints(const Image<Rgb8>& Ii, const Image<Rgb8>& Ij, const FundamentalMatrix& F, const vector<Match>& Mij, const Tensor_<int, 1>& sample_best, double err_thres, int display_step) { const auto scale = 0.25f; const auto w = int((Ii.width() + Ij.width()) * scale + 0.5f); const auto h = int(max(Ii.height(), Ij.height()) * scale + 0.5f); const auto off = sara::Point2f{float(Ii.width()), 0.f}; if (!sara::active_window()) { sara::create_window(w, h); sara::set_antialiasing(); } if (sara::get_sizes(sara::active_window()) != Eigen::Vector2i(w, h)) sara::resize_window(w, h); PairWiseDrawer drawer(Ii, Ij); drawer.set_viz_params(scale, scale, PairWiseDrawer::CatH); drawer.display_images(); auto distance = EpipolarDistance{F.matrix()}; for (size_t m = 0; m < Mij.size(); ++m) { const Vector3d X1 = Mij[m].x_pos().cast<double>().homogeneous(); const Vector3d X2 = Mij[m].y_pos().cast<double>().homogeneous(); if (distance(X1, X2) > err_thres) continue; if (m % display_step == 0) { drawer.draw_match(Mij[m], Blue8, false); const auto proj_X1 = F.right_epipolar_line(X1); const auto proj_X2 = F.left_epipolar_line(X2); drawer.draw_line_from_eqn(0, proj_X2.cast<float>(), Cyan8, 1); drawer.draw_line_from_eqn(1, proj_X1.cast<float>(), Cyan8, 1); } } for (size_t m = 0; m < sample_best.size(); ++m) { // Draw the best elemental subset drawn by RANSAC. drawer.draw_match(Mij[sample_best(m)], Red8, true); const Vector3d X1 = Mij[sample_best(m)].x_pos().cast<double>().homogeneous(); const Vector3d X2 = Mij[sample_best(m)].y_pos().cast<double>().homogeneous(); const auto proj_X1 = F.right_epipolar_line(X1); const auto proj_X2 = F.left_epipolar_line(X2); // Draw the corresponding epipolar lines. drawer.draw_line_from_eqn(1, proj_X1.cast<float>(), Magenta8, 1); drawer.draw_line_from_eqn(0, proj_X2.cast<float>(), Magenta8, 1); } //get_key(); } struct IndexMatch { int i; int j; float score; }; struct EpipolarEdge { int i; // left int j; // right Matrix3d m; }; template <> struct CalculateH5Type<IndexMatch> { static inline auto value() -> H5::CompType { auto h5_comp_type = H5::CompType{sizeof(IndexMatch)}; INSERT_MEMBER(h5_comp_type, IndexMatch, i); INSERT_MEMBER(h5_comp_type, IndexMatch, j); INSERT_MEMBER(h5_comp_type, IndexMatch, score); return h5_comp_type; } }; template <> struct CalculateH5Type<EpipolarEdge> { static inline auto value() -> H5::CompType { auto h5_comp_type = H5::CompType{sizeof(EpipolarEdge)}; INSERT_MEMBER(h5_comp_type, EpipolarEdge, i); INSERT_MEMBER(h5_comp_type, EpipolarEdge, j); INSERT_MEMBER(h5_comp_type, EpipolarEdge, m); return h5_comp_type; } }; KeypointList<OERegion, float> read_keypoints(H5File& h5_file, const std::string& group_name) { auto features = std::vector<sara::OERegion>{}; auto descriptors = sara::Tensor_<float, 2>{}; SARA_DEBUG << "Read features..." << std::endl; h5_file.read_dataset(group_name + "/" + "features", features); SARA_DEBUG << "Read descriptors..." << std::endl; h5_file.read_dataset(group_name + "/" + "descriptors", descriptors); return {features, descriptors}; } auto read_matches(H5File& file, const std::string& name) { auto matches = std::vector<IndexMatch>{}; file.read_dataset(name, matches); return matches; } } // namespace DO::Sara void match_keypoints(const std::string& dirpath, const std::string& h5_filepath) { // Create a backup. if (!fs::exists(h5_filepath + ".bak")) sara::cp(h5_filepath, h5_filepath + ".bak"); auto h5_file = sara::H5File{h5_filepath, H5F_ACC_RDWR}; auto image_paths = std::vector<std::string>{}; append(image_paths, sara::ls(dirpath, ".png")); append(image_paths, sara::ls(dirpath, ".jpg")); std::sort(image_paths.begin(), image_paths.end()); const auto N = int(image_paths.size()); for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { // Specify the image pair to process. const auto& fi = image_paths[i]; const auto& fj = image_paths[j]; const auto gi = sara::basename(fi); const auto gj = sara::basename(fj); SARA_DEBUG << gi << std::endl; SARA_DEBUG << gj << std::endl; const auto Ii = sara::imread<sara::Rgb8>(fi); const auto Ij = sara::imread<sara::Rgb8>(fj); const auto Ki = sara::read_internal_camera_parameters(dirpath + "/" + gi + ".png.K"); const auto Kj = sara::read_internal_camera_parameters(dirpath + "/" + gj + ".png.K"); const Eigen::Matrix3d Ki_inv = Ki.inverse(); const Eigen::Matrix3d Kj_inv = Kj.inverse(); // Load the keypoints. const auto ki = sara::read_keypoints(h5_file, gi); const auto kj = sara::read_keypoints(h5_file, gj); // Match keypoints. const auto Mij = match(ki, kj); // Save the keypoints to HDF5 auto Mij2 = std::vector<sara::IndexMatch>{}; std::transform( Mij.begin(), Mij.end(), std::back_inserter(Mij2), [](const auto& m) { return sara::IndexMatch{m.x_index(), m.y_index(), m.score()}; }); const auto group_name = std::string{"matches"}; h5_file.group(group_name); const auto match_dataset = group_name + "/" + std::to_string(i) + "_" + std::to_string(j); h5_file.write_dataset(match_dataset, tensor_view(Mij2)); const auto num_samples = 1000; const auto err_thres = 5e-3; //// Estimate the fundamental matrix. //const auto [F, num_inliers, sample_best] = // sara::estimate_fundamental_matrix(Mij, ki, kj, num_samples, // err_thres); const auto [E, num_inliers_e, sample_best_e] = sara::estimate_essential_matrix(Mij, ki, kj, Ki_inv, Kj_inv, num_samples, err_thres); auto F1 = sara::FundamentalMatrix{}; F1.matrix() = Kj_inv.transpose() * E.matrix() * Ki_inv; // Visualize the estimated fundamental matrix. const int display_step = 20; //sara::check_epipolar_constraints(Ii, Ij, F, Mij, sample_best, err_thres, // display_step); sara::check_epipolar_constraints(Ii, Ij, F1, Mij, sample_best_e, err_thres, display_step); } } } int __main(int argc, char **argv) { try { po::options_description desc{"Detect SIFT keypoints"}; desc.add_options() // ("help, h", "Help screen") // ("dirpath", po::value<std::string>(), "Image directory path") // ("out_h5_file", po::value<std::string>(), "Output HDF5 file") // ("read", "Visualize detected keypoints") // ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 0; } if (!vm.count("dirpath")) { std::cout << "Missing image directory path" << std::endl; return 0; } if (!vm.count("out_h5_file")) { std::cout << desc << std::endl; std::cout << "Missing output H5 file path" << std::endl; return 0; } const auto dirpath = vm["dirpath"].as<std::string>(); const auto h5_filepath = vm["out_h5_file"].as<std::string>(); match_keypoints(dirpath, h5_filepath); return 0; } catch (const po::error& e) { std::cerr << e.what() << "\n"; return 1; } } int main(int argc, char** argv) { DO::Sara::GraphicsApplication app(argc, argv); app.register_user_main(__main); return app.exec(); } <|endoftext|>
<commit_before>#include <unistd.h> #include <stdio.h> #include <stdint.h> #include <iohub_client.h> #include <mug.h> #include <res_manager.h> #ifndef USE_IOHUB #include <io.h> #endif struct __attribute__((packed)) led_line_data { uint8_t row; uint8_t reserved[2]; uint8_t content[MAX_COLS/2]; }; error_t mug_disp_raw(handle_t handle, char* imgData) { int row, col; char *p = imgData; error_t err = ERROR_NONE; struct led_line_data data = { 0, {0xff, 0xff}, {0} }; for(row = 0; row < MAX_COMPRESSED_ROWS; row++) { // pack the data data.row = row; memcpy(&(data.content), p, MAX_COMPRESSED_COLS); // send to iohub #ifdef USE_IOHUB err = iohub_send_command(handle, IOHUB_CMD_FB, (char*)&data, sizeof(data)); #else err = dev_send_command(handle, IOHUB_CMD_FB, (char*)&data, sizeof(data)); #endif if(err != ERROR_NONE) { MUG_ASSERT(0, "iohub_send_command error: %d\n", err); return err; } // go to the next row p += MAX_COMPRESSED_COLS; } return err; } error_t mug_disp_raw_N(handle_t handle, char* imgData, int number, int interval) { int semResource = resource_init(RESOURCE_DISPLAY_TOUCH); char *p = imgData; error_t error = ERROR_NONE; int i; resource_wait(semResource); for(i = 0; i < number; i++) { error = mug_disp_raw(handle, p); if(error != ERROR_NONE) { printf("C program, disp page error!\n"); fflush(NULL); resource_post(semResource); return error; } p += COMPRESSED_SIZE; usleep(interval * 1000); } resource_post(semResource); return error; } handle_t mug_init(device_t type) { #ifdef USE_IOHUB handle_t handle = iohub_open_session(type); #else handle_t handle = dev_open(type); #endif return handle; } void mug_close(handle_t handle) { #ifdef USE_IOHUB iohub_close_session(handle); #else dev_close(handle); #endif } handle_t mug_disp_init() { return mug_init(DEVICE_LED); } <commit_msg>Fix bug<commit_after>#include <unistd.h> #include <stdio.h> #include <stdint.h> #include <iohub_client.h> #include <mug.h> #include <res_manager.h> #ifndef USE_IOHUB #include <io.h> #endif struct __attribute__((packed)) led_line_data { uint8_t row; uint8_t reserved[2]; uint8_t content[MAX_COLS/2]; }; error_t mug_disp_raw(handle_t handle, char* imgData) { int row, col; char *p = imgData; error_t err = ERROR_NONE; struct led_line_data data = { 0, {0xff, 0xff}, {0} }; for(row = 0; row < MAX_COMPRESSED_ROWS; row++) { // pack the data data.row = row; memcpy(&(data.content), p, MAX_COMPRESSED_COLS); // send to iohub #ifdef USE_IOHUB err = iohub_send_command(handle, IOHUB_CMD_FB, (char*)&data, sizeof(data)); #else err = dev_send_command(handle, IOHUB_CMD_FB, (char*)&data, sizeof(data)); #endif if(err != ERROR_NONE) { MUG_ASSERT(0, "iohub_send_command error: %d\n", err); return err; } // go to the next row p += MAX_COMPRESSED_COLS; } return err; } error_t mug_disp_raw_N(handle_t handle, char* imgData, int number, int interval) { int semResource = resource_init(LOCK_DISPLAY_TOUCH); char *p = imgData; error_t error = ERROR_NONE; int i; resource_wait(semResource); for(i = 0; i < number; i++) { error = mug_disp_raw(handle, p); if(error != ERROR_NONE) { printf("C program, disp page error!\n"); fflush(NULL); resource_post(semResource); return error; } p += COMPRESSED_SIZE; usleep(interval * 1000); } resource_post(semResource); return error; } handle_t mug_init(device_t type) { #ifdef USE_IOHUB handle_t handle = iohub_open_session(type); #else handle_t handle = dev_open(type); #endif return handle; } void mug_close(handle_t handle) { #ifdef USE_IOHUB iohub_close_session(handle); #else dev_close(handle); #endif } handle_t mug_disp_init() { return mug_init(DEVICE_LED); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: LinExtrd.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "LinExtrd.hh" // Description: // Create object with normal extrusion type, capping on, scale factor=1.0, // vector (0,0,1), and point (0,0,0). vlLinearExtrusionFilter::vlLinearExtrusionFilter() { this->ExtrusionType = NORMAL_EXTRUSION; this->Capping = 1; this->ScaleFactor = 1.0; this->Vector[0] = this->Vector[1] = 0.0; this->Vector[2] = 1.0; this->Point[0] = this->Point[1] = this->Point[2] = 0.0; } float *vlLinearExtrusionFilter::ViaNormal(float x[3], int id, vlNormals *n) { static float xNew[3], *normal; int i; normal = n->GetNormal(id); for (i=0; i<3; i++) xNew[i] = x[i] + this->ScaleFactor*normal[i]; return xNew; } float *vlLinearExtrusionFilter::ViaVector(float x[3], int id, vlNormals *n) { static float xNew[3]; int i; for (i=0; i<3; i++) xNew[i] = x[i] + this->ScaleFactor*this->Vector[i]; return xNew; } float *vlLinearExtrusionFilter::ViaPoint(float x[3], int id, vlNormals *n) { static float xNew[3]; int i; for (i=0; i<3; i++) xNew[i] = x[i] + this->ScaleFactor*(x[i] - this->Point[i]); return xNew; } void vlLinearExtrusionFilter::Execute() { int numPts, numCells; vlPolyData *input=(vlPolyData *)this->Input; vlPointData *pd=input->GetPointData(); vlNormals *inNormals; vlPolyData mesh; vlPoints *inPts; vlCellArray *inVerts, *inLines, *inPolys, *inStrips; int npts, *pts, numEdges, cellId, dim; int ptId, ncells, ptIds[MAX_CELL_SIZE], i, j, k, p1, p2; float *x; vlFloatPoints *newPts; vlCellArray *newLines=NULL, *newPolys=NULL, *newStrips=NULL; vlCell *cell, *edge; vlIdList cellIds(MAX_CELL_SIZE), *cellPts; // // Initialize / check input // vlDebugMacro(<<"Linearly extruding data"); this->Initialize(); if ( (numPts=input->GetNumberOfPoints()) < 1 || (numCells=input->GetNumberOfCells()) < 1 ) { vlErrorMacro(<<"No data to extrude!"); return; } // // Decide which vector to use for extrusion // if ( this->ExtrusionType == POINT_EXTRUSION ) { this->ExtrudePoint = &vlLinearExtrusionFilter::ViaPoint; } else if ( this->ExtrusionType == NORMAL_EXTRUSION && (inNormals = pd->GetNormals()) != NULL ) { this->ExtrudePoint = &vlLinearExtrusionFilter::ViaNormal; inNormals = pd->GetNormals(); } else // Vector_EXTRUSION { this->ExtrudePoint = &vlLinearExtrusionFilter::ViaVector; } // // Build cell data structure. // inPts = input->GetPoints(); inVerts = input->GetVerts(); inLines = input->GetLines(); inPolys = input->GetPolys(); inStrips = input->GetStrips(); mesh.SetPoints(inPts); mesh.SetVerts(inVerts); mesh.SetLines(inLines); mesh.SetPolys(inPolys); mesh.SetStrips(inStrips); if ( inPolys || inStrips ) mesh.BuildLinks(); // // Allocate memory for output. We don't copy normals because surface geometry // is modified. Copy all points - this is the usual requirement and it makes // creation of skirt much easier. // this->PointData.CopyNormalsOff(); this->PointData.CopyAllocate(pd,2*numPts); newPts = new vlFloatPoints(2*numPts); if ( (ncells=inVerts->GetNumberOfCells()) > 0 ) { newLines = new vlCellArray; newLines->Allocate(newLines->EstimateSize(ncells,2)); } // arbitrary initial allocation size ncells = inLines->GetNumberOfCells() + inPolys->GetNumberOfCells()/10 + inStrips->GetNumberOfCells()/10; ncells = (ncells < 100 ? 100 : ncells); newStrips = new vlCellArray; newStrips->Allocate(newStrips->EstimateSize(ncells,4)); // copy points for (ptId=0; ptId < numPts; ptId++) { x = inPts->GetPoint(ptId); newPts->SetPoint(ptId,x); newPts->SetPoint(ptId+numPts,(this->*(ExtrudePoint))(x,ptId,inNormals)); this->PointData.CopyData(pd,ptId,ptId); this->PointData.CopyData(pd,ptId,ptId+numPts); } // // If capping is on, copy 2D cells to output (plus create cap) // if ( this->Capping ) { if ( inPolys->GetNumberOfCells() > 0 ) { newPolys = new vlCellArray(inPolys->GetSize()); for ( inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); ) { newPolys->InsertNextCell(npts,pts); newPolys->InsertNextCell(npts); for (i=0; i < npts; i++) newPolys->InsertCellPoint(pts[i] + numPts); } } if ( inStrips->GetNumberOfCells() > 0 ) { for ( inStrips->InitTraversal(); inStrips->GetNextCell(npts,pts); ) { newStrips->InsertNextCell(npts,pts); newStrips->InsertNextCell(npts); for (i=0; i < npts; i++) newStrips->InsertCellPoint(pts[i] + numPts); } } } // // Loop over all polygons and triangle strips searching for boundary edges. // If boundary edge found, extrude triangle strip. // for ( cellId=0; cellId < numCells; cellId++) { cell = mesh.GetCell(cellId); cellPts = cell->GetPointIds(); if ( (dim=cell->GetCellDimension()) == 0 ) //create lines from points { for (i=0; i<cellPts->GetNumberOfIds(); i++) { newLines->InsertNextCell(2); ptId = cellPts->GetId(i); newLines->InsertCellPoint(ptId); newLines->InsertCellPoint(ptId+numPts); } } else if ( dim == 1 ) // create strips from lines { for (i=0; i < (cellPts->GetNumberOfIds()-1); i++) { p1 = cellPts->GetId(i); p2 = cellPts->GetId(i+1); newStrips->InsertNextCell(4); newStrips->InsertCellPoint(p1); newStrips->InsertCellPoint(p2); newStrips->InsertCellPoint(p1+numPts); newStrips->InsertCellPoint(p2+numPts); } } else if ( dim == 2 ) // create strips from boundary edges { numEdges = cell->GetNumberOfEdges(); for (i=0; i<numEdges; i++) { edge = cell->GetEdge(i); for (j=0; j<(edge->GetNumberOfPoints()-1); j++) { p1 = pts[j]; p2 = pts[(j+1)%npts]; mesh.GetCellEdgeNeighbors(cellId, p1, p2, cellIds); if ( cellIds.GetNumberOfIds() < 1 ) //generate strip { newStrips->InsertNextCell(4); newStrips->InsertCellPoint(p1); newStrips->InsertCellPoint(p2); newStrips->InsertCellPoint(p1+numPts); newStrips->InsertCellPoint(p2+numPts); } } //for each sub-edge } //for each edge } //for each polygon or triangle strip } //for each cell // // Send data to output // this->SetPoints(newPts); if ( newLines ) this->SetLines(newLines); if ( newPolys ) this->SetPolys(newLines); this->SetStrips(newStrips); this->Squeeze(); } void vlLinearExtrusionFilter::PrintSelf(ostream& os, vlIndent indent) { vlPolyToPolyFilter::PrintSelf(os,indent); if ( this->ExtrusionType == VECTOR_EXTRUSION ) { os << indent << "Extrusion Type: Extrude along vector\n"; os << indent << "Vector: (" << this->Vector[0] << ", " << this->Vector[1] << ", " << this->Vector[2] << ")\n"; } else if ( this->ExtrusionType == NORMAL_EXTRUSION ) { os << indent << "Extrusion Type: Extrude along vertex normals\n"; } else //POINT_EXTRUSION { os << indent << "Extrusion Type: Extrude towards point\n"; os << indent << "Point: (" << this->Point[0] << ", " << this->Point[1] << ", " << this->Point[2] << ")\n"; } os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n"); os << indent << "Scale Factor: " << this->ScaleFactor << "\n"; } <commit_msg>ERR: Fixed bug with polygon generation.<commit_after>/*========================================================================= Program: Visualization Library Module: LinExtrd.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "LinExtrd.hh" // Description: // Create object with normal extrusion type, capping on, scale factor=1.0, // vector (0,0,1), and point (0,0,0). vlLinearExtrusionFilter::vlLinearExtrusionFilter() { this->ExtrusionType = NORMAL_EXTRUSION; this->Capping = 1; this->ScaleFactor = 1.0; this->Vector[0] = this->Vector[1] = 0.0; this->Vector[2] = 1.0; this->Point[0] = this->Point[1] = this->Point[2] = 0.0; } float *vlLinearExtrusionFilter::ViaNormal(float x[3], int id, vlNormals *n) { static float xNew[3], *normal; int i; normal = n->GetNormal(id); for (i=0; i<3; i++) xNew[i] = x[i] + this->ScaleFactor*normal[i]; return xNew; } float *vlLinearExtrusionFilter::ViaVector(float x[3], int id, vlNormals *n) { static float xNew[3]; int i; for (i=0; i<3; i++) xNew[i] = x[i] + this->ScaleFactor*this->Vector[i]; return xNew; } float *vlLinearExtrusionFilter::ViaPoint(float x[3], int id, vlNormals *n) { static float xNew[3]; int i; for (i=0; i<3; i++) xNew[i] = x[i] + this->ScaleFactor*(x[i] - this->Point[i]); return xNew; } void vlLinearExtrusionFilter::Execute() { int numPts, numCells; vlPolyData *input=(vlPolyData *)this->Input; vlPointData *pd=input->GetPointData(); vlNormals *inNormals; vlPolyData mesh; vlPoints *inPts; vlCellArray *inVerts, *inLines, *inPolys, *inStrips; int npts, *pts, numEdges, cellId, dim; int ptId, ncells, ptIds[MAX_CELL_SIZE], i, j, k, p1, p2; float *x; vlFloatPoints *newPts; vlCellArray *newLines=NULL, *newPolys=NULL, *newStrips=NULL; vlCell *cell, *edge; vlIdList cellIds(MAX_CELL_SIZE), *cellPts; // // Initialize / check input // vlDebugMacro(<<"Linearly extruding data"); this->Initialize(); if ( (numPts=input->GetNumberOfPoints()) < 1 || (numCells=input->GetNumberOfCells()) < 1 ) { vlErrorMacro(<<"No data to extrude!"); return; } // // Decide which vector to use for extrusion // if ( this->ExtrusionType == POINT_EXTRUSION ) { this->ExtrudePoint = &vlLinearExtrusionFilter::ViaPoint; } else if ( this->ExtrusionType == NORMAL_EXTRUSION && (inNormals = pd->GetNormals()) != NULL ) { this->ExtrudePoint = &vlLinearExtrusionFilter::ViaNormal; inNormals = pd->GetNormals(); } else // Vector_EXTRUSION { this->ExtrudePoint = &vlLinearExtrusionFilter::ViaVector; } // // Build cell data structure. // inPts = input->GetPoints(); inVerts = input->GetVerts(); inLines = input->GetLines(); inPolys = input->GetPolys(); inStrips = input->GetStrips(); mesh.SetPoints(inPts); mesh.SetVerts(inVerts); mesh.SetLines(inLines); mesh.SetPolys(inPolys); mesh.SetStrips(inStrips); if ( inPolys || inStrips ) mesh.BuildLinks(); // // Allocate memory for output. We don't copy normals because surface geometry // is modified. Copy all points - this is the usual requirement and it makes // creation of skirt much easier. // this->PointData.CopyNormalsOff(); this->PointData.CopyAllocate(pd,2*numPts); newPts = new vlFloatPoints(2*numPts); if ( (ncells=inVerts->GetNumberOfCells()) > 0 ) { newLines = new vlCellArray; newLines->Allocate(newLines->EstimateSize(ncells,2)); } // arbitrary initial allocation size ncells = inLines->GetNumberOfCells() + inPolys->GetNumberOfCells()/10 + inStrips->GetNumberOfCells()/10; ncells = (ncells < 100 ? 100 : ncells); newStrips = new vlCellArray; newStrips->Allocate(newStrips->EstimateSize(ncells,4)); // copy points for (ptId=0; ptId < numPts; ptId++) { x = inPts->GetPoint(ptId); newPts->SetPoint(ptId,x); newPts->SetPoint(ptId+numPts,(this->*(ExtrudePoint))(x,ptId,inNormals)); this->PointData.CopyData(pd,ptId,ptId); this->PointData.CopyData(pd,ptId,ptId+numPts); } // // If capping is on, copy 2D cells to output (plus create cap) // if ( this->Capping ) { if ( inPolys->GetNumberOfCells() > 0 ) { newPolys = new vlCellArray(inPolys->GetSize()); for ( inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); ) { newPolys->InsertNextCell(npts,pts); newPolys->InsertNextCell(npts); for (i=0; i < npts; i++) newPolys->InsertCellPoint(pts[i] + numPts); } } if ( inStrips->GetNumberOfCells() > 0 ) { for ( inStrips->InitTraversal(); inStrips->GetNextCell(npts,pts); ) { newStrips->InsertNextCell(npts,pts); newStrips->InsertNextCell(npts); for (i=0; i < npts; i++) newStrips->InsertCellPoint(pts[i] + numPts); } } } // // Loop over all polygons and triangle strips searching for boundary edges. // If boundary edge found, extrude triangle strip. // for ( cellId=0; cellId < numCells; cellId++) { cell = mesh.GetCell(cellId); cellPts = cell->GetPointIds(); if ( (dim=cell->GetCellDimension()) == 0 ) //create lines from points { for (i=0; i<cellPts->GetNumberOfIds(); i++) { newLines->InsertNextCell(2); ptId = cellPts->GetId(i); newLines->InsertCellPoint(ptId); newLines->InsertCellPoint(ptId+numPts); } } else if ( dim == 1 ) // create strips from lines { for (i=0; i < (cellPts->GetNumberOfIds()-1); i++) { p1 = cellPts->GetId(i); p2 = cellPts->GetId(i+1); newStrips->InsertNextCell(4); newStrips->InsertCellPoint(p1); newStrips->InsertCellPoint(p2); newStrips->InsertCellPoint(p1+numPts); newStrips->InsertCellPoint(p2+numPts); } } else if ( dim == 2 ) // create strips from boundary edges { numEdges = cell->GetNumberOfEdges(); for (i=0; i<numEdges; i++) { edge = cell->GetEdge(i); for (j=0; j<(edge->GetNumberOfPoints()-1); j++) { p1 = edge->PointIds.GetId(j); p2 = edge->PointIds.GetId(j+1); mesh.GetCellEdgeNeighbors(cellId, p1, p2, cellIds); if ( cellIds.GetNumberOfIds() < 1 ) //generate strip { newStrips->InsertNextCell(4); newStrips->InsertCellPoint(p1); newStrips->InsertCellPoint(p2); newStrips->InsertCellPoint(p1+numPts); newStrips->InsertCellPoint(p2+numPts); } } //for each sub-edge } //for each edge } //for each polygon or triangle strip } //for each cell // // Send data to output // this->SetPoints(newPts); if ( newLines ) this->SetLines(newLines); if ( newPolys ) this->SetPolys(newLines); this->SetStrips(newStrips); this->Squeeze(); } void vlLinearExtrusionFilter::PrintSelf(ostream& os, vlIndent indent) { vlPolyToPolyFilter::PrintSelf(os,indent); if ( this->ExtrusionType == VECTOR_EXTRUSION ) { os << indent << "Extrusion Type: Extrude along vector\n"; os << indent << "Vector: (" << this->Vector[0] << ", " << this->Vector[1] << ", " << this->Vector[2] << ")\n"; } else if ( this->ExtrusionType == NORMAL_EXTRUSION ) { os << indent << "Extrusion Type: Extrude along vertex normals\n"; } else //POINT_EXTRUSION { os << indent << "Extrusion Type: Extrude towards point\n"; os << indent << "Point: (" << this->Point[0] << ", " << this->Point[1] << ", " << this->Point[2] << ")\n"; } os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n"); os << indent << "Scale Factor: " << this->ScaleFactor << "\n"; } <|endoftext|>
<commit_before>#include "gdrawer.hpp" #include <QThreadPool> #include <QRunnable> #include <QDebug> namespace { class Task : public QRunnable { private: QImage *img; QRectF rect; QRect viewport; Instrs *vm; QAtomicPointer<Exception>* e; public: Task(QImage* _img, const QRectF& _rect, const QRect& _viewport, Instrs *_vm, QAtomicPointer<Exception>* _e); void run(); }; } QImage drawFormula(const QString& formula, const QRectF& rect, const QSize& viewport) { Instrs vm = Instrs::get(formula); vm.dump(); int threads = QThread::idealThreadCount(); if (threads == -1) threads = 2; QImage ret(viewport, QImage::Format_Indexed8); qDebug() << "viewport: " << viewport; ret.setColor(0, qRgb(255, 255, 255)); ret.setColor(1, qRgb(0, 0, 0)); ret.setColor(2, qRgb(255, 255, 0)); ret.fill(2); QThreadPool pool; pool.setMaxThreadCount(threads); QRectF rect1(rect); rect1.setHeight(rect1.height() / threads); QRect viewport1(QPoint(0, 0), viewport); viewport1.setHeight(viewport1.height() / threads); QAtomicPointer<Exception> e; for (int i = 0; i < threads; ++i) { pool.start(new Task(&ret, rect1, viewport1, &vm, &e)); qDebug() << "Started pool" << rect1 << viewport1; rect1.moveTop(rect1.top() + rect1.height()); viewport1.moveTop(viewport1.top() + viewport1.height()); } pool.waitForDone(); if (Exception *e0 = e.load()) { Exception e1(*e0); delete e0; throw e1; } return ret; } Task::Task(QImage* _img, const QRectF& _rect, const QRect& _viewport, Instrs* _vm, QAtomicPointer<Exception>* _e): img(_img), rect(_rect), viewport(_viewport), vm(_vm), e(_e) { } void Task::run() { float_t dx = static_cast<float_t>(rect.width()) / viewport.width(), dy = static_cast<float_t>(rect.height()) / viewport.height(), y = rect.top(), x = 0; int pxEnd = viewport.right() + 1, pyEnd = viewport.bottom() + 1; Ctx ctx(vm->requiredStackSize); qDebug() << viewport.top() << pyEnd; for (int py = viewport.top(); py != pyEnd; ++py, y += dy) { x = rect.left(); uchar *line = img->scanLine(py); ctx.vars['y' - 'a'] = Real(y, y + dy); for (int px = 0; px != pxEnd; ++px, x += dx) { ctx.vars['x' - 'a'] = Real(x, x + dx); ctx.reset(); try { Real res = vm->execute(&ctx); line[px] = res.isZero(); } catch (Exception e0) { e0.append(QString("Point: (%1, %2)").arg(x).arg(y)); delete e->fetchAndStoreOrdered(new Exception(e0)); return; } } } } <commit_msg>Fixed inverted y-axis<commit_after>#include "gdrawer.hpp" #include <QThreadPool> #include <QRunnable> #include <QDebug> namespace { class Task : public QRunnable { private: QImage *img; QRectF rect; QRect viewport; Instrs *vm; QAtomicPointer<Exception>* e; public: Task(QImage* _img, const QRectF& _rect, const QRect& _viewport, Instrs *_vm, QAtomicPointer<Exception>* _e); void run(); }; } QImage drawFormula(const QString& formula, const QRectF& rect, const QSize& viewport) { Instrs vm = Instrs::get(formula); vm.dump(); int threads = QThread::idealThreadCount(); if (threads == -1) threads = 2; QImage ret(viewport, QImage::Format_Indexed8); qDebug() << "viewport: " << viewport; ret.setColor(0, qRgb(255, 255, 255)); ret.setColor(1, qRgb(0, 0, 0)); ret.setColor(2, qRgb(255, 255, 0)); ret.fill(2); QThreadPool pool; pool.setMaxThreadCount(threads); QRectF rect1(rect); rect1.setHeight(rect1.height() / threads); rect1.moveTop(rect1.top() + rect1.height() * (threads - 1)); QRect viewport1(QPoint(0, 0), viewport); viewport1.setHeight(viewport1.height() / threads); QAtomicPointer<Exception> e; for (int i = 0; i < threads; ++i) { pool.start(new Task(&ret, rect1, viewport1, &vm, &e)); qDebug() << "Started pool" << rect1 << viewport1; rect1.moveTop(rect1.top() - rect1.height()); viewport1.moveTop(viewport1.top() + viewport1.height()); } pool.waitForDone(); if (Exception *e0 = e.load()) { Exception e1(*e0); delete e0; throw e1; } return ret; } Task::Task(QImage* _img, const QRectF& _rect, const QRect& _viewport, Instrs* _vm, QAtomicPointer<Exception>* _e): img(_img), rect(_rect), viewport(_viewport), vm(_vm), e(_e) { } void Task::run() { float_t dx = static_cast<float_t>(rect.width()) / viewport.width(), dy = static_cast<float_t>(rect.height()) / viewport.height(), y = rect.bottom(), x = 0; int pxEnd = viewport.right() + 1, pyEnd = viewport.bottom() + 1; Ctx ctx(vm->requiredStackSize); qDebug() << viewport.top() << pyEnd; for (int py = viewport.top(); py != pyEnd; ++py, y -= dy) { x = rect.left(); uchar *line = img->scanLine(py); ctx.vars['y' - 'a'] = Real(y, y + dy); for (int px = 0; px != pxEnd; ++px, x += dx) { ctx.vars['x' - 'a'] = Real(x, x + dx); ctx.reset(); try { Real res = vm->execute(&ctx); line[px] = res.isZero(); } catch (Exception e0) { e0.append(QString("Point: (%1, %2)").arg(x).arg(y)); delete e->fetchAndStoreOrdered(new Exception(e0)); return; } } } } <|endoftext|>
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. 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. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3211 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3211 to 3212<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. 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. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3212 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>#include <string.h> #include <node.h> #include <node_buffer.h> #include <openssl/bn.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/ecdh.h> #include "eckey.h" using namespace v8; using namespace node; static Handle<Value> V8Exception(const char* msg) { HandleScope scope; return ThrowException(Exception::Error(String::New(msg))); } // Not sure where this came from. but looks like a function that should be part of openssl int static inline EC_KEY_regenerate_key(EC_KEY *eckey, const BIGNUM *priv_key) { if (!eckey) return 0; int ok = 0; BN_CTX *ctx = NULL; EC_POINT *pub_key = NULL; const EC_GROUP *group = EC_KEY_get0_group(eckey); if ((ctx = BN_CTX_new()) == NULL) goto err; pub_key = EC_POINT_new(group); if (pub_key == NULL) goto err; if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx)) goto err; EC_KEY_set_private_key(eckey, priv_key); EC_KEY_set_public_key(eckey, pub_key); ok = 1; err: if (pub_key) EC_POINT_free(pub_key); if (ctx != NULL) BN_CTX_free(ctx); return ok; } ECKey::ECKey(int curve) { mHasPrivateKey = false; mCurve = curve; mKey = EC_KEY_new_by_curve_name(mCurve); if (!mKey) { V8Exception("EC_KEY_new_by_curve_name Invalid curve?"); return; } } ECKey::~ECKey() { if (mKey) { EC_KEY_free(mKey); } } // Node module init void ECKey::Init(Handle<Object> exports) { Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("ECKey")); tpl->InstanceTemplate()->SetInternalFieldCount(1); //Accessors // tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("LastError"), GetLastError); tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("HasPrivateKey"), GetHasPrivateKey); tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PublicKey"), GetPublicKey); tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PrivateKey"), GetPrivateKey); //Methods (Prototype) tpl->PrototypeTemplate()->Set(String::NewSymbol("sign"), FunctionTemplate::New(Sign)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("verifySignature"), FunctionTemplate::New(VerifySignature)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("deriveSharedSecret"), FunctionTemplate::New(DeriveSharedSecret)->GetFunction()); Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction()); exports->Set(String::NewSymbol("ECKey"), constructor); } // Node constructor function // new ECKey(curve, buffer, isPrivate) Handle<Value> ECKey::New(const Arguments &args) { if (!args.IsConstructCall()) { return V8Exception("Must use new keyword"); } if (args[0]->IsUndefined()) { return V8Exception("First argument must be an ECCurve"); } HandleScope scope; ECKey *eckey = new ECKey(args[0]->NumberValue()); if (!args[1]->IsUndefined()) { //we have a second parameter, check the third to see if it is public or private. if (!Buffer::HasInstance(args[1])) { return V8Exception("Second parameter must be a buffer"); } Handle<Object> buffer = args[1]->ToObject(); const unsigned char *bufferData = (unsigned char *) Buffer::Data(buffer); if ((args[2]->IsUndefined()) || (args[2]->BooleanValue() == false)) { // it's a private key BIGNUM *bn = BN_bin2bn(bufferData, Buffer::Length(buffer), BN_new()); if (EC_KEY_regenerate_key(eckey->mKey, bn) == 0) { BN_clear_free(bn); return V8Exception("Invalid private key"); } BN_clear_free(bn); eckey->mHasPrivateKey = true; } else { // it's a public key if (!o2i_ECPublicKey(&(eckey->mKey), &bufferData, Buffer::Length(buffer))) { return V8Exception("o2i_ECPublicKey failed"); } } } else { if (!EC_KEY_generate_key(eckey->mKey)) { return V8Exception("EC_KEY_generate_key failed"); } eckey->mHasPrivateKey = true; } eckey->Wrap(args.Holder()); return args.Holder(); } // Node properity functions Handle<Value> ECKey::GetHasPrivateKey(Local<String> property, const AccessorInfo &info) { HandleScope scope; ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); return scope.Close(Boolean::New(eckey->mHasPrivateKey)); } Handle<Value> ECKey::GetPublicKey(Local<String> property, const AccessorInfo &info) { ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); const EC_GROUP *group = EC_KEY_get0_group(eckey->mKey); const EC_POINT *point = EC_KEY_get0_public_key(eckey->mKey); unsigned int nReq = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, NULL); if (!nReq) { return V8Exception("EC_POINT_point2oct error"); } unsigned char *buf, *buf2; buf = buf2 = (unsigned char *)malloc(nReq); if (EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, buf, nReq, NULL) != nReq) { return V8Exception("EC_POINT_point2oct didn't return correct size"); } HandleScope scope; Buffer *buffer = Buffer::New(nReq); memcpy(Buffer::Data(buffer), buf2, nReq); free(buf2); return scope.Close(buffer->handle_); } Handle<Value> ECKey::GetPrivateKey(Local<String> property, const AccessorInfo &info) { ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); const BIGNUM *bn = EC_KEY_get0_private_key(eckey->mKey); if (bn == NULL) { return V8Exception("EC_KEY_get0_private_key failed"); } int priv_size = BN_num_bytes(bn); unsigned char *priv_buf = (unsigned char *)malloc(priv_size); int n = BN_bn2bin(bn, priv_buf); if (n != priv_size) { return V8Exception("BN_bn2bin didn't return priv_size"); } HandleScope scope; Buffer *buffer = Buffer::New(priv_size); memcpy(Buffer::Data(buffer), priv_buf, priv_size); free(priv_buf); return scope.Close(buffer->handle_); } // Node method functions Handle<Value> ECKey::Sign(const Arguments &args) { HandleScope scope; ECKey * eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); if (!Buffer::HasInstance(args[0])) { return V8Exception("digest must be a buffer"); } if (!eckey->mHasPrivateKey) { return V8Exception("cannot sign without private key"); } Handle<Object> digest = args[0]->ToObject(); const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest); unsigned int digest_len = Buffer::Length(digest); ECDSA_SIG *sig = ECDSA_do_sign(digest_data, digest_len, eckey->mKey); if (!sig) { return V8Exception("ECDSA_do_sign"); } int sig_len = i2d_ECDSA_SIG(sig, NULL); if (!sig_len) { return V8Exception("i2d_ECDSA_SIG"); } unsigned char *sig_data, *sig_data2; sig_data = sig_data2 = (unsigned char *)malloc(sig_len); if (i2d_ECDSA_SIG(sig, &sig_data) != sig_len) { ECDSA_SIG_free(sig); free(sig_data2); return V8Exception("i2d_ECDSA_SIG didnot return correct length"); } ECDSA_SIG_free(sig); Buffer *result = Buffer::New(sig_len); memcpy(Buffer::Data(result), sig_data2, sig_len); free(sig_data2); return scope.Close(result->handle_); } Handle<Value> ECKey::VerifySignature(const Arguments &args) { HandleScope scope; ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); if (!Buffer::HasInstance(args[0])) { return V8Exception("digest must be a buffer"); } if (!Buffer::HasInstance(args[1])) { return V8Exception("signature must be a buffer"); } Handle<Object> digest = args[0]->ToObject(); Handle<Object> signature = args[1]->ToObject(); const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest); const unsigned char *signature_data = (unsigned char *)Buffer::Data(signature); unsigned int digest_len = Buffer::Length(digest); unsigned int signature_len = Buffer::Length(signature); int result = ECDSA_verify(0, digest_data, digest_len, signature_data, signature_len, eckey->mKey); if (result == -1) { return V8Exception("ECDSA_verify"); } else if (result == 0) { return scope.Close(Boolean::New(false)); } else if (result == 1) { return scope.Close(Boolean::New(true)); } else { return V8Exception("ECDSA_verify gave an unexpected return value"); } } Handle<Value> ECKey::DeriveSharedSecret(const Arguments &args) { HandleScope scope; if (args[0]->IsUndefined()) { return V8Exception("other is required"); } ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); ECKey *other = ObjectWrap::Unwrap<ECKey>(args[0]->ToObject()); if (!other) { return V8Exception("other must be an ECKey"); } unsigned char *secret = (unsigned char*)malloc(512); int len = ECDH_compute_key(secret, 512, EC_KEY_get0_public_key(other->mKey), eckey->mKey, NULL); Buffer *result = Buffer::New(len); memcpy(Buffer::Data(result), secret, len); free(secret); return scope.Close(result->handle_); } <commit_msg>remove commented line for removed LastError<commit_after>#include <string.h> #include <node.h> #include <node_buffer.h> #include <openssl/bn.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/ecdh.h> #include "eckey.h" using namespace v8; using namespace node; static Handle<Value> V8Exception(const char* msg) { HandleScope scope; return ThrowException(Exception::Error(String::New(msg))); } // Not sure where this came from. but looks like a function that should be part of openssl int static inline EC_KEY_regenerate_key(EC_KEY *eckey, const BIGNUM *priv_key) { if (!eckey) return 0; int ok = 0; BN_CTX *ctx = NULL; EC_POINT *pub_key = NULL; const EC_GROUP *group = EC_KEY_get0_group(eckey); if ((ctx = BN_CTX_new()) == NULL) goto err; pub_key = EC_POINT_new(group); if (pub_key == NULL) goto err; if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx)) goto err; EC_KEY_set_private_key(eckey, priv_key); EC_KEY_set_public_key(eckey, pub_key); ok = 1; err: if (pub_key) EC_POINT_free(pub_key); if (ctx != NULL) BN_CTX_free(ctx); return ok; } ECKey::ECKey(int curve) { mHasPrivateKey = false; mCurve = curve; mKey = EC_KEY_new_by_curve_name(mCurve); if (!mKey) { V8Exception("EC_KEY_new_by_curve_name Invalid curve?"); return; } } ECKey::~ECKey() { if (mKey) { EC_KEY_free(mKey); } } // Node module init void ECKey::Init(Handle<Object> exports) { Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("ECKey")); tpl->InstanceTemplate()->SetInternalFieldCount(1); //Accessors tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("HasPrivateKey"), GetHasPrivateKey); tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PublicKey"), GetPublicKey); tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PrivateKey"), GetPrivateKey); //Methods (Prototype) tpl->PrototypeTemplate()->Set(String::NewSymbol("sign"), FunctionTemplate::New(Sign)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("verifySignature"), FunctionTemplate::New(VerifySignature)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("deriveSharedSecret"), FunctionTemplate::New(DeriveSharedSecret)->GetFunction()); Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction()); exports->Set(String::NewSymbol("ECKey"), constructor); } // Node constructor function // new ECKey(curve, buffer, isPrivate) Handle<Value> ECKey::New(const Arguments &args) { if (!args.IsConstructCall()) { return V8Exception("Must use new keyword"); } if (args[0]->IsUndefined()) { return V8Exception("First argument must be an ECCurve"); } HandleScope scope; ECKey *eckey = new ECKey(args[0]->NumberValue()); if (!args[1]->IsUndefined()) { //we have a second parameter, check the third to see if it is public or private. if (!Buffer::HasInstance(args[1])) { return V8Exception("Second parameter must be a buffer"); } Handle<Object> buffer = args[1]->ToObject(); const unsigned char *bufferData = (unsigned char *) Buffer::Data(buffer); if ((args[2]->IsUndefined()) || (args[2]->BooleanValue() == false)) { // it's a private key BIGNUM *bn = BN_bin2bn(bufferData, Buffer::Length(buffer), BN_new()); if (EC_KEY_regenerate_key(eckey->mKey, bn) == 0) { BN_clear_free(bn); return V8Exception("Invalid private key"); } BN_clear_free(bn); eckey->mHasPrivateKey = true; } else { // it's a public key if (!o2i_ECPublicKey(&(eckey->mKey), &bufferData, Buffer::Length(buffer))) { return V8Exception("o2i_ECPublicKey failed"); } } } else { if (!EC_KEY_generate_key(eckey->mKey)) { return V8Exception("EC_KEY_generate_key failed"); } eckey->mHasPrivateKey = true; } eckey->Wrap(args.Holder()); return args.Holder(); } // Node properity functions Handle<Value> ECKey::GetHasPrivateKey(Local<String> property, const AccessorInfo &info) { HandleScope scope; ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); return scope.Close(Boolean::New(eckey->mHasPrivateKey)); } Handle<Value> ECKey::GetPublicKey(Local<String> property, const AccessorInfo &info) { ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); const EC_GROUP *group = EC_KEY_get0_group(eckey->mKey); const EC_POINT *point = EC_KEY_get0_public_key(eckey->mKey); unsigned int nReq = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, NULL); if (!nReq) { return V8Exception("EC_POINT_point2oct error"); } unsigned char *buf, *buf2; buf = buf2 = (unsigned char *)malloc(nReq); if (EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, buf, nReq, NULL) != nReq) { return V8Exception("EC_POINT_point2oct didn't return correct size"); } HandleScope scope; Buffer *buffer = Buffer::New(nReq); memcpy(Buffer::Data(buffer), buf2, nReq); free(buf2); return scope.Close(buffer->handle_); } Handle<Value> ECKey::GetPrivateKey(Local<String> property, const AccessorInfo &info) { ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); const BIGNUM *bn = EC_KEY_get0_private_key(eckey->mKey); if (bn == NULL) { return V8Exception("EC_KEY_get0_private_key failed"); } int priv_size = BN_num_bytes(bn); unsigned char *priv_buf = (unsigned char *)malloc(priv_size); int n = BN_bn2bin(bn, priv_buf); if (n != priv_size) { return V8Exception("BN_bn2bin didn't return priv_size"); } HandleScope scope; Buffer *buffer = Buffer::New(priv_size); memcpy(Buffer::Data(buffer), priv_buf, priv_size); free(priv_buf); return scope.Close(buffer->handle_); } // Node method functions Handle<Value> ECKey::Sign(const Arguments &args) { HandleScope scope; ECKey * eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); if (!Buffer::HasInstance(args[0])) { return V8Exception("digest must be a buffer"); } if (!eckey->mHasPrivateKey) { return V8Exception("cannot sign without private key"); } Handle<Object> digest = args[0]->ToObject(); const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest); unsigned int digest_len = Buffer::Length(digest); ECDSA_SIG *sig = ECDSA_do_sign(digest_data, digest_len, eckey->mKey); if (!sig) { return V8Exception("ECDSA_do_sign"); } int sig_len = i2d_ECDSA_SIG(sig, NULL); if (!sig_len) { return V8Exception("i2d_ECDSA_SIG"); } unsigned char *sig_data, *sig_data2; sig_data = sig_data2 = (unsigned char *)malloc(sig_len); if (i2d_ECDSA_SIG(sig, &sig_data) != sig_len) { ECDSA_SIG_free(sig); free(sig_data2); return V8Exception("i2d_ECDSA_SIG didnot return correct length"); } ECDSA_SIG_free(sig); Buffer *result = Buffer::New(sig_len); memcpy(Buffer::Data(result), sig_data2, sig_len); free(sig_data2); return scope.Close(result->handle_); } Handle<Value> ECKey::VerifySignature(const Arguments &args) { HandleScope scope; ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); if (!Buffer::HasInstance(args[0])) { return V8Exception("digest must be a buffer"); } if (!Buffer::HasInstance(args[1])) { return V8Exception("signature must be a buffer"); } Handle<Object> digest = args[0]->ToObject(); Handle<Object> signature = args[1]->ToObject(); const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest); const unsigned char *signature_data = (unsigned char *)Buffer::Data(signature); unsigned int digest_len = Buffer::Length(digest); unsigned int signature_len = Buffer::Length(signature); int result = ECDSA_verify(0, digest_data, digest_len, signature_data, signature_len, eckey->mKey); if (result == -1) { return V8Exception("ECDSA_verify"); } else if (result == 0) { return scope.Close(Boolean::New(false)); } else if (result == 1) { return scope.Close(Boolean::New(true)); } else { return V8Exception("ECDSA_verify gave an unexpected return value"); } } Handle<Value> ECKey::DeriveSharedSecret(const Arguments &args) { HandleScope scope; if (args[0]->IsUndefined()) { return V8Exception("other is required"); } ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); ECKey *other = ObjectWrap::Unwrap<ECKey>(args[0]->ToObject()); if (!other) { return V8Exception("other must be an ECKey"); } unsigned char *secret = (unsigned char*)malloc(512); int len = ECDH_compute_key(secret, 512, EC_KEY_get0_public_key(other->mKey), eckey->mKey, NULL); Buffer *result = Buffer::New(len); memcpy(Buffer::Data(result), secret, len); free(secret); return scope.Close(result->handle_); } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2017 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * ****************************************************************************/ #ifndef DTK_FINE_SEARCH_DEF_HPP #define DTK_FINE_SEARCH_DEF_HPP #include <DTK_DBC.hpp> #include <DTK_FineSearchFunctor.hpp> #include <Kokkos_Core.hpp> namespace DataTransferKit { template <typename DeviceType> void FineSearch<DeviceType>::search( Kokkos::View<Coordinate **, DeviceType> reference_points, Kokkos::View<bool *, DeviceType> point_in_cell, Kokkos::View<Coordinate **, DeviceType> physical_points, Kokkos::View<Coordinate ***, DeviceType> cells, Kokkos::View<unsigned int *, DeviceType> coarse_search_output_points, Kokkos::View<unsigned int *, DeviceType> coarse_search_output_cells, shards::CellTopology cell_topo ) { // Check the size of the Views DTK_REQUIRE( reference_points.extent( 0 ) == point_in_cell.extent( 0 ) ); DTK_REQUIRE( reference_points.extent( 1 ) == physical_points.extent( 1 ) ); DTK_REQUIRE( reference_points.extent( 1 ) == cells.extent( 2 ) ); DTK_REQUIRE( coarse_search_output_cells.extent( 0 ) == coarse_search_output_points.extent( 0 ) ); using ExecutionSpace = typename DeviceType::execution_space; int const n_ref_pts = reference_points.extent( 0 ); // Perform the fine search. We hide the template parameters used by // Intrepid2, using the CellType template. // Note that if the Newton solver does not converge, Intrepid2 will just // return the last results and there is no way to know that the coordinates // in the reference frames where not found. unsigned int const cell_topo_key = cell_topo.getKey(); if ( cell_topo_key == shards::getCellTopologyData<shards::Hexahedron<8>>()->key ) { Functor::FineSearch<CellType::Hexahedron_8, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_hex_8" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Hexahedron<27>>()->key ) { Functor::FineSearch<CellType::Hexahedron_27, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_hex_27" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Pyramid<5>>()->key ) { Functor::FineSearch<CellType::Pyramid_5, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_pyr_5" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Quadrilateral<4>>()->key ) { Functor::FineSearch<CellType::Quadrilateral_4, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_quad_4" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Quadrilateral<8>>()->key ) { Functor::FineSearch<CellType::Quadrilateral_9, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_quad_9" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Tetrahedron<4>>()->key ) { Functor::FineSearch<CellType::Tetrahedron_4, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tet_4" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Tetrahedron<10>>()->key ) { Functor::FineSearch<CellType::Tetrahedron_10, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tet_10" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Triangle<3>>()->key ) { Functor::FineSearch<CellType::Triangle_3, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tri_3" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Triangle<6>>()->key ) { Functor::FineSearch<CellType::Triangle_6, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tri_6" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Wedge<6>>()->key ) { Functor::FineSearch<CellType::Wedge_6, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_wedge_6" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Wedge<18>>()->key ) { Functor::FineSearch<CellType::Wedge_18, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_wedge_18" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else { throw std::runtime_error( "Not implemented" ); } Kokkos::fence(); } } // Explicit instantiation macro #define DTK_FINESEARCH_INSTANT( NODE ) \ template class FineSearch<typename NODE::device_type>; #endif <commit_msg>Fix a bug: replace Quadrilateral<8> by Quadrilateral<9><commit_after>/**************************************************************************** * Copyright (c) 2012-2017 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * ****************************************************************************/ #ifndef DTK_FINE_SEARCH_DEF_HPP #define DTK_FINE_SEARCH_DEF_HPP #include <DTK_DBC.hpp> #include <DTK_FineSearchFunctor.hpp> #include <Kokkos_Core.hpp> namespace DataTransferKit { template <typename DeviceType> void FineSearch<DeviceType>::search( Kokkos::View<Coordinate **, DeviceType> reference_points, Kokkos::View<bool *, DeviceType> point_in_cell, Kokkos::View<Coordinate **, DeviceType> physical_points, Kokkos::View<Coordinate ***, DeviceType> cells, Kokkos::View<unsigned int *, DeviceType> coarse_search_output_points, Kokkos::View<unsigned int *, DeviceType> coarse_search_output_cells, shards::CellTopology cell_topo ) { // Check the size of the Views DTK_REQUIRE( reference_points.extent( 0 ) == point_in_cell.extent( 0 ) ); DTK_REQUIRE( reference_points.extent( 1 ) == physical_points.extent( 1 ) ); DTK_REQUIRE( reference_points.extent( 1 ) == cells.extent( 2 ) ); DTK_REQUIRE( coarse_search_output_cells.extent( 0 ) == coarse_search_output_points.extent( 0 ) ); using ExecutionSpace = typename DeviceType::execution_space; int const n_ref_pts = reference_points.extent( 0 ); // Perform the fine search. We hide the template parameters used by // Intrepid2, using the CellType template. // Note that if the Newton solver does not converge, Intrepid2 will just // return the last results and there is no way to know that the coordinates // in the reference frames where not found. unsigned int const cell_topo_key = cell_topo.getKey(); if ( cell_topo_key == shards::getCellTopologyData<shards::Hexahedron<8>>()->key ) { Functor::FineSearch<CellType::Hexahedron_8, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_hex_8" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Hexahedron<27>>()->key ) { Functor::FineSearch<CellType::Hexahedron_27, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_hex_27" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Pyramid<5>>()->key ) { Functor::FineSearch<CellType::Pyramid_5, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_pyr_5" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Quadrilateral<4>>()->key ) { Functor::FineSearch<CellType::Quadrilateral_4, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_quad_4" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Quadrilateral<9>>()->key ) { Functor::FineSearch<CellType::Quadrilateral_9, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_quad_9" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Tetrahedron<4>>()->key ) { Functor::FineSearch<CellType::Tetrahedron_4, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tet_4" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Tetrahedron<10>>()->key ) { Functor::FineSearch<CellType::Tetrahedron_10, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tet_10" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Triangle<3>>()->key ) { Functor::FineSearch<CellType::Triangle_3, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tri_3" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Triangle<6>>()->key ) { Functor::FineSearch<CellType::Triangle_6, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tri_6" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Wedge<6>>()->key ) { Functor::FineSearch<CellType::Wedge_6, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_wedge_6" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Wedge<18>>()->key ) { Functor::FineSearch<CellType::Wedge_18, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_wedge_18" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else { throw std::runtime_error( "Not implemented" ); } Kokkos::fence(); } } // Explicit instantiation macro #define DTK_FINESEARCH_INSTANT( NODE ) \ template class FineSearch<typename NODE::device_type>; #endif <|endoftext|>
<commit_before>// // itkBioFormatsImageIO.cxx // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Adapted from the Slicer3 project: http://www.slicer.org/ http://viewvc.slicer.org/viewcvs.cgi/trunk/Libs/MGHImageIO/ See slicer-license.txt for licensing information. For more information about the ITK Plugin IO mechanism, see: http://www.itk.org/Wiki/Plugin_IO_mechanisms */ #include <fstream> #include "itkBioFormatsImageIO.h" #include "itkIOCommon.h" #include "itkExceptionObject.h" #include "itkByteSwapper.h" #include "itkMetaDataObject.h" #include <vnl/vnl_matrix.h> #include <vnl/vnl_vector.h> #include <vnl/vnl_cross.h> #include <cmath> #include <stdio.h> #include <stdlib.h> //-------------------------------------- // // BioFormatsImageIO // namespace itk { BioFormatsImageIO::BioFormatsImageIO() { PRINT("BioFormatsImageIO constuctor"); m_PixelType = SCALAR; m_FileType = Binary; m_NumberOfComponents = 1; // NB: Always split channels for now. // initialize the Java virtual machine PRINT("Creating JVM..."); StaticVmLoader loader(JNI_VERSION_1_4); OptionList list; // NB: Use full path for now, to ensure Java libraries can be found. std::string jarPath = "/home/curtis/src/itk/InsightToolkit-3.10.2/build/bin/"; //std::string jarPath = ""; list.push_back(jace::ClassPath( jarPath + "jace-runtime.jar:" + jarPath + "bio-formats.jar:" + jarPath + "loci_tools.jar" )); list.push_back(jace::CustomOption("-Xcheck:jni")); list.push_back(jace::CustomOption("-Xmx256m")); //list.push_back(jace::CustomOption("-verbose:jni")); jace::helper::createVm(loader, list, false); PRINT("JVM created."); PRINT("Creating Bio-Formats objects..."); reader = new ChannelSeparator; writer = new ImageWriter; PRINT("Created reader and writer."); } BioFormatsImageIO::~BioFormatsImageIO() { delete reader; delete writer; } bool BioFormatsImageIO::CanReadFile(const char* FileNameToRead) { PRINT("BioFormatsImageIO::CanReadFile: FileNameToRead=" << FileNameToRead); std::string filename(FileNameToRead); if ( filename == "" ) { itkExceptionMacro(<<"A FileName must be specified."); return false; } // call Bio-Formats to check file type // NB: Calling reader->isThisType() causes a symbol lookup error on: // _ZNK4jace5proxy5types8JBooleancvaEv /* bool isType = reader->isThisType(filename); PRINT("BioFormatsImageIO::CanReadFile: isType=" << isType); return isType; */ return true; } void BioFormatsImageIO::ReadImageInformation() { PRINT("BioFormatsImageIO::ReadImageInformation: m_FileName=" << m_FileName); // attach OME metadata object IMetadata omeMeta = MetadataTools::createOMEXMLMetadata(); reader->setMetadataStore(omeMeta); // initialize dataset PRINT("Initializing..."); reader->setId(m_FileName); PRINT("Initialized."); int seriesCount = reader->getSeriesCount(); PRINT("\tSeriesCount = " << seriesCount); // get byte order // NB: Calling reader->isLittleEndian() causes a symbol lookup error on: // _ZNK4jace5proxy5types8JBooleancvaEv /* bool little = reader->isLittleEndian(); if (little) SetByteOrderToLittleEndian(); else SetByteOrderToBigEndian(); */ SetByteOrderToBigEndian(); // m_ByteOrder // get component type // NB: Calling FormatTools::UINT8() causes a symbol lookup error on: // _ZN4jace6helper15deleteGlobalRefEP10_Jv_JNIEnvP9__jobject int pixelType = reader->getPixelType(); int bpp = FormatTools::getBytesPerPixel(pixelType); PRINT("\tBytes per pixel = " << bpp); /* IOComponentType componentType; if (pixelType == FormatTools::UINT8()) componentType = UCHAR; else if (pixelType == FormatTools::INT8()) componentType = CHAR; if (pixelType == FormatTools::UINT16()) componentType = USHORT; else if (pixelType == FormatTools::INT16()) componentType = SHORT; if (pixelType == FormatTools::UINT32()) componentType = UINT; else if (pixelType == FormatTools::INT32()) componentType = INT; if (pixelType == FormatTools::FLOAT()) componentType = FLOAT; else if (pixelType == FormatTools::DOUBLE()) componentType = DOUBLE; else componentType = UNKNOWNCOMPONENTTYPE; SetComponentType(componentType); // m_ComponentType if (componentType == UNKNOWNCOMPONENTTYPE) { itkExceptionMacro(<<"Unknown pixel type: " << pixelType); } */ // TEMP - for now we assume 8-bit unsigned integer data SetComponentType(UCHAR); // get pixel resolution and dimensional extents int sizeX = reader->getSizeX(); int sizeY = reader->getSizeY(); int sizeZ = reader->getSizeZ(); int sizeC = reader->getSizeC(); int sizeT = reader->getSizeT(); // NB: ITK does not seem to provide a facility for multidimensional // data beyond multichannel 3D? Need to investigate further. int imageCount = reader->getImageCount(); SetNumberOfDimensions(imageCount > 1 ? 3 : 2); m_Dimensions[0] = sizeX; m_Dimensions[1] = sizeY; if (imageCount > 1) m_Dimensions[2] = imageCount; PRINT("\tSizeX = " << sizeX); PRINT("\tSizeY = " << sizeY); PRINT("\tSizeZ = " << sizeZ); PRINT("\tSizeC = " << sizeC); PRINT("\tSizeT = " << sizeT); PRINT("\tImage Count = " << imageCount); // get physical resolution // NB: Jace interface proxies do not inherit from superinterfaces. // E.g., IMetadata does not possess methods from MetadataRetrieve. // Need to find a way around this, or improve Jace. //float physX = omeMeta.getDimensionsPhysicalSizeX(0, 0); //float physY = omeMeta.getDimensionsPhysicalSizeY(0, 0); //m_Spacing[0] = physX; //m_Spacing[1] = physY; //if (imageCount > 1) m_Spacing[2] = 1; //PRINT("\tPhysicalSizeX = " << physX); //PRINT("\tPhysicalSizeY = " << physY); } void BioFormatsImageIO::Read(void* pData) { char* data = (char*) pData; PRINT("BioFormatsImageIO::Read"); typedef JArray<JByte> ByteArray; int pixelType = reader->getPixelType(); int bpp = FormatTools::getBytesPerPixel(pixelType); // check IO region to identify the planar extents desired ImageIORegion region = GetIORegion(); int regionDim = region.GetImageDimension(); int xIndex = region.GetIndex(0); int xCount = region.GetSize(0); int yIndex = region.GetIndex(1); int yCount = region.GetSize(1); int pIndex = 0, pCount = 1; if (regionDim > 2) { pIndex = region.GetIndex(2); pCount = region.GetSize(2); } int bytesPerSubPlane = xCount * yCount * bpp; PRINT("\tRegion dimension = " << regionDim); PRINT("\tX index = " << xIndex); PRINT("\tX count = " << xCount); PRINT("\tY index = " << yIndex); PRINT("\tY count = " << yCount); PRINT("\tPlane index = " << pIndex); PRINT("\tPlane count = " << pCount); PRINT("\tBytes per plane = " << bytesPerSubPlane); int p = 0; for (int no=pIndex; no<pIndex+pCount; no++) { PRINT("Reading image plane " << (no + 1) << "/" << reader->getImageCount()); ByteArray buf = reader->openBytes(no, xIndex, xCount, yIndex, yCount); // NB: Using brackets with a JArray causes a symbol lookup error on: // _ZN4jace6helper12newGlobalRefEP10_Jv_JNIEnvP9__jobject //for (int i=0; i<bytesPerSubPlane; i++) data[p++] = buf[i]; // TEMP - for now we populate the buffer with dummy data for (int i=0; i<bytesPerSubPlane; i++) data[p++] = 255 - no; } reader->close(); PRINT("Done."); } // end Read function bool BioFormatsImageIO::CanWriteFile(const char* name) { PRINT("BioFormatsImageIO::CanWriteFile: name=" << name); std::string filename(name); if ( filename == "" ) { itkExceptionMacro(<<"A FileName must be specified."); return false; } // call Bio-Formats to check file type ImageWriter writer; bool isType = writer.isThisType(filename); PRINT("BioFormatsImageIO::CanWriteFile: isType=" << isType); return isType; } void BioFormatsImageIO::WriteImageInformation() { PRINT("BioFormatsImageIO::WriteImageInformation"); } void BioFormatsImageIO::Write(const void* buffer) { PRINT("BioFormatsImageIO::Write"); // CTR TODO - implmeent Write function } // end Write function } // end NAMESPACE ITK <commit_msg>Eliminate hardcoded ITK path.<commit_after>// // itkBioFormatsImageIO.cxx // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Adapted from the Slicer3 project: http://www.slicer.org/ http://viewvc.slicer.org/viewcvs.cgi/trunk/Libs/MGHImageIO/ See slicer-license.txt for licensing information. For more information about the ITK Plugin IO mechanism, see: http://www.itk.org/Wiki/Plugin_IO_mechanisms */ #include <fstream> #include "itkBioFormatsImageIO.h" #include "itkIOCommon.h" #include "itkExceptionObject.h" #include "itkByteSwapper.h" #include "itkMetaDataObject.h" #include <vnl/vnl_matrix.h> #include <vnl/vnl_vector.h> #include <vnl/vnl_cross.h> #include <cmath> #include <stdio.h> #include <stdlib.h> //-------------------------------------- // // BioFormatsImageIO // namespace itk { BioFormatsImageIO::BioFormatsImageIO() { PRINT("BioFormatsImageIO constuctor"); m_PixelType = SCALAR; m_FileType = Binary; m_NumberOfComponents = 1; // NB: Always split channels for now. // initialize the Java virtual machine PRINT("Creating JVM..."); StaticVmLoader loader(JNI_VERSION_1_4); OptionList list; list.push_back(jace::ClassPath( "jace-runtime.jar:bio-formats.jar:loci_tools.jar" )); list.push_back(jace::CustomOption("-Xcheck:jni")); list.push_back(jace::CustomOption("-Xmx256m")); //list.push_back(jace::CustomOption("-verbose:jni")); jace::helper::createVm(loader, list, false); PRINT("JVM created."); PRINT("Creating Bio-Formats objects..."); reader = new ChannelSeparator; writer = new ImageWriter; PRINT("Created reader and writer."); } BioFormatsImageIO::~BioFormatsImageIO() { delete reader; delete writer; } bool BioFormatsImageIO::CanReadFile(const char* FileNameToRead) { PRINT("BioFormatsImageIO::CanReadFile: FileNameToRead=" << FileNameToRead); std::string filename(FileNameToRead); if ( filename == "" ) { itkExceptionMacro(<<"A FileName must be specified."); return false; } // call Bio-Formats to check file type // NB: Calling reader->isThisType() causes a symbol lookup error on: // _ZNK4jace5proxy5types8JBooleancvaEv /* bool isType = reader->isThisType(filename); PRINT("BioFormatsImageIO::CanReadFile: isType=" << isType); return isType; */ return true; } void BioFormatsImageIO::ReadImageInformation() { PRINT("BioFormatsImageIO::ReadImageInformation: m_FileName=" << m_FileName); // attach OME metadata object IMetadata omeMeta = MetadataTools::createOMEXMLMetadata(); reader->setMetadataStore(omeMeta); // initialize dataset PRINT("Initializing..."); reader->setId(m_FileName); PRINT("Initialized."); int seriesCount = reader->getSeriesCount(); PRINT("\tSeriesCount = " << seriesCount); // get byte order // NB: Calling reader->isLittleEndian() causes a symbol lookup error on: // _ZNK4jace5proxy5types8JBooleancvaEv /* bool little = reader->isLittleEndian(); if (little) SetByteOrderToLittleEndian(); else SetByteOrderToBigEndian(); */ SetByteOrderToBigEndian(); // m_ByteOrder // get component type // NB: Calling FormatTools::UINT8() causes a symbol lookup error on: // _ZN4jace6helper15deleteGlobalRefEP10_Jv_JNIEnvP9__jobject int pixelType = reader->getPixelType(); int bpp = FormatTools::getBytesPerPixel(pixelType); PRINT("\tBytes per pixel = " << bpp); /* IOComponentType componentType; if (pixelType == FormatTools::UINT8()) componentType = UCHAR; else if (pixelType == FormatTools::INT8()) componentType = CHAR; if (pixelType == FormatTools::UINT16()) componentType = USHORT; else if (pixelType == FormatTools::INT16()) componentType = SHORT; if (pixelType == FormatTools::UINT32()) componentType = UINT; else if (pixelType == FormatTools::INT32()) componentType = INT; if (pixelType == FormatTools::FLOAT()) componentType = FLOAT; else if (pixelType == FormatTools::DOUBLE()) componentType = DOUBLE; else componentType = UNKNOWNCOMPONENTTYPE; SetComponentType(componentType); // m_ComponentType if (componentType == UNKNOWNCOMPONENTTYPE) { itkExceptionMacro(<<"Unknown pixel type: " << pixelType); } */ // TEMP - for now we assume 8-bit unsigned integer data SetComponentType(UCHAR); // get pixel resolution and dimensional extents int sizeX = reader->getSizeX(); int sizeY = reader->getSizeY(); int sizeZ = reader->getSizeZ(); int sizeC = reader->getSizeC(); int sizeT = reader->getSizeT(); // NB: ITK does not seem to provide a facility for multidimensional // data beyond multichannel 3D? Need to investigate further. int imageCount = reader->getImageCount(); SetNumberOfDimensions(imageCount > 1 ? 3 : 2); m_Dimensions[0] = sizeX; m_Dimensions[1] = sizeY; if (imageCount > 1) m_Dimensions[2] = imageCount; PRINT("\tSizeX = " << sizeX); PRINT("\tSizeY = " << sizeY); PRINT("\tSizeZ = " << sizeZ); PRINT("\tSizeC = " << sizeC); PRINT("\tSizeT = " << sizeT); PRINT("\tImage Count = " << imageCount); // get physical resolution // NB: Jace interface proxies do not inherit from superinterfaces. // E.g., IMetadata does not possess methods from MetadataRetrieve. // Need to find a way around this, or improve Jace. //float physX = omeMeta.getDimensionsPhysicalSizeX(0, 0); //float physY = omeMeta.getDimensionsPhysicalSizeY(0, 0); //m_Spacing[0] = physX; //m_Spacing[1] = physY; //if (imageCount > 1) m_Spacing[2] = 1; //PRINT("\tPhysicalSizeX = " << physX); //PRINT("\tPhysicalSizeY = " << physY); } void BioFormatsImageIO::Read(void* pData) { char* data = (char*) pData; PRINT("BioFormatsImageIO::Read"); typedef JArray<JByte> ByteArray; int pixelType = reader->getPixelType(); int bpp = FormatTools::getBytesPerPixel(pixelType); // check IO region to identify the planar extents desired ImageIORegion region = GetIORegion(); int regionDim = region.GetImageDimension(); int xIndex = region.GetIndex(0); int xCount = region.GetSize(0); int yIndex = region.GetIndex(1); int yCount = region.GetSize(1); int pIndex = 0, pCount = 1; if (regionDim > 2) { pIndex = region.GetIndex(2); pCount = region.GetSize(2); } int bytesPerSubPlane = xCount * yCount * bpp; PRINT("\tRegion dimension = " << regionDim); PRINT("\tX index = " << xIndex); PRINT("\tX count = " << xCount); PRINT("\tY index = " << yIndex); PRINT("\tY count = " << yCount); PRINT("\tPlane index = " << pIndex); PRINT("\tPlane count = " << pCount); PRINT("\tBytes per plane = " << bytesPerSubPlane); int p = 0; for (int no=pIndex; no<pIndex+pCount; no++) { PRINT("Reading image plane " << (no + 1) << "/" << reader->getImageCount()); ByteArray buf = reader->openBytes(no, xIndex, xCount, yIndex, yCount); // NB: Using brackets with a JArray causes a symbol lookup error on: // _ZN4jace6helper12newGlobalRefEP10_Jv_JNIEnvP9__jobject //for (int i=0; i<bytesPerSubPlane; i++) data[p++] = buf[i]; // TEMP - for now we populate the buffer with dummy data for (int i=0; i<bytesPerSubPlane; i++) data[p++] = 255 - no; } reader->close(); PRINT("Done."); } // end Read function bool BioFormatsImageIO::CanWriteFile(const char* name) { PRINT("BioFormatsImageIO::CanWriteFile: name=" << name); std::string filename(name); if ( filename == "" ) { itkExceptionMacro(<<"A FileName must be specified."); return false; } // call Bio-Formats to check file type ImageWriter writer; bool isType = writer.isThisType(filename); PRINT("BioFormatsImageIO::CanWriteFile: isType=" << isType); return isType; } void BioFormatsImageIO::WriteImageInformation() { PRINT("BioFormatsImageIO::WriteImageInformation"); } void BioFormatsImageIO::Write(const void* buffer) { PRINT("BioFormatsImageIO::Write"); // CTR TODO - implmeent Write function } // end Write function } // end NAMESPACE ITK <|endoftext|>
<commit_before>/** * Copyright (c) 2010 Daniel Wiberg * * 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 "Painter.h" #include "util/ScopedLock.h" #include <iostream> namespace canvas { Painter::Painter(int width, int height, std::string const& fileOrCode, bool isFile) : m_painterMutex(), m_logMutex(), m_width(width), m_height(height), m_fileOrCode(fileOrCode), m_isFile(isFile), m_script(0), m_context(0), m_callbackIndex(0), m_windowBinding(0), m_contextBinding(0) { } void Painter::start() { v8::HandleScope scope; // Create V8 context m_scriptTemplate = v8::Persistent<v8::ObjectTemplate>::New(v8::ObjectTemplate::New()); v8::Local<v8::Context> jsContext = v8::Local<v8::Context>::New(v8::Context::New(0, m_scriptTemplate)); // Create bindings m_windowBinding = new binding::Object<Painter>("Window"); m_windowBinding->function("setInterval", &Painter::setInterval) .function("clearInterval", &Painter::clearInterval) .function("getContext", &Painter::getContext) .function("log", &Painter::log); m_contextBinding = new binding::Object<Context>("Context"); m_contextBinding->function("scale", &Context::scale) .function("rotate", &Context::rotate) .function("translate", &Context::translate) .function("beginPath", &Context::beginPath) .function("closePath", &Context::closePath) .function("moveTo", &Context::moveTo) .function("lineTo", &Context::lineTo) .function("fillRect", &Context::fillRect) .function("strokeRect", &Context::strokeRect) .attribute("width", &Context::width, &Context::setWidth) .attribute("height", &Context::height, &Context::setHeight) .attribute("lineWidth", &Context::lineWidth, &Context::setLineWidth) .attribute("lineCap", &Context::lineCap, &Context::setLineCap); v8::Context::Scope contextScope(jsContext); // Inject the window object jsContext->Global()->Set(v8::String::New("window"), m_windowBinding->wrap(this)); // Create graphics context m_context = new Context(m_width, m_height); // Create javascript object m_script = new Script(jsContext); if (m_isFile) m_script->load(m_fileOrCode); else m_script->runString(m_fileOrCode); } Painter::~Painter() { delete m_script; delete m_context; } void Painter::draw() { ScopedLock lock(m_painterMutex); // Call all registered callbacks v8::HandleScope scope; v8::Context::Scope contextScope(m_script->context()); v8::TryCatch tryCatch; CallbackMap::iterator it = m_callbacks.begin(); CallbackMap::iterator end = m_callbacks.end(); for (; it != end; ++it) { Callback & callback = it->second; v8::Handle<v8::Value> result = callback.call(); if (result.IsEmpty()) { v8::String::Utf8Value error(tryCatch.Exception()); std::cerr << "Script runtime error: " << *error << std::endl; } } } void Painter::copyImageTo(void * target) { ScopedLock lock(m_painterMutex); if (target && m_context) m_context->copyImageTo(target); } int Painter::setInterval(v8::Handle<v8::Function> const& function) { m_callbacks.insert(std::make_pair(++m_callbackIndex, Callback(function))); return m_callbackIndex; } void Painter::clearInterval(int index) { CallbackMap::iterator result = m_callbacks.find(index); if (result != m_callbacks.end()) m_callbacks.erase(result); } v8::Handle<v8::Value> Painter::getContext(std::string const& type) { v8::HandleScope scope; if (type == "2d") return scope.Close(m_contextBinding->wrap(m_context)); std::cerr << "Error: Requested wrong context type '" << type << "'" << std::endl; return v8::Undefined(); } void Painter::log(std::string const& log) { ScopedLock lock(m_logMutex); m_history.push_back(log); // We only store a 1000 log entries if (m_history.size() > 1000) m_history.pop_front(); //std::cerr << log << std::endl; } std::string Painter::lastLogEntry() { ScopedLock lock(m_logMutex); if (m_history.empty()) return ""; std::string log = m_history.front(); m_history.pop_front(); return log; } } <commit_msg>Added bindings for fill/stroke style attributes.<commit_after>/** * Copyright (c) 2010 Daniel Wiberg * * 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 "Painter.h" #include "util/ScopedLock.h" #include <iostream> namespace canvas { Painter::Painter(int width, int height, std::string const& fileOrCode, bool isFile) : m_painterMutex(), m_logMutex(), m_width(width), m_height(height), m_fileOrCode(fileOrCode), m_isFile(isFile), m_script(0), m_context(0), m_callbackIndex(0), m_windowBinding(0), m_contextBinding(0) { } void Painter::start() { v8::HandleScope scope; // Create V8 context m_scriptTemplate = v8::Persistent<v8::ObjectTemplate>::New(v8::ObjectTemplate::New()); v8::Local<v8::Context> jsContext = v8::Local<v8::Context>::New(v8::Context::New(0, m_scriptTemplate)); // Create bindings m_windowBinding = new binding::Object<Painter>("Window"); m_windowBinding->function("setInterval", &Painter::setInterval) .function("clearInterval", &Painter::clearInterval) .function("getContext", &Painter::getContext) .function("log", &Painter::log); m_contextBinding = new binding::Object<Context>("Context"); m_contextBinding->function("scale", &Context::scale) .function("rotate", &Context::rotate) .function("translate", &Context::translate) .function("beginPath", &Context::beginPath) .function("closePath", &Context::closePath) .function("moveTo", &Context::moveTo) .function("lineTo", &Context::lineTo) .function("fillRect", &Context::fillRect) .function("strokeRect", &Context::strokeRect) .attribute("width", &Context::width, &Context::setWidth) .attribute("height", &Context::height, &Context::setHeight) .attribute("lineWidth", &Context::lineWidth, &Context::setLineWidth) .attribute("lineCap", &Context::lineCap, &Context::setLineCap) .attribute("strokeStyle", &Context::strokeStyle, &Context::setStrokeStyle) .attribute("fillStyle", &Context::fillStyle, &Context::setFillStyle); v8::Context::Scope contextScope(jsContext); // Inject the window object jsContext->Global()->Set(v8::String::New("window"), m_windowBinding->wrap(this)); // Create graphics context m_context = new Context(m_width, m_height); // Create javascript object m_script = new Script(jsContext); if (m_isFile) m_script->load(m_fileOrCode); else m_script->runString(m_fileOrCode); } Painter::~Painter() { delete m_script; delete m_context; } void Painter::draw() { ScopedLock lock(m_painterMutex); // Call all registered callbacks v8::HandleScope scope; v8::Context::Scope contextScope(m_script->context()); v8::TryCatch tryCatch; CallbackMap::iterator it = m_callbacks.begin(); CallbackMap::iterator end = m_callbacks.end(); for (; it != end; ++it) { Callback & callback = it->second; v8::Handle<v8::Value> result = callback.call(); if (result.IsEmpty()) { v8::String::Utf8Value error(tryCatch.Exception()); std::cerr << "Script runtime error: " << *error << std::endl; } } } void Painter::copyImageTo(void * target) { ScopedLock lock(m_painterMutex); if (target && m_context) m_context->copyImageTo(target); } int Painter::setInterval(v8::Handle<v8::Function> const& function) { m_callbacks.insert(std::make_pair(++m_callbackIndex, Callback(function))); return m_callbackIndex; } void Painter::clearInterval(int index) { CallbackMap::iterator result = m_callbacks.find(index); if (result != m_callbacks.end()) m_callbacks.erase(result); } v8::Handle<v8::Value> Painter::getContext(std::string const& type) { v8::HandleScope scope; if (type == "2d") return scope.Close(m_contextBinding->wrap(m_context)); std::cerr << "Error: Requested wrong context type '" << type << "'" << std::endl; return v8::Undefined(); } void Painter::log(std::string const& log) { ScopedLock lock(m_logMutex); m_history.push_back(log); // We only store a 1000 log entries if (m_history.size() > 1000) m_history.pop_front(); //std::cerr << log << std::endl; } std::string Painter::lastLogEntry() { ScopedLock lock(m_logMutex); if (m_history.empty()) return ""; std::string log = m_history.front(); m_history.pop_front(); return log; } } <|endoftext|>
<commit_before>// Maintainer: Jan Kristian Sto. Domingo [[email protected]] // exec.cpp for rshell #include <iostream> #include <string> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> using namespace std; //Notes on function formats: //execvp(const char *file, char *const argv[]) int main() { int PID = fork(); if(PID == 0) { cout << "child process" << endl; string input; cout << "$ "; getline(cin, input); input.c_str(); //converts string into a cstring // testing cout << "Test string: " << input << endl << endl; // execvp(argv[0], argv); } else { wait(0); cout << "parent process" << endl; } return 0; } <commit_msg>added user input functionality<commit_after>// Maintainer: Jan Kristian Sto. Domingo [[email protected]] // exec.cpp for rshell #include <iostream> #include <cstring> #include <string> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> using namespace std; //Notes on function formats: //execvp(const char *file, char *const argv[]) int main() { int PID = fork(); if(PID == 0) { cout << "child process" << endl; string str_input; cout << "$ "; //serves as command prompt getline(cin, str_input); cout << "Original string: " << str_input << endl << endl; char* c_input = new char[str_input.length() + 1]; strcpy(c_input, str_input.c_str()); cout << "Converted to cstring: " << c_input << endl << endl; /* char **token; token = strtok(c_input, " "); while(token != NULL) { token = strtok(NULL, " "); } */ // testing // cout << "Test c_string: " << c_input << endl << endl; // new cstring now has to be tokenized and placed into a char** // for the exec vp function // execvp(argv[0], argv); } else { wait(0); cout << "parent process" << endl; } return 0; } <|endoftext|>
<commit_before>/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* This is script-generated code (for the most part). */ /* See fileChksum.h for a description of this API call.*/ #include "fileChksum.hpp" #include "miscServerFunct.hpp" // =-=-=-=-=-=-=- #include "irods_log.hpp" #include "irods_file_object.hpp" #include "irods_stacktrace.hpp" #include "irods_resource_backport.hpp" #include "irods_hasher_factory.hpp" #include "readServerConfig.hpp" #include "irods_server_properties.hpp" #include "MD5Strategy.hpp" #define SVR_MD5_BUF_SZ (1024*1024) int rsFileChksum( rsComm_t *rsComm, fileChksumInp_t *fileChksumInp, char **chksumStr ) { rodsServerHost_t *rodsServerHost; int remoteFlag; int status; irods::error ret = irods::get_host_for_hier_string( fileChksumInp->rescHier, remoteFlag, rodsServerHost ); if ( !ret.ok() ) { irods::log( PASSMSG( "failed in call to irods::get_host_for_hier_string", ret ) ); return -1; } if ( remoteFlag == LOCAL_HOST ) { status = _rsFileChksum( rsComm, fileChksumInp, chksumStr ); } else if ( remoteFlag == REMOTE_HOST ) { status = remoteFileChksum( rsComm, fileChksumInp, chksumStr, rodsServerHost ); } else { if ( remoteFlag < 0 ) { return remoteFlag; } else { rodsLog( LOG_NOTICE, "rsFileChksum: resolveHost returned unrecognized value %d", remoteFlag ); return SYS_UNRECOGNIZED_REMOTE_FLAG; } } return status; } int remoteFileChksum( rsComm_t *rsComm, fileChksumInp_t *fileChksumInp, char **chksumStr, rodsServerHost_t *rodsServerHost ) { int status; if ( rodsServerHost == NULL ) { rodsLog( LOG_NOTICE, "remoteFileChksum: Invalid rodsServerHost" ); return SYS_INVALID_SERVER_HOST; } if ( ( status = svrToSvrConnect( rsComm, rodsServerHost ) ) < 0 ) { return status; } status = rcFileChksum( rodsServerHost->conn, fileChksumInp, chksumStr ); if ( status < 0 ) { rodsLog( LOG_NOTICE, "remoteFileChksum: rcFileChksum failed for %s", fileChksumInp->fileName ); } return status; } int _rsFileChksum( rsComm_t *rsComm, fileChksumInp_t *fileChksumInp, char **chksumStr ) { int status; if ( !*chksumStr ) { *chksumStr = ( char* )malloc( sizeof( char ) * NAME_LEN ); } status = fileChksum( rsComm, fileChksumInp->objPath, fileChksumInp->fileName, fileChksumInp->rescHier, fileChksumInp->orig_chksum, *chksumStr ); if ( status < 0 ) { rodsLog( LOG_DEBUG, "_rsFileChksum: fileChksum for %s, status = %d", fileChksumInp->fileName, status ); free( *chksumStr ); *chksumStr = NULL; } return status; } int fileChksum( rsComm_t* rsComm, char* objPath, char* fileName, char* rescHier, char* orig_chksum, char* chksumStr ) { // =-=-=-=-=-=-=- // capture server hashing settings std::string svr_hash_scheme; irods::server_properties& props = irods::server_properties::getInstance(); irods::error ret = props.get_property< std::string >( DEFAULT_HASH_SCHEME_KW, svr_hash_scheme ); std::string hash_scheme( irods::MD5_NAME ); if ( ret.ok() ) { hash_scheme = svr_hash_scheme; } std::string svr_hash_policy; ret = props.get_property< std::string >( MATCH_HASH_POLICY_KW, svr_hash_policy ); std::string hash_policy; if ( ret.ok() ) { hash_policy = svr_hash_policy; } // =-=-=-=-=-=-=- // extract scheme from checksum string std::string chkstr_scheme; if ( orig_chksum ) { ret = irods::get_hash_scheme_from_checksum( orig_chksum, chkstr_scheme ); if ( !ret.ok() ) { //irods::log( PASS( ret ) ); } } // =-=-=-=-=-=-=- // check the hash scheme against the policy // if necessary std::string final_scheme( hash_scheme ); if ( !chkstr_scheme.empty() ) { if ( !hash_policy.empty() ) { if ( irods::STRICT_HASH_POLICY == hash_policy ) { if ( hash_scheme != chkstr_scheme ) { return USER_HASH_TYPE_MISMATCH; } } } final_scheme = chkstr_scheme; } rodsLog( LOG_DEBUG, "fileChksum :: final_scheme [%s] chkstr_scheme [%s] svr_hash_policy [%s] hash_policy [%s]", final_scheme.c_str(), chkstr_scheme.c_str(), svr_hash_policy.c_str(), hash_policy.c_str() ); // =-=-=-=-=-=-=- // call resource plugin to open file irods::file_object_ptr file_obj( new irods::file_object( rsComm, objPath, fileName, rescHier, -1, 0, O_RDONLY ) ); // FIXME :: hack until this is better abstracted - JMC ret = fileOpen( rsComm, file_obj ); if ( !ret.ok() ) { int status = UNIX_FILE_OPEN_ERR - errno; if ( ret.code() != DIRECT_ARCHIVE_ACCESS ) { std::stringstream msg; msg << "fileOpen failed for ["; msg << fileName; msg << "]"; irods::log( PASSMSG( msg.str(), ret ) ); } else { status = ret.code(); } return status; } // =-=-=-=-=-=-=- // create a hasher object and init given a scheme // if it is unsupported then default to md5 irods::Hasher hasher; ret = irods::getHasher( final_scheme, hasher ); if ( !ret.ok() ) { irods::getHasher( irods::MD5_NAME, hasher ); } // =-=-=-=-=-=-=- // do an inital read of the file char buffer[SVR_MD5_BUF_SZ]; irods::error read_err = fileRead( rsComm, file_obj, buffer, SVR_MD5_BUF_SZ ); int bytes_read = read_err.code(); // =-=-=-=-=-=-=- // loop and update while there are still bytes to be read #ifdef MD5_DEBUG rodsLong_t total_bytes_read = 0; /* XXXX debug */ #endif while ( read_err.ok() && bytes_read > 0 ) { // =-=-=-=-=-=-=- // debug statistics #ifdef MD5_DEBUG total_bytes_read += bytes_read; #endif // =-=-=-=-=-=-=- // update hasher hasher.update( std::string( buffer, bytes_read ) ); // =-=-=-=-=-=-=- // read some more read_err = fileRead( rsComm, file_obj, buffer, SVR_MD5_BUF_SZ ); if ( read_err.ok() ) { bytes_read = read_err.code(); } else { std::stringstream msg; msg << __FUNCTION__; msg << " - Failed to read buffer from file: \""; msg << fileName; msg << "\""; irods::error result = PASSMSG( msg.str(), ret ); irods::log( result ); return result.code(); } } // while // =-=-=-=-=-=-=- // close out the file ret = fileClose( rsComm, file_obj ); if ( !ret.ok() ) { irods::error err = PASSMSG( "error on close", ret ); irods::log( err ); } // =-=-=-=-=-=-=- // extract the digest from the hasher object // and copy to outgoing string std::string digest; hasher.digest( digest ); strncpy( chksumStr, digest.c_str(), NAME_LEN ); // =-=-=-=-=-=-=- // debug messaging #ifdef MD5_DEBUG rodsLog( LOG_NOTICE, "fileChksum: chksum = %s, total_bytes_read = %lld", chksumStr, total_bytes_read ); #endif return 0; } <commit_msg>[#2340] Pass correct error object to PASSMSG in fileChksum()<commit_after>/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* This is script-generated code (for the most part). */ /* See fileChksum.h for a description of this API call.*/ #include "fileChksum.hpp" #include "miscServerFunct.hpp" // =-=-=-=-=-=-=- #include "irods_log.hpp" #include "irods_file_object.hpp" #include "irods_stacktrace.hpp" #include "irods_resource_backport.hpp" #include "irods_hasher_factory.hpp" #include "readServerConfig.hpp" #include "irods_server_properties.hpp" #include "MD5Strategy.hpp" #define SVR_MD5_BUF_SZ (1024*1024) int rsFileChksum( rsComm_t *rsComm, fileChksumInp_t *fileChksumInp, char **chksumStr ) { rodsServerHost_t *rodsServerHost; int remoteFlag; int status; irods::error ret = irods::get_host_for_hier_string( fileChksumInp->rescHier, remoteFlag, rodsServerHost ); if ( !ret.ok() ) { irods::log( PASSMSG( "failed in call to irods::get_host_for_hier_string", ret ) ); return -1; } if ( remoteFlag == LOCAL_HOST ) { status = _rsFileChksum( rsComm, fileChksumInp, chksumStr ); } else if ( remoteFlag == REMOTE_HOST ) { status = remoteFileChksum( rsComm, fileChksumInp, chksumStr, rodsServerHost ); } else { if ( remoteFlag < 0 ) { return remoteFlag; } else { rodsLog( LOG_NOTICE, "rsFileChksum: resolveHost returned unrecognized value %d", remoteFlag ); return SYS_UNRECOGNIZED_REMOTE_FLAG; } } return status; } int remoteFileChksum( rsComm_t *rsComm, fileChksumInp_t *fileChksumInp, char **chksumStr, rodsServerHost_t *rodsServerHost ) { int status; if ( rodsServerHost == NULL ) { rodsLog( LOG_NOTICE, "remoteFileChksum: Invalid rodsServerHost" ); return SYS_INVALID_SERVER_HOST; } if ( ( status = svrToSvrConnect( rsComm, rodsServerHost ) ) < 0 ) { return status; } status = rcFileChksum( rodsServerHost->conn, fileChksumInp, chksumStr ); if ( status < 0 ) { rodsLog( LOG_NOTICE, "remoteFileChksum: rcFileChksum failed for %s", fileChksumInp->fileName ); } return status; } int _rsFileChksum( rsComm_t *rsComm, fileChksumInp_t *fileChksumInp, char **chksumStr ) { int status; if ( !*chksumStr ) { *chksumStr = ( char* )malloc( sizeof( char ) * NAME_LEN ); } status = fileChksum( rsComm, fileChksumInp->objPath, fileChksumInp->fileName, fileChksumInp->rescHier, fileChksumInp->orig_chksum, *chksumStr ); if ( status < 0 ) { rodsLog( LOG_DEBUG, "_rsFileChksum: fileChksum for %s, status = %d", fileChksumInp->fileName, status ); free( *chksumStr ); *chksumStr = NULL; } return status; } int fileChksum( rsComm_t* rsComm, char* objPath, char* fileName, char* rescHier, char* orig_chksum, char* chksumStr ) { // =-=-=-=-=-=-=- // capture server hashing settings std::string svr_hash_scheme; irods::server_properties& props = irods::server_properties::getInstance(); irods::error ret = props.get_property< std::string >( DEFAULT_HASH_SCHEME_KW, svr_hash_scheme ); std::string hash_scheme( irods::MD5_NAME ); if ( ret.ok() ) { hash_scheme = svr_hash_scheme; } std::string svr_hash_policy; ret = props.get_property< std::string >( MATCH_HASH_POLICY_KW, svr_hash_policy ); std::string hash_policy; if ( ret.ok() ) { hash_policy = svr_hash_policy; } // =-=-=-=-=-=-=- // extract scheme from checksum string std::string chkstr_scheme; if ( orig_chksum ) { ret = irods::get_hash_scheme_from_checksum( orig_chksum, chkstr_scheme ); if ( !ret.ok() ) { //irods::log( PASS( ret ) ); } } // =-=-=-=-=-=-=- // check the hash scheme against the policy // if necessary std::string final_scheme( hash_scheme ); if ( !chkstr_scheme.empty() ) { if ( !hash_policy.empty() ) { if ( irods::STRICT_HASH_POLICY == hash_policy ) { if ( hash_scheme != chkstr_scheme ) { return USER_HASH_TYPE_MISMATCH; } } } final_scheme = chkstr_scheme; } rodsLog( LOG_DEBUG, "fileChksum :: final_scheme [%s] chkstr_scheme [%s] svr_hash_policy [%s] hash_policy [%s]", final_scheme.c_str(), chkstr_scheme.c_str(), svr_hash_policy.c_str(), hash_policy.c_str() ); // =-=-=-=-=-=-=- // call resource plugin to open file irods::file_object_ptr file_obj( new irods::file_object( rsComm, objPath, fileName, rescHier, -1, 0, O_RDONLY ) ); // FIXME :: hack until this is better abstracted - JMC ret = fileOpen( rsComm, file_obj ); if ( !ret.ok() ) { int status = UNIX_FILE_OPEN_ERR - errno; if ( ret.code() != DIRECT_ARCHIVE_ACCESS ) { std::stringstream msg; msg << "fileOpen failed for ["; msg << fileName; msg << "]"; irods::log( PASSMSG( msg.str(), ret ) ); } else { status = ret.code(); } return status; } // =-=-=-=-=-=-=- // create a hasher object and init given a scheme // if it is unsupported then default to md5 irods::Hasher hasher; ret = irods::getHasher( final_scheme, hasher ); if ( !ret.ok() ) { irods::getHasher( irods::MD5_NAME, hasher ); } // =-=-=-=-=-=-=- // do an inital read of the file char buffer[SVR_MD5_BUF_SZ]; irods::error read_err = fileRead( rsComm, file_obj, buffer, SVR_MD5_BUF_SZ ); int bytes_read = read_err.code(); // =-=-=-=-=-=-=- // loop and update while there are still bytes to be read #ifdef MD5_DEBUG rodsLong_t total_bytes_read = 0; /* XXXX debug */ #endif while ( read_err.ok() && bytes_read > 0 ) { // =-=-=-=-=-=-=- // debug statistics #ifdef MD5_DEBUG total_bytes_read += bytes_read; #endif // =-=-=-=-=-=-=- // update hasher hasher.update( std::string( buffer, bytes_read ) ); // =-=-=-=-=-=-=- // read some more read_err = fileRead( rsComm, file_obj, buffer, SVR_MD5_BUF_SZ ); if ( read_err.ok() ) { bytes_read = read_err.code(); } else { std::stringstream msg; msg << __FUNCTION__; msg << " - Failed to read buffer from file: \""; msg << fileName; msg << "\""; irods::error result = PASSMSG( msg.str(), read_err ); irods::log( result ); return result.code(); } } // while // =-=-=-=-=-=-=- // close out the file ret = fileClose( rsComm, file_obj ); if ( !ret.ok() ) { irods::error err = PASSMSG( "error on close", ret ); irods::log( err ); } // =-=-=-=-=-=-=- // extract the digest from the hasher object // and copy to outgoing string std::string digest; hasher.digest( digest ); strncpy( chksumStr, digest.c_str(), NAME_LEN ); // =-=-=-=-=-=-=- // debug messaging #ifdef MD5_DEBUG rodsLog( LOG_NOTICE, "fileChksum: chksum = %s, total_bytes_read = %lld", chksumStr, total_bytes_read ); #endif return 0; } <|endoftext|>
<commit_before>#include <tinyxml2.h> #include <chrono> #include <sstream> #include <ctime> #include "feed.h" #include "storage.h" namespace C3 { namespace Feed { std::string feed_str = ""; uint16_t feed_length; std::string title; std::string url; std::string generate_rfc3999(uint64_t ms_since_epoch) { std::chrono::milliseconds duration(ms_since_epoch); std::chrono::time_point<std::chrono::system_clock> point(duration); time_t tt = std::chrono::system_clock::to_time_t(point); std::tm *cal = gmtime(&tt); std::stringstream ss; ss<<cal->tm_year + 1900<<'-'<<cal->tm_mon<<'-'<<cal->tm_mday<<'T'<<cal->tm_hour<<':'<<cal->tm_min<<':'<<cal->tm_sec<<'Z'; return ss.str(); } void setup(const Config &c) { feed_length = c.app_feedLength; title = c.app_title; url = c.app_url; update(); } void update(void) { bool dummy; auto posts = list_posts(0, feed_length, dummy); tinyxml2::XMLDocument doc; auto dec = doc.NewDeclaration(); auto root = doc.NewElement("feed"); root->SetAttribute("xmlns", "http://www.w3.org/2005/Atom"); auto id_e = doc.NewElement("id"); id_e->SetText(url.c_str()); root->InsertEndChild(id_e); auto title_e = doc.NewElement("title"); title_e->SetText(title.c_str()); root->InsertEndChild(title_e); auto link_e = doc.NewElement("link"); link_e->SetAttribute("href", url.c_str()); root->InsertEndChild(link_e); auto dur = std::chrono::system_clock::now().time_since_epoch(); auto durStr = generate_rfc3999(std::chrono::duration_cast<std::chrono::milliseconds>(dur).count()); auto updated_e = doc.NewElement("updated"); updated_e->SetText(durStr.c_str()); root->InsertEndChild(updated_e); for(auto i = posts.begin(); i != posts.end(); ++i) { auto entry_e = doc.NewElement("entry"); auto entry_id_e = doc.NewElement("id"); entry_id_e->SetText((url + "[" + std::to_string(i->post_time) + "]").c_str()); entry_e->InsertEndChild(entry_id_e); auto entry_title_e = doc.NewElement("title"); entry_title_e->SetText(i->topic.c_str()); entry_e->InsertEndChild(entry_title_e); auto entry_updated_e = doc.NewElement("updated"); entry_updated_e->SetText(generate_rfc3999(i->update_time).c_str()); entry_e->InsertEndChild(entry_updated_e); auto entry_link_e = doc.NewElement("link"); entry_link_e->SetAttribute("href", (url + "/" + i->url).c_str()); entry_link_e->SetAttribute("rel", "alternative"); entry_e->InsertEndChild(entry_link_e); root->InsertEndChild(entry_e); } doc.InsertEndChild(dec); doc.InsertEndChild(root); tinyxml2::XMLPrinter printer(NULL, true, 0); doc.Print(&printer); feed_str = printer.CStr(); } std::string fetch(void) { return feed_str; } } } <commit_msg>Fixed: monthes in feeds are counted from Janurary<commit_after>#include <tinyxml2.h> #include <chrono> #include <sstream> #include <ctime> #include "feed.h" #include "storage.h" namespace C3 { namespace Feed { std::string feed_str = ""; uint16_t feed_length; std::string title; std::string url; std::string generate_rfc3999(uint64_t ms_since_epoch) { std::chrono::milliseconds duration(ms_since_epoch); std::chrono::time_point<std::chrono::system_clock> point(duration); time_t tt = std::chrono::system_clock::to_time_t(point); std::tm *cal = gmtime(&tt); std::stringstream ss; ss<<cal->tm_year + 1900<<'-'<<cal->tm_mon + 1<<'-'<<cal->tm_mday<<'T'<<cal->tm_hour<<':'<<cal->tm_min<<':'<<cal->tm_sec<<'Z'; return ss.str(); } void setup(const Config &c) { feed_length = c.app_feedLength; title = c.app_title; url = c.app_url; update(); } void update(void) { bool dummy; auto posts = list_posts(0, feed_length, dummy); tinyxml2::XMLDocument doc; auto dec = doc.NewDeclaration(); auto root = doc.NewElement("feed"); root->SetAttribute("xmlns", "http://www.w3.org/2005/Atom"); auto id_e = doc.NewElement("id"); id_e->SetText(url.c_str()); root->InsertEndChild(id_e); auto title_e = doc.NewElement("title"); title_e->SetText(title.c_str()); root->InsertEndChild(title_e); auto link_e = doc.NewElement("link"); link_e->SetAttribute("href", url.c_str()); root->InsertEndChild(link_e); auto dur = std::chrono::system_clock::now().time_since_epoch(); auto durStr = generate_rfc3999(std::chrono::duration_cast<std::chrono::milliseconds>(dur).count()); auto updated_e = doc.NewElement("updated"); updated_e->SetText(durStr.c_str()); root->InsertEndChild(updated_e); for(auto i = posts.begin(); i != posts.end(); ++i) { auto entry_e = doc.NewElement("entry"); auto entry_id_e = doc.NewElement("id"); entry_id_e->SetText((url + "[" + std::to_string(i->post_time) + "]").c_str()); entry_e->InsertEndChild(entry_id_e); auto entry_title_e = doc.NewElement("title"); entry_title_e->SetText(i->topic.c_str()); entry_e->InsertEndChild(entry_title_e); auto entry_updated_e = doc.NewElement("updated"); entry_updated_e->SetText(generate_rfc3999(i->update_time).c_str()); entry_e->InsertEndChild(entry_updated_e); auto entry_link_e = doc.NewElement("link"); entry_link_e->SetAttribute("href", (url + "/" + i->url).c_str()); entry_link_e->SetAttribute("rel", "alternative"); entry_e->InsertEndChild(entry_link_e); root->InsertEndChild(entry_e); } doc.InsertEndChild(dec); doc.InsertEndChild(root); tinyxml2::XMLPrinter printer(NULL, true, 0); doc.Print(&printer); feed_str = printer.CStr(); } std::string fetch(void) { return feed_str; } } } <|endoftext|>
<commit_before>// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/InputConversion/MHLO/Passes.h" #include "iree/compiler/Dialect/Util/Transforms/Passes.h" #include "iree/compiler/InputConversion/Common/Passes.h" #include "mhlo/transforms/passes.h" #include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h" #include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h" #include "mlir/Conversion/ShapeToStandard/ShapeToStandard.h" #include "mlir/Dialect/SCF/Transforms/Passes.h" #include "mlir/Dialect/Shape/Transforms/Passes.h" #include "mlir/Pass/PassManager.h" #include "mlir/Pass/PassOptions.h" #include "mlir/Pass/PassRegistry.h" #include "mlir/Transforms/Passes.h" namespace mlir { namespace iree_compiler { namespace MHLO { // TODO(#8745): remove these flags when the -iree-flow-demote-* flags can be // used without tripping upstream verifier issues. static llvm::cl::opt<bool> clDemoteI64ToI32( "iree-mhlo-demote-i64-to-i32", llvm::cl::desc( "Converts all MHLO i64 ops and values into i32 counterparts."), llvm::cl::init(true)); static llvm::cl::opt<bool> clDemoteF64ToF32( "iree-mhlo-demote-f64-to-f32", llvm::cl::desc( "Converts all MHLO f64 ops and values into f32 counterparts."), llvm::cl::init(true)); void registerMHLOConversionPassPipeline() { PassPipelineRegistration<> mhlo( "iree-mhlo-input-transformation-pipeline", "Runs the MHLO IREE flow dialect transformation pipeline", [](OpPassManager &passManager) { buildMHLOInputConversionPassPipeline(passManager); }); PassPipelineRegistration<> xla("iree-mhlo-xla-cleanup-pipeline", "Runs the post-XLA import cleanup pipeline", [](OpPassManager &passManager) { buildXLACleanupPassPipeline(passManager); }); } // Prepare HLO for use as an input to the Flow dialect. void buildMHLOInputConversionPassPipeline(OpPassManager &passManager) { passManager.addPass(mlir::mhlo::createStablehloLegalizeToHloPass()); passManager.addNestedPass<func::FuncOp>( mhlo::createLegalizeControlFlowPass()); // Currently we don't handle SCF ops well and have to convert them all to CFG. // In the future it would be nice if we could have all of flow be both scf // and cfg compatible. passManager.addNestedPass<func::FuncOp>(createTopLevelSCFToCFGPass()); passManager.addNestedPass<func::FuncOp>(createMHLOToMHLOPreprocessingPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); // Various shape functions may have been materialized in the `shape.shape_of` // style of treating shapes as tensors. We prefer to legalize these to // scalar ops as early as possible to avoid having them persist as tensor // computations. passManager.addNestedPass<func::FuncOp>(createShapeToShapeLowering()); passManager.addPass(createConvertShapeToStandardPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); // We also don't handle calls well on the old codepath; until we remove the // use of the CFG we can continue inlining. passManager.addPass(mlir::createInlinerPass()); // Hacky type conversion to work around lack of type support lower in the // stack. This is often required because of implicit i64 insertion by JAX/HLO // that we don't want forcing 32-bit embedded devices to support. // TODO(#8745): remove these and prefer the flow pipeline options instead. if (clDemoteI64ToI32) { passManager.addPass(IREE::Util::createDemoteI64ToI32Pass()); } if (clDemoteF64ToF32) { passManager.addPass(IREE::Util::createDemoteF64ToF32Pass()); } // Perform initial cleanup. createLegalizeInputTypes could rewrite types. In // this context, some operations could be folded away. passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCSEPass()); // Convert to Linalg. After this point, MHLO will be eliminated. passManager.addNestedPass<func::FuncOp>( mhlo::createLegalizeShapeComputationsPass()); passManager.addNestedPass<func::FuncOp>(createConvertMHLOToLinalgExtPass()); passManager.addPass(createMHLOToLinalgOnTensorsPass()); // Ensure conversion completed. passManager.addPass(createReconcileUnrealizedCastsPass()); // Note that some MHLO ops are left by the above and must resolve via // canonicalization. See comments in the above pass and find a better way. passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); //---------------------------------------------------------------------------- // Entry dialect cleanup //---------------------------------------------------------------------------- passManager.addPass(createVerifyCompilerMHLOInputLegality()); } void buildXLACleanupPassPipeline(OpPassManager &passManager) { passManager.addNestedPass<func::FuncOp>( mhlo::createLegalizeControlFlowPass()); passManager.addPass(createFlattenTuplesInCFGPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); } namespace { #define GEN_PASS_REGISTRATION #include "iree/compiler/InputConversion/MHLO/Passes.h.inc" // IWYU pragma: export } // namespace void registerMHLOConversionPasses() { // Generated. registerPasses(); // Pipelines. registerMHLOConversionPassPipeline(); } } // namespace MHLO } // namespace iree_compiler } // namespace mlir <commit_msg>Add missing canonicalize pass on import (#11181)<commit_after>// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/InputConversion/MHLO/Passes.h" #include "iree/compiler/Dialect/Util/Transforms/Passes.h" #include "iree/compiler/InputConversion/Common/Passes.h" #include "mhlo/transforms/passes.h" #include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h" #include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h" #include "mlir/Conversion/ShapeToStandard/ShapeToStandard.h" #include "mlir/Dialect/SCF/Transforms/Passes.h" #include "mlir/Dialect/Shape/Transforms/Passes.h" #include "mlir/Pass/PassManager.h" #include "mlir/Pass/PassOptions.h" #include "mlir/Pass/PassRegistry.h" #include "mlir/Transforms/Passes.h" namespace mlir { namespace iree_compiler { namespace MHLO { // TODO(#8745): remove these flags when the -iree-flow-demote-* flags can be // used without tripping upstream verifier issues. static llvm::cl::opt<bool> clDemoteI64ToI32( "iree-mhlo-demote-i64-to-i32", llvm::cl::desc( "Converts all MHLO i64 ops and values into i32 counterparts."), llvm::cl::init(true)); static llvm::cl::opt<bool> clDemoteF64ToF32( "iree-mhlo-demote-f64-to-f32", llvm::cl::desc( "Converts all MHLO f64 ops and values into f32 counterparts."), llvm::cl::init(true)); void registerMHLOConversionPassPipeline() { PassPipelineRegistration<> mhlo( "iree-mhlo-input-transformation-pipeline", "Runs the MHLO IREE flow dialect transformation pipeline", [](OpPassManager &passManager) { buildMHLOInputConversionPassPipeline(passManager); }); PassPipelineRegistration<> xla("iree-mhlo-xla-cleanup-pipeline", "Runs the post-XLA import cleanup pipeline", [](OpPassManager &passManager) { buildXLACleanupPassPipeline(passManager); }); } // Prepare HLO for use as an input to the Flow dialect. void buildMHLOInputConversionPassPipeline(OpPassManager &passManager) { passManager.addPass(mlir::mhlo::createStablehloLegalizeToHloPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); passManager.addNestedPass<func::FuncOp>( mhlo::createLegalizeControlFlowPass()); // Currently we don't handle SCF ops well and have to convert them all to CFG. // In the future it would be nice if we could have all of flow be both scf // and cfg compatible. passManager.addNestedPass<func::FuncOp>(createTopLevelSCFToCFGPass()); passManager.addNestedPass<func::FuncOp>(createMHLOToMHLOPreprocessingPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); // Various shape functions may have been materialized in the `shape.shape_of` // style of treating shapes as tensors. We prefer to legalize these to // scalar ops as early as possible to avoid having them persist as tensor // computations. passManager.addNestedPass<func::FuncOp>(createShapeToShapeLowering()); passManager.addPass(createConvertShapeToStandardPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); // We also don't handle calls well on the old codepath; until we remove the // use of the CFG we can continue inlining. passManager.addPass(mlir::createInlinerPass()); // Hacky type conversion to work around lack of type support lower in the // stack. This is often required because of implicit i64 insertion by JAX/HLO // that we don't want forcing 32-bit embedded devices to support. // TODO(#8745): remove these and prefer the flow pipeline options instead. if (clDemoteI64ToI32) { passManager.addPass(IREE::Util::createDemoteI64ToI32Pass()); } if (clDemoteF64ToF32) { passManager.addPass(IREE::Util::createDemoteF64ToF32Pass()); } // Perform initial cleanup. createLegalizeInputTypes could rewrite types. In // this context, some operations could be folded away. passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCSEPass()); // Convert to Linalg. After this point, MHLO will be eliminated. passManager.addNestedPass<func::FuncOp>( mhlo::createLegalizeShapeComputationsPass()); passManager.addNestedPass<func::FuncOp>(createConvertMHLOToLinalgExtPass()); passManager.addPass(createMHLOToLinalgOnTensorsPass()); // Ensure conversion completed. passManager.addPass(createReconcileUnrealizedCastsPass()); // Note that some MHLO ops are left by the above and must resolve via // canonicalization. See comments in the above pass and find a better way. passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); //---------------------------------------------------------------------------- // Entry dialect cleanup //---------------------------------------------------------------------------- passManager.addPass(createVerifyCompilerMHLOInputLegality()); } void buildXLACleanupPassPipeline(OpPassManager &passManager) { passManager.addNestedPass<func::FuncOp>( mhlo::createLegalizeControlFlowPass()); passManager.addPass(createFlattenTuplesInCFGPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); } namespace { #define GEN_PASS_REGISTRATION #include "iree/compiler/InputConversion/MHLO/Passes.h.inc" // IWYU pragma: export } // namespace void registerMHLOConversionPasses() { // Generated. registerPasses(); // Pipelines. registerMHLOConversionPassPipeline(); } } // namespace MHLO } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_ENETPACKET_HPP #define NAZARA_ENETPACKET_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Network/NetPacket.hpp> namespace Nz { enum ENetPacketFlag { ENetPacketFlag_NoAllocate, ENetPacketFlag_Reliable, ENetPacketFlag_Unsequenced, ENetPacketFlag_UnreliableFragment, ENetPacketFlag_Sent }; template<> struct EnumAsFlags<ENetPacketFlag> { static constexpr bool value = true; static constexpr int max = ENetPacketFlag_Sent; }; using ENetPacketFlags = Flags<ENetPacketFlag>; class MemoryPool; struct ENetPacket { MemoryPool* owner; ENetPacketFlags flags; NetPacket data; std::size_t referenceCount = 0; }; struct NAZARA_NETWORK_API ENetPacketRef { ENetPacketRef() = default; ENetPacketRef(ENetPacket* packet) { Reset(packet); } ENetPacketRef(const ENetPacketRef& packet) : ENetPacketRef() { Reset(packet); } ENetPacketRef(ENetPacketRef&& packet) : m_packet(packet.m_packet) { packet.m_packet = nullptr; } ~ENetPacketRef() { Reset(); } void Reset(ENetPacket* packet = nullptr); operator ENetPacket*() const { return m_packet; } ENetPacket* operator->() const { return m_packet; } ENetPacketRef& operator=(ENetPacket* packet) { Reset(packet); return *this; } ENetPacketRef& operator=(const ENetPacketRef& packet) { Reset(packet); return *this; } ENetPacketRef& operator=(ENetPacketRef&& packet) { m_packet = packet.m_packet; packet.m_packet = nullptr; return *this; } ENetPacket* m_packet = nullptr; }; } #endif // NAZARA_ENETPACKET_HPP <commit_msg>Network/ENetPacket: Remove unused flags<commit_after>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_ENETPACKET_HPP #define NAZARA_ENETPACKET_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Network/NetPacket.hpp> namespace Nz { enum ENetPacketFlag { ENetPacketFlag_Reliable, ENetPacketFlag_Unsequenced, ENetPacketFlag_UnreliableFragment }; template<> struct EnumAsFlags<ENetPacketFlag> { static constexpr bool value = true; static constexpr int max = ENetPacketFlag_UnreliableFragment; }; using ENetPacketFlags = Flags<ENetPacketFlag>; class MemoryPool; struct ENetPacket { MemoryPool* owner; ENetPacketFlags flags; NetPacket data; std::size_t referenceCount = 0; }; struct NAZARA_NETWORK_API ENetPacketRef { ENetPacketRef() = default; ENetPacketRef(ENetPacket* packet) { Reset(packet); } ENetPacketRef(const ENetPacketRef& packet) : ENetPacketRef() { Reset(packet); } ENetPacketRef(ENetPacketRef&& packet) : m_packet(packet.m_packet) { packet.m_packet = nullptr; } ~ENetPacketRef() { Reset(); } void Reset(ENetPacket* packet = nullptr); operator ENetPacket*() const { return m_packet; } ENetPacket* operator->() const { return m_packet; } ENetPacketRef& operator=(ENetPacket* packet) { Reset(packet); return *this; } ENetPacketRef& operator=(const ENetPacketRef& packet) { Reset(packet); return *this; } ENetPacketRef& operator=(ENetPacketRef&& packet) { m_packet = packet.m_packet; packet.m_packet = nullptr; return *this; } ENetPacket* m_packet = nullptr; }; } #endif // NAZARA_ENETPACKET_HPP <|endoftext|>
<commit_before>#include <assert.h> #include <vector> #include <iostream> #include <iomanip> #include <algorithm> #include <functional> #include "helpers.hpp" //============================================================================== int main(int /*argc*/, char** /*argv*/) { try { int length = 10; std::uint8_t pixels_8u[length]; std::uint16_t pixels_16u[length]; memset(pixels_8u, 1, length*sizeof(std::uint8_t)); memset(pixels_16u, 1, length*sizeof(std::uint16_t)); std::cout << "using memset:" << std::endl; for (auto px : pixels_8u) { std::cout << static_cast<std::int32_t>(px) << " "; } std::cout << std::endl; for (auto px : pixels_16u) { std::cout << static_cast<std::int32_t>(px) << " "; } std::cout << std::endl << std::endl; // use std::fill std::fill(pixels_8u, pixels_8u+length, 1); std::fill(pixels_16u, pixels_16u+length, 1); std::cout << "using std::fill:" << std::endl; for (auto px : pixels_8u) { std::cout << static_cast<std::int32_t>(px) << " "; } std::cout << std::endl; for (auto px : pixels_16u) { std::cout << static_cast<std::int32_t>(px) << " "; } std::cout << std::endl; } catch (std::exception& e) { std::cout << "[exception] " << e.what() << std::endl; assert(false); } return EXIT_SUCCESS; } <commit_msg>added array demo<commit_after>#include <assert.h> #include <vector> #include <iostream> #include <iomanip> #include <algorithm> #include <functional> #include <array> #include "helpers.hpp" //============================================================================== int main(int /*argc*/, char** /*argv*/) { try { const int length = 10; std::uint8_t pixels_8u[length]; std::uint16_t pixels_16u[length]; //-------------------------------------------------------------------------- memset(pixels_8u, 1, length*sizeof(std::uint8_t)); memset(pixels_16u, 1, length*sizeof(std::uint16_t)); std::cout << "using memset:" << std::endl; for (auto px : pixels_8u) { std::cout << static_cast<std::int32_t>(px) << " "; } std::cout << std::endl; for (auto px : pixels_16u) { std::cout << static_cast<std::int32_t>(px) << " "; } std::cout << std::endl << std::endl; //-------------------------------------------------------------------------- // use std::fill std::fill(pixels_8u, pixels_8u+length, 1); std::fill(pixels_16u, pixels_16u+length, 1); std::cout << "using std::fill:" << std::endl; for (auto px : pixels_8u) { std::cout << static_cast<std::int32_t>(px) << " "; } std::cout << std::endl; for (auto px : pixels_16u) { std::cout << static_cast<std::int32_t>(px) << " "; } std::cout << std::endl << std::endl; //-------------------------------------------------------------------------- // you know about array? std::array<std::uint8_t, length> arr; std::fill(arr.begin(), arr.end(), 128); std::cout << "array:" << std::endl; for (const auto& v : arr) { std::cout << static_cast<int>(v) << ' '; } std::cout << std::endl << std::endl; } catch (std::exception& e) { std::cout << "[exception] " << e.what() << std::endl; assert(false); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before> /* /~` _ _ _|_. _ _ |_ | _ \_,(_)| | | || ||_|(_||_)|(/_ https://github.com/Naios/continuable v3.0.0 Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com> 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. **/ #ifndef CONTINUABLE_DETAIL_TRAITS_HPP_INCLUDED #define CONTINUABLE_DETAIL_TRAITS_HPP_INCLUDED #include <cstdint> #include <tuple> #include <type_traits> #include <utility> #include <continuable/detail/features.hpp> namespace cti { namespace detail { namespace traits { namespace detail { template <typename T, typename... Args> struct index_of_impl; template <typename T, typename... Args> struct index_of_impl<T, T, Args...> : std::integral_constant<std::size_t, 0U> { }; template <typename T, typename U, typename... Args> struct index_of_impl<T, U, Args...> : std::integral_constant<std::size_t, 1 + index_of_impl<T, Args...>::value> {}; } // namespace detail /// Evaluates to the index of T in the given pack template <typename T, typename... Args> using index_of_t = detail::index_of_impl<T, Args...>; /// A tagging type for wrapping other types template <typename... T> struct identity {}; template <typename> struct is_identity : std::false_type {}; template <typename... Args> struct is_identity<identity<Args...>> : std::true_type {}; template <typename T> using identify = std::conditional_t<is_identity<std::decay_t<T>>::value, T, identity<std::decay_t<T>>>; #if defined(CONTINUABLE_HAS_CXX17_VOID_T) using std::void_t; #else namespace detail { // Equivalent to C++17's std::void_t which targets a bug in GCC, // that prevents correct SFINAE behavior. // See http://stackoverflow.com/questions/35753920 for details. template <typename...> struct deduce_to_void : std::common_type<void> {}; } // namespace detail /// C++17 like void_t type template <typename... T> using void_t = typename detail::deduce_to_void<T...>::type; #endif // CONTINUABLE_HAS_CXX17_VOID_T namespace detail { template <typename Type, typename TrueCallback> constexpr void static_if_impl(std::true_type, Type&& type, TrueCallback&& trueCallback) { std::forward<TrueCallback>(trueCallback)(std::forward<Type>(type)); } template <typename Type, typename TrueCallback> constexpr void static_if_impl(std::false_type, Type&& /*type*/, TrueCallback&& /*trueCallback*/) { } template <typename Type, typename TrueCallback, typename FalseCallback> constexpr auto static_if_impl(std::true_type, Type&& type, TrueCallback&& trueCallback, FalseCallback&& /*falseCallback*/) { return std::forward<TrueCallback>(trueCallback)(std::forward<Type>(type)); } template <typename Type, typename TrueCallback, typename FalseCallback> constexpr auto static_if_impl(std::false_type, Type&& type, TrueCallback&& /*trueCallback*/, FalseCallback&& falseCallback) { return std::forward<FalseCallback>(falseCallback)(std::forward<Type>(type)); } /// Evaluates to the size of the given tuple like type, // / if the type has no static size it will be one. template <typename T, typename Enable = void> struct tuple_like_size : std::integral_constant<std::size_t, 1U> {}; template <typename T> struct tuple_like_size<T, void_t<decltype(std::tuple_size<T>::value)>> : std::tuple_size<T> {}; } // namespace detail /// Returns the pack size of the given empty pack constexpr std::size_t pack_size_of(identity<>) noexcept { return 0U; } /// Returns the pack size of the given type template <typename T> constexpr std::size_t pack_size_of(identity<T>) noexcept { return detail::tuple_like_size<T>::value; } /// Returns the pack size of the given type template <typename First, typename Second, typename... Args> constexpr std::size_t pack_size_of(identity<First, Second, Args...>) noexcept { return 2U + sizeof...(Args); } /// Returns an index sequence of the given type template <typename T> constexpr auto sequence_of(identity<T>) noexcept { constexpr auto const size = pack_size_of(identity<T>{}); return std::make_index_sequence<size>(); } /// Invokes the callback only if the given type matches the check template <typename Type, typename Check, typename TrueCallback> constexpr void static_if(Type&& type, Check&& check, TrueCallback&& trueCallback) { detail::static_if_impl(std::forward<Check>(check)(type), std::forward<Type>(type), std::forward<TrueCallback>(trueCallback)); } /// Invokes the callback only if the given type matches the check template <typename Type, typename Check, typename TrueCallback, typename FalseCallback> constexpr auto static_if(Type&& type, Check&& check, TrueCallback&& trueCallback, FalseCallback&& falseCallback) { return detail::static_if_impl(std::forward<Check>(check)(type), std::forward<Type>(type), std::forward<TrueCallback>(trueCallback), std::forward<FalseCallback>(falseCallback)); } namespace detail { /// Calls the given unpacker with the content of the given sequenceable template <typename U, typename F, std::size_t... I> constexpr auto unpack_impl(U&& unpacker, F&& first_sequenceable, std::integer_sequence<std::size_t, I...>) -> decltype(std::forward<U>(unpacker)( std::get<I>(std::forward<F>(first_sequenceable))...)) { (void)first_sequenceable; return std::forward<U>(unpacker)( std::get<I>(std::forward<F>(first_sequenceable))...); } } // namespace detail /// Calls the given callable object with the content of the given sequenceable /// /// \note We can't use std::apply here since this implementation is SFINAE /// aware and the std version not! This would lead to compilation errors. template <typename Callable, typename TupleLike, typename Sequence = std::make_index_sequence< std::tuple_size<std::decay_t<TupleLike>>::value>> constexpr auto unpack(Callable&& obj, TupleLike&& tuple_like) -> decltype(detail::unpack_impl(std::forward<Callable>(obj), std::forward<TupleLike>(tuple_like), Sequence{})) { return detail::unpack_impl(std::forward<Callable>(obj), std::forward<TupleLike>(tuple_like), Sequence{}); } namespace detail { template <typename T, typename Args, typename = traits::void_t<>> struct is_invokable_impl : std::common_type<std::false_type> {}; template <typename T, typename... Args> struct is_invokable_impl< T, std::tuple<Args...>, void_t<decltype(std::declval<T>()(std::declval<Args>()...))>> : std::common_type<std::true_type> {}; } // namespace detail /// Deduces to a std::true_type if the given type is callable with the arguments /// inside the given tuple. /// The main reason for implementing it with the detection idiom instead of /// hana like detection is that MSVC has issues with capturing raw template /// arguments inside lambda closures. /// /// ```cpp /// traits::is_invokable<object, std::tuple<Args...>> /// ``` template <typename T, typename Args> using is_invokable_from_tuple = typename detail::is_invokable_impl<T, Args>::type; // Checks whether the given callable object is invocable with the given // arguments. This doesn't take member functions into account! template <typename T, typename... Args> using is_invocable = is_invokable_from_tuple<T, std::tuple<Args...>>; /// Deduces to a std::false_type template <typename T> using fail = std::integral_constant<bool, !std::is_same<T, T>::value>; #ifdef CONTINUABLE_HAS_CXX17_DISJUNCTION using std::disjunction; #else namespace detail { /// Declares a C++14 polyfill for C++17 std::disjunction. template <typename Args, typename = void_t<>> struct disjunction_impl : std::common_type<std::true_type> {}; template <typename... Args> struct disjunction_impl<identity<Args...>, void_t<std::enable_if_t<!bool(Args::value)>...>> : std::common_type<std::false_type> {}; } // namespace detail template <typename... Args> using disjunction = typename detail::disjunction_impl<identity<Args...>>::type; #endif // CONTINUABLE_HAS_CXX17_DISJUNCTION #ifdef CONTINUABLE_HAS_CXX17_CONJUNCTION using std::conjunction; #else namespace detail { /// Declares a C++14 polyfill for C++17 std::conjunction. template <typename Args, typename = void_t<>> struct conjunction_impl : std::common_type<std::false_type> {}; template <typename... Args> struct conjunction_impl<identity<Args...>, void_t<std::enable_if_t<bool(Args::value)>...>> : std::common_type<std::true_type> {}; } // namespace detail template <typename... Args> using conjunction = typename detail::conjunction_impl<identity<Args...>>::type; #endif // CONTINUABLE_HAS_CXX17_CONJUNCTION } // namespace traits } // namespace detail } // namespace cti #endif // CONTINUABLE_DETAIL_TRAITS_HPP_INCLUDED <commit_msg>Remove unused static_if<commit_after> /* /~` _ _ _|_. _ _ |_ | _ \_,(_)| | | || ||_|(_||_)|(/_ https://github.com/Naios/continuable v3.0.0 Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com> 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. **/ #ifndef CONTINUABLE_DETAIL_TRAITS_HPP_INCLUDED #define CONTINUABLE_DETAIL_TRAITS_HPP_INCLUDED #include <cstdint> #include <tuple> #include <type_traits> #include <utility> #include <continuable/detail/features.hpp> namespace cti { namespace detail { namespace traits { namespace detail { template <typename T, typename... Args> struct index_of_impl; template <typename T, typename... Args> struct index_of_impl<T, T, Args...> : std::integral_constant<std::size_t, 0U> { }; template <typename T, typename U, typename... Args> struct index_of_impl<T, U, Args...> : std::integral_constant<std::size_t, 1 + index_of_impl<T, Args...>::value> {}; } // namespace detail /// Evaluates to the index of T in the given pack template <typename T, typename... Args> using index_of_t = detail::index_of_impl<T, Args...>; /// A tagging type for wrapping other types template <typename... T> struct identity {}; template <typename> struct is_identity : std::false_type {}; template <typename... Args> struct is_identity<identity<Args...>> : std::true_type {}; template <typename T> using identify = std::conditional_t<is_identity<std::decay_t<T>>::value, T, identity<std::decay_t<T>>>; #if defined(CONTINUABLE_HAS_CXX17_VOID_T) using std::void_t; #else namespace detail { // Equivalent to C++17's std::void_t which targets a bug in GCC, // that prevents correct SFINAE behavior. // See http://stackoverflow.com/questions/35753920 for details. template <typename...> struct deduce_to_void : std::common_type<void> {}; } // namespace detail /// C++17 like void_t type template <typename... T> using void_t = typename detail::deduce_to_void<T...>::type; #endif // CONTINUABLE_HAS_CXX17_VOID_T namespace detail { /// Evaluates to the size of the given tuple like type, // / if the type has no static size it will be one. template <typename T, typename Enable = void> struct tuple_like_size : std::integral_constant<std::size_t, 1U> {}; template <typename T> struct tuple_like_size<T, void_t<decltype(std::tuple_size<T>::value)>> : std::tuple_size<T> {}; } // namespace detail /// Returns the pack size of the given empty pack constexpr std::size_t pack_size_of(identity<>) noexcept { return 0U; } /// Returns the pack size of the given type template <typename T> constexpr std::size_t pack_size_of(identity<T>) noexcept { return detail::tuple_like_size<T>::value; } /// Returns the pack size of the given type template <typename First, typename Second, typename... Args> constexpr std::size_t pack_size_of(identity<First, Second, Args...>) noexcept { return 2U + sizeof...(Args); } /// Returns an index sequence of the given type template <typename T> constexpr auto sequence_of(identity<T>) noexcept { constexpr auto const size = pack_size_of(identity<T>{}); return std::make_index_sequence<size>(); } namespace detail { /// Calls the given unpacker with the content of the given sequenceable template <typename U, typename F, std::size_t... I> constexpr auto unpack_impl(U&& unpacker, F&& first_sequenceable, std::integer_sequence<std::size_t, I...>) -> decltype(std::forward<U>(unpacker)( std::get<I>(std::forward<F>(first_sequenceable))...)) { (void)first_sequenceable; return std::forward<U>(unpacker)( std::get<I>(std::forward<F>(first_sequenceable))...); } } // namespace detail /// Calls the given callable object with the content of the given sequenceable /// /// \note We can't use std::apply here since this implementation is SFINAE /// aware and the std version not! This would lead to compilation errors. template <typename Callable, typename TupleLike, typename Sequence = std::make_index_sequence< std::tuple_size<std::decay_t<TupleLike>>::value>> constexpr auto unpack(Callable&& obj, TupleLike&& tuple_like) -> decltype(detail::unpack_impl(std::forward<Callable>(obj), std::forward<TupleLike>(tuple_like), Sequence{})) { return detail::unpack_impl(std::forward<Callable>(obj), std::forward<TupleLike>(tuple_like), Sequence{}); } namespace detail { template <typename T, typename Args, typename = traits::void_t<>> struct is_invokable_impl : std::common_type<std::false_type> {}; template <typename T, typename... Args> struct is_invokable_impl< T, std::tuple<Args...>, void_t<decltype(std::declval<T>()(std::declval<Args>()...))>> : std::common_type<std::true_type> {}; } // namespace detail /// Deduces to a std::true_type if the given type is callable with the arguments /// inside the given tuple. /// The main reason for implementing it with the detection idiom instead of /// hana like detection is that MSVC has issues with capturing raw template /// arguments inside lambda closures. /// /// ```cpp /// traits::is_invokable<object, std::tuple<Args...>> /// ``` template <typename T, typename Args> using is_invokable_from_tuple = typename detail::is_invokable_impl<T, Args>::type; // Checks whether the given callable object is invocable with the given // arguments. This doesn't take member functions into account! template <typename T, typename... Args> using is_invocable = is_invokable_from_tuple<T, std::tuple<Args...>>; /// Deduces to a std::false_type template <typename T> using fail = std::integral_constant<bool, !std::is_same<T, T>::value>; #ifdef CONTINUABLE_HAS_CXX17_DISJUNCTION using std::disjunction; #else namespace detail { /// Declares a C++14 polyfill for C++17 std::disjunction. template <typename Args, typename = void_t<>> struct disjunction_impl : std::common_type<std::true_type> {}; template <typename... Args> struct disjunction_impl<identity<Args...>, void_t<std::enable_if_t<!bool(Args::value)>...>> : std::common_type<std::false_type> {}; } // namespace detail template <typename... Args> using disjunction = typename detail::disjunction_impl<identity<Args...>>::type; #endif // CONTINUABLE_HAS_CXX17_DISJUNCTION #ifdef CONTINUABLE_HAS_CXX17_CONJUNCTION using std::conjunction; #else namespace detail { /// Declares a C++14 polyfill for C++17 std::conjunction. template <typename Args, typename = void_t<>> struct conjunction_impl : std::common_type<std::false_type> {}; template <typename... Args> struct conjunction_impl<identity<Args...>, void_t<std::enable_if_t<bool(Args::value)>...>> : std::common_type<std::true_type> {}; } // namespace detail template <typename... Args> using conjunction = typename detail::conjunction_impl<identity<Args...>>::type; #endif // CONTINUABLE_HAS_CXX17_CONJUNCTION } // namespace traits } // namespace detail } // namespace cti #endif // CONTINUABLE_DETAIL_TRAITS_HPP_INCLUDED <|endoftext|>
<commit_before>// (c) Mathias Panzenböck // http://github.com/panzi/mathfun/blob/master/examples/portable_endian.h // #pragma once #if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__) # define __WINDOWS__ #endif #if defined(__linux__) || defined(__CYGWIN__) # include <endian.h> #elif defined(__APPLE__) # include <machine/endian.h> # include <libkern/OSByteOrder.h> # define htobe16 OSSwapHostToBigInt16 # define htole16 OSSwapHostToLittleInt16 # define be16toh OSSwapBigToHostInt16 # define le16toh OSSwapLittleToHostInt16 # define htobe32 OSSwapHostToBigInt32 # define htole32 OSSwapHostToLittleInt32 # define be32toh OSSwapBigToHostInt32 # define le32toh OSSwapLittleToHostInt32 # define htobe64 OSSwapHostToBigInt64 # define htole64 OSSwapHostToLittleInt64 # define be64toh OSSwapBigToHostInt64 # define le64toh OSSwapLittleToHostInt64 /** # define __BYTE_ORDER BYTE_ORDER # define __BIG_ENDIAN BIG_ENDIAN # define __LITTLE_ENDIAN LITTLE_ENDIAN # define __PDP_ENDIAN PDP_ENDIAN **/ #elif defined(__OpenBSD__) # include <sys/endian.h> #elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) # include <sys/endian.h> # define be16toh betoh16 # define le16toh letoh16 # define be32toh betoh32 # define le32toh letoh32 # define be64toh betoh64 # define le64toh letoh64 #elif defined(__FreeBSD_kernel__) # include <endian.h> #elif defined(__WINDOWS__) # include <winsock2.h> # if BYTE_ORDER == LITTLE_ENDIAN # define htobe16 htons # define htole16(x) (x) # define be16toh ntohs # define le16toh(x) (x) # define htobe32 htonl # define htole32(x) (x) # define be32toh ntohl # define le32toh(x) (x) # define htobe64 htonll # define htole64(x) (x) # define be64toh ntohll # define le64toh(x) (x) # elif BYTE_ORDER == BIG_ENDIAN /* that would be xbox 360 */ # define htobe16(x) (x) # define htole16(x) __builtin_bswap16(x) # define be16toh(x) (x) # define le16toh(x) __builtin_bswap16(x) # define htobe32(x) (x) # define htole32(x) __builtin_bswap32(x) # define be32toh(x) (x) # define le32toh(x) __builtin_bswap32(x) # define htobe64(x) (x) # define htole64(x) __builtin_bswap64(x) # define be64toh(x) (x) # define le64toh(x) __builtin_bswap64(x) # else # error byte order not supported # endif # define __BYTE_ORDER BYTE_ORDER # define __BIG_ENDIAN BIG_ENDIAN # define __LITTLE_ENDIAN LITTLE_ENDIAN # define __PDP_ENDIAN PDP_ENDIAN #else # error platform not supported #endif <commit_msg>portable_endian: Remove wrong byte-order macro definitions for the BSDs.<commit_after>// (c) Mathias Panzenböck // http://github.com/panzi/mathfun/blob/master/examples/portable_endian.h // #pragma once #if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__) # define __WINDOWS__ #endif #if defined(__linux__) || defined(__CYGWIN__) # include <endian.h> #elif defined(__APPLE__) # include <machine/endian.h> # include <libkern/OSByteOrder.h> # define htobe16 OSSwapHostToBigInt16 # define htole16 OSSwapHostToLittleInt16 # define be16toh OSSwapBigToHostInt16 # define le16toh OSSwapLittleToHostInt16 # define htobe32 OSSwapHostToBigInt32 # define htole32 OSSwapHostToLittleInt32 # define be32toh OSSwapBigToHostInt32 # define le32toh OSSwapLittleToHostInt32 # define htobe64 OSSwapHostToBigInt64 # define htole64 OSSwapHostToLittleInt64 # define be64toh OSSwapBigToHostInt64 # define le64toh OSSwapLittleToHostInt64 /** # define __BYTE_ORDER BYTE_ORDER # define __BIG_ENDIAN BIG_ENDIAN # define __LITTLE_ENDIAN LITTLE_ENDIAN # define __PDP_ENDIAN PDP_ENDIAN **/ #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) # include <sys/endian.h> #elif defined(__FreeBSD_kernel__) # include <endian.h> #elif defined(__WINDOWS__) # include <winsock2.h> # if BYTE_ORDER == LITTLE_ENDIAN # define htobe16 htons # define htole16(x) (x) # define be16toh ntohs # define le16toh(x) (x) # define htobe32 htonl # define htole32(x) (x) # define be32toh ntohl # define le32toh(x) (x) # define htobe64 htonll # define htole64(x) (x) # define be64toh ntohll # define le64toh(x) (x) # elif BYTE_ORDER == BIG_ENDIAN /* that would be xbox 360 */ # define htobe16(x) (x) # define htole16(x) __builtin_bswap16(x) # define be16toh(x) (x) # define le16toh(x) __builtin_bswap16(x) # define htobe32(x) (x) # define htole32(x) __builtin_bswap32(x) # define be32toh(x) (x) # define le32toh(x) __builtin_bswap32(x) # define htobe64(x) (x) # define htole64(x) __builtin_bswap64(x) # define be64toh(x) (x) # define le64toh(x) __builtin_bswap64(x) # else # error byte order not supported # endif # define __BYTE_ORDER BYTE_ORDER # define __BIG_ENDIAN BIG_ENDIAN # define __LITTLE_ENDIAN LITTLE_ENDIAN # define __PDP_ENDIAN PDP_ENDIAN #else # error platform not supported #endif <|endoftext|>
<commit_before>#include "game.hpp" #include "exception.hpp" namespace Quoridor { // order in which pawns are adding // pawns rotates according to their indexes: 0 -> 1 -> 2 -> 3 -> 0 -> ... static const std::vector<int> pawn_idx_list = {0, 2, 1, 3}; Game::Game(int board_size) : board_size_(board_size), pawn_data_list_(), cur_pawn_idx_(-1), bg_(board_size_, board_size_), wg_(board_size_ + 1) { } Game::~Game() { } void Game::set_pawns(std::vector<std::shared_ptr<Pawn>> &pawn_list) { size_t pawn_num = pawn_list.size(); if ((pawn_num != 2) && (pawn_num != 4)) { throw Exception("Invalid number of players: " + std::to_string(pawn_num)); } for (size_t i = 0; i < pawn_list.size(); ++i) { pawn_data_t pawn_data; pawn_data.pawn = pawn_list[i]; pawn_data.idx = pawn_idx_list[i]; switch (pawn_data.idx) { case 0: pawn_data.node.set_row(0); pawn_data.node.set_col(board_size_ / 2); for (int j = 0; j < board_size_; ++j) { Node gn(board_size_ - 1, j); pawn_data.goal_nodes.insert(gn); } break; case 1: pawn_data.node.set_row(board_size_ / 2); pawn_data.node.set_col(0); for (int j = 0; j < board_size_; ++j) { Node gn(j, board_size_ - 1); pawn_data.goal_nodes.insert(gn); } break; case 2: pawn_data.node.set_row(board_size_ - 1); pawn_data.node.set_col(board_size_ / 2); for (int j = 0; j < board_size_; ++j) { Node gn(0, j); pawn_data.goal_nodes.insert(gn); } break; case 3: pawn_data.node.set_row(board_size_ / 2); pawn_data.node.set_col(board_size_ - 1); for (int j = 0; j < board_size_; ++j) { Node gn(j, 0); pawn_data.goal_nodes.insert(gn); } break; } pawn_data_list_.insert(pawn_data); } } void Game::switch_pawn() { auto it = pawn_data_list_.upper_bound(cur_pawn_idx_); if (it == pawn_data_list_.end()) { it = pawn_data_list_.begin(); } cur_pawn_idx_ = it->idx; } const pawn_data_t &Game::cur_pawn_data() const { return *pawn_data_list_.find(cur_pawn_idx_); } const pawn_data_list_t &Game::pawn_data_list() const { return pawn_data_list_; } const pawn_data_t &Game::pawn_data(std::shared_ptr<Pawn> &pawn) const { return *pawn_data_list_.get<by_pawn>().find(pawn); } int Game::move_pawn(const Node &node) { Node cur_node = pawn_data_list_.find(cur_pawn_idx_)->node; if (bg_.is_adjacent(cur_node, node)) { bg_.unblock_neighbours(cur_node); pawn_data_list_t::iterator it = pawn_data_list_.find(cur_pawn_idx_); pawn_data_t pawn_data = *it; pawn_data.node = node; pawn_data_list_.replace(it, pawn_data); bg_.block_neighbours(node); return 0; } else { return -1; } } int Game::add_wall(const Wall &wall) { std::vector<std::pair<Node, Node>> edges; if (try_add_wall(wall, &edges) < 0) { return -1; } wg_.apply_tmp_wall(); for (auto edge : edges) { bg_.remove_edges(edge.first, edge.second); } return 0; } int Game::try_add_wall(const Wall &wall, std::vector<std::pair<Node, Node>> *edges) { if (wg_.add_tmp_wall(wall) < 0) { return -1; } bg_.reset_filters(); Node node1; Node node2; Node node_tmp; if (wall.orientation() == Wall::kHorizontal) { for (int i = 0; i < wall.cnt(); ++i) { node1 = Node(wall.row() - 1, wall.col() + i); node2 = Node(wall.row(), wall.col() + i); bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = Node(wall.row() + 1, wall.col() + i); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() - 2, wall.col() + i); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = Node(wall.row(), wall.col() + j); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() - 1, wall.col() + j); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } else { for (int i = 0; i < wall.cnt(); ++i) { node1 = Node(wall.row() + i, wall.col() - 1); node2 = Node(wall.row() + i, wall.col()); bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = Node(wall.row() + i, wall.col() + 1); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() + i, wall.col() - 2); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = Node(wall.row() + j, wall.col()); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() + j, wall.col() - 1); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } bool path_blocked = false; for (auto pawn_data : pawn_data_list_) { path_blocked = true; for (auto goal_node : pawn_data.goal_nodes) { if (bg_.is_path_exists(pawn_data.node, goal_node)) { path_blocked = false; break; } } // wall blocks all pathes to the opposite side for one of pawns if (path_blocked) { break; } } if (path_blocked) { return -1; } return 0; } bool Game::is_finished() const { Node cur_node = pawn_data_list_.find(cur_pawn_idx_)->node; if (pawn_data_list_.find(cur_pawn_idx_)->goal_nodes.count(cur_node) != 0) { return true; } return false; } bool Game::get_path(std::shared_ptr<Pawn> pawn, const Node &node, std::list<Node> *path) const { return bg_.find_path(pawn_data(pawn).node, node, path); } } // namespace Quoridor <commit_msg>Check invalid wall in Game::try_add_wall<commit_after>#include "game.hpp" #include "exception.hpp" namespace Quoridor { // order in which pawns are adding // pawns rotates according to their indexes: 0 -> 1 -> 2 -> 3 -> 0 -> ... static const std::vector<int> pawn_idx_list = {0, 2, 1, 3}; Game::Game(int board_size) : board_size_(board_size), pawn_data_list_(), cur_pawn_idx_(-1), bg_(board_size_, board_size_), wg_(board_size_ + 1) { } Game::~Game() { } void Game::set_pawns(std::vector<std::shared_ptr<Pawn>> &pawn_list) { size_t pawn_num = pawn_list.size(); if ((pawn_num != 2) && (pawn_num != 4)) { throw Exception("Invalid number of players: " + std::to_string(pawn_num)); } for (size_t i = 0; i < pawn_list.size(); ++i) { pawn_data_t pawn_data; pawn_data.pawn = pawn_list[i]; pawn_data.idx = pawn_idx_list[i]; switch (pawn_data.idx) { case 0: pawn_data.node.set_row(0); pawn_data.node.set_col(board_size_ / 2); for (int j = 0; j < board_size_; ++j) { Node gn(board_size_ - 1, j); pawn_data.goal_nodes.insert(gn); } break; case 1: pawn_data.node.set_row(board_size_ / 2); pawn_data.node.set_col(0); for (int j = 0; j < board_size_; ++j) { Node gn(j, board_size_ - 1); pawn_data.goal_nodes.insert(gn); } break; case 2: pawn_data.node.set_row(board_size_ - 1); pawn_data.node.set_col(board_size_ / 2); for (int j = 0; j < board_size_; ++j) { Node gn(0, j); pawn_data.goal_nodes.insert(gn); } break; case 3: pawn_data.node.set_row(board_size_ / 2); pawn_data.node.set_col(board_size_ - 1); for (int j = 0; j < board_size_; ++j) { Node gn(j, 0); pawn_data.goal_nodes.insert(gn); } break; } pawn_data_list_.insert(pawn_data); } } void Game::switch_pawn() { auto it = pawn_data_list_.upper_bound(cur_pawn_idx_); if (it == pawn_data_list_.end()) { it = pawn_data_list_.begin(); } cur_pawn_idx_ = it->idx; } const pawn_data_t &Game::cur_pawn_data() const { return *pawn_data_list_.find(cur_pawn_idx_); } const pawn_data_list_t &Game::pawn_data_list() const { return pawn_data_list_; } const pawn_data_t &Game::pawn_data(std::shared_ptr<Pawn> &pawn) const { return *pawn_data_list_.get<by_pawn>().find(pawn); } int Game::move_pawn(const Node &node) { Node cur_node = pawn_data_list_.find(cur_pawn_idx_)->node; if (bg_.is_adjacent(cur_node, node)) { bg_.unblock_neighbours(cur_node); pawn_data_list_t::iterator it = pawn_data_list_.find(cur_pawn_idx_); pawn_data_t pawn_data = *it; pawn_data.node = node; pawn_data_list_.replace(it, pawn_data); bg_.block_neighbours(node); return 0; } else { return -1; } } int Game::add_wall(const Wall &wall) { std::vector<std::pair<Node, Node>> edges; if (try_add_wall(wall, &edges) < 0) { return -1; } wg_.apply_tmp_wall(); for (auto edge : edges) { bg_.remove_edges(edge.first, edge.second); } return 0; } int Game::try_add_wall(const Wall &wall, std::vector<std::pair<Node, Node>> *edges) { if (wg_.add_tmp_wall(wall) < 0) { return -1; } bg_.reset_filters(); Node node1; Node node2; Node node_tmp; if (wall.orientation() == Wall::kHorizontal) { for (int i = 0; i < wall.cnt(); ++i) { node1 = Node(wall.row() - 1, wall.col() + i); node2 = Node(wall.row(), wall.col() + i); bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = Node(wall.row() + 1, wall.col() + i); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() - 2, wall.col() + i); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = Node(wall.row(), wall.col() + j); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() - 1, wall.col() + j); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } else if (wall.orientation() == Wall::kVertical) { for (int i = 0; i < wall.cnt(); ++i) { node1 = Node(wall.row() + i, wall.col() - 1); node2 = Node(wall.row() + i, wall.col()); bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = Node(wall.row() + i, wall.col() + 1); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() + i, wall.col() - 2); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = Node(wall.row() + j, wall.col()); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() + j, wall.col() - 1); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } else { return -1; } bool path_blocked = false; for (auto pawn_data : pawn_data_list_) { path_blocked = true; for (auto goal_node : pawn_data.goal_nodes) { if (bg_.is_path_exists(pawn_data.node, goal_node)) { path_blocked = false; break; } } // wall blocks all pathes to the opposite side for one of pawns if (path_blocked) { break; } } if (path_blocked) { return -1; } return 0; } bool Game::is_finished() const { Node cur_node = pawn_data_list_.find(cur_pawn_idx_)->node; if (pawn_data_list_.find(cur_pawn_idx_)->goal_nodes.count(cur_node) != 0) { return true; } return false; } bool Game::get_path(std::shared_ptr<Pawn> pawn, const Node &node, std::list<Node> *path) const { return bg_.find_path(pawn_data(pawn).node, node, path); } } // namespace Quoridor <|endoftext|>
<commit_before>/* // Copyright (c) 2018 Intel 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 #ifndef BOOST_COROUTINES_NO_DEPRECATION_WARNING // users should define this if they directly include boost/asio/spawn.hpp, // but by defining it here, warnings won't cause problems with a compile #define BOOST_COROUTINES_NO_DEPRECATION_WARNING #endif #include <boost/asio/async_result.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/posix/stream_descriptor.hpp> #include <boost/asio/post.hpp> #include <boost/asio/spawn.hpp> #include <boost/callable_traits.hpp> #include <sdbusplus/asio/detail/async_send_handler.hpp> #include <sdbusplus/message.hpp> #include <sdbusplus/utility/read_into_tuple.hpp> #include <sdbusplus/utility/type_traits.hpp> #include <chrono> #include <string> #include <tuple> namespace sdbusplus { namespace asio { /// Root D-Bus IO object /** * A connection to a bus, through which messages may be sent or received. */ class connection : public sdbusplus::bus_t { public: // default to system bus connection(boost::asio::io_context& io) : sdbusplus::bus_t(sdbusplus::bus::new_default()), io_(io), socket(io_) { socket.assign(get_fd()); read_wait(); } connection(boost::asio::io_context& io, sd_bus* bus) : sdbusplus::bus_t(bus), io_(io), socket(io_) { socket.assign(get_fd()); read_wait(); } ~connection() { // The FD will be closed by the socket object, so assign null to the // sd_bus object to avoid a double close() Ignore return codes here, // because there's nothing we can do about errors socket.release(); } /** @brief Perform an asynchronous send of a message, executing the handler * upon return and return * * @param[in] m - A message ready to send * @param[in] token- The completion token to execute upon completion; * */ template <typename CompletionToken> inline auto async_send(message_t& m, CompletionToken&& token, uint64_t timeout = 0) { constexpr bool is_yield = std::is_same_v<CompletionToken, boost::asio::yield_context>; using return_t = std::conditional_t<is_yield, message_t, message_t&>; using callback_t = void(boost::system::error_code, return_t); return boost::asio::async_initiate<CompletionToken, callback_t>( detail::async_send_handler(get(), m, timeout), token); } /** @brief Perform an asynchronous method call, with input parameter packing * and return value unpacking. * * @param[in] handler - A function object that is to be called as a * continuation for the async dbus method call. The * arguments to parse on the return are deduced from * the handler's signature and then passed in along * with an error code and optional message_t * @param[in] service - The service to call. * @param[in] objpath - The object's path for the call. * @param[in] interf - The object's interface to call. * @param[in] method - The object's method to call. * @param[in] timeout - The timeout for the method call in usec (0 results * in using the default value). * @param[in] a... - Optional parameters for the method call. * * @return immediate return of the internal handler registration. The * result of the actual asynchronous call will get unpacked from * the message and passed into the handler when the call is * complete. */ template <typename MessageHandler, typename... InputArgs> void async_method_call_timed(MessageHandler&& handler, const std::string& service, const std::string& objpath, const std::string& interf, const std::string& method, uint64_t timeout, const InputArgs&... a) { using FunctionTuple = boost::callable_traits::args_t<MessageHandler>; using FunctionTupleType = utility::decay_tuple_t<FunctionTuple>; constexpr bool returnWithMsg = []() { if constexpr ((std::tuple_size_v<FunctionTupleType>) > 1) { return std::is_same_v< std::tuple_element_t<1, FunctionTupleType>, sdbusplus::message_t>; } return false; }(); using UnpackType = utility::strip_first_n_args_t<returnWithMsg ? 2 : 1, FunctionTupleType>; auto applyHandler = [handler = std::forward<MessageHandler>(handler)]( boost::system::error_code ec, message_t& r) mutable { UnpackType responseData; if (!ec) { try { utility::read_into_tuple(responseData, r); } catch (const std::exception& e) { // Set error code if not already set ec = boost::system::errc::make_error_code( boost::system::errc::invalid_argument); } } // Note. Callback is called whether or not the unpack was // successful to allow the user to implement their own handling if constexpr (returnWithMsg) { auto response = std::tuple_cat(std::make_tuple(ec), std::forward_as_tuple(r), std::move(responseData)); std::apply(handler, response); } else { auto response = std::tuple_cat(std::make_tuple(ec), std::move(responseData)); std::apply(handler, response); } }; message_t m; boost::system::error_code ec; try { m = new_method_call(service.c_str(), objpath.c_str(), interf.c_str(), method.c_str()); m.append(a...); } catch (const exception::SdBusError& e) { ec = boost::system::errc::make_error_code( static_cast<boost::system::errc::errc_t>(e.get_errno())); applyHandler(ec, m); return; } async_send(m, std::forward<decltype(applyHandler)>(applyHandler), timeout); } /** @brief Perform an asynchronous method call, with input parameter packing * and return value unpacking. Uses the default timeout value. * * @param[in] handler - A function object that is to be called as a * continuation for the async dbus method call. The * arguments to parse on the return are deduced from * the handler's signature and then passed in along * with an error code and optional message_t * @param[in] service - The service to call. * @param[in] objpath - The object's path for the call. * @param[in] interf - The object's interface to call. * @param[in] method - The object's method to call. * @param[in] a... - Optional parameters for the method call. * * @return immediate return of the internal handler registration. The * result of the actual asynchronous call will get unpacked from * the message and passed into the handler when the call is * complete. */ template <typename MessageHandler, typename... InputArgs> void async_method_call(MessageHandler&& handler, const std::string& service, const std::string& objpath, const std::string& interf, const std::string& method, const InputArgs&... a) { async_method_call_timed(std::forward<MessageHandler>(handler), service, objpath, interf, method, 0, a...); } /** @brief Perform a yielding asynchronous method call, with input * parameter packing and return value unpacking * * @param[in] yield - A yield context to async block upon. * @param[in] ec - an error code that will be set for any errors * @param[in] service - The service to call. * @param[in] objpath - The object's path for the call. * @param[in] interf - The object's interface to call. * @param[in] method - The object's method to call. * @param[in] a... - Optional parameters for the method call. * * @return Unpacked value of RetType */ template <typename... RetTypes, typename... InputArgs> auto yield_method_call(boost::asio::yield_context yield, boost::system::error_code& ec, const std::string& service, const std::string& objpath, const std::string& interf, const std::string& method, const InputArgs&... a) { message_t m; try { m = new_method_call(service.c_str(), objpath.c_str(), interf.c_str(), method.c_str()); m.append(a...); } catch (const exception::SdBusError& e) { ec = boost::system::errc::make_error_code( static_cast<boost::system::errc::errc_t>(e.get_errno())); } message_t r; if (!ec) { r = async_send(m, yield[ec]); } if constexpr (sizeof...(RetTypes) == 0) { // void return return; } else if constexpr (sizeof...(RetTypes) == 1) { if constexpr (std::is_same_v<utility::first_type_t<RetTypes...>, void>) { return; } else { // single item return utility::first_type_t<RetTypes...> responseData{}; // before attempting to read, check ec and bail on error if (ec) { return responseData; } try { r.read(responseData); } catch (const std::exception& e) { ec = boost::system::errc::make_error_code( boost::system::errc::invalid_argument); // responseData will be default-constructed... } return responseData; } } else { // tuple of things to return std::tuple<RetTypes...> responseData{}; // before attempting to read, check ec and bail on error if (ec) { return responseData; } try { r.read(responseData); } catch (const std::exception& e) { ec = boost::system::errc::make_error_code( boost::system::errc::invalid_argument); // responseData will be default-constructed... } return responseData; } } boost::asio::io_context& get_io_context() { return io_; } private: boost::asio::io_context& io_; boost::asio::posix::stream_descriptor socket; void read_wait() { socket.async_read_some( boost::asio::null_buffers(), [&](const boost::system::error_code& ec, std::size_t) { if (ec) { return; } if (process_discard()) { read_immediate(); } else { read_wait(); } }); } void read_immediate() { boost::asio::post(io_, [&] { if (process_discard()) { read_immediate(); } else { read_wait(); } }); } }; } // namespace asio } // namespace sdbusplus <commit_msg>asio: fix instances of unused-exception-parameter<commit_after>/* // Copyright (c) 2018 Intel 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 #ifndef BOOST_COROUTINES_NO_DEPRECATION_WARNING // users should define this if they directly include boost/asio/spawn.hpp, // but by defining it here, warnings won't cause problems with a compile #define BOOST_COROUTINES_NO_DEPRECATION_WARNING #endif #include <boost/asio/async_result.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/posix/stream_descriptor.hpp> #include <boost/asio/post.hpp> #include <boost/asio/spawn.hpp> #include <boost/callable_traits.hpp> #include <sdbusplus/asio/detail/async_send_handler.hpp> #include <sdbusplus/message.hpp> #include <sdbusplus/utility/read_into_tuple.hpp> #include <sdbusplus/utility/type_traits.hpp> #include <chrono> #include <string> #include <tuple> namespace sdbusplus { namespace asio { /// Root D-Bus IO object /** * A connection to a bus, through which messages may be sent or received. */ class connection : public sdbusplus::bus_t { public: // default to system bus connection(boost::asio::io_context& io) : sdbusplus::bus_t(sdbusplus::bus::new_default()), io_(io), socket(io_) { socket.assign(get_fd()); read_wait(); } connection(boost::asio::io_context& io, sd_bus* bus) : sdbusplus::bus_t(bus), io_(io), socket(io_) { socket.assign(get_fd()); read_wait(); } ~connection() { // The FD will be closed by the socket object, so assign null to the // sd_bus object to avoid a double close() Ignore return codes here, // because there's nothing we can do about errors socket.release(); } /** @brief Perform an asynchronous send of a message, executing the handler * upon return and return * * @param[in] m - A message ready to send * @param[in] token- The completion token to execute upon completion; * */ template <typename CompletionToken> inline auto async_send(message_t& m, CompletionToken&& token, uint64_t timeout = 0) { constexpr bool is_yield = std::is_same_v<CompletionToken, boost::asio::yield_context>; using return_t = std::conditional_t<is_yield, message_t, message_t&>; using callback_t = void(boost::system::error_code, return_t); return boost::asio::async_initiate<CompletionToken, callback_t>( detail::async_send_handler(get(), m, timeout), token); } /** @brief Perform an asynchronous method call, with input parameter packing * and return value unpacking. * * @param[in] handler - A function object that is to be called as a * continuation for the async dbus method call. The * arguments to parse on the return are deduced from * the handler's signature and then passed in along * with an error code and optional message_t * @param[in] service - The service to call. * @param[in] objpath - The object's path for the call. * @param[in] interf - The object's interface to call. * @param[in] method - The object's method to call. * @param[in] timeout - The timeout for the method call in usec (0 results * in using the default value). * @param[in] a... - Optional parameters for the method call. * * @return immediate return of the internal handler registration. The * result of the actual asynchronous call will get unpacked from * the message and passed into the handler when the call is * complete. */ template <typename MessageHandler, typename... InputArgs> void async_method_call_timed(MessageHandler&& handler, const std::string& service, const std::string& objpath, const std::string& interf, const std::string& method, uint64_t timeout, const InputArgs&... a) { using FunctionTuple = boost::callable_traits::args_t<MessageHandler>; using FunctionTupleType = utility::decay_tuple_t<FunctionTuple>; constexpr bool returnWithMsg = []() { if constexpr ((std::tuple_size_v<FunctionTupleType>) > 1) { return std::is_same_v< std::tuple_element_t<1, FunctionTupleType>, sdbusplus::message_t>; } return false; }(); using UnpackType = utility::strip_first_n_args_t<returnWithMsg ? 2 : 1, FunctionTupleType>; auto applyHandler = [handler = std::forward<MessageHandler>(handler)]( boost::system::error_code ec, message_t& r) mutable { UnpackType responseData; if (!ec) { try { utility::read_into_tuple(responseData, r); } catch (const std::exception&) { // Set error code if not already set ec = boost::system::errc::make_error_code( boost::system::errc::invalid_argument); } } // Note. Callback is called whether or not the unpack was // successful to allow the user to implement their own handling if constexpr (returnWithMsg) { auto response = std::tuple_cat(std::make_tuple(ec), std::forward_as_tuple(r), std::move(responseData)); std::apply(handler, response); } else { auto response = std::tuple_cat(std::make_tuple(ec), std::move(responseData)); std::apply(handler, response); } }; message_t m; boost::system::error_code ec; try { m = new_method_call(service.c_str(), objpath.c_str(), interf.c_str(), method.c_str()); m.append(a...); } catch (const exception::SdBusError& e) { ec = boost::system::errc::make_error_code( static_cast<boost::system::errc::errc_t>(e.get_errno())); applyHandler(ec, m); return; } async_send(m, std::forward<decltype(applyHandler)>(applyHandler), timeout); } /** @brief Perform an asynchronous method call, with input parameter packing * and return value unpacking. Uses the default timeout value. * * @param[in] handler - A function object that is to be called as a * continuation for the async dbus method call. The * arguments to parse on the return are deduced from * the handler's signature and then passed in along * with an error code and optional message_t * @param[in] service - The service to call. * @param[in] objpath - The object's path for the call. * @param[in] interf - The object's interface to call. * @param[in] method - The object's method to call. * @param[in] a... - Optional parameters for the method call. * * @return immediate return of the internal handler registration. The * result of the actual asynchronous call will get unpacked from * the message and passed into the handler when the call is * complete. */ template <typename MessageHandler, typename... InputArgs> void async_method_call(MessageHandler&& handler, const std::string& service, const std::string& objpath, const std::string& interf, const std::string& method, const InputArgs&... a) { async_method_call_timed(std::forward<MessageHandler>(handler), service, objpath, interf, method, 0, a...); } /** @brief Perform a yielding asynchronous method call, with input * parameter packing and return value unpacking * * @param[in] yield - A yield context to async block upon. * @param[in] ec - an error code that will be set for any errors * @param[in] service - The service to call. * @param[in] objpath - The object's path for the call. * @param[in] interf - The object's interface to call. * @param[in] method - The object's method to call. * @param[in] a... - Optional parameters for the method call. * * @return Unpacked value of RetType */ template <typename... RetTypes, typename... InputArgs> auto yield_method_call(boost::asio::yield_context yield, boost::system::error_code& ec, const std::string& service, const std::string& objpath, const std::string& interf, const std::string& method, const InputArgs&... a) { message_t m; try { m = new_method_call(service.c_str(), objpath.c_str(), interf.c_str(), method.c_str()); m.append(a...); } catch (const exception::SdBusError& e) { ec = boost::system::errc::make_error_code( static_cast<boost::system::errc::errc_t>(e.get_errno())); } message_t r; if (!ec) { r = async_send(m, yield[ec]); } if constexpr (sizeof...(RetTypes) == 0) { // void return return; } else if constexpr (sizeof...(RetTypes) == 1) { if constexpr (std::is_same_v<utility::first_type_t<RetTypes...>, void>) { return; } else { // single item return utility::first_type_t<RetTypes...> responseData{}; // before attempting to read, check ec and bail on error if (ec) { return responseData; } try { r.read(responseData); } catch (const std::exception&) { ec = boost::system::errc::make_error_code( boost::system::errc::invalid_argument); // responseData will be default-constructed... } return responseData; } } else { // tuple of things to return std::tuple<RetTypes...> responseData{}; // before attempting to read, check ec and bail on error if (ec) { return responseData; } try { r.read(responseData); } catch (const std::exception&) { ec = boost::system::errc::make_error_code( boost::system::errc::invalid_argument); // responseData will be default-constructed... } return responseData; } } boost::asio::io_context& get_io_context() { return io_; } private: boost::asio::io_context& io_; boost::asio::posix::stream_descriptor socket; void read_wait() { socket.async_read_some( boost::asio::null_buffers(), [&](const boost::system::error_code& ec, std::size_t) { if (ec) { return; } if (process_discard()) { read_immediate(); } else { read_wait(); } }); } void read_immediate() { boost::asio::post(io_, [&] { if (process_discard()) { read_immediate(); } else { read_wait(); } }); } }; } // namespace asio } // namespace sdbusplus <|endoftext|>
<commit_before>#include "Surface.h" #include "OpenGLTexture.h" #include "Color.h" #include "Image.h" #include <cstring> #include <vector> #include <cmath> #include <cassert> #include <iostream> using namespace std; using namespace canvas; static vector<int> make_kernel(float radius) { int r = (int)ceil(radius); int rows = 2 * r + 1; float sigma = radius / 3; float sigma22 = 2.0f * sigma * sigma; float sigmaPi2 = 2.0f * float(M_PI) * sigma; float sqrtSigmaPi2 = sqrt(sigmaPi2); // float radius2 = radius*radius; vector<int> kernel; kernel.reserve(rows); int row = -r; float first_value = exp(-row*row/sigma22) / sqrtSigmaPi2; kernel.push_back(1); for (row++; row <= r; row++) { kernel.push_back(int(exp(-row * row / sigma22) / sqrtSigmaPi2 / first_value)); } return kernel; } void Surface::gaussianBlur(float hradius, float vradius) { if (!(hradius > 0 || vradius > 0)) { return; } unsigned char * buffer = lockMemory(true); assert(buffer); unsigned char * tmp = new unsigned char[width * height * 4]; if (hradius > 0.0f) { vector<int> hkernel = make_kernel(hradius); unsigned short hsize = hkernel.size(); int htotal = 0; for (vector<int>::iterator it = hkernel.begin(); it != hkernel.end(); it++) { htotal += *it; } memset(tmp, 0, width * height * 4); for (unsigned int row = 0; row < height; row++) { for (unsigned int col = 0; col + hsize < width; col++) { int c0 = 0, c1 = 0, c2 = 0, c3 = 0; for (unsigned int i = 0; i < hsize; i++) { unsigned char * ptr = buffer + (row * width + col + i) * 4; c0 += *ptr++ * hkernel[i]; c1 += *ptr++ * hkernel[i]; c2 += *ptr++ * hkernel[i]; c3 += *ptr++ * hkernel[i]; } unsigned char * ptr = tmp + (row * width + col + hsize / 2) * 4; *ptr++ = (unsigned char)(c0 / htotal); *ptr++ = (unsigned char)(c1 / htotal); *ptr++ = (unsigned char)(c2 / htotal); *ptr++ = (unsigned char)(c3 / htotal); } } } else { memcpy(tmp, buffer, width * height * 4); } if (vradius > 0) { vector<int> vkernel = make_kernel(vradius); unsigned short vsize = vkernel.size(); int vtotal = 0; for (vector<int>::iterator it = vkernel.begin(); it != vkernel.end(); it++) { vtotal += *it; } memset(buffer, 0, width * height * 4); for (unsigned int col = 0; col < width; col++) { for (unsigned int row = 0; row + vsize < height; row++) { int c0 = 0, c1 = 0, c2 = 0, c3 = 0; for (unsigned int i = 0; i < vsize; i++) { unsigned char * ptr = tmp + ((row + i) * width + col) * 4; c0 += *ptr++ * vkernel[i]; c1 += *ptr++ * vkernel[i]; c2 += *ptr++ * vkernel[i]; c3 += *ptr++ * vkernel[i]; } unsigned char * ptr = buffer + ((row + vsize / 2) * width + col) * 4; *ptr++ = (unsigned char)(c0 / vtotal); *ptr++ = (unsigned char)(c1 / vtotal); *ptr++ = (unsigned char)(c2 / vtotal); *ptr++ = (unsigned char)(c3 / vtotal); } } } else { memcpy(buffer, tmp, width * height * 4); } delete[] tmp; releaseMemory(); } static inline unsigned char toByte(float f) { int a = int(f * 255); if (a < 0) a = 0; else if (a > 255) a = 255; return (unsigned char)a; } void Surface::colorFill(const Color & color) { unsigned char * buffer = lockMemory(true); assert(buffer); unsigned int red = toByte(color.red * color.alpha); unsigned int green = toByte(color.green * color.alpha); unsigned int blue = toByte(color.blue * color.alpha); unsigned int alpha = toByte(color.alpha); for (unsigned int i = 0; i < width * height; i++) { unsigned char * ptr = buffer + (i * 4); unsigned int dest_alpha = ptr[3]; *ptr++ = (unsigned char)(dest_alpha * red / 255); *ptr++ = (unsigned char)(dest_alpha * green / 255); *ptr++ = (unsigned char)(dest_alpha * blue / 255); *ptr++ = (unsigned char)(dest_alpha * alpha / 255); } releaseMemory(); } void Surface::multiply(const Color & color) { unsigned char * buffer = lockMemory(true); assert(buffer); unsigned int red = toByte(color.red); unsigned int green = toByte(color.green); unsigned int blue = toByte(color.blue); unsigned int alpha = toByte(color.alpha); for (unsigned int i = 0; i < width * height; i++) { unsigned char * ptr = buffer + (i * 4); ptr[0] = (unsigned char)(ptr[0] * red / 255); ptr[1] = (unsigned char)(ptr[1] * green / 255); ptr[2] = (unsigned char)(ptr[2] * blue / 255); ptr[3] = (unsigned char)(ptr[3] * alpha / 255); } releaseMemory(); } const TextureRef & Surface::updateTexture() { flush(); // cerr << "updating texture, this = " << this << ", tex = " << texture.getData() << "\n"; bool premultiplied_alpha = true; #ifdef OPENGL if (!texture.isDefined()) { texture = OpenGLTexture::createTexture(getWidth(), getHeight(), min_filter, mag_filter); } #endif unsigned char * buffer = lockMemory(); assert(buffer); if (premultiplied_alpha) { texture.updateData(buffer); } else { // remove premultiplied alpha unsigned char * buffer2 = new unsigned char[getWidth() * getHeight() * 4]; for (unsigned int i = 0; i < getWidth() * getHeight(); i++) { unsigned int red = buffer[4 * i + 0]; unsigned int green = buffer[4 * i + 1]; unsigned int blue = buffer[4 * i + 2]; unsigned int alpha = buffer[4 * i + 3]; if (alpha >= 1) { buffer2[4 * i + 0] = (unsigned char)(255 * red / alpha); buffer2[4 * i + 1] = (unsigned char)(255 * green / alpha); buffer2[4 * i + 2] = (unsigned char)(255 * blue / alpha); } else { buffer2[4 * i + 0] = 0; buffer2[4 * i + 1] = 0; buffer2[4 * i + 2] = 0; } buffer2[4 * i + 3] = alpha; } texture.updateData(buffer2); delete[] buffer2; } releaseMemory(); return texture; } std::shared_ptr<Image> Surface::createImage(unsigned int required_width, unsigned int required_height) { flush(); unsigned char * buffer = lockMemory(false, required_width, required_height); assert(buffer); shared_ptr<Image> image(new Image(required_width ? required_width : getWidth(), required_height ? required_height : getHeight(), buffer, true)); releaseMemory(); return image; } <commit_msg>remove support for non-premultiplied alpha, add updateTexture method with size and offset<commit_after>#include "Surface.h" #include "OpenGLTexture.h" #include "Color.h" #include "Image.h" #include <cstring> #include <vector> #include <cmath> #include <cassert> #include <iostream> using namespace std; using namespace canvas; static vector<int> make_kernel(float radius) { int r = (int)ceil(radius); int rows = 2 * r + 1; float sigma = radius / 3; float sigma22 = 2.0f * sigma * sigma; float sigmaPi2 = 2.0f * float(M_PI) * sigma; float sqrtSigmaPi2 = sqrt(sigmaPi2); // float radius2 = radius*radius; vector<int> kernel; kernel.reserve(rows); int row = -r; float first_value = exp(-row*row/sigma22) / sqrtSigmaPi2; kernel.push_back(1); for (row++; row <= r; row++) { kernel.push_back(int(exp(-row * row / sigma22) / sqrtSigmaPi2 / first_value)); } return kernel; } void Surface::gaussianBlur(float hradius, float vradius) { if (!(hradius > 0 || vradius > 0)) { return; } unsigned char * buffer = lockMemory(true); assert(buffer); unsigned char * tmp = new unsigned char[width * height * 4]; if (hradius > 0.0f) { vector<int> hkernel = make_kernel(hradius); unsigned short hsize = hkernel.size(); int htotal = 0; for (vector<int>::iterator it = hkernel.begin(); it != hkernel.end(); it++) { htotal += *it; } memset(tmp, 0, width * height * 4); for (unsigned int row = 0; row < height; row++) { for (unsigned int col = 0; col + hsize < width; col++) { int c0 = 0, c1 = 0, c2 = 0, c3 = 0; for (unsigned int i = 0; i < hsize; i++) { unsigned char * ptr = buffer + (row * width + col + i) * 4; c0 += *ptr++ * hkernel[i]; c1 += *ptr++ * hkernel[i]; c2 += *ptr++ * hkernel[i]; c3 += *ptr++ * hkernel[i]; } unsigned char * ptr = tmp + (row * width + col + hsize / 2) * 4; *ptr++ = (unsigned char)(c0 / htotal); *ptr++ = (unsigned char)(c1 / htotal); *ptr++ = (unsigned char)(c2 / htotal); *ptr++ = (unsigned char)(c3 / htotal); } } } else { memcpy(tmp, buffer, width * height * 4); } if (vradius > 0) { vector<int> vkernel = make_kernel(vradius); unsigned short vsize = vkernel.size(); int vtotal = 0; for (vector<int>::iterator it = vkernel.begin(); it != vkernel.end(); it++) { vtotal += *it; } memset(buffer, 0, width * height * 4); for (unsigned int col = 0; col < width; col++) { for (unsigned int row = 0; row + vsize < height; row++) { int c0 = 0, c1 = 0, c2 = 0, c3 = 0; for (unsigned int i = 0; i < vsize; i++) { unsigned char * ptr = tmp + ((row + i) * width + col) * 4; c0 += *ptr++ * vkernel[i]; c1 += *ptr++ * vkernel[i]; c2 += *ptr++ * vkernel[i]; c3 += *ptr++ * vkernel[i]; } unsigned char * ptr = buffer + ((row + vsize / 2) * width + col) * 4; *ptr++ = (unsigned char)(c0 / vtotal); *ptr++ = (unsigned char)(c1 / vtotal); *ptr++ = (unsigned char)(c2 / vtotal); *ptr++ = (unsigned char)(c3 / vtotal); } } } else { memcpy(buffer, tmp, width * height * 4); } delete[] tmp; releaseMemory(); } static inline unsigned char toByte(float f) { int a = int(f * 255); if (a < 0) a = 0; else if (a > 255) a = 255; return (unsigned char)a; } void Surface::colorFill(const Color & color) { unsigned char * buffer = lockMemory(true); assert(buffer); unsigned int red = toByte(color.red * color.alpha); unsigned int green = toByte(color.green * color.alpha); unsigned int blue = toByte(color.blue * color.alpha); unsigned int alpha = toByte(color.alpha); for (unsigned int i = 0; i < width * height; i++) { unsigned char * ptr = buffer + (i * 4); unsigned int dest_alpha = ptr[3]; *ptr++ = (unsigned char)(dest_alpha * red / 255); *ptr++ = (unsigned char)(dest_alpha * green / 255); *ptr++ = (unsigned char)(dest_alpha * blue / 255); *ptr++ = (unsigned char)(dest_alpha * alpha / 255); } releaseMemory(); } void Surface::multiply(const Color & color) { unsigned char * buffer = lockMemory(true); assert(buffer); unsigned int red = toByte(color.red); unsigned int green = toByte(color.green); unsigned int blue = toByte(color.blue); unsigned int alpha = toByte(color.alpha); for (unsigned int i = 0; i < width * height; i++) { unsigned char * ptr = buffer + (i * 4); ptr[0] = (unsigned char)(ptr[0] * red / 255); ptr[1] = (unsigned char)(ptr[1] * green / 255); ptr[2] = (unsigned char)(ptr[2] * blue / 255); ptr[3] = (unsigned char)(ptr[3] * alpha / 255); } releaseMemory(); } const TextureRef & Surface::updateTexture() { flush(); // cerr << "updating texture, this = " << this << ", tex = " << texture.getData() << "\n"; bool premultiplied_alpha = true; #ifdef OPENGL if (!texture.isDefined()) { texture = OpenGLTexture::createTexture(getWidth(), getHeight(), min_filter, mag_filter); } #endif unsigned char * buffer = lockMemory(); assert(buffer); texture.updateData(buffer); releaseMemory(); return texture; } const TextureRef & Surface::updateTexture(unsigned int x0, unsigned int y0, unsigned int width, unsigned int height) { flush(); // cerr << "updating texture, this = " << this << ", tex = " << texture.getData() << "\n"; bool premultiplied_alpha = true; #ifdef OPENGL if (!texture.isDefined()) { texture = OpenGLTexture::createTexture(getWidth(), getHeight(), min_filter, mag_filter); } #endif unsigned char * buffer = lockMemory(); assert(buffer); unsigned char * buffer2 = new unsigned char[width * height * 4]; unsigned int offset2 = 0; for (unsigned int y = y0; y < y0 + height; y++) { for (unsigned int x = x0; x < x0 + width; x++) { unsigned int offset = 4 * (y * width + x); buffer2[offset2++] = buffer[offset++]; buffer2[offset2++] = buffer[offset++]; buffer2[offset2++] = buffer[offset++]; buffer2[offset2++] = buffer[offset++]; } } texture.updateData(buffer2, x0, y0, width, height); releaseMemory(); delete[] buffer2; return texture; } std::shared_ptr<Image> Surface::createImage(unsigned int required_width, unsigned int required_height) { flush(); unsigned char * buffer = lockMemory(false, required_width, required_height); assert(buffer); shared_ptr<Image> image(new Image(required_width ? required_width : getWidth(), required_height ? required_height : getHeight(), buffer, true)); releaseMemory(); return image; } <|endoftext|>
<commit_before>/* ************************************************************************* */ /* This file is part of Shard. */ /* */ /* Shard 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. */ /* */ /* 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/>. */ /* ************************************************************************* */ #pragma once /* ************************************************************************* */ // Shard #include "shard/Path.hpp" #include "shard/String.hpp" #include "shard/ViewPtr.hpp" #include "shard/tokenizer/Source.hpp" #include "shard/tokenizer/KeywordType.hpp" #include "shard/tokenizer/TokenType.hpp" #include "shard/tokenizer/Token.hpp" #include "shard/tokenizer/TokenizerException.hpp" /* ************************************************************************* */ namespace shard { inline namespace v1 { namespace tokenizer { /* ************************************************************************* */ class Tokenizer; //FWD declaration /* ************************************************************************* */ class TokenizerIterator { protected: ViewPtr<Tokenizer> m_tokenizer; public: /** * @brief constructs empty TokenizerIterator. */ TokenizerIterator() = default; /** * @brief constructs TokenizerIterator for given Tokenizer. */ explicit TokenizerIterator(ViewPtr<Tokenizer> tokenizer): m_tokenizer(tokenizer) {} inline const Token& operator*() const; inline TokenizerIterator& operator++(); inline TokenizerIterator operator++(int); /** * @brief returns pointer to related tokenizer. */ inline ViewPtr<Tokenizer> getTokenizer() const noexcept { return m_tokenizer; } }; /* ************************************************************************* */ /** * @brief checks whether lhs or rhs is at final token. * * This operator serves for range-for purposes. */ inline bool operator==(const TokenizerIterator& lhs, const TokenizerIterator& rhs) { return (lhs.getTokenizer() == nullptr || (*lhs).getType() == TokenType::End) && (rhs.getTokenizer() == nullptr || (*rhs).getType() == TokenType::End); } inline bool operator!=(const TokenizerIterator& lhs, const TokenizerIterator& rhs) { return !(lhs == rhs); } /* ************************************************************************* */ class Tokenizer { protected: Source m_src; Token m_current; static constexpr char string_literal_border = '"'; static constexpr char char_literal_border = '\''; /* ************************************************************************* */ public: /** * @brief constructs Tokenizer which reads from file. */ explicit Tokenizer(const Path& path): m_src(path) { next(); } /** * @brief constructs Tokenizer which reads from String. */ explicit Tokenizer(const String& source): m_src(source) { next(); } /* ************************************************************************* */ protected: /** * @brief returns if current character is between two chars in the ASCII table. */ inline bool isBetween(char value1, char value2) noexcept { return !empty() && (m_src.get() >= value1) && (m_src.get() <= value2); } /** * @brief returns if current character is whitespace. */ inline bool isWhitespace() noexcept { return isBetween('\1', ' '); } /** * @brief returns if current character is a letter. */ inline bool isLetter() noexcept { return isBetween('a', 'z') || isBetween('A', 'Z'); } /** * @brief returns if current character is a letter, number or '_'. */ inline bool isIdentifier() noexcept { return isBetween('a', 'z') || isBetween('A', 'Z') || isDigit() || is('_'); } /** * @brief returns if current character is a number. */ inline bool isDigit() noexcept { return isBetween('0', '9'); } /** * @brief returns if current character is tested character. */ inline bool is(char value) noexcept { return !empty() && m_src.get() == value; } /** * @brief returns if current character is one of tested characters. */ template<typename... Chars> inline bool is(char a, Chars... options) noexcept { char chars[]{a, options...}; for (const char option : chars) { if (is(option)) { return true; } } return false; } /** * @brief returns if current character is tested character. * If so, moves to next character. */ inline bool match(char value) noexcept { if (is(value)) { m_src.extract(); return true; } return false; } /** * @brief returns if current character is one of tested characters. * If so, moves to next character. */ template<typename... Chars> inline bool match(Chars... options) noexcept { const char chars[]{options...}; for (const char option : chars) { if (is(option)) { m_src.extract(); return true; } } return false; } /* ************************************************************************* */ protected: /** * @brief Iterates to next non-whitespace char. */ inline void skipWhitespace() noexcept { while (isWhitespace()) { m_src.extract(); } } inline void skipComments() noexcept { if (match('/')) { if (match('*')) { while (!match('*') || !match('/')) { m_src.extract(); } return; } if (match('/')) { while (!match('\n') && !match('\r')) { m_src.extract(); } return; } m_src.unget(); } } /** * @brief chcecks if source is empty. */ inline bool empty() { return m_src.empty(); } /* ************************************************************************* */ protected: /** * @brief tokenizes tokentype number. */ void tokenizeNumber(); /** * @brief tokenizes string into identifier. */ void tokenizeIdentifier() noexcept; /** * @brief tokenizes string value into keyword, function or identifier. */ void tokenizeString(); /** * @brief tokenizes string value into keyword, function or identifier. */ void tokenizeChar(); /** * @brief tokenizes operators. */ void tokenizeOperator(); /* ************************************************************************* */ public: /** * @brief go to next token. */ void next(); /** * @brief get current token. */ inline const Token& get() const noexcept { return m_current; } /** * @brief get current token an move to next. */ inline Token extract() { auto tmp = m_current; next(); return tmp; } /** * @brief checks if there is non-ending token available. */ inline bool isEof() { return m_current.getType() == TokenType::End; } /* ************************************************************************* */ public: /** * @brief returns tokenizer iterator pointing to currect token. */ inline TokenizerIterator begin() noexcept { return TokenizerIterator(this); } /** * @brief returns tokenizer iterator pointing to token with end. */ inline TokenizerIterator end() noexcept { return TokenizerIterator(nullptr); } }; /* ************************************************************************* */ inline const Token& TokenizerIterator::operator*() const { return m_tokenizer->get(); } inline TokenizerIterator& TokenizerIterator::operator++() { m_tokenizer->next(); return *this; } inline TokenizerIterator TokenizerIterator::operator++(int) { TokenizerIterator tmp(*this); operator++(); return tmp; } /* ************************************************************************* */ } } } /* ************************************************************************* */ <commit_msg>function isHexDigit<commit_after>/* ************************************************************************* */ /* This file is part of Shard. */ /* */ /* Shard 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. */ /* */ /* 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/>. */ /* ************************************************************************* */ #pragma once /* ************************************************************************* */ // Shard #include "shard/Path.hpp" #include "shard/String.hpp" #include "shard/ViewPtr.hpp" #include "shard/tokenizer/Source.hpp" #include "shard/tokenizer/KeywordType.hpp" #include "shard/tokenizer/TokenType.hpp" #include "shard/tokenizer/Token.hpp" #include "shard/tokenizer/TokenizerException.hpp" /* ************************************************************************* */ namespace shard { inline namespace v1 { namespace tokenizer { /* ************************************************************************* */ class Tokenizer; //FWD declaration /* ************************************************************************* */ class TokenizerIterator { protected: ViewPtr<Tokenizer> m_tokenizer; public: /** * @brief constructs empty TokenizerIterator. */ TokenizerIterator() = default; /** * @brief constructs TokenizerIterator for given Tokenizer. */ explicit TokenizerIterator(ViewPtr<Tokenizer> tokenizer): m_tokenizer(tokenizer) {} inline const Token& operator*() const; inline TokenizerIterator& operator++(); inline TokenizerIterator operator++(int); /** * @brief returns pointer to related tokenizer. */ inline ViewPtr<Tokenizer> getTokenizer() const noexcept { return m_tokenizer; } }; /* ************************************************************************* */ /** * @brief checks whether lhs or rhs is at final token. * * This operator serves for range-for purposes. */ inline bool operator==(const TokenizerIterator& lhs, const TokenizerIterator& rhs) { return (lhs.getTokenizer() == nullptr || (*lhs).getType() == TokenType::End) && (rhs.getTokenizer() == nullptr || (*rhs).getType() == TokenType::End); } inline bool operator!=(const TokenizerIterator& lhs, const TokenizerIterator& rhs) { return !(lhs == rhs); } /* ************************************************************************* */ class Tokenizer { protected: Source m_src; Token m_current; static constexpr char string_literal_border = '"'; static constexpr char char_literal_border = '\''; /* ************************************************************************* */ public: /** * @brief constructs Tokenizer which reads from file. */ explicit Tokenizer(const Path& path): m_src(path) { next(); } /** * @brief constructs Tokenizer which reads from String. */ explicit Tokenizer(const String& source): m_src(source) { next(); } /* ************************************************************************* */ protected: /** * @brief returns if current character is between two chars in the ASCII table. */ inline bool isBetween(char value1, char value2) noexcept { return !empty() && (m_src.get() >= value1) && (m_src.get() <= value2); } /** * @brief returns if current character is whitespace. */ inline bool isWhitespace() noexcept { return isBetween('\1', ' '); } /** * @brief returns if current character is a letter. */ inline bool isLetter() noexcept { return isBetween('a', 'z') || isBetween('A', 'Z'); } /** * @brief returns if current character is a letter, number or '_'. */ inline bool isIdentifier() noexcept { return isBetween('a', 'z') || isBetween('A', 'Z') || isDigit() || is('_'); } /** * @brief returns if current character is a number. */ inline bool isDigit() noexcept { return isBetween('0', '9'); } /** * @brief returns if current character is a hexadecimal number. */ inline bool isHexDigit() noexcept { return isBetween('0', '9') || isBetween('a', 'f') || isBetween('A', 'F'); } /** * @brief returns if current character is tested character. */ inline bool is(char value) noexcept { return !empty() && m_src.get() == value; } /** * @brief returns if current character is one of tested characters. */ template<typename... Chars> inline bool is(char a, Chars... options) noexcept { char chars[]{a, options...}; for (const char option : chars) { if (is(option)) { return true; } } return false; } /** * @brief returns if current character is tested character. * If so, moves to next character. */ inline bool match(char value) noexcept { if (is(value)) { m_src.extract(); return true; } return false; } /** * @brief returns if current character is one of tested characters. * If so, moves to next character. */ template<typename... Chars> inline bool match(Chars... options) noexcept { const char chars[]{options...}; for (const char option : chars) { if (is(option)) { m_src.extract(); return true; } } return false; } /* ************************************************************************* */ protected: /** * @brief Iterates to next non-whitespace char. */ inline void skipWhitespace() noexcept { while (isWhitespace()) { m_src.extract(); } } inline void skipComments() noexcept { if (match('/')) { if (match('*')) { while (!match('*') || !match('/')) { m_src.extract(); } return; } if (match('/')) { while (!match('\n') && !match('\r')) { m_src.extract(); } return; } m_src.unget(); } } /** * @brief chcecks if source is empty. */ inline bool empty() { return m_src.empty(); } /* ************************************************************************* */ protected: /** * @brief tokenizes tokentype number. */ void tokenizeNumber(); /** * @brief tokenizes string into identifier. */ void tokenizeIdentifier() noexcept; /** * @brief tokenizes string value into keyword, function or identifier. */ void tokenizeString(); /** * @brief tokenizes string value into keyword, function or identifier. */ void tokenizeChar(); /** * @brief tokenizes operators. */ void tokenizeOperator(); /* ************************************************************************* */ public: /** * @brief go to next token. */ void next(); /** * @brief get current token. */ inline const Token& get() const noexcept { return m_current; } /** * @brief get current token an move to next. */ inline Token extract() { auto tmp = m_current; next(); return tmp; } /** * @brief checks if there is non-ending token available. */ inline bool isEof() { return m_current.getType() == TokenType::End; } /* ************************************************************************* */ public: /** * @brief returns tokenizer iterator pointing to currect token. */ inline TokenizerIterator begin() noexcept { return TokenizerIterator(this); } /** * @brief returns tokenizer iterator pointing to token with end. */ inline TokenizerIterator end() noexcept { return TokenizerIterator(nullptr); } }; /* ************************************************************************* */ inline const Token& TokenizerIterator::operator*() const { return m_tokenizer->get(); } inline TokenizerIterator& TokenizerIterator::operator++() { m_tokenizer->next(); return *this; } inline TokenizerIterator TokenizerIterator::operator++(int) { TokenizerIterator tmp(*this); operator++(); return tmp; } /* ************************************************************************* */ } } } /* ************************************************************************* */ <|endoftext|>
<commit_before>/** * Copyright 2014 Krzysztof Magosa * * 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 "microbe/Teacher.hpp" #include "microbe/TeacherPlugin.hpp" namespace microbe { void Teacher::setGoal(const double value) { if (value <= 0.0) { throw std::invalid_argument("Goal must be positive number."); } goal = value; } void Teacher::setLearningRate(const double value) { if (value <= 0.0) { throw std::invalid_argument("Learning rate cannot be 0.0 or negative number."); } if (value > 1.0) { throw std::invalid_argument("Learning rate cannot be higher than 1.0."); } learningRate = value; } double Teacher::getLearningRate(void) { return learningRate; } void Teacher::setMomentum(const double value) { if (value < 0.0) { throw std::invalid_argument("Momentum cannot be negative."); } if (value > 1.0) { throw std::invalid_argument("Momentum cannot be higher than 1.0."); } momentum = value; } void Teacher::addLearningSet(LearningSet& set) { learningSets.push_back(&set); } std::vector<LearningSet*> Teacher::getLearningSets(void) { return learningSets; } double Teacher::getLastEpochError(void) { return lastEpochError; } double Teacher::calculateSquaredErrorEpoch(void) { double error = 0; for (LearningSet* set : learningSets) { error += squaredError(*set); } lastEpochError = std::sqrt(error / learningSets.size()); return lastEpochError; } bool Teacher::train(void) { calculateSquaredErrorEpoch(); while (lastEpochError > goal) { firePreEpoch(); trainEpoch(); calculateSquaredErrorEpoch(); firePostEpoch(); } return true; } double Teacher::squaredError(LearningSet& set) { double error = 0.0; network->setValues(set.getInput()); network->run(); auto outputs = network->getOutput(); auto expected = set.getOutput(); for (int i = 0; i < outputs.size(); i++) { error += std::pow(outputs.at(i) - expected.at(i), 2); } return error; } void Teacher::registerPlugin(TeacherPlugin& plugin) { plugin.setTeacher(this); plugin.init(); plugins.push_back(&plugin); } void Teacher::firePreEpoch(void) { for (TeacherPlugin *plugin : plugins) { plugin->preEpoch(); } } void Teacher::firePostEpoch(void) { for (TeacherPlugin *plugin : plugins) { plugin->postEpoch(); } } } <commit_msg>Teacher - formatting<commit_after>/** * Copyright 2014 Krzysztof Magosa * * 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 "microbe/Teacher.hpp" #include "microbe/TeacherPlugin.hpp" namespace microbe { void Teacher::setGoal(const double value) { if (value <= 0.0) { throw std::invalid_argument("Goal must be positive number."); } goal = value; } void Teacher::setLearningRate(const double value) { if (value <= 0.0) { throw std::invalid_argument("Learning rate cannot be 0.0 or negative number."); } if (value > 1.0) { throw std::invalid_argument("Learning rate cannot be higher than 1.0."); } learningRate = value; } double Teacher::getLearningRate(void) { return learningRate; } void Teacher::setMomentum(const double value) { if (value < 0.0) { throw std::invalid_argument("Momentum cannot be negative."); } if (value > 1.0) { throw std::invalid_argument("Momentum cannot be higher than 1.0."); } momentum = value; } void Teacher::addLearningSet(LearningSet& set) { learningSets.push_back(&set); } std::vector<LearningSet*> Teacher::getLearningSets(void) { return learningSets; } double Teacher::getLastEpochError(void) { return lastEpochError; } double Teacher::calculateSquaredErrorEpoch(void) { double error = 0; for (LearningSet* set : learningSets) { error += squaredError(*set); } lastEpochError = std::sqrt(error / learningSets.size()); return lastEpochError; } bool Teacher::train(void) { calculateSquaredErrorEpoch(); while (lastEpochError > goal) { firePreEpoch(); trainEpoch(); calculateSquaredErrorEpoch(); firePostEpoch(); } return true; } double Teacher::squaredError(LearningSet& set) { double error = 0.0; network->setValues(set.getInput()); network->run(); auto outputs = network->getOutput(); auto expected = set.getOutput(); for (int i = 0; i < outputs.size(); i++) { error += std::pow(outputs.at(i) - expected.at(i), 2); } return error; } void Teacher::registerPlugin(TeacherPlugin& plugin) { plugin.setTeacher(this); plugin.init(); plugins.push_back(&plugin); } void Teacher::firePreEpoch(void) { for (TeacherPlugin *plugin : plugins) { plugin->preEpoch(); } } void Teacher::firePostEpoch(void) { for (TeacherPlugin *plugin : plugins) { plugin->postEpoch(); } } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/timing.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] 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 */ // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Jacob Harvey <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include <generic/memory/lib/utils/find.H> #include <lib/eff_config/timing.H> namespace mss { enum temp_mode : uint8_t { NORMAL = 1, EXTENDED = 2, }; // Proposed DDR4 Full spec update(79-4B) // Item No. 1716.78C // pg.46 // Table 24 - tREFI and tRFC parameters (in ps) constexpr uint64_t TREFI_BASE = 7800000; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR1 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 90000}, {8, 120000}, // 16Gb - TBD }; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR2 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 55000}, {8, 90000} // 16Gb - TBD }; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR4 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 40000}, {8, 55000} // 16Gb - TBD }; /// /// @brief Calculates refresh interval time /// @param[in] i_mode fine refresh rate mode /// @param[in] i_temp_refresh_range temperature refresh range /// @param[out] o_value timing val in ps /// @return fapi2::ReturnCode /// fapi2::ReturnCode calc_trefi( const refresh_rate i_mode, const uint8_t i_temp_refresh_range, uint64_t& o_timing ) { uint64_t l_multiplier = 0; uint64_t l_quotient = 0; uint64_t l_remainder = 0; switch(i_temp_refresh_range) { case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_NORMAL: l_multiplier = temp_mode::NORMAL; break; case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_EXTEND: l_multiplier = temp_mode::EXTENDED; break; default: // Temperature Refresh Range will be a platform attribute set by the MRW, // which they "shouldn't" mess up as long as use "attribute" enums. // if someone messes this up we can at least catch it FAPI_ASSERT( false, fapi2::MSS_INVALID_TEMP_REFRESH() .set_TEMP_REFRESH_RANGE(i_temp_refresh_range), "Incorrect Temperature Ref. Range received: %d ", i_temp_refresh_range); break; } l_quotient = TREFI_BASE / ( int64_t(i_mode) * l_multiplier ); l_remainder = TREFI_BASE % ( int64_t(i_mode) * l_multiplier ); o_timing = l_quotient + (l_remainder == 0 ? 0 : 1); FAPI_INF( "tREFI: %d, quotient: %d, remainder: %d, tREFI_base: %d", o_timing, l_quotient, l_remainder, TREFI_BASE ); // FAPI_ASSERT doesn't set current error to good return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// @brief Calculates Minimum Refresh Recovery Delay Time (different logical rank) /// @param[in] i_mode fine refresh rate mode /// @param[in] i_density SDRAM density /// @param[out] o_trfc_in_ps timing val in ps /// @return fapi2::FAPI2_RC_SUCCESS iff okay /// fapi2::ReturnCode calc_trfc_dlr(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const uint8_t i_refresh_mode, const uint8_t i_density, uint64_t& o_trfc_in_ps) { bool l_is_val_found = 0; // Selects appropriate tRFC based on fine refresh mode switch(i_refresh_mode) { case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_NORMAL: l_is_val_found = find_value_from_key(TRFC_DLR1, i_density, o_trfc_in_ps); break; case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FIXED_2X: case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FLY_2X: l_is_val_found = find_value_from_key(TRFC_DLR2, i_density, o_trfc_in_ps); break; case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FIXED_4X: case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FLY_4X: l_is_val_found = find_value_from_key(TRFC_DLR4, i_density, o_trfc_in_ps); break; default: // Fine Refresh Mode will be a platform attribute set by the MRW, // which they "shouldn't" mess up as long as use "attribute" enums. // if openpower messes this up we can at least catch it FAPI_ASSERT( false, fapi2::MSS_INVALID_FINE_REFRESH() .set_REFRESH_MODE(i_refresh_mode), "Incorrect Fine Refresh Mode received: %d ", i_refresh_mode); break; }// switch FAPI_ASSERT( l_is_val_found, fapi2::MSS_FAILED_TO_FIND_TRFC() .set_SDRAM_DENSITY(i_density) .set_REFRESH_MODE(i_refresh_mode) .set_TARGET(i_target), "%s: Unable to find tRFC (ps) from map with SDRAM density key %d with %d refresh mode", mss::c_str(i_target), i_density, i_refresh_mode); // Again, FAPI_ASSERT doesn't set current_err to good, only to bad return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } }// mss <commit_msg>L3 RAS for draminit_training, eff_config, lib<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/timing.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] 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 */ // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Jacob Harvey <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include <generic/memory/lib/utils/find.H> #include <lib/eff_config/timing.H> namespace mss { enum temp_mode : uint8_t { NORMAL = 1, EXTENDED = 2, }; // Proposed DDR4 Full spec update(79-4B) // Item No. 1716.78C // pg.46 // Table 24 - tREFI and tRFC parameters (in ps) constexpr uint64_t TREFI_BASE = 7800000; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR1 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 90000}, {8, 120000}, // 16Gb - TBD }; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR2 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 55000}, {8, 90000} // 16Gb - TBD }; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR4 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 40000}, {8, 55000} // 16Gb - TBD }; /// /// @brief Calculates refresh interval time /// @param[in] i_mode fine refresh rate mode /// @param[in] i_temp_refresh_range temperature refresh range /// @param[out] o_value timing val in ps /// @return fapi2::ReturnCode /// fapi2::ReturnCode calc_trefi( const refresh_rate i_mode, const uint8_t i_temp_refresh_range, uint64_t& o_timing ) { uint64_t l_multiplier = 0; uint64_t l_quotient = 0; uint64_t l_remainder = 0; switch(i_temp_refresh_range) { case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_NORMAL: l_multiplier = temp_mode::NORMAL; break; case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_EXTEND: l_multiplier = temp_mode::EXTENDED; break; default: // Temperature Refresh Range will be a platform attribute set by the MRW, // which they "shouldn't" mess up as long as use "attribute" enums. // if someone messes this up we can at least catch it FAPI_ASSERT( false, fapi2::MSS_INVALID_TEMP_REFRESH() .set_TEMP_REFRESH_RANGE(i_temp_refresh_range), "Incorrect Temperature Ref. Range received: %d ", i_temp_refresh_range); break; } l_quotient = TREFI_BASE / ( int64_t(i_mode) * l_multiplier ); l_remainder = TREFI_BASE % ( int64_t(i_mode) * l_multiplier ); o_timing = l_quotient + (l_remainder == 0 ? 0 : 1); FAPI_INF( "tREFI: %d, quotient: %d, remainder: %d, tREFI_base: %d", o_timing, l_quotient, l_remainder, TREFI_BASE ); // FAPI_ASSERT doesn't set current error to good return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// @brief Calculates Minimum Refresh Recovery Delay Time (different logical rank) /// @param[in] i_mode fine refresh rate mode /// @param[in] i_density SDRAM density /// @param[out] o_trfc_in_ps timing val in ps /// @return fapi2::FAPI2_RC_SUCCESS iff okay /// fapi2::ReturnCode calc_trfc_dlr(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const uint8_t i_refresh_mode, const uint8_t i_density, uint64_t& o_trfc_in_ps) { bool l_is_val_found = 0; // Selects appropriate tRFC based on fine refresh mode switch(i_refresh_mode) { case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_NORMAL: l_is_val_found = find_value_from_key(TRFC_DLR1, i_density, o_trfc_in_ps); break; case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FIXED_2X: case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FLY_2X: l_is_val_found = find_value_from_key(TRFC_DLR2, i_density, o_trfc_in_ps); break; case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FIXED_4X: case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FLY_4X: l_is_val_found = find_value_from_key(TRFC_DLR4, i_density, o_trfc_in_ps); break; default: // Fine Refresh Mode will be a platform attribute set by the MRW, // which they "shouldn't" mess up as long as use "attribute" enums. // if openpower messes this up we can at least catch it FAPI_ASSERT( false, fapi2::MSS_INVALID_FINE_REFRESH() .set_REFRESH_MODE(i_refresh_mode), "Incorrect Fine Refresh Mode received: %d ", i_refresh_mode); break; }// switch FAPI_ASSERT( l_is_val_found, fapi2::MSS_FAILED_TO_FIND_TRFC() .set_SDRAM_DENSITY(i_density) .set_REFRESH_MODE(i_refresh_mode) .set_DIMM_TARGET(i_target), "%s: Unable to find tRFC (ps) from map with SDRAM density key %d with %d refresh mode", mss::c_str(i_target), i_density, i_refresh_mode); // Again, FAPI_ASSERT doesn't set current_err to good, only to bad return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } }// mss <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_revert_sbe_mcs_setup.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] 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 p9_revert_sbe_mcs_setup.C /// @brief Revert MC configuration applied by SBE (FAPI2) /// /// @author Joe McGill <[email protected]> /// // // *HWP HWP Owner: Joe McGill <[email protected]> // *HWP FW Owner: Thi Tran <[email protected]> // *HWP Team: Nest // *HWP Level: 2 // *HWP Consumed by: HB // //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p9_revert_sbe_mcs_setup.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> //------------------------------------------------------------------------------ // Function prototypes //------------------------------------------------------------------------------ /// /// @brief Reset SBE applied hostboot dcbz MC configuration for one unit target /// /// @param[in] i_target Reference to an MC target (MCS/MI) /// @return FAPI2_RC_SUCCESS if success, else error code. /// template<fapi2::TargetType T> fapi2::ReturnCode revert_hb_dcbz_config(const fapi2::Target<T>& i_target); //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ // specialization for MCS target type template<> fapi2::ReturnCode revert_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target) { FAPI_DBG("Start"); fapi2::buffer<uint64_t> l_mcfgp; fapi2::buffer<uint64_t> l_mcmode1; fapi2::buffer<uint64_t> l_mcfirmask; // MCFGP -- mark BAR invalid & reset grouping configuration fields FAPI_TRY(fapi2::getScom(i_target, MCS_MCFGP, l_mcfgp), "Error from getScom (MCS_MCFGP)"); l_mcfgp.clearBit<MCS_MCFGP_VALID>(); l_mcfgp.clearBit<MCS_MCFGP_MC_CHANNELS_PER_GROUP, MCS_MCFGP_MC_CHANNELS_PER_GROUP_LEN>(); l_mcfgp.clearBit<MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION, MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION_LEN>(); l_mcfgp.clearBit<MCS_MCFGP_GROUP_SIZE, MCS_MCFGP_GROUP_SIZE_LEN>(); FAPI_TRY(fapi2::putScom(i_target, MCS_MCFGP, l_mcfgp), "Error from putScom (MCS_MCFGP)"); // MCMODE1 -- enable speculation FAPI_TRY(fapi2::getScom(i_target, MCS_MCMODE1, l_mcmode1), "Error from getScom (MCS_MCMODE1)"); l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_ALL_SPEC_OPS>(); l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_SPEC_OP, MCS_MCMODE1_DISABLE_SPEC_OP_LEN>(); FAPI_TRY(fapi2::putScom(i_target, MCS_MCMODE1, l_mcmode1), "Error from putScom (MCS_MCMODE1)"); // MCFIRMASK -- mask all errors l_mcfirmask.flush<1>(); FAPI_TRY(fapi2::putScom(i_target, MCS_MCFIRMASK_OR, l_mcfirmask), "Error from putScom (MCS_MCFIRMASK_OR)"); fapi_try_exit: FAPI_DBG("End"); return fapi2::current_err; } // specialization for MI target type template<> fapi2::ReturnCode revert_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_MI>& i_target) { // TODO: implement for Cumulus (MI target) return fapi2::current_err; } // HWP entry point fapi2::ReturnCode p9_revert_sbe_mcs_setup(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("Start"); auto l_mcs_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>(); if (l_mcs_chiplets.size()) { for (auto l_target_mcs : l_mcs_chiplets) { FAPI_TRY(revert_hb_dcbz_config(l_target_mcs), "Error from revert_hb_dcbz_config (MCS)"); } } else { auto l_mi_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_MI>(); for (auto l_target_mi : l_mi_chiplets) { FAPI_TRY(revert_hb_dcbz_config(l_target_mi), "Error from revert_hb_dcbz_config (MI)"); } } fapi_try_exit: FAPI_INF("End"); return fapi2::current_err; } <commit_msg>VBU IPL framework updates<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_revert_sbe_mcs_setup.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] 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 p9_revert_sbe_mcs_setup.C /// @brief Revert MC configuration applied by SBE (FAPI2) /// /// @author Joe McGill <[email protected]> /// // // *HWP HWP Owner: Joe McGill <[email protected]> // *HWP FW Owner: Thi Tran <[email protected]> // *HWP Team: Nest // *HWP Level: 2 // *HWP Consumed by: HB // //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p9_revert_sbe_mcs_setup.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ // MCS target type constants const uint8_t NUM_MCS_TARGETS = 4; const uint64_t MCS_MCFGP_ARR[NUM_MCS_TARGETS] = { MCS_0_MCFGP, MCS_1_MCFGP, MCS_2_MCFGP, MCS_3_MCFGP }; const uint64_t MCS_MCMODE1_ARR[NUM_MCS_TARGETS] = { MCS_0_MCMODE1, MCS_1_MCMODE1, MCS_2_MCMODE1, MCS_3_MCMODE1 }; const uint64_t MCS_MCFIRMASK_OR_ARR[NUM_MCS_TARGETS] = { MCS_0_MCFIRMASK_OR, MCS_1_MCFIRMASK_OR, MCS_2_MCFIRMASK_OR, MCS_3_MCFIRMASK_OR }; //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ // helper function for MCS target type fapi2::ReturnCode revert_mcs_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint8_t i_mcs) { FAPI_DBG("Start"); fapi2::buffer<uint64_t> l_mcfgp; fapi2::buffer<uint64_t> l_mcmode1; fapi2::buffer<uint64_t> l_mcfirmask; // MCFGP -- mark BAR invalid & reset grouping configuration fields FAPI_TRY(fapi2::getScom(i_target, MCS_MCFGP_ARR[i_mcs], l_mcfgp), "Error from getScom (MCS%d_MCFGP)", i_mcs); l_mcfgp.clearBit<MCS_MCFGP_VALID>(); l_mcfgp.clearBit<MCS_MCFGP_MC_CHANNELS_PER_GROUP, MCS_MCFGP_MC_CHANNELS_PER_GROUP_LEN>(); l_mcfgp.clearBit<MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION, MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION_LEN>(); l_mcfgp.clearBit<MCS_MCFGP_GROUP_SIZE, MCS_MCFGP_GROUP_SIZE_LEN>(); FAPI_TRY(fapi2::putScom(i_target, MCS_MCFGP_ARR[i_mcs], l_mcfgp), "Error from putScom (MCS%d_MCFGP)", i_mcs); // MCMODE1 -- enable speculation FAPI_TRY(fapi2::getScom(i_target, MCS_MCMODE1_ARR[i_mcs], l_mcmode1), "Error from getScom (MCS%d_MCMODE1)", i_mcs); l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_ALL_SPEC_OPS>(); l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_SPEC_OP, MCS_MCMODE1_DISABLE_SPEC_OP_LEN>(); FAPI_TRY(fapi2::putScom(i_target, MCS_MCMODE1_ARR[i_mcs], l_mcmode1), "Error from putScom (MCS%d_MCMODE1)", i_mcs); // MCFIRMASK -- mask all errors l_mcfirmask.flush<1>(); FAPI_TRY(fapi2::putScom(i_target, MCS_MCFIRMASK_OR_ARR[i_mcs], l_mcfirmask), "Error from putScom (MCS%d_MCFIRMASK_OR)", i_mcs); fapi_try_exit: FAPI_DBG("End"); return fapi2::current_err; } // helper function for MI target type fapi2::ReturnCode revert_mi_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_DBG("Start"); // TODO: implement for Cumulus/MI target type (void) i_target; goto fapi_try_exit; fapi_try_exit: FAPI_DBG("End"); return fapi2::current_err; } // HWP entry point fapi2::ReturnCode p9_revert_sbe_mcs_setup(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("Start"); fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; fapi2::ATTR_SYSTEM_IPL_PHASE_Type l_ipl_phase; auto l_mcs_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>(fapi2::TARGET_STATE_PRESENT); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_IPL_PHASE, FAPI_SYSTEM, l_ipl_phase), "Error from FAPI_ATTR_GET (ATTR_SYSTEM_IPL_PHASE)"); if (l_ipl_phase == fapi2::ENUM_ATTR_SYSTEM_IPL_PHASE_CHIP_CONTAINED) { FAPI_INF("Leaving MC BAR configured for chip contained execution"); goto fapi_try_exit; } if (l_mcs_chiplets.size()) { for (uint8_t l_mcs = 0; l_mcs < NUM_MCS_TARGETS; l_mcs++) { FAPI_TRY(revert_mcs_hb_dcbz_config(i_target, l_mcs), "Error from revert_mcs_hb_dcbz_config"); } } else { FAPI_TRY(revert_mi_hb_dcbz_config(i_target), "Error from revert_mi_hb_dcbz_config"); } fapi_try_exit: FAPI_INF("End"); return fapi2::current_err; } <|endoftext|>
<commit_before>/************************************************************************/ /* */ /* Copyright 1998-2000 by Ullrich Koethe */ /* Cognitive Systems Group, University of Hamburg, Germany */ /* */ /* This file is part of the VIGRA computer vision library. */ /* You may use, modify, and distribute this software according */ /* to the terms stated in the LICENSE file included in */ /* the VIGRA distribution. */ /* */ /* The VIGRA Website is */ /* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* [email protected] */ /* */ /* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */ /* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* */ /************************************************************************/ #ifndef VIGRA_SEEDEDREGIONGROWING_HXX #define VIGRA_SEEDEDREGIONGROWING_HXX #include <vector> #include <stack> #include <queue> #include <vigra/utilities.hxx> #include <vigra/stdimage.hxx> #include <vigra/stdimagefunctions.hxx> namespace vigra { template <class COST> class InternalSeedRgPixel { public: Diff2D location_, nearest_; COST cost_; int count_; int label_; int dist_; InternalSeedRgPixel() : location_(0,0), nearest_(0,0), cost_(0), count_(0), label_(0) {} InternalSeedRgPixel(Diff2D const & location, Diff2D const & nearest, COST const & cost, int const & count, int const & label) : location_(location), nearest_(nearest), cost_(cost), count_(count), label_(label) { int dx = location_.x - nearest_.x; int dy = location_.y - nearest_.y; dist_ = dx * dx + dy * dy; } void set(Diff2D const & location, Diff2D const & nearest, COST const & cost, int const & count, int const & label) { location_ = location; nearest_ = nearest; cost_ = cost; count_ = count; label_ = label; int dx = location_.x - nearest_.x; int dy = location_.y - nearest_.y; dist_ = dx * dx + dy * dy; } struct Compare { // must implement > since priority_queue looks for largest element bool operator()(InternalSeedRgPixel const & l, InternalSeedRgPixel const & r) const { if(r.cost_ == l.cost_) { if(r.dist_ == l.dist_) return r.count_ < l.count_; return r.dist_ < l.dist_; } return r.cost_ < l.cost_; } bool operator()(InternalSeedRgPixel const * l, InternalSeedRgPixel const * r) const { if(r->cost_ == l->cost_) { if(r->dist_ == l->dist_) return r->count_ < l->count_; return r->dist_ < l->dist_; } return r->cost_ < l->cost_; } }; struct Allocator { ~Allocator() { while(!freelist_.empty()) { delete freelist_.top(); freelist_.pop(); } } InternalSeedRgPixel * create(Diff2D const & location, Diff2D const & nearest, COST const & cost, int const & count, int const & label) { if(!freelist_.empty()) { InternalSeedRgPixel * res = freelist_.top(); freelist_.pop(); res->set(location, nearest, cost, count, label); return res; } return new InternalSeedRgPixel(location, nearest, cost, count, label); } void dismiss(InternalSeedRgPixel * p) { freelist_.push(p); } std::stack<InternalSeedRgPixel<COST> *> freelist_; }; }; /** \addtogroup SeededRegionGrowing Seeded Region Growing Region segmentation and voronoi tesselation */ //@{ /********************************************************/ /* */ /* seededRegionGrowing */ /* */ /********************************************************/ /** \brief Region Segmentation by means of Seeded Region Growing. This algorithm implements seeded region growing as described in R. Adams, L. Bischof: "<em> Seeded Region Growing</em>", IEEE Trans. on Pattern Analysis and Maschine Intelligence, vol 16, no 6, 1994, and Ullrich K\"othe: <em> "<a href="http://kogs-www.informatik.uni-hamburg.de/~koethe/papers/#primary">Primary Image Segmentation</a>"</em>, in: G. Sagerer, S. Posch, F. Kummert (eds.): Mustererkennung 1995, Proc. 17. DAGM-Symposium, Springer 1995 The seed image is a partly segmented image which contains uniquely labeled regions (the seeds) and unlabeled pixels (the candidates, label 0). Seed regions can be as large as you wish and as small as one pixel. If there are no candidates, the algorithm will simply copy the seed image into the output image. Otherwise it will aggregate the candidates into the existing regions so that a cost function is minimized. This works as follows: <ol> <li> Find all candidate pixels that are 4-adjacent to a seed region. Calculate the cost for aggregating each candidate into its adajacent region and put the candidates into a priority queue. <li> While( priority queue is not empty) <ol> <li> Take the candidate with least cost from the queue. If it has not already been merged, merge it with it's adjacent region. <li> Put all candidates that are 4-adjacent to the pixel just processed into the priority queue. </ol> </ol> This algorithm will always lead to a complete, 4-connected tesselation of the image. The cost is determined jointly by the source image and the region statistics functor. The source image contains feature values for each pixel which will be used by the region statistics functor to calculate and update statistics for each region and to calculate the cost for each candidate. The <TT>RegionStatisticsFunctor</TT> must be compatible to the \ref ArrayOfRegionStatistics functor and contains an <em> array</em> of statistics objects for each region. The indices must correspond to the labels of the seed regions. The statistics for the initial regions must have been calculated prior to calling <TT>seededRegionGrowing()</TT> (for example by means of \ref inspectTwoImagesIf()). For each candidate <TT>x</TT> that is adjacent to region <TT>i</TT>, the algorithm will call <TT>stats[i].cost(as(x))</TT> to get the cost (where <TT>x</TT> is a <TT>SrcImageIterator</TT> and <TT>as</TT> is the SrcAccessor). When a candidate has been merged with a region, the statistics are updated by calling <TT>stats[i].operator()(as(x))</TT>. Since the <TT>RegionStatisticsFunctor</TT> is passed by reference, this will overwrite the original statistics. If a candidate could be merged into more than one regions with identical cost, the algorithm will favour the nearest region. In some cases, the cost only depends on the feature value of the current pixel. Then the update operation will simply be a no-op, and the <TT>cost()</TT> function returns its argument. This behavior is implemented by the \ref SeedRgDirectValueFunctor. <b> Declarations:</b> pass arguments explicitly: \code namespace vigra { template <class SrcImageIterator, class SrcAccessor, class SeedImageIterator, class SeedAccessor, class DestImageIterator, class DestAccessor, class RegionStatisticsFunctor> void seededRegionGrowing(SrcImageIterator srcul, SrcImageIterator srclr, SrcAccessor as, SeedImageIterator seedsul, SeedAccessor aseeds, DestImageIterator destul, DestAccessor ad, RegionStatisticsFunctor & stats); } \endcode use argument objects in conjuction with \ref ArgumentObjectFactories: \code namespace vigra { template <class SrcImageIterator, class SrcAccessor, class SeedImageIterator, class SeedAccessor, class DestImageIterator, class DestAccessor, class RegionStatisticsFunctor> inline void seededRegionGrowing(triple<SrcImageIterator, SrcImageIterator, SrcAccessor> img1, pair<SeedImageIterator, SeedAccessor> img3, pair<DestImageIterator, DestAccessor> img4, RegionStatisticsFunctor & stats); } \endcode <b> Usage:</b> <b>\#include</b> "<a href="seededregiongrowing_8hxx-source.html">vigra/seededregiongrowing.hxx</a>"<br> Namespace: vigra Example: implementation of the voronoi tesselation \code vigra::BImage points(w,h); vigra::FImage dist(x,y); // empty edge image points = 0; dist = 0; int max_region_label = 100; // throw in some random points: for(int i = 1; i <= max_region_label; ++i) points(w * rand() / RAND_MAX , h * rand() / RAND_MAX) = i; // calculate Euclidean distance transform vigra::distanceTransform(srcImageRange(points), destImage(dist), 2); // init statistics functor vigra::ArrayOfRegionStatistics<vigra::SeedRgDirectValueFunctor<float> > stats(max_region_label); // find voronoi region of each point vigra:: seededRegionGrowing(srcImageRange(dist), srcImage(points), destImage(points), stats); \endcode <b> Required Interface:</b> \code SrcImageIterator src_upperleft, src_lowerright; SeedImageIterator seed_upperleft; DestImageIterator dest_upperleft; SrcAccessor src_accessor; SeedAccessor seed_accessor; DestAccessor dest_accessor; RegionStatisticsFunctor stats; // calculate costs RegionStatisticsFunctor::value_type cost = stats[seed_accessor(seed_upperleft)].cost(src_accessor(src_upperleft)); // compare costs cost < cost; // update statistics stats[seed_accessor(seed_upperleft)](src_accessor(src_upperleft)); // set result dest_accessor.set(seed_accessor(seed_upperleft), dest_upperleft); \endcode Further requirements are determined by the <TT>RegionStatisticsFunctor</TT>. */ template <class SrcImageIterator, class SrcAccessor, class SeedImageIterator, class SeedAccessor, class DestImageIterator, class DestAccessor, class RegionStatisticsFunctor> void seededRegionGrowing(SrcImageIterator srcul, SrcImageIterator srclr, SrcAccessor as, SeedImageIterator seedsul, SeedAccessor aseeds, DestImageIterator destul, DestAccessor ad, RegionStatisticsFunctor & stats) { int w = srclr.x - srcul.x; int h = srclr.y - srcul.y; int count = 0; SrcImageIterator isy = srcul, isx = srcul; // iterators for the src image typedef typename RegionStatisticsFunctor::value_type TmpType; typedef InternalSeedRgPixel<TmpType> Pixel; typename Pixel::Allocator allocator; typedef std::priority_queue<Pixel *, std::vector<Pixel *>, typename Pixel::Compare> SeedRgPixelHeap; // copy seed image in an image with border IImage regions(w+2, h+2); IImage::Iterator ir = regions.upperLeft() + Diff2D(1,1); IImage::Iterator iry, irx; initImageBorder(srcImageRange(regions), 1, -1); copyImage(seedsul, seedsul+Diff2D(w,h), aseeds, ir, regions.accessor()); // allocate and init memory for the results SeedRgPixelHeap pheap; static const Diff2D dist[] = { Diff2D(-1,0), Diff2D(0,-1), Diff2D(1,0), Diff2D(0,1) }; Diff2D pos(0,0); for(isy=srcul, iry=ir, pos.y=0; pos.y<h; ++pos.y, ++isy.y, ++iry.y) { for(isx=isy, irx=iry, pos.x=0; pos.x<w; ++pos.x, ++isx.x, ++irx.x) { if(*irx == 0) { // find candidate pixels for growing and fill heap int cneighbor; for(int i=0; i<4; i++) { cneighbor = irx[dist[i]]; if(cneighbor > 0) { TmpType cost = stats[cneighbor].cost(as(isx)); Pixel * pixel = allocator.create(pos, pos+dist[i], cost, count++, cneighbor); pheap.push(pixel); } } } } } // perform region growing while(pheap.size() != 0) { Pixel * pixel = pheap.top(); pheap.pop(); Diff2D pos = pixel->location_; Diff2D nearest = pixel->nearest_; int lab = pixel->label_; allocator.dismiss(pixel); irx = ir + pos; isx = srcul + pos; if(*irx > 0) continue; *irx = lab; // update statistics stats[*irx](as(isx)); // search neighborhood // second pass: find new candidate pixels for(int i=0; i<4; i++) { if(irx[dist[i]] == 0) { TmpType cost = stats[lab].cost(as(isx, dist[i])); Pixel * new_pixel = allocator.create(pos+dist[i], nearest, cost, count++, lab); pheap.push(new_pixel); } } } // write result copyImage(ir, ir+Diff2D(w,h), regions.accessor(), destul, ad); } template <class SrcImageIterator, class SrcAccessor, class SeedImageIterator, class SeedAccessor, class DestImageIterator, class DestAccessor, class RegionStatisticsFunctor> inline void seededRegionGrowing(triple<SrcImageIterator, SrcImageIterator, SrcAccessor> img1, pair<SeedImageIterator, SeedAccessor> img3, pair<DestImageIterator, DestAccessor> img4, RegionStatisticsFunctor & stats) { seededRegionGrowing(img1.first, img1.second, img1.third, img3.first, img3.second, img4.first, img4.second, stats); } /********************************************************/ /* */ /* SeedRgDirectValueFunctor */ /* */ /********************************************************/ /** \brief Statistics functor to be used for seeded region growing. This functor can be used if the cost of a candidate during \ref seededRegionGrowing() is equal to the feature value of that candidate and does not depend on properties of the region it is going to be merged with. <b>\#include</b> "<a href="seededregiongrowing_8hxx-source.html">vigra/seededregiongrowing.hxx</a>"<br> Namespace: vigra <b> Required Interface:</b> no requirements */ template <class Value> class SeedRgDirectValueFunctor { public: typedef Value value_type; typedef Value cost_type; /** Do nothing (since we need not update region statistics). */ void operator()(Value const &) const {} /** Return argument (since cost is identical to feature value) */ Value const & cost(Value const & v) const { return v; } }; //@} } // namespace vigra #endif // VIGRA_SEEDEDREGIONGROWING_HXX <commit_msg>change srcImageRange() into destImageRange() in call to initImageBorder()<commit_after>/************************************************************************/ /* */ /* Copyright 1998-2000 by Ullrich Koethe */ /* Cognitive Systems Group, University of Hamburg, Germany */ /* */ /* This file is part of the VIGRA computer vision library. */ /* You may use, modify, and distribute this software according */ /* to the terms stated in the LICENSE file included in */ /* the VIGRA distribution. */ /* */ /* The VIGRA Website is */ /* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* [email protected] */ /* */ /* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */ /* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* */ /************************************************************************/ #ifndef VIGRA_SEEDEDREGIONGROWING_HXX #define VIGRA_SEEDEDREGIONGROWING_HXX #include <vector> #include <stack> #include <queue> #include <vigra/utilities.hxx> #include <vigra/stdimage.hxx> #include <vigra/stdimagefunctions.hxx> namespace vigra { template <class COST> class InternalSeedRgPixel { public: Diff2D location_, nearest_; COST cost_; int count_; int label_; int dist_; InternalSeedRgPixel() : location_(0,0), nearest_(0,0), cost_(0), count_(0), label_(0) {} InternalSeedRgPixel(Diff2D const & location, Diff2D const & nearest, COST const & cost, int const & count, int const & label) : location_(location), nearest_(nearest), cost_(cost), count_(count), label_(label) { int dx = location_.x - nearest_.x; int dy = location_.y - nearest_.y; dist_ = dx * dx + dy * dy; } void set(Diff2D const & location, Diff2D const & nearest, COST const & cost, int const & count, int const & label) { location_ = location; nearest_ = nearest; cost_ = cost; count_ = count; label_ = label; int dx = location_.x - nearest_.x; int dy = location_.y - nearest_.y; dist_ = dx * dx + dy * dy; } struct Compare { // must implement > since priority_queue looks for largest element bool operator()(InternalSeedRgPixel const & l, InternalSeedRgPixel const & r) const { if(r.cost_ == l.cost_) { if(r.dist_ == l.dist_) return r.count_ < l.count_; return r.dist_ < l.dist_; } return r.cost_ < l.cost_; } bool operator()(InternalSeedRgPixel const * l, InternalSeedRgPixel const * r) const { if(r->cost_ == l->cost_) { if(r->dist_ == l->dist_) return r->count_ < l->count_; return r->dist_ < l->dist_; } return r->cost_ < l->cost_; } }; struct Allocator { ~Allocator() { while(!freelist_.empty()) { delete freelist_.top(); freelist_.pop(); } } InternalSeedRgPixel * create(Diff2D const & location, Diff2D const & nearest, COST const & cost, int const & count, int const & label) { if(!freelist_.empty()) { InternalSeedRgPixel * res = freelist_.top(); freelist_.pop(); res->set(location, nearest, cost, count, label); return res; } return new InternalSeedRgPixel(location, nearest, cost, count, label); } void dismiss(InternalSeedRgPixel * p) { freelist_.push(p); } std::stack<InternalSeedRgPixel<COST> *> freelist_; }; }; /** \addtogroup SeededRegionGrowing Seeded Region Growing Region segmentation and voronoi tesselation */ //@{ /********************************************************/ /* */ /* seededRegionGrowing */ /* */ /********************************************************/ /** \brief Region Segmentation by means of Seeded Region Growing. This algorithm implements seeded region growing as described in R. Adams, L. Bischof: "<em> Seeded Region Growing</em>", IEEE Trans. on Pattern Analysis and Maschine Intelligence, vol 16, no 6, 1994, and Ullrich K\"othe: <em> "<a href="http://kogs-www.informatik.uni-hamburg.de/~koethe/papers/#primary">Primary Image Segmentation</a>"</em>, in: G. Sagerer, S. Posch, F. Kummert (eds.): Mustererkennung 1995, Proc. 17. DAGM-Symposium, Springer 1995 The seed image is a partly segmented image which contains uniquely labeled regions (the seeds) and unlabeled pixels (the candidates, label 0). Seed regions can be as large as you wish and as small as one pixel. If there are no candidates, the algorithm will simply copy the seed image into the output image. Otherwise it will aggregate the candidates into the existing regions so that a cost function is minimized. This works as follows: <ol> <li> Find all candidate pixels that are 4-adjacent to a seed region. Calculate the cost for aggregating each candidate into its adajacent region and put the candidates into a priority queue. <li> While( priority queue is not empty) <ol> <li> Take the candidate with least cost from the queue. If it has not already been merged, merge it with it's adjacent region. <li> Put all candidates that are 4-adjacent to the pixel just processed into the priority queue. </ol> </ol> This algorithm will always lead to a complete, 4-connected tesselation of the image. The cost is determined jointly by the source image and the region statistics functor. The source image contains feature values for each pixel which will be used by the region statistics functor to calculate and update statistics for each region and to calculate the cost for each candidate. The <TT>RegionStatisticsFunctor</TT> must be compatible to the \ref ArrayOfRegionStatistics functor and contains an <em> array</em> of statistics objects for each region. The indices must correspond to the labels of the seed regions. The statistics for the initial regions must have been calculated prior to calling <TT>seededRegionGrowing()</TT> (for example by means of \ref inspectTwoImagesIf()). For each candidate <TT>x</TT> that is adjacent to region <TT>i</TT>, the algorithm will call <TT>stats[i].cost(as(x))</TT> to get the cost (where <TT>x</TT> is a <TT>SrcImageIterator</TT> and <TT>as</TT> is the SrcAccessor). When a candidate has been merged with a region, the statistics are updated by calling <TT>stats[i].operator()(as(x))</TT>. Since the <TT>RegionStatisticsFunctor</TT> is passed by reference, this will overwrite the original statistics. If a candidate could be merged into more than one regions with identical cost, the algorithm will favour the nearest region. In some cases, the cost only depends on the feature value of the current pixel. Then the update operation will simply be a no-op, and the <TT>cost()</TT> function returns its argument. This behavior is implemented by the \ref SeedRgDirectValueFunctor. <b> Declarations:</b> pass arguments explicitly: \code namespace vigra { template <class SrcImageIterator, class SrcAccessor, class SeedImageIterator, class SeedAccessor, class DestImageIterator, class DestAccessor, class RegionStatisticsFunctor> void seededRegionGrowing(SrcImageIterator srcul, SrcImageIterator srclr, SrcAccessor as, SeedImageIterator seedsul, SeedAccessor aseeds, DestImageIterator destul, DestAccessor ad, RegionStatisticsFunctor & stats); } \endcode use argument objects in conjuction with \ref ArgumentObjectFactories: \code namespace vigra { template <class SrcImageIterator, class SrcAccessor, class SeedImageIterator, class SeedAccessor, class DestImageIterator, class DestAccessor, class RegionStatisticsFunctor> inline void seededRegionGrowing(triple<SrcImageIterator, SrcImageIterator, SrcAccessor> img1, pair<SeedImageIterator, SeedAccessor> img3, pair<DestImageIterator, DestAccessor> img4, RegionStatisticsFunctor & stats); } \endcode <b> Usage:</b> <b>\#include</b> "<a href="seededregiongrowing_8hxx-source.html">vigra/seededregiongrowing.hxx</a>"<br> Namespace: vigra Example: implementation of the voronoi tesselation \code vigra::BImage points(w,h); vigra::FImage dist(x,y); // empty edge image points = 0; dist = 0; int max_region_label = 100; // throw in some random points: for(int i = 1; i <= max_region_label; ++i) points(w * rand() / RAND_MAX , h * rand() / RAND_MAX) = i; // calculate Euclidean distance transform vigra::distanceTransform(srcImageRange(points), destImage(dist), 2); // init statistics functor vigra::ArrayOfRegionStatistics<vigra::SeedRgDirectValueFunctor<float> > stats(max_region_label); // find voronoi region of each point vigra:: seededRegionGrowing(srcImageRange(dist), srcImage(points), destImage(points), stats); \endcode <b> Required Interface:</b> \code SrcImageIterator src_upperleft, src_lowerright; SeedImageIterator seed_upperleft; DestImageIterator dest_upperleft; SrcAccessor src_accessor; SeedAccessor seed_accessor; DestAccessor dest_accessor; RegionStatisticsFunctor stats; // calculate costs RegionStatisticsFunctor::value_type cost = stats[seed_accessor(seed_upperleft)].cost(src_accessor(src_upperleft)); // compare costs cost < cost; // update statistics stats[seed_accessor(seed_upperleft)](src_accessor(src_upperleft)); // set result dest_accessor.set(seed_accessor(seed_upperleft), dest_upperleft); \endcode Further requirements are determined by the <TT>RegionStatisticsFunctor</TT>. */ template <class SrcImageIterator, class SrcAccessor, class SeedImageIterator, class SeedAccessor, class DestImageIterator, class DestAccessor, class RegionStatisticsFunctor> void seededRegionGrowing(SrcImageIterator srcul, SrcImageIterator srclr, SrcAccessor as, SeedImageIterator seedsul, SeedAccessor aseeds, DestImageIterator destul, DestAccessor ad, RegionStatisticsFunctor & stats) { int w = srclr.x - srcul.x; int h = srclr.y - srcul.y; int count = 0; SrcImageIterator isy = srcul, isx = srcul; // iterators for the src image typedef typename RegionStatisticsFunctor::value_type TmpType; typedef InternalSeedRgPixel<TmpType> Pixel; typename Pixel::Allocator allocator; typedef std::priority_queue<Pixel *, std::vector<Pixel *>, typename Pixel::Compare> SeedRgPixelHeap; // copy seed image in an image with border IImage regions(w+2, h+2); IImage::Iterator ir = regions.upperLeft() + Diff2D(1,1); IImage::Iterator iry, irx; initImageBorder(destImageRange(regions), 1, -1); copyImage(seedsul, seedsul+Diff2D(w,h), aseeds, ir, regions.accessor()); // allocate and init memory for the results SeedRgPixelHeap pheap; static const Diff2D dist[] = { Diff2D(-1,0), Diff2D(0,-1), Diff2D(1,0), Diff2D(0,1) }; Diff2D pos(0,0); for(isy=srcul, iry=ir, pos.y=0; pos.y<h; ++pos.y, ++isy.y, ++iry.y) { for(isx=isy, irx=iry, pos.x=0; pos.x<w; ++pos.x, ++isx.x, ++irx.x) { if(*irx == 0) { // find candidate pixels for growing and fill heap int cneighbor; for(int i=0; i<4; i++) { cneighbor = irx[dist[i]]; if(cneighbor > 0) { TmpType cost = stats[cneighbor].cost(as(isx)); Pixel * pixel = allocator.create(pos, pos+dist[i], cost, count++, cneighbor); pheap.push(pixel); } } } } } // perform region growing while(pheap.size() != 0) { Pixel * pixel = pheap.top(); pheap.pop(); Diff2D pos = pixel->location_; Diff2D nearest = pixel->nearest_; int lab = pixel->label_; allocator.dismiss(pixel); irx = ir + pos; isx = srcul + pos; if(*irx > 0) continue; *irx = lab; // update statistics stats[*irx](as(isx)); // search neighborhood // second pass: find new candidate pixels for(int i=0; i<4; i++) { if(irx[dist[i]] == 0) { TmpType cost = stats[lab].cost(as(isx, dist[i])); Pixel * new_pixel = allocator.create(pos+dist[i], nearest, cost, count++, lab); pheap.push(new_pixel); } } } // write result copyImage(ir, ir+Diff2D(w,h), regions.accessor(), destul, ad); } template <class SrcImageIterator, class SrcAccessor, class SeedImageIterator, class SeedAccessor, class DestImageIterator, class DestAccessor, class RegionStatisticsFunctor> inline void seededRegionGrowing(triple<SrcImageIterator, SrcImageIterator, SrcAccessor> img1, pair<SeedImageIterator, SeedAccessor> img3, pair<DestImageIterator, DestAccessor> img4, RegionStatisticsFunctor & stats) { seededRegionGrowing(img1.first, img1.second, img1.third, img3.first, img3.second, img4.first, img4.second, stats); } /********************************************************/ /* */ /* SeedRgDirectValueFunctor */ /* */ /********************************************************/ /** \brief Statistics functor to be used for seeded region growing. This functor can be used if the cost of a candidate during \ref seededRegionGrowing() is equal to the feature value of that candidate and does not depend on properties of the region it is going to be merged with. <b>\#include</b> "<a href="seededregiongrowing_8hxx-source.html">vigra/seededregiongrowing.hxx</a>"<br> Namespace: vigra <b> Required Interface:</b> no requirements */ template <class Value> class SeedRgDirectValueFunctor { public: typedef Value value_type; typedef Value cost_type; /** Do nothing (since we need not update region statistics). */ void operator()(Value const &) const {} /** Return argument (since cost is identical to feature value) */ Value const & cost(Value const & v) const { return v; } }; //@} } // namespace vigra #endif // VIGRA_SEEDEDREGIONGROWING_HXX <|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 "cc/surfaces/display.h" #include "base/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "cc/debug/benchmark_instrumentation.h" #include "cc/output/compositor_frame.h" #include "cc/output/compositor_frame_ack.h" #include "cc/output/direct_renderer.h" #include "cc/output/gl_renderer.h" #include "cc/output/renderer_settings.h" #include "cc/output/software_renderer.h" #include "cc/output/texture_mailbox_deleter.h" #include "cc/surfaces/display_client.h" #include "cc/surfaces/display_scheduler.h" #include "cc/surfaces/surface.h" #include "cc/surfaces/surface_aggregator.h" #include "cc/surfaces/surface_manager.h" #include "gpu/command_buffer/client/gles2_interface.h" namespace cc { Display::Display(DisplayClient* client, SurfaceManager* manager, SharedBitmapManager* bitmap_manager, gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager, const RendererSettings& settings) : client_(client), manager_(manager), bitmap_manager_(bitmap_manager), gpu_memory_buffer_manager_(gpu_memory_buffer_manager), settings_(settings), device_scale_factor_(1.f), swapped_since_resize_(false), scheduler_(nullptr), texture_mailbox_deleter_(new TextureMailboxDeleter(nullptr)) { manager_->AddObserver(this); } Display::~Display() { manager_->RemoveObserver(this); if (aggregator_) { for (const auto& id_entry : aggregator_->previous_contained_surfaces()) { Surface* surface = manager_->GetSurfaceForId(id_entry.first); if (surface) surface->RunDrawCallbacks(SurfaceDrawStatus::DRAW_SKIPPED); } } } bool Display::Initialize(scoped_ptr<OutputSurface> output_surface, DisplayScheduler* scheduler) { output_surface_ = output_surface.Pass(); scheduler_ = scheduler; return output_surface_->BindToClient(this); } void Display::SetSurfaceId(SurfaceId id, float device_scale_factor) { if (current_surface_id_ == id && device_scale_factor_ == device_scale_factor) return; current_surface_id_ = id; device_scale_factor_ = device_scale_factor; UpdateRootSurfaceResourcesLocked(); if (scheduler_) scheduler_->EntireDisplayDamaged(id); } void Display::Resize(const gfx::Size& size) { if (size == current_surface_size_) return; // Need to ensure all pending swaps have executed before the window is // resized, or D3D11 will scale the swap output. if (settings_.finish_rendering_on_resize) { if (!swapped_since_resize_ && scheduler_) scheduler_->ForceImmediateSwapIfPossible(); if (swapped_since_resize_ && output_surface_ && output_surface_->context_provider()) output_surface_->context_provider()->ContextGL()->ShallowFinishCHROMIUM(); } swapped_since_resize_ = false; current_surface_size_ = size; if (scheduler_) scheduler_->EntireDisplayDamaged(current_surface_id_); } void Display::SetExternalClip(const gfx::Rect& clip) { external_clip_ = clip; } void Display::InitializeRenderer() { if (resource_provider_) return; // Display does not use GpuMemoryBuffers, so persistent map is not relevant. bool use_persistent_map_for_gpu_memory_buffers = false; scoped_ptr<ResourceProvider> resource_provider = ResourceProvider::Create( output_surface_.get(), bitmap_manager_, gpu_memory_buffer_manager_, nullptr, settings_.highp_threshold_min, settings_.use_rgba_4444_textures, settings_.texture_id_allocation_chunk_size, use_persistent_map_for_gpu_memory_buffers); if (!resource_provider) return; if (output_surface_->context_provider()) { scoped_ptr<GLRenderer> renderer = GLRenderer::Create( this, &settings_, output_surface_.get(), resource_provider.get(), texture_mailbox_deleter_.get(), settings_.highp_threshold_min); if (!renderer) return; renderer_ = renderer.Pass(); } else { scoped_ptr<SoftwareRenderer> renderer = SoftwareRenderer::Create( this, &settings_, output_surface_.get(), resource_provider.get()); if (!renderer) return; renderer_ = renderer.Pass(); } resource_provider_ = resource_provider.Pass(); aggregator_.reset(new SurfaceAggregator(manager_, resource_provider_.get())); } void Display::DidLoseOutputSurface() { if (scheduler_) scheduler_->OutputSurfaceLost(); // WARNING: The client may delete the Display in this method call. Do not // make any additional references to members after this call. client_->OutputSurfaceLost(); } void Display::UpdateRootSurfaceResourcesLocked() { Surface* surface = manager_->GetSurfaceForId(current_surface_id_); bool root_surface_resources_locked = !surface || !surface->GetEligibleFrame(); if (scheduler_) scheduler_->SetRootSurfaceResourcesLocked(root_surface_resources_locked); } bool Display::DrawAndSwap() { if (current_surface_id_.is_null()) return false; InitializeRenderer(); if (!output_surface_) return false; scoped_ptr<CompositorFrame> frame = aggregator_->Aggregate(current_surface_id_); if (!frame) return false; TRACE_EVENT0("cc", "Display::DrawAndSwap"); benchmark_instrumentation::IssueDisplayRenderingStatsEvent(); // Run callbacks early to allow pipelining. for (const auto& id_entry : aggregator_->previous_contained_surfaces()) { Surface* surface = manager_->GetSurfaceForId(id_entry.first); if (surface) surface->RunDrawCallbacks(SurfaceDrawStatus::DRAWN); } DelegatedFrameData* frame_data = frame->delegated_frame_data.get(); frame->metadata.latency_info.insert(frame->metadata.latency_info.end(), stored_latency_info_.begin(), stored_latency_info_.end()); stored_latency_info_.clear(); bool have_copy_requests = false; for (const auto* pass : frame_data->render_pass_list) { have_copy_requests |= !pass->copy_requests.empty(); } gfx::Size surface_size; bool have_damage = false; if (!frame_data->render_pass_list.empty()) { surface_size = frame_data->render_pass_list.back()->output_rect.size(); have_damage = !frame_data->render_pass_list.back()->damage_rect.size().IsEmpty(); } bool avoid_swap = surface_size != current_surface_size_; bool should_draw = !frame->metadata.latency_info.empty() || have_copy_requests || (have_damage && !avoid_swap); if (should_draw) { gfx::Rect device_viewport_rect = gfx::Rect(current_surface_size_); gfx::Rect device_clip_rect = external_clip_.IsEmpty() ? device_viewport_rect : external_clip_; bool disable_picture_quad_image_filtering = false; renderer_->DecideRenderPassAllocationsForFrame( frame_data->render_pass_list); renderer_->DrawFrame(&frame_data->render_pass_list, device_scale_factor_, device_viewport_rect, device_clip_rect, disable_picture_quad_image_filtering); } if (should_draw && !avoid_swap) { swapped_since_resize_ = true; renderer_->SwapBuffers(frame->metadata); } else { stored_latency_info_.insert(stored_latency_info_.end(), frame->metadata.latency_info.begin(), frame->metadata.latency_info.end()); DidSwapBuffers(); DidSwapBuffersComplete(); } return true; } void Display::DidSwapBuffers() { if (scheduler_) scheduler_->DidSwapBuffers(); } void Display::DidSwapBuffersComplete() { if (scheduler_) scheduler_->DidSwapBuffersComplete(); } void Display::CommitVSyncParameters(base::TimeTicks timebase, base::TimeDelta interval) { client_->CommitVSyncParameters(timebase, interval); } void Display::SetMemoryPolicy(const ManagedMemoryPolicy& policy) { client_->SetMemoryPolicy(policy); } void Display::OnDraw() { NOTREACHED(); } void Display::SetNeedsRedrawRect(const gfx::Rect& damage_rect) { NOTREACHED(); } void Display::ReclaimResources(const CompositorFrameAck* ack) { NOTREACHED(); } void Display::SetExternalDrawConstraints( const gfx::Transform& transform, const gfx::Rect& viewport, const gfx::Rect& clip, const gfx::Rect& viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority, bool resourceless_software_draw) { NOTREACHED(); } void Display::SetTreeActivationCallback(const base::Closure& callback) { NOTREACHED(); } void Display::SetFullRootLayerDamage() { if (aggregator_ && !current_surface_id_.is_null()) aggregator_->SetFullDamageForSurface(current_surface_id_); } void Display::OnSurfaceDamaged(SurfaceId surface_id, bool* changed) { if (aggregator_ && aggregator_->previous_contained_surfaces().count(surface_id)) { Surface* surface = manager_->GetSurfaceForId(surface_id); if (surface) { const CompositorFrame* current_frame = surface->GetEligibleFrame(); if (!current_frame || !current_frame->delegated_frame_data || !current_frame->delegated_frame_data->resource_list.size()) { aggregator_->ReleaseResources(surface_id); } } if (scheduler_) scheduler_->SurfaceDamaged(surface_id); *changed = true; } else if (surface_id == current_surface_id_) { if (scheduler_) scheduler_->SurfaceDamaged(surface_id); *changed = true; } if (surface_id == current_surface_id_) UpdateRootSurfaceResourcesLocked(); } SurfaceId Display::CurrentSurfaceId() { return current_surface_id_; } } // namespace cc <commit_msg>Trace LatencyInfo flow event in Display::DrawAndSwap()<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 "cc/surfaces/display.h" #include "base/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "cc/debug/benchmark_instrumentation.h" #include "cc/output/compositor_frame.h" #include "cc/output/compositor_frame_ack.h" #include "cc/output/direct_renderer.h" #include "cc/output/gl_renderer.h" #include "cc/output/renderer_settings.h" #include "cc/output/software_renderer.h" #include "cc/output/texture_mailbox_deleter.h" #include "cc/surfaces/display_client.h" #include "cc/surfaces/display_scheduler.h" #include "cc/surfaces/surface.h" #include "cc/surfaces/surface_aggregator.h" #include "cc/surfaces/surface_manager.h" #include "gpu/command_buffer/client/gles2_interface.h" namespace cc { Display::Display(DisplayClient* client, SurfaceManager* manager, SharedBitmapManager* bitmap_manager, gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager, const RendererSettings& settings) : client_(client), manager_(manager), bitmap_manager_(bitmap_manager), gpu_memory_buffer_manager_(gpu_memory_buffer_manager), settings_(settings), device_scale_factor_(1.f), swapped_since_resize_(false), scheduler_(nullptr), texture_mailbox_deleter_(new TextureMailboxDeleter(nullptr)) { manager_->AddObserver(this); } Display::~Display() { manager_->RemoveObserver(this); if (aggregator_) { for (const auto& id_entry : aggregator_->previous_contained_surfaces()) { Surface* surface = manager_->GetSurfaceForId(id_entry.first); if (surface) surface->RunDrawCallbacks(SurfaceDrawStatus::DRAW_SKIPPED); } } } bool Display::Initialize(scoped_ptr<OutputSurface> output_surface, DisplayScheduler* scheduler) { output_surface_ = output_surface.Pass(); scheduler_ = scheduler; return output_surface_->BindToClient(this); } void Display::SetSurfaceId(SurfaceId id, float device_scale_factor) { if (current_surface_id_ == id && device_scale_factor_ == device_scale_factor) return; current_surface_id_ = id; device_scale_factor_ = device_scale_factor; UpdateRootSurfaceResourcesLocked(); if (scheduler_) scheduler_->EntireDisplayDamaged(id); } void Display::Resize(const gfx::Size& size) { if (size == current_surface_size_) return; // Need to ensure all pending swaps have executed before the window is // resized, or D3D11 will scale the swap output. if (settings_.finish_rendering_on_resize) { if (!swapped_since_resize_ && scheduler_) scheduler_->ForceImmediateSwapIfPossible(); if (swapped_since_resize_ && output_surface_ && output_surface_->context_provider()) output_surface_->context_provider()->ContextGL()->ShallowFinishCHROMIUM(); } swapped_since_resize_ = false; current_surface_size_ = size; if (scheduler_) scheduler_->EntireDisplayDamaged(current_surface_id_); } void Display::SetExternalClip(const gfx::Rect& clip) { external_clip_ = clip; } void Display::InitializeRenderer() { if (resource_provider_) return; // Display does not use GpuMemoryBuffers, so persistent map is not relevant. bool use_persistent_map_for_gpu_memory_buffers = false; scoped_ptr<ResourceProvider> resource_provider = ResourceProvider::Create( output_surface_.get(), bitmap_manager_, gpu_memory_buffer_manager_, nullptr, settings_.highp_threshold_min, settings_.use_rgba_4444_textures, settings_.texture_id_allocation_chunk_size, use_persistent_map_for_gpu_memory_buffers); if (!resource_provider) return; if (output_surface_->context_provider()) { scoped_ptr<GLRenderer> renderer = GLRenderer::Create( this, &settings_, output_surface_.get(), resource_provider.get(), texture_mailbox_deleter_.get(), settings_.highp_threshold_min); if (!renderer) return; renderer_ = renderer.Pass(); } else { scoped_ptr<SoftwareRenderer> renderer = SoftwareRenderer::Create( this, &settings_, output_surface_.get(), resource_provider.get()); if (!renderer) return; renderer_ = renderer.Pass(); } resource_provider_ = resource_provider.Pass(); aggregator_.reset(new SurfaceAggregator(manager_, resource_provider_.get())); } void Display::DidLoseOutputSurface() { if (scheduler_) scheduler_->OutputSurfaceLost(); // WARNING: The client may delete the Display in this method call. Do not // make any additional references to members after this call. client_->OutputSurfaceLost(); } void Display::UpdateRootSurfaceResourcesLocked() { Surface* surface = manager_->GetSurfaceForId(current_surface_id_); bool root_surface_resources_locked = !surface || !surface->GetEligibleFrame(); if (scheduler_) scheduler_->SetRootSurfaceResourcesLocked(root_surface_resources_locked); } bool Display::DrawAndSwap() { if (current_surface_id_.is_null()) return false; InitializeRenderer(); if (!output_surface_) return false; scoped_ptr<CompositorFrame> frame = aggregator_->Aggregate(current_surface_id_); if (!frame) return false; TRACE_EVENT0("cc", "Display::DrawAndSwap"); benchmark_instrumentation::IssueDisplayRenderingStatsEvent(); // Run callbacks early to allow pipelining. for (const auto& id_entry : aggregator_->previous_contained_surfaces()) { Surface* surface = manager_->GetSurfaceForId(id_entry.first); if (surface) surface->RunDrawCallbacks(SurfaceDrawStatus::DRAWN); } DelegatedFrameData* frame_data = frame->delegated_frame_data.get(); frame->metadata.latency_info.insert(frame->metadata.latency_info.end(), stored_latency_info_.begin(), stored_latency_info_.end()); stored_latency_info_.clear(); bool have_copy_requests = false; for (const auto* pass : frame_data->render_pass_list) { have_copy_requests |= !pass->copy_requests.empty(); } gfx::Size surface_size; bool have_damage = false; if (!frame_data->render_pass_list.empty()) { surface_size = frame_data->render_pass_list.back()->output_rect.size(); have_damage = !frame_data->render_pass_list.back()->damage_rect.size().IsEmpty(); } bool avoid_swap = surface_size != current_surface_size_; bool should_draw = !frame->metadata.latency_info.empty() || have_copy_requests || (have_damage && !avoid_swap); if (should_draw) { gfx::Rect device_viewport_rect = gfx::Rect(current_surface_size_); gfx::Rect device_clip_rect = external_clip_.IsEmpty() ? device_viewport_rect : external_clip_; bool disable_picture_quad_image_filtering = false; renderer_->DecideRenderPassAllocationsForFrame( frame_data->render_pass_list); renderer_->DrawFrame(&frame_data->render_pass_list, device_scale_factor_, device_viewport_rect, device_clip_rect, disable_picture_quad_image_filtering); } if (should_draw && !avoid_swap) { swapped_since_resize_ = true; for (auto& latency : frame->metadata.latency_info) { TRACE_EVENT_FLOW_STEP0( "input,benchmark", "LatencyInfo.Flow", TRACE_ID_DONT_MANGLE(latency.trace_id), "Display::DrawAndSwap"); } renderer_->SwapBuffers(frame->metadata); } else { stored_latency_info_.insert(stored_latency_info_.end(), frame->metadata.latency_info.begin(), frame->metadata.latency_info.end()); DidSwapBuffers(); DidSwapBuffersComplete(); } return true; } void Display::DidSwapBuffers() { if (scheduler_) scheduler_->DidSwapBuffers(); } void Display::DidSwapBuffersComplete() { if (scheduler_) scheduler_->DidSwapBuffersComplete(); } void Display::CommitVSyncParameters(base::TimeTicks timebase, base::TimeDelta interval) { client_->CommitVSyncParameters(timebase, interval); } void Display::SetMemoryPolicy(const ManagedMemoryPolicy& policy) { client_->SetMemoryPolicy(policy); } void Display::OnDraw() { NOTREACHED(); } void Display::SetNeedsRedrawRect(const gfx::Rect& damage_rect) { NOTREACHED(); } void Display::ReclaimResources(const CompositorFrameAck* ack) { NOTREACHED(); } void Display::SetExternalDrawConstraints( const gfx::Transform& transform, const gfx::Rect& viewport, const gfx::Rect& clip, const gfx::Rect& viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority, bool resourceless_software_draw) { NOTREACHED(); } void Display::SetTreeActivationCallback(const base::Closure& callback) { NOTREACHED(); } void Display::SetFullRootLayerDamage() { if (aggregator_ && !current_surface_id_.is_null()) aggregator_->SetFullDamageForSurface(current_surface_id_); } void Display::OnSurfaceDamaged(SurfaceId surface_id, bool* changed) { if (aggregator_ && aggregator_->previous_contained_surfaces().count(surface_id)) { Surface* surface = manager_->GetSurfaceForId(surface_id); if (surface) { const CompositorFrame* current_frame = surface->GetEligibleFrame(); if (!current_frame || !current_frame->delegated_frame_data || !current_frame->delegated_frame_data->resource_list.size()) { aggregator_->ReleaseResources(surface_id); } } if (scheduler_) scheduler_->SurfaceDamaged(surface_id); *changed = true; } else if (surface_id == current_surface_id_) { if (scheduler_) scheduler_->SurfaceDamaged(surface_id); *changed = true; } if (surface_id == current_surface_id_) UpdateRootSurfaceResourcesLocked(); } SurfaceId Display::CurrentSurfaceId() { return current_surface_id_; } } // namespace cc <|endoftext|>
<commit_before>#include "Variant.h" #include "split.h" #include "cdflib.hpp" #include "pdflib.hpp" #include "var.hpp" #include <string> #include <iostream> #include <math.h> #include <cmath> #include <stdlib.h> #include <time.h> #include <stdio.h> #include <getopt.h> using namespace std; using namespace vcf; void printVersion(void){ cerr << "INFO: version 1.0.0 ; date: April 2014 ; author: Zev Kronenberg; email : [email protected] " << endl; } void printHelp(void){ cerr << endl << endl; cerr << "INFO: help" << endl; cerr << "INFO: description:" << endl; cerr << " General population genetic statistics for each SNP " << endl << endl; cerr << "Output : 9 columns : " << endl; cerr << " 1. seqid " << endl; cerr << " 2. position " << endl; cerr << " 3. target allele frequency " << endl; cerr << " 4. expected heterozygosity " << endl; cerr << " 5. observed heterozygosity " << endl; cerr << " 6. number of hets " << endl; cerr << " 7. number of homozygous ref " << endl; cerr << " 8. number of homozygous alt " << endl; cerr << " 9. target Fis " << endl; cerr << "INFO: usage: popStat --type PL --target 0,1,2,3,4,5,6,7 --file my.vcf " << endl; cerr << endl; cerr << "INFO: required: t,target -- a zero based comma seperated list of target individuals corrisponding to VCF columns " << endl; cerr << "INFO: required: f,file -- proper formatted VCF " << endl; cerr << "INFO: required, y,type -- genotype likelihood format; genotype : GL,PL,GP " << endl; cerr << "INFO: optional, r,region -- a tabix compliant region : chr1:1-1000 or chr1 " << endl; printVersion(); } double bound(double v){ if(v <= 0.00001){ return 0.00001; } if(v >= 0.99999){ return 0.99999; } return v; } void loadIndices(map<int, int> & index, string set){ vector<string> indviduals = split(set, ","); vector<string>::iterator it = indviduals.begin(); for(; it != indviduals.end(); it++){ index[ atoi( (*it).c_str() ) ] = 1; } } int main(int argc, char** argv) { // set the random seed for MCMC srand((unsigned)time(NULL)); // the filename string filename = "NA"; // set region to scaffold string region = "NA"; // using vcflib; thanks to Erik Garrison VariantCallFile variantFile; // zero based index for the target and background indivudals map<int, int> it, ib; // genotype likelihood format string type = "NA"; const struct option longopts[] = { {"version" , 0, 0, 'v'}, {"help" , 0, 0, 'h'}, {"file" , 1, 0, 'f'}, {"target" , 1, 0, 't'}, {"region" , 1, 0, 'r'}, {"type" , 1, 0, 'y'}, {0,0,0,0} }; int index; int iarg=0; while(iarg != -1) { iarg = getopt_long(argc, argv, "y:r:d:t:b:f:chv", longopts, &index); switch (iarg) { case 'h': printHelp(); return 0; case 'v': printVersion(); return 0; case 't': loadIndices(it, optarg); cerr << "INFO: there are " << it.size() << " individuals in the target" << endl; cerr << "INFO: target ids: " << optarg << endl; break; case 'b': loadIndices(ib, optarg); cerr << "INFO: there are " << ib.size() << " individuals in the background" << endl; cerr << "INFO: background ids: " << optarg << endl; break; case 'f': cerr << "INFO: file: " << optarg << endl; filename = optarg; break; case 'r': cerr << "INFO: set seqid region to : " << optarg << endl; region = optarg; break; case 'y': type = optarg; cerr << "INFO: set genotype likelihood to: " << type; break; default: break; } } if(filename == "NA"){ cerr << "FATAL: failed to specify a file" << endl; printHelp(); } if(!variantFile.open(filename)){ cerr << "FATAL: could not open file for reading" << endl; printHelp(); } if(region != "NA"){ variantFile.setRegion(region); } if (!variantFile.is_open()) { cerr << "FATAL: could not open VCF for reading" << endl; printHelp(); return 1; } map<string, int> okayGenotypeLikelihoods; okayGenotypeLikelihoods["PL"] = 1; okayGenotypeLikelihoods["GL"] = 1; okayGenotypeLikelihoods["GP"] = 1; if(type == "NA"){ cerr << "FATAL: failed to specify genotype likelihood format : PL or GL" << endl; printHelp(); return 1; } if(okayGenotypeLikelihoods.find(type) == okayGenotypeLikelihoods.end()){ cerr << "FATAL: genotype likelihood is incorrectly formatted, only use: PL or GL" << endl; printHelp(); return 1; } Variant var(variantFile); while (variantFile.getNextVariant(var)) { map<string, map<string, vector<string> > >::iterator s = var.samples.begin(); map<string, map<string, vector<string> > >::iterator sEnd = var.samples.end(); // biallelic sites naturally if(var.alt.size() > 1){ continue; } vector < map< string, vector<string> > > target, background, total; int index = 0; for (; s != sEnd; ++s) { map<string, vector<string> >& sample = s->second; if(sample["GT"].front() != "./."){ if(it.find(index) != it.end() ){ target.push_back(sample); } } index += 1; } genotype * populationTarget ; genotype * populationBackground ; if(type == "PL"){ populationTarget = new pl(); } if(type == "GL"){ populationTarget = new gl(); } if(type == "GP"){ populationTarget = new gp(); } populationTarget->loadPop(target, var.sequenceName, var.position); //cerr << " 3. target allele frequency " << endl; //cerr << " 4. expected heterozygosity " << endl; //cerr << " 5. observed heterozygosity " << endl; //cerr << " 6. number of hets " << endl; //cerr << " 7. number of homozygous ref " << endl; //cerr << " 8. number of homozygous alt " << endl; //cerr << " 9. target Fis " << endl; double ehet = 2*(populationTarget->af * (1 - populationTarget->af)); cout << var.sequenceName << "\t" << var.position << "\t" << populationTarget->af << "\t" << ehet << "\t" << populationTarget->hfrq << "\t" << populationTarget->nhet << "\t" << populationTarget->nhomr << "\t" << populationTarget->nhoma << "\t" << populationTarget->fis << endl; } return 0; } <commit_msg>skipping -1 af sites<commit_after>#include "Variant.h" #include "split.h" #include "cdflib.hpp" #include "pdflib.hpp" #include "var.hpp" #include <string> #include <iostream> #include <math.h> #include <cmath> #include <stdlib.h> #include <time.h> #include <stdio.h> #include <getopt.h> using namespace std; using namespace vcf; void printVersion(void){ cerr << "INFO: version 1.0.0 ; date: April 2014 ; author: Zev Kronenberg; email : [email protected] " << endl; } void printHelp(void){ cerr << endl << endl; cerr << "INFO: help" << endl; cerr << "INFO: description:" << endl; cerr << " General population genetic statistics for each SNP " << endl << endl; cerr << "Output : 9 columns : " << endl; cerr << " 1. seqid " << endl; cerr << " 2. position " << endl; cerr << " 3. target allele frequency " << endl; cerr << " 4. expected heterozygosity " << endl; cerr << " 5. observed heterozygosity " << endl; cerr << " 6. number of hets " << endl; cerr << " 7. number of homozygous ref " << endl; cerr << " 8. number of homozygous alt " << endl; cerr << " 9. target Fis " << endl; cerr << "INFO: usage: popStat --type PL --target 0,1,2,3,4,5,6,7 --file my.vcf " << endl; cerr << endl; cerr << "INFO: required: t,target -- a zero based comma seperated list of target individuals corrisponding to VCF columns " << endl; cerr << "INFO: required: f,file -- proper formatted VCF " << endl; cerr << "INFO: required, y,type -- genotype likelihood format; genotype : GL,PL,GP " << endl; cerr << "INFO: optional, r,region -- a tabix compliant region : chr1:1-1000 or chr1 " << endl; printVersion(); } double bound(double v){ if(v <= 0.00001){ return 0.00001; } if(v >= 0.99999){ return 0.99999; } return v; } void loadIndices(map<int, int> & index, string set){ vector<string> indviduals = split(set, ","); vector<string>::iterator it = indviduals.begin(); for(; it != indviduals.end(); it++){ index[ atoi( (*it).c_str() ) ] = 1; } } int main(int argc, char** argv) { // set the random seed for MCMC srand((unsigned)time(NULL)); // the filename string filename = "NA"; // set region to scaffold string region = "NA"; // using vcflib; thanks to Erik Garrison VariantCallFile variantFile; // zero based index for the target and background indivudals map<int, int> it, ib; // genotype likelihood format string type = "NA"; const struct option longopts[] = { {"version" , 0, 0, 'v'}, {"help" , 0, 0, 'h'}, {"file" , 1, 0, 'f'}, {"target" , 1, 0, 't'}, {"region" , 1, 0, 'r'}, {"type" , 1, 0, 'y'}, {0,0,0,0} }; int index; int iarg=0; while(iarg != -1) { iarg = getopt_long(argc, argv, "y:r:d:t:b:f:chv", longopts, &index); switch (iarg) { case 'h': printHelp(); return 0; case 'v': printVersion(); return 0; case 't': loadIndices(it, optarg); cerr << "INFO: there are " << it.size() << " individuals in the target" << endl; cerr << "INFO: target ids: " << optarg << endl; break; case 'b': loadIndices(ib, optarg); cerr << "INFO: there are " << ib.size() << " individuals in the background" << endl; cerr << "INFO: background ids: " << optarg << endl; break; case 'f': cerr << "INFO: file: " << optarg << endl; filename = optarg; break; case 'r': cerr << "INFO: set seqid region to : " << optarg << endl; region = optarg; break; case 'y': type = optarg; cerr << "INFO: set genotype likelihood to: " << type; break; default: break; } } if(filename == "NA"){ cerr << "FATAL: failed to specify a file" << endl; printHelp(); } if(!variantFile.open(filename)){ cerr << "FATAL: could not open file for reading" << endl; printHelp(); } if(region != "NA"){ variantFile.setRegion(region); } if (!variantFile.is_open()) { cerr << "FATAL: could not open VCF for reading" << endl; printHelp(); return 1; } map<string, int> okayGenotypeLikelihoods; okayGenotypeLikelihoods["PL"] = 1; okayGenotypeLikelihoods["GL"] = 1; okayGenotypeLikelihoods["GP"] = 1; if(type == "NA"){ cerr << "FATAL: failed to specify genotype likelihood format : PL or GL" << endl; printHelp(); return 1; } if(okayGenotypeLikelihoods.find(type) == okayGenotypeLikelihoods.end()){ cerr << "FATAL: genotype likelihood is incorrectly formatted, only use: PL or GL" << endl; printHelp(); return 1; } Variant var(variantFile); while (variantFile.getNextVariant(var)) { map<string, map<string, vector<string> > >::iterator s = var.samples.begin(); map<string, map<string, vector<string> > >::iterator sEnd = var.samples.end(); // biallelic sites naturally if(var.alt.size() > 1){ continue; } vector < map< string, vector<string> > > target, background, total; int index = 0; for (; s != sEnd; ++s) { map<string, vector<string> >& sample = s->second; if(sample["GT"].front() != "./."){ if(it.find(index) != it.end() ){ target.push_back(sample); } } index += 1; } genotype * populationTarget ; genotype * populationBackground ; if(type == "PL"){ populationTarget = new pl(); } if(type == "GL"){ populationTarget = new gl(); } if(type == "GP"){ populationTarget = new gp(); } populationTarget->loadPop(target, var.sequenceName, var.position); //cerr << " 3. target allele frequency " << endl; //cerr << " 4. expected heterozygosity " << endl; //cerr << " 5. observed heterozygosity " << endl; //cerr << " 6. number of hets " << endl; //cerr << " 7. number of homozygous ref " << endl; //cerr << " 8. number of homozygous alt " << endl; //cerr << " 9. target Fis " << endl; if(populationTarget->af == -1){ continue; } double ehet = 2*(populationTarget->af * (1 - populationTarget->af)); cout << var.sequenceName << "\t" << var.position << "\t" << populationTarget->af << "\t" << ehet << "\t" << populationTarget->hfrq << "\t" << populationTarget->nhet << "\t" << populationTarget->nhomr << "\t" << populationTarget->nhoma << "\t" << populationTarget->fis << endl; } return 0; } <|endoftext|>
<commit_before> #define TC_LIST_TEMPLATE \ typename T, uint32_t DEFAULT_ELEMENT_COUNT, class AllocatorType, class Policy #define TC_LIST_TEMPLATE_PARAMS \ T, DEFAULT_ELEMENT_COUNT, AllocatorType, Policy template< TC_LIST_TEMPLATE > void TCList< TC_LIST_TEMPLATE_PARAMS >::_SetFirst( ElementType* /*pEl*/ ) { } template< TC_LIST_TEMPLATE > void TCList< TC_LIST_TEMPLATE_PARAMS >::_SetIdxs( uint32_t setIdx ) { for( uint32_t i = setIdx; i < this->m_resizeElementCount; ++i ) { auto& El = this->m_pCurrPtr[i]; El.nextIdx = i + 1; El.prevIdx = i - 1; } this->m_pCurrPtr[this->m_resizeElementCount - 1].nextIdx = Npos(); m_firstAddedIdx = Npos(); m_lastAddedIdx = Npos(); m_BeginItr.m_pCurr = &this->m_pCurrPtr[ Npos() ]; m_BeginItr.m_pData = this->m_pCurrPtr; m_EndItr = m_BeginItr; } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::PushBack( const T& Data ) { if( this->m_count < this->m_resizeElementCount ) { // Get next free element //const auto currIdx = m_nextFreeIdx; //VKE_ASSERT( currIdx > 0, "" ); //auto& El = this->m_pCurrPtr[currIdx]; //// Get last added element //auto& LastEl = this->m_pCurrPtr[m_lastAddedIdx]; //El.prevIdx = m_lastAddedIdx; //m_lastAddedIdx = m_nextFreeIdx; //// Set next free element //m_nextFreeIdx = El.nextIdx; //VKE_ASSERT( m_nextFreeIdx > 0, "" ); //// Set next id of current element to 0 //El.nextIdx = 0; //El.Data = Data; //LastEl.nextIdx = currIdx; //if( this->m_count == 0 ) //{ // m_firstAddedIdx = currIdx; // VKE_ASSERT( m_firstAddedIdx > 0, "" ); //} VKE_ASSERT( m_nextFreeIdx != Npos(), "" ); const uint32_t currIdx = m_nextFreeIdx; auto& CurrElement = this->m_pCurrPtr[ currIdx ]; m_nextFreeIdx = CurrElement.nextIdx; CurrElement.prevIdx = m_lastAddedIdx; CurrElement.nextIdx = Npos(); CurrElement.Data = Data; m_lastAddedIdx = currIdx; if( this->m_count == 0 ) { m_firstAddedIdx = currIdx; m_BeginItr.m_pCurr = &this->m_pCurrPtr[m_firstAddedIdx]; m_BeginItr.m_pData = this->m_pCurrPtr; } else { VKE_ASSERT( CurrElement.prevIdx != Npos(), "" ); auto& PrevElement = this->m_pCurrPtr[CurrElement.prevIdx]; PrevElement.nextIdx = currIdx; } this->m_count++; return true; } else { if( Resize( this->m_count * 2 ) ) { return PushBack( Data ); } return false; } } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::_Remove( uint32_t idx, DataTypePtr pOut ) { //// Note idx must be > 0 //assert( idx > 0 ); //auto& CurrEl = this->m_pCurrPtr[idx]; //auto& NextEl = this->m_pCurrPtr[CurrEl.nextIdx]; //auto& PrevEl = this->m_pCurrPtr[CurrEl.prevIdx]; //const auto currIdx = NextEl.prevIdx; //assert( idx == currIdx || idx == m_lastAddedIdx ); //const auto nextIdx = CurrEl.nextIdx; //PrevEl.nextIdx = CurrEl.nextIdx; //NextEl.prevIdx = CurrEl.prevIdx; //CurrEl.nextIdx = m_nextFreeIdx; //m_nextFreeIdx = currIdx ? currIdx : 1; //VKE_ASSERT( m_nextFreeIdx > 0, "" ); //if( m_firstAddedIdx == currIdx ) //{ // m_firstAddedIdx = nextIdx; //} //this->m_count--; //if( pOut ) //{ // *pOut = CurrEl.Data; //} bool ret = true; this->m_count--; auto& CurrEl = this->m_pCurrPtr[ idx ]; uint32_t currIdx = Npos(); auto pNextEl = &CurrEl; auto pPrevEl = &CurrEl; if( CurrEl.nextIdx != Npos() ) { // A case when current element is not a last one auto& NextEl = this->m_pCurrPtr[CurrEl.nextIdx]; currIdx = NextEl.prevIdx; VKE_ASSERT( NextEl.prevIdx == idx, "" ); pNextEl = &NextEl; } if( CurrEl.prevIdx != Npos() ) { // A case when current element is not a first one auto& PrevEl = this->m_pCurrPtr[CurrEl.prevIdx]; VKE_ASSERT( PrevEl.nextIdx == idx, "" ); currIdx = PrevEl.nextIdx; pPrevEl = &PrevEl; } else { // A first element in the list // Change begin iterator m_BeginItr.m_pCurr = &this->m_pCurrPtr[CurrEl.nextIdx]; } pPrevEl->nextIdx = CurrEl.nextIdx; pNextEl->prevIdx = CurrEl.prevIdx; *pOut = CurrEl.Data; // Update free elements CurrEl.nextIdx = m_nextFreeIdx; m_nextFreeIdx = idx; return ret; } template< TC_LIST_TEMPLATE > T TCList< TC_LIST_TEMPLATE_PARAMS >::Remove( const Iterator& Itr ) { //if( Itr != end() ) //const auto EndItr = end(); //VKE_ASSERT( Itr != EndItr, "" ); VKE_ASSERT( this->m_count > 0, "" ); { // Find out current element index ElementType& CurrEl = *Itr.m_pCurr; // If current element has next index get nextElement->prevElement uint32_t currIdx = Npos(); if( CurrEl.nextIdx != Npos() ) { // A case when current element is not a last one auto& NextEl = this->m_pCurrPtr[ CurrEl.nextIdx ]; currIdx = NextEl.prevIdx; } else if( CurrEl.prevIdx != Npos() ) { // A case when current element is not a first one auto& PrevEl = this->m_pCurrPtr[ CurrEl.prevIdx ]; currIdx = PrevEl.nextIdx; } else { currIdx = m_firstAddedIdx; } DataType Tmp; _Remove( currIdx, &Tmp ); return Tmp; } return T(); } template< TC_LIST_TEMPLATE > template< class ItrType > ItrType TCList< TC_LIST_TEMPLATE_PARAMS >::_Find( CountType idx ) { uint32_t currIdx = 0; const auto& EndItr = end(); for( auto& Itr = begin(); Itr != EndItr; ++Itr, ++currIdx ) { if( currIdx == idx ) { return Itr; } } return EndItr; } template< TC_LIST_TEMPLATE > template< class ItrType > ItrType TCList< TC_LIST_TEMPLATE_PARAMS >::_Find( const DataTypeRef Data ) { const auto& EndItr = end(); for( auto& Itr = begin(); Itr != EndItr; ++Itr, ++currIdx ) { if( Data == Itr ) { return Itr; } } return EndItr; } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::PopFront( DataTypePtr pOut ) { bool ret = false; if( !this->IsEmpty() ) { PopFrontFast( pOut ); ret = true; } return ret; } template< TC_LIST_TEMPLATE > void TCList< TC_LIST_TEMPLATE_PARAMS >::PopFrontFast( DataTypePtr pOut ) { { *pOut = Remove( begin() ); } } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::PopBack( DataTypePtr pOut ) { bool ret = false; if( !this->IsEmpty() ) { PopBackFast( pOut ); ret = true; } return ret; } template< TC_LIST_TEMPLATE > void TCList< TC_LIST_TEMPLATE_PARAMS >::PopBackFast( DataTypePtr pOut ) { { _Remove( m_lastAddedIdx, pOut ); } } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::Resize( CountType count ) { bool ret = Base::Resize( count ); m_BeginItr.m_pData = this->m_pCurrPtr; m_EndItr.m_pData = this->m_pCurrPtr; m_EndItr.m_pCurr = &this->m_pCurrPtr[ Npos() ]; return ret; } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::Resize( CountType count, const DataTypeRef Default ) { bool ret = Base::Resize( count, Default ); m_BeginItr.m_pData = this->m_pCurrPtr; m_EndItr.m_pData = this->m_pCurrPtr; m_EndItr.m_pCurr = &this->m_pCurrPtr[ Npos() ]; return ret; }<commit_msg>List remove fix<commit_after> #define TC_LIST_TEMPLATE \ typename T, uint32_t DEFAULT_ELEMENT_COUNT, class AllocatorType, class Policy #define TC_LIST_TEMPLATE_PARAMS \ T, DEFAULT_ELEMENT_COUNT, AllocatorType, Policy template< TC_LIST_TEMPLATE > void TCList< TC_LIST_TEMPLATE_PARAMS >::_SetFirst( ElementType* /*pEl*/ ) { } template< TC_LIST_TEMPLATE > void TCList< TC_LIST_TEMPLATE_PARAMS >::_SetIdxs( uint32_t setIdx ) { for( uint32_t i = setIdx; i < this->m_resizeElementCount; ++i ) { auto& El = this->m_pCurrPtr[i]; El.nextIdx = i + 1; El.prevIdx = i - 1; } this->m_pCurrPtr[this->m_resizeElementCount - 1].nextIdx = Npos(); m_firstAddedIdx = Npos(); m_lastAddedIdx = Npos(); m_BeginItr.m_pCurr = &this->m_pCurrPtr[ Npos() ]; m_BeginItr.m_pData = this->m_pCurrPtr; m_EndItr = m_BeginItr; } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::PushBack( const T& Data ) { if( this->m_count < this->m_resizeElementCount ) { // Get next free element //const auto currIdx = m_nextFreeIdx; //VKE_ASSERT( currIdx > 0, "" ); //auto& El = this->m_pCurrPtr[currIdx]; //// Get last added element //auto& LastEl = this->m_pCurrPtr[m_lastAddedIdx]; //El.prevIdx = m_lastAddedIdx; //m_lastAddedIdx = m_nextFreeIdx; //// Set next free element //m_nextFreeIdx = El.nextIdx; //VKE_ASSERT( m_nextFreeIdx > 0, "" ); //// Set next id of current element to 0 //El.nextIdx = 0; //El.Data = Data; //LastEl.nextIdx = currIdx; //if( this->m_count == 0 ) //{ // m_firstAddedIdx = currIdx; // VKE_ASSERT( m_firstAddedIdx > 0, "" ); //} VKE_ASSERT( m_nextFreeIdx != Npos(), "" ); const uint32_t currIdx = m_nextFreeIdx; auto& CurrElement = this->m_pCurrPtr[ currIdx ]; m_nextFreeIdx = CurrElement.nextIdx; CurrElement.prevIdx = m_lastAddedIdx; CurrElement.nextIdx = Npos(); CurrElement.Data = Data; m_lastAddedIdx = currIdx; if( this->m_count == 0 ) { m_firstAddedIdx = currIdx; m_BeginItr.m_pCurr = &this->m_pCurrPtr[m_firstAddedIdx]; m_BeginItr.m_pData = this->m_pCurrPtr; } else { VKE_ASSERT( CurrElement.prevIdx != Npos(), "" ); auto& PrevElement = this->m_pCurrPtr[CurrElement.prevIdx]; PrevElement.nextIdx = currIdx; } this->m_count++; return true; } else { if( Resize( this->m_count * 2 ) ) { return PushBack( Data ); } return false; } } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::_Remove( uint32_t idx, DataTypePtr pOut ) { //// Note idx must be > 0 //assert( idx > 0 ); //auto& CurrEl = this->m_pCurrPtr[idx]; //auto& NextEl = this->m_pCurrPtr[CurrEl.nextIdx]; //auto& PrevEl = this->m_pCurrPtr[CurrEl.prevIdx]; //const auto currIdx = NextEl.prevIdx; //assert( idx == currIdx || idx == m_lastAddedIdx ); //const auto nextIdx = CurrEl.nextIdx; //PrevEl.nextIdx = CurrEl.nextIdx; //NextEl.prevIdx = CurrEl.prevIdx; //CurrEl.nextIdx = m_nextFreeIdx; //m_nextFreeIdx = currIdx ? currIdx : 1; //VKE_ASSERT( m_nextFreeIdx > 0, "" ); //if( m_firstAddedIdx == currIdx ) //{ // m_firstAddedIdx = nextIdx; //} //this->m_count--; //if( pOut ) //{ // *pOut = CurrEl.Data; //} bool ret = true; this->m_count--; const uint32_t NPOS = Npos(); auto& CurrEl = this->m_pCurrPtr[ idx ]; uint32_t currIdx = NPOS; auto pNextEl = &CurrEl; auto pPrevEl = &CurrEl; if( CurrEl.nextIdx != NPOS ) { // A case when current element is not a last one auto& NextEl = this->m_pCurrPtr[CurrEl.nextIdx]; currIdx = NextEl.prevIdx; VKE_ASSERT( NextEl.prevIdx == idx, "" ); pNextEl = &NextEl; } if( CurrEl.prevIdx != NPOS ) { // A case when current element is not a first one auto& PrevEl = this->m_pCurrPtr[CurrEl.prevIdx]; VKE_ASSERT( PrevEl.nextIdx == idx, "" ); currIdx = PrevEl.nextIdx; pPrevEl = &PrevEl; } else { // A first element in the list // Change begin iterator m_BeginItr.m_pCurr = &this->m_pCurrPtr[CurrEl.nextIdx]; // If last element is removed there is no last added one m_lastAddedIdx = NPOS; } pPrevEl->nextIdx = CurrEl.nextIdx; pNextEl->prevIdx = CurrEl.prevIdx; *pOut = CurrEl.Data; // Update free elements CurrEl.nextIdx = m_nextFreeIdx; m_nextFreeIdx = idx; return ret; } template< TC_LIST_TEMPLATE > T TCList< TC_LIST_TEMPLATE_PARAMS >::Remove( const Iterator& Itr ) { //if( Itr != end() ) //const auto EndItr = end(); //VKE_ASSERT( Itr != EndItr, "" ); VKE_ASSERT( this->m_count > 0, "" ); { // Find out current element index ElementType& CurrEl = *Itr.m_pCurr; // If current element has next index get nextElement->prevElement uint32_t currIdx = Npos(); if( CurrEl.nextIdx != Npos() ) { // A case when current element is not a last one auto& NextEl = this->m_pCurrPtr[ CurrEl.nextIdx ]; currIdx = NextEl.prevIdx; } else if( CurrEl.prevIdx != Npos() ) { // A case when current element is not a first one auto& PrevEl = this->m_pCurrPtr[ CurrEl.prevIdx ]; currIdx = PrevEl.nextIdx; } else { currIdx = m_firstAddedIdx; } DataType Tmp; _Remove( currIdx, &Tmp ); return Tmp; } return T(); } template< TC_LIST_TEMPLATE > template< class ItrType > ItrType TCList< TC_LIST_TEMPLATE_PARAMS >::_Find( CountType idx ) { uint32_t currIdx = 0; const auto& EndItr = end(); for( auto& Itr = begin(); Itr != EndItr; ++Itr, ++currIdx ) { if( currIdx == idx ) { return Itr; } } return EndItr; } template< TC_LIST_TEMPLATE > template< class ItrType > ItrType TCList< TC_LIST_TEMPLATE_PARAMS >::_Find( const DataTypeRef Data ) { const auto& EndItr = end(); for( auto& Itr = begin(); Itr != EndItr; ++Itr, ++currIdx ) { if( Data == Itr ) { return Itr; } } return EndItr; } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::PopFront( DataTypePtr pOut ) { bool ret = false; if( !this->IsEmpty() ) { PopFrontFast( pOut ); ret = true; } return ret; } template< TC_LIST_TEMPLATE > void TCList< TC_LIST_TEMPLATE_PARAMS >::PopFrontFast( DataTypePtr pOut ) { { *pOut = Remove( begin() ); } } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::PopBack( DataTypePtr pOut ) { bool ret = false; if( !this->IsEmpty() ) { PopBackFast( pOut ); ret = true; } return ret; } template< TC_LIST_TEMPLATE > void TCList< TC_LIST_TEMPLATE_PARAMS >::PopBackFast( DataTypePtr pOut ) { { _Remove( m_lastAddedIdx, pOut ); } } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::Resize( CountType count ) { bool ret = Base::Resize( count ); m_BeginItr.m_pData = this->m_pCurrPtr; m_EndItr.m_pData = this->m_pCurrPtr; m_EndItr.m_pCurr = &this->m_pCurrPtr[ Npos() ]; return ret; } template< TC_LIST_TEMPLATE > bool TCList< TC_LIST_TEMPLATE_PARAMS >::Resize( CountType count, const DataTypeRef Default ) { bool ret = Base::Resize( count, Default ); m_BeginItr.m_pData = this->m_pCurrPtr; m_EndItr.m_pData = this->m_pCurrPtr; m_EndItr.m_pCurr = &this->m_pCurrPtr[ Npos() ]; return ret; }<|endoftext|>
<commit_before>#ifndef XSIMD_CONFIG_HPP #define XSIMD_CONFIG_HPP /** * high level free functions * * @defgroup xsimd_config_macro Instruction Set Detection */ /** * @ingroup xsimd_config_macro * * Set to 1 if SSE2 is available at compile-time, to 0 otherwise. */ #ifdef __SSE2__ #define XSIMD_WITH_SSE2 1 #else #define XSIMD_WITH_SSE2 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if SSE3 is available at compile-time, to 0 otherwise. */ #ifdef __SSE3__ #define XSIMD_WITH_SSE3 1 #else #define XSIMD_WITH_SSE3 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if SSSE3 is available at compile-time, to 0 otherwise. */ #ifdef __SSSE3__ #define XSIMD_WITH_SSSE3 1 #else #define XSIMD_WITH_SSSE3 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if SSE4.1 is available at compile-time, to 0 otherwise. */ #ifdef __SSE4_1__ #define XSIMD_WITH_SSE4_1 1 #else #define XSIMD_WITH_SSE4_1 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if SSE4.2 is available at compile-time, to 0 otherwise. */ #ifdef __SSE4_2__ #define XSIMD_WITH_SSE4_2 1 #else #define XSIMD_WITH_SSE4_2 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX is available at compile-time, to 0 otherwise. */ #ifdef __AVX__ #define XSIMD_WITH_AVX 1 #else #define XSIMD_WITH_AVX 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX2 is available at compile-time, to 0 otherwise. */ #ifdef __AVX2__ #define XSIMD_WITH_AVX2 1 #else #define XSIMD_WITH_AVX2 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if FMA for SSE is available at compile-time, to 0 otherwise. */ #ifdef __FMA__ #if defined(__SSE__) && ! defined(__AVX__) #define XSIMD_WITH_FMA3 1 #else #define XSIMD_WITH_FMA3 0 #endif #else #define XSIMD_WITH_FMA3 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if FMA for AVX is available at compile-time, to 0 otherwise. */ #ifdef __FMA__ #if defined(__AVX__) #define XSIMD_WITH_FMA5 1 #else #define XSIMD_WITH_FMA5 0 #endif #else #define XSIMD_WITH_FMA5 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX512F is available at compile-time, to 0 otherwise. */ #ifdef __AVX512F__ // AVX512 instructions are supported starting with gcc 6 // see https://www.gnu.org/software/gcc/gcc-6/changes.html #if defined(__GNUC__) && __GNUC__ < 6 #define XSIMD_WITH_AVX512F 0 #else #define XSIMD_WITH_AVX512F 1 #if __GNUC__ == 6 #define XSIMD_AVX512_SHIFT_INTRINSICS_IMM_ONLY 1 #endif #endif #else #define XSIMD_WITH_AVX512F 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX512CD is available at compile-time, to 0 otherwise. */ #ifdef __AVX512CD__ // Avoids repeating the GCC workaround over and over #define XSIMD_WITH_AVX512CD XSIMD_WITH_AVX512F #else #define XSIMD_WITH_AVX512CD 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX512DQ is available at compile-time, to 0 otherwise. */ #ifdef __AVX512DQ__ #define XSIMD_WITH_AVX512DQ XSIMD_WITH_AVX512F #else #define XSIMD_WITH_AVX512DQ 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX512BW is available at compile-time, to 0 otherwise. */ #ifdef __AVX512BW__ #define XSIMD_WITH_AVX512BW XSIMD_WITH_AVX512F #else #define XSIMD_WITH_AVX512BW 0 #endif #ifdef __ARM_NEON /** * @ingroup xsimd_config_macro * * Set to 1 if NEON is available at compile-time, to 0 otherwise. */ #if __ARM_ARCH >= 7 #define XSIMD_WITH_NEON 1 #else #define XSIMD_WITH_NEON 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if NEON64 is available at compile-time, to 0 otherwise. */ #ifdef __aarch64__ #define XSIMD_WITH_NEON64 1 #else #define XSIMD_WITH_NEON64 0 #endif #else #define XSIMD_WITH_NEON 0 #define XSIMD_WITH_NEON64 0 #endif // Workaround for MSVC compiler #ifdef _MSC_VER #if XSIMD_WITH_AVX512 #define XSIMD_WITH_AVX2 1 #endif #if XSIMD_WITH_AVX2 #define XSIMD_WITH_AVX 1 #endif #if XSIMD_WITH_AVX #define XSIMD_WITH_SSE4_2 1 #endif #if XSIMD_WITH_SSE4_2 #define XSIMD_WITH_SSE4_1 1 #endif #if XSIMD_WITH_SSE4_1 #define XSIMD_WITH_SSSE3 1 #endif #if XSIMD_WITH_SSSE3 #define XSIMD_WITH_SSE3 1 #endif #if XSIMD_WITH_SSE3 #define XSIMD_WITH_SSE2 1 #endif #endif #endif <commit_msg>added XSIMD_VERSION_* defines back to config<commit_after>#ifndef XSIMD_CONFIG_HPP #define XSIMD_CONFIG_HPP #define XSIMD_VERSION_MAJOR 8 #define XSIMD_VERSION_MINOR 0 #define XSIMD_VERSION_PATCH 0 /** * high level free functions * * @defgroup xsimd_config_macro Instruction Set Detection */ /** * @ingroup xsimd_config_macro * * Set to 1 if SSE2 is available at compile-time, to 0 otherwise. */ #ifdef __SSE2__ #define XSIMD_WITH_SSE2 1 #else #define XSIMD_WITH_SSE2 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if SSE3 is available at compile-time, to 0 otherwise. */ #ifdef __SSE3__ #define XSIMD_WITH_SSE3 1 #else #define XSIMD_WITH_SSE3 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if SSSE3 is available at compile-time, to 0 otherwise. */ #ifdef __SSSE3__ #define XSIMD_WITH_SSSE3 1 #else #define XSIMD_WITH_SSSE3 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if SSE4.1 is available at compile-time, to 0 otherwise. */ #ifdef __SSE4_1__ #define XSIMD_WITH_SSE4_1 1 #else #define XSIMD_WITH_SSE4_1 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if SSE4.2 is available at compile-time, to 0 otherwise. */ #ifdef __SSE4_2__ #define XSIMD_WITH_SSE4_2 1 #else #define XSIMD_WITH_SSE4_2 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX is available at compile-time, to 0 otherwise. */ #ifdef __AVX__ #define XSIMD_WITH_AVX 1 #else #define XSIMD_WITH_AVX 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX2 is available at compile-time, to 0 otherwise. */ #ifdef __AVX2__ #define XSIMD_WITH_AVX2 1 #else #define XSIMD_WITH_AVX2 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if FMA for SSE is available at compile-time, to 0 otherwise. */ #ifdef __FMA__ #if defined(__SSE__) && ! defined(__AVX__) #define XSIMD_WITH_FMA3 1 #else #define XSIMD_WITH_FMA3 0 #endif #else #define XSIMD_WITH_FMA3 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if FMA for AVX is available at compile-time, to 0 otherwise. */ #ifdef __FMA__ #if defined(__AVX__) #define XSIMD_WITH_FMA5 1 #else #define XSIMD_WITH_FMA5 0 #endif #else #define XSIMD_WITH_FMA5 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX512F is available at compile-time, to 0 otherwise. */ #ifdef __AVX512F__ // AVX512 instructions are supported starting with gcc 6 // see https://www.gnu.org/software/gcc/gcc-6/changes.html #if defined(__GNUC__) && __GNUC__ < 6 #define XSIMD_WITH_AVX512F 0 #else #define XSIMD_WITH_AVX512F 1 #if __GNUC__ == 6 #define XSIMD_AVX512_SHIFT_INTRINSICS_IMM_ONLY 1 #endif #endif #else #define XSIMD_WITH_AVX512F 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX512CD is available at compile-time, to 0 otherwise. */ #ifdef __AVX512CD__ // Avoids repeating the GCC workaround over and over #define XSIMD_WITH_AVX512CD XSIMD_WITH_AVX512F #else #define XSIMD_WITH_AVX512CD 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX512DQ is available at compile-time, to 0 otherwise. */ #ifdef __AVX512DQ__ #define XSIMD_WITH_AVX512DQ XSIMD_WITH_AVX512F #else #define XSIMD_WITH_AVX512DQ 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if AVX512BW is available at compile-time, to 0 otherwise. */ #ifdef __AVX512BW__ #define XSIMD_WITH_AVX512BW XSIMD_WITH_AVX512F #else #define XSIMD_WITH_AVX512BW 0 #endif #ifdef __ARM_NEON /** * @ingroup xsimd_config_macro * * Set to 1 if NEON is available at compile-time, to 0 otherwise. */ #if __ARM_ARCH >= 7 #define XSIMD_WITH_NEON 1 #else #define XSIMD_WITH_NEON 0 #endif /** * @ingroup xsimd_config_macro * * Set to 1 if NEON64 is available at compile-time, to 0 otherwise. */ #ifdef __aarch64__ #define XSIMD_WITH_NEON64 1 #else #define XSIMD_WITH_NEON64 0 #endif #else #define XSIMD_WITH_NEON 0 #define XSIMD_WITH_NEON64 0 #endif // Workaround for MSVC compiler #ifdef _MSC_VER #if XSIMD_WITH_AVX512 #define XSIMD_WITH_AVX2 1 #endif #if XSIMD_WITH_AVX2 #define XSIMD_WITH_AVX 1 #endif #if XSIMD_WITH_AVX #define XSIMD_WITH_SSE4_2 1 #endif #if XSIMD_WITH_SSE4_2 #define XSIMD_WITH_SSE4_1 1 #endif #if XSIMD_WITH_SSE4_1 #define XSIMD_WITH_SSSE3 1 #endif #if XSIMD_WITH_SSSE3 #define XSIMD_WITH_SSE3 1 #endif #if XSIMD_WITH_SSE3 #define XSIMD_WITH_SSE2 1 #endif #endif #endif <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XSIMD_CONFIG_HPP #define XSIMD_CONFIG_HPP #include "xsimd_align.hpp" #define XSIMD_VERSION_MAJOR 4 #define XSIMD_VERSION_MINOR 1 #define XSIMD_VERSION_PATCH 6 #ifndef XSIMD_DEFAULT_ALLOCATOR #if XSIMD_X86_INSTR_SET_AVAILABLE #define XSIMD_DEFAULT_ALLOCATOR(T) xsimd::aligned_allocator<T, XSIMD_DEFAULT_ALIGNMENT> #else #define XSIMD_DEFAULT_ALLOCATOR(T) std::allocator<T> #endif #endif #ifndef XSIMD_STACK_ALLOCATION_LIMIT #define XSIMD_STACK_ALLOCATION_LIMIT 20000 #endif #endif <commit_msg>Release 5.0.0<commit_after>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XSIMD_CONFIG_HPP #define XSIMD_CONFIG_HPP #include "xsimd_align.hpp" #define XSIMD_VERSION_MAJOR 5 #define XSIMD_VERSION_MINOR 0 #define XSIMD_VERSION_PATCH 0 #ifndef XSIMD_DEFAULT_ALLOCATOR #if XSIMD_X86_INSTR_SET_AVAILABLE #define XSIMD_DEFAULT_ALLOCATOR(T) xsimd::aligned_allocator<T, XSIMD_DEFAULT_ALIGNMENT> #else #define XSIMD_DEFAULT_ALLOCATOR(T) std::allocator<T> #endif #endif #ifndef XSIMD_STACK_ALLOCATION_LIMIT #define XSIMD_STACK_ALLOCATION_LIMIT 20000 #endif #endif <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <cmath> // [[Rcpp::depends(RcppArmadillo)]] //' Construct several polygenic risk scores from a matrix of weights. //' @param name Path to .ped file (or binary file, working on this now). //' @param weights A matrix of weights with each row being beta corresponding to the association between SNP at that position and the outcome. // [[Rcpp::export]] double prs_test(std::string input, bool debug, int nsnp) { std::ifstream in(input, std::ios::binary); int count = 0; // overall counter int snp = 0; // snp counter, will be reset each time it hits nsnp in order to properly skip blank spcaes. char c; while (in.get(c)) { // char c; // in.get(c); char mask = 1; char bits[8]; for (int i = 0; i < 8; i++) { bits[i] = (c & (mask << i)) != 0; } // Read in, incriment count // If the count is less than 4 then its still in either // the magic number portion or the format // // Will probably want to check the format portion // at some point. count++; if(count < 4) continue; int gen; // Convert to gen and add in to results vector. for(int i = 0; i < 8; i+=2){ snp++; // On first snp counter is going to be 1 // ! -------------------- ! // // CHECK SNP COUNT // // ! -------------------- ! // if( std::remainder(snp, nsnp) == 0) { continue; } // If hit the number of SNPs then skip the rest of the byte // Find gen coding if( bits[i] == 0 & bits[i+1] == 0 ) { gen = 0; } else if( bits[i] == 0 & bits[i+1] == 1 ) { gen = 1; // check } else if( bits[i] == 1 & bits[i+1] == 0 ) { gen = 0; //missing is the same as 0 } else if( bits[i] == 1 & bits[i+1] == 1 ) { gen = 2; } else { throw std::invalid_argument( "Non binary input or improper input." ); } // Think about this results.row(n) = results.row(n) + weights.row(nsnp)*gen; if(debug){ printf("%d", gen); } } // Check to see if everything is adding up correctly // only for debug if(debug) { for (int i = 0; i < 8; i++) { printf("Bit: %d\n",bits[i]); } printf("byte %d\n", count); } } return 0.0; } <commit_msg>this might blow up<commit_after>#include <RcppArmadillo.h> #include <iostream> #include <fstream> #include <cmath> // [[Rcpp::depends(RcppArmadillo)]] //' Construct several polygenic risk scores from a matrix of weights. //' @param name Path to .ped file (or binary file, working on this now). //' @param weights A matrix of weights with each row being beta corresponding to the association between SNP at that position and the outcome. // [[Rcpp::export]] arma::mat prs_test(std::string input, bool debug, arma::uword n, arma::mat weights) { std::ifstream in(input, std::ios::binary); int count = 0; // overall counter int snp = 0; // snp counter, will be reset each time it hits nsnp in order to properly skip blank spcaes. char c; arma::uword n_u = n; // def results matrix arma::mat results(n_u, weights.n_cols); // maybe have to convert to unsigned while (in.get(c)) { // char c; // in.get(c); char mask = 1; char bits[8]; for (int i = 0; i < 8; i++) { bits[i] = (c & (mask << i)) != 0; } // Read in, incriment count // If the count is less than 4 then its still in either // the magic number portion or the format // // Will probably want to check the format portion // at some point. count++; if(count < 4) continue; int gen; // Convert to gen and add in to results vector. for(int i = 0; i < 8; i+=2){ snp++; // On first snp counter is going to be 1 // ! -------------------- ! // // CHECK SNP COUNT // // ! -------------------- ! // if( std::remainder(snp, n) == 0) { snp = 0; continue; } // If hit the number of SNPs then skip the rest of the byte if( strncmp(bits[i], "0") && strncmp(bits[i+1], "0"){ printf("yep") } // Find gen coding if( bits[i] == 0 && bits[i+1] == 0 ) { gen = 0; } else if( bits[i] == 0 && bits[i+1] == 1 ) { gen = 1; // check } else if( bits[i] == 1 && bits[i+1] == 0 ) { gen = 0; //missing is the same as 0 } else if( bits[i] == 1 && bits[i+1] == 1 ) { gen = 2; } else { throw std::invalid_argument( "Non binary input or improper input." ); } // Think about this // Need to make results results.row(snp) = results.row(snp) + weights.row(snp)*gen; if(debug){ printf("%d", gen); } } // Check to see if everything is adding up correctly // only for debug if(debug) { for (int i = 0; i < 8; i++) { printf("Bit: %d\n",bits[i]); } printf("byte %d\n", count); } } return results; } <|endoftext|>
<commit_before>/** * @file llcrashlookup.cpp * @brief Base crash analysis class * * Copyright (C) 2011, Kitty Barnett * * 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; * version 2.1 of the License only. * * 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 "linden_common.h" #include "llcrashlookup.h" std::string LLCrashLookup::getModuleVersionString() const { std::string strVersion = llformat("%d.%d.%d.%d", m_nModuleVersion >> 48, (m_nModuleVersion >> 32) & 0xFFFF, (m_nModuleVersion >> 16) & 0xFFFF, m_nModuleVersion & 0xFFFF); return strVersion; } <commit_msg>- fixed : crash lookup module version string is misformatted<commit_after>/** * @file llcrashlookup.cpp * @brief Base crash analysis class * * Copyright (C) 2011, Kitty Barnett * * 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; * version 2.1 of the License only. * * 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 "linden_common.h" #include "llcrashlookup.h" std::string LLCrashLookup::getModuleVersionString() const { std::string strVersion = llformat("%d.%d.%d.%d", (U32)(m_nModuleVersion >> 48), (U32)((m_nModuleVersion >> 32) & 0xFFFF), (U32)((m_nModuleVersion >> 16) & 0xFFFF), (U32)(m_nModuleVersion & 0xFFFF)); return strVersion; } <|endoftext|>
<commit_before>/** * @file LLNearbyChatHandler.cpp * @brief Nearby chat notification managment * * $LicenseInfo:firstyear=2009&license=viewergpl$ * * Copyright (c) 2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llnearbychathandler.h" #include "llbottomtray.h" #include "llchatitemscontainerctrl.h" #include "llnearbychat.h" #include "llrecentpeople.h" #include "llviewercontrol.h" #include "llfloaterreg.h"//for LLFloaterReg::getTypedInstance #include "llviewerwindow.h"//for screen channel position //add LLNearbyChatHandler to LLNotificationsUI namespace using namespace LLNotificationsUI; //----------------------------------------------------------------------------------------------- //LLNearbyChatScreenChannel //----------------------------------------------------------------------------------------------- LLToastPanelBase* createToastPanel() { LLNearbyChatToastPanel* item = LLNearbyChatToastPanel::createInstance(); return item; } class LLNearbyChatScreenChannel: public LLScreenChannelBase { public: LLNearbyChatScreenChannel(const LLUUID& id):LLScreenChannelBase(id) { mStopProcessing = false;}; void addNotification (LLSD& notification); void arrangeToasts (); void showToastsBottom (); typedef boost::function<LLToastPanelBase* (void )> create_toast_panel_callback_t; void setCreatePanelCallback(create_toast_panel_callback_t value) { m_create_toast_panel_callback_t = value;} void onToastDestroyed (LLToast* toast); void onToastFade (LLToast* toast); void reshape (S32 width, S32 height, BOOL called_from_parent); void redrawToasts() { arrangeToasts(); } // hide all toasts from screen, but not remove them from a channel virtual void hideToastsFromScreen() { }; // removes all toasts from a channel virtual void removeToastsFromChannel() { for(std::vector<LLToast*>::iterator it = m_active_toasts.begin(); it != m_active_toasts.end(); ++it) { LLToast* toast = (*it); toast->setVisible(FALSE); toast->stopTimer(); m_toast_pool.push_back(toast); } m_active_toasts.clear(); }; virtual void deleteAllChildren() { m_toast_pool.clear(); m_active_toasts.clear(); LLScreenChannelBase::deleteAllChildren(); } protected: void createOverflowToast(S32 bottom, F32 timer); create_toast_panel_callback_t m_create_toast_panel_callback_t; bool createPoolToast(); std::vector<LLToast*> m_active_toasts; std::list<LLToast*> m_toast_pool; bool mStopProcessing; }; void LLNearbyChatScreenChannel::createOverflowToast(S32 bottom, F32 timer) { //we don't need overflow toast in nearby chat } void LLNearbyChatScreenChannel::onToastDestroyed(LLToast* toast) { mStopProcessing = true; } void LLNearbyChatScreenChannel::onToastFade(LLToast* toast) { //fade mean we put toast to toast pool if(!toast) return; m_toast_pool.push_back(toast); std::vector<LLToast*>::iterator pos = std::find(m_active_toasts.begin(),m_active_toasts.end(),toast); if(pos!=m_active_toasts.end()) m_active_toasts.erase(pos); arrangeToasts(); } bool LLNearbyChatScreenChannel::createPoolToast() { LLToastPanelBase* panel= m_create_toast_panel_callback_t(); if(!panel) return false; LLToast::Params p; p.panel = panel; p.lifetime_secs = gSavedSettings.getS32("NearbyToastLifeTime"); p.fading_time_secs = gSavedSettings.getS32("NearbyToastFadingTime"); LLToast* toast = new LLToast(p); toast->setOnFadeCallback(boost::bind(&LLNearbyChatScreenChannel::onToastFade, this, _1)); toast->setOnToastDestroyedCallback(boost::bind(&LLNearbyChatScreenChannel::onToastDestroyed, this, _1)); m_toast_pool.push_back(toast); return true; } void LLNearbyChatScreenChannel::addNotification(LLSD& notification) { //look in pool. if there is any message if(mStopProcessing) return; /* find last toast and check ID */ if(m_active_toasts.size()) { LLUUID fromID = notification["from_id"].asUUID(); // agent id or object id std::string from = notification["from"].asString(); LLToast* toast = m_active_toasts[0]; LLNearbyChatToastPanel* panel = dynamic_cast<LLNearbyChatToastPanel*>(toast->getPanel()); if(panel && panel->messageID() == fromID && panel->getFromName() == from && panel->canAddText()) { panel->addMessage(notification); toast->reshapeToPanel(); toast->resetTimer(); arrangeToasts(); return; } } if(m_toast_pool.empty()) { //"pool" is empty - create one more panel if(!createPoolToast())//created toast will go to pool. so next call will find it return; addNotification(notification); return; } int chat_type = notification["chat_type"].asInteger(); if( ((EChatType)chat_type == CHAT_TYPE_DEBUG_MSG)) { if(gSavedSettings.getBOOL("ShowScriptErrors") == FALSE) return; if(gSavedSettings.getS32("ShowScriptErrorsLocation")== 1) return; } //take 1st element from pool, (re)initialize it, put it in active toasts LLToast* toast = m_toast_pool.back(); m_toast_pool.pop_back(); LLToastPanelBase* panel = dynamic_cast<LLToastPanelBase*>(toast->getPanel()); if(!panel) return; panel->init(notification); toast->reshapeToPanel(); toast->resetTimer(); m_active_toasts.insert(m_active_toasts.begin(),toast); arrangeToasts(); } void LLNearbyChatScreenChannel::arrangeToasts() { if(m_active_toasts.size() == 0 || isHovering()) return; hideToastsFromScreen(); showToastsBottom(); } void LLNearbyChatScreenChannel::showToastsBottom() { if(mStopProcessing) return; LLRect toast_rect; S32 bottom = getRect().mBottom; S32 margin = gSavedSettings.getS32("ToastGap"); for(std::vector<LLToast*>::iterator it = m_active_toasts.begin(); it != m_active_toasts.end(); ++it) { LLToast* toast = (*it); S32 toast_top = bottom + toast->getRect().getHeight() + margin; if(toast_top > gFloaterView->getRect().getHeight()) { while(it!=m_active_toasts.end()) { toast->setVisible(FALSE); toast->stopTimer(); m_toast_pool.push_back(toast); it=m_active_toasts.erase(it); } break; } else { toast_rect = toast->getRect(); toast_rect.setLeftTopAndSize(getRect().mLeft , toast_top, toast_rect.getWidth() ,toast_rect.getHeight()); toast->setRect(toast_rect); toast->setIsHidden(false); toast->setVisible(TRUE); if(!toast->hasFocus()) { // Fixing Z-order of toasts (EXT-4862) // Next toast will be positioned under this one. gFloaterView->sendChildToBack(toast); } bottom = toast->getRect().mTop - toast->getTopPad(); } } } void LLNearbyChatScreenChannel::reshape (S32 width, S32 height, BOOL called_from_parent) { LLScreenChannelBase::reshape(width, height, called_from_parent); arrangeToasts(); } //----------------------------------------------------------------------------------------------- //LLNearbyChatHandler //----------------------------------------------------------------------------------------------- LLNearbyChatHandler::LLNearbyChatHandler(e_notification_type type, const LLSD& id) { mType = type; // Getting a Channel for our notifications LLNearbyChatScreenChannel* channel = new LLNearbyChatScreenChannel(LLUUID(gSavedSettings.getString("NearByChatChannelUUID"))); LLNearbyChatScreenChannel::create_toast_panel_callback_t callback = createToastPanel; channel->setCreatePanelCallback(callback); mChannel = LLChannelManager::getInstance()->addChannel(channel); } LLNearbyChatHandler::~LLNearbyChatHandler() { } void LLNearbyChatHandler::initChannel() { LLNearbyChat* nearby_chat = LLFloaterReg::getTypedInstance<LLNearbyChat>("nearby_chat", LLSD()); LLView* chat_box = LLBottomTray::getInstance()->getChildView("chat_box"); S32 channel_right_bound = nearby_chat->getRect().mRight; mChannel->init(chat_box->getRect().mLeft, channel_right_bound); } void LLNearbyChatHandler::processChat(const LLChat& chat_msg, const LLSD &args) { if(chat_msg.mMuted == TRUE) return; if(chat_msg.mSourceType == CHAT_SOURCE_AGENT && chat_msg.mFromID.notNull()) LLRecentPeople::instance().add(chat_msg.mFromID); if(chat_msg.mText.empty()) return;//don't process empty messages LLChat& tmp_chat = const_cast<LLChat&>(chat_msg); LLNearbyChat* nearby_chat = LLFloaterReg::getTypedInstance<LLNearbyChat>("nearby_chat", LLSD()); { //sometimes its usefull to have no name at all... //if(tmp_chat.mFromName.empty() && tmp_chat.mFromID!= LLUUID::null) // tmp_chat.mFromName = tmp_chat.mFromID.asString(); } nearby_chat->addMessage(chat_msg, true, args); if( nearby_chat->getVisible() || ( chat_msg.mSourceType == CHAT_SOURCE_AGENT && gSavedSettings.getBOOL("UseChatBubbles") ) ) return;//no need in toast if chat is visible or if bubble chat is enabled // Handle irc styled messages for toast panel if (tmp_chat.mChatStyle == CHAT_STYLE_IRC) { if(!tmp_chat.mFromName.empty()) tmp_chat.mText = tmp_chat.mFromName + tmp_chat.mText.substr(3); else tmp_chat.mText = tmp_chat.mText.substr(3); } // arrange a channel on a screen if(!mChannel->getVisible()) { initChannel(); } /* //comment all this due to EXT-4432 ..may clean up after some time... //only messages from AGENTS if(CHAT_SOURCE_OBJECT == chat_msg.mSourceType) { if(chat_msg.mChatType == CHAT_TYPE_DEBUG_MSG) return;//ok for now we don't skip messeges from object, so skip only debug messages } */ LLUUID id; id.generate(); LLNearbyChatScreenChannel* channel = dynamic_cast<LLNearbyChatScreenChannel*>(mChannel); if(channel) { LLSD notification; notification["id"] = id; notification["message"] = chat_msg.mText; notification["from"] = chat_msg.mFromName; notification["from_id"] = chat_msg.mFromID; notification["time"] = chat_msg.mTime; notification["source"] = (S32)chat_msg.mSourceType; notification["chat_type"] = (S32)chat_msg.mChatType; notification["chat_style"] = (S32)chat_msg.mChatStyle; std::string r_color_name = "White"; F32 r_color_alpha = 1.0f; LLViewerChat::getChatColor( chat_msg, r_color_name, r_color_alpha); notification["text_color"] = r_color_name; notification["color_alpha"] = r_color_alpha; notification["font_size"] = (S32)LLViewerChat::getChatFontSize() ; channel->addNotification(notification); } } void LLNearbyChatHandler::onDeleteToast(LLToast* toast) { } <commit_msg>fixed EXT-5630 “nearby chat flickers when top line fades out”, used reverse order to provide correct z-order and avoid toast blinking caused by z-reordering; reviewed by Vadim at https://codereview.productengine.com/secondlife/r/57/<commit_after>/** * @file LLNearbyChatHandler.cpp * @brief Nearby chat notification managment * * $LicenseInfo:firstyear=2009&license=viewergpl$ * * Copyright (c) 2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llnearbychathandler.h" #include "llbottomtray.h" #include "llchatitemscontainerctrl.h" #include "llnearbychat.h" #include "llrecentpeople.h" #include "llviewercontrol.h" #include "llfloaterreg.h"//for LLFloaterReg::getTypedInstance #include "llviewerwindow.h"//for screen channel position //add LLNearbyChatHandler to LLNotificationsUI namespace using namespace LLNotificationsUI; //----------------------------------------------------------------------------------------------- //LLNearbyChatScreenChannel //----------------------------------------------------------------------------------------------- LLToastPanelBase* createToastPanel() { LLNearbyChatToastPanel* item = LLNearbyChatToastPanel::createInstance(); return item; } class LLNearbyChatScreenChannel: public LLScreenChannelBase { public: LLNearbyChatScreenChannel(const LLUUID& id):LLScreenChannelBase(id) { mStopProcessing = false;}; void addNotification (LLSD& notification); void arrangeToasts (); void showToastsBottom (); typedef boost::function<LLToastPanelBase* (void )> create_toast_panel_callback_t; void setCreatePanelCallback(create_toast_panel_callback_t value) { m_create_toast_panel_callback_t = value;} void onToastDestroyed (LLToast* toast); void onToastFade (LLToast* toast); void reshape (S32 width, S32 height, BOOL called_from_parent); void redrawToasts() { arrangeToasts(); } // hide all toasts from screen, but not remove them from a channel virtual void hideToastsFromScreen() { }; // removes all toasts from a channel virtual void removeToastsFromChannel() { for(std::vector<LLToast*>::iterator it = m_active_toasts.begin(); it != m_active_toasts.end(); ++it) { LLToast* toast = (*it); toast->setVisible(FALSE); toast->stopTimer(); m_toast_pool.push_back(toast); } m_active_toasts.clear(); }; virtual void deleteAllChildren() { m_toast_pool.clear(); m_active_toasts.clear(); LLScreenChannelBase::deleteAllChildren(); } protected: void createOverflowToast(S32 bottom, F32 timer); create_toast_panel_callback_t m_create_toast_panel_callback_t; bool createPoolToast(); std::vector<LLToast*> m_active_toasts; std::list<LLToast*> m_toast_pool; bool mStopProcessing; }; void LLNearbyChatScreenChannel::createOverflowToast(S32 bottom, F32 timer) { //we don't need overflow toast in nearby chat } void LLNearbyChatScreenChannel::onToastDestroyed(LLToast* toast) { mStopProcessing = true; } void LLNearbyChatScreenChannel::onToastFade(LLToast* toast) { //fade mean we put toast to toast pool if(!toast) return; m_toast_pool.push_back(toast); std::vector<LLToast*>::iterator pos = std::find(m_active_toasts.begin(),m_active_toasts.end(),toast); if(pos!=m_active_toasts.end()) m_active_toasts.erase(pos); arrangeToasts(); } bool LLNearbyChatScreenChannel::createPoolToast() { LLToastPanelBase* panel= m_create_toast_panel_callback_t(); if(!panel) return false; LLToast::Params p; p.panel = panel; p.lifetime_secs = gSavedSettings.getS32("NearbyToastLifeTime"); p.fading_time_secs = gSavedSettings.getS32("NearbyToastFadingTime"); LLToast* toast = new LLToast(p); toast->setOnFadeCallback(boost::bind(&LLNearbyChatScreenChannel::onToastFade, this, _1)); toast->setOnToastDestroyedCallback(boost::bind(&LLNearbyChatScreenChannel::onToastDestroyed, this, _1)); m_toast_pool.push_back(toast); return true; } void LLNearbyChatScreenChannel::addNotification(LLSD& notification) { //look in pool. if there is any message if(mStopProcessing) return; /* find last toast and check ID */ if(m_active_toasts.size()) { LLUUID fromID = notification["from_id"].asUUID(); // agent id or object id std::string from = notification["from"].asString(); LLToast* toast = m_active_toasts[0]; LLNearbyChatToastPanel* panel = dynamic_cast<LLNearbyChatToastPanel*>(toast->getPanel()); if(panel && panel->messageID() == fromID && panel->getFromName() == from && panel->canAddText()) { panel->addMessage(notification); toast->reshapeToPanel(); toast->resetTimer(); arrangeToasts(); return; } } if(m_toast_pool.empty()) { //"pool" is empty - create one more panel if(!createPoolToast())//created toast will go to pool. so next call will find it return; addNotification(notification); return; } int chat_type = notification["chat_type"].asInteger(); if( ((EChatType)chat_type == CHAT_TYPE_DEBUG_MSG)) { if(gSavedSettings.getBOOL("ShowScriptErrors") == FALSE) return; if(gSavedSettings.getS32("ShowScriptErrorsLocation")== 1) return; } //take 1st element from pool, (re)initialize it, put it in active toasts LLToast* toast = m_toast_pool.back(); m_toast_pool.pop_back(); LLToastPanelBase* panel = dynamic_cast<LLToastPanelBase*>(toast->getPanel()); if(!panel) return; panel->init(notification); toast->reshapeToPanel(); toast->resetTimer(); m_active_toasts.insert(m_active_toasts.begin(),toast); arrangeToasts(); } void LLNearbyChatScreenChannel::arrangeToasts() { if(m_active_toasts.size() == 0 || isHovering()) return; hideToastsFromScreen(); showToastsBottom(); } void LLNearbyChatScreenChannel::showToastsBottom() { if(mStopProcessing) return; LLRect toast_rect; S32 bottom = getRect().mBottom; S32 margin = gSavedSettings.getS32("ToastGap"); for(std::vector<LLToast*>::iterator it = m_active_toasts.begin(); it != m_active_toasts.end(); ++it) { LLToast* toast = (*it); S32 toast_top = bottom + toast->getRect().getHeight() + margin; if(toast_top > gFloaterView->getRect().getHeight()) { while(it!=m_active_toasts.end()) { toast->setVisible(FALSE); toast->stopTimer(); m_toast_pool.push_back(toast); it=m_active_toasts.erase(it); } break; } bottom = toast_top - toast->getTopPad(); } // use reverse order to provide correct z-order and avoid toast blinking for(std::vector<LLToast*>::reverse_iterator it = m_active_toasts.rbegin(); it != m_active_toasts.rend(); ++it) { LLToast* toast = (*it); S32 toast_top = bottom + toast->getTopPad(); toast_rect = toast->getRect(); toast_rect.setLeftTopAndSize(getRect().mLeft , toast_top, toast_rect.getWidth() ,toast_rect.getHeight()); toast->setRect(toast_rect); toast->setIsHidden(false); toast->setVisible(TRUE); bottom = toast->getRect().mBottom - margin; } } void LLNearbyChatScreenChannel::reshape (S32 width, S32 height, BOOL called_from_parent) { LLScreenChannelBase::reshape(width, height, called_from_parent); arrangeToasts(); } //----------------------------------------------------------------------------------------------- //LLNearbyChatHandler //----------------------------------------------------------------------------------------------- LLNearbyChatHandler::LLNearbyChatHandler(e_notification_type type, const LLSD& id) { mType = type; // Getting a Channel for our notifications LLNearbyChatScreenChannel* channel = new LLNearbyChatScreenChannel(LLUUID(gSavedSettings.getString("NearByChatChannelUUID"))); LLNearbyChatScreenChannel::create_toast_panel_callback_t callback = createToastPanel; channel->setCreatePanelCallback(callback); mChannel = LLChannelManager::getInstance()->addChannel(channel); } LLNearbyChatHandler::~LLNearbyChatHandler() { } void LLNearbyChatHandler::initChannel() { LLNearbyChat* nearby_chat = LLFloaterReg::getTypedInstance<LLNearbyChat>("nearby_chat", LLSD()); LLView* chat_box = LLBottomTray::getInstance()->getChildView("chat_box"); S32 channel_right_bound = nearby_chat->getRect().mRight; mChannel->init(chat_box->getRect().mLeft, channel_right_bound); } void LLNearbyChatHandler::processChat(const LLChat& chat_msg, const LLSD &args) { if(chat_msg.mMuted == TRUE) return; if(chat_msg.mSourceType == CHAT_SOURCE_AGENT && chat_msg.mFromID.notNull()) LLRecentPeople::instance().add(chat_msg.mFromID); if(chat_msg.mText.empty()) return;//don't process empty messages LLChat& tmp_chat = const_cast<LLChat&>(chat_msg); LLNearbyChat* nearby_chat = LLFloaterReg::getTypedInstance<LLNearbyChat>("nearby_chat", LLSD()); { //sometimes its usefull to have no name at all... //if(tmp_chat.mFromName.empty() && tmp_chat.mFromID!= LLUUID::null) // tmp_chat.mFromName = tmp_chat.mFromID.asString(); } nearby_chat->addMessage(chat_msg, true, args); if( nearby_chat->getVisible() || ( chat_msg.mSourceType == CHAT_SOURCE_AGENT && gSavedSettings.getBOOL("UseChatBubbles") ) ) return;//no need in toast if chat is visible or if bubble chat is enabled // Handle irc styled messages for toast panel if (tmp_chat.mChatStyle == CHAT_STYLE_IRC) { if(!tmp_chat.mFromName.empty()) tmp_chat.mText = tmp_chat.mFromName + tmp_chat.mText.substr(3); else tmp_chat.mText = tmp_chat.mText.substr(3); } // arrange a channel on a screen if(!mChannel->getVisible()) { initChannel(); } /* //comment all this due to EXT-4432 ..may clean up after some time... //only messages from AGENTS if(CHAT_SOURCE_OBJECT == chat_msg.mSourceType) { if(chat_msg.mChatType == CHAT_TYPE_DEBUG_MSG) return;//ok for now we don't skip messeges from object, so skip only debug messages } */ LLUUID id; id.generate(); LLNearbyChatScreenChannel* channel = dynamic_cast<LLNearbyChatScreenChannel*>(mChannel); if(channel) { LLSD notification; notification["id"] = id; notification["message"] = chat_msg.mText; notification["from"] = chat_msg.mFromName; notification["from_id"] = chat_msg.mFromID; notification["time"] = chat_msg.mTime; notification["source"] = (S32)chat_msg.mSourceType; notification["chat_type"] = (S32)chat_msg.mChatType; notification["chat_style"] = (S32)chat_msg.mChatStyle; std::string r_color_name = "White"; F32 r_color_alpha = 1.0f; LLViewerChat::getChatColor( chat_msg, r_color_name, r_color_alpha); notification["text_color"] = r_color_name; notification["color_alpha"] = r_color_alpha; notification["font_size"] = (S32)LLViewerChat::getChatFontSize() ; channel->addNotification(notification); } } void LLNearbyChatHandler::onDeleteToast(LLToast* toast) { } <|endoftext|>
<commit_before>#include <iostream> #include "Lib.hpp" #include "Root.hpp" #include "QdlParser.hpp" int main() { try { Lib lib; QdlParser(std::cin, lib); std::unique_ptr<Root> root(lib.compile("top")); //root->dumpClauses(std::cout); Result const res = root->solve(); std::cout << res << std::endl; if(res) root->printConfig(std::cout); } catch(char const *const msg) { std::cerr << "Error:\n\t" << msg << std::endl; } catch(std::string const& msg) { std::cerr << "Error:\n\t" << msg << std::endl; } } <commit_msg>Additional status line in test program.<commit_after>#include <iostream> #include "Lib.hpp" #include "Root.hpp" #include "QdlParser.hpp" int main() { try { Lib lib; QdlParser(std::cin, lib); std::unique_ptr<Root> root(lib.compile("top")); //root->dumpClauses(std::cout); std::cerr << std::endl << "Solving ... "; Result const res = root->solve(); std::cout << res << std::endl; if(res) root->printConfig(std::cout); } catch(char const *const msg) { std::cerr << "Error:\n\t" << msg << std::endl; } catch(std::string const& msg) { std::cerr << "Error:\n\t" << msg << std::endl; } } <|endoftext|>
<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "intro.h" #include "ui_intro.h" #include "guiutil.h" #include "util.h" #include <boost/filesystem.hpp> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <cmath> static const uint64_t GB_BYTES = 1000000000LL; /* Minimum free space (in GB) needed for data directory */ static const uint64_t BLOCK_CHAIN_SIZE = 100; /* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */ static const uint64_t CHAIN_STATE_SIZE = 2; /* Total required space (in GB) depending on user choice (prune, not prune) */ static uint64_t requiredSpace; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include "intro.moc" FreespaceChecker::FreespaceChecker(Intro *intro) { this->intro = intro; } void FreespaceChecker::check() { namespace fs = boost::filesystem; QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget *parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME))); ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME))); uint64_t pruneTarget = std::max<int64_t>(0, GetArg("-prune", 0)); requiredSpace = BLOCK_CHAIN_SIZE; if (pruneTarget) requiredSpace = CHAIN_STATE_SIZE + std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES); ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(tr(PACKAGE_NAME)).arg(requiredSpace)); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ Q_EMIT stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory() { namespace fs = boost::filesystem; QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || GetBoolArg("-resetguisettings", false)) { /* If current default data directory does not exist, let the user choose one */ Intro intro; intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir)); break; } catch (const fs::filesystem_error&) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); settings.setValue("fReset", false); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the bitcoin.conf file in the default data directory * (to be consistent with bitcoind behavior) */ if(dataDir != getDefaultDataDirectory()) SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES); if(bytesAvailable < requiredSpace * GB_BYTES) { freeString += " " + tr("(of %n GB needed)", "", requiredSpace); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64))); connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <commit_msg>Set required space<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "intro.h" #include "ui_intro.h" #include "guiutil.h" #include "util.h" #include <boost/filesystem.hpp> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <cmath> static const uint64_t GB_BYTES = 1000000000LL; /* Minimum free space (in GB) needed for data directory */ static const uint64_t BLOCK_CHAIN_SIZE = 2; /* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */ static const uint64_t CHAIN_STATE_SIZE = 1; /* Total required space (in GB) depending on user choice (prune, not prune) */ static uint64_t requiredSpace; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include "intro.moc" FreespaceChecker::FreespaceChecker(Intro *intro) { this->intro = intro; } void FreespaceChecker::check() { namespace fs = boost::filesystem; QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget *parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME))); ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME))); uint64_t pruneTarget = std::max<int64_t>(0, GetArg("-prune", 0)); requiredSpace = BLOCK_CHAIN_SIZE; if (pruneTarget) requiredSpace = CHAIN_STATE_SIZE + std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES); ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(tr(PACKAGE_NAME)).arg(requiredSpace)); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ Q_EMIT stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory() { namespace fs = boost::filesystem; QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || GetBoolArg("-resetguisettings", false)) { /* If current default data directory does not exist, let the user choose one */ Intro intro; intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir)); break; } catch (const fs::filesystem_error&) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); settings.setValue("fReset", false); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the bitcoin.conf file in the default data directory * (to be consistent with bitcoind behavior) */ if(dataDir != getDefaultDataDirectory()) SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES); if(bytesAvailable < requiredSpace * GB_BYTES) { freeString += " " + tr("(of %n GB needed)", "", requiredSpace); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64))); connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: cat %s | %cling -I%p | FileCheck %s #include <cmath> struct S{int i;} ss; S s = {12 }; struct U{void f() const {};} uu; struct V{V(): v(12) {}; int v; } vv; int i = 12; float f = sin(12); int j = i; extern "C" int printf(const char* fmt, ...); printf("j=%d\n",j); // CHECK:j=12 #include <string> std::string str("abc"); printf("str=%s\n",str.c_str()); // CHECK: str=abc .q <commit_msg>Temporary breakage to debug cont integration.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: cat %s | %cling -I%p | FileCheck %s #include <cmath> TEMPORARY BREAKAGE! struct S{int i;} ss; S s = {12 }; struct U{void f() const {};} uu; struct V{V(): v(12) {}; int v; } vv; int i = 12; float f = sin(12); int j = i; extern "C" int printf(const char* fmt, ...); printf("j=%d\n",j); // CHECK:j=12 #include <string> std::string str("abc"); printf("str=%s\n",str.c_str()); // CHECK: str=abc .q <|endoftext|>
<commit_before>// // quadTree.cpp // layout++ // // Created by Andrei Kashcha on 5/21/15. // Copyright (c) 2015 Andrei Kashcha. All rights reserved. // // NOTE: This code was copied as is from https://github.com/anvaka/ngraph.quadtreebh3d/blob/master/index.js // Some of the coments are no longer relvant to C++. // #include "quadTree.h" #include "Random.h" #include <cmath> QuadTreeNode *QuadTree::createRootNode(std::vector<Body> &bodies) { double x1 = INT32_MAX, x2 = INT32_MIN, y1 = INT32_MAX, y2 = INT32_MIN, z1 = INT32_MAX, z2 = INT32_MIN; for (std::vector<Body>::iterator body = bodies.begin() ; body != bodies.end(); ++body) { double x = body->pos.x; double y = body->pos.y; double z = body->pos.z; if (x < x1) x1 = x; if (x > x2) x2 = x; if (y < y1) y1 = y; if (y > y2) y2 = y; if (z < z1) z1 = z; if (z > z2) z2 = z; } // squarify bounds: double maxSide = std::max(x2 - x1, std::max(y2 - y1, z2 - z1)); if (maxSide == 0) { maxSide = bodies.size() * 500; x1 -= maxSide; y1 -= maxSide; z1 -= maxSide; x2 += maxSide; y2 += maxSide; z2 += maxSide; } else { x2 = x1 + maxSide; y2 = y1 + maxSide; z2 = z1 + maxSide; } QuadTreeNode *root = treeNodes.get(); root->left = x1; root->right = x2; root->top = y1; root->bottom = y2; root->back = z1; root->front = z2; return root; } void QuadTree::insert(Body *body, QuadTreeNode *node){ if (!node->body) { // This is internal node. Update the total mass of the node and center-of-mass. double x = body->pos.x; double y = body->pos.y; double z = body->pos.z; node->mass += body->mass; node->massVector.x += body->mass * x; node->massVector.y += body->mass * y; node->massVector.z += body->mass * z; // Recursively insert the body in the appropriate quadrant. // But first find the appropriate quadrant. int quadIdx = 0; // Assume we are in the 0's quad. double left = node->left, right = (node->right + left) / 2, top = node->top, bottom = (node->bottom + top) / 2, back = node->back, front = (node->front + back) / 2; if (x > right) { // somewhere in the eastern part. quadIdx += 1; int oldLeft = left; left = right; right = right + (right - oldLeft); } if (y > bottom) { // and in south. quadIdx += 2; int oldTop = top; top = bottom; bottom = bottom + (bottom - oldTop); } if (z > front) { // and in frontal part quadIdx += 4; int oldBack = back; back = front; front = back + (back - oldBack); } QuadTreeNode *child = node->quads[quadIdx]; if (!child) { // The node is internal but this quadrant is not taken. Add subnode to it. child = treeNodes.get(); child->left = left; child->top = top; child->right = right; child->bottom = bottom; child->back = back; child->front = front; child->body = body; node->quads[quadIdx] = child; } else { // continue searching in this quadrant. insert(body, child); } } else { // We are trying to add to the leaf node. // We have to convert current leaf into internal node // and continue adding two nodes. Body *oldBody = node->body; node->body = NULL; // internal nodes do not carry bodies if (oldBody->pos.sameAs(body->pos)) { int retriesCount = 3; do { double offset = Random::nextDouble(), dx = (node->right - node->left) * offset, dy = (node->bottom - node->top) * offset, dz = (node->front - node->back) * offset; oldBody->pos.x = node->left + dx; oldBody->pos.y = node->top + dy; oldBody->pos.z = node->back + dz; retriesCount -= 1; // Make sure we don't bump it out of the box. If we do, next iteration should fix it } while (retriesCount > 0 && oldBody->pos.sameAs(body->pos)); if (retriesCount == 0 && oldBody->pos.sameAs(body->pos)) { // This is very bad, we ran out of precision. // if we do not return from the method we'll get into // infinite loop here. So we sacrifice correctness of layout, and keep the app running // Next layout iteration should get larger bounding box in the first step and fix this throw "Nooo"; // TODO: handle this up } } // Next iteration should subdivide node further. insert(oldBody, node); insert(body, node); } } void QuadTree::insertBodies(std::vector<Body> &bodies) { treeNodes.reset(); root = createRootNode(bodies); if (bodies.size() > 0) { root->body = &bodies[0]; } for (std::vector<Body>::iterator body = bodies.begin() + 1; body != bodies.end(); ++body) { insert(&*body, root); } }; void QuadTree::updateBodyForce(Body *sourceBody) { std::vector<QuadTreeNode *> queue; int queueLength = 1; int shiftIndex = 0; int pushIndex = 0; double v, dx, dy, dz, r; double fx = 0, fy = 0, fz = 0; queue.push_back(root); while (queueLength) { QuadTreeNode *node = queue[shiftIndex]; Body *body = node->body; queueLength -= 1; shiftIndex += 1; bool differentBody = (body != sourceBody); if (body != NULL && differentBody) { // If the current node is a leaf node (and it is not source body), // calculate the force exerted by the current node on body, and add this // amount to body's net force. dx = body->pos.x - sourceBody->pos.x; dy = body->pos.y - sourceBody->pos.y; dz = body->pos.z - sourceBody->pos.z; r = sqrt(dx * dx + dy * dy + dz * dz); if (r == 0) { // Poor man's protection against zero distance. dx = (Random::nextDouble() - 0.5) / 50; dy = (Random::nextDouble() - 0.5) / 50; dz = (Random::nextDouble() - 0.5) / 50; r = sqrt(dx * dx + dy * dy + dz * dz); } // This is standard gravitation force calculation but we divide // by r^3 to save two operations when normalizing force vector. v = layoutSettings->gravity * body->mass * sourceBody->mass / (r * r * r); fx += v * dx; fy += v * dy; fz += v * dz; } else if (differentBody) { // Otherwise, calculate the ratio s / r, where s is the width of the region // represented by the internal node, and r is the distance between the body // and the node's center-of-mass dx = node->massVector.x / node->mass - sourceBody->pos.x; dy = node->massVector.y / node->mass - sourceBody->pos.y; dz = node->massVector.z / node->mass - sourceBody->pos.z; r = sqrt(dx * dx + dy * dy + dz * dz); if (r == 0) { // Sorry about code duplication. I don't want to create many functions // right away. Just want to see performance first. dx = (Random::nextDouble() - 0.5) / 50; dy = (Random::nextDouble() - 0.5) / 50; dz = (Random::nextDouble() - 0.5) / 50; r = sqrt(dx * dx + dy * dy + dz * dz); } // If s / r < θ, treat this internal node as a single body, and calculate the // force it exerts on sourceBody, and add this amount to sourceBody's net force. if ((node->right - node->left) / r < layoutSettings->theta) { // in the if statement above we consider node's width only // because the region was squarified during tree creation. // Thus there is no difference between using width or height. v = layoutSettings->gravity * node->mass * sourceBody->mass / (r * r * r); fx += v * dx; fy += v * dy; fz += v * dz; } else { // Otherwise, run the procedure recursively on each of the current node's children. for (int i = 0; i < 8; ++i) { if (node->quads[i]) { if (queue.size() < pushIndex) { queue[pushIndex] = node->quads[i]; } else { queue.push_back(node->quads[i]); } queueLength += 1; pushIndex += 1; } } } } } sourceBody->force.x += fx; sourceBody->force.y += fy; sourceBody->force.z += fz; } <commit_msg>Fixed a bug which led to infinite tree construction<commit_after>// // quadTree.cpp // layout++ // // Created by Andrei Kashcha on 5/21/15. // Copyright (c) 2015 Andrei Kashcha. All rights reserved. // // NOTE: This code was copied as is from https://github.com/anvaka/ngraph.quadtreebh3d/blob/master/index.js // Some of the coments are no longer relvant to C++. // #include "quadTree.h" #include "Random.h" #include <cmath> QuadTreeNode *QuadTree::createRootNode(std::vector<Body> &bodies) { double x1 = INT32_MAX, x2 = INT32_MIN, y1 = INT32_MAX, y2 = INT32_MIN, z1 = INT32_MAX, z2 = INT32_MIN; for (std::vector<Body>::iterator body = bodies.begin() ; body != bodies.end(); ++body) { double x = body->pos.x; double y = body->pos.y; double z = body->pos.z; if (x < x1) x1 = x; if (x > x2) x2 = x; if (y < y1) y1 = y; if (y > y2) y2 = y; if (z < z1) z1 = z; if (z > z2) z2 = z; } // squarify bounds: double maxSide = std::max(x2 - x1, std::max(y2 - y1, z2 - z1)); if (maxSide == 0) { maxSide = bodies.size() * 500; x1 -= maxSide; y1 -= maxSide; z1 -= maxSide; x2 += maxSide; y2 += maxSide; z2 += maxSide; } else { x2 = x1 + maxSide; y2 = y1 + maxSide; z2 = z1 + maxSide; } QuadTreeNode *root = treeNodes.get(); root->left = x1; root->right = x2; root->top = y1; root->bottom = y2; root->back = z1; root->front = z2; return root; } void QuadTree::insert(Body *body, QuadTreeNode *node) { if (!node->body) { // This is internal node. Update the total mass of the node and center-of-mass. double x = body->pos.x; double y = body->pos.y; double z = body->pos.z; node->mass += body->mass; node->massVector.x += body->mass * x; node->massVector.y += body->mass * y; node->massVector.z += body->mass * z; // Recursively insert the body in the appropriate quadrant. // But first find the appropriate quadrant. int quadIdx = 0; // Assume we are in the 0's quad. double left = node->left, right = (node->right + left) / 2, top = node->top, bottom = (node->bottom + top) / 2, back = node->back, front = (node->front + back) / 2; if (x > right) { // somewhere in the eastern part. quadIdx += 1; left = right; right = node->right; } if (y > bottom) { // and in south. quadIdx += 2; top = bottom; bottom = node->bottom; } if (z > front) { // and in frontal part quadIdx += 4; back = front; front = node->front; } QuadTreeNode *child = node->quads[quadIdx]; if (!child) { // The node is internal but this quadrant is not taken. Add subnode to it. child = treeNodes.get(); child->left = left; child->top = top; child->right = right; child->bottom = bottom; child->back = back; child->front = front; child->body = body; node->quads[quadIdx] = child; } else { // continue searching in this quadrant. insert(body, child); } } else { // We are trying to add to the leaf node. // We have to convert current leaf into internal node // and continue adding two nodes. Body *oldBody = node->body; node->body = NULL; // internal nodes do not carry bodies if (oldBody->pos.sameAs(body->pos)) { int retriesCount = 3; do { double offset = Random::nextDouble(), dx = (node->right - node->left) * offset, dy = (node->bottom - node->top) * offset, dz = (node->front - node->back) * offset; oldBody->pos.x = node->left + dx; oldBody->pos.y = node->top + dy; oldBody->pos.z = node->back + dz; retriesCount -= 1; // Make sure we don't bump it out of the box. If we do, next iteration should fix it } while (retriesCount > 0 && oldBody->pos.sameAs(body->pos)); if (retriesCount == 0 && oldBody->pos.sameAs(body->pos)) { // This is very bad, we ran out of precision. // if we do not return from the method we'll get into // infinite loop here. So we sacrifice correctness of layout, and keep the app running // Next layout iteration should get larger bounding box in the first step and fix this throw "Nooo"; // TODO: handle this up } } // Next iteration should subdivide node further. insert(oldBody, node); insert(body, node); } } void QuadTree::insertBodies(std::vector<Body> &bodies) { treeNodes.reset(); root = createRootNode(bodies); if (bodies.size() > 0) { root->body = &bodies[0]; } for (int i = 1; i < bodies.size(); ++i) { insert(&(bodies[i]), root); } }; void QuadTree::updateBodyForce(Body *sourceBody) { std::vector<QuadTreeNode *> queue; int queueLength = 1; int shiftIndex = 0; int pushIndex = 0; double v, dx, dy, dz, r; double fx = 0, fy = 0, fz = 0; queue.push_back(root); while (queueLength) { QuadTreeNode *node = queue[shiftIndex]; Body *body = node->body; queueLength -= 1; shiftIndex += 1; bool differentBody = (body != sourceBody); if (body != NULL && differentBody) { // If the current node is a leaf node (and it is not source body), // calculate the force exerted by the current node on body, and add this // amount to body's net force. dx = body->pos.x - sourceBody->pos.x; dy = body->pos.y - sourceBody->pos.y; dz = body->pos.z - sourceBody->pos.z; r = sqrt(dx * dx + dy * dy + dz * dz); if (r == 0) { // Poor man's protection against zero distance. dx = (Random::nextDouble() - 0.5) / 50; dy = (Random::nextDouble() - 0.5) / 50; dz = (Random::nextDouble() - 0.5) / 50; r = sqrt(dx * dx + dy * dy + dz * dz); } // This is standard gravitation force calculation but we divide // by r^3 to save two operations when normalizing force vector. v = layoutSettings->gravity * body->mass * sourceBody->mass / (r * r * r); fx += v * dx; fy += v * dy; fz += v * dz; } else if (differentBody) { // Otherwise, calculate the ratio s / r, where s is the width of the region // represented by the internal node, and r is the distance between the body // and the node's center-of-mass dx = node->massVector.x / node->mass - sourceBody->pos.x; dy = node->massVector.y / node->mass - sourceBody->pos.y; dz = node->massVector.z / node->mass - sourceBody->pos.z; r = sqrt(dx * dx + dy * dy + dz * dz); if (r == 0) { // Sorry about code duplication. I don't want to create many functions // right away. Just want to see performance first. dx = (Random::nextDouble() - 0.5) / 50; dy = (Random::nextDouble() - 0.5) / 50; dz = (Random::nextDouble() - 0.5) / 50; r = sqrt(dx * dx + dy * dy + dz * dz); } // If s / r < θ, treat this internal node as a single body, and calculate the // force it exerts on sourceBody, and add this amount to sourceBody's net force. if ((node->right - node->left) / r < layoutSettings->theta) { // in the if statement above we consider node's width only // because the region was squarified during tree creation. // Thus there is no difference between using width or height. v = layoutSettings->gravity * node->mass * sourceBody->mass / (r * r * r); fx += v * dx; fy += v * dy; fz += v * dz; } else { // Otherwise, run the procedure recursively on each of the current node's children. for (int i = 0; i < 8; ++i) { if (node->quads[i]) { if (queue.size() < pushIndex) { queue[pushIndex] = node->quads[i]; } else { queue.push_back(node->quads[i]); } queueLength += 1; pushIndex += 1; } } } } } sourceBody->force.x += fx; sourceBody->force.y += fy; sourceBody->force.z += fz; } <|endoftext|>
<commit_before><commit_msg>Cherry Pick: Fix VertexBufferData::CopyInto bug<commit_after><|endoftext|>
<commit_before>#include "iges.h" #ifdef SIREN_ENABLE_IGES bool siren_iges_install(mrb_state* mrb, struct RClass* mod_siren) { // Class method mrb_define_class_method(mrb, mod_siren, "save_iges", siren_iges_save, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, mod_siren, "load_iges", siren_iges_load, MRB_ARGS_REQ(1)); // For mix-in mrb_define_method (mrb, mod_siren, "save_iges", siren_iges_save, MRB_ARGS_REQ(2)); mrb_define_method (mrb, mod_siren, "load_iges", siren_iges_load, MRB_ARGS_REQ(1)); return true; } mrb_value siren_iges_save(mrb_state* mrb, mrb_value self) { mrb_value target; mrb_value path; int argc = mrb_get_args(mrb, "oS", &target, &path); IGESControl_Controller::Init(); IGESControl_Writer writer(Interface_Static::CVal("XSTEP.iges.unit"), Interface_Static::IVal("XSTEP.iges.writebrep.mode")); writer.AddShape(*siren_shape_get(mrb, target)); writer.ComputeModel(); std::ofstream fst(RSTRING_PTR(path), std::ios_base::out); if (writer.Write(fst) == Standard_False) { mrb_raisef(mrb, E_ARGUMENT_ERROR, "Failed to save IGES to %S.", path); } return mrb_nil_value(); } mrb_value siren_iges_load(mrb_state* mrb, mrb_value self) { mrb_value path; mrb_bool as_ary; int argc = mrb_get_args(mrb, "S|b", &path, &as_ary); if (argc == 1) { as_ary = FALSE; } IGESControl_Reader iges_reader; int stat = iges_reader.ReadFile((Standard_CString)RSTRING_PTR(path)); mrb_value result; if (stat == IFSelect_RetDone) { try { iges_reader.TransferRoots(); } catch (...) { mrb_raise(mrb, E_RUNTIME_ERROR, "Failed to TransferRoots() with an IGES."); } if (as_ary) { // Return array result = mrb_ary_new(mrb); for (int i=1; i <= iges_reader.NbShapes(); i++) { try { TopoDS_Shape shape = iges_reader.Shape(i); mrb_value mrshape = siren_shape_new(mrb, shape); mrb_ary_push(mrb, result, mrshape); } catch(...) { mrb_warn(mrb, "Failed to get entitiy at %d.", i); } } if (mrb_ary_len(mrb, result) < 1) { result = mrb_nil_value(); } } else { // As one shape result = siren_shape_new(mrb, iges_reader.OneShape()); } } else { mrb_raisef(mrb, E_ARGUMENT_ERROR, "Failed to load IGES from %S.", path); } return result; } #endif <commit_msg>set save_iges to BRep mode<commit_after>#include "iges.h" #ifdef SIREN_ENABLE_IGES bool siren_iges_install(mrb_state* mrb, struct RClass* mod_siren) { // Class method mrb_define_class_method(mrb, mod_siren, "save_iges", siren_iges_save, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, mod_siren, "load_iges", siren_iges_load, MRB_ARGS_REQ(1)); // For mix-in mrb_define_method (mrb, mod_siren, "save_iges", siren_iges_save, MRB_ARGS_REQ(2)); mrb_define_method (mrb, mod_siren, "load_iges", siren_iges_load, MRB_ARGS_REQ(1)); return true; } mrb_value siren_iges_save(mrb_state* mrb, mrb_value self) { mrb_value target; mrb_value path; int argc = mrb_get_args(mrb, "oS", &target, &path); IGESControl_Controller::Init(); // IGESControl_Writer writer(Interface_Static::CVal("XSTEP.iges.unit"), // Interface_Static::IVal("XSTEP.iges.writebrep.mode")); IGESControl_Writer writer(Interface_Static::CVal("XSTEP.iges.unit"), 1); // the second argument "1" sets the OCCT => IGES conversion method to "BRep" writer.AddShape(*siren_shape_get(mrb, target)); writer.ComputeModel(); std::ofstream fst(RSTRING_PTR(path), std::ios_base::out); if (writer.Write(fst) == Standard_False) { mrb_raisef(mrb, E_ARGUMENT_ERROR, "Failed to save IGES to %S.", path); } return mrb_nil_value(); } mrb_value siren_iges_load(mrb_state* mrb, mrb_value self) { mrb_value path; mrb_bool as_ary; int argc = mrb_get_args(mrb, "S|b", &path, &as_ary); if (argc == 1) { as_ary = FALSE; } IGESControl_Reader iges_reader; int stat = iges_reader.ReadFile((Standard_CString)RSTRING_PTR(path)); mrb_value result; if (stat == IFSelect_RetDone) { try { iges_reader.TransferRoots(); } catch (...) { mrb_raise(mrb, E_RUNTIME_ERROR, "Failed to TransferRoots() with an IGES."); } if (as_ary) { // Return array result = mrb_ary_new(mrb); for (int i=1; i <= iges_reader.NbShapes(); i++) { try { TopoDS_Shape shape = iges_reader.Shape(i); mrb_value mrshape = siren_shape_new(mrb, shape); mrb_ary_push(mrb, result, mrshape); } catch(...) { mrb_warn(mrb, "Failed to get entitiy at %d.", i); } } if (mrb_ary_len(mrb, result) < 1) { result = mrb_nil_value(); } } else { // As one shape result = siren_shape_new(mrb, iges_reader.OneShape()); } } else { mrb_raisef(mrb, E_ARGUMENT_ERROR, "Failed to load IGES from %S.", path); } return result; } #endif <|endoftext|>
<commit_before>#ifndef STACK_HPP #define STACK_HPP #include <iostream> #include "Card.hpp" class Stack { public: Stack ( ); Stack (int c); Stack (const Stack& rhs); ~Stack ( ); int getSize ( ) const; int getTotalCapacity ( ) const; bool isEmpty ( ) const; bool isFull ( ) const; Card* peek ( ) const; Card* pop ( ); void push (Card* c); Stack& operator=(const Stack& rhs); friend std::ostream& operator<<(std::ostream& output, const Stack& currentStack); private: int capacity; int size; Card** stack; }; #endif<commit_msg>Templatizes the Stack class<commit_after>#ifndef STACK_HPP #define STACK_HPP #include <iostream> template <class T> class Stack { public: Stack ( ) : capacity (13), size (0), stack ( stack = new T*[capacity]) { } Stack (int c) : capacity (c), size (0), stack (nullptr) { if (c < 0) { capacity = 0; } stack = new T*[capacity]; } Stack (const Stack& rhs) : capacity (rhs.capacity), stack (nullptr) { stack = new T*[capacity]; for (size = 0; size < rhs.size; ++size) { stack[size] = new T (*rhs.stack[size]); } } ~Stack ( ) { for (int i = 0; i < size; ++i) { delete stack[i]; } delete[] stack; } int getSize ( ) const { return size; } int getTotalCapacity ( ) const { return capacity; } bool isEmpty ( ) const { return size == 0; } bool isFull ( ) const { return size == capacity; } T* peek ( ) const { return stack[size - 1]; } T* pop ( ) { if (! isEmpty ( )) { return stack[--size]; } return nullptr; } void push (T* c) { if(!isFull()) { stack[size++] = c; } } Stack& operator=(const Stack& rhs) { if (this != &rhs) { for (int i = 0; i < size; ++i) { delete stack[i]; } delete[] stack; capacity = rhs.capacity; stack = new T*[capacity]; for (size = 0; size < rhs.size; ++size) { stack[size] = new T (*rhs.stack[size]); } } return *this; } friend std::ostream& operator<<(std::ostream& output, const Stack& currentStack) { for (int i = 0; i < currentStack.size; ++i) { output << *currentStack.stack[i] << "\n"; } return output; } private: int capacity; int size; T** stack; }; #endif <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "itemlibraryinfo.h" #include "nodemetainfo.h" #include <QSharedData> namespace QmlDesigner { namespace Internal { class ItemLibraryEntryData : public QSharedData { public: ItemLibraryEntryData() : majorVersion(-1), minorVersion(-1) { } QString name; QString typeName; QString category; int majorVersion; int minorVersion; QString iconPath; QIcon icon; QIcon dragIcon; QList<PropertyContainer> properties; QString qml; QString requiredImport; }; class ItemLibraryInfoPrivate { public: QHash<QString, ItemLibraryEntry> nameToEntryHash; QWeakPointer<ItemLibraryInfo> baseInfo; }; } // namespace Internal // // ItemLibraryEntry // ItemLibraryEntry::ItemLibraryEntry(const ItemLibraryEntry &other) : m_data(other.m_data) { } ItemLibraryEntry& ItemLibraryEntry::operator=(const ItemLibraryEntry &other) { if (this !=&other) m_data = other.m_data; return *this; } void ItemLibraryEntry::setDragIcon(const QIcon &icon) { m_data->dragIcon = icon; } void ItemLibraryEntry::setIcon(const QIcon &icon) { m_data->icon = icon; } QIcon ItemLibraryEntry::dragIcon() const { return m_data->dragIcon; } void ItemLibraryEntry::addProperty(const Property &property) { m_data->properties.append(property); } QList<ItemLibraryEntry::Property> ItemLibraryEntry::properties() const { return m_data->properties; } ItemLibraryEntry::ItemLibraryEntry() : m_data(new Internal::ItemLibraryEntryData) { m_data->name.clear(); } ItemLibraryEntry::~ItemLibraryEntry() { } QString ItemLibraryEntry::name() const { return m_data->name; } QString ItemLibraryEntry::typeName() const { return m_data->typeName; } QString ItemLibraryEntry::qml() const { return m_data->qml; } QString ItemLibraryEntry::requiredImport() const { return m_data->requiredImport; } int ItemLibraryEntry::majorVersion() const { return m_data->majorVersion; } int ItemLibraryEntry::minorVersion() const { return m_data->minorVersion; } QString ItemLibraryEntry::category() const { return m_data->category; } void ItemLibraryEntry::setCategory(const QString &category) { m_data->category = category; } QIcon ItemLibraryEntry::icon() const { return m_data->icon; } QString ItemLibraryEntry::iconPath() const { return m_data->iconPath; } void ItemLibraryEntry::setName(const QString &name) { m_data->name = name; } void ItemLibraryEntry::setType(const QString &typeName, int majorVersion, int minorVersion) { m_data->typeName = typeName; m_data->majorVersion = majorVersion; m_data->minorVersion = minorVersion; } void ItemLibraryEntry::setIconPath(const QString &iconPath) { m_data->iconPath = iconPath; } void ItemLibraryEntry::setQml(const QString &qml) { m_data->qml = qml; } void ItemLibraryEntry::setRequiredImport(const QString &requiredImport) { m_data->requiredImport = requiredImport; } void ItemLibraryEntry::addProperty(QString &name, QString &type, QString &value) { Property property; property.set(name, type, value); addProperty(property); } QDataStream& operator<<(QDataStream& stream, const ItemLibraryEntry &itemLibraryEntry) { stream << itemLibraryEntry.name(); stream << itemLibraryEntry.typeName(); stream << itemLibraryEntry.majorVersion(); stream << itemLibraryEntry.minorVersion(); stream << itemLibraryEntry.icon(); stream << itemLibraryEntry.iconPath(); stream << itemLibraryEntry.category(); stream << itemLibraryEntry.dragIcon(); stream << itemLibraryEntry.requiredImport(); stream << itemLibraryEntry.m_data->properties; return stream; } QDataStream& operator>>(QDataStream& stream, ItemLibraryEntry &itemLibraryEntry) { stream >> itemLibraryEntry.m_data->name; stream >> itemLibraryEntry.m_data->typeName; stream >> itemLibraryEntry.m_data->majorVersion; stream >> itemLibraryEntry.m_data->minorVersion; stream >> itemLibraryEntry.m_data->icon; stream >> itemLibraryEntry.m_data->iconPath; stream >> itemLibraryEntry.m_data->category; stream >> itemLibraryEntry.m_data->dragIcon; stream >> itemLibraryEntry.m_data->requiredImport; stream >> itemLibraryEntry.m_data->properties; return stream; } // // ItemLibraryInfo // ItemLibraryInfo::ItemLibraryInfo(QObject *parent) : QObject(parent), m_d(new Internal::ItemLibraryInfoPrivate()) { } ItemLibraryInfo::~ItemLibraryInfo() { } QList<ItemLibraryEntry> ItemLibraryInfo::entriesForType(const QString &typeName, int majorVersion, int minorVersion) const { QList<ItemLibraryEntry> entries; foreach (const ItemLibraryEntry &entry, m_d->nameToEntryHash.values()) { if (entry.typeName() == typeName && entry.majorVersion() == majorVersion && entry.minorVersion() == minorVersion) entries += entry; } if (m_d->baseInfo) entries += m_d->baseInfo->entriesForType(typeName, majorVersion, minorVersion); return entries; } ItemLibraryEntry ItemLibraryInfo::entry(const QString &name) const { if (m_d->nameToEntryHash.contains(name)) return m_d->nameToEntryHash.value(name); if (m_d->baseInfo) return m_d->baseInfo->entry(name); return ItemLibraryEntry(); } QList<ItemLibraryEntry> ItemLibraryInfo::entries() const { QList<ItemLibraryEntry> list = m_d->nameToEntryHash.values(); if (m_d->baseInfo) list += m_d->baseInfo->entries(); return list; } static inline QString keyForEntry(const ItemLibraryEntry &entry) { return entry.name() + entry.category(); } void ItemLibraryInfo::addEntry(const ItemLibraryEntry &entry) { const QString key = keyForEntry(entry); if (m_d->nameToEntryHash.contains(key)) throw InvalidMetaInfoException(__LINE__, __FUNCTION__, __FILE__); m_d->nameToEntryHash.insert(key, entry); emit entriesChanged(); } bool ItemLibraryInfo::containsEntry(const ItemLibraryEntry &entry) { const QString key = keyForEntry(entry); return m_d->nameToEntryHash.contains(key); } void ItemLibraryInfo::clearEntries() { m_d->nameToEntryHash.clear(); emit entriesChanged(); } void ItemLibraryInfo::setBaseInfo(ItemLibraryInfo *baseInfo) { m_d->baseInfo = baseInfo; } } // namespace QmlDesigner <commit_msg>QmlDesigneritemLibrary: relax condition for entriesForType()<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "itemlibraryinfo.h" #include "nodemetainfo.h" #include <QSharedData> namespace QmlDesigner { namespace Internal { class ItemLibraryEntryData : public QSharedData { public: ItemLibraryEntryData() : majorVersion(-1), minorVersion(-1) { } QString name; QString typeName; QString category; int majorVersion; int minorVersion; QString iconPath; QIcon icon; QIcon dragIcon; QList<PropertyContainer> properties; QString qml; QString requiredImport; }; class ItemLibraryInfoPrivate { public: QHash<QString, ItemLibraryEntry> nameToEntryHash; QWeakPointer<ItemLibraryInfo> baseInfo; }; } // namespace Internal // // ItemLibraryEntry // ItemLibraryEntry::ItemLibraryEntry(const ItemLibraryEntry &other) : m_data(other.m_data) { } ItemLibraryEntry& ItemLibraryEntry::operator=(const ItemLibraryEntry &other) { if (this !=&other) m_data = other.m_data; return *this; } void ItemLibraryEntry::setDragIcon(const QIcon &icon) { m_data->dragIcon = icon; } void ItemLibraryEntry::setIcon(const QIcon &icon) { m_data->icon = icon; } QIcon ItemLibraryEntry::dragIcon() const { return m_data->dragIcon; } void ItemLibraryEntry::addProperty(const Property &property) { m_data->properties.append(property); } QList<ItemLibraryEntry::Property> ItemLibraryEntry::properties() const { return m_data->properties; } ItemLibraryEntry::ItemLibraryEntry() : m_data(new Internal::ItemLibraryEntryData) { m_data->name.clear(); } ItemLibraryEntry::~ItemLibraryEntry() { } QString ItemLibraryEntry::name() const { return m_data->name; } QString ItemLibraryEntry::typeName() const { return m_data->typeName; } QString ItemLibraryEntry::qml() const { return m_data->qml; } QString ItemLibraryEntry::requiredImport() const { return m_data->requiredImport; } int ItemLibraryEntry::majorVersion() const { return m_data->majorVersion; } int ItemLibraryEntry::minorVersion() const { return m_data->minorVersion; } QString ItemLibraryEntry::category() const { return m_data->category; } void ItemLibraryEntry::setCategory(const QString &category) { m_data->category = category; } QIcon ItemLibraryEntry::icon() const { return m_data->icon; } QString ItemLibraryEntry::iconPath() const { return m_data->iconPath; } void ItemLibraryEntry::setName(const QString &name) { m_data->name = name; } void ItemLibraryEntry::setType(const QString &typeName, int majorVersion, int minorVersion) { m_data->typeName = typeName; m_data->majorVersion = majorVersion; m_data->minorVersion = minorVersion; } void ItemLibraryEntry::setIconPath(const QString &iconPath) { m_data->iconPath = iconPath; } void ItemLibraryEntry::setQml(const QString &qml) { m_data->qml = qml; } void ItemLibraryEntry::setRequiredImport(const QString &requiredImport) { m_data->requiredImport = requiredImport; } void ItemLibraryEntry::addProperty(QString &name, QString &type, QString &value) { Property property; property.set(name, type, value); addProperty(property); } QDataStream& operator<<(QDataStream& stream, const ItemLibraryEntry &itemLibraryEntry) { stream << itemLibraryEntry.name(); stream << itemLibraryEntry.typeName(); stream << itemLibraryEntry.majorVersion(); stream << itemLibraryEntry.minorVersion(); stream << itemLibraryEntry.icon(); stream << itemLibraryEntry.iconPath(); stream << itemLibraryEntry.category(); stream << itemLibraryEntry.dragIcon(); stream << itemLibraryEntry.requiredImport(); stream << itemLibraryEntry.m_data->properties; return stream; } QDataStream& operator>>(QDataStream& stream, ItemLibraryEntry &itemLibraryEntry) { stream >> itemLibraryEntry.m_data->name; stream >> itemLibraryEntry.m_data->typeName; stream >> itemLibraryEntry.m_data->majorVersion; stream >> itemLibraryEntry.m_data->minorVersion; stream >> itemLibraryEntry.m_data->icon; stream >> itemLibraryEntry.m_data->iconPath; stream >> itemLibraryEntry.m_data->category; stream >> itemLibraryEntry.m_data->dragIcon; stream >> itemLibraryEntry.m_data->requiredImport; stream >> itemLibraryEntry.m_data->properties; return stream; } // // ItemLibraryInfo // ItemLibraryInfo::ItemLibraryInfo(QObject *parent) : QObject(parent), m_d(new Internal::ItemLibraryInfoPrivate()) { } ItemLibraryInfo::~ItemLibraryInfo() { } QList<ItemLibraryEntry> ItemLibraryInfo::entriesForType(const QString &typeName, int majorVersion, int minorVersion) const { QList<ItemLibraryEntry> entries; foreach (const ItemLibraryEntry &entry, m_d->nameToEntryHash.values()) { if (entry.typeName() == typeName && entry.majorVersion() >= majorVersion && entry.minorVersion() >= minorVersion) entries += entry; } if (m_d->baseInfo) entries += m_d->baseInfo->entriesForType(typeName, majorVersion, minorVersion); return entries; } ItemLibraryEntry ItemLibraryInfo::entry(const QString &name) const { if (m_d->nameToEntryHash.contains(name)) return m_d->nameToEntryHash.value(name); if (m_d->baseInfo) return m_d->baseInfo->entry(name); return ItemLibraryEntry(); } QList<ItemLibraryEntry> ItemLibraryInfo::entries() const { QList<ItemLibraryEntry> list = m_d->nameToEntryHash.values(); if (m_d->baseInfo) list += m_d->baseInfo->entries(); return list; } static inline QString keyForEntry(const ItemLibraryEntry &entry) { return entry.name() + entry.category(); } void ItemLibraryInfo::addEntry(const ItemLibraryEntry &entry) { const QString key = keyForEntry(entry); if (m_d->nameToEntryHash.contains(key)) throw InvalidMetaInfoException(__LINE__, __FUNCTION__, __FILE__); m_d->nameToEntryHash.insert(key, entry); emit entriesChanged(); } bool ItemLibraryInfo::containsEntry(const ItemLibraryEntry &entry) { const QString key = keyForEntry(entry); return m_d->nameToEntryHash.contains(key); } void ItemLibraryInfo::clearEntries() { m_d->nameToEntryHash.clear(); emit entriesChanged(); } void ItemLibraryInfo::setBaseInfo(ItemLibraryInfo *baseInfo) { m_d->baseInfo = baseInfo; } } // namespace QmlDesigner <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** GNU Lesser General Public License Usage ** ** 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. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "genericlinuxdeviceconfigurationwidget.h" #include "ui_genericlinuxdeviceconfigurationwidget.h" #include <utils/portlist.h> #include <utils/ssh/sshconnection.h> #include <utils/ssh/sshkeycreationdialog.h> #include <QTextStream> using namespace RemoteLinux; using namespace Utils; GenericLinuxDeviceConfigurationWidget::GenericLinuxDeviceConfigurationWidget( const LinuxDeviceConfiguration::Ptr &deviceConfig, QWidget *parent) : ProjectExplorer::IDeviceWidget(deviceConfig, parent), m_ui(new Ui::GenericLinuxDeviceConfigurationWidget) { m_ui->setupUi(this); connect(m_ui->hostLineEdit, SIGNAL(editingFinished()), this, SLOT(hostNameEditingFinished())); connect(m_ui->userLineEdit, SIGNAL(editingFinished()), this, SLOT(userNameEditingFinished())); connect(m_ui->pwdLineEdit, SIGNAL(editingFinished()), this, SLOT(passwordEditingFinished())); connect(m_ui->passwordButton, SIGNAL(toggled(bool)), this, SLOT(authenticationTypeChanged())); connect(m_ui->keyFileLineEdit, SIGNAL(editingFinished()), this, SLOT(keyFileEditingFinished())); connect(m_ui->keyFileLineEdit, SIGNAL(browsingFinished()), this, SLOT(keyFileEditingFinished())); connect(m_ui->keyButton, SIGNAL(toggled(bool)), this, SLOT(authenticationTypeChanged())); connect(m_ui->timeoutSpinBox, SIGNAL(editingFinished()), this, SLOT(timeoutEditingFinished())); connect(m_ui->timeoutSpinBox, SIGNAL(valueChanged(int)), this, SLOT(timeoutEditingFinished())); connect(m_ui->sshPortSpinBox, SIGNAL(editingFinished()), this, SLOT(sshPortEditingFinished())); connect(m_ui->sshPortSpinBox, SIGNAL(valueChanged(int)), this, SLOT(sshPortEditingFinished())); connect(m_ui->showPasswordCheckBox, SIGNAL(toggled(bool)), this, SLOT(showPassword(bool))); connect(m_ui->portsLineEdit, SIGNAL(editingFinished()), this, SLOT(handleFreePortsChanged())); connect(m_ui->createKeyButton, SIGNAL(clicked()), SLOT(createNewKey())); initGui(); } GenericLinuxDeviceConfigurationWidget::~GenericLinuxDeviceConfigurationWidget() { delete m_ui; } void GenericLinuxDeviceConfigurationWidget::authenticationTypeChanged() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); const bool usePassword = m_ui->passwordButton->isChecked(); sshParams.authenticationType = usePassword ? SshConnectionParameters::AuthenticationByPassword : SshConnectionParameters::AuthenticationByKey; deviceConfiguration()->setSshParameters(sshParams); m_ui->pwdLineEdit->setEnabled(usePassword); m_ui->passwordLabel->setEnabled(usePassword); m_ui->keyFileLineEdit->setEnabled(!usePassword); m_ui->keyLabel->setEnabled(!usePassword); } void GenericLinuxDeviceConfigurationWidget::hostNameEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.host = m_ui->hostLineEdit->text(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::sshPortEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.port = m_ui->sshPortSpinBox->value(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::timeoutEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.timeout = m_ui->timeoutSpinBox->value(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::userNameEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.userName = m_ui->userLineEdit->text(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::passwordEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.password = m_ui->pwdLineEdit->text(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::keyFileEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.privateKeyFile = m_ui->keyFileLineEdit->path(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::handleFreePortsChanged() { deviceConfiguration()->setFreePorts(PortList::fromString(m_ui->portsLineEdit->text())); updatePortsWarningLabel(); } void GenericLinuxDeviceConfigurationWidget::showPassword(bool showClearText) { m_ui->pwdLineEdit->setEchoMode(showClearText ? QLineEdit::Normal : QLineEdit::Password); } void GenericLinuxDeviceConfigurationWidget::setPrivateKey(const QString &path) { m_ui->keyFileLineEdit->setPath(path); keyFileEditingFinished(); } void GenericLinuxDeviceConfigurationWidget::createNewKey() { SshKeyCreationDialog dialog(this); if (dialog.exec() == QDialog::Accepted) setPrivateKey(dialog.privateKeyFilePath()); } void GenericLinuxDeviceConfigurationWidget::updatePortsWarningLabel() { m_ui->portsWarningLabel->setVisible(!deviceConfiguration()->freePorts().hasMore()); } void GenericLinuxDeviceConfigurationWidget::initGui() { if (deviceConfiguration()->machineType() == LinuxDeviceConfiguration::Hardware) m_ui->machineTypeValueLabel->setText(tr("Physical Device")); else m_ui->machineTypeValueLabel->setText(tr("Emulator")); m_ui->portsWarningLabel->setPixmap(QPixmap(":/projectexplorer/images/compile_error.png")); m_ui->portsWarningLabel->setToolTip(QLatin1String("<font color=\"red\">") + tr("You will need at least one port.") + QLatin1String("</font>")); m_ui->keyFileLineEdit->setExpectedKind(PathChooser::File); m_ui->keyFileLineEdit->lineEdit()->setMinimumWidth(0); QRegExpValidator * const portsValidator = new QRegExpValidator(QRegExp(PortList::regularExpression()), this); m_ui->portsLineEdit->setValidator(portsValidator); const SshConnectionParameters &sshParams = deviceConfiguration()->sshParameters(); if (sshParams.authenticationType == SshConnectionParameters::AuthenticationByPassword) m_ui->passwordButton->setChecked(true); else m_ui->keyButton->setChecked(true); m_ui->timeoutSpinBox->setValue(sshParams.timeout); m_ui->hostLineEdit->setEnabled(!deviceConfiguration()->isAutoDetected()); m_ui->sshPortSpinBox->setEnabled(!deviceConfiguration()->isAutoDetected()); m_ui->hostLineEdit->setText(sshParams.host); m_ui->sshPortSpinBox->setValue(sshParams.port); m_ui->portsLineEdit->setText(deviceConfiguration()->freePorts().toString()); m_ui->timeoutSpinBox->setValue(sshParams.timeout); m_ui->userLineEdit->setText(sshParams.userName); m_ui->pwdLineEdit->setText(sshParams.password); m_ui->keyFileLineEdit->setPath(sshParams.privateKeyFile); m_ui->showPasswordCheckBox->setChecked(false); updatePortsWarningLabel(); } LinuxDeviceConfiguration::Ptr GenericLinuxDeviceConfigurationWidget::deviceConfiguration() const { return device().staticCast<LinuxDeviceConfiguration>(); } <commit_msg>RemoteLinux: Trim hostname string when configuring device<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** GNU Lesser General Public License Usage ** ** 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. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "genericlinuxdeviceconfigurationwidget.h" #include "ui_genericlinuxdeviceconfigurationwidget.h" #include <utils/portlist.h> #include <utils/ssh/sshconnection.h> #include <utils/ssh/sshkeycreationdialog.h> #include <QTextStream> using namespace RemoteLinux; using namespace Utils; GenericLinuxDeviceConfigurationWidget::GenericLinuxDeviceConfigurationWidget( const LinuxDeviceConfiguration::Ptr &deviceConfig, QWidget *parent) : ProjectExplorer::IDeviceWidget(deviceConfig, parent), m_ui(new Ui::GenericLinuxDeviceConfigurationWidget) { m_ui->setupUi(this); connect(m_ui->hostLineEdit, SIGNAL(editingFinished()), this, SLOT(hostNameEditingFinished())); connect(m_ui->userLineEdit, SIGNAL(editingFinished()), this, SLOT(userNameEditingFinished())); connect(m_ui->pwdLineEdit, SIGNAL(editingFinished()), this, SLOT(passwordEditingFinished())); connect(m_ui->passwordButton, SIGNAL(toggled(bool)), this, SLOT(authenticationTypeChanged())); connect(m_ui->keyFileLineEdit, SIGNAL(editingFinished()), this, SLOT(keyFileEditingFinished())); connect(m_ui->keyFileLineEdit, SIGNAL(browsingFinished()), this, SLOT(keyFileEditingFinished())); connect(m_ui->keyButton, SIGNAL(toggled(bool)), this, SLOT(authenticationTypeChanged())); connect(m_ui->timeoutSpinBox, SIGNAL(editingFinished()), this, SLOT(timeoutEditingFinished())); connect(m_ui->timeoutSpinBox, SIGNAL(valueChanged(int)), this, SLOT(timeoutEditingFinished())); connect(m_ui->sshPortSpinBox, SIGNAL(editingFinished()), this, SLOT(sshPortEditingFinished())); connect(m_ui->sshPortSpinBox, SIGNAL(valueChanged(int)), this, SLOT(sshPortEditingFinished())); connect(m_ui->showPasswordCheckBox, SIGNAL(toggled(bool)), this, SLOT(showPassword(bool))); connect(m_ui->portsLineEdit, SIGNAL(editingFinished()), this, SLOT(handleFreePortsChanged())); connect(m_ui->createKeyButton, SIGNAL(clicked()), SLOT(createNewKey())); initGui(); } GenericLinuxDeviceConfigurationWidget::~GenericLinuxDeviceConfigurationWidget() { delete m_ui; } void GenericLinuxDeviceConfigurationWidget::authenticationTypeChanged() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); const bool usePassword = m_ui->passwordButton->isChecked(); sshParams.authenticationType = usePassword ? SshConnectionParameters::AuthenticationByPassword : SshConnectionParameters::AuthenticationByKey; deviceConfiguration()->setSshParameters(sshParams); m_ui->pwdLineEdit->setEnabled(usePassword); m_ui->passwordLabel->setEnabled(usePassword); m_ui->keyFileLineEdit->setEnabled(!usePassword); m_ui->keyLabel->setEnabled(!usePassword); } void GenericLinuxDeviceConfigurationWidget::hostNameEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.host = m_ui->hostLineEdit->text().trimmed(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::sshPortEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.port = m_ui->sshPortSpinBox->value(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::timeoutEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.timeout = m_ui->timeoutSpinBox->value(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::userNameEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.userName = m_ui->userLineEdit->text(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::passwordEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.password = m_ui->pwdLineEdit->text(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::keyFileEditingFinished() { SshConnectionParameters sshParams = deviceConfiguration()->sshParameters(); sshParams.privateKeyFile = m_ui->keyFileLineEdit->path(); deviceConfiguration()->setSshParameters(sshParams); } void GenericLinuxDeviceConfigurationWidget::handleFreePortsChanged() { deviceConfiguration()->setFreePorts(PortList::fromString(m_ui->portsLineEdit->text())); updatePortsWarningLabel(); } void GenericLinuxDeviceConfigurationWidget::showPassword(bool showClearText) { m_ui->pwdLineEdit->setEchoMode(showClearText ? QLineEdit::Normal : QLineEdit::Password); } void GenericLinuxDeviceConfigurationWidget::setPrivateKey(const QString &path) { m_ui->keyFileLineEdit->setPath(path); keyFileEditingFinished(); } void GenericLinuxDeviceConfigurationWidget::createNewKey() { SshKeyCreationDialog dialog(this); if (dialog.exec() == QDialog::Accepted) setPrivateKey(dialog.privateKeyFilePath()); } void GenericLinuxDeviceConfigurationWidget::updatePortsWarningLabel() { m_ui->portsWarningLabel->setVisible(!deviceConfiguration()->freePorts().hasMore()); } void GenericLinuxDeviceConfigurationWidget::initGui() { if (deviceConfiguration()->machineType() == LinuxDeviceConfiguration::Hardware) m_ui->machineTypeValueLabel->setText(tr("Physical Device")); else m_ui->machineTypeValueLabel->setText(tr("Emulator")); m_ui->portsWarningLabel->setPixmap(QPixmap(":/projectexplorer/images/compile_error.png")); m_ui->portsWarningLabel->setToolTip(QLatin1String("<font color=\"red\">") + tr("You will need at least one port.") + QLatin1String("</font>")); m_ui->keyFileLineEdit->setExpectedKind(PathChooser::File); m_ui->keyFileLineEdit->lineEdit()->setMinimumWidth(0); QRegExpValidator * const portsValidator = new QRegExpValidator(QRegExp(PortList::regularExpression()), this); m_ui->portsLineEdit->setValidator(portsValidator); const SshConnectionParameters &sshParams = deviceConfiguration()->sshParameters(); if (sshParams.authenticationType == SshConnectionParameters::AuthenticationByPassword) m_ui->passwordButton->setChecked(true); else m_ui->keyButton->setChecked(true); m_ui->timeoutSpinBox->setValue(sshParams.timeout); m_ui->hostLineEdit->setEnabled(!deviceConfiguration()->isAutoDetected()); m_ui->sshPortSpinBox->setEnabled(!deviceConfiguration()->isAutoDetected()); m_ui->hostLineEdit->setText(sshParams.host); m_ui->sshPortSpinBox->setValue(sshParams.port); m_ui->portsLineEdit->setText(deviceConfiguration()->freePorts().toString()); m_ui->timeoutSpinBox->setValue(sshParams.timeout); m_ui->userLineEdit->setText(sshParams.userName); m_ui->pwdLineEdit->setText(sshParams.password); m_ui->keyFileLineEdit->setPath(sshParams.privateKeyFile); m_ui->showPasswordCheckBox->setChecked(false); updatePortsWarningLabel(); } LinuxDeviceConfiguration::Ptr GenericLinuxDeviceConfigurationWidget::deviceConfiguration() const { return device().staticCast<LinuxDeviceConfiguration>(); } <|endoftext|>
<commit_before> #include <algorithm> #include <iostream> #include "lib/units.h" #include "c_thrustable.h" #include "c_moveable.h" #include "s_thrust.h" namespace spacegun { using namespace std; extern const string COMPONENT_TYPE_THRUSTABLE; void Thrust::init(aronnax::Entities& entities) { for (auto e : entities) { bindEntity(*e); } } void Thrust::onAddEntity(aronnax::Entity& entity) { bindEntity(entity); } void Thrust::bindEntity(aronnax::Entity& entity) { entity.on(aronnax::EV_USER_MOVEMENT, [&](aronnax::EvUserMovement* ev) { handleMovementKey(*ev, entity); //cout << "ev-user_move x:" << ev->getDirection().x // << " y:" << ev->getDirection().y << endl; }); entity.on(aronnax::EV_USER_ROTATION, [&](aronnax::EvUserRotation* ev) { handleRotationKey(*ev, entity); //cout << "ev-user_rotation " << ev->getDirection() << endl; }); } void Thrust::handleMovementKey(aronnax::EvUserMovement& ev, aronnax::Entity& entity) { auto moveable = entity.getComponent<Moveable>(COMPONENT_TYPE_MOVEABLE); auto thrustable = entity.getComponent<Thrustable>( COMPONENT_TYPE_THRUSTABLE); auto thrustFactor = thrustable->getFactor(); Vector2d curr = moveable->getVel(); Vector2d mod = ev.getDirection(); // mod *= thrustFactor; mod.x *= thrustFactor; mod.y *= thrustFactor; Vector2d newV = mod + curr; cout << "vx: " << curr.x << " vy: " << curr.y << endl; moveable->applyForce(newV); } void Thrust::handleRotationKey(aronnax::EvUserRotation& ev, aronnax::Entity& entity) { auto moveable = entity.getComponent<Moveable>(COMPONENT_TYPE_MOVEABLE); auto thrustable = entity.getComponent<Thrustable>( COMPONENT_TYPE_THRUSTABLE); auto thrustFactor = thrustable->getFactor(); auto torque = ev.getDirection() * thrustFactor; moveable->applyTorque(torque); } const string& Thrust::getType() { return COMPONENT_TYPE_THRUSTABLE; } } <commit_msg>Prototype one thrust engine<commit_after> #include <algorithm> #include <cmath> #include <iostream> #include "lib/units.h" #include "c_thrustable.h" #include "c_moveable.h" #include "s_thrust.h" namespace spacegun { using namespace std; extern const string COMPONENT_TYPE_THRUSTABLE; void Thrust::init(aronnax::Entities& entities) { for (auto e : entities) { bindEntity(*e); } } void Thrust::onAddEntity(aronnax::Entity& entity) { bindEntity(entity); } void Thrust::bindEntity(aronnax::Entity& entity) { entity.on(aronnax::EV_USER_MOVEMENT, [&](aronnax::EvUserMovement* ev) { handleMovementKey(*ev, entity); //cout << "ev-user_move x:" << ev->getDirection().x // << " y:" << ev->getDirection().y << endl; }); entity.on(aronnax::EV_USER_ROTATION, [&](aronnax::EvUserRotation* ev) { handleRotationKey(*ev, entity); //cout << "ev-user_rotation " << ev->getDirection() << endl; }); } void Thrust::handleMovementKey(aronnax::EvUserMovement& ev, aronnax::Entity& entity) { auto moveable = entity.getComponent<Moveable>(COMPONENT_TYPE_MOVEABLE); auto thrustable = entity.getComponent<Thrustable>( COMPONENT_TYPE_THRUSTABLE); auto thrustFactor = thrustable->getFactor(); Vector2d force; auto angle = moveable->getAngle(); force.x = cos(angle); force.y = sin(angle); force.x *= thrustFactor; force.y *= thrustFactor; cout << "vx: " << force.x << " vy: " << force.y << endl; moveable->applyForce(force); } void Thrust::handleRotationKey(aronnax::EvUserRotation& ev, aronnax::Entity& entity) { auto moveable = entity.getComponent<Moveable>(COMPONENT_TYPE_MOVEABLE); auto thrustable = entity.getComponent<Thrustable>( COMPONENT_TYPE_THRUSTABLE); auto thrustFactor = thrustable->getFactor(); auto torque = ev.getDirection() * thrustFactor * 3; moveable->applyTorque(torque); } const string& Thrust::getType() { return COMPONENT_TYPE_THRUSTABLE; } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "highlightersettings.h" #include <coreplugin/icore.h> #include <QtCore/QSettings> #include <QtCore/QLatin1String> #include <QtCore/QLatin1Char> #include <QtCore/QDir> #include <QtCore/QFile> #ifdef Q_OS_UNIX #include <QtCore/QProcess> #endif namespace TextEditor { namespace Internal { QString findDefinitionsLocation() { #ifdef Q_OS_UNIX static const QLatin1String kateSyntax[] = { QLatin1String("/share/apps/katepart/syntax"), QLatin1String("/share/kde4/apps/katepart/syntax") }; static const int kateSyntaxCount = sizeof(kateSyntax) / sizeof(kateSyntax[0]); // Some wild guesses. QDir dir; for (int i = 0; i < kateSyntaxCount; ++i) { QStringList paths; paths << QLatin1String("/usr") + kateSyntax[i] << QLatin1String("/usr/local") + kateSyntax[i] << QLatin1String("/opt") + kateSyntax[i]; foreach (const QString &path, paths) { dir.setPath(path); if (dir.exists()) return dir.path(); } } // Try kde-config. QStringList programs; programs << QLatin1String("kde-config") << QLatin1String("kde4-config"); foreach (const QString &program, programs) { QProcess process; process.start(program, QStringList(QLatin1String("--prefix"))); if (process.waitForStarted(5000)) { process.waitForFinished(5000); QString output = QString::fromLocal8Bit(process.readAllStandardOutput()); output.remove(QLatin1Char('\n')); for (int i = 0; i < kateSyntaxCount; ++i) { dir.setPath(output + kateSyntax[i]); if (dir.exists()) return dir.path(); } } } #endif return QString(); } } // namespace Internal } // namespace TextEditor namespace { static const QLatin1String kDefinitionFilesPath("UserDefinitionFilesPath"); static const QLatin1String kFallbackDefinitionFilesPath("FallbackDefinitionFilesPath"); static const QLatin1String kAlertWhenDefinitionIsNotFound("AlertWhenDefinitionsIsNotFound"); static const QLatin1String kUseFallbackLocation("UseFallbackLocation"); static const QLatin1String kIgnoredFilesPatterns("IgnoredFilesPatterns"); static const QLatin1String kGroupPostfix("HighlighterSettings"); QString groupSpecifier(const QString &postFix, const QString &category) { if (category.isEmpty()) return postFix; return QString(category + postFix); } } // namespace anonymous using namespace TextEditor; using namespace Internal; HighlighterSettings::HighlighterSettings() : m_alertWhenNoDefinition(true), m_useFallbackLocation(true) {} void HighlighterSettings::toSettings(const QString &category, QSettings *s) const { const QString &group = groupSpecifier(kGroupPostfix, category); s->beginGroup(group); s->setValue(kDefinitionFilesPath, m_definitionFilesPath); s->setValue(kFallbackDefinitionFilesPath, m_fallbackDefinitionFilesPath); s->setValue(kAlertWhenDefinitionIsNotFound, m_alertWhenNoDefinition); s->setValue(kUseFallbackLocation, m_useFallbackLocation); s->setValue(kIgnoredFilesPatterns, ignoredFilesPatterns()); s->endGroup(); } void HighlighterSettings::fromSettings(const QString &category, QSettings *s) { const QString &group = groupSpecifier(kGroupPostfix, category); s->beginGroup(group); m_definitionFilesPath = s->value(kDefinitionFilesPath, QString()).toString(); if (!s->contains(kDefinitionFilesPath)) assignDefaultDefinitionsPath(); else m_definitionFilesPath = s->value(kDefinitionFilesPath).toString(); if (!s->contains(kFallbackDefinitionFilesPath)) { m_fallbackDefinitionFilesPath = findDefinitionsLocation(); if (m_fallbackDefinitionFilesPath.isEmpty()) m_useFallbackLocation = false; else m_useFallbackLocation = true; } else { m_fallbackDefinitionFilesPath = s->value(kFallbackDefinitionFilesPath).toString(); m_useFallbackLocation = s->value(kUseFallbackLocation, true).toBool(); } m_alertWhenNoDefinition = s->value(kAlertWhenDefinitionIsNotFound, true).toBool(); if (!s->contains(kIgnoredFilesPatterns)) assignDefaultIgnoredPatterns(); else setIgnoredFilesPatterns(s->value(kIgnoredFilesPatterns, QString()).toString()); s->endGroup(); } void HighlighterSettings::setIgnoredFilesPatterns(const QString &patterns) { setExpressionsFromList(patterns.split(QLatin1Char(','), QString::SkipEmptyParts)); } QString HighlighterSettings::ignoredFilesPatterns() const { return listFromExpressions().join(QLatin1String(",")); } void HighlighterSettings::assignDefaultIgnoredPatterns() { QStringList patterns; patterns << QLatin1String("*.txt") << QLatin1String("LICENSE*") << QLatin1String("README") << QLatin1String("INSTALL") << QLatin1String("COPYING") << QLatin1String("NEWS") << QLatin1String("qmldir"); setExpressionsFromList(patterns); } void HighlighterSettings::assignDefaultDefinitionsPath() { const QString &path = Core::ICore::instance()->userResourcePath() + QLatin1String("/generic-highlighter"); if (QFile::exists(path) || QDir().mkpath(path)) m_definitionFilesPath = path; } bool HighlighterSettings::isIgnoredFilePattern(const QString &fileName) const { foreach (const QRegExp &regExp, m_ignoredFiles) if (regExp.indexIn(fileName) != -1) return true; return false; } bool HighlighterSettings::equals(const HighlighterSettings &highlighterSettings) const { return m_definitionFilesPath == highlighterSettings.m_definitionFilesPath && m_fallbackDefinitionFilesPath == highlighterSettings.m_fallbackDefinitionFilesPath && m_alertWhenNoDefinition == highlighterSettings.m_alertWhenNoDefinition && m_useFallbackLocation == highlighterSettings.m_useFallbackLocation && m_ignoredFiles == highlighterSettings.m_ignoredFiles; } void HighlighterSettings::setExpressionsFromList(const QStringList &patterns) { m_ignoredFiles.clear(); QRegExp regExp; regExp.setCaseSensitivity(Qt::CaseInsensitive); regExp.setPatternSyntax(QRegExp::Wildcard); foreach (const QString &s, patterns) { regExp.setPattern(s); m_ignoredFiles.append(regExp); } } QStringList HighlighterSettings::listFromExpressions() const { QStringList patterns; foreach (const QRegExp &regExp, m_ignoredFiles) patterns.append(regExp.pattern()); return patterns; } <commit_msg>Generic highlighter: Don't search for pre-installed definitions on mac.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "highlightersettings.h" #include <coreplugin/icore.h> #include <QtCore/QSettings> #include <QtCore/QLatin1String> #include <QtCore/QLatin1Char> #include <QtCore/QDir> #include <QtCore/QFile> #ifdef Q_OS_UNIX #include <QtCore/QProcess> #endif namespace TextEditor { namespace Internal { QString findDefinitionsLocation() { #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) static const QLatin1String kateSyntax[] = { QLatin1String("/share/apps/katepart/syntax"), QLatin1String("/share/kde4/apps/katepart/syntax") }; static const int kateSyntaxCount = sizeof(kateSyntax) / sizeof(kateSyntax[0]); // Some wild guesses. QDir dir; for (int i = 0; i < kateSyntaxCount; ++i) { QStringList paths; paths << QLatin1String("/usr") + kateSyntax[i] << QLatin1String("/usr/local") + kateSyntax[i] << QLatin1String("/opt") + kateSyntax[i]; foreach (const QString &path, paths) { dir.setPath(path); if (dir.exists()) return dir.path(); } } // Try kde-config. QStringList programs; programs << QLatin1String("kde-config") << QLatin1String("kde4-config"); foreach (const QString &program, programs) { QProcess process; process.start(program, QStringList(QLatin1String("--prefix"))); if (process.waitForStarted(5000)) { process.waitForFinished(5000); QString output = QString::fromLocal8Bit(process.readAllStandardOutput()); output.remove(QLatin1Char('\n')); for (int i = 0; i < kateSyntaxCount; ++i) { dir.setPath(output + kateSyntax[i]); if (dir.exists()) return dir.path(); } } } #endif return QString(); } } // namespace Internal } // namespace TextEditor namespace { static const QLatin1String kDefinitionFilesPath("UserDefinitionFilesPath"); static const QLatin1String kFallbackDefinitionFilesPath("FallbackDefinitionFilesPath"); static const QLatin1String kAlertWhenDefinitionIsNotFound("AlertWhenDefinitionsIsNotFound"); static const QLatin1String kUseFallbackLocation("UseFallbackLocation"); static const QLatin1String kIgnoredFilesPatterns("IgnoredFilesPatterns"); static const QLatin1String kGroupPostfix("HighlighterSettings"); QString groupSpecifier(const QString &postFix, const QString &category) { if (category.isEmpty()) return postFix; return QString(category + postFix); } } // namespace anonymous using namespace TextEditor; using namespace Internal; HighlighterSettings::HighlighterSettings() : m_alertWhenNoDefinition(true), m_useFallbackLocation(true) {} void HighlighterSettings::toSettings(const QString &category, QSettings *s) const { const QString &group = groupSpecifier(kGroupPostfix, category); s->beginGroup(group); s->setValue(kDefinitionFilesPath, m_definitionFilesPath); s->setValue(kFallbackDefinitionFilesPath, m_fallbackDefinitionFilesPath); s->setValue(kAlertWhenDefinitionIsNotFound, m_alertWhenNoDefinition); s->setValue(kUseFallbackLocation, m_useFallbackLocation); s->setValue(kIgnoredFilesPatterns, ignoredFilesPatterns()); s->endGroup(); } void HighlighterSettings::fromSettings(const QString &category, QSettings *s) { const QString &group = groupSpecifier(kGroupPostfix, category); s->beginGroup(group); m_definitionFilesPath = s->value(kDefinitionFilesPath, QString()).toString(); if (!s->contains(kDefinitionFilesPath)) assignDefaultDefinitionsPath(); else m_definitionFilesPath = s->value(kDefinitionFilesPath).toString(); if (!s->contains(kFallbackDefinitionFilesPath)) { m_fallbackDefinitionFilesPath = findDefinitionsLocation(); if (m_fallbackDefinitionFilesPath.isEmpty()) m_useFallbackLocation = false; else m_useFallbackLocation = true; } else { m_fallbackDefinitionFilesPath = s->value(kFallbackDefinitionFilesPath).toString(); m_useFallbackLocation = s->value(kUseFallbackLocation, true).toBool(); } m_alertWhenNoDefinition = s->value(kAlertWhenDefinitionIsNotFound, true).toBool(); if (!s->contains(kIgnoredFilesPatterns)) assignDefaultIgnoredPatterns(); else setIgnoredFilesPatterns(s->value(kIgnoredFilesPatterns, QString()).toString()); s->endGroup(); } void HighlighterSettings::setIgnoredFilesPatterns(const QString &patterns) { setExpressionsFromList(patterns.split(QLatin1Char(','), QString::SkipEmptyParts)); } QString HighlighterSettings::ignoredFilesPatterns() const { return listFromExpressions().join(QLatin1String(",")); } void HighlighterSettings::assignDefaultIgnoredPatterns() { QStringList patterns; patterns << QLatin1String("*.txt") << QLatin1String("LICENSE*") << QLatin1String("README") << QLatin1String("INSTALL") << QLatin1String("COPYING") << QLatin1String("NEWS") << QLatin1String("qmldir"); setExpressionsFromList(patterns); } void HighlighterSettings::assignDefaultDefinitionsPath() { const QString &path = Core::ICore::instance()->userResourcePath() + QLatin1String("/generic-highlighter"); if (QFile::exists(path) || QDir().mkpath(path)) m_definitionFilesPath = path; } bool HighlighterSettings::isIgnoredFilePattern(const QString &fileName) const { foreach (const QRegExp &regExp, m_ignoredFiles) if (regExp.indexIn(fileName) != -1) return true; return false; } bool HighlighterSettings::equals(const HighlighterSettings &highlighterSettings) const { return m_definitionFilesPath == highlighterSettings.m_definitionFilesPath && m_fallbackDefinitionFilesPath == highlighterSettings.m_fallbackDefinitionFilesPath && m_alertWhenNoDefinition == highlighterSettings.m_alertWhenNoDefinition && m_useFallbackLocation == highlighterSettings.m_useFallbackLocation && m_ignoredFiles == highlighterSettings.m_ignoredFiles; } void HighlighterSettings::setExpressionsFromList(const QStringList &patterns) { m_ignoredFiles.clear(); QRegExp regExp; regExp.setCaseSensitivity(Qt::CaseInsensitive); regExp.setPatternSyntax(QRegExp::Wildcard); foreach (const QString &s, patterns) { regExp.setPattern(s); m_ignoredFiles.append(regExp); } } QStringList HighlighterSettings::listFromExpressions() const { QStringList patterns; foreach (const QRegExp &regExp, m_ignoredFiles) patterns.append(regExp.pattern()); return patterns; } <|endoftext|>
<commit_before>#include "ofApp.h" #include "ofxXmlSettings.h" #include "ofxJSONElement.h" void ofApp::setup(){ ofBackground(54, 54, 54, 255); #ifdef TARGET_OSX ofSetDataPathRoot("../Resources/data/"); #endif // start logging ofLogToFile("app.log"); // start recoding events if (!eventLog.open(ofToDataPath("events.txt"), ofFile::WriteOnly)) { std::cerr << "Error opening events.txt - !!!DATA WILL BE LOST!!!" << std::endl; } if (!configuration.Read()) { std::cerr << "Error reading configuration" << std::endl; } gameStats.Read(); ofSetFrameRate(configuration.FrameRate); ofSetFullscreen(configuration.Fullscreen); //ofSetWindowShape(1000, 200); ofSetWindowPosition(0, 0); // Distance reader serialReader.ActiveSerialPort = configuration.ActiveSerialPort; serialReader.startThread(); // HUD if (!hudFont.loadFont("verdana.ttf", 12, true, true)) { std::cerr << "Error loading HUD font" << std::endl; } hudFont.setLineHeight(18.0f); hudFont.setLetterSpacing(1.037); // Overlay if (!overlayFont.loadFont("verdana.ttf", 300, true, true)) { std::cerr << "Error loading overlay font" << std::endl; } if (!stateFont.loadFont("verdana.ttf", 100, true, true)) { std::cerr << "Error loading status font" << std::endl; } // Audio if (!heartbeatSound.loadSound("2.mp3")) { std::cerr << "Error loading heartbeat sound" << std::endl; } heartbeatSound.setLoop(true); // Video if (!loadVideo()) { std::cerr << "Error loading video" << std::endl; } // Intro and outro pics if (!intro.loadImage(ofToDataPath(configuration.IntroFileName))) { std::cerr << "Error loading intro" << std::endl; } serialReader.SetMaxReading(configuration.MaxDistance); serialReader.Enable(); } const int kForward = 1; const int kBack = -1; void ofApp::exit() { serialReader.stopThread(); } bool ofApp::isPlaying() { return videoPlayer.isPlaying() && !videoPlayer.isPaused(); } bool ofApp::loadVideo() { videoPlayer = ofVideoPlayer(); if (!videoPlayer.loadMovie(ofToDataPath(configuration.VideoFileName))) { return false; } videoPlayer.setLoopState(OF_LOOP_NONE); totalNumOfFrames = videoPlayer.getTotalNumFrames(); return true; } void ofApp::update(){ long now = ofGetElapsedTimeMillis(); const int distance = serialReader.Reading(); if (kStateWaiting == state.name) { // If user finds itself *in* the save zone, we start the game. if (distance < configuration.MaxDistance && distance >= configuration.MaxDistance - configuration.SaveZone) { startGame(); } } else if (kStateStarted == state.name) { // Determine if user is now in the death zone if (distance < configuration.MinDistance + configuration.DeathZone) { killGame(); } // If save zone is active and user finds itself in it, // then declare the game saved and finish it. if (state.saveZoneActive && distance > configuration.MaxDistance - configuration.SaveZone) { saveGame("user walked into save zone"); } // If user has moved out of save zone, and game is not finished // yet, activate save zone if (distance < configuration.MaxDistance - configuration.SaveZone) { state.saveZoneActive = true; } } else if (kStateStatsKilled == state.name || kStateStatsSaved == state.name) { if (state.finishedAt < now - (configuration.RestartIntervalSeconds*1000)) { restartGame(); } } else if (kStateKilled == state.name || kStateSaved == state.name) { int destinationFrame = frameForDistance(distance); if (destinationFrame == videoPlayer.getCurrentFrame()) { showStats(); } } else { throw("invalid state"); } updateVideo(distance); updateAudio(distance); } void ofApp::showStats() { long now = ofGetElapsedTimeMillis(); serialReader.Disable(); std::cout << "Showing stats " << now << std::endl; if (kStateKilled == state.name) { state.name = kStateStatsKilled; } else if (kStateSaved == state.name) { state.name = kStateStatsSaved; } else { throw("invalid state"); } state.finishedAt = now; } void ofApp::updateVideo(const int distance) { if (kStateWaiting == state.name || kStateStatsKilled == state.name || kStateStatsSaved == state.name) { if (videoPlayer.isPlaying()) { videoPlayer.stop(); } return; } int currentFrame = videoPlayer.getCurrentFrame(); int destinationFrame = frameForDistance(distance); if (isPlaying()) { if (videoPlayer.getSpeed() == kForward) { if (currentFrame >= destinationFrame) { videoPlayer.setPaused(true); } } else if (videoPlayer.getSpeed() == kBack) { if (currentFrame <= destinationFrame) { videoPlayer.setPaused(true); } } } else { if (currentFrame > destinationFrame) { videoPlayer.setSpeed(kBack); videoPlayer.setPaused(false); } else if (currentFrame < destinationFrame) { videoPlayer.setSpeed(kForward); videoPlayer.setPaused(false); } } videoPlayer.update(); } void ofApp::killGame() { long now = ofGetElapsedTimeMillis(); serialReader.Disable(); std::cout << "Game finished with kill at " << now << std::endl; eventLog << "killed=" << now << std::endl; state.name = kStateKilled; gameStats.AddKill(); } void ofApp::saveGame(const std::string reason) { long now = ofGetElapsedTimeMillis(); std::cout << "Game finished with save at " << now << " because of " << reason << std::endl; eventLog << "saved=" << now << std::endl; state.name = kStateSaved; gameStats.AddSave(); } void ofApp::keyPressed(int key) { ofLogNotice() << "keyPressed key=" << key; const int kMinStep = 50; if (OF_KEY_UP == key) { serialReader.AddReading(ofClamp(serialReader.Reading() - kMinStep, configuration.MinDistance, configuration.MaxDistance)); } else if (OF_KEY_DOWN == key) { serialReader.AddReading(ofClamp(serialReader.Reading() + kMinStep, configuration.MinDistance, configuration.MaxDistance)); } } void ofApp::updateAudio(const int distance) { // Game over, dudes if (kStateStatsSaved == state.name || kStateStatsKilled == state.name) { if (heartbeatSound.getIsPlaying()) { heartbeatSound.stop(); } } else { if (!heartbeatSound.getIsPlaying()) { heartbeatSound.play(); } heartbeatSound.setSpeed(ofMap(videoPlayer.getCurrentFrame(), 0, totalNumOfFrames, configuration.StartingHeartBeatSpeed, configuration.FinishingHeartBeatSpeed)); } ofSoundUpdate(); } void ofApp::restartGame() { std::cout << "Game restarted" << std::endl; state = GameState(); serialReader.Disable(); serialReader.Clear(); serialReader.Enable(); if (!loadVideo()) { std::cerr << "Error loading video after kill" << std::endl; } std::cout << "frame after resettting video player: " << videoPlayer.getCurrentFrame() << std::endl; eventLog << "started=" << ofGetElapsedTimeMillis() << std::endl; } void ofApp::startGame() { long now = ofGetElapsedTimeMillis(); serialReader.Enable(); std::cout << "Game started at " << now << std::endl; state.name = kStateStarted; eventLog << "started=" << ofGetElapsedTimeMillis() << std::endl; } // Frame for current distance // Note that this is not the actual frame that will be animated. // Instead will start to animate towards this frame. int ofApp::frameForDistance(const int distance) const { int d(0); // Override dest. frame on certain conditions, like kill, save, waiting etc if (kStateKilled == state.name || kStateStatsKilled == state.name) { d = configuration.MinDistance; } else if (kStateSaved == state.name || kStateStatsSaved == state.name) { d = configuration.MaxDistance; } else if (kStateWaiting == state.name || kStateStarted == state.name) { d = distance; } else { throw("invalid state!"); } return ofMap(d, configuration.MaxDistance, configuration.MinDistance, 0, totalNumOfFrames); } const int kColorWhite = 0xFFFFFF; const int kColorBlack = 0x000000; void ofApp::draw(){ int restartCountdownSeconds = 0; if (kStateStatsSaved == state.name || kStateStatsKilled == state.name) { long now = ofGetElapsedTimeMillis(); int beenDeadSeconds = (now - state.finishedAt) / 1000; restartCountdownSeconds = configuration.RestartIntervalSeconds - beenDeadSeconds; } // Update HUD ofSetColor(255); const int distance = serialReader.Reading(); int y = 20; hudFont.drawString("distance=" + ofToString(distance), 10, y); hudFont.drawString("frame=" + ofToString(videoPlayer.getCurrentFrame()) + "/" + ofToString(totalNumOfFrames), 200, y); hudFont.drawString("dest.f=" + ofToString(frameForDistance(distance)), 400, y); hudFont.drawString("s/k=" + ofToString(gameStats.TotalSaves()), 600, y); hudFont.drawString("video=" + ofToString(isPlaying() ? "yes" : "no"), 800, y); y = 40; hudFont.drawString("restart=" + ofToString(restartCountdownSeconds), 10, y); hudFont.drawString("save zone=" + ofToString(configuration.SaveZone), 200, y); hudFont.drawString("death zone=" + ofToString(configuration.DeathZone), 400, y); hudFont.drawString("save active=" + ofToString(state.saveZoneActive ? "yes" : "no"), 600, y); hudFont.drawString("max distance=" + ofToString(configuration.MaxDistance), 800, y); const int kMargin = 50; if (kStateStatsSaved == state.name) { ofSetHexColor(kColorWhite); ofRect(0, kMargin, ofGetWindowWidth(), ofGetWindowHeight() - kMargin); ofFill(); ofSetHexColor(kColorBlack); hudFont.drawString("LIFES SAVED: " + ofToString(gameStats.TotalSaves()), ofGetWindowWidth() / 2 - 100, ofGetWindowHeight() / 2); } else if (kStateStatsKilled == state.name) { ofSetHexColor(kColorBlack); ofRect(0, kMargin, ofGetWindowWidth(), ofGetWindowHeight() - kMargin); ofFill(); ofSetHexColor(kColorWhite); hudFont.drawString("TOTAL KILLS: " + ofToString(gameStats.TotalKills()), ofGetWindowWidth() / 2 - 100, ofGetWindowHeight() / 2); } else if (kStateWaiting == state.name) { ofSetHexColor(kColorWhite); ofFill(); intro.draw(0, kMargin, ofGetWindowWidth(), ofGetWindowHeight() - kMargin); } else if (kStateStarted == state.name || kStateKilled == state.name || kStateSaved == state.name) { ofSetHexColor(kColorWhite); ofFill(); videoPlayer.draw(0, kMargin, ofGetWindowWidth(), ofGetWindowHeight() - kMargin); // Draw overlay, for debugging if (configuration.DebugOverlay) { ofSetHexColor(kColorBlack); overlayFont.drawString(ofToString(distance), 100, ofGetWindowHeight() / 2); } } else { throw("invalid state"); } if (configuration.DebugOverlay) { ofSetHexColor(kColorBlack); stateFont.drawString(state.name, 100, ofGetWindowHeight() / 2 + 200); } }<commit_msg>refactor<commit_after>#include "ofApp.h" #include "ofxXmlSettings.h" #include "ofxJSONElement.h" void ofApp::setup(){ ofBackground(54, 54, 54, 255); #ifdef TARGET_OSX ofSetDataPathRoot("../Resources/data/"); #endif // start logging ofLogToFile("app.log"); // start recoding events if (!eventLog.open(ofToDataPath("events.txt"), ofFile::WriteOnly)) { std::cerr << "Error opening events.txt - !!!DATA WILL BE LOST!!!" << std::endl; } if (!configuration.Read()) { std::cerr << "Error reading configuration" << std::endl; } gameStats.Read(); ofSetFrameRate(configuration.FrameRate); ofSetFullscreen(configuration.Fullscreen); //ofSetWindowShape(1000, 200); ofSetWindowPosition(0, 0); // Distance reader serialReader.ActiveSerialPort = configuration.ActiveSerialPort; serialReader.startThread(); // HUD if (!hudFont.loadFont("verdana.ttf", 12, true, true)) { std::cerr << "Error loading HUD font" << std::endl; } hudFont.setLineHeight(18.0f); hudFont.setLetterSpacing(1.037); // Overlay if (!overlayFont.loadFont("verdana.ttf", 300, true, true)) { std::cerr << "Error loading overlay font" << std::endl; } if (!stateFont.loadFont("verdana.ttf", 100, true, true)) { std::cerr << "Error loading status font" << std::endl; } // Audio if (!heartbeatSound.loadSound("2.mp3")) { std::cerr << "Error loading heartbeat sound" << std::endl; } heartbeatSound.setLoop(true); // Video if (!loadVideo()) { std::cerr << "Error loading video" << std::endl; } // Intro and outro pics if (!intro.loadImage(ofToDataPath(configuration.IntroFileName))) { std::cerr << "Error loading intro" << std::endl; } serialReader.SetMaxReading(configuration.MaxDistance); serialReader.Enable(); } const int kForward = 1; const int kBack = -1; void ofApp::exit() { serialReader.stopThread(); } bool ofApp::isPlaying() { return videoPlayer.isPlaying() && !videoPlayer.isPaused(); } bool ofApp::loadVideo() { videoPlayer = ofVideoPlayer(); if (!videoPlayer.loadMovie(ofToDataPath(configuration.VideoFileName))) { return false; } videoPlayer.setLoopState(OF_LOOP_NONE); totalNumOfFrames = videoPlayer.getTotalNumFrames(); return true; } void ofApp::update(){ long now = ofGetElapsedTimeMillis(); const int distance = serialReader.Reading(); if (kStateWaiting == state.name) { // If user finds itself *in* the save zone, we start the game. if (distance < configuration.MaxDistance && distance >= configuration.MaxDistance - configuration.SaveZone) { startGame(); } } else if (kStateStarted == state.name) { if (distance < configuration.MinDistance + configuration.DeathZone) { // Determine if user is now in the death zone killGame(); } else if (state.saveZoneActive && distance > configuration.MaxDistance - configuration.SaveZone) { // If save zone is active and user finds itself in it, // then declare the game saved and finish it. saveGame("user walked into save zone"); } else if (!state.saveZoneActive && distance < configuration.MaxDistance - configuration.SaveZone) { // If user has moved out of save zone, and game is not finished // yet, activate save zone state.saveZoneActive = true; } } else if (kStateStatsKilled == state.name || kStateStatsSaved == state.name) { if (state.finishedAt < now - (configuration.RestartIntervalSeconds*1000)) { restartGame(); } } else if (kStateKilled == state.name || kStateSaved == state.name) { int destinationFrame = frameForDistance(distance); if (destinationFrame == videoPlayer.getCurrentFrame()) { showStats(); } } else { throw("invalid state"); } updateVideo(distance); updateAudio(distance); } void ofApp::showStats() { long now = ofGetElapsedTimeMillis(); serialReader.Disable(); std::cout << "Showing stats " << now << std::endl; if (kStateKilled == state.name) { state.name = kStateStatsKilled; } else if (kStateSaved == state.name) { state.name = kStateStatsSaved; } else { throw("invalid state"); } state.finishedAt = now; } void ofApp::updateVideo(const int distance) { if (kStateWaiting == state.name || kStateStatsKilled == state.name || kStateStatsSaved == state.name) { if (videoPlayer.isPlaying()) { videoPlayer.stop(); } return; } int currentFrame = videoPlayer.getCurrentFrame(); int destinationFrame = frameForDistance(distance); if (isPlaying()) { if (videoPlayer.getSpeed() == kForward) { if (currentFrame >= destinationFrame) { videoPlayer.setPaused(true); } } else if (videoPlayer.getSpeed() == kBack) { if (currentFrame <= destinationFrame) { videoPlayer.setPaused(true); } } } else { if (currentFrame > destinationFrame) { videoPlayer.setSpeed(kBack); videoPlayer.setPaused(false); } else if (currentFrame < destinationFrame) { videoPlayer.setSpeed(kForward); videoPlayer.setPaused(false); } } videoPlayer.update(); } void ofApp::killGame() { long now = ofGetElapsedTimeMillis(); serialReader.Disable(); std::cout << "Game finished with kill at " << now << std::endl; eventLog << "killed=" << now << std::endl; state.name = kStateKilled; gameStats.AddKill(); } void ofApp::saveGame(const std::string reason) { long now = ofGetElapsedTimeMillis(); std::cout << "Game finished with save at " << now << " because of " << reason << std::endl; eventLog << "saved=" << now << std::endl; state.name = kStateSaved; gameStats.AddSave(); } void ofApp::keyPressed(int key) { ofLogNotice() << "keyPressed key=" << key; const int kMinStep = 50; if (OF_KEY_UP == key) { serialReader.AddReading(ofClamp(serialReader.Reading() - kMinStep, configuration.MinDistance, configuration.MaxDistance)); } else if (OF_KEY_DOWN == key) { serialReader.AddReading(ofClamp(serialReader.Reading() + kMinStep, configuration.MinDistance, configuration.MaxDistance)); } } void ofApp::updateAudio(const int distance) { // Game over, dudes if (kStateStatsSaved == state.name || kStateStatsKilled == state.name) { if (heartbeatSound.getIsPlaying()) { heartbeatSound.stop(); } } else { if (!heartbeatSound.getIsPlaying()) { heartbeatSound.play(); } heartbeatSound.setSpeed(ofMap(videoPlayer.getCurrentFrame(), 0, totalNumOfFrames, configuration.StartingHeartBeatSpeed, configuration.FinishingHeartBeatSpeed)); } ofSoundUpdate(); } void ofApp::restartGame() { std::cout << "Game restarted" << std::endl; state = GameState(); serialReader.Disable(); serialReader.Clear(); serialReader.Enable(); if (!loadVideo()) { std::cerr << "Error loading video after kill" << std::endl; } std::cout << "frame after resettting video player: " << videoPlayer.getCurrentFrame() << std::endl; eventLog << "started=" << ofGetElapsedTimeMillis() << std::endl; } void ofApp::startGame() { long now = ofGetElapsedTimeMillis(); serialReader.Enable(); std::cout << "Game started at " << now << std::endl; state.name = kStateStarted; eventLog << "started=" << ofGetElapsedTimeMillis() << std::endl; } // Frame for current distance // Note that this is not the actual frame that will be animated. // Instead will start to animate towards this frame. int ofApp::frameForDistance(const int distance) const { int d(0); // Override dest. frame on certain conditions, like kill, save, waiting etc if (kStateKilled == state.name || kStateStatsKilled == state.name) { d = configuration.MinDistance; } else if (kStateSaved == state.name || kStateStatsSaved == state.name) { d = configuration.MaxDistance; } else if (kStateWaiting == state.name || kStateStarted == state.name) { d = distance; } else { throw("invalid state!"); } return ofMap(d, configuration.MaxDistance, configuration.MinDistance, 0, totalNumOfFrames); } const int kColorWhite = 0xFFFFFF; const int kColorBlack = 0x000000; void ofApp::draw(){ int restartCountdownSeconds = 0; if (kStateStatsSaved == state.name || kStateStatsKilled == state.name) { long now = ofGetElapsedTimeMillis(); int beenDeadSeconds = (now - state.finishedAt) / 1000; restartCountdownSeconds = configuration.RestartIntervalSeconds - beenDeadSeconds; } // Update HUD ofSetColor(255); const int distance = serialReader.Reading(); int y = 20; hudFont.drawString("distance=" + ofToString(distance), 10, y); hudFont.drawString("frame=" + ofToString(videoPlayer.getCurrentFrame()) + "/" + ofToString(totalNumOfFrames), 200, y); hudFont.drawString("dest.f=" + ofToString(frameForDistance(distance)), 400, y); hudFont.drawString("s/k=" + ofToString(gameStats.TotalSaves()), 600, y); hudFont.drawString("video=" + ofToString(isPlaying() ? "yes" : "no"), 800, y); y = 40; hudFont.drawString("restart=" + ofToString(restartCountdownSeconds), 10, y); hudFont.drawString("save zone=" + ofToString(configuration.SaveZone), 200, y); hudFont.drawString("death zone=" + ofToString(configuration.DeathZone), 400, y); hudFont.drawString("save active=" + ofToString(state.saveZoneActive ? "yes" : "no"), 600, y); hudFont.drawString("max distance=" + ofToString(configuration.MaxDistance), 800, y); const int kMargin = 50; if (kStateStatsSaved == state.name) { ofSetHexColor(kColorWhite); ofRect(0, kMargin, ofGetWindowWidth(), ofGetWindowHeight() - kMargin); ofFill(); ofSetHexColor(kColorBlack); hudFont.drawString("LIFES SAVED: " + ofToString(gameStats.TotalSaves()), ofGetWindowWidth() / 2 - 100, ofGetWindowHeight() / 2); } else if (kStateStatsKilled == state.name) { ofSetHexColor(kColorBlack); ofRect(0, kMargin, ofGetWindowWidth(), ofGetWindowHeight() - kMargin); ofFill(); ofSetHexColor(kColorWhite); hudFont.drawString("TOTAL KILLS: " + ofToString(gameStats.TotalKills()), ofGetWindowWidth() / 2 - 100, ofGetWindowHeight() / 2); } else if (kStateWaiting == state.name) { ofSetHexColor(kColorWhite); ofFill(); intro.draw(0, kMargin, ofGetWindowWidth(), ofGetWindowHeight() - kMargin); } else if (kStateStarted == state.name || kStateKilled == state.name || kStateSaved == state.name) { ofSetHexColor(kColorWhite); ofFill(); videoPlayer.draw(0, kMargin, ofGetWindowWidth(), ofGetWindowHeight() - kMargin); // Draw overlay, for debugging if (configuration.DebugOverlay) { ofSetHexColor(kColorBlack); overlayFont.drawString(ofToString(distance), 100, ofGetWindowHeight() / 2); } } else { throw("invalid state"); } if (configuration.DebugOverlay) { ofSetHexColor(kColorBlack); stateFont.drawString(state.name, 100, ofGetWindowHeight() / 2 + 200); } }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AnimationSchemesPanel.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-16 19:17:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "AnimationSchemesPanel.hxx" #include "strings.hrc" #include "sdresid.hxx" #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif namespace sd { class ViewShellBase; extern ::Window * createAnimationSchemesPanel( ::Window* pParent, ViewShellBase& rBase ); namespace toolpanel { namespace controls { AnimationSchemesPanel::AnimationSchemesPanel(TreeNode* pParent, ViewShellBase& rBase) : SubToolPanel (pParent), maPreferredSize( 100, 200 ) { mpWrappedControl = createAnimationSchemesPanel( pParent->GetWindow(), rBase ); mpWrappedControl->Show(); } AnimationSchemesPanel::~AnimationSchemesPanel() { delete mpWrappedControl; } Size AnimationSchemesPanel::GetPreferredSize() { return maPreferredSize; } sal_Int32 AnimationSchemesPanel::GetPreferredWidth(sal_Int32 nHeigh) { return maPreferredSize.Width(); } sal_Int32 AnimationSchemesPanel::GetPreferredHeight(sal_Int32 nWidth) { return maPreferredSize.Height(); } ::Window* AnimationSchemesPanel::GetWindow() { return mpWrappedControl; } bool AnimationSchemesPanel::IsResizable() { return true; } bool AnimationSchemesPanel::IsExpandable() const { return true; } } } } // end of namespace ::sd::toolpanel::controls <commit_msg>INTEGRATION: CWS sdwarningsbegone (1.4.38); FILE MERGED 2006/11/22 12:42:16 cl 1.4.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AnimationSchemesPanel.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2006-12-12 18:45:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "AnimationSchemesPanel.hxx" #include "strings.hrc" #include "sdresid.hxx" #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif namespace sd { class ViewShellBase; extern ::Window * createAnimationSchemesPanel( ::Window* pParent, ViewShellBase& rBase ); namespace toolpanel { namespace controls { AnimationSchemesPanel::AnimationSchemesPanel(TreeNode* pParent, ViewShellBase& rBase) : SubToolPanel (pParent), maPreferredSize( 100, 200 ) { mpWrappedControl = createAnimationSchemesPanel( pParent->GetWindow(), rBase ); mpWrappedControl->Show(); } AnimationSchemesPanel::~AnimationSchemesPanel() { delete mpWrappedControl; } Size AnimationSchemesPanel::GetPreferredSize() { return maPreferredSize; } sal_Int32 AnimationSchemesPanel::GetPreferredWidth(sal_Int32 ) { return maPreferredSize.Width(); } sal_Int32 AnimationSchemesPanel::GetPreferredHeight(sal_Int32 ) { return maPreferredSize.Height(); } ::Window* AnimationSchemesPanel::GetWindow() { return mpWrappedControl; } bool AnimationSchemesPanel::IsResizable() { return true; } bool AnimationSchemesPanel::IsExpandable() const { return true; } } } } // end of namespace ::sd::toolpanel::controls <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Karoliina T. Salminen <[email protected]> ** ** This file is part of duicontrolpanel. ** ** ** This program is free software; you can redistribute it and/or ** modify it 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. ** ****************************************************************************/ #include "dcpappletlauncherservice.h" #include "pagefactory.h" #include "security.h" #include "dcpappletmanager.h" #include "dcpappletlauncherifadaptor.h" #include <QtDebug> #include <MApplication> #include <MApplicationWindow> #include <QDBusError> #include <dcpdebug.h> #include <DuiControlPanelIf> #include <QDBusServiceWatcher> #include <DcpAppletMetadata> /* If the below gets defined, then the applet page in outprocess mode will * be drawn empty first and the applet can finish its animation during the * page-like animation which compositor provides for us. * * Else, controlpanel will wait until the applet creates its widget and only * displays it afterwards. */ #define DELAYED_APPLET_PAGE #ifdef DELAYED_APPLET_PAGE # define PROCESS_EVENTS QCoreApplication::processEvents(); #else # define PROCESS_EVENTS #endif static const char* serviceName = "com.nokia.DcpAppletLauncher"; DcpAppletLauncherService::DcpAppletLauncherService (): MApplicationService (serviceName), m_IsSheetOnly (false), m_IsServiceRegistered (false), m_SkipNextClosing (false) { m_MainIface = new DuiControlPanelIf ("", this); // this makes us die if the main process dies anyhow: #if 0 // TODO this would be nicer, but does not work: connect (iface, SIGNAL (serviceUnavailable(QString)), this, SLOT (close())); #else m_MainUnregistrationWatcher = new QDBusServiceWatcher ("com.nokia.DuiControlPanel", QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForUnregistration, this); connect (m_MainUnregistrationWatcher, SIGNAL (serviceUnregistered(QString)), this, SLOT (close())); #endif // the main process will be able able to close us down if needed even if // the appletlauncher does not provide the service anymore, // through its (main process's) own service: connect (m_MainIface, SIGNAL (closeAppletLaunchers()), this, SLOT (closeWithDelay())); } /* * Pops up the applet's page if the window is already created * and raises it * * Returns false only if there was window but the page popup was unsuccessful */ bool DcpAppletLauncherService::maybeAppletRealStart () { if (m_PageHandle.id == PageHandle::NOPAGE) return true; PageFactory* pageFactory = PageFactory::instance(); // the pagefactory starts the applet out of process and refuses to load it, // in case it is not already loaded, so we load it here: // these ugly processEvent calls makes the page animation look right if the // applet page gets drawn delayed PROCESS_EVENTS // we drop our credentials here and load the applet with the credentials // it specifies only: Security::loadAppletRestricted (m_PageHandle.param); PROCESS_EVENTS bool success = pageFactory->changePage (m_PageHandle); if (success) { // we only unregister the service if the window is shown to prevent // the user click on the appletbutton after that (it would open another // instace) QTimer::singleShot (1000, this, SLOT (unregisterService())); } else { close (); } return success; } bool DcpAppletLauncherService::sheduleApplet (const QString& appletPath, bool isStandalone) { // only care about the first request if (m_PageHandle.id != PageHandle::NOPAGE) return false; m_PageHandle.id = PageHandle::APPLET; m_PageHandle.param = QString(); m_PageHandle.widgetId = -1; m_PageHandle.isStandalone = isStandalone; m_AppletPath = appletPath; // the db is empty, so we add the started applet into it: DcpAppletManager* mng = DcpAppletManager::instance(); if (!mng->loadDesktopFile (m_AppletPath)) { close (); } // we get the name of the applet: DcpAppletMetadataList list = mng->list(); dcp_failfunc_unless (list.count() >= 1, false); DcpAppletMetadata* metadata = list.last(); m_PageHandle.param = metadata->name(); m_IsSheetOnly = metadata->isSheetOnly(); return true; } bool DcpAppletLauncherService::appletPage (const QString& appletPath) { sheduleApplet (appletPath); // we start the mainwindow animation before loading the applet: if (!m_IsSheetOnly) { PageFactory::instance()->raiseMainWindow (); } #ifdef DELAYED_APPLET_PAGE // TODO unfortunately this ruins the animation somehow (why?) QTimer::singleShot (0, this, SLOT (maybeAppletRealStart())); return true; #else return maybeAppletRealStart(); #endif } void DcpAppletLauncherService::closeWithDelay () { if (m_SkipNextClosing) { m_SkipNextClosing = false; return; } QTimer::singleShot (2000, this, SLOT(close())); } bool DcpAppletLauncherService::appletPageAlone (const QString& appletPath) { m_SkipNextClosing = true; bool success = sheduleApplet (appletPath, true); // we start the mainwindow animation before loading the applet: if (!m_IsSheetOnly) { PageFactory::instance()->newWin (); PageFactory::instance()->raiseMainWindow (); } // in this scenario the main process hides its window, and we must // ensure that it will close if our window gets closed PageFactory::instance()->enableCloseMainProcessOnQuit(); if (success) { success = maybeAppletRealStart(); } return success; } bool DcpAppletLauncherService::registerService () { if (m_IsServiceRegistered) return true; // memory owned by QDBusAbstractAdaptor instance and must be on the heap new DcpAppletLauncherIfAdaptor(this); QDBusConnection connection = QDBusConnection::sessionBus(); bool ret = connection.registerService (serviceName); if (ret) { ret = connection.registerObject("/", this); if (!ret) { qWarning ("Error while registering the service object"); } } else { qWarning ("Error while registering the service name"); } if (!ret) { handleServiceRegistrationFailure(); } m_IsServiceRegistered = true; return ret; } bool DcpAppletLauncherService::unregisterService () { if (!m_IsServiceRegistered) return true; QDBusConnection connection = QDBusConnection::sessionBus(); connection.unregisterObject("/"); bool ret = connection.unregisterService (serviceName); if (!ret) { QDBusError error = connection.lastError(); qWarning ("Unregistering the service failed (%s): %s", qPrintable (error.name()), qPrintable (error.message())); } m_IsServiceRegistered = false; return ret; } void DcpAppletLauncherService::prestart () { PageFactory* pf = PageFactory::instance(); dcp_failfunc_unless (pf); pf->preloadAppletPage (); MApplicationWindow* win = pf->window(); dcp_failfunc_unless (win); win->hide(); } void DcpAppletLauncherService::close () { // this ensures that we never close the main process if it was the // one which instructed us to close PageFactory::instance()->enableCloseMainProcessOnQuit (false); MApplication* app = MApplication::instance(); if (app) { app->exit (0); } } <commit_msg>Disables delayed appletPage content<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Karoliina T. Salminen <[email protected]> ** ** This file is part of duicontrolpanel. ** ** ** This program is free software; you can redistribute it and/or ** modify it 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. ** ****************************************************************************/ #include "dcpappletlauncherservice.h" #include "pagefactory.h" #include "security.h" #include "dcpappletmanager.h" #include "dcpappletlauncherifadaptor.h" #include <QtDebug> #include <MApplication> #include <MApplicationWindow> #include <QDBusError> #include <dcpdebug.h> #include <DuiControlPanelIf> #include <QDBusServiceWatcher> #include <DcpAppletMetadata> /* If the below gets defined, then the applet page in outprocess mode will * be drawn empty first and the applet can finish its animation during the * page-like animation which compositor provides for us. * * Else, controlpanel will wait until the applet creates its widget and only * displays it afterwards. */ // #define DELAYED_APPLET_PAGE #ifdef DELAYED_APPLET_PAGE # define PROCESS_EVENTS QCoreApplication::processEvents(); #else # define PROCESS_EVENTS #endif static const char* serviceName = "com.nokia.DcpAppletLauncher"; DcpAppletLauncherService::DcpAppletLauncherService (): MApplicationService (serviceName), m_IsSheetOnly (false), m_IsServiceRegistered (false), m_SkipNextClosing (false) { m_MainIface = new DuiControlPanelIf ("", this); // this makes us die if the main process dies anyhow: #if 0 // TODO this would be nicer, but does not work: connect (iface, SIGNAL (serviceUnavailable(QString)), this, SLOT (close())); #else m_MainUnregistrationWatcher = new QDBusServiceWatcher ("com.nokia.DuiControlPanel", QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForUnregistration, this); connect (m_MainUnregistrationWatcher, SIGNAL (serviceUnregistered(QString)), this, SLOT (close())); #endif // the main process will be able able to close us down if needed even if // the appletlauncher does not provide the service anymore, // through its (main process's) own service: connect (m_MainIface, SIGNAL (closeAppletLaunchers()), this, SLOT (closeWithDelay())); } /* * Pops up the applet's page if the window is already created * and raises it * * Returns false only if there was window but the page popup was unsuccessful */ bool DcpAppletLauncherService::maybeAppletRealStart () { if (m_PageHandle.id == PageHandle::NOPAGE) return true; PageFactory* pageFactory = PageFactory::instance(); // the pagefactory starts the applet out of process and refuses to load it, // in case it is not already loaded, so we load it here: // these ugly processEvent calls makes the page animation look right if the // applet page gets drawn delayed PROCESS_EVENTS // we drop our credentials here and load the applet with the credentials // it specifies only: Security::loadAppletRestricted (m_PageHandle.param); PROCESS_EVENTS bool success = pageFactory->changePage (m_PageHandle); if (success) { // we only unregister the service if the window is shown to prevent // the user click on the appletbutton after that (it would open another // instace) QTimer::singleShot (1000, this, SLOT (unregisterService())); #ifndef DELAYED_APPLET_PAGE pageFactory->raiseMainWindow (); #endif } else { close (); } return success; } bool DcpAppletLauncherService::sheduleApplet (const QString& appletPath, bool isStandalone) { // only care about the first request if (m_PageHandle.id != PageHandle::NOPAGE) return false; m_PageHandle.id = PageHandle::APPLET; m_PageHandle.param = QString(); m_PageHandle.widgetId = -1; m_PageHandle.isStandalone = isStandalone; m_AppletPath = appletPath; // the db is empty, so we add the started applet into it: DcpAppletManager* mng = DcpAppletManager::instance(); if (!mng->loadDesktopFile (m_AppletPath)) { close (); } // we get the name of the applet: DcpAppletMetadataList list = mng->list(); dcp_failfunc_unless (list.count() >= 1, false); DcpAppletMetadata* metadata = list.last(); m_PageHandle.param = metadata->name(); m_IsSheetOnly = metadata->isSheetOnly(); return true; } bool DcpAppletLauncherService::appletPage (const QString& appletPath) { sheduleApplet (appletPath); #ifdef DELAYED_APPLET_PAGE // we start the mainwindow animation before loading the applet: if (!m_IsSheetOnly) { PageFactory::instance()->raiseMainWindow (); } // TODO unfortunately this ruins the animation somehow (why?) QTimer::singleShot (0, this, SLOT (maybeAppletRealStart())); return true; #else return maybeAppletRealStart(); #endif } void DcpAppletLauncherService::closeWithDelay () { if (m_SkipNextClosing) { m_SkipNextClosing = false; return; } QTimer::singleShot (2000, this, SLOT(close())); } bool DcpAppletLauncherService::appletPageAlone (const QString& appletPath) { m_SkipNextClosing = true; bool success = sheduleApplet (appletPath, true); #ifdef DELAYED_APPLET_PAGE // we start the mainwindow animation before loading the applet: if (!m_IsSheetOnly) { PageFactory::instance()->newWin (); PageFactory::instance()->raiseMainWindow (); } #endif // in this scenario the main process hides its window, and we must // ensure that it will close if our window gets closed PageFactory::instance()->enableCloseMainProcessOnQuit(); if (success) { success = maybeAppletRealStart(); } return success; } bool DcpAppletLauncherService::registerService () { if (m_IsServiceRegistered) return true; // memory owned by QDBusAbstractAdaptor instance and must be on the heap new DcpAppletLauncherIfAdaptor(this); QDBusConnection connection = QDBusConnection::sessionBus(); bool ret = connection.registerService (serviceName); if (ret) { ret = connection.registerObject("/", this); if (!ret) { qWarning ("Error while registering the service object"); } } else { qWarning ("Error while registering the service name"); } if (!ret) { handleServiceRegistrationFailure(); } m_IsServiceRegistered = true; return ret; } bool DcpAppletLauncherService::unregisterService () { if (!m_IsServiceRegistered) return true; QDBusConnection connection = QDBusConnection::sessionBus(); connection.unregisterObject("/"); bool ret = connection.unregisterService (serviceName); if (!ret) { QDBusError error = connection.lastError(); qWarning ("Unregistering the service failed (%s): %s", qPrintable (error.name()), qPrintable (error.message())); } m_IsServiceRegistered = false; return ret; } void DcpAppletLauncherService::prestart () { PageFactory* pf = PageFactory::instance(); dcp_failfunc_unless (pf); pf->preloadAppletPage (); MApplicationWindow* win = pf->window(); dcp_failfunc_unless (win); win->hide(); } void DcpAppletLauncherService::close () { // this ensures that we never close the main process if it was the // one which instructed us to close PageFactory::instance()->enableCloseMainProcessOnQuit (false); MApplication* app = MApplication::instance(); if (app) { app->exit (0); } } <|endoftext|>
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__MULTIVARIATE__CONTINUOUS__DIRICHLET_HPP__ #define __STAN__PROB__DISTRIBUTIONS__MULTIVARIATE__CONTINUOUS__DIRICHLET_HPP__ #include <boost/math/special_functions/gamma.hpp> #include <boost/random/gamma_distribution.hpp> #include <boost/random/variate_generator.hpp> #include <stan/prob/constants.hpp> #include <stan/math/matrix_error_handling.hpp> #include <stan/math/error_handling.hpp> #include <stan/prob/traits.hpp> #include <stan/math/functions/multiply_log.hpp> namespace stan { namespace prob { /** * The log of the Dirichlet density for the given theta and * a vector of prior sample sizes, alpha. * Each element of alpha must be greater than 0. * Each element of theta must be greater than or 0. * Theta sums to 1. * * \f{eqnarray*}{ \theta &\sim& \mbox{\sf{Dirichlet}} (\alpha_1, \ldots, \alpha_k) \\ \log (p (\theta \,|\, \alpha_1, \ldots, \alpha_k) ) &=& \log \left( \frac{\Gamma(\alpha_1 + \cdots + \alpha_k)}{\Gamma(\alpha_1) \cdots \Gamma(\alpha_k)} \theta_1^{\alpha_1 - 1} \cdots \theta_k^{\alpha_k - 1} \right) \\ &=& \log (\Gamma(\alpha_1 + \cdots + \alpha_k)) - \log(\Gamma(\alpha_1)) - \cdots - \log(\Gamma(\alpha_k)) + (\alpha_1 - 1) \log (\theta_1) + \cdots + (\alpha_k - 1) \log (\theta_k) \f} * * @param theta A scalar vector. * @param alpha Prior sample sizes. * @return The log of the Dirichlet density. * @throw std::domain_error if any element of alpha is less than * or equal to 0. * @throw std::domain_error if any element of theta is less than 0. * @throw std::domain_error if the sum of theta is not 1. * @tparam T_prob Type of scalar. * @tparam T_prior_sample_size Type of prior sample sizes. */ template <bool propto, typename T_prob, typename T_prior_sample_size> typename boost::math::tools::promote_args<T_prob,T_prior_sample_size>::type dirichlet_log(const Eigen::Matrix<T_prob,Eigen::Dynamic,1>& theta, const Eigen::Matrix<T_prior_sample_size,Eigen::Dynamic,1>& alpha) { // FIXME: parameter check using boost::math::lgamma; using boost::math::tools::promote_args; typename promote_args<T_prob,T_prior_sample_size>::type lp(0.0); using stan::math::multiply_log; if (include_summand<propto,T_prior_sample_size>::value) { lp += lgamma(alpha.sum()); for (int k = 0; k < alpha.rows(); ++k) lp -= lgamma(alpha[k]); } if (include_summand<propto,T_prob,T_prior_sample_size>::value) for (int k = 0; k < theta.rows(); ++k) lp += multiply_log(alpha[k]-1, theta[k]); return lp; } template <typename T_prob, typename T_prior_sample_size> inline typename boost::math::tools::promote_args<T_prob,T_prior_sample_size>::type dirichlet_log(const Eigen::Matrix<T_prob,Eigen::Dynamic,1>& theta, const Eigen::Matrix<T_prior_sample_size,Eigen::Dynamic,1>& alpha) { return dirichlet_log<false>(theta,alpha); } template <class RNG> inline Eigen::VectorXd dirichlet_rng(const Eigen::Matrix<double,Eigen::Dynamic,1>& alpha, RNG& rng) { using boost::variate_generator; using boost::gamma_distribution; double sum = 0; Eigen::VectorXd y(alpha.rows()); for(int i = 0; i < alpha.rows(); i++) { variate_generator<RNG&, gamma_distribution<> > gamma_rng(rng, gamma_distribution<>(alpha(i,0),1)); y(i) = gamma_rng(); sum += y(i); } for(int i = 0; i < alpha.rows(); i++) y(i) /= sum; return y; } } } #endif <commit_msg>dirichlet: checking mismatched sizes<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__MULTIVARIATE__CONTINUOUS__DIRICHLET_HPP__ #define __STAN__PROB__DISTRIBUTIONS__MULTIVARIATE__CONTINUOUS__DIRICHLET_HPP__ #include <boost/math/special_functions/gamma.hpp> #include <boost/random/gamma_distribution.hpp> #include <boost/random/variate_generator.hpp> #include <stan/prob/constants.hpp> #include <stan/math/matrix_error_handling.hpp> #include <stan/math/error_handling.hpp> #include <stan/prob/traits.hpp> #include <stan/math/functions/multiply_log.hpp> namespace stan { namespace prob { /** * The log of the Dirichlet density for the given theta and * a vector of prior sample sizes, alpha. * Each element of alpha must be greater than 0. * Each element of theta must be greater than or 0. * Theta sums to 1. * * \f{eqnarray*}{ \theta &\sim& \mbox{\sf{Dirichlet}} (\alpha_1, \ldots, \alpha_k) \\ \log (p (\theta \,|\, \alpha_1, \ldots, \alpha_k) ) &=& \log \left( \frac{\Gamma(\alpha_1 + \cdots + \alpha_k)}{\Gamma(\alpha_1) \cdots \Gamma(\alpha_k)} \theta_1^{\alpha_1 - 1} \cdots \theta_k^{\alpha_k - 1} \right) \\ &=& \log (\Gamma(\alpha_1 + \cdots + \alpha_k)) - \log(\Gamma(\alpha_1)) - \cdots - \log(\Gamma(\alpha_k)) + (\alpha_1 - 1) \log (\theta_1) + \cdots + (\alpha_k - 1) \log (\theta_k) \f} * * @param theta A scalar vector. * @param alpha Prior sample sizes. * @return The log of the Dirichlet density. * @throw std::domain_error if any element of alpha is less than * or equal to 0. * @throw std::domain_error if any element of theta is less than 0. * @throw std::domain_error if the sum of theta is not 1. * @tparam T_prob Type of scalar. * @tparam T_prior_sample_size Type of prior sample sizes. */ template <bool propto, typename T_prob, typename T_prior_sample_size> typename boost::math::tools::promote_args<T_prob,T_prior_sample_size>::type dirichlet_log(const Eigen::Matrix<T_prob,Eigen::Dynamic,1>& theta, const Eigen::Matrix<T_prior_sample_size,Eigen::Dynamic,1>& alpha) { static const char* function = "stan::prob::dirichlet_log(%1%)"; using boost::math::lgamma; using boost::math::tools::promote_args; using stan::math::check_consistent_sizes; typename promote_args<T_prob,T_prior_sample_size>::type lp(0.0); if (!check_consistent_sizes(function,theta,alpha, "probabilities","prior sample sizes", &lp)) return lp; // FIXME: parameter check using stan::math::multiply_log; if (include_summand<propto,T_prior_sample_size>::value) { lp += lgamma(alpha.sum()); for (int k = 0; k < alpha.rows(); ++k) lp -= lgamma(alpha[k]); } if (include_summand<propto,T_prob,T_prior_sample_size>::value) for (int k = 0; k < theta.rows(); ++k) lp += multiply_log(alpha[k]-1, theta[k]); return lp; } template <typename T_prob, typename T_prior_sample_size> inline typename boost::math::tools::promote_args<T_prob,T_prior_sample_size>::type dirichlet_log(const Eigen::Matrix<T_prob,Eigen::Dynamic,1>& theta, const Eigen::Matrix<T_prior_sample_size,Eigen::Dynamic,1>& alpha) { return dirichlet_log<false>(theta,alpha); } template <class RNG> inline Eigen::VectorXd dirichlet_rng(const Eigen::Matrix<double,Eigen::Dynamic,1>& alpha, RNG& rng) { using boost::variate_generator; using boost::gamma_distribution; double sum = 0; Eigen::VectorXd y(alpha.rows()); for(int i = 0; i < alpha.rows(); i++) { variate_generator<RNG&, gamma_distribution<> > gamma_rng(rng, gamma_distribution<>(alpha(i,0),1)); y(i) = gamma_rng(); sum += y(i); } for(int i = 0; i < alpha.rows(); i++) y(i) /= sum; return y; } } } #endif <|endoftext|>
<commit_before>#include "chrono_parallel/physics/ChSystemParallel.h" #include <omp.h> using namespace chrono; using namespace chrono::collision; ChSystemParallelDEM::ChSystemParallelDEM(unsigned int max_objects) : ChSystemParallel(max_objects) { LCP_solver_speed = new ChLcpSolverParallelDEM(data_manager); ((ChCollisionSystemParallel *) collision_system)->SetCollisionEnvelope(0); //Set this so that the CD can check what type of system it is (needed for narrowphase) data_manager->settings.system_type = SYSTEM_DEM; data_manager->system_timer.AddTimer("ChLcpSolverParallelDEM_ProcessContact"); } void ChSystemParallelDEM::AddMaterialSurfaceData(ChSharedPtr<ChBody> newbody) { assert(typeid(*newbody.get_ptr()) == typeid(ChBodyDEM)); // Reserve space for material properties for the specified body. Not that the // actual data is set in UpdateMaterialProperties(). data_manager->host_data.mu.push_back(0); data_manager->host_data.cohesion_data.push_back(0); data_manager->host_data.mass_data.push_back(0); if (data_manager->settings.solver.use_material_properties) { data_manager->host_data.elastic_moduli.push_back(R2(0, 0)); data_manager->host_data.cr.push_back(0); } else { data_manager->host_data.dem_coeffs.push_back(R4(0, 0, 0, 0)); } } void ChSystemParallelDEM::UpdateMaterialSurfaceData(int index, ChBody* body) { custom_vector<real>& mass = data_manager->host_data.mass_data; custom_vector<real2>& elastic_moduli = data_manager->host_data.elastic_moduli; custom_vector<real>& cohesion = data_manager->host_data.cohesion_data; custom_vector<real>& mu = data_manager->host_data.mu; custom_vector<real>& cr = data_manager->host_data.cr; custom_vector<real4>& dem_coeffs = data_manager->host_data.dem_coeffs; ChSharedPtr<ChMaterialSurfaceDEM>& mat = ((ChBodyDEM*)body)->GetMaterialSurfaceDEM(); mass[index] = body->GetMass(); mu[index] = mat->GetSfriction(); cohesion[index] = mat->GetCohesion(); if (data_manager->settings.solver.use_material_properties) { elastic_moduli[index] = R2(mat->GetYoungModulus(), mat->GetPoissonRatio()); cr[index] = mat->GetRestitution(); } else { dem_coeffs[index] = R4(mat->GetKn(), mat->GetKt(), mat->GetGn(), mat->GetGt()); } } void ChSystemParallelDEM::ChangeCollisionSystem(COLLISIONSYSTEMTYPE type) { ChSystemParallel::ChangeCollisionSystem(type); if (ChCollisionSystemParallel* coll_sys = dynamic_cast<ChCollisionSystemParallel*>(collision_system)) coll_sys->SetCollisionEnvelope(0); } real3 ChSystemParallelDEM::GetBodyContactForce(uint body_id) const { int index = data_manager->host_data.ct_body_map[body_id]; if (index == -1) return R3(0); return data_manager->host_data.ct_body_force[index]; } real3 ChSystemParallelDEM::GetBodyContactTorque(uint body_id) const { int index = data_manager->host_data.ct_body_map[body_id]; if (index == -1) return R3(0); return data_manager->host_data.ct_body_torque[index]; } void ChSystemParallelDEM::PrintStepStats() { double timer_solver_setup = data_manager->system_timer.GetTime("ChLcpSolverParallel_Setup"); double timer_solver_stab = data_manager->system_timer.GetTime("ChLcpSolverParallel_Stab"); std::cout << std::endl; std::cout << "System Information" << std::endl; std::cout << "------------------" << std::endl; std::cout << " Number of bodies " << GetNumBodies() << std::endl; std::cout << " Number of contacts " << GetNcontacts() << std::endl; std::cout << " Number of bilaterals " << GetNumBilaterals() << std::endl; std::cout << std::endl; std::cout << "Timing Information" << std::endl; std::cout << "------------------" << std::endl; std::cout << "Simulation time " << GetTimerStep() << std::endl; std::cout << " Collision detection " << GetTimerCollision() << std::endl; std::cout << " broad phase " << GetTimerCollisionBroad() << std::endl; std::cout << " narrow phase " << GetTimerCollisionNarrow() << std::endl; std::cout << " Update " << GetTimerUpdate() << std::endl; std::cout << " Solver " << GetTimerLcp() << std::endl; std::cout << " contact force calc " << GetTimerProcessContact() << std::endl; std::cout << " setup " << timer_solver_setup << std::endl; std::cout << " stabilization " << timer_solver_stab << std::endl; std::cout << std::endl; } <commit_msg>Cleanup<commit_after>#include "chrono_parallel/physics/ChSystemParallel.h" #include <omp.h> using namespace chrono; using namespace chrono::collision; ChSystemParallelDEM::ChSystemParallelDEM(unsigned int max_objects) : ChSystemParallel(max_objects) { LCP_solver_speed = new ChLcpSolverParallelDEM(data_manager); data_manager->settings.collision.collision_envelope = 0; //Set this so that the CD can check what type of system it is (needed for narrowphase) data_manager->settings.system_type = SYSTEM_DEM; data_manager->system_timer.AddTimer("ChLcpSolverParallelDEM_ProcessContact"); } void ChSystemParallelDEM::AddMaterialSurfaceData(ChSharedPtr<ChBody> newbody) { assert(typeid(*newbody.get_ptr()) == typeid(ChBodyDEM)); // Reserve space for material properties for the specified body. Not that the // actual data is set in UpdateMaterialProperties(). data_manager->host_data.mu.push_back(0); data_manager->host_data.cohesion_data.push_back(0); data_manager->host_data.mass_data.push_back(0); if (data_manager->settings.solver.use_material_properties) { data_manager->host_data.elastic_moduli.push_back(R2(0, 0)); data_manager->host_data.cr.push_back(0); } else { data_manager->host_data.dem_coeffs.push_back(R4(0, 0, 0, 0)); } } void ChSystemParallelDEM::UpdateMaterialSurfaceData(int index, ChBody* body) { custom_vector<real>& mass = data_manager->host_data.mass_data; custom_vector<real2>& elastic_moduli = data_manager->host_data.elastic_moduli; custom_vector<real>& cohesion = data_manager->host_data.cohesion_data; custom_vector<real>& mu = data_manager->host_data.mu; custom_vector<real>& cr = data_manager->host_data.cr; custom_vector<real4>& dem_coeffs = data_manager->host_data.dem_coeffs; ChSharedPtr<ChMaterialSurfaceDEM>& mat = ((ChBodyDEM*)body)->GetMaterialSurfaceDEM(); mass[index] = body->GetMass(); mu[index] = mat->GetSfriction(); cohesion[index] = mat->GetCohesion(); if (data_manager->settings.solver.use_material_properties) { elastic_moduli[index] = R2(mat->GetYoungModulus(), mat->GetPoissonRatio()); cr[index] = mat->GetRestitution(); } else { dem_coeffs[index] = R4(mat->GetKn(), mat->GetKt(), mat->GetGn(), mat->GetGt()); } } void ChSystemParallelDEM::ChangeCollisionSystem(COLLISIONSYSTEMTYPE type) { ChSystemParallel::ChangeCollisionSystem(type); data_manager->settings.collision.collision_envelope = 0; } real3 ChSystemParallelDEM::GetBodyContactForce(uint body_id) const { int index = data_manager->host_data.ct_body_map[body_id]; if (index == -1) return R3(0); return data_manager->host_data.ct_body_force[index]; } real3 ChSystemParallelDEM::GetBodyContactTorque(uint body_id) const { int index = data_manager->host_data.ct_body_map[body_id]; if (index == -1) return R3(0); return data_manager->host_data.ct_body_torque[index]; } void ChSystemParallelDEM::PrintStepStats() { double timer_solver_setup = data_manager->system_timer.GetTime("ChLcpSolverParallel_Setup"); double timer_solver_stab = data_manager->system_timer.GetTime("ChLcpSolverParallel_Stab"); std::cout << std::endl; std::cout << "System Information" << std::endl; std::cout << "------------------" << std::endl; std::cout << " Number of bodies " << GetNumBodies() << std::endl; std::cout << " Number of contacts " << GetNcontacts() << std::endl; std::cout << " Number of bilaterals " << GetNumBilaterals() << std::endl; std::cout << std::endl; std::cout << "Timing Information" << std::endl; std::cout << "------------------" << std::endl; std::cout << "Simulation time " << GetTimerStep() << std::endl; std::cout << " Collision detection " << GetTimerCollision() << std::endl; std::cout << " broad phase " << GetTimerCollisionBroad() << std::endl; std::cout << " narrow phase " << GetTimerCollisionNarrow() << std::endl; std::cout << " Update " << GetTimerUpdate() << std::endl; std::cout << " Solver " << GetTimerLcp() << std::endl; std::cout << " contact force calc " << GetTimerProcessContact() << std::endl; std::cout << " setup " << timer_solver_setup << std::endl; std::cout << " stabilization " << timer_solver_stab << std::endl; std::cout << std::endl; } <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2017 Gleb Mishchenko, The appleseedhq Organization // // 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. // // Interface header. #include "unzipper.h" // appleseed.foundation headers. #include "foundation/core/exceptions/exception.h" #include "foundation/utility/minizip/unzip.h" #include "foundation/utility/string.h" // Boost headers. #include "boost/filesystem.hpp" // Standard headers. #include <fstream> #include <sstream> using namespace std; namespace bf = boost::filesystem; namespace foundation { UnzipException::UnzipException(const char* what) : Exception(what) { } UnzipException::UnzipException(const char* what, const int err) { string string_what = what + to_string(err); set_what(string_what.c_str()); } bool is_zip_entry_directory(const string& dirname) { // used own implementation of is_zip_entry_directory instead of boost implementation // because this directory is not in filesystem, but in zipfile return dirname[dirname.size() - 1] == '/'; } void open_current_file(unzFile& zip_file) { const int err = unzOpenCurrentFile(zip_file); if (err != UNZ_OK) throw UnzipException("Can't open file inside zip: ", err); } int read_chunk(unzFile& zip_file, char* buffer, const int chunk_size) { const int err = unzReadCurrentFile(zip_file, buffer, chunk_size); if (err == UNZ_ERRNO) throw UnzipException("IO error while reading from zip"); if (err < 0) throw UnzipException("zLib error while decompressing file: ", err); return err; } void close_current_file(unzFile& zip_file) { const int err = unzCloseCurrentFile(zip_file); if (err == UNZ_CRCERROR) throw UnzipException("CRC32 is not good"); } string read_filename(unzFile& zip_file) { unz_file_info zip_file_info; unzGetCurrentFileInfo(zip_file, &zip_file_info, 0, 0, 0, 0, 0, 0); vector<char> filename(zip_file_info.size_filename + 1); unzGetCurrentFileInfo( zip_file, &zip_file_info, &filename[0], static_cast<uLong>(filename.size(), 0, 0, 0, 0); filename[filename.size() - 1] = '\0'; const string inzip_filename(&filename[0]); return inzip_filename; } string get_filepath(unzFile& zip_file, const string& unzipped_dir) { string filename = read_filename(zip_file); return (bf::path(unzipped_dir) / bf::path(filename)).string(); } void extract_current_file(unzFile& zip_file, const string& unzipped_dir) { const string filepath = get_filepath(zip_file, unzipped_dir); if (is_zip_entry_directory(filepath)) { bf::create_directories(bf::path(filepath)); return; } else open_current_file(zip_file); fstream out(filepath.c_str(), ios_base::out | ios_base::binary); do { const size_t BUFFER_SIZE = 4096; char buffer[BUFFER_SIZE]; const int read = read_chunk(zip_file, (char*) &buffer, BUFFER_SIZE); out.write((char*) &buffer, read); } while (!unzeof(zip_file)); out.close(); close_current_file(zip_file); } void unzip(const string& zip_filename, const string& unzipped_dir) { try { bf::create_directories(bf::path(unzipped_dir)); unzFile zip_file = unzOpen(zip_filename.c_str()); if (zip_file == 0) throw UnzipException(("Can't open file " + zip_filename).c_str()); unzGoToFirstFile(zip_file); int has_next = UNZ_OK; while (has_next == UNZ_OK) { extract_current_file(zip_file, unzipped_dir); has_next = unzGoToNextFile(zip_file); } unzClose(zip_file); } catch (exception e) { bf::remove_all(bf::path(unzipped_dir)); throw e; } } bool is_zip_file(const char* filename) { unzFile zip_file = unzOpen(filename); if (zip_file == 0) return false; else { unzClose(zip_file); return true; } } vector<string> get_filenames_with_extension_from_zip(const string& zip_filename, const string& extension) { vector<string> filenames; unzFile zip_file = unzOpen(zip_filename.c_str()); if (zip_file == 0) throw UnzipException(("Can't open file " + zip_filename).c_str()); unzGoToFirstFile(zip_file); int has_next = UNZ_OK; while (has_next == UNZ_OK) { const string filename = read_filename(zip_file); if (ends_with(filename, extension)) filenames.push_back(filename); has_next = unzGoToNextFile(zip_file); } unzClose(zip_file); return filenames; } } // namespace foundation <commit_msg>Restore accidentally deleted parentheses<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2017 Gleb Mishchenko, The appleseedhq Organization // // 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. // // Interface header. #include "unzipper.h" // appleseed.foundation headers. #include "foundation/core/exceptions/exception.h" #include "foundation/utility/minizip/unzip.h" #include "foundation/utility/string.h" // Boost headers. #include "boost/filesystem.hpp" // Standard headers. #include <fstream> #include <sstream> using namespace std; namespace bf = boost::filesystem; namespace foundation { UnzipException::UnzipException(const char* what) : Exception(what) { } UnzipException::UnzipException(const char* what, const int err) { string string_what = what + to_string(err); set_what(string_what.c_str()); } bool is_zip_entry_directory(const string& dirname) { // used own implementation of is_zip_entry_directory instead of boost implementation // because this directory is not in filesystem, but in zipfile return dirname[dirname.size() - 1] == '/'; } void open_current_file(unzFile& zip_file) { const int err = unzOpenCurrentFile(zip_file); if (err != UNZ_OK) throw UnzipException("Can't open file inside zip: ", err); } int read_chunk(unzFile& zip_file, char* buffer, const int chunk_size) { const int err = unzReadCurrentFile(zip_file, buffer, chunk_size); if (err == UNZ_ERRNO) throw UnzipException("IO error while reading from zip"); if (err < 0) throw UnzipException("zLib error while decompressing file: ", err); return err; } void close_current_file(unzFile& zip_file) { const int err = unzCloseCurrentFile(zip_file); if (err == UNZ_CRCERROR) throw UnzipException("CRC32 is not good"); } string read_filename(unzFile& zip_file) { unz_file_info zip_file_info; unzGetCurrentFileInfo(zip_file, &zip_file_info, 0, 0, 0, 0, 0, 0); vector<char> filename(zip_file_info.size_filename + 1); unzGetCurrentFileInfo( zip_file, &zip_file_info, &filename[0], static_cast<uLong>(filename.size()), 0, 0, 0, 0); filename[filename.size() - 1] = '\0'; const string inzip_filename(&filename[0]); return inzip_filename; } string get_filepath(unzFile& zip_file, const string& unzipped_dir) { string filename = read_filename(zip_file); return (bf::path(unzipped_dir) / bf::path(filename)).string(); } void extract_current_file(unzFile& zip_file, const string& unzipped_dir) { const string filepath = get_filepath(zip_file, unzipped_dir); if (is_zip_entry_directory(filepath)) { bf::create_directories(bf::path(filepath)); return; } else open_current_file(zip_file); fstream out(filepath.c_str(), ios_base::out | ios_base::binary); do { const size_t BUFFER_SIZE = 4096; char buffer[BUFFER_SIZE]; const int read = read_chunk(zip_file, (char*) &buffer, BUFFER_SIZE); out.write((char*) &buffer, read); } while (!unzeof(zip_file)); out.close(); close_current_file(zip_file); } void unzip(const string& zip_filename, const string& unzipped_dir) { try { bf::create_directories(bf::path(unzipped_dir)); unzFile zip_file = unzOpen(zip_filename.c_str()); if (zip_file == 0) throw UnzipException(("Can't open file " + zip_filename).c_str()); unzGoToFirstFile(zip_file); int has_next = UNZ_OK; while (has_next == UNZ_OK) { extract_current_file(zip_file, unzipped_dir); has_next = unzGoToNextFile(zip_file); } unzClose(zip_file); } catch (exception e) { bf::remove_all(bf::path(unzipped_dir)); throw e; } } bool is_zip_file(const char* filename) { unzFile zip_file = unzOpen(filename); if (zip_file == 0) return false; else { unzClose(zip_file); return true; } } vector<string> get_filenames_with_extension_from_zip(const string& zip_filename, const string& extension) { vector<string> filenames; unzFile zip_file = unzOpen(zip_filename.c_str()); if (zip_file == 0) throw UnzipException(("Can't open file " + zip_filename).c_str()); unzGoToFirstFile(zip_file); int has_next = UNZ_OK; while (has_next == UNZ_OK) { const string filename = read_filename(zip_file); if (ends_with(filename, extension)) filenames.push_back(filename); has_next = unzGoToNextFile(zip_file); } unzClose(zip_file); return filenames; } } // namespace foundation <|endoftext|>
<commit_before>/** Copyright (c) 2013, Philip Deegan. 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 Philip Deegan 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. */ #include "maiken/project.hpp" const kul::yaml::FileValidator maiken::Settings::validator(){ using namespace kul::yaml; return FileValidator({ NodeValidator("inc"), NodeValidator("path"), NodeValidator("local", { NodeValidator("repo", 1), NodeValidator("lib", 1), NodeValidator("bin", 1) }, 0, NodeType::MAP), NodeValidator("remote", { NodeValidator("repo", 1) }, 0, NodeType::MAP), NodeValidator("env", { NodeValidator("name", 1), NodeValidator("mode", 1), NodeValidator("value", 1) }, 0, NodeType::LIST), NodeValidator("file", { NodeValidator("type", 1), NodeValidator("compiler"), NodeValidator("linker"), NodeValidator("archiver"), NodeValidator("args") }, 1, NodeType::LIST) }); } void maiken::Settings::write(const kul::File& f){ kul::io::Writer w(f); w.write("\n", true); w.write("#local:", true); w.write("# Optionnaly override local repository directory", true); w.write("# repo: <directory>", true); w.write("# Add include directories to every compilation", true); w.write("#inc: <directory>", true); w.write("# Add library paths when linking every binary", true); w.write("#path: <directory>\n", true); w.write("# Modify environement variables for application commands - excludes run", true); w.write("#env:", true); w.write("# - name: VAR", true); w.write("# mode: prepend", true); w.write("# value: value", true); w.write("file:", true); #ifdef _WIN32 w.write(" - type: c:cpp", true); w.write(" archiver: lib", true); w.write(" compiler: cl", true); w.write(" linker: link", true); #else bool c = kul::env::WHICH("clang"); w.write(" - type: c", true); w.write(" archiver: ar -cr", true); w << " compiler: " << (c?"clang":"gcc") << kul::os::EOL(); w << " linker: " << (c?"clang":"gcc") << kul::os::EOL(); w.write(" - type: cpp", true); w.write(" archiver: ar -cr", true); w << " compiler: " << (c?"clang":"") << "g++" << kul::os::EOL(); w << " linker: " << (c?"clang":"") << "g++" << kul::os::EOL(); #endif w.write("# Other examples", true); w.write("# - type: cu", true); w.write("# archiver: ar -cr", true); w.write("# compiler: nvcc", true); w.write("# linker: nvcc", true); w.write("# - type: m", true); w.write("# archiver: ar -cr", true); w.write("# compiler: g++ -lobjc", true); w.write("# linker: g++", true); w.write("# - type: cs", true); w.write("# compiler: csc", true); w.write("# linker: csc", true); } std::unique_ptr<maiken::Settings> maiken::Settings::instance; <commit_msg>not so mandatory settings<commit_after>/** Copyright (c) 2013, Philip Deegan. 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 Philip Deegan 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. */ #include "maiken/project.hpp" const kul::yaml::FileValidator maiken::Settings::validator(){ using namespace kul::yaml; return FileValidator({ NodeValidator("inc"), NodeValidator("path"), NodeValidator("local", { NodeValidator("repo"), NodeValidator("lib"), NodeValidator("bin") }, 0, NodeType::MAP), NodeValidator("remote", { NodeValidator("repo") }, 0, NodeType::MAP), NodeValidator("env", { NodeValidator("name", 1), NodeValidator("mode", 1), NodeValidator("value", 1) }, 0, NodeType::LIST), NodeValidator("file", { NodeValidator("type", 1), NodeValidator("compiler", 1), NodeValidator("linker"), NodeValidator("archiver") }, 1, NodeType::LIST) }); } void maiken::Settings::write(const kul::File& f){ kul::io::Writer w(f); w.write("\n", true); w.write("#local:", true); w.write("# Optionnaly override local repository directory", true); w.write("# repo: <directory>", true); w.write("# Add include directories to every compilation", true); w.write("#inc: <directory>", true); w.write("# Add library paths when linking every binary", true); w.write("#path: <directory>\n", true); w.write("# Modify environement variables for application commands - excludes run", true); w.write("#env:", true); w.write("# - name: VAR", true); w.write("# mode: prepend", true); w.write("# value: value", true); w.write("file:", true); #ifdef _WIN32 w.write(" - type: c:cpp", true); w.write(" archiver: lib", true); w.write(" compiler: cl", true); w.write(" linker: link", true); #else bool c = kul::env::WHICH("clang"); w.write(" - type: c", true); w.write(" archiver: ar -cr", true); w << " compiler: " << (c?"clang":"gcc") << kul::os::EOL(); w << " linker: " << (c?"clang":"gcc") << kul::os::EOL(); w.write(" - type: cpp", true); w.write(" archiver: ar -cr", true); w << " compiler: " << (c?"clang":"") << "g++" << kul::os::EOL(); w << " linker: " << (c?"clang":"") << "g++" << kul::os::EOL(); #endif w.write("# Other examples", true); w.write("# - type: cu", true); w.write("# archiver: ar -cr", true); w.write("# compiler: nvcc", true); w.write("# linker: nvcc", true); w.write("# - type: m", true); w.write("# archiver: ar -cr", true); w.write("# compiler: g++ -lobjc", true); w.write("# linker: g++", true); w.write("# - type: cs", true); w.write("# compiler: csc", true); w.write("# linker: csc", true); } std::unique_ptr<maiken::Settings> maiken::Settings::instance; <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2018, Raghavender Sahdev. * 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 Raghavender Sahdev 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. *********************************************************************/ /* Author: Raghavender Sahdev */ #include <moveit/planning_request_adapter/planning_request_adapter.h> #include <moveit/robot_state/conversions.h> #include <moveit/trajectory_processing/trajectory_tools.h> #include <moveit_msgs/RobotTrajectory.h> #include <class_loader/class_loader.hpp> #include <ros/ros.h> #include <chomp_motion_planner/chomp_planner.h> #include <chomp_motion_planner/chomp_parameters.h> #include <moveit/planning_interface/planning_interface.h> #include <moveit/trajectory_processing/iterative_time_parameterization.h> #include <moveit/collision_distance_field/collision_detector_allocator_hybrid.h> #include <moveit/robot_state/conversions.h> #include <vector> #include <eigen3/Eigen/Core> namespace chomp { class OptimizerAdapter : public planning_request_adapter::PlanningRequestAdapter { public: OptimizerAdapter() : planning_request_adapter::PlanningRequestAdapter(), nh_("~") { if (!nh_.getParam("planning_time_limit", params_.planning_time_limit_)) { params_.planning_time_limit_ = 10.0; ROS_INFO_STREAM("Param planning_time_limit was not set. Using default value: " << params_.planning_time_limit_); } if (!nh_.getParam("max_iterations", params_.max_iterations_)) { params_.max_iterations_ = 200; ROS_INFO_STREAM("Param max_iterations was not set. Using default value: " << params_.max_iterations_); } if (!nh_.getParam("max_iterations_after_collision_free", params_.max_iterations_after_collision_free_)) { params_.max_iterations_after_collision_free_ = 5; ROS_INFO_STREAM("Param max_iterations_after_collision_free was not set. Using default value: " << params_.max_iterations_after_collision_free_); } if (!nh_.getParam("smoothness_cost_weight", params_.smoothness_cost_weight_)) { params_.smoothness_cost_weight_ = 0.1; ROS_INFO_STREAM( "Param smoothness_cost_weight was not set. Using default value: " << params_.smoothness_cost_weight_); } if (!nh_.getParam("obstacle_cost_weight", params_.obstacle_cost_weight_)) { params_.obstacle_cost_weight_ = 1.0; ROS_INFO_STREAM("Param obstacle_cost_weight was not set. Using default value: " << params_.obstacle_cost_weight_); } if (!nh_.getParam("learning_rate", params_.learning_rate_)) { params_.learning_rate_ = 0.01; ROS_INFO_STREAM("Param learning_rate was not set. Using default value: " << params_.learning_rate_); } if (!nh_.getParam("smoothness_cost_velocity", params_.smoothness_cost_velocity_)) { params_.smoothness_cost_velocity_ = 0.0; ROS_INFO_STREAM( "Param smoothness_cost_velocity was not set. Using default value: " << params_.smoothness_cost_velocity_); } if (!nh_.getParam("smoothness_cost_acceleration", params_.smoothness_cost_acceleration_)) { params_.smoothness_cost_acceleration_ = 1.0; ROS_INFO_STREAM("Param smoothness_cost_acceleration was not set. Using default value: " << params_.smoothness_cost_acceleration_); } if (!nh_.getParam("smoothness_cost_jerk", params_.smoothness_cost_jerk_)) { params_.smoothness_cost_jerk_ = 0.0; ROS_INFO_STREAM( "Param smoothness_cost_jerk_ was not set. Using default value: " << params_.smoothness_cost_jerk_); } if (!nh_.getParam("ridge_factor", params_.ridge_factor_)) { params_.ridge_factor_ = 0.0; ROS_INFO_STREAM("Param ridge_factor_ was not set. Using default value: " << params_.ridge_factor_); } if (!nh_.getParam("use_pseudo_inverse", params_.use_pseudo_inverse_)) { params_.use_pseudo_inverse_ = 0.0; ROS_INFO_STREAM("Param use_pseudo_inverse_ was not set. Using default value: " << params_.use_pseudo_inverse_); } if (!nh_.getParam("pseudo_inverse_ridge_factor", params_.pseudo_inverse_ridge_factor_)) { params_.pseudo_inverse_ridge_factor_ = 1e-4; ROS_INFO_STREAM("Param pseudo_inverse_ridge_factor was not set. Using default value: " << params_.pseudo_inverse_ridge_factor_); } if (!nh_.getParam("joint_update_limit", params_.joint_update_limit_)) { params_.joint_update_limit_ = 0.1; ROS_INFO_STREAM("Param joint_update_limit was not set. Using default value: " << params_.joint_update_limit_); } if (!nh_.getParam("min_clearence", params_.min_clearence_)) { params_.min_clearence_ = 0.2; ROS_INFO_STREAM("Param min_clearence was not set. Using default value: " << params_.min_clearence_); } if (!nh_.getParam("collision_threshold", params_.collision_threshold_)) { params_.collision_threshold_ = 0.07; ROS_INFO_STREAM("Param collision_threshold_ was not set. Using default value: " << params_.collision_threshold_); } if (!nh_.getParam("use_stochastic_descent", params_.use_stochastic_descent_)) { params_.use_stochastic_descent_ = true; ROS_INFO_STREAM( "Param use_stochastic_descent was not set. Using default value: " << params_.use_stochastic_descent_); } if (!nh_.getParam("trajectory_initialization_method", params_.trajectory_initialization_method_)) { params_.trajectory_initialization_method_ = std::string("fillTrajectory"); ROS_INFO_STREAM("Param trajectory_initialization_method was not set. Using New value as: " << params_.trajectory_initialization_method_); } } std::string getDescription() const override { return "CHOMP Optimizer"; } bool adaptAndPlan(const PlannerFn& planner, const planning_scene::PlanningSceneConstPtr& ps, const planning_interface::MotionPlanRequest& req, planning_interface::MotionPlanResponse& res, std::vector<std::size_t>& added_path_index) const override { // following call to planner() calls the OMPL planner and stores the trajectory inside the MotionPlanResponse res // variable which is then used by CHOMP for optimization of the computed trajectory bool solved = planner(ps, req, res); // create a hybrid collision detector to set the collision checker as hybrid collision_detection::CollisionDetectorAllocatorPtr hybrid_cd( collision_detection::CollisionDetectorAllocatorHybrid::create()); // create a writable planning scene planning_scene::PlanningScenePtr planning_scene = ps->diff(); ROS_INFO_STREAM("Configuring Planning Scene for CHOMP ...."); planning_scene->setActiveCollisionDetector(hybrid_cd, true); chomp::ChompPlanner chompPlanner; planning_interface::MotionPlanDetailedResponse res_detailed; moveit_msgs::MotionPlanDetailedResponse res_detailed_moveit_msgs; // populate the trajectory to pass to CHOMPPlanner::solve() method. Obtain trajectory from OMPL's // planning_interface::MotionPlanResponse object and put / populate it in the // moveit_msgs::MotionPlanDetailedResponse object moveit_msgs::RobotTrajectory trajectory_msgs_from_response; res.trajectory_->getRobotTrajectoryMsg(trajectory_msgs_from_response); res_detailed_moveit_msgs.trajectory.resize(1); res_detailed_moveit_msgs.trajectory[0] = trajectory_msgs_from_response; bool planning_success = chompPlanner.solve(planning_scene, req, params_, res_detailed_moveit_msgs); if (planning_success) { res_detailed.trajectory_.resize(1); res_detailed.trajectory_[0] = robot_trajectory::RobotTrajectoryPtr( new robot_trajectory::RobotTrajectory(res.trajectory_->getRobotModel(), res.trajectory_->getGroup())); moveit::core::RobotState start_state(planning_scene->getRobotModel()); robot_state::robotStateMsgToRobotState(res_detailed_moveit_msgs.trajectory_start, start_state); res_detailed.trajectory_[0]->setRobotTrajectoryMsg(start_state, res_detailed_moveit_msgs.trajectory[0]); res_detailed.description_.push_back("plan"); res_detailed.processing_time_ = res_detailed_moveit_msgs.processing_time; res_detailed.error_code_ = res_detailed_moveit_msgs.error_code; } else res_detailed.error_code_ = res_detailed_moveit_msgs.error_code; res.error_code_ = res_detailed.error_code_; // populate the original response object 'res' with the CHOMP's optimized trajectory. if (planning_success) { res.trajectory_ = res_detailed.trajectory_[0]; res.planning_time_ = res_detailed.processing_time_[0]; } return solved; } private: ros::NodeHandle nh_; chomp::ChompParameters params_; }; } // namespace chomp CLASS_LOADER_REGISTER_CLASS(chomp::OptimizerAdapter, planning_request_adapter::PlanningRequestAdapter); <commit_msg>fix segfault in chomp adapter (#1377)<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2018, Raghavender Sahdev. * 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 Raghavender Sahdev 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. *********************************************************************/ /* Author: Raghavender Sahdev */ #include <moveit/planning_request_adapter/planning_request_adapter.h> #include <moveit/robot_state/conversions.h> #include <moveit/trajectory_processing/trajectory_tools.h> #include <moveit_msgs/RobotTrajectory.h> #include <class_loader/class_loader.hpp> #include <ros/ros.h> #include <chomp_motion_planner/chomp_planner.h> #include <chomp_motion_planner/chomp_parameters.h> #include <moveit/planning_interface/planning_interface.h> #include <moveit/trajectory_processing/iterative_time_parameterization.h> #include <moveit/collision_distance_field/collision_detector_allocator_hybrid.h> #include <moveit/robot_state/conversions.h> #include <vector> #include <eigen3/Eigen/Core> namespace chomp { class OptimizerAdapter : public planning_request_adapter::PlanningRequestAdapter { public: OptimizerAdapter() : planning_request_adapter::PlanningRequestAdapter(), nh_("~") { if (!nh_.getParam("planning_time_limit", params_.planning_time_limit_)) { params_.planning_time_limit_ = 10.0; ROS_INFO_STREAM("Param planning_time_limit was not set. Using default value: " << params_.planning_time_limit_); } if (!nh_.getParam("max_iterations", params_.max_iterations_)) { params_.max_iterations_ = 200; ROS_INFO_STREAM("Param max_iterations was not set. Using default value: " << params_.max_iterations_); } if (!nh_.getParam("max_iterations_after_collision_free", params_.max_iterations_after_collision_free_)) { params_.max_iterations_after_collision_free_ = 5; ROS_INFO_STREAM("Param max_iterations_after_collision_free was not set. Using default value: " << params_.max_iterations_after_collision_free_); } if (!nh_.getParam("smoothness_cost_weight", params_.smoothness_cost_weight_)) { params_.smoothness_cost_weight_ = 0.1; ROS_INFO_STREAM( "Param smoothness_cost_weight was not set. Using default value: " << params_.smoothness_cost_weight_); } if (!nh_.getParam("obstacle_cost_weight", params_.obstacle_cost_weight_)) { params_.obstacle_cost_weight_ = 1.0; ROS_INFO_STREAM("Param obstacle_cost_weight was not set. Using default value: " << params_.obstacle_cost_weight_); } if (!nh_.getParam("learning_rate", params_.learning_rate_)) { params_.learning_rate_ = 0.01; ROS_INFO_STREAM("Param learning_rate was not set. Using default value: " << params_.learning_rate_); } if (!nh_.getParam("smoothness_cost_velocity", params_.smoothness_cost_velocity_)) { params_.smoothness_cost_velocity_ = 0.0; ROS_INFO_STREAM( "Param smoothness_cost_velocity was not set. Using default value: " << params_.smoothness_cost_velocity_); } if (!nh_.getParam("smoothness_cost_acceleration", params_.smoothness_cost_acceleration_)) { params_.smoothness_cost_acceleration_ = 1.0; ROS_INFO_STREAM("Param smoothness_cost_acceleration was not set. Using default value: " << params_.smoothness_cost_acceleration_); } if (!nh_.getParam("smoothness_cost_jerk", params_.smoothness_cost_jerk_)) { params_.smoothness_cost_jerk_ = 0.0; ROS_INFO_STREAM( "Param smoothness_cost_jerk_ was not set. Using default value: " << params_.smoothness_cost_jerk_); } if (!nh_.getParam("ridge_factor", params_.ridge_factor_)) { params_.ridge_factor_ = 0.0; ROS_INFO_STREAM("Param ridge_factor_ was not set. Using default value: " << params_.ridge_factor_); } if (!nh_.getParam("use_pseudo_inverse", params_.use_pseudo_inverse_)) { params_.use_pseudo_inverse_ = 0.0; ROS_INFO_STREAM("Param use_pseudo_inverse_ was not set. Using default value: " << params_.use_pseudo_inverse_); } if (!nh_.getParam("pseudo_inverse_ridge_factor", params_.pseudo_inverse_ridge_factor_)) { params_.pseudo_inverse_ridge_factor_ = 1e-4; ROS_INFO_STREAM("Param pseudo_inverse_ridge_factor was not set. Using default value: " << params_.pseudo_inverse_ridge_factor_); } if (!nh_.getParam("joint_update_limit", params_.joint_update_limit_)) { params_.joint_update_limit_ = 0.1; ROS_INFO_STREAM("Param joint_update_limit was not set. Using default value: " << params_.joint_update_limit_); } if (!nh_.getParam("min_clearence", params_.min_clearence_)) { params_.min_clearence_ = 0.2; ROS_INFO_STREAM("Param min_clearence was not set. Using default value: " << params_.min_clearence_); } if (!nh_.getParam("collision_threshold", params_.collision_threshold_)) { params_.collision_threshold_ = 0.07; ROS_INFO_STREAM("Param collision_threshold_ was not set. Using default value: " << params_.collision_threshold_); } if (!nh_.getParam("use_stochastic_descent", params_.use_stochastic_descent_)) { params_.use_stochastic_descent_ = true; ROS_INFO_STREAM( "Param use_stochastic_descent was not set. Using default value: " << params_.use_stochastic_descent_); } if (!nh_.getParam("trajectory_initialization_method", params_.trajectory_initialization_method_)) { params_.trajectory_initialization_method_ = std::string("fillTrajectory"); ROS_INFO_STREAM("Param trajectory_initialization_method was not set. Using New value as: " << params_.trajectory_initialization_method_); } } std::string getDescription() const override { return "CHOMP Optimizer"; } bool adaptAndPlan(const PlannerFn& planner, const planning_scene::PlanningSceneConstPtr& ps, const planning_interface::MotionPlanRequest& req, planning_interface::MotionPlanResponse& res, std::vector<std::size_t>& added_path_index) const override { // following call to planner() calls the OMPL planner and stores the trajectory inside the MotionPlanResponse res // variable which is then used by CHOMP for optimization of the computed trajectory if (!planner(ps, req, res)) return false; // create a hybrid collision detector to set the collision checker as hybrid collision_detection::CollisionDetectorAllocatorPtr hybrid_cd( collision_detection::CollisionDetectorAllocatorHybrid::create()); // create a writable planning scene planning_scene::PlanningScenePtr planning_scene = ps->diff(); ROS_INFO_STREAM("Configuring Planning Scene for CHOMP ...."); planning_scene->setActiveCollisionDetector(hybrid_cd, true); chomp::ChompPlanner chompPlanner; planning_interface::MotionPlanDetailedResponse res_detailed; moveit_msgs::MotionPlanDetailedResponse res_detailed_moveit_msgs; // populate the trajectory to pass to CHOMPPlanner::solve() method. Obtain trajectory from OMPL's // planning_interface::MotionPlanResponse object and put / populate it in the // moveit_msgs::MotionPlanDetailedResponse object moveit_msgs::RobotTrajectory trajectory_msgs_from_response; res.trajectory_->getRobotTrajectoryMsg(trajectory_msgs_from_response); res_detailed_moveit_msgs.trajectory.resize(1); res_detailed_moveit_msgs.trajectory[0] = trajectory_msgs_from_response; bool planning_success = chompPlanner.solve(planning_scene, req, params_, res_detailed_moveit_msgs); if (planning_success) { res_detailed.trajectory_.resize(1); res_detailed.trajectory_[0] = robot_trajectory::RobotTrajectoryPtr( new robot_trajectory::RobotTrajectory(res.trajectory_->getRobotModel(), res.trajectory_->getGroup())); moveit::core::RobotState start_state(planning_scene->getRobotModel()); robot_state::robotStateMsgToRobotState(res_detailed_moveit_msgs.trajectory_start, start_state); res_detailed.trajectory_[0]->setRobotTrajectoryMsg(start_state, res_detailed_moveit_msgs.trajectory[0]); res_detailed.description_.push_back("plan"); res_detailed.processing_time_ = res_detailed_moveit_msgs.processing_time; res_detailed.error_code_ = res_detailed_moveit_msgs.error_code; } else res_detailed.error_code_ = res_detailed_moveit_msgs.error_code; res.error_code_ = res_detailed.error_code_; // populate the original response object 'res' with the CHOMP's optimized trajectory. if (planning_success) { res.trajectory_ = res_detailed.trajectory_[0]; res.planning_time_ = res_detailed.processing_time_[0]; } return planning_success; } private: ros::NodeHandle nh_; chomp::ChompParameters params_; }; } // namespace chomp CLASS_LOADER_REGISTER_CLASS(chomp::OptimizerAdapter, planning_request_adapter::PlanningRequestAdapter); <|endoftext|>
<commit_before> /* * Copyright 2007 Sandia Corporation. * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive * license for use of this work by or on behalf of the * U.S. Government. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that this Notice and any * statement of authorship are reproduced on all copies. */ #include <vtkIconGlyphFilter.h> #include <vtkActor2D.h> #include <vtkDoubleArray.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkPointSet.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper2D.h> #include <vtkPNGReader.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkTexture.h> #include <vtkImageData.h> #include <vtkTestUtilities.h> #include <vtkRegressionTestImage.h> int TestActor2DTextures( int argc, char *argv[]) { // vtkRegressionTester::Result result = vtkRegressionTester::Passed; // vtkRegressionTester *test = new vtkRegressionTester("IconGlyphFilter"); char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/Tango/TangoIcons.png"); int imageDims[3]; vtkPNGReader * imageReader = vtkPNGReader::New(); imageReader->SetFileName(fname); imageReader->Update(); imageReader->GetOutput()->GetDimensions(imageDims); vtkPolyData * pointSet = vtkPolyData::New(); vtkPoints * points = vtkPoints::New(); vtkDoubleArray * pointData = vtkDoubleArray::New(); pointData->SetNumberOfComponents(3); points->SetData((vtkDataArray *)pointData); pointSet->SetPoints(points); vtkIntArray * iconIndex = vtkIntArray::New(); iconIndex->SetNumberOfComponents(1); pointSet->GetPointData()->SetScalars(iconIndex); for(double i = 1.0; i < 20; i++) { for(double j = 1.0; j < 20; j++) { points->InsertNextPoint(i * 26.0, j * 26.0, 0.0); } } for(int i = 0; i < points->GetNumberOfPoints(); i++) { iconIndex->InsertNextTuple1(i); } int size[] = {24, 24}; vtkIconGlyphFilter * iconFilter = vtkIconGlyphFilter::New(); iconFilter->SetInput(pointSet); iconFilter->SetIconSize(size); iconFilter->SetUseIconSize(true); iconFilter->SetIconSheetSize(imageDims); vtkPolyDataMapper2D * mapper = vtkPolyDataMapper2D::New(); mapper->SetInputConnection(iconFilter->GetOutputPort()); vtkActor2D * iconActor = vtkActor2D::New(); iconActor->SetMapper(mapper); vtkTexture * texture = vtkTexture::New(); texture->SetInputConnection(imageReader->GetOutputPort()); iconActor->SetTexture(texture); vtkRenderer * renderer = vtkRenderer::New(); vtkRenderWindow * renWin = vtkRenderWindow::New(); renWin->SetSize(520, 520); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); renderer->AddActor(iconActor); renWin->Render(); int retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } renderer->Delete(); renWin->Delete(); iren->Delete(); mapper->Delete(); texture->Delete(); imageReader->Delete(); iconIndex->Delete(); iconFilter->Delete(); iconActor->Delete(); pointSet->Delete(); points->Delete(); pointData->Delete(); return !retVal; } <commit_msg>ENH: update test.<commit_after> /* * Copyright 2007 Sandia Corporation. * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive * license for use of this work by or on behalf of the * U.S. Government. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that this Notice and any * statement of authorship are reproduced on all copies. */ #include <vtkIconGlyphFilter.h> #include <vtkActor2D.h> #include <vtkDoubleArray.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkPointSet.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper2D.h> #include <vtkPNGReader.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkTexture.h> #include <vtkImageData.h> #include <vtkTestUtilities.h> #include <vtkRegressionTestImage.h> int TestActor2DTextures( int argc, char *argv[]) { // vtkRegressionTester::Result result = vtkRegressionTester::Passed; // vtkRegressionTester *test = new vtkRegressionTester("IconGlyphFilter"); char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/Tango/TangoIcons.png"); int imageDims[3]; vtkPNGReader * imageReader = vtkPNGReader::New(); imageReader->SetFileName(fname); imageReader->Update(); imageReader->GetOutput()->GetDimensions(imageDims); vtkPolyData * pointSet = vtkPolyData::New(); vtkPoints * points = vtkPoints::New(); vtkDoubleArray * pointData = vtkDoubleArray::New(); pointData->SetNumberOfComponents(3); points->SetData((vtkDataArray *)pointData); pointSet->SetPoints(points); vtkIntArray * iconIndex = vtkIntArray::New(); iconIndex->SetNumberOfComponents(1); pointSet->GetPointData()->SetScalars(iconIndex); for(double i = 1.0; i < 8; i++) { for(double j = 1.0; j < 8; j++) { points->InsertNextPoint(i * 26.0, j * 26.0, 0.0); } } for(int i = 0; i < points->GetNumberOfPoints(); i++) { iconIndex->InsertNextTuple1(i); } int size[] = {24, 24}; vtkIconGlyphFilter * iconFilter = vtkIconGlyphFilter::New(); iconFilter->SetInput(pointSet); iconFilter->SetIconSize(size); iconFilter->SetUseIconSize(true); iconFilter->SetIconSheetSize(imageDims); vtkPolyDataMapper2D * mapper = vtkPolyDataMapper2D::New(); mapper->SetInputConnection(iconFilter->GetOutputPort()); vtkActor2D * iconActor = vtkActor2D::New(); iconActor->SetMapper(mapper); vtkTexture * texture = vtkTexture::New(); texture->SetInputConnection(imageReader->GetOutputPort()); iconActor->SetTexture(texture); vtkRenderer * renderer = vtkRenderer::New(); vtkRenderWindow * renWin = vtkRenderWindow::New(); renWin->SetSize(208, 208); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); renderer->AddActor(iconActor); renWin->Render(); int retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } renderer->Delete(); renWin->Delete(); iren->Delete(); mapper->Delete(); texture->Delete(); imageReader->Delete(); iconIndex->Delete(); iconFilter->Delete(); iconActor->Delete(); pointSet->Delete(); points->Delete(); pointData->Delete(); return !retVal; } <|endoftext|>
<commit_before>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Author: Li Liu // // 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. #include <asm/sigcontext.h> #include <signal.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <cassert> #include <cstdlib> #include <ctime> #include "client/linux/handler/exception_handler.h" #include "common/linux/guid_creator.h" #include "google_breakpad/common/minidump_format.h" namespace google_breakpad { // Signals that we are interested. int SigTable[] = { #if defined(SIGSEGV) SIGSEGV, #endif #ifdef SIGABRT SIGABRT, #endif #ifdef SIGFPE SIGFPE, #endif #ifdef SIGILL SIGILL, #endif #ifdef SIGBUS SIGBUS, #endif }; std::vector<ExceptionHandler*> *ExceptionHandler::handler_stack_ = NULL; int ExceptionHandler::handler_stack_index_ = 0; pthread_mutex_t ExceptionHandler::handler_stack_mutex_ = PTHREAD_MUTEX_INITIALIZER; ExceptionHandler::ExceptionHandler(const string &dump_path, FilterCallback filter, MinidumpCallback callback, void *callback_context, bool install_handler) : filter_(filter), callback_(callback), callback_context_(callback_context), dump_path_(), installed_handler_(install_handler) { set_dump_path(dump_path); if (install_handler) { SetupHandler(); pthread_mutex_lock(&handler_stack_mutex_); if (handler_stack_ == NULL) handler_stack_ = new std::vector<ExceptionHandler *>; handler_stack_->push_back(this); pthread_mutex_unlock(&handler_stack_mutex_); } } ExceptionHandler::~ExceptionHandler() { TeardownAllHandler(); pthread_mutex_lock(&handler_stack_mutex_); if (handler_stack_->back() == this) { handler_stack_->pop_back(); } else { fprintf(stderr, "warning: removing Breakpad handler out of order\n"); for (std::vector<ExceptionHandler *>::iterator iterator = handler_stack_->begin(); iterator != handler_stack_->end(); ++iterator) { if (*iterator == this) { handler_stack_->erase(iterator); } } } if (handler_stack_->empty()) { // When destroying the last ExceptionHandler that installed a handler, // clean up the handler stack. delete handler_stack_; handler_stack_ = NULL; } pthread_mutex_unlock(&handler_stack_mutex_); } bool ExceptionHandler::WriteMinidump() { return InternalWriteMinidump(0, NULL); } // static bool ExceptionHandler::WriteMinidump(const string &dump_path, MinidumpCallback callback, void *callback_context) { ExceptionHandler handler(dump_path, NULL, callback, callback_context, false); return handler.InternalWriteMinidump(0, NULL); } void ExceptionHandler::SetupHandler() { // Signal on a different stack to avoid using the stack // of the crashing thread. struct sigaltstack sig_stack; sig_stack.ss_sp = malloc(MINSIGSTKSZ); if (sig_stack.ss_sp == NULL) return; sig_stack.ss_size = MINSIGSTKSZ; sig_stack.ss_flags = 0; if (sigaltstack(&sig_stack, NULL) < 0) return; for (size_t i = 0; i < sizeof(SigTable) / sizeof(SigTable[0]); ++i) SetupHandler(SigTable[i]); } void ExceptionHandler::SetupHandler(int signo) { struct sigaction act, old_act; act.sa_handler = HandleException; act.sa_flags = SA_ONSTACK; if (sigaction(signo, &act, &old_act) < 0) return; old_handlers_[signo] = old_act.sa_handler; } void ExceptionHandler::TeardownHandler(int signo) { if (old_handlers_.find(signo) != old_handlers_.end()) { struct sigaction act; act.sa_handler = old_handlers_[signo]; act.sa_flags = 0; sigaction(signo, &act, 0); } } void ExceptionHandler::TeardownAllHandler() { for (size_t i = 0; i < sizeof(SigTable) / sizeof(SigTable[0]); ++i) { TeardownHandler(SigTable[i]); } } // static void ExceptionHandler::HandleException(int signo) { // In Linux, the context information about the signal is put on the stack of // the signal handler frame as value parameter. For some reasons, the // prototype of the handler doesn't declare this information as parameter, we // will do it by hand. It is the second parameter above the signal number. const struct sigcontext *sig_ctx = reinterpret_cast<const struct sigcontext *>(&signo + 1); pthread_mutex_lock(&handler_stack_mutex_); ExceptionHandler *current_handler = handler_stack_->at(handler_stack_->size() - ++handler_stack_index_); pthread_mutex_unlock(&handler_stack_mutex_); // Restore original handler. current_handler->TeardownHandler(signo); if (current_handler->InternalWriteMinidump(signo, sig_ctx)) { // Fully handled this exception, safe to exit. exit(EXIT_FAILURE); } else { // Exception not fully handled, will call the next handler in stack to // process it. typedef void (*SignalHandler)(int signo, struct sigcontext); SignalHandler old_handler = reinterpret_cast<SignalHandler>(current_handler->old_handlers_[signo]); if (old_handler != NULL) old_handler(signo, *sig_ctx); } pthread_mutex_lock(&handler_stack_mutex_); current_handler->SetupHandler(signo); --handler_stack_index_; // All the handlers in stack have been invoked to handle the exception, // normally the process should be terminated and should not reach here. // In case we got here, ask the OS to handle it to avoid endless loop, // normally the OS will generate a core and termiate the process. This // may be desired to debug the program. if (handler_stack_index_ == 0) signal(signo, SIG_DFL); pthread_mutex_unlock(&handler_stack_mutex_); } bool ExceptionHandler::InternalWriteMinidump(int signo, const struct sigcontext *sig_ctx) { if (filter_ && !filter_(callback_context_)) return false; GUID guid; bool success = false;; char guid_str[kGUIDStringLength + 1]; if (CreateGUID(&guid) && GUIDToString(&guid, guid_str, sizeof(guid_str))) { char minidump_path[PATH_MAX]; snprintf(minidump_path, sizeof(minidump_path), "%s/%s.dmp", dump_path_c_, guid_str); success = minidump_generator_.WriteMinidumpToFile( minidump_path, signo, sig_ctx); if (callback_) success = callback_(dump_path_c_, guid_str, callback_context_, success); } return success; } } // namespace google_breakpad <commit_msg>Fix issue 136. Block signals before writing minidumps.<commit_after>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Author: Li Liu // // 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. #include <asm/sigcontext.h> #include <signal.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <cassert> #include <cstdlib> #include <ctime> #include "client/linux/handler/exception_handler.h" #include "common/linux/guid_creator.h" #include "google_breakpad/common/minidump_format.h" namespace google_breakpad { // Signals that we are interested. int SigTable[] = { #if defined(SIGSEGV) SIGSEGV, #endif #ifdef SIGABRT SIGABRT, #endif #ifdef SIGFPE SIGFPE, #endif #ifdef SIGILL SIGILL, #endif #ifdef SIGBUS SIGBUS, #endif }; std::vector<ExceptionHandler*> *ExceptionHandler::handler_stack_ = NULL; int ExceptionHandler::handler_stack_index_ = 0; pthread_mutex_t ExceptionHandler::handler_stack_mutex_ = PTHREAD_MUTEX_INITIALIZER; ExceptionHandler::ExceptionHandler(const string &dump_path, FilterCallback filter, MinidumpCallback callback, void *callback_context, bool install_handler) : filter_(filter), callback_(callback), callback_context_(callback_context), dump_path_(), installed_handler_(install_handler) { set_dump_path(dump_path); if (install_handler) { SetupHandler(); pthread_mutex_lock(&handler_stack_mutex_); if (handler_stack_ == NULL) handler_stack_ = new std::vector<ExceptionHandler *>; handler_stack_->push_back(this); pthread_mutex_unlock(&handler_stack_mutex_); } } ExceptionHandler::~ExceptionHandler() { TeardownAllHandler(); pthread_mutex_lock(&handler_stack_mutex_); if (handler_stack_->back() == this) { handler_stack_->pop_back(); } else { fprintf(stderr, "warning: removing Breakpad handler out of order\n"); for (std::vector<ExceptionHandler *>::iterator iterator = handler_stack_->begin(); iterator != handler_stack_->end(); ++iterator) { if (*iterator == this) { handler_stack_->erase(iterator); } } } if (handler_stack_->empty()) { // When destroying the last ExceptionHandler that installed a handler, // clean up the handler stack. delete handler_stack_; handler_stack_ = NULL; } pthread_mutex_unlock(&handler_stack_mutex_); } bool ExceptionHandler::WriteMinidump() { return InternalWriteMinidump(0, NULL); } // static bool ExceptionHandler::WriteMinidump(const string &dump_path, MinidumpCallback callback, void *callback_context) { ExceptionHandler handler(dump_path, NULL, callback, callback_context, false); return handler.InternalWriteMinidump(0, NULL); } void ExceptionHandler::SetupHandler() { // Signal on a different stack to avoid using the stack // of the crashing thread. struct sigaltstack sig_stack; sig_stack.ss_sp = malloc(MINSIGSTKSZ); if (sig_stack.ss_sp == NULL) return; sig_stack.ss_size = MINSIGSTKSZ; sig_stack.ss_flags = 0; if (sigaltstack(&sig_stack, NULL) < 0) return; for (size_t i = 0; i < sizeof(SigTable) / sizeof(SigTable[0]); ++i) SetupHandler(SigTable[i]); } void ExceptionHandler::SetupHandler(int signo) { struct sigaction act, old_act; act.sa_handler = HandleException; act.sa_flags = SA_ONSTACK; if (sigaction(signo, &act, &old_act) < 0) return; old_handlers_[signo] = old_act.sa_handler; } void ExceptionHandler::TeardownHandler(int signo) { if (old_handlers_.find(signo) != old_handlers_.end()) { struct sigaction act; act.sa_handler = old_handlers_[signo]; act.sa_flags = 0; sigaction(signo, &act, 0); } } void ExceptionHandler::TeardownAllHandler() { for (size_t i = 0; i < sizeof(SigTable) / sizeof(SigTable[0]); ++i) { TeardownHandler(SigTable[i]); } } // static void ExceptionHandler::HandleException(int signo) { // In Linux, the context information about the signal is put on the stack of // the signal handler frame as value parameter. For some reasons, the // prototype of the handler doesn't declare this information as parameter, we // will do it by hand. It is the second parameter above the signal number. const struct sigcontext *sig_ctx = reinterpret_cast<const struct sigcontext *>(&signo + 1); pthread_mutex_lock(&handler_stack_mutex_); ExceptionHandler *current_handler = handler_stack_->at(handler_stack_->size() - ++handler_stack_index_); pthread_mutex_unlock(&handler_stack_mutex_); // Restore original handler. current_handler->TeardownHandler(signo); if (current_handler->InternalWriteMinidump(signo, sig_ctx)) { // Fully handled this exception, safe to exit. exit(EXIT_FAILURE); } else { // Exception not fully handled, will call the next handler in stack to // process it. typedef void (*SignalHandler)(int signo, struct sigcontext); SignalHandler old_handler = reinterpret_cast<SignalHandler>(current_handler->old_handlers_[signo]); if (old_handler != NULL) old_handler(signo, *sig_ctx); } pthread_mutex_lock(&handler_stack_mutex_); current_handler->SetupHandler(signo); --handler_stack_index_; // All the handlers in stack have been invoked to handle the exception, // normally the process should be terminated and should not reach here. // In case we got here, ask the OS to handle it to avoid endless loop, // normally the OS will generate a core and termiate the process. This // may be desired to debug the program. if (handler_stack_index_ == 0) signal(signo, SIG_DFL); pthread_mutex_unlock(&handler_stack_mutex_); } bool ExceptionHandler::InternalWriteMinidump(int signo, const struct sigcontext *sig_ctx) { if (filter_ && !filter_(callback_context_)) return false; GUID guid; bool success = false;; char guid_str[kGUIDStringLength + 1]; if (CreateGUID(&guid) && GUIDToString(&guid, guid_str, sizeof(guid_str))) { char minidump_path[PATH_MAX]; snprintf(minidump_path, sizeof(minidump_path), "%s/%s.dmp", dump_path_c_, guid_str); // Block all the signals we want to process when writting minidump. // We don't want it to be interrupted. sigset_t sig_blocked, sig_old; bool blocked = true; sigfillset(&sig_blocked); for (size_t i = 0; i < sizeof(SigTable) / sizeof(SigTable[0]); ++i) sigdelset(&sig_blocked, SigTable[i]); if (sigprocmask(SIG_BLOCK, &sig_blocked, &sig_old) != 0) { blocked = false; fprintf(stderr, "google_breakpad::ExceptionHandler::HandleException: " "failed to block signals.\n"); } success = minidump_generator_.WriteMinidumpToFile( minidump_path, signo, sig_ctx); // Unblock the signals. if (blocked) { sigprocmask(SIG_SETMASK, &sig_old, &sig_old); } if (callback_) success = callback_(dump_path_c_, guid_str, callback_context_, success); } return success; } } // namespace google_breakpad <|endoftext|>
<commit_before>#include "extensions/filters/http/well_known_names.h" #include "test/integration/http_protocol_integration.h" namespace Envoy { namespace { const std::string RBAC_CONFIG = R"EOF( name: envoy.filters.http.rbac config: rules: policies: foo: permissions: - header: { name: ":method", exact_match: "GET" } principals: - any: true )EOF"; typedef HttpProtocolIntegrationTest RBACIntegrationTest; INSTANTIATE_TEST_CASE_P(Protocols, RBACIntegrationTest, testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams()), HttpProtocolIntegrationTest::protocolTestParamsToString); TEST_P(RBACIntegrationTest, Allowed) { config_helper_.addFilter(RBAC_CONFIG); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto response = codec_client_->makeRequestWithBody( Http::TestHeaderMapImpl{ {":method", "GET"}, {":path", "/"}, {":scheme", "http"}, {":authority", "host"}, {"x-forwarded-for", "10.0.0.1"}, }, 1024); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "200"}}, true); response->waitForEndStream(); ASSERT_TRUE(response->complete()); EXPECT_STREQ("200", response->headers().Status()->value().c_str()); } TEST_P(RBACIntegrationTest, Denied) { config_helper_.addFilter(RBAC_CONFIG); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto response = codec_client_->makeRequestWithBody( Http::TestHeaderMapImpl{ {":method", "POST"}, {":path", "/"}, {":scheme", "http"}, {":authority", "host"}, {"x-forwarded-for", "10.0.0.1"}, }, 1024); response->waitForEndStream(); ASSERT_TRUE(response->complete()); EXPECT_STREQ("403", response->headers().Status()->value().c_str()); } TEST_P(RBACIntegrationTest, RouteOverride) { config_helper_.addConfigModifier( [](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& cfg) { ProtobufWkt::Struct pfc; Protobuf::util::JsonStringToMessage(R"EOF({"disabled": true})EOF", &pfc); auto* config = cfg.mutable_route_config() ->mutable_virtual_hosts() ->Mutable(0) ->mutable_per_filter_config(); (*config)[Extensions::HttpFilters::HttpFilterNames::get().RBAC] = pfc; }); config_helper_.addFilter(RBAC_CONFIG); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto response = codec_client_->makeRequestWithBody( Http::TestHeaderMapImpl{ {":method", "POST"}, {":path", "/"}, {":scheme", "http"}, {":authority", "host"}, {"x-forwarded-for", "10.0.0.1"}, }, 1024); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "200"}}, true); response->waitForEndStream(); ASSERT_TRUE(response->complete()); EXPECT_STREQ("200", response->headers().Status()->value().c_str()); } } // namespace } // namespace Envoy <commit_msg>RBAC filter test: Check return value. (#3497)<commit_after>#include "extensions/filters/http/well_known_names.h" #include "test/integration/http_protocol_integration.h" namespace Envoy { namespace { const std::string RBAC_CONFIG = R"EOF( name: envoy.filters.http.rbac config: rules: policies: foo: permissions: - header: { name: ":method", exact_match: "GET" } principals: - any: true )EOF"; typedef HttpProtocolIntegrationTest RBACIntegrationTest; INSTANTIATE_TEST_CASE_P(Protocols, RBACIntegrationTest, testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams()), HttpProtocolIntegrationTest::protocolTestParamsToString); TEST_P(RBACIntegrationTest, Allowed) { config_helper_.addFilter(RBAC_CONFIG); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto response = codec_client_->makeRequestWithBody( Http::TestHeaderMapImpl{ {":method", "GET"}, {":path", "/"}, {":scheme", "http"}, {":authority", "host"}, {"x-forwarded-for", "10.0.0.1"}, }, 1024); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "200"}}, true); response->waitForEndStream(); ASSERT_TRUE(response->complete()); EXPECT_STREQ("200", response->headers().Status()->value().c_str()); } TEST_P(RBACIntegrationTest, Denied) { config_helper_.addFilter(RBAC_CONFIG); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto response = codec_client_->makeRequestWithBody( Http::TestHeaderMapImpl{ {":method", "POST"}, {":path", "/"}, {":scheme", "http"}, {":authority", "host"}, {"x-forwarded-for", "10.0.0.1"}, }, 1024); response->waitForEndStream(); ASSERT_TRUE(response->complete()); EXPECT_STREQ("403", response->headers().Status()->value().c_str()); } TEST_P(RBACIntegrationTest, RouteOverride) { config_helper_.addConfigModifier( [](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& cfg) { ProtobufWkt::Struct pfc; ASSERT_TRUE(Protobuf::util::JsonStringToMessage(R"EOF({"disabled": true})EOF", &pfc).ok()); auto* config = cfg.mutable_route_config() ->mutable_virtual_hosts() ->Mutable(0) ->mutable_per_filter_config(); (*config)[Extensions::HttpFilters::HttpFilterNames::get().RBAC] = pfc; }); config_helper_.addFilter(RBAC_CONFIG); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto response = codec_client_->makeRequestWithBody( Http::TestHeaderMapImpl{ {":method", "POST"}, {":path", "/"}, {":scheme", "http"}, {":authority", "host"}, {"x-forwarded-for", "10.0.0.1"}, }, 1024); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "200"}}, true); response->waitForEndStream(); ASSERT_TRUE(response->complete()); EXPECT_STREQ("200", response->headers().Status()->value().c_str()); } } // namespace } // namespace Envoy <|endoftext|>