text
stringlengths
54
60.6k
<commit_before>#pragma once // C++ wrapper around a statically sized array // // Based on: // https://github.com/stephentu/silo/blob/master/static_vector.h #include <algorithm> #include <type_traits> #include <microscopes/common/macros.hpp> template <typename T, size_t MaxSize> class static_vector { static const bool is_trivially_destructible = std::is_trivially_destructible<T>::value; static const bool is_trivially_copyable = std::is_trivially_copyable<T>::value; public: typedef T value_type; typedef T & reference; typedef const T & const_reference; typedef size_t size_type; inline static_vector() : n(0) {} inline ~static_vector() { clear(); } inline static_vector(const static_vector &that) : n(0) { assignFrom(that); } // not efficient, don't use in performance critical parts static_vector(std::initializer_list<T> l) : n(0) { for (auto &p : l) push_back(p); } static_vector & operator=(const static_vector &that) { assignFrom(that); return *this; } inline size_t size() const { return n; } inline bool empty() const { return !n; } inline reference front() { MICROSCOPES_ASSERT(n > 0); MICROSCOPES_ASSERT(n <= MaxSize); return *ptr(); } inline const_reference front() const { return const_cast<static_vector *>(this)->front(); } inline reference back() { MICROSCOPES_ASSERT(n > 0); MICROSCOPES_ASSERT(n <= MaxSize); return ptr()[n - 1]; } inline const_reference back() const { return const_cast<static_vector *>(this)->back(); } inline void pop_back() { MICROSCOPES_ASSERT(n > 0); if (!is_trivially_destructible) ptr()[n - 1].~T(); n--; } inline void push_back(const T &obj) { emplace_back(obj); } inline void push_back(T &&obj) { emplace_back(std::move(obj)); } // C++11 goodness- a strange syntax this is template <class... Args> inline void emplace_back(Args &&... args) { MICROSCOPES_ASSERT(n < MaxSize); new (&(ptr()[n++])) T(std::forward<Args>(args)...); } inline reference operator[](int i) { return ptr()[i]; } inline const_reference operator[](int i) const { return const_cast<static_vector *>(this)->operator[](i); } void clear() { if (!is_trivially_destructible) for (size_t i = 0; i < n; i++) ptr()[i].~T(); n = 0; } inline void reserve(size_t n) { } inline void resize(size_t n, value_type val = value_type()) { MICROSCOPES_ASSERT(n <= MaxSize); if (n > this->n) { // expand while (this->n < n) new (&ptr()[this->n++]) T(val); } else if (n < this->n) { // shrink while (this->n > n) { if (!is_trivially_destructible) ptr()[this->n - 1].~T(); this->n--; } } } // non-standard API template <typename Compare = std::less<T>> inline void sort(Compare c = Compare()) { std::sort(begin(), end(), c); } private: template <typename ObjType> class iterator_ : public std::iterator<std::bidirectional_iterator_tag, ObjType> { friend class static_vector; public: inline iterator_() : p(0) {} template <typename O> inline iterator_(const iterator_<O> &other) : p(other.p) {} inline ObjType & operator*() const { return *p; } inline ObjType * operator->() const { return p; } inline bool operator==(const iterator_ &o) const { return p == o.p; } inline bool operator!=(const iterator_ &o) const { return !operator==(o); } inline bool operator<(const iterator_ &o) const { return p < o.p; } inline bool operator>=(const iterator_ &o) const { return !operator<(o); } inline bool operator>(const iterator_ &o) const { return p > o.p; } inline bool operator<=(const iterator_ &o) const { return !operator>(o); } inline iterator_ & operator+=(int n) { p += n; return *this; } inline iterator_ & operator-=(int n) { p -= n; return *this; } inline iterator_ operator+(int n) const { iterator_ cpy = *this; return cpy += n; } inline iterator_ operator-(int n) const { iterator_ cpy = *this; return cpy -= n; } inline intptr_t operator-(const iterator_ &o) const { return p - o.p; } inline iterator_ & operator++() { ++p; return *this; } inline iterator_ operator++(int) { iterator_ cur = *this; ++(*this); return cur; } inline iterator_ & operator--() { --p; return *this; } inline iterator_ operator--(int) { iterator_ cur = *this; --(*this); return cur; } protected: inline iterator_(ObjType *p) : p(p) {} private: ObjType *p; }; public: typedef iterator_<T> iterator; typedef iterator_<const T> const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; inline iterator begin() { return iterator(ptr()); } inline const_iterator begin() const { return const_iterator(ptr()); } inline iterator end() { return iterator(endptr()); } inline const_iterator end() const { return const_iterator(endptr()); } inline reverse_iterator rbegin() { return reverse_iterator(end()); } inline const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } inline reverse_iterator rend() { return reverse_iterator(begin()); } inline const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } private: void assignFrom(const static_vector &that) { if (unlikely(this == &that)) return; clear(); MICROSCOPES_ASSERT(that.n <= MaxSize); if (is_trivially_copyable) { MICROSCOPES_MEMCPY(ptr(), that.ptr(), that.n * sizeof(T)); } else { for (size_t i = 0; i < that.n; i++) new (&(ptr()[i])) T(that.ptr()[i]); } n = that.n; } inline ALWAYS_INLINE T * ptr() { return reinterpret_cast<T *>(&elems_buf[0]); } inline ALWAYS_INLINE const T * ptr() const { return reinterpret_cast<const T *>(&elems_buf[0]); } inline ALWAYS_INLINE T * endptr() { return ptr() + n; } inline ALWAYS_INLINE const T * endptr() const { return ptr() + n; } size_t n; char elems_buf[sizeof(T) * MaxSize]; }; <commit_msg>missing import<commit_after>#pragma once // C++ wrapper around a statically sized array // // Based on: // https://github.com/stephentu/silo/blob/master/static_vector.h #include <algorithm> #include <type_traits> #include <microscopes/common/macros.hpp> #include <microscopes/common/assert.hpp> template <typename T, size_t MaxSize> class static_vector { static const bool is_trivially_destructible = std::is_trivially_destructible<T>::value; static const bool is_trivially_copyable = std::is_trivially_copyable<T>::value; public: typedef T value_type; typedef T & reference; typedef const T & const_reference; typedef size_t size_type; inline static_vector() : n(0) {} inline ~static_vector() { clear(); } inline static_vector(const static_vector &that) : n(0) { assignFrom(that); } // not efficient, don't use in performance critical parts static_vector(std::initializer_list<T> l) : n(0) { for (auto &p : l) push_back(p); } static_vector & operator=(const static_vector &that) { assignFrom(that); return *this; } inline size_t size() const { return n; } inline bool empty() const { return !n; } inline reference front() { MICROSCOPES_ASSERT(n > 0); MICROSCOPES_ASSERT(n <= MaxSize); return *ptr(); } inline const_reference front() const { return const_cast<static_vector *>(this)->front(); } inline reference back() { MICROSCOPES_ASSERT(n > 0); MICROSCOPES_ASSERT(n <= MaxSize); return ptr()[n - 1]; } inline const_reference back() const { return const_cast<static_vector *>(this)->back(); } inline void pop_back() { MICROSCOPES_ASSERT(n > 0); if (!is_trivially_destructible) ptr()[n - 1].~T(); n--; } inline void push_back(const T &obj) { emplace_back(obj); } inline void push_back(T &&obj) { emplace_back(std::move(obj)); } // C++11 goodness- a strange syntax this is template <class... Args> inline void emplace_back(Args &&... args) { MICROSCOPES_ASSERT(n < MaxSize); new (&(ptr()[n++])) T(std::forward<Args>(args)...); } inline reference operator[](int i) { return ptr()[i]; } inline const_reference operator[](int i) const { return const_cast<static_vector *>(this)->operator[](i); } void clear() { if (!is_trivially_destructible) for (size_t i = 0; i < n; i++) ptr()[i].~T(); n = 0; } inline void reserve(size_t n) { } inline void resize(size_t n, value_type val = value_type()) { MICROSCOPES_ASSERT(n <= MaxSize); if (n > this->n) { // expand while (this->n < n) new (&ptr()[this->n++]) T(val); } else if (n < this->n) { // shrink while (this->n > n) { if (!is_trivially_destructible) ptr()[this->n - 1].~T(); this->n--; } } } // non-standard API template <typename Compare = std::less<T>> inline void sort(Compare c = Compare()) { std::sort(begin(), end(), c); } private: template <typename ObjType> class iterator_ : public std::iterator<std::bidirectional_iterator_tag, ObjType> { friend class static_vector; public: inline iterator_() : p(0) {} template <typename O> inline iterator_(const iterator_<O> &other) : p(other.p) {} inline ObjType & operator*() const { return *p; } inline ObjType * operator->() const { return p; } inline bool operator==(const iterator_ &o) const { return p == o.p; } inline bool operator!=(const iterator_ &o) const { return !operator==(o); } inline bool operator<(const iterator_ &o) const { return p < o.p; } inline bool operator>=(const iterator_ &o) const { return !operator<(o); } inline bool operator>(const iterator_ &o) const { return p > o.p; } inline bool operator<=(const iterator_ &o) const { return !operator>(o); } inline iterator_ & operator+=(int n) { p += n; return *this; } inline iterator_ & operator-=(int n) { p -= n; return *this; } inline iterator_ operator+(int n) const { iterator_ cpy = *this; return cpy += n; } inline iterator_ operator-(int n) const { iterator_ cpy = *this; return cpy -= n; } inline intptr_t operator-(const iterator_ &o) const { return p - o.p; } inline iterator_ & operator++() { ++p; return *this; } inline iterator_ operator++(int) { iterator_ cur = *this; ++(*this); return cur; } inline iterator_ & operator--() { --p; return *this; } inline iterator_ operator--(int) { iterator_ cur = *this; --(*this); return cur; } protected: inline iterator_(ObjType *p) : p(p) {} private: ObjType *p; }; public: typedef iterator_<T> iterator; typedef iterator_<const T> const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; inline iterator begin() { return iterator(ptr()); } inline const_iterator begin() const { return const_iterator(ptr()); } inline iterator end() { return iterator(endptr()); } inline const_iterator end() const { return const_iterator(endptr()); } inline reverse_iterator rbegin() { return reverse_iterator(end()); } inline const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } inline reverse_iterator rend() { return reverse_iterator(begin()); } inline const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } private: void assignFrom(const static_vector &that) { if (unlikely(this == &that)) return; clear(); MICROSCOPES_ASSERT(that.n <= MaxSize); if (is_trivially_copyable) { MICROSCOPES_MEMCPY(ptr(), that.ptr(), that.n * sizeof(T)); } else { for (size_t i = 0; i < that.n; i++) new (&(ptr()[i])) T(that.ptr()[i]); } n = that.n; } inline ALWAYS_INLINE T * ptr() { return reinterpret_cast<T *>(&elems_buf[0]); } inline ALWAYS_INLINE const T * ptr() const { return reinterpret_cast<const T *>(&elems_buf[0]); } inline ALWAYS_INLINE T * endptr() { return ptr() + n; } inline ALWAYS_INLINE const T * endptr() const { return ptr() + n; } size_t n; char elems_buf[sizeof(T) * MaxSize]; }; <|endoftext|>
<commit_before>#pragma once #include "../../base/logging.hpp" #include "../../defines.hpp" #include "../../indexer/classificator.hpp" #include "../../indexer/feature.hpp" #include "../../indexer/feature_merger.hpp" #include "../../indexer/feature_visibility.hpp" #include "../../indexer/point_to_int64.hpp" #include "../../std/map.hpp" #include "../../std/list.hpp" #include "../../std/vector.hpp" #include "../../std/functional.hpp" #include "../../std/iostream.hpp" #include <boost/scoped_ptr.hpp> #include <boost/unordered_map.hpp> namespace m2 { inline size_t hash_value(m2::PointD const & pt) { return static_cast<size_t>(PointToInt64(pt.x, pt.y)); } } template <class FeatureOutT> class WorldMapGenerator { /// if NULL, separate world data file is not generated boost::scoped_ptr<FeatureOutT> m_worldBucket; /// features visible before or at this scale level will go to World map int m_maxWorldScale; bool m_mergeCoastlines; size_t m_mergedCounter; size_t m_areasCounter; typedef boost::unordered_map<m2::PointD, FeatureBuilder1Merger> FeaturesContainerT; typedef map<vector<uint32_t>, FeaturesContainerT> TypesContainerT; TypesContainerT m_features; private: /// scans all features and tries to merge them with each other /// @return true if one feature was merged bool ReMergeFeatures(FeaturesContainerT & features) { for (FeaturesContainerT::iterator base = features.begin(); base != features.end(); ++base) { FeaturesContainerT::iterator found = features.find(base->second.LastPoint()); if (found != features.end()) { CHECK(found != base, ()); base->second.AppendFeature(found->second); features.erase(found); ++m_mergedCounter; if (base->second.FirstPoint() == base->second.LastPoint()) { // @TODO create area feature (*m_worldBucket)(base->second); features.erase(base); ++m_areasCounter; } return true; } } return false; } void TryToMerge(FeatureBuilder1 const & fb) { FeatureBuilder1Merger fbm(fb); FeaturesContainerT & container = m_features[fbm.Type()]; FeaturesContainerT::iterator found = container.find(fbm.LastPoint()); if (found != container.end()) { fbm.AppendFeature(found->second); container.erase(found); ++m_mergedCounter; } if (fbm.FirstPoint() == fbm.LastPoint()) { // @TODO create area feature (*m_worldBucket)(fbm); ++m_areasCounter; return; } pair<FeaturesContainerT::iterator, bool> result = container.insert(make_pair(fbm.FirstPoint(), fbm)); // if we found feature with the same starting point, emit it directly if (!result.second) { LOG(LWARNING, ("Found features with common first point, points counts are:", result.first->second.GetPointsCount(), fb.GetPointsCount())); (*m_worldBucket)(fbm); } } struct FeatureTypePrinter { void operator()(uint32_t type) const { cout << classif().GetFullObjectName(type) << "."; } }; public: WorldMapGenerator(int maxWorldScale, bool mergeCoastlines, typename FeatureOutT::InitDataType featureOutInitData) : m_maxWorldScale(maxWorldScale), m_mergeCoastlines(mergeCoastlines), m_mergedCounter(0), m_areasCounter(0) { if (maxWorldScale >= 0) m_worldBucket.reset(new FeatureOutT(WORLD_FILE_NAME, featureOutInitData)); } ~WorldMapGenerator() { if (m_mergeCoastlines) { LOG(LINFO, ("Final merging of coastlines started")); } // try to merge all merged features with each other for (TypesContainerT::iterator it = m_features.begin(); it != m_features.end(); ++it) { LOG(LINFO, (it->second.size())); while (ReMergeFeatures(it->second)) {} // emit all merged features for (FeaturesContainerT::iterator itF = it->second.begin(); itF != it->second.end(); ++itF) (*m_worldBucket)(itF->second); } if (m_mergeCoastlines) { LOG(LINFO, ("Final merging of coastlines ended")); LOG(LINFO, ("Merged features:", m_mergedCounter, "new areas created:", m_areasCounter)); } } bool operator()(FeatureBuilder1 const & fb) { if (m_worldBucket) { FeatureBase fBase = fb.GetFeatureBase(); int minScale = feature::MinDrawableScaleForFeature(fBase); CHECK_GREATER(minScale, -1, ("Non-drawable feature found!?")); if (m_maxWorldScale >= minScale) { FeatureTypePrinter typePrinter; fBase.ForEachTypeRef(typePrinter); cout << endl; if (m_mergeCoastlines) { // we're merging only linear features, // areas and points are written immediately if (fBase.GetFeatureType() != FeatureBase::FEATURE_TYPE_LINE) (*m_worldBucket)(fb); else TryToMerge(fb); } else (*m_worldBucket)(fb); return true; } } return false; } }; <commit_msg>Use our std headers instead of native <boost/...><commit_after>#pragma once #include "../../base/logging.hpp" #include "../../defines.hpp" #include "../../indexer/classificator.hpp" #include "../../indexer/feature.hpp" #include "../../indexer/feature_merger.hpp" #include "../../indexer/feature_visibility.hpp" #include "../../indexer/point_to_int64.hpp" #include "../../std/map.hpp" #include "../../std/vector.hpp" #include "../../std/iostream.hpp" #include "../../std/scoped_ptr.hpp" #include "../../std/unordered_map.hpp" namespace m2 { inline size_t hash_value(m2::PointD const & pt) { return static_cast<size_t>(PointToInt64(pt.x, pt.y)); } } template <class FeatureOutT> class WorldMapGenerator { /// if NULL, separate world data file is not generated scoped_ptr<FeatureOutT> m_worldBucket; /// features visible before or at this scale level will go to World map int m_maxWorldScale; bool m_mergeCoastlines; size_t m_mergedCounter; size_t m_areasCounter; typedef unordered_map<m2::PointD, FeatureBuilder1Merger> FeaturesContainerT; typedef map<vector<uint32_t>, FeaturesContainerT> TypesContainerT; TypesContainerT m_features; private: /// scans all features and tries to merge them with each other /// @return true if one feature was merged bool ReMergeFeatures(FeaturesContainerT & features) { for (FeaturesContainerT::iterator base = features.begin(); base != features.end(); ++base) { FeaturesContainerT::iterator found = features.find(base->second.LastPoint()); if (found != features.end()) { CHECK(found != base, ()); base->second.AppendFeature(found->second); features.erase(found); ++m_mergedCounter; if (base->second.FirstPoint() == base->second.LastPoint()) { // @TODO create area feature (*m_worldBucket)(base->second); features.erase(base); ++m_areasCounter; } return true; } } return false; } void TryToMerge(FeatureBuilder1 const & fb) { FeatureBuilder1Merger fbm(fb); FeaturesContainerT & container = m_features[fbm.Type()]; FeaturesContainerT::iterator found = container.find(fbm.LastPoint()); if (found != container.end()) { fbm.AppendFeature(found->second); container.erase(found); ++m_mergedCounter; } if (fbm.FirstPoint() == fbm.LastPoint()) { // @TODO create area feature (*m_worldBucket)(fbm); ++m_areasCounter; return; } pair<FeaturesContainerT::iterator, bool> result = container.insert(make_pair(fbm.FirstPoint(), fbm)); // if we found feature with the same starting point, emit it directly if (!result.second) { LOG(LWARNING, ("Found features with common first point, points counts are:", result.first->second.GetPointsCount(), fb.GetPointsCount())); (*m_worldBucket)(fbm); } } struct FeatureTypePrinter { void operator()(uint32_t type) const { cout << classif().GetFullObjectName(type) << "."; } }; public: WorldMapGenerator(int maxWorldScale, bool mergeCoastlines, typename FeatureOutT::InitDataType featureOutInitData) : m_maxWorldScale(maxWorldScale), m_mergeCoastlines(mergeCoastlines), m_mergedCounter(0), m_areasCounter(0) { if (maxWorldScale >= 0) m_worldBucket.reset(new FeatureOutT(WORLD_FILE_NAME, featureOutInitData)); } ~WorldMapGenerator() { if (m_mergeCoastlines) { LOG(LINFO, ("Final merging of coastlines started")); } // try to merge all merged features with each other for (TypesContainerT::iterator it = m_features.begin(); it != m_features.end(); ++it) { LOG(LINFO, (it->second.size())); while (ReMergeFeatures(it->second)) {} // emit all merged features for (FeaturesContainerT::iterator itF = it->second.begin(); itF != it->second.end(); ++itF) (*m_worldBucket)(itF->second); } if (m_mergeCoastlines) { LOG(LINFO, ("Final merging of coastlines ended")); LOG(LINFO, ("Merged features:", m_mergedCounter, "new areas created:", m_areasCounter)); } } bool operator()(FeatureBuilder1 const & fb) { if (m_worldBucket) { FeatureBase fBase = fb.GetFeatureBase(); int minScale = feature::MinDrawableScaleForFeature(fBase); CHECK_GREATER(minScale, -1, ("Non-drawable feature found!?")); if (m_maxWorldScale >= minScale) { FeatureTypePrinter typePrinter; fBase.ForEachTypeRef(typePrinter); cout << endl; if (m_mergeCoastlines) { // we're merging only linear features, // areas and points are written immediately if (fBase.GetFeatureType() != FeatureBase::FEATURE_TYPE_LINE) (*m_worldBucket)(fb); else TryToMerge(fb); } else (*m_worldBucket)(fb); return true; } } return false; } }; <|endoftext|>
<commit_before>/* Copyright (C) 2006 Imperial College London and others. Please see the AUTHORS file in the main source directory for a full list of copyright holders. Prof. C Pain Applied Modelling and Computation Group Department of Earth Science and Engineering Imperial College London C.Pain@Imperial.ac.uk 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. 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 */ #include "Usage.h" #include "spud.h" using namespace std; using namespace Spud; map<string, string> fl_command_line_options; void print_version(ostream& stream){ stream<<"Revision: "<<__FLUIDITY_VERSION__ #ifdef DDEBUG <<" (debugging)" #endif <<endl <<"Compile date: "<<__DATE__<<" "<<__TIME__<<endl //#include <cvsdata.h> <<"Adaptivity support\t\t" #ifdef HAVE_ADAPTIVITY <<"yes\n" #else <<"no\n" #endif <<"2D adaptivity support\t\t" #ifdef HAVE_MBA_2D <<"yes\n" #else <<"no\n" #endif <<"3D MBA support\t\t\t" #ifdef HAVE_MBA_3D <<"yes\n" #else <<"no\n" #endif <<"CGAL support\t\t\t" #ifdef HAVE_CGAL <<"yes\n" #else <<"no\n" #endif <<"MPI support\t\t\t" #ifdef HAVE_MPI <<"yes\n" #else <<"no\n" #endif <<"Double precision\t\t" #ifdef DOUBLEP <<"yes\n" #else <<"no\n" #endif <<"CGNS support\t\t\t" #ifdef HAVE_CGNS <<"yes\n" #else <<"no\n" #endif <<"NetCDF support\t\t\t" #ifdef HAVE_NETCDF <<"yes\n" #else <<"no\n" #endif <<"Signal handling support\t\t" #ifdef NSIGNAL <<"no\n" #else <<"yes\n" #endif <<"PETSc support\t\t\t" #ifdef HAVE_PETSC <<"yes\n" #else <<"no\n" #endif <<"Hypre support\t\t\t" #ifdef HAVE_HYPRE <<"yes\n" #else <<"no\n" #endif <<"ARPACK support\t\t\t" #ifdef HAVE_LIBARPACK <<"yes\n" #else <<"no\n" #endif <<"Python support\t\t\t" #ifdef HAVE_PYTHON <<"yes\n" #else <<"no\n" #endif <<"Numpy support\t\t\t" #ifdef HAVE_NUMPY <<"yes\n" #else <<"no\n" #endif <<"VTK support\t\t\t" #ifdef HAVE_VTK <<"yes\n" #else <<"no\n" #endif <<"Zoltan support\t\t\t" #ifdef HAVE_ZOLTAN <<"yes\n" #else <<"no\n" #endif ; stream.flush(); return; } void print_environment(){ const char *relevant_variables[]={"PETSC_OPTIONS"}; int no_relevant_variables=1; cout<<"Environment variables relevant for fluidity:\n"; for(int i=0; i<1; i++) { char *env=getenv(relevant_variables[i]); if(env!=NULL) { cout<<relevant_variables[i]<<" = "<<env<<endl; no_relevant_variables=0; } }; if (no_relevant_variables) cout<<" none\n"; } void usage(char *cmd){ print_version(); cerr<<"\n\nUsage: "<<cmd<<" [options ...] [simulation-file]\n" <<"\nOptions (NOTE: Long options are not available on AIX.):\n" <<" -h, --help\n\tHelp! Prints this message.\n" <<" -l, --log\n\tCreate log file for each process (useful for non-interactive testing)." <<" Sets default value for -v to 2.\n" <<" -v <level>, --verbose\n\tVerbose output to stdout, default level 0\n" <<" -V, --version\n\tVersion\n"; return; } void ParseArguments(int argc, char** argv){ #ifndef _AIX struct option longOptions[] = { {"help", 0, 0, 'h'}, {"log", 0, 0, 'l'}, {"verbose", optional_argument, 0, 'v'}, {"version", 0, 0, 'V'}, {0, 0, 0, 0} }; #endif int optionIndex = 0; int verbosity = 0; int c; // set opterr to nonzero to make getopt print error messages opterr=1; while (true){ #ifndef _AIX c = getopt_long(argc, argv, "hlv::V", longOptions, &optionIndex); #else c = getopt(argc, argv, "hlv::V"); #endif if (c == -1) break; OptionError stat; switch (c){ case 'h': fl_command_line_options["help"] = ""; break; case 'l': fl_command_line_options["log"] = ""; break; case 'v': fl_command_line_options["verbose"] = (optarg == NULL) ? "1" : optarg; break; case 'V': fl_command_line_options["version"] = ""; break; case '?': // missing argument only returns ':' if the option string starts with ':' // but this seems to stop the printing of error messages by getopt? cerr<<"ERROR: unknown option or missing argument\n"; usage(argv[0]); exit(-1); case ':': cerr<<"ERROR: missing argument\n"; usage(argv[0]); exit(-1); default: // unexpected: cerr<<"ERROR: getopt returned unrecognized character code\n"; exit(-1); } } // Help? if(fl_command_line_options.count("help")){ usage(argv[0]); exit(-1); } // Version? if(fl_command_line_options.count("version")){ print_version(); exit(-1); } // Verbose? { int MyRank = 0; #ifdef HAVE_MPI if(MPI::Is_initialized()){ MyRank = MPI::COMM_WORLD.Get_rank(); } #endif if(fl_command_line_options.count("verbose") == 0){ verbosity = 0; }else{ verbosity = atoi(fl_command_line_options["verbose"].c_str()); } set_global_debug_level_fc(&verbosity); } // Pseudo2d? if(fl_command_line_options.count("pseudo2d")){ int val; val = atoi(fl_command_line_options["pseudo2d"].c_str()); set_pseudo2d_domain_fc(&val); } // What to do with stdout/stderr? if(fl_command_line_options.count("log")){ ostringstream debug_file, err_file; debug_file << "fluidity.log"; err_file << "fluidity.err"; #ifdef HAVE_MPI if(MPI::Is_initialized()){ int MyRank = MPI::COMM_WORLD.Get_rank(); debug_file << "-" << MyRank; err_file << "-" << MyRank; } #endif if(freopen(debug_file.str().c_str(), "w", stdout) == NULL) perror("failed to redirect stdio for debugging"); if(freopen(err_file.str().c_str(), "w", stderr) == NULL) perror("failed to redirect stderr for debugging"); } // Find the filename if one is specified. Assuming that final // argument is simulation filename if it does not correspond to a // known option. if (fl_command_line_options.count("xml") == 0) { if(argc > optind + 1) { fl_command_line_options["xml"] = argv[optind + 1]; } else if(argc == optind + 1) { fl_command_line_options["xml"] = argv[optind]; } else if(fl_command_line_options.count("xml") == 0) { cerr << "ERROR: Unrecognized arguments!" << endl; usage(argv[0]); exit(-1); } } load_options(fl_command_line_options["xml"]); if(!have_option("/simulation_name")){ cerr<<"ERROR: failed to find simulation name after loading options file\n"; exit(-1); } OptionError stat = get_option("/simulation_name", fl_command_line_options["simulation_name"]); assert(stat == SPUD_NO_ERROR); // now that we know the verbosity, and possibly redirected stdout, // we may print the given command line if(verbosity >= 2){ cout<<"Fluidity command line:\n "; for(int i=0;i<argc; i++) cout<<argv[i]<<" "; cout<<endl; print_environment(); // Useful for debugging options print_options(); } // Environmental stuff -- this needs to me moved out of here and // into populate state. if(have_option("/timestepping/current_time/time_units")){ string option; get_option("/timestepping/current_time/time_units/date", option); FluxesReader_global.SetSimulationTimeUnits(option.c_str()); ClimateReader_global.SetSimulationTimeUnits(option.c_str()); NEMOReader_v2_global.SetSimulationTimeUnits(option.c_str()); } if(have_option("/environmental_data/climatology/file_name")){ string option; get_option("/environmental_data/climatology/file_name", option); ClimateReader_global.SetClimatology(option); } if(have_option("/ocean_forcing/input_file")) { string option; get_option("/ocean_forcing/input_file/file_name", option); FluxesReader_global.RegisterDataFile(option); #ifdef DDEBUG //FluxesReader_global.VerboseOn(); #endif // field from NetCDF file Index | Physical meaning FluxesReader_global.AddFieldOfInterest("10u"); // 0 | 10 metre U wind component FluxesReader_global.AddFieldOfInterest("10v"); // 1 | 10 metre V wind component FluxesReader_global.AddFieldOfInterest("ssrd"); // 2 | Surface solar radiation FluxesReader_global.AddFieldOfInterest("strd"); // 3 | Surface thermal radiation FluxesReader_global.AddFieldOfInterest("ro"); // 4 | Runoff FluxesReader_global.AddFieldOfInterest("tp"); // 5 | Total precipitation FluxesReader_global.AddFieldOfInterest("2d"); // 6 | Dew point temp at 2m FluxesReader_global.AddFieldOfInterest("2t"); // 7 | Air temp at 2m FluxesReader_global.AddFieldOfInterest("msl"); // 8 | Mean sea level pressure } if(have_option("/ocean_forcing/external_data_boundary_conditions")) { string option; get_option("/ocean_forcing/external_data_boundary_conditions/input_file/file_name", option); if(verbosity >= 3) cout << "Registering external data forcing file: " << option << endl; NEMOReader_v2_global.RegisterDataFile(option); NEMOReader_v2_global.AddFieldOfInterest("temperature"); // 0 | Sea temperature NEMOReader_v2_global.AddFieldOfInterest("salinity"); // 1 | Salinity NEMOReader_v2_global.AddFieldOfInterest("u"); // 2 | Azimuthal velocity NEMOReader_v2_global.AddFieldOfInterest("v"); // 3 | Meridional velocity NEMOReader_v2_global.AddFieldOfInterest("ssh"); // 4 | Sea surface height } return; } void PetscInit(int argc, char** argv){ #ifdef HAVE_PETSC int petscargc; char** petscargv; petscargc = 1; petscargv = new char*[1]; petscargv[0] = new char[strlen(argv[0]) + 1]; strncpy(petscargv[0], argv[0], strlen(argv[0]) + 1); static char help[] = "Use --help to see the help.\n\n"; PetscErrorCode ierr = PetscInitialize(&petscargc, &petscargv, NULL, help); // PetscInitializeFortran needs to be called when initialising PETSc from C, but calling it from Fortran // This sets all kinds of objects such as PETSC_NULL_OBJECT, PETSC_COMM_WORLD, etc., etc. ierr = PetscInitializeFortran(); // CHKERRQ(ierr); signal(SIGSEGV, SIG_DFL); signal(SIGTRAP, SIG_DFL); for(int i = 0; i < petscargc; i++) delete [] petscargv[i]; delete [] petscargv; #endif } <commit_msg>Adding a bit more information to --version<commit_after>/* Copyright (C) 2006 Imperial College London and others. Please see the AUTHORS file in the main source directory for a full list of copyright holders. Prof. C Pain Applied Modelling and Computation Group Department of Earth Science and Engineering Imperial College London C.Pain@Imperial.ac.uk 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. 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 */ #include "Usage.h" #include "spud.h" using namespace std; using namespace Spud; map<string, string> fl_command_line_options; void print_version(ostream& stream){ stream<<"Revision: "<<__FLUIDITY_VERSION__ #ifdef DDEBUG <<" (debugging)" #endif <<endl <<"Compile date: "<<__DATE__<<" "<<__TIME__<<endl <<"Adaptivity support\t\t" #ifdef HAVE_ADAPTIVITY <<"yes\n" #else <<"no\n" #endif <<"2D adaptivity support\t\t" #ifdef HAVE_MBA_2D <<"yes\n" #else <<"no\n" #endif <<"3D MBA support\t\t\t" #ifdef HAVE_MBA_3D <<"yes\n" #else <<"no\n" #endif <<"CGAL support\t\t\t" #ifdef HAVE_CGAL <<"yes\n" #else <<"no\n" #endif <<"MPI support\t\t\t" #ifdef HAVE_MPI <<"yes\n" #else <<"no\n" #endif <<"Double precision\t\t" #ifdef DOUBLEP <<"yes\n" #else <<"no\n" #endif <<"CGNS support\t\t\t" #ifdef HAVE_CGNS <<"yes\n" #else <<"no\n" #endif <<"NetCDF support\t\t\t" #ifdef HAVE_NETCDF <<"yes\n" #else <<"no\n" #endif <<"Signal handling support\t\t" #ifdef NSIGNAL <<"no\n" #else <<"yes\n" #endif <<"Stream I/O support\t\t" #ifdef STREAM_IO <<"yes\n" #else <<"no\n" #endif <<"PETSc support\t\t\t" #ifdef HAVE_PETSC <<"yes\n" #else <<"no\n" #endif <<"Hypre support\t\t\t" #ifdef HAVE_HYPRE <<"yes\n" #else <<"no\n" #endif <<"ARPACK support\t\t\t" #ifdef HAVE_LIBARPACK <<"yes\n" #else <<"no\n" #endif <<"Python support\t\t\t" #ifdef HAVE_PYTHON <<"yes\n" #else <<"no\n" #endif <<"Numpy support\t\t\t" #ifdef HAVE_NUMPY <<"yes\n" #else <<"no\n" #endif <<"VTK support\t\t\t" #ifdef HAVE_VTK <<"yes\n" #else <<"no\n" #endif <<"Zoltan support\t\t\t" #ifdef HAVE_ZOLTAN <<"yes\n" #else <<"no\n" #endif <<"Memory diagnostics\t\t" #ifdef HAVE_MEMORY_STATS <<"yes\n" #else <<"no\n" #endif ; stream.flush(); return; } void print_environment(){ const char *relevant_variables[]={"PETSC_OPTIONS"}; int no_relevant_variables=1; cout<<"Environment variables relevant for fluidity:\n"; for(int i=0; i<1; i++) { char *env=getenv(relevant_variables[i]); if(env!=NULL) { cout<<relevant_variables[i]<<" = "<<env<<endl; no_relevant_variables=0; } }; if (no_relevant_variables) cout<<" none\n"; } void usage(char *cmd){ print_version(); cerr<<"\n\nUsage: "<<cmd<<" [options ...] [simulation-file]\n" <<"\nOptions (NOTE: Long options are not available on AIX.):\n" <<" -h, --help\n\tHelp! Prints this message.\n" <<" -l, --log\n\tCreate log file for each process (useful for non-interactive testing)." <<" Sets default value for -v to 2.\n" <<" -v <level>, --verbose\n\tVerbose output to stdout, default level 0\n" <<" -V, --version\n\tVersion\n"; return; } void ParseArguments(int argc, char** argv){ #ifndef _AIX struct option longOptions[] = { {"help", 0, 0, 'h'}, {"log", 0, 0, 'l'}, {"verbose", optional_argument, 0, 'v'}, {"version", 0, 0, 'V'}, {0, 0, 0, 0} }; #endif int optionIndex = 0; int verbosity = 0; int c; // set opterr to nonzero to make getopt print error messages opterr=1; while (true){ #ifndef _AIX c = getopt_long(argc, argv, "hlv::V", longOptions, &optionIndex); #else c = getopt(argc, argv, "hlv::V"); #endif if (c == -1) break; switch (c){ case 'h': fl_command_line_options["help"] = ""; break; case 'l': fl_command_line_options["log"] = ""; break; case 'v': fl_command_line_options["verbose"] = (optarg == NULL) ? "1" : optarg; break; case 'V': fl_command_line_options["version"] = ""; break; case '?': // missing argument only returns ':' if the option string starts with ':' // but this seems to stop the printing of error messages by getopt? cerr<<"ERROR: unknown option or missing argument\n"; usage(argv[0]); exit(-1); case ':': cerr<<"ERROR: missing argument\n"; usage(argv[0]); exit(-1); default: // unexpected: cerr<<"ERROR: getopt returned unrecognized character code\n"; exit(-1); } } // Help? if(fl_command_line_options.count("help")){ usage(argv[0]); exit(-1); } // Version? if(fl_command_line_options.count("version")){ print_version(); exit(-1); } // Verbose? { int MyRank = 0; #ifdef HAVE_MPI if(MPI::Is_initialized()){ MyRank = MPI::COMM_WORLD.Get_rank(); } #endif if(fl_command_line_options.count("verbose") == 0){ verbosity = 0; }else{ verbosity = atoi(fl_command_line_options["verbose"].c_str()); } set_global_debug_level_fc(&verbosity); } // Pseudo2d? if(fl_command_line_options.count("pseudo2d")){ int val; val = atoi(fl_command_line_options["pseudo2d"].c_str()); set_pseudo2d_domain_fc(&val); } // What to do with stdout/stderr? if(fl_command_line_options.count("log")){ ostringstream debug_file, err_file; debug_file << "fluidity.log"; err_file << "fluidity.err"; #ifdef HAVE_MPI if(MPI::Is_initialized()){ int MyRank = MPI::COMM_WORLD.Get_rank(); debug_file << "-" << MyRank; err_file << "-" << MyRank; } #endif if(freopen(debug_file.str().c_str(), "w", stdout) == NULL) perror("failed to redirect stdio for debugging"); if(freopen(err_file.str().c_str(), "w", stderr) == NULL) perror("failed to redirect stderr for debugging"); } // Find the filename if one is specified. Assuming that final // argument is simulation filename if it does not correspond to a // known option. if (fl_command_line_options.count("xml") == 0) { if(argc > optind + 1) { fl_command_line_options["xml"] = argv[optind + 1]; } else if(argc == optind + 1) { fl_command_line_options["xml"] = argv[optind]; } else if(fl_command_line_options.count("xml") == 0) { cerr << "ERROR: Unrecognized arguments!" << endl; usage(argv[0]); exit(-1); } } load_options(fl_command_line_options["xml"]); if(!have_option("/simulation_name")){ cerr<<"ERROR: failed to find simulation name after loading options file\n"; exit(-1); } OptionError stat = get_option("/simulation_name", fl_command_line_options["simulation_name"]); assert(stat == SPUD_NO_ERROR); // now that we know the verbosity, and possibly redirected stdout, // we may print the given command line if(verbosity >= 2){ cout<<"Fluidity command line:\n "; for(int i=0;i<argc; i++) cout<<argv[i]<<" "; cout<<endl; print_environment(); // Useful for debugging options print_options(); } // Environmental stuff -- this needs to me moved out of here and // into populate state. if(have_option("/timestepping/current_time/time_units")){ string option; get_option("/timestepping/current_time/time_units/date", option); FluxesReader_global.SetSimulationTimeUnits(option.c_str()); ClimateReader_global.SetSimulationTimeUnits(option.c_str()); NEMOReader_v2_global.SetSimulationTimeUnits(option.c_str()); } if(have_option("/environmental_data/climatology/file_name")){ string option; get_option("/environmental_data/climatology/file_name", option); ClimateReader_global.SetClimatology(option); } if(have_option("/ocean_forcing/input_file")) { string option; get_option("/ocean_forcing/input_file/file_name", option); FluxesReader_global.RegisterDataFile(option); #ifdef DDEBUG //FluxesReader_global.VerboseOn(); #endif // field from NetCDF file Index | Physical meaning FluxesReader_global.AddFieldOfInterest("10u"); // 0 | 10 metre U wind component FluxesReader_global.AddFieldOfInterest("10v"); // 1 | 10 metre V wind component FluxesReader_global.AddFieldOfInterest("ssrd"); // 2 | Surface solar radiation FluxesReader_global.AddFieldOfInterest("strd"); // 3 | Surface thermal radiation FluxesReader_global.AddFieldOfInterest("ro"); // 4 | Runoff FluxesReader_global.AddFieldOfInterest("tp"); // 5 | Total precipitation FluxesReader_global.AddFieldOfInterest("2d"); // 6 | Dew point temp at 2m FluxesReader_global.AddFieldOfInterest("2t"); // 7 | Air temp at 2m FluxesReader_global.AddFieldOfInterest("msl"); // 8 | Mean sea level pressure } if(have_option("/ocean_forcing/external_data_boundary_conditions")) { string option; get_option("/ocean_forcing/external_data_boundary_conditions/input_file/file_name", option); if(verbosity >= 3) cout << "Registering external data forcing file: " << option << endl; NEMOReader_v2_global.RegisterDataFile(option); NEMOReader_v2_global.AddFieldOfInterest("temperature"); // 0 | Sea temperature NEMOReader_v2_global.AddFieldOfInterest("salinity"); // 1 | Salinity NEMOReader_v2_global.AddFieldOfInterest("u"); // 2 | Azimuthal velocity NEMOReader_v2_global.AddFieldOfInterest("v"); // 3 | Meridional velocity NEMOReader_v2_global.AddFieldOfInterest("ssh"); // 4 | Sea surface height } return; } void PetscInit(int argc, char** argv){ #ifdef HAVE_PETSC int petscargc; char** petscargv; petscargc = 1; petscargv = new char*[1]; petscargv[0] = new char[strlen(argv[0]) + 1]; strncpy(petscargv[0], argv[0], strlen(argv[0]) + 1); static char help[] = "Use --help to see the help.\n\n"; PetscErrorCode ierr = PetscInitialize(&petscargc, &petscargv, NULL, help); // PetscInitializeFortran needs to be called when initialising PETSc from C, but calling it from Fortran // This sets all kinds of objects such as PETSC_NULL_OBJECT, PETSC_COMM_WORLD, etc., etc. ierr = PetscInitializeFortran(); // CHKERRQ(ierr); signal(SIGSEGV, SIG_DFL); signal(SIGTRAP, SIG_DFL); for(int i = 0; i < petscargc; i++) delete [] petscargv[i]; delete [] petscargv; #endif } <|endoftext|>
<commit_before>#ifndef OMNI_CORE_ID_HPP #define OMNI_CORE_ID_HPP #include <omni/core/core.hpp> #include <omni/core/domain.hpp> #include <string> #include <ostream> namespace omni { namespace core { /** An `id' is a globally unique identifier that is used throughout omni to identify parts of the context such as variables, types, functions, classes, enums, and even statements and expressions. **/ class OMNI_CORE_API id { public: id (); id (domain domain, std::string id); bool operator<(id const & rhs) const; bool operator==(id const & rhs) const; bool isValid () const; domain getDomain () const; std::string getId () const; private: domain _domain; std::string _id; }; std::ostream OMNI_CORE_API & operator << (std::ostream & lhs, id const & rhs); } // namespace core } // namespace omni #endif // include guard <commit_msg>Completed documentation in id.hpp<commit_after>#ifndef OMNI_CORE_ID_HPP #define OMNI_CORE_ID_HPP #include <omni/core/core.hpp> #include <omni/core/domain.hpp> #include <string> #include <ostream> namespace omni { namespace core { /** @class id id.hpp omni/core/model/id.hpp @brief An id consists of a domain and a globally unique identifier that is used throughout omni to identify parts of the context such as variables, types, functions, classes, enums, and even statements and expressions. To minimize the potential clash of ids, the identifiers for entities in omni are split into "domains" (@see domain). This means that only a pair of domain and id builds up a unique identifier of an entity. Usually objects of type id should be used passed around as values instead of references or shared_ptr. **/ class OMNI_CORE_API id { public: id (); id (domain domain, std::string id); bool operator<(id const & rhs) const; bool operator==(id const & rhs) const; bool isValid () const; domain getDomain () const; std::string getId () const; private: domain _domain; std::string _id; }; std::ostream OMNI_CORE_API & operator << (std::ostream & lhs, id const & rhs); } // namespace core } // namespace omni #endif // include guard <|endoftext|>
<commit_before><commit_msg>Fixes bug in AcceleratorHandler. It's possible to get events for GtkWidgets outside of those created by Chrome that we need to ignore. I saw this with drag and drop.<commit_after><|endoftext|>
<commit_before>#include <getopt.h> #include "configurator.hpp" #include "isolation_module_factory.hpp" #include "slave.hpp" #include "slave_webui.hpp" using boost::lexical_cast; using boost::bad_lexical_cast; using namespace std; using namespace nexus::internal::slave; void usage(const char *programName, const Configurator& conf) { cerr << "Usage: " << programName << " --url=MASTER_URL [--cpus=NUM] [--mem=NUM] [...]" << endl << endl << "MASTER_URL may be one of:" << endl << " nexus://id@host:port" << endl << " zoo://host1:port1,host2:port2,..." << endl << " zoofile://file where file contains a host:port pair per line" << endl << conf.getUsage(); } int main(int argc, char **argv) { Configurator conf; conf.addOption<string>("url", 'u', "Master URL"); conf.addOption<int>("port", 'p', "Port to listen on (default: random)"); conf.addOption<bool>("quiet", 'q', "Disable logging to stderr", false); conf.addOption<string>("log_dir", "Where to place logs", "/tmp"); conf.addOption<string>("isolation", 'i', "Isolation module name", "process"); conf.addOption<int32_t>("cpus", 'c', "CPU cores to use for tasks", 1); conf.addOption<int64_t>("mem", 'm', "Memory to use for tasks, in bytes\n", 1 * Gigabyte); #ifdef NEXUS_WEBUI conf.addOption<int>("webui_port", 'w', "Web UI port", 8081); #endif Slave::registerOptions(&conf); if (argc == 2 && string("--help") == argv[1]) { usage(argv[0], conf); exit(1); } Params params; try { conf.load(argc, argv, true); params = conf.getParams(); } catch (BadOptionValueException& e) { cerr << "Invalid value for '" << e.what() << "' option" << endl; exit(1); } catch (ConfigurationException& e) { cerr << "Configuration error: " << e.what() << endl; exit(1); } if (params.contains("port")) setenv("LIBPROCESS_PORT", params["port"].c_str(), 1); FLAGS_log_dir = params["log_dir"]; FLAGS_logbufsecs = 1; google::InitGoogleLogging(argv[0]); bool quiet = params.get<bool>("quiet", false); if (!quiet) google::SetStderrLogging(google::INFO); if (!params.contains("url")) { cerr << "Master URL argument (--url) required." << endl; exit(1); } string url = params["url"]; string isolation = params["isolation"]; LOG(INFO) << "Creating \"" << isolation << "\" isolation module"; IsolationModule *isolationModule = IsolationModule::create(isolation); if (isolationModule == NULL) { cerr << "Unrecognized isolation type: " << isolation << endl; exit(1); } LOG(INFO) << "Build: " << BUILD_DATE << " by " << BUILD_USER; LOG(INFO) << "Starting Nexus slave"; if (chdir(dirname(argv[0])) != 0) fatalerror("Could not chdir into %s", dirname(argv[0])); Resources resources(params.get<int32_t>("cpus", 1), params.get<int64_t>("mem", 1 * Gigabyte)); Slave* slave = new Slave(params, resources, false, isolationModule); PID pid = Process::spawn(slave); MasterDetector *detector = MasterDetector::create(url, pid, false, quiet); #ifdef NEXUS_WEBUI startSlaveWebUI(pid, (char*) params["webui_port"].c_str()); #endif Process::wait(pid); MasterDetector::destroy(detector); IsolationModule::destroy(isolationModule); delete slave; return 0; } <commit_msg>Tweak slave usage message<commit_after>#include <getopt.h> #include "configurator.hpp" #include "isolation_module_factory.hpp" #include "slave.hpp" #include "slave_webui.hpp" using boost::lexical_cast; using boost::bad_lexical_cast; using namespace std; using namespace nexus::internal::slave; void usage(const char *programName, const Configurator& conf) { cerr << "Usage: " << programName << " --url=MASTER_URL [--cpus=NUM] [--mem=BYTES] [...]" << endl << endl << "MASTER_URL may be one of:" << endl << " nexus://id@host:port" << endl << " zoo://host1:port1,host2:port2,..." << endl << " zoofile://file where file contains a host:port pair per line" << endl << conf.getUsage(); } int main(int argc, char **argv) { Configurator conf; conf.addOption<string>("url", 'u', "Master URL"); conf.addOption<int>("port", 'p', "Port to listen on (default: random)"); conf.addOption<bool>("quiet", 'q', "Disable logging to stderr", false); conf.addOption<string>("log_dir", "Where to place logs", "/tmp"); conf.addOption<string>("isolation", 'i', "Isolation module name", "process"); conf.addOption<int32_t>("cpus", 'c', "CPU cores to use for tasks", 1); conf.addOption<int64_t>("mem", 'm', "Memory to use for tasks, in bytes\n", 1 * Gigabyte); #ifdef NEXUS_WEBUI conf.addOption<int>("webui_port", 'w', "Web UI port", 8081); #endif Slave::registerOptions(&conf); if (argc == 2 && string("--help") == argv[1]) { usage(argv[0], conf); exit(1); } Params params; try { conf.load(argc, argv, true); params = conf.getParams(); } catch (BadOptionValueException& e) { cerr << "Invalid value for '" << e.what() << "' option" << endl; exit(1); } catch (ConfigurationException& e) { cerr << "Configuration error: " << e.what() << endl; exit(1); } if (params.contains("port")) setenv("LIBPROCESS_PORT", params["port"].c_str(), 1); FLAGS_log_dir = params["log_dir"]; FLAGS_logbufsecs = 1; google::InitGoogleLogging(argv[0]); bool quiet = params.get<bool>("quiet", false); if (!quiet) google::SetStderrLogging(google::INFO); if (!params.contains("url")) { cerr << "Master URL argument (--url) required." << endl; exit(1); } string url = params["url"]; string isolation = params["isolation"]; LOG(INFO) << "Creating \"" << isolation << "\" isolation module"; IsolationModule *isolationModule = IsolationModule::create(isolation); if (isolationModule == NULL) { cerr << "Unrecognized isolation type: " << isolation << endl; exit(1); } LOG(INFO) << "Build: " << BUILD_DATE << " by " << BUILD_USER; LOG(INFO) << "Starting Nexus slave"; if (chdir(dirname(argv[0])) != 0) fatalerror("Could not chdir into %s", dirname(argv[0])); Resources resources(params.get<int32_t>("cpus", 1), params.get<int64_t>("mem", 1 * Gigabyte)); Slave* slave = new Slave(params, resources, false, isolationModule); PID pid = Process::spawn(slave); MasterDetector *detector = MasterDetector::create(url, pid, false, quiet); #ifdef NEXUS_WEBUI startSlaveWebUI(pid, (char*) params["webui_port"].c_str()); #endif Process::wait(pid); MasterDetector::destroy(detector); IsolationModule::destroy(isolationModule); delete slave; return 0; } <|endoftext|>
<commit_before>#include <vector> #include <fstream> #include <ostream> #include <string> #include "mainWindow.h" #include "addStreamDialog.h" #include "livestreamerProcess.h" #include "fileHelper.h" mainWindow::mainWindow(BaseObjectType *base, const Glib::RefPtr<Gtk::Builder> &builder) : Gtk::Window(base), builder(builder) { builder->get_widget("addButton", addStreamButton); builder->get_widget("removeButton", removeStreamButton); builder->get_widget("playButton", playStreamButton); builder->get_widget("quitButton", quitButton); builder->get_widget("streamList", streamList); builder->get_widget("statusbar", statusbar); listModel = Gtk::ListStore::create(columns); streamList->set_model(listModel); streamList->append_column("URL", columns.streamUrl); streamList->append_column("Quality", columns.streamQuality); readDataFile(); auto addHandler = [this](){ addStreamDialog dlg(*this); if(dlg.run() == Gtk::RESPONSE_OK) { Gtk::TreeModel::Row row = *(listModel->append()); row[columns.streamUrl] = dlg.UrlEntry.get_text(); row[columns.streamQuality] = dlg.qualityEntry.get_text(); writeDataFile(); } }; addStreamButton->signal_clicked().connect(addHandler); auto removeHandler = [this](){ using namespace Gtk; using namespace Glib; TreeModel::iterator iter = streamList->get_selection()->get_selected(); if(iter != nullptr) { listModel->erase(iter); writeDataFile(); } }; removeStreamButton->signal_clicked().connect(removeHandler); auto playHandler = [this](){ using namespace Gtk; using namespace Glib; TreeModel::iterator iter = streamList->get_selection()->get_selected(); if(iter != nullptr) { TreeModel::Row row = *iter; // using raw pointers because livestreamerProcess will kill itself when needed livestreamerProcess* proc = new livestreamerProcess(row[columns.streamUrl], row[columns.streamQuality]); proc->addOutputWatch([this, proc](IOCondition condition) -> bool { Glib::ustring str, output; proc->output->read_line(str); // remove livestreamer's newline. //str.erase(std::remove(str.begin(), str.end(), '\n'), str.end()); -- doesn't work, "lvalue required as left operand of assignment in stl_algo.h" for (size_t i=0; i < str.size(); i++) { if(str[i] != '\n') { output += str[i]; } } statusbar->push(output); return true; }); } }; playStreamButton->signal_clicked().connect(playHandler); auto quitHandler = [this](){ close(); }; quitButton->signal_clicked().connect(quitHandler); auto activatedHandler = [this] (auto path, auto unused) { using namespace Gtk; TreeModel::iterator iter = listModel->get_iter(path); if(iter != nullptr) { TreeModel::Row row = *iter; addStreamDialog dlg(*this, row[columns.streamUrl], row[columns.streamQuality]); if(dlg.run() == Gtk::RESPONSE_OK) { row[columns.streamUrl] = dlg.UrlEntry.get_text(); row[columns.streamQuality] = dlg.qualityEntry.get_text(); this->writeDataFile(); // not quite sure why I need this this-> } } }; streamList->signal_row_activated().connect(activatedHandler); } void mainWindow::readDataFile() { using namespace Glib; using namespace std; ifstream stream(fileHelper::getConfigFilePath("streams.list")); for (string line; getline(stream, line);) { // I'd use a ustring here if getline was compatible with it if(!line.empty()) { auto separator = line.find_first_of(";"); if(separator == string::npos) { continue; } ustring stream = line.substr(0, separator); ustring quality = line.substr(separator + 1, line.length() - separator); Gtk::TreeModel::Row row = *(listModel->append()); row[columns.streamUrl] = stream; row[columns.streamQuality] = quality; } } } void mainWindow::writeDataFile() { using namespace std; ofstream stream(fileHelper::getConfigFilePath("streams.list") , ofstream::out | ofstream::trunc); for (const auto &row : listModel->children()) { stream << row[columns.streamUrl] << ";" << row[columns.streamQuality] << endl; } } <commit_msg>Get rid of the auto lambda in mainWindow.cpp.<commit_after>#include <vector> #include <fstream> #include <ostream> #include <string> #include "mainWindow.h" #include "addStreamDialog.h" #include "livestreamerProcess.h" #include "fileHelper.h" mainWindow::mainWindow(BaseObjectType *base, const Glib::RefPtr<Gtk::Builder> &builder) : Gtk::Window(base), builder(builder) { builder->get_widget("addButton", addStreamButton); builder->get_widget("removeButton", removeStreamButton); builder->get_widget("playButton", playStreamButton); builder->get_widget("quitButton", quitButton); builder->get_widget("streamList", streamList); builder->get_widget("statusbar", statusbar); listModel = Gtk::ListStore::create(columns); streamList->set_model(listModel); streamList->append_column("URL", columns.streamUrl); streamList->append_column("Quality", columns.streamQuality); readDataFile(); auto addHandler = [this](){ addStreamDialog dlg(*this); if(dlg.run() == Gtk::RESPONSE_OK) { Gtk::TreeModel::Row row = *(listModel->append()); row[columns.streamUrl] = dlg.UrlEntry.get_text(); row[columns.streamQuality] = dlg.qualityEntry.get_text(); writeDataFile(); } }; addStreamButton->signal_clicked().connect(addHandler); auto removeHandler = [this](){ using namespace Gtk; using namespace Glib; TreeModel::iterator iter = streamList->get_selection()->get_selected(); if(iter != nullptr) { listModel->erase(iter); writeDataFile(); } }; removeStreamButton->signal_clicked().connect(removeHandler); auto playHandler = [this](){ using namespace Gtk; using namespace Glib; TreeModel::iterator iter = streamList->get_selection()->get_selected(); if(iter != nullptr) { TreeModel::Row row = *iter; // using raw pointers because livestreamerProcess will kill itself when needed livestreamerProcess* proc = new livestreamerProcess(row[columns.streamUrl], row[columns.streamQuality]); proc->addOutputWatch([this, proc](IOCondition condition) -> bool { Glib::ustring str, output; proc->output->read_line(str); // remove livestreamer's newline. //str.erase(std::remove(str.begin(), str.end(), '\n'), str.end()); -- doesn't work, "lvalue required as left operand of assignment in stl_algo.h" for (size_t i=0; i < str.size(); i++) { if(str[i] != '\n') { output += str[i]; } } statusbar->push(output); return true; }); } }; playStreamButton->signal_clicked().connect(playHandler); auto quitHandler = [this](){ close(); }; quitButton->signal_clicked().connect(quitHandler); auto activatedHandler = [this] (const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn* unused) { using namespace Gtk; TreeModel::iterator iter = listModel->get_iter(path); if(iter != nullptr) { TreeModel::Row row = *iter; addStreamDialog dlg(*this, row[columns.streamUrl], row[columns.streamQuality]); if(dlg.run() == Gtk::RESPONSE_OK) { row[columns.streamUrl] = dlg.UrlEntry.get_text(); row[columns.streamQuality] = dlg.qualityEntry.get_text(); writeDataFile(); } } }; streamList->signal_row_activated().connect(activatedHandler); } void mainWindow::readDataFile() { using namespace Glib; using namespace std; ifstream stream(fileHelper::getConfigFilePath("streams.list")); for (string line; getline(stream, line);) { // I'd use a ustring here if getline was compatible with it if(!line.empty()) { auto separator = line.find_first_of(";"); if(separator == string::npos) { continue; } ustring stream = line.substr(0, separator); ustring quality = line.substr(separator + 1, line.length() - separator); Gtk::TreeModel::Row row = *(listModel->append()); row[columns.streamUrl] = stream; row[columns.streamQuality] = quality; } } } void mainWindow::writeDataFile() { using namespace std; ofstream stream(fileHelper::getConfigFilePath("streams.list") , ofstream::out | ofstream::trunc); for (const auto &row : listModel->children()) { stream << row[columns.streamUrl] << ";" << row[columns.streamQuality] << endl; } } <|endoftext|>
<commit_before>#include "mainwidget.h" #include "ui_mainwidget.h" MainWidget::MainWidget(QWidget *parent) : QWidget(parent), ui(new Ui::MainWidget), m_ipconfig( new QProcess( this ) ) { ui->setupUi(this); // setup createAction(); createTrayIcon(); // set echomode ui->passEdit->setEchoMode( QLineEdit::Password ); // setting #ifdef Q_OS_MAC setting = new QSettings( QSettings::UserScope, "futr", "QAutoLogin" ); setting->setFallbacksEnabled( false ); #else setting = new QSettings( "conf.ini", QSettings::IniFormat, this ); #endif // load setting loadConfigSlot(); // 読み込まれた設定によってフォーカスを制御 if ( setting->value( "Auth" ).toString().length() == 0 ) { ui->serverNameEdit->setFocus(); } else if ( setting->value( "ID" ).toString().length() == 0 ) { ui->idEdit->setFocus(); } else { ui->passEdit->setFocus(); } // connect timer connect( &statusTimer, SIGNAL(timeout()), SLOT(updateStatusSlot()) ); connect( &timer, SIGNAL(timeout()), this, SLOT(loginSlot()) ); // ネットワークのエラーを接続 connect( &webAuth, SIGNAL(sslErrorOccurred(QList<QSslError>)), this, SLOT(sslErrorSlot(QList<QSslError>)) ); connect( &webAuth, SIGNAL(networkErrorOccurred(QNetworkReply::NetworkError)), this, SLOT(networkErrorSlot(QNetworkReply::NetworkError)) ); connect( &webAuth, SIGNAL(finished(LoginWebAuth::AuthStatus)), this ,SLOT(readyReadSlot(LoginWebAuth::AuthStatus)) ); } MainWidget::~MainWidget() { delete ui; } void MainWidget::on_loginButton_clicked() { // login button // clear status clearStatusSlot(); // stop all timer timer.stop(); statusTimer.stop(); // disable stop button ui->stopTimerButton->setEnabled( false ); if ( ui->repeatCheckBox->isChecked() ) { // repeat login int repeatTime; // 必要なら乱数でぶらす repeatTime = ui->repatSpinBox->value(); if ( ui->randomizeCheckBox->isChecked() && ui->randomizeSpinBox->value() != 0 ) { repeatTime += ( qrand() % ui->randomizeSpinBox->value() ) * ( ( qrand() % 2 ) * -1 ); } if ( repeatTime < 0 ) { repeatTime = 1; } timer.setInterval( repeatTime * 60 * 1000 ); // set progress ui->progressBar->setMaximum( repeatTime ); ui->progressBar->setValue( repeatTime ); // set status timer statusTimer.setInterval( 1000 * 60 ); statusTimer.start(); // start timer timer.start(); // button enable ui->stopTimerButton->setEnabled( true ); } // login loginSlot(); } void MainWidget::loginSlot() { // ログイン webAuth.setServerUrl( ui->serverNameEdit->text() ); webAuth.setUserName( ui->idEdit->text() ); webAuth.setPassword( ui->passEdit->text() ); // SSLエラー無視 webAuth.setIgnoreSslError(); webAuth.login(); } void MainWidget::logoutSlot() { // logout slot webAuth.setServerUrl( ui->serverNameEdit->text() ); webAuth.setUserName( ui->idEdit->text() ); webAuth.setPassword( ui->passEdit->text() ); // SSLエラー無視 webAuth.setIgnoreSslError(); webAuth.logout(); } void MainWidget::readyReadSlot( LoginWebAuth::AuthStatus stat ) { // 通信完了 // メッセージ作成 QString info; QString title; if ( stat == LoginWebAuth::LoginSucceeded ) { // ログイン成功 title = tr( "Login" ); info = QString() + tr( "Login time\t : " ) + webAuth.loginTime().toString( Qt::DefaultLocaleShortDate ) + tr( "\nLogout time\t : " ) + webAuth.autoLogoutTime().toString( Qt::DefaultLocaleShortDate ); if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info ); } } else if ( stat == LoginWebAuth::LogoutSucceeded ) { // ログアウト成功 title = tr( "Logout" ); info = tr( "Logout succeeded" ); if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info ); } } else { // error title = tr( "Error" ); info = tr( "Some errors occurred" ); if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info, QSystemTrayIcon::Warning ); } } // ラベルに表示 ui->messageLabel->setText( title + "\n" + info ); // 成功していて必要ならIP更新 if ( ui->renewIPCheckBox->isChecked() && ( stat == LoginWebAuth::LoginSucceeded || stat == LoginWebAuth::LoginSucceeded ) ) { renewIP(); } } void MainWidget::saveConfigSlot() { // save config // save check setting->setValue( "Repeat", ui->repeatCheckBox->isChecked() ); setting->setValue( "AutoMinimize", ui->autoToTrayCheckBox->isChecked() ); setting->setValue( "AutoStart", ui->autoStartCheckBox->isChecked() ); setting->setValue( "ConfigId", ui->saveIdCheckBox->isChecked() ); setting->setValue( "ConfigPass", ui->savePassCheckBox->isChecked() ); setting->setValue( "RepeatMin", ui->repatSpinBox->value() ); setting->setValue( "Auth", ui->serverNameEdit->text() ); setting->setValue( "AutoLogout", ui->autoLogoutCheckBox->isChecked() ); setting->setValue( "AutoRenewIP", ui->renewIPCheckBox->isChecked() ); setting->setValue( "RandomizeEnable", ui->randomizeCheckBox->isChecked() ); setting->setValue( "RandomizeRange", ui->randomizeSpinBox->value() ); // if need id,pass if ( ui->saveIdCheckBox->isChecked() ) { setting->setValue( "ID", ui->idEdit->text() ); } if ( ui->savePassCheckBox->isChecked() ) { setting->setValue( "Pass", ui->passEdit->text() ); } } void MainWidget::loadConfigSlot() { // load config // load check ui->repeatCheckBox->setChecked( setting->value( "Repeat" ).toBool() ); ui->autoToTrayCheckBox->setChecked( setting->value( "AutoMinimize" ).toBool() ); ui->autoStartCheckBox->setChecked( setting->value( "AutoStart" ).toBool() ); ui->saveIdCheckBox->setChecked( setting->value( "ConfigId" ).toBool() ); ui->savePassCheckBox->setChecked( setting->value( "ConfigPass" ).toBool() ); ui->repatSpinBox->setValue( setting->value( "RepeatMin" ).toInt() ); ui->serverNameEdit->setText( setting->value( "Auth" ).toString() ); ui->autoLogoutCheckBox->setChecked( setting->value( "AutoLogout" ).toBool() ); ui->renewIPCheckBox->setChecked( setting->value( "AutoRenewIP" ).toBool() ); ui->randomizeCheckBox->setChecked( setting->value( "RandomizeEnable" ).toBool() ); ui->randomizeSpinBox->setValue( setting->value( "RandomizeRange" ).toInt() ); // if need id,pass if ( ui->saveIdCheckBox->isChecked() ) { ui->idEdit->setText( setting->value( "ID" ).toString() ); } if ( ui->savePassCheckBox->isChecked() ) { ui->passEdit->setText( setting->value( "Pass" ).toString() ); } // do setting if ( ui->autoStartCheckBox->isChecked() ) { // 起動時に自動ログイン // Windowsの場合いったんIPをrenewする renewIP(); m_ipconfig->waitForFinished(); on_loginButton_clicked(); } if ( ui->autoToTrayCheckBox->isChecked() ) { // minimize to tray QTimer::singleShot( 100, this, SLOT(minimizeSlot()) ); } } void MainWidget::minimizeSlot() { // minimize to tray trayIcon->show(); /* trayIcon->showMessage( tr( "Minimize to tray" ), tr( "This application is still running. To quit please click this icon and select Close" ) ); */ hide(); } void MainWidget::updateStatusSlot() { // update status // update progress bar if ( timer.isActive() ) { ui->progressBar->setValue( ui->progressBar->value() - 1 ); } } void MainWidget::clearStatusSlot() { // clearStatus ui->progressBar->setValue( 0 ); } void MainWidget::sslErrorSlot(const QList<QSslError> &errors) { // sslError Slot QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() ); QString errString; // iOSでは不完全型となっているため直接アクセスしない #ifndef Q_OS_IOS foreach ( QSslError err, errors ) { errString += err.errorString() + "\n"; } #endif // 全エラー無視(本来は確認すべき) reply->ignoreSslErrors(); // view ssl error if ( isVisible() ) { QMessageBox::warning( this, tr( "Ssl warning" ), errString + tr( "\n\nThese \"SslError\" are ignored." ) ); } } void MainWidget::trayIconClickSlot( QSystemTrayIcon::ActivationReason reason ) { // tray icon clicked if ( reason == QSystemTrayIcon::Trigger ) { // Macの場合ここでhideすると落ちるためなにもしない #ifdef Q_OS_MAC return; #endif trayIcon->hide(); this->show(); } } void MainWidget::networkErrorSlot( QNetworkReply::NetworkError code ) { // network error Q_UNUSED( code ) if ( isVisible() ) { QMessageBox::warning( this, tr( "Network error" ), tr( "Some network error occurred" ) ); } } void MainWidget::checkIpSlot() { // check ip foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) ui->ipEdit->setText( address.toString() ); } } void MainWidget::renewIP() { // IPを更新する ( Windows only ) #ifdef Q_OS_WIN m_ipconfig->start( "ipconfig", QStringList() << "/renew" ); #endif } void MainWidget::on_aboutButton_clicked() { // aboutQt QMessageBox::aboutQt( this ); } void MainWidget::on_closeButton_clicked() { close(); } void MainWidget::on_stopTimerButton_clicked() { // stop timer timer.stop(); statusTimer.stop(); ui->stopTimerButton->setEnabled( false ); } void MainWidget::createTrayIcon() { // create tray icon // create menu trayMenu = new QMenu( this ); trayMenu->addAction( showAction ); trayMenu->addSeparator(); trayMenu->addAction( connectAction ); trayMenu->addAction( disconnectAction ); trayMenu->addSeparator(); trayMenu->addAction( closeAction ); // setup icon trayIcon = new QSystemTrayIcon( this ); trayIcon->setContextMenu( trayMenu ); trayIcon->setIcon( QIcon( ":/image/icon.png" ) ); trayIcon->setToolTip( tr( "QAutoLogin" ) ); // connect connect( trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconClickSlot(QSystemTrayIcon::ActivationReason)) ); } void MainWidget::createAction() { // create actions closeAction = new QAction( tr( "&Close" ), this ); connectAction = new QAction( tr( "&Login" ), this ); disconnectAction = new QAction( tr( "Log&out" ), this ); showAction = new QAction( tr( "&Show" ), this ); connect( closeAction, SIGNAL(triggered()), this, SLOT(close()) ); connect( connectAction, SIGNAL(triggered()), this, SLOT(on_loginButton_clicked()) ); connect( disconnectAction, SIGNAL(triggered()), this, SLOT(on_logoutButton_clicked()) ); connect( showAction, SIGNAL(triggered()), SLOT(show()) ); } void MainWidget::closeEvent(QCloseEvent *) { // close event if ( trayIcon->isVisible() ) { trayIcon->hide(); } // 必要ならログアウト if ( ui->autoLogoutCheckBox->isChecked() ) { // ログアウト処理が完了するまでブロック QEventLoop loop; connect( &webAuth, SIGNAL(finished(LoginWebAuth::AuthStatus)), &loop, SLOT(quit()) ); // ログアウト実行 logoutSlot(); // イベントループ開始 loop.exec(); } // ipconfigプロセスの終了を待つ m_ipconfig->waitForFinished(); } void MainWidget::on_saveConfigButton_clicked() { // save config button saveConfigSlot(); } void MainWidget::on_logoutButton_clicked() { // logout logoutSlot(); // disable timer timer.stop(); statusTimer.stop(); ui->stopTimerButton->setEnabled( false ); } void MainWidget::on_minimizePushButton_clicked() { minimizeSlot(); } void MainWidget::on_checkIpButton_clicked() { // check ip checkIpSlot(); } void MainWidget::on_renewIPButton_clicked() { // IPを再取得 renewIP(); } <commit_msg>再ログイン時間の乱数揺らしが正しく動作しない問題を修正<commit_after>#include "mainwidget.h" #include "ui_mainwidget.h" MainWidget::MainWidget(QWidget *parent) : QWidget(parent), ui(new Ui::MainWidget), m_ipconfig( new QProcess( this ) ) { ui->setupUi(this); // setup createAction(); createTrayIcon(); // set echomode ui->passEdit->setEchoMode( QLineEdit::Password ); // setting #ifdef Q_OS_MAC setting = new QSettings( QSettings::UserScope, "futr", "QAutoLogin" ); setting->setFallbacksEnabled( false ); #else setting = new QSettings( "conf.ini", QSettings::IniFormat, this ); #endif // load setting loadConfigSlot(); // 読み込まれた設定によってフォーカスを制御 if ( setting->value( "Auth" ).toString().length() == 0 ) { ui->serverNameEdit->setFocus(); } else if ( setting->value( "ID" ).toString().length() == 0 ) { ui->idEdit->setFocus(); } else { ui->passEdit->setFocus(); } // connect timer connect( &statusTimer, SIGNAL(timeout()), SLOT(updateStatusSlot()) ); connect( &timer, SIGNAL(timeout()), this, SLOT(loginSlot()) ); // ネットワークのエラーを接続 connect( &webAuth, SIGNAL(sslErrorOccurred(QList<QSslError>)), this, SLOT(sslErrorSlot(QList<QSslError>)) ); connect( &webAuth, SIGNAL(networkErrorOccurred(QNetworkReply::NetworkError)), this, SLOT(networkErrorSlot(QNetworkReply::NetworkError)) ); connect( &webAuth, SIGNAL(finished(LoginWebAuth::AuthStatus)), this ,SLOT(readyReadSlot(LoginWebAuth::AuthStatus)) ); } MainWidget::~MainWidget() { delete ui; } void MainWidget::on_loginButton_clicked() { // login button // clear status clearStatusSlot(); // stop all timer timer.stop(); statusTimer.stop(); // disable stop button ui->stopTimerButton->setEnabled( false ); if ( ui->repeatCheckBox->isChecked() ) { // repeat login int repeatTime; int randTime; // 必要なら乱数でぶらす repeatTime = ui->repatSpinBox->value(); if ( ui->randomizeCheckBox->isChecked() && ui->randomizeSpinBox->value() != 0 ) { randTime = qrand() % ui->randomizeSpinBox->value(); if ( qrand() % 2 ) { randTime *= -1; } repeatTime += randTime; } if ( repeatTime < 0 ) { repeatTime = 1; } timer.setInterval( repeatTime * 60 * 1000 ); // set progress ui->progressBar->setMaximum( repeatTime ); ui->progressBar->setValue( repeatTime ); // set status timer statusTimer.setInterval( 1000 * 60 ); statusTimer.start(); // start timer timer.start(); // button enable ui->stopTimerButton->setEnabled( true ); } // login loginSlot(); } void MainWidget::loginSlot() { // ログイン webAuth.setServerUrl( ui->serverNameEdit->text() ); webAuth.setUserName( ui->idEdit->text() ); webAuth.setPassword( ui->passEdit->text() ); // SSLエラー無視 webAuth.setIgnoreSslError(); webAuth.login(); } void MainWidget::logoutSlot() { // logout slot webAuth.setServerUrl( ui->serverNameEdit->text() ); webAuth.setUserName( ui->idEdit->text() ); webAuth.setPassword( ui->passEdit->text() ); // SSLエラー無視 webAuth.setIgnoreSslError(); webAuth.logout(); } void MainWidget::readyReadSlot( LoginWebAuth::AuthStatus stat ) { // 通信完了 // メッセージ作成 QString info; QString title; if ( stat == LoginWebAuth::LoginSucceeded ) { // ログイン成功 title = tr( "Login" ); info = QString() + tr( "Login time\t : " ) + webAuth.loginTime().toString( Qt::DefaultLocaleShortDate ) + tr( "\nLogout time\t : " ) + webAuth.autoLogoutTime().toString( Qt::DefaultLocaleShortDate ); if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info ); } } else if ( stat == LoginWebAuth::LogoutSucceeded ) { // ログアウト成功 title = tr( "Logout" ); info = tr( "Logout succeeded" ); if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info ); } } else { // error title = tr( "Error" ); info = tr( "Some errors occurred" ); if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info, QSystemTrayIcon::Warning ); } } // ラベルに表示 ui->messageLabel->setText( title + "\n" + info ); // 成功していて必要ならIP更新 if ( ui->renewIPCheckBox->isChecked() && ( stat == LoginWebAuth::LoginSucceeded || stat == LoginWebAuth::LoginSucceeded ) ) { renewIP(); } } void MainWidget::saveConfigSlot() { // save config // save check setting->setValue( "Repeat", ui->repeatCheckBox->isChecked() ); setting->setValue( "AutoMinimize", ui->autoToTrayCheckBox->isChecked() ); setting->setValue( "AutoStart", ui->autoStartCheckBox->isChecked() ); setting->setValue( "ConfigId", ui->saveIdCheckBox->isChecked() ); setting->setValue( "ConfigPass", ui->savePassCheckBox->isChecked() ); setting->setValue( "RepeatMin", ui->repatSpinBox->value() ); setting->setValue( "Auth", ui->serverNameEdit->text() ); setting->setValue( "AutoLogout", ui->autoLogoutCheckBox->isChecked() ); setting->setValue( "AutoRenewIP", ui->renewIPCheckBox->isChecked() ); setting->setValue( "RandomizeEnable", ui->randomizeCheckBox->isChecked() ); setting->setValue( "RandomizeRange", ui->randomizeSpinBox->value() ); // if need id,pass if ( ui->saveIdCheckBox->isChecked() ) { setting->setValue( "ID", ui->idEdit->text() ); } if ( ui->savePassCheckBox->isChecked() ) { setting->setValue( "Pass", ui->passEdit->text() ); } } void MainWidget::loadConfigSlot() { // load config // load check ui->repeatCheckBox->setChecked( setting->value( "Repeat" ).toBool() ); ui->autoToTrayCheckBox->setChecked( setting->value( "AutoMinimize" ).toBool() ); ui->autoStartCheckBox->setChecked( setting->value( "AutoStart" ).toBool() ); ui->saveIdCheckBox->setChecked( setting->value( "ConfigId" ).toBool() ); ui->savePassCheckBox->setChecked( setting->value( "ConfigPass" ).toBool() ); ui->repatSpinBox->setValue( setting->value( "RepeatMin" ).toInt() ); ui->serverNameEdit->setText( setting->value( "Auth" ).toString() ); ui->autoLogoutCheckBox->setChecked( setting->value( "AutoLogout" ).toBool() ); ui->renewIPCheckBox->setChecked( setting->value( "AutoRenewIP" ).toBool() ); ui->randomizeCheckBox->setChecked( setting->value( "RandomizeEnable" ).toBool() ); ui->randomizeSpinBox->setValue( setting->value( "RandomizeRange" ).toInt() ); // if need id,pass if ( ui->saveIdCheckBox->isChecked() ) { ui->idEdit->setText( setting->value( "ID" ).toString() ); } if ( ui->savePassCheckBox->isChecked() ) { ui->passEdit->setText( setting->value( "Pass" ).toString() ); } // do setting if ( ui->autoStartCheckBox->isChecked() ) { // 起動時に自動ログイン // Windowsの場合いったんIPをrenewする renewIP(); m_ipconfig->waitForFinished(); on_loginButton_clicked(); } if ( ui->autoToTrayCheckBox->isChecked() ) { // minimize to tray QTimer::singleShot( 100, this, SLOT(minimizeSlot()) ); } } void MainWidget::minimizeSlot() { // minimize to tray trayIcon->show(); /* trayIcon->showMessage( tr( "Minimize to tray" ), tr( "This application is still running. To quit please click this icon and select Close" ) ); */ hide(); } void MainWidget::updateStatusSlot() { // update status // update progress bar if ( timer.isActive() ) { ui->progressBar->setValue( ui->progressBar->value() - 1 ); } } void MainWidget::clearStatusSlot() { // clearStatus ui->progressBar->setValue( 0 ); } void MainWidget::sslErrorSlot(const QList<QSslError> &errors) { // sslError Slot QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() ); QString errString; // iOSでは不完全型となっているため直接アクセスしない #ifndef Q_OS_IOS foreach ( QSslError err, errors ) { errString += err.errorString() + "\n"; } #endif // 全エラー無視(本来は確認すべき) reply->ignoreSslErrors(); // view ssl error if ( isVisible() ) { QMessageBox::warning( this, tr( "Ssl warning" ), errString + tr( "\n\nThese \"SslError\" are ignored." ) ); } } void MainWidget::trayIconClickSlot( QSystemTrayIcon::ActivationReason reason ) { // tray icon clicked if ( reason == QSystemTrayIcon::Trigger ) { // Macの場合ここでhideすると落ちるためなにもしない #ifdef Q_OS_MAC return; #endif trayIcon->hide(); this->show(); } } void MainWidget::networkErrorSlot( QNetworkReply::NetworkError code ) { // network error Q_UNUSED( code ) if ( isVisible() ) { QMessageBox::warning( this, tr( "Network error" ), tr( "Some network error occurred" ) ); } } void MainWidget::checkIpSlot() { // check ip foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) ui->ipEdit->setText( address.toString() ); } } void MainWidget::renewIP() { // IPを更新する ( Windows only ) #ifdef Q_OS_WIN m_ipconfig->start( "ipconfig", QStringList() << "/renew" ); #endif } void MainWidget::on_aboutButton_clicked() { // aboutQt QMessageBox::aboutQt( this ); } void MainWidget::on_closeButton_clicked() { close(); } void MainWidget::on_stopTimerButton_clicked() { // stop timer timer.stop(); statusTimer.stop(); ui->stopTimerButton->setEnabled( false ); } void MainWidget::createTrayIcon() { // create tray icon // create menu trayMenu = new QMenu( this ); trayMenu->addAction( showAction ); trayMenu->addSeparator(); trayMenu->addAction( connectAction ); trayMenu->addAction( disconnectAction ); trayMenu->addSeparator(); trayMenu->addAction( closeAction ); // setup icon trayIcon = new QSystemTrayIcon( this ); trayIcon->setContextMenu( trayMenu ); trayIcon->setIcon( QIcon( ":/image/icon.png" ) ); trayIcon->setToolTip( tr( "QAutoLogin" ) ); // connect connect( trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconClickSlot(QSystemTrayIcon::ActivationReason)) ); } void MainWidget::createAction() { // create actions closeAction = new QAction( tr( "&Close" ), this ); connectAction = new QAction( tr( "&Login" ), this ); disconnectAction = new QAction( tr( "Log&out" ), this ); showAction = new QAction( tr( "&Show" ), this ); connect( closeAction, SIGNAL(triggered()), this, SLOT(close()) ); connect( connectAction, SIGNAL(triggered()), this, SLOT(on_loginButton_clicked()) ); connect( disconnectAction, SIGNAL(triggered()), this, SLOT(on_logoutButton_clicked()) ); connect( showAction, SIGNAL(triggered()), SLOT(show()) ); } void MainWidget::closeEvent(QCloseEvent *) { // close event if ( trayIcon->isVisible() ) { trayIcon->hide(); } // 必要ならログアウト if ( ui->autoLogoutCheckBox->isChecked() ) { // ログアウト処理が完了するまでブロック QEventLoop loop; connect( &webAuth, SIGNAL(finished(LoginWebAuth::AuthStatus)), &loop, SLOT(quit()) ); // ログアウト実行 logoutSlot(); // イベントループ開始 loop.exec(); } // ipconfigプロセスの終了を待つ m_ipconfig->waitForFinished(); } void MainWidget::on_saveConfigButton_clicked() { // save config button saveConfigSlot(); } void MainWidget::on_logoutButton_clicked() { // logout logoutSlot(); // disable timer timer.stop(); statusTimer.stop(); ui->stopTimerButton->setEnabled( false ); } void MainWidget::on_minimizePushButton_clicked() { minimizeSlot(); } void MainWidget::on_checkIpButton_clicked() { // check ip checkIpSlot(); } void MainWidget::on_renewIPButton_clicked() { // IPを再取得 renewIP(); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "dbmanager.h" #include <QDebug> #include <QFile> #include <QFileDialog> #include <QTextDocument> #include <QMessageBox> #include <QSettings> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // Find and remember location of journalSqlite.sqlite database // qDebug() << MySettings.fileName(); // qDebug() << MySettings.value("path").toString(); PATH = MySettings.value("path").toString(); // qDebug() << PATH << PATH.length(); if (PATH.length() == 0) { QString SelectedFile = QFileDialog::getOpenFileName( this, "Select journalSqlite.sqlite" ); if (!SelectedFile.isEmpty()) { // qDebug() << MySettings.value("path").toString(); PATH = SelectedFile; db = new DbManager(PATH); if (db->isOpen()) { if (db->isValidDatabase()) { db->getLastRecord(); ui->textEdit->setText(db->lastEntry); ui->dateEdit->setDate(QDate::fromString(db->lastDate,"yyyy-MM-dd")); MySettings.setValue("path", SelectedFile); } else { invalidMessage(); } } else { // qDebug() << "DB not open"; } } } else { db = new DbManager(PATH); if (db->isOpen()) { if (db->isValidDatabase()) { db->getLastRecord(); ui->textEdit->setText(db->lastEntry); ui->dateEdit->setDate(QDate::fromString(db->lastDate,"yyyy-MM-dd")); } else { invalidMessage(); } } } } MainWindow::~MainWindow() { delete ui; } void MainWindow::invalidMessage() { QMessageBox msgBox; msgBox.setText("You tried to open an invalid database without a table 'journal'" " with columns: ID, Date, Month, Day, Year, DayOfWeek, Entry \n" "Close the program and restart to load a valid database."); msgBox.exec(); PATH = ""; MySettings.setValue("path", PATH); } void MainWindow::on_writeButton_clicked() { QString dt = ui->dateEdit->date().toString("yyyy-MM-dd"); int id = ui->dateEdit->date().toJulianDay() - 2455711; QString month(QDate::longMonthName(ui->dateEdit->date().month())); int day = ui->dateEdit->date().day(); int year = ui->dateEdit->date().year(); QString dayOfWeek(QDate::longDayName(ui->dateEdit->date().day())); QString entry = ui->textEdit->toPlainText(); //qDebug() << "id" << id << "date" << dt << "month" << month // << "day" << day << "year" << year << "dayOfWeek" << dayOfWeek; db->writeRecord(id, dt, month,day, year, dayOfWeek, entry); } void MainWindow::on_dateEdit_dateChanged(const QDate &date) { ui->writeButton->setEnabled(true); db->getRecordOnDate(date); ui->textEdit->setText(db->lastEntry); } void MainWindow::on_similarDatesButton_clicked() { ui->writeButton->setEnabled(false); QString result = db->similarDateQuery(ui->dateEdit->date()); ui->textEdit->setText(result); } void MainWindow::on_searchButton_clicked() { ui->writeButton->setEnabled(false); QString term = ui->lineEdit->text(); QString result = db->searchTermQuery(term); ui->textEdit->setText(result); } void MainWindow::on_weightHistoryButton_clicked() { ui->writeButton->setEnabled(false); QMap<QString, QString> map = db->getWeightRecord(); QMapIterator<QString, QString> i(map); QString answer; QString filename = QFileDialog::getSaveFileName(this, "Save To CSV", "weightHistory.csv", "CSV files (.csv);;Zip files (.zip, *.7z)", 0, 0); // getting the filename (full path) QFile data(filename); if(data.open(QFile::WriteOnly |QFile::Truncate)) { QTextStream output(&data); while (i.hasNext()) { i.next(); answer.append(i.key() + " " + i.value() + "\n"); output << i.key() << "," << i.value().toFloat() << "\n"; // //qDebug() << i.key() << ": " << i.value() << endl; } } ui->textEdit->setText(answer); } void MainWindow::on_exportHtmlButton_clicked() { QString tmp = db->printAllRecords(); QTextDocument mdoc(tmp); QString filename = QFileDialog::getSaveFileName(this, "Save to HTML", "journal.html","html files (.html);" , 0, 0); // getting the filename (full path) QFile data(filename); if(data.open(QFile::WriteOnly |QFile::Truncate)) { QTextStream output(&data); output.setCodec( "utf-8" ); output << mdoc.toHtml("utf-8"); } } <commit_msg>fixed dayOfWeek write to database<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "dbmanager.h" #include <QDebug> #include <QFile> #include <QFileDialog> #include <QTextDocument> #include <QMessageBox> #include <QSettings> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // Find and remember location of journalSqlite.sqlite database // qDebug() << MySettings.fileName(); // qDebug() << MySettings.value("path").toString(); PATH = MySettings.value("path").toString(); // qDebug() << PATH << PATH.length(); if (PATH.length() == 0) { QString SelectedFile = QFileDialog::getOpenFileName( this, "Select journalSqlite.sqlite" ); if (!SelectedFile.isEmpty()) { // qDebug() << MySettings.value("path").toString(); PATH = SelectedFile; db = new DbManager(PATH); if (db->isOpen()) { if (db->isValidDatabase()) { db->getLastRecord(); ui->textEdit->setText(db->lastEntry); ui->dateEdit->setDate(QDate::fromString(db->lastDate,"yyyy-MM-dd")); MySettings.setValue("path", SelectedFile); } else { invalidMessage(); } } else { // qDebug() << "DB not open"; } } } else { db = new DbManager(PATH); if (db->isOpen()) { if (db->isValidDatabase()) { db->getLastRecord(); ui->textEdit->setText(db->lastEntry); ui->dateEdit->setDate(QDate::fromString(db->lastDate,"yyyy-MM-dd")); } else { invalidMessage(); } } } } MainWindow::~MainWindow() { delete ui; } void MainWindow::invalidMessage() { QMessageBox msgBox; msgBox.setText("You tried to open an invalid database without a table 'journal'" " with columns: ID, Date, Month, Day, Year, DayOfWeek, Entry \n" "Close the program and restart to load a valid database."); msgBox.exec(); PATH = ""; MySettings.setValue("path", PATH); } void MainWindow::on_writeButton_clicked() { QString dt = ui->dateEdit->date().toString("yyyy-MM-dd"); int id = ui->dateEdit->date().toJulianDay() - 2455711; QString month(QDate::longMonthName(ui->dateEdit->date().month())); int day = ui->dateEdit->date().day(); int year = ui->dateEdit->date().year(); QString dayOfWeek(QDate::longDayName(ui->dateEdit->date().dayOfWeek())); QString entry = ui->textEdit->toPlainText(); //qDebug() << "id" << id << "date" << dt << "month" << month // << "day" << day << "year" << year << "dayOfWeek" << dayOfWeek; db->writeRecord(id, dt, month,day, year, dayOfWeek, entry); } void MainWindow::on_dateEdit_dateChanged(const QDate &date) { ui->writeButton->setEnabled(true); db->getRecordOnDate(date); ui->textEdit->setText(db->lastEntry); } void MainWindow::on_similarDatesButton_clicked() { ui->writeButton->setEnabled(false); QString result = db->similarDateQuery(ui->dateEdit->date()); ui->textEdit->setText(result); } void MainWindow::on_searchButton_clicked() { ui->writeButton->setEnabled(false); QString term = ui->lineEdit->text(); QString result = db->searchTermQuery(term); ui->textEdit->setText(result); } void MainWindow::on_weightHistoryButton_clicked() { ui->writeButton->setEnabled(false); QMap<QString, QString> map = db->getWeightRecord(); QMapIterator<QString, QString> i(map); QString answer; QString filename = QFileDialog::getSaveFileName(this, "Save To CSV", "weightHistory.csv", "CSV files (.csv);;Zip files (.zip, *.7z)", 0, 0); // getting the filename (full path) QFile data(filename); if(data.open(QFile::WriteOnly |QFile::Truncate)) { QTextStream output(&data); while (i.hasNext()) { i.next(); answer.append(i.key() + " " + i.value() + "\n"); output << i.key() << "," << i.value().toFloat() << "\n"; // //qDebug() << i.key() << ": " << i.value() << endl; } } ui->textEdit->setText(answer); } void MainWindow::on_exportHtmlButton_clicked() { QString tmp = db->printAllRecords(); QTextDocument mdoc(tmp); QString filename = QFileDialog::getSaveFileName(this, "Save to HTML", "journal.html","html files (.html);" , 0, 0); // getting the filename (full path) QFile data(filename); if(data.open(QFile::WriteOnly |QFile::Truncate)) { QTextStream output(&data); output.setCodec( "utf-8" ); output << mdoc.toHtml("utf-8"); } } <|endoftext|>
<commit_before>/** * @file DemangleTest.cpp * @brief Demangle class tester. * @author zer0 * @date 2017-09-02 */ #include <gtest/gtest.h> #include <libtbag/debug/Demangle.hpp> using namespace libtbag; using namespace libtbag::debug; TEST(DemangleTest, Default) { std::string const TEST_NAME = "_ZN3FooC1Ev"; std::string const RESULT_NAME = "Foo::Foo()"; std::string const ABI_DEMANGLE = getAbiDemangle(TEST_NAME.c_str()); std::string const DEMANGLE_NAME = getDemangle(TEST_NAME.c_str()); std::cout << "getAbiDemangle(" << TEST_NAME << "): " << ABI_DEMANGLE << std::endl; std::cout << "getDemangle(" << TEST_NAME << "): " << DEMANGLE_NAME << std::endl; ASSERT_EQ(RESULT_NAME, DEMANGLE_NAME); } TEST(DemangleTest, Demangler) { ASSERT_STREQ("f()", getDemangle("_Z1fv").c_str()); ASSERT_STREQ("f(int)", getDemangle("_Z1fi").c_str()); ASSERT_STREQ("Foo::Bar()", getDemangle("_ZN3Foo3BarEv").c_str()); ASSERT_STREQ("operator%(X, X)", getDemangle("_Zrm1XS_").c_str()); ASSERT_STREQ("Foo::Foo()", getDemangle("_ZN3FooC1Ev").c_str()); } TEST(DemangleTest, ComplexDemangle) { char const * const ERROR_STRING = "_ZNSt3__114__thread_proxyINS_5tupleIJNS_10unique_ptrINS_15__thread_structENS_14default_deleteIS3_EEEEZN23WorkerTest_Default_Test8TestBodyEvE3$_0EEEEEPvSA_+497"; //std::string const ABI_DEMANGLE = getAbiDemangle(ERROR_STRING); //std::string const DEMANGLE_NAME = getDemangle(ERROR_STRING); //std::cout << "ABI DEMANGLE: " << ABI_DEMANGLE << std::endl; //std::cout << "DEMANGLE: " << DEMANGLE_NAME << std::endl; } <commit_msg>Create DemangleTest.EnableAbiDemangle tester.<commit_after>/** * @file DemangleTest.cpp * @brief Demangle class tester. * @author zer0 * @date 2017-09-02 */ #include <gtest/gtest.h> #include <libtbag/debug/Demangle.hpp> using namespace libtbag; using namespace libtbag::debug; TEST(DemangleTest, EnableAbiDemangle) { std::cout << "Enable ABI Demangle: " << enableAbiDemangle() << std::endl; } TEST(DemangleTest, Default) { std::string const TEST_NAME = "_ZN3FooC1Ev"; std::string const RESULT_NAME = "Foo::Foo()"; std::string const ABI_DEMANGLE = getAbiDemangle(TEST_NAME.c_str()); std::string const GTEST_DEMANGLE_NAME = getGtestDemangle(TEST_NAME.c_str()); std::cout << "getAbiDemangle(" << TEST_NAME << "): " << ABI_DEMANGLE << std::endl; std::cout << "getGtestDemangle(" << TEST_NAME << "): " << GTEST_DEMANGLE_NAME << std::endl; ASSERT_EQ(RESULT_NAME, GTEST_DEMANGLE_NAME); } TEST(DemangleTest, Demangler) { EXPECT_STREQ("f()", getDemangle("_Z1fv").c_str()); EXPECT_STREQ("f(int)", getDemangle("_Z1fi").c_str()); EXPECT_STREQ("Foo::Bar()", getDemangle("_ZN3Foo3BarEv").c_str()); EXPECT_STREQ("operator%(X, X)", getDemangle("_Zrm1XS_").c_str()); EXPECT_STREQ("Foo::Foo()", getDemangle("_ZN3FooC1Ev").c_str()); } TEST(DemangleTest, ComplexDemangle) { char const * const ERROR_STRING = "_ZNSt3__114__thread_proxyINS_5tupleIJNS_10unique_ptrINS_15__thread_structENS_14default_deleteIS3_EEEEZN23WorkerTest_Default_Test8TestBodyEvE3$_0EEEEEPvSA_+497"; //std::string const ABI_DEMANGLE = getAbiDemangle(ERROR_STRING); //std::string const DEMANGLE_NAME = getDemangle(ERROR_STRING); //std::cout << "ABI DEMANGLE: " << ABI_DEMANGLE << std::endl; //std::cout << "DEMANGLE: " << DEMANGLE_NAME << std::endl; } <|endoftext|>
<commit_before>#include <cstring> #include <iostream> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/wait.h> #include <sys/types.h> #include "words.h" //implementation of Node Node::Node(string token) { this->content = token; } void Node::setNext(Node* n) { this->next = n; } Node* Node::getNext() { return this->next; } string Node::getContent() { return this->content; } //state = 0 means success //state = -1 means fail void Node::run(int state) { //BEGIN: if the node is a connector if (content == "||") { if (state == 0) { next->run(-1); }else { next->run(0); } return; } if (content == "&&") { if (state == 0) { next->run(0); }else { next->run(-1); } return; } if (content == ";") { if (next == 0) { }else { next->run(0); } return; } //END: if the node is a connector //Then the node is a bash command if (state == 0){ char* test = new char[content.size()+1]; char* cstr = new char[content.size()+1]; char *pch1, *pch2; int count = 0, i = 0; //we're cutting string up twice //first time is to know how many slots in cmd do we need //second time creates the actual char** cmd into execute() strcpy(test, content.c_str()); strcpy(cstr, content.c_str()); pch1 = strtok(test, " "); while (pch1 != NULL) { count++; pch1 = strtok(NULL, " "); } char* cmd[count+1]; pch2 = strtok(cstr, " "); while (pch2 != NULL) { cmd[i] = pch2; i++; pch2 = strtok(NULL, " "); } cmd[count] = NULL; int status = execute(cmd); if (next == 0) return; next->run(status); delete[] test; delete[] cstr; }else { if (next == 0) return; next->run(-1); } } //implementation of Line Line::Line(const vector<string> &input) { if (input.empty()) return; Node *a; head = new Node(input.at(0)); a = head; for (int i = 1; i < input.size(); i++) { a->setNext(new Node(input.at(i))); a = a->getNext(); } a->setNext(0); } Line::~Line() { Node* a = head; Node* x; while (a != 0) { x = a; a = a->getNext(); delete x; } } void Line::run(){ head->run(0); } void Line::printLine() { Node* a = head; while (a != 0) { cout << a->getContent() << endl; a = a->getNext(); } } //Executes a bash command, returns int execute(char* cmd[]) { pid_t pid; int status; int output = 0; int fd[2]; //Wangho: This is a pipe made for passing variable // (this case: output) between parent and child // process. if (pipe(fd) == -1) { perror("Pipe error"); } pid = fork(); if (pid < 0) { perror("fork() function error"); }else if (pid == 0) { //Wangho: Close the read function of pipe if (close(fd[0] == -1)) { perror("Pipe closing error [0]"); } //Wangho: This is the child process output = execvp(cmd[0], cmd); //Wangho: Will only be here if execp() fail, which means output failed if (write(fd[1], &output, sizeof(output)) == -1) { perror("Pipe writing error"); } perror("Invalid command"); }else if (pid > 0) { //Wangho: Close the write function of pipe if (close(fd[1])) { perror("Pipe closing error [1]"); } //Wangho: This is the parent process waitpid(pid, &status, 0); //Wangho: When child process is fully returned if(WIFEXITED(status)){ //Wangho: Take the output value; if execvp fail, it returns -1 if (read(fd[0], &output, sizeof(output)) == -1) { perror("Pipe reading error"); } return output; } } } int main(){ vector<string> ss; ss.push_back("ls -a"); ss.push_back("&&"); ss.push_back("pw"); ss.push_back("||"); ss.push_back("echo hello world"); Line abc(ss); abc.run(); return 0; } <commit_msg>slight mod<commit_after>#include <cstring> #include <iostream> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/wait.h> #include <sys/types.h> #include "words.h" //implementation of Node Node::Node(string token) { this->content = token; } void Node::setNext(Node* n) { this->next = n; } Node* Node::getNext() { return this->next; } string Node::getContent() { return this->content; } //state = 0 means success //state = -1 means fail void Node::run(int state) { //BEGIN: if the node is a connector if (content == "||") { if (state == 0) { next->run(-1); }else { next->run(0); } return; } if (content == "&&") { if (state == 0) { next->run(0); }else { next->run(-1); } return; } if (content == ";") { if (next == 0) { }else { next->run(0); } return; } //END: if the node is a connector //Then the node is a bash command if (state == 0){ char* test = new char[content.size()+1]; char* cstr = new char[content.size()+1]; char *pch1, *pch2; int count = 0, i = 0; //we're cutting string up twice //first time is to know how many slots in cmd do we need //second time creates the actual char** cmd into execute() strcpy(test, content.c_str()); strcpy(cstr, content.c_str()); pch1 = strtok(test, " "); while (pch1 != NULL) { count++; pch1 = strtok(NULL, " "); } char* cmd[count+1]; pch2 = strtok(cstr, " "); while (pch2 != NULL) { cmd[i] = pch2; i++; pch2 = strtok(NULL, " "); } cmd[count] = NULL; int status = execute(cmd); if (next == 0) return; next->run(status); delete[] test; delete[] cstr; }else { if (next == 0) return; next->run(-1); } } //implementation of Line Line::Line(const vector<string> &input) { if (input.empty()) return; Node *a; head = new Node(input.at(0)); a = head; for (int i = 1; i < input.size(); i++) { a->setNext(new Node(input.at(i))); a = a->getNext(); } a->setNext(0); } Line::~Line() { Node* a = head; Node* x; while (a != 0) { x = a; a = a->getNext(); delete x; } } void Line::run(){ head->run(0); } void Line::printLine() { Node* a = head; while (a != 0) { cout << a->getContent() << endl; a = a->getNext(); } } //Executes a bash command, returns int execute(char* cmd[]) { pid_t pid; int status; int output = 0; int fd[2]; //Wangho: This is a pipe made for passing variable // (this case: output) between parent and child // process. if (pipe(fd) == -1) { perror("Pipe error"); } pid = fork(); if (pid < 0) { perror("fork() function error"); }else if (pid == 0) { //Wangho: Close the read function of pipe if (close(fd[0] == -1)) { perror("Pipe closing error [0]"); } //Wangho: This is the child process output = execvp(cmd[0], cmd); //Wangho: Will only be here if execp() fail, which means output failed if (write(fd[1], &output, sizeof(output)) == -1) { perror("Pipe writing error"); } perror(cmd[0]); }else if (pid > 0) { //Wangho: Close the write function of pipe if (close(fd[1])) { perror("Pipe closing error [1]"); } //Wangho: This is the parent process waitpid(pid, &status, 0); //Wangho: When child process is fully returned if(WIFEXITED(status)){ //Wangho: Take the output value; if execvp fail, it returns -1 if (read(fd[0], &output, sizeof(output)) == -1) { perror("Pipe reading error"); } return output; } } } int main(){ vector<string> ss; ss.push_back("ls -a"); ss.push_back("&&"); ss.push_back("ls -e"); ss.push_back("||"); ss.push_back("echo hello world"); Line abc(ss); abc.run(); return 0; } <|endoftext|>
<commit_before>//============================================================================== // Collapsable widget //============================================================================== #include "collapsablewidget.h" #include "coreutils.h" //============================================================================== #include <QLabel> #include <QLayout> #include <QToolButton> //============================================================================== namespace OpenCOR { namespace Core { //============================================================================== void CollapsableWidget::constructor(const QString &pTitle, QWidget *pBody) { // Some initialisations mBody = pBody; // Create a vertical layout which will contain our header and body QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setMargin(0); mainLayout->setSpacing(0); // Create our header QWidget *header = new QWidget(this); QHBoxLayout *headerLayout = new QHBoxLayout(header); headerLayout->setMargin(0); headerLayout->setSpacing(0); mTitle = new QLabel(pTitle, header); mButton = new QToolButton(header); #ifdef Q_WS_MAC mTitle->setAlignment(Qt::AlignCenter); #endif int iconSize = 0.4*mTitle->height(); mButton->setIconSize(QSize(iconSize, iconSize)); connect(mButton, SIGNAL(clicked()), this, SLOT(toggleCollapsableState())); #ifdef Q_WS_MAC headerLayout->addWidget(mButton); #endif headerLayout->addWidget(mTitle); #ifndef Q_WS_MAC headerLayout->addWidget(mButton); #endif header->setLayout(headerLayout); // Create our separator mSeparator = Core::newLineWidget(this); // Update our GUI by showing our widget collapsed or not, depdending on // whether there is a body updateGui(!pBody); // Populate our main layout mainLayout->addWidget(header); mainLayout->addWidget(mSeparator); if (pBody) mainLayout->addWidget(pBody); else mSeparator->hide(); // Apply the main layout to ourselves setLayout(mainLayout); } //============================================================================== CollapsableWidget::CollapsableWidget(const QString &pTitle, QWidget *pBody, QWidget *pParent) : QWidget(pParent), CommonWidget(pParent) { // Construct our object constructor(pTitle, pBody); } //============================================================================== CollapsableWidget::CollapsableWidget(QWidget *pParent) : QWidget(pParent), CommonWidget(pParent) { // Construct our object constructor(); } //============================================================================== QSize CollapsableWidget::sizeHint() const { // Suggest a default size for our collapsable widget return defaultSize(0); } //============================================================================== QString CollapsableWidget::title() const { // Return our title return mTitle->text(); } //============================================================================== void CollapsableWidget::setTitle(const QString &pTitle) { // Set our title if (pTitle.compare(mTitle->text())) mTitle->setText(pTitle); } //============================================================================== QWidget * CollapsableWidget::body() const { // Return our body return mBody; } //============================================================================== void CollapsableWidget::setBody(QWidget *pBody) { // Set our body if (pBody != mBody) { bool bodyBefore = mBody; if (mBody) layout()->removeWidget(mBody); mBody = pBody; if (pBody) { layout()->addWidget(pBody); // Update our GUI, using the previous collapsable state of our // widget, in case there was already a body before, or by asking // it to be uncollapsed now that there is a body updateGui(bodyBefore?mCollapsed:false); } else { // There is no body (still or anymore), so collapse ourselves updateGui(true); } } } //============================================================================== void CollapsableWidget::setCollapsed(const bool &pCollapsed) { // Collapse or uncollapse ourselves, if needed if (pCollapsed != mCollapsed) updateGui(pCollapsed); } //============================================================================== bool CollapsableWidget::isCollapsed() const { // Return wheter we are collapsed return mCollapsed; } //============================================================================== void CollapsableWidget::updateGui(const bool &pCollapsed) { // Update our widget's GUI mCollapsed = pCollapsed; if (pCollapsed) { #ifdef Q_WS_MAC mButton->setIcon(QIcon(":/oxygen/actions/arrow-right.png")); #else mButton->setIcon(QIcon(":/oxygen/actions/arrow-left.png")); #endif } else { mButton->setIcon(QIcon(":/oxygen/actions/arrow-down.png")); } mSeparator->setVisible(!pCollapsed); if (mBody) mBody->setVisible(!pCollapsed); mButton->setEnabled(mBody); } //============================================================================== void CollapsableWidget::toggleCollapsableState() { // Toggle the collapsable state of our widget and update its GUI updateGui(!mCollapsed); } //============================================================================== } // namespace Core } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some work on a collpsable widget as part of our work on the SingleCellSimulation plugin (#112).<commit_after>//============================================================================== // Collapsable widget //============================================================================== #include "collapsablewidget.h" #include "coreutils.h" //============================================================================== #include <QLabel> #include <QLayout> #include <QToolButton> //============================================================================== namespace OpenCOR { namespace Core { //============================================================================== void CollapsableWidget::constructor(const QString &pTitle, QWidget *pBody) { // Some initialisations mBody = pBody; // Create a vertical layout which will contain our header and body QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setMargin(0); mainLayout->setSpacing(0); // Create our header QWidget *header = new QWidget(this); QHBoxLayout *headerLayout = new QHBoxLayout(header); headerLayout->setMargin(0); headerLayout->setSpacing(0); mTitle = new QLabel(pTitle, header); mButton = new QToolButton(header); #ifdef Q_WS_MAC mTitle->setAlignment(Qt::AlignCenter); #endif int iconSize = 0.4*mTitle->height(); mButton->setIconSize(QSize(iconSize, iconSize)); connect(mButton, SIGNAL(clicked()), this, SLOT(toggleCollapsableState())); #ifdef Q_WS_MAC headerLayout->addWidget(mButton); #endif headerLayout->addWidget(mTitle); #ifndef Q_WS_MAC headerLayout->addWidget(mButton); #endif header->setLayout(headerLayout); // Create our separator mSeparator = Core::newLineWidget(this); // Populate our main layout mainLayout->addWidget(header); mainLayout->addWidget(mSeparator); if (pBody) mainLayout->addWidget(pBody); else mSeparator->hide(); // Apply the main layout to ourselves setLayout(mainLayout); // Update our GUI by showing our widget collapsed or not, depdending on // whether there is a body updateGui(!pBody); } //============================================================================== CollapsableWidget::CollapsableWidget(const QString &pTitle, QWidget *pBody, QWidget *pParent) : QWidget(pParent), CommonWidget(pParent) { // Construct our object constructor(pTitle, pBody); } //============================================================================== CollapsableWidget::CollapsableWidget(QWidget *pParent) : QWidget(pParent), CommonWidget(pParent) { // Construct our object constructor(); } //============================================================================== QSize CollapsableWidget::sizeHint() const { // Suggest a default size for our collapsable widget return defaultSize(0); } //============================================================================== QString CollapsableWidget::title() const { // Return our title return mTitle->text(); } //============================================================================== void CollapsableWidget::setTitle(const QString &pTitle) { // Set our title if (pTitle.compare(mTitle->text())) mTitle->setText(pTitle); } //============================================================================== QWidget * CollapsableWidget::body() const { // Return our body return mBody; } //============================================================================== void CollapsableWidget::setBody(QWidget *pBody) { // Set our body if (pBody != mBody) { bool bodyBefore = mBody; if (mBody) layout()->removeWidget(mBody); mBody = pBody; if (pBody) { layout()->addWidget(pBody); // Update our GUI, using the previous collapsable state of our // widget, in case there was already a body before, or by asking // it to be uncollapsed now that there is a body updateGui(bodyBefore?mCollapsed:false); } else { // There is no body (still or anymore), so collapse ourselves updateGui(true); } } } //============================================================================== void CollapsableWidget::setCollapsed(const bool &pCollapsed) { // Collapse or uncollapse ourselves, if needed if (pCollapsed != mCollapsed) updateGui(pCollapsed); } //============================================================================== bool CollapsableWidget::isCollapsed() const { // Return wheter we are collapsed return mCollapsed; } //============================================================================== void CollapsableWidget::updateGui(const bool &pCollapsed) { // Update our widget's GUI mCollapsed = pCollapsed; if (pCollapsed) { #ifdef Q_WS_MAC mButton->setIcon(QIcon(":/oxygen/actions/arrow-right.png")); #else mButton->setIcon(QIcon(":/oxygen/actions/arrow-left.png")); #endif } else { mButton->setIcon(QIcon(":/oxygen/actions/arrow-down.png")); } mSeparator->setVisible(!pCollapsed); if (mBody) mBody->setVisible(!pCollapsed); mButton->setEnabled(mBody); } //============================================================================== void CollapsableWidget::toggleCollapsableState() { // Toggle the collapsable state of our widget and update its GUI updateGui(!mCollapsed); } //============================================================================== } // namespace Core } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/location_bar/star_view.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/command_updater.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/browser_dialogs.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "grit/theme_resources_standard.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" StarView::StarView(CommandUpdater* command_updater) : command_updater_(command_updater) { set_id(VIEW_ID_STAR_BUTTON); SetToggled(false); set_accessibility_focusable(true); } StarView::~StarView() { } void StarView::SetToggled(bool on) { SetTooltipText(UTF16ToWide(l10n_util::GetStringUTF16( on ? IDS_TOOLTIP_STARRED : IDS_TOOLTIP_STAR))); SetImage(ResourceBundle::GetSharedInstance().GetBitmapNamed( on ? IDR_STAR_LIT : IDR_STAR)); } void StarView::GetAccessibleState(ui::AccessibleViewState* state) { state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_STAR); state->role = ui::AccessibilityTypes::ROLE_PUSHBUTTON; } bool StarView::GetTooltipText(const gfx::Point& p, std::wstring* tooltip) { // Don't show tooltip to distract user if BookmarkBubbleView is showing. if (browser::IsBookmarkBubbleViewShowing()) return false; return ImageView::GetTooltipText(p, tooltip); } bool StarView::OnMousePressed(const views::MouseEvent& event) { // We want to show the bubble on mouse release; that is the standard behavior // for buttons. return true; } void StarView::OnMouseReleased(const views::MouseEvent& event) { if (HitTest(event.location())) command_updater_->ExecuteCommand(IDC_BOOKMARK_PAGE); } bool StarView::OnKeyPressed(const views::KeyEvent& event) { if (event.key_code() == ui::VKEY_SPACE || event.key_code() == ui::VKEY_RETURN) { command_updater_->ExecuteCommand(IDC_BOOKMARK_PAGE); return true; } return false; } void StarView::BubbleClosing(Bubble* bubble, bool closed_by_escape) { } bool StarView::CloseOnEscape() { return true; } bool StarView::FadeInOnShow() { return false; } <commit_msg>views/bookmarks: Right click on bookmark star should do nothing.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/location_bar/star_view.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/command_updater.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/browser_dialogs.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "grit/theme_resources_standard.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" StarView::StarView(CommandUpdater* command_updater) : command_updater_(command_updater) { set_id(VIEW_ID_STAR_BUTTON); SetToggled(false); set_accessibility_focusable(true); } StarView::~StarView() { } void StarView::SetToggled(bool on) { SetTooltipText(UTF16ToWide(l10n_util::GetStringUTF16( on ? IDS_TOOLTIP_STARRED : IDS_TOOLTIP_STAR))); SetImage(ResourceBundle::GetSharedInstance().GetBitmapNamed( on ? IDR_STAR_LIT : IDR_STAR)); } void StarView::GetAccessibleState(ui::AccessibleViewState* state) { state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_STAR); state->role = ui::AccessibilityTypes::ROLE_PUSHBUTTON; } bool StarView::GetTooltipText(const gfx::Point& p, std::wstring* tooltip) { // Don't show tooltip to distract user if BookmarkBubbleView is showing. if (browser::IsBookmarkBubbleViewShowing()) return false; return ImageView::GetTooltipText(p, tooltip); } bool StarView::OnMousePressed(const views::MouseEvent& event) { // We want to show the bubble on mouse release; that is the standard behavior // for buttons. return true; } void StarView::OnMouseReleased(const views::MouseEvent& event) { if (event.IsOnlyLeftMouseButton() && HitTest(event.location())) command_updater_->ExecuteCommand(IDC_BOOKMARK_PAGE); } bool StarView::OnKeyPressed(const views::KeyEvent& event) { if (event.key_code() == ui::VKEY_SPACE || event.key_code() == ui::VKEY_RETURN) { command_updater_->ExecuteCommand(IDC_BOOKMARK_PAGE); return true; } return false; } void StarView::BubbleClosing(Bubble* bubble, bool closed_by_escape) { } bool StarView::CloseOnEscape() { return true; } bool StarView::FadeInOnShow() { return false; } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this // source code is governed by a BSD-style license that can be found in the // LICENSE file. #include "chrome/renderer/renderer_sandbox_support_linux.h" #include "base/global_descriptors_posix.h" #include "base/pickle.h" #include "base/unix_domain_socket_posix.h" #include "chrome/common/chrome_descriptors.h" #include "chrome/common/sandbox_methods_linux.h" namespace renderer_sandbox_support { std::string getFontFamilyForCharacters(const uint16_t* utf16, size_t num_utf16) { Pickle request; request.WriteInt(LinuxSandbox::METHOD_GET_FONT_FAMILY_FOR_CHARS); request.WriteInt(num_utf16); for (size_t i = 0; i < num_utf16; ++i) request.WriteUInt32(utf16[i]); uint8_t buf[512]; const int sandbox_fd = kSandboxIPCChannel + base::GlobalDescriptors::kBaseDescriptor; const ssize_t n = base::SendRecvMsg(sandbox_fd, buf, sizeof(buf), NULL, request); std::string family_name; if (n != -1) { Pickle reply(reinterpret_cast<char*>(buf), n); void* pickle_iter = NULL; reply.ReadString(&pickle_iter, &family_name); } return family_name; } } // namespace render_sandbox_support <commit_msg>Revert "Revert "Linux: add LOG(FATAL) to try and catch an error.""<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this // source code is governed by a BSD-style license that can be found in the // LICENSE file. #include "chrome/renderer/renderer_sandbox_support_linux.h" #include "base/global_descriptors_posix.h" #include "base/pickle.h" #include "base/unix_domain_socket_posix.h" #include "chrome/common/chrome_descriptors.h" #include "chrome/common/sandbox_methods_linux.h" namespace renderer_sandbox_support { std::string getFontFamilyForCharacters(const uint16_t* utf16, size_t num_utf16) { Pickle request; request.WriteInt(LinuxSandbox::METHOD_GET_FONT_FAMILY_FOR_CHARS); request.WriteInt(num_utf16); for (size_t i = 0; i < num_utf16; ++i) request.WriteUInt32(utf16[i]); uint8_t buf[512]; const int sandbox_fd = kSandboxIPCChannel + base::GlobalDescriptors::kBaseDescriptor; const ssize_t n = base::SendRecvMsg(sandbox_fd, buf, sizeof(buf), NULL, request); std::string family_name; if (n != -1) { Pickle reply(reinterpret_cast<char*>(buf), n); void* pickle_iter = NULL; reply.ReadString(&pickle_iter, &family_name); } if (!family_name.size()) { LOG(ERROR) << "Starting code point dump:"; for (size_t i = 0; i < num_utf16; ++i) LOG(ERROR) << " " << utf16[i]; LOG(FATAL) << "Bug caught: requested font family for " << num_utf16 << " code points and got an empty string on return"; } return family_name; } } // namespace render_sandbox_support <|endoftext|>
<commit_before>/*++ Module Name: FASTA.cpp Abstract: FASTA reader Authors: Bill Bolosky, August, 2011 Environment: User mode service. Revision History: Adapted from Matei Zaharia's Scala implementation. --*/ #include "stdafx.h" #include "Compat.h" #include "FASTA.h" using namespace std; const Genome * ReadFASTAGenome( const char *fileName, const char *pieceNameTerminatorCharacters, bool spaceIsAPieceNameTerminator, unsigned chromosomePaddingSize) { // // We need to know a bound on the size of the genome before we create the Genome object. // A bound is the number of bytes in the FASTA file, because we store at most one base per // byte. Get the file size to use for this bound. // _int64 fileSize = QueryFileSize(fileName); if (fileSize >> 32 != 0) { fprintf(stderr,"This tool only works with genomes with 2^32 bases or fewer.\n"); return NULL; } FILE *fastaFile = fopen(fileName, "r"); if (fastaFile == NULL) { fprintf(stderr,"Unable to open FASTA file '%s' (even though we already got its size)\n",fileName); return NULL; } const size_t lineBufferSize = 4096; char lineBuffer[lineBufferSize]; // // Count the chromosomes // unsigned nChromosomes = 0; while (NULL != fgets(lineBuffer,lineBufferSize,fastaFile)) { if (lineBuffer[0] == '>') { nChromosomes++; } } rewind(fastaFile); Genome *genome = new Genome((unsigned) fileSize + (nChromosomes+1) * chromosomePaddingSize, (unsigned)fileSize + (nChromosomes+1) * chromosomePaddingSize, chromosomePaddingSize); char *paddingBuffer = new char[chromosomePaddingSize+1]; for (unsigned i = 0; i < chromosomePaddingSize; i++) { paddingBuffer[i] = 'n'; } paddingBuffer[chromosomePaddingSize] = '\0'; while (NULL != fgets(lineBuffer,lineBufferSize,fastaFile)) { if (lineBuffer[0] == '>') { // // A new chromosome. Add in the padding first. // genome->addData(paddingBuffer); // // Now supply the chromosome name. // if (NULL != pieceNameTerminatorCharacters) { for (int i = 0; i < strlen(pieceNameTerminatorCharacters); i++) { char *terminator = strchr(lineBuffer+1, pieceNameTerminatorCharacters[i]); if (NULL != terminator) { *terminator = '\0'; } } } if (spaceIsAPieceNameTerminator) { char *terminator = strchr(lineBuffer, ' '); if (NULL != terminator) { *terminator = '\0'; } terminator = strchr(lineBuffer, '\t'); if (NULL != terminator) { *terminator = '\0'; } } char *terminator = strchr(lineBuffer, '\n'); if (NULL != terminator) { *terminator = '\0'; } genome->startContig(lineBuffer+1); } else { // // Convert it to upper case and truncate the newline before adding it to the genome. // char *newline = strchr(lineBuffer, '\n'); if (NULL != newline) { *newline = 0; } // // But convert any 'N' to 'n'. This is so we don't match the N from the genome with N // in reads (where we just do a straight text comparison. // size_t lineLen = strlen(lineBuffer); for (unsigned i = 0; i < lineLen; i++) { lineBuffer[i] = toupper(lineBuffer[i]); } for (unsigned i = 0; i < lineLen; i++) { if ('N' == lineBuffer[i]) { lineBuffer[i] = 'n'; } } genome->addData(lineBuffer); } } // // And finally add padding at the end of the genome. // genome->addData(paddingBuffer); genome->fillInContigLengths(); genome->sortContigsByName(); fclose(fastaFile); delete [] paddingBuffer; return genome; } // // TODO: Reduce code duplication with the mutator. // bool AppendFASTAGenome(const Genome *genome, FILE *fasta, const char *prefix="") { int nContigs = genome->getNumContigs(); const Genome::Contig *contigs = genome->getContigs(); for (int i = 0; i < nContigs; ++i) { const Genome::Contig &contig = contigs[i]; unsigned start = contig.beginningOffset; unsigned end = i + 1 < nContigs ? contigs[i + 1].beginningOffset : genome->getCountOfBases(); unsigned size = end - start; const char *bases = genome->getSubstring(start, size); fprintf(fasta, ">%s%s\n", prefix, contig.name); fwrite(bases, 1, size, fasta); fputc('\n', fasta); } return !ferror(fasta); } <commit_msg>Allow DOS line endings in FASTA on Linux<commit_after>/*++ Module Name: FASTA.cpp Abstract: FASTA reader Authors: Bill Bolosky, August, 2011 Environment: User mode service. Revision History: Adapted from Matei Zaharia's Scala implementation. --*/ #include "stdafx.h" #include "Compat.h" #include "FASTA.h" using namespace std; const Genome * ReadFASTAGenome( const char *fileName, const char *pieceNameTerminatorCharacters, bool spaceIsAPieceNameTerminator, unsigned chromosomePaddingSize) { // // We need to know a bound on the size of the genome before we create the Genome object. // A bound is the number of bytes in the FASTA file, because we store at most one base per // byte. Get the file size to use for this bound. // _int64 fileSize = QueryFileSize(fileName); if (fileSize >> 32 != 0) { fprintf(stderr,"This tool only works with genomes with 2^32 bases or fewer.\n"); return NULL; } FILE *fastaFile = fopen(fileName, "r"); if (fastaFile == NULL) { fprintf(stderr,"Unable to open FASTA file '%s' (even though we already got its size)\n",fileName); return NULL; } const size_t lineBufferSize = 4096; char lineBuffer[lineBufferSize]; // // Count the chromosomes // unsigned nChromosomes = 0; while (NULL != fgets(lineBuffer,lineBufferSize,fastaFile)) { if (lineBuffer[0] == '>') { nChromosomes++; } } rewind(fastaFile); Genome *genome = new Genome((unsigned) fileSize + (nChromosomes+1) * chromosomePaddingSize, (unsigned)fileSize + (nChromosomes+1) * chromosomePaddingSize, chromosomePaddingSize); char *paddingBuffer = new char[chromosomePaddingSize+1]; for (unsigned i = 0; i < chromosomePaddingSize; i++) { paddingBuffer[i] = 'n'; } paddingBuffer[chromosomePaddingSize] = '\0'; while (NULL != fgets(lineBuffer,lineBufferSize,fastaFile)) { if (lineBuffer[0] == '>') { // // A new chromosome. Add in the padding first. // genome->addData(paddingBuffer); // // Now supply the chromosome name. // if (NULL != pieceNameTerminatorCharacters) { for (int i = 0; i < strlen(pieceNameTerminatorCharacters); i++) { char *terminator = strchr(lineBuffer+1, pieceNameTerminatorCharacters[i]); if (NULL != terminator) { *terminator = '\0'; } } } if (spaceIsAPieceNameTerminator) { char *terminator = strchr(lineBuffer, ' '); if (NULL != terminator) { *terminator = '\0'; } terminator = strchr(lineBuffer, '\t'); if (NULL != terminator) { *terminator = '\0'; } } char *terminator = strchr(lineBuffer, '\n'); if (NULL != terminator) { *terminator = '\0'; } terminator = strchr(lineBuffer, '\r'); if (NULL != terminator) { *terminator = '\0'; } genome->startContig(lineBuffer+1); } else { // // Convert it to upper case and truncate the newline before adding it to the genome. // char *newline = strchr(lineBuffer, '\n'); if (NULL != newline) { *newline = 0; } // // But convert any 'N' to 'n'. This is so we don't match the N from the genome with N // in reads (where we just do a straight text comparison. // size_t lineLen = strlen(lineBuffer); for (unsigned i = 0; i < lineLen; i++) { lineBuffer[i] = toupper(lineBuffer[i]); } for (unsigned i = 0; i < lineLen; i++) { if ('N' == lineBuffer[i]) { lineBuffer[i] = 'n'; } } genome->addData(lineBuffer); } } // // And finally add padding at the end of the genome. // genome->addData(paddingBuffer); genome->fillInContigLengths(); genome->sortContigsByName(); fclose(fastaFile); delete [] paddingBuffer; return genome; } // // TODO: Reduce code duplication with the mutator. // bool AppendFASTAGenome(const Genome *genome, FILE *fasta, const char *prefix="") { int nContigs = genome->getNumContigs(); const Genome::Contig *contigs = genome->getContigs(); for (int i = 0; i < nContigs; ++i) { const Genome::Contig &contig = contigs[i]; unsigned start = contig.beginningOffset; unsigned end = i + 1 < nContigs ? contigs[i + 1].beginningOffset : genome->getCountOfBases(); unsigned size = end - start; const char *bases = genome->getSubstring(start, size); fprintf(fasta, ">%s%s\n", prefix, contig.name); fwrite(bases, 1, size, fasta); fputc('\n', fasta); } return !ferror(fasta); } <|endoftext|>
<commit_before>// Time: O(m + n) // Space: O(min(m, n)) // Hash solution. class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { if (nums1.size() > nums2.size()) { return intersection(nums2, nums1); } unordered_set<int> lookup{nums1.cbegin(), nums1.cend()}; vector<int> result; for (const auto& i : nums2) { if (lookup.count(i)) { result.emplace_back(i); lookup.erase(i); } } return result; } }; // Time: O(min(m, n) * log(max(m, n))) // Space: O(1) // Binary search solution. class Solution2 { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { if (nums1.size() > nums2.size()) { return intersection(nums2, nums1); } // Make sure it is sorted, doesn't count in time. sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); vector<int> result; auto it = nums2.cbegin(); for (const auto& i : nums1) { it = lower_bound(it, nums2.cend(), i); if (it != nums2.end() && *it == i) { result.emplace_back(*it); it = upper_bound(it, nums2.cend(), i); } } return result; } }; // Time: O(max(m, n) * log(max(m, n))) // Space: O(1) // Two pointers solution. class Solution3 { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> result; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); auto it1 = nums1.cbegin(), it2 = nums2.cbegin(); while (it1 != nums1.cend() && it2 != nums2.cend()) { if (*it1 < *it2) { ++it1; } else if (*it1 > *it2) { ++it2; } else { if (result.empty() || result.back() != *it1) { result.emplace_back(*it1); } ++it1, ++it2; } } return result; } }; <commit_msg>Update intersection-of-two-arrays.cpp<commit_after>// Time: O(m + n) // Space: O(min(m, n)) // Hash solution. class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { if (nums1.size() > nums2.size()) { return intersection(nums2, nums1); } unordered_set<int> lookup{nums1.cbegin(), nums1.cend()}; vector<int> result; for (const auto& i : nums2) { if (lookup.count(i)) { result.emplace_back(i); lookup.erase(i); } } return result; } }; // Time: O(max(m, n) * log(max(m, n))) // Space: O(1) // Binary search solution. class Solution2 { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { if (nums1.size() > nums2.size()) { return intersection(nums2, nums1); } // Make sure it is sorted, doesn't count in time. sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); vector<int> result; auto it = nums2.cbegin(); for (const auto& i : nums1) { it = lower_bound(it, nums2.cend(), i); if (it != nums2.end() && *it == i) { result.emplace_back(*it); it = upper_bound(it, nums2.cend(), i); } } return result; } }; // Time: O(max(m, n) * log(max(m, n))) // Space: O(1) // Two pointers solution. class Solution3 { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> result; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); auto it1 = nums1.cbegin(), it2 = nums2.cbegin(); while (it1 != nums1.cend() && it2 != nums2.cend()) { if (*it1 < *it2) { ++it1; } else if (*it1 > *it2) { ++it2; } else { if (result.empty() || result.back() != *it1) { result.emplace_back(*it1); } ++it1, ++it2; } } return result; } }; <|endoftext|>
<commit_before>#include <cstdio> #include <string> #include <regex> #include <fstream> #include <sys/stat.h> // http://tclap.sourceforge.net/manual.html #include "tclap/CmdLine.h" #include "HCIDumpParser.h" #include "MsgPublisherTypeConstraint.h" static HCIDumpParser parserLogic; #define STOP_MARKER_FILE "STOP" inline bool stopMarkerExists() { struct stat buffer; bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0); if(stop) { printf("Found STOP marker file, will exit...\n"); } return stop; } static long eventCount = 0; static long maxEventCount = 0; static int64_t lastMarkerCheckTime = 0; /** * Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack */ extern "C" bool beacon_event_callback(const beacon_info *info) { #ifdef PRINT_DEBUG printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time); #endif parserLogic.beaconEvent(info); eventCount ++; // Check for a termination marker every 1000 events or 5 seconds bool stop = false; int64_t elapsed = info->time - lastMarkerCheckTime; if((eventCount % 1000) == 0 || elapsed > 5000) { lastMarkerCheckTime = info->time; stop = stopMarkerExists(); } // Check max event count limit if(maxEventCount > 0 && eventCount >= maxEventCount) stop = true; return stop; } using namespace std; /** * A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing * the hcidump output. */ int main(int argc, const char **argv) { printf("NativeScanner starting up...\n"); TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1"); // TCLAP::ValueArg<std::string> scannerID("s", "scannerID", "Specify the ID of the scanner reading the beacon events", true, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID", "Specify the UUID of the beacon used to signal the scanner heartbeat event", false, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile", "Specify a path to an hcidump file to parse for testing", false, "", "string", cmd); TCLAP::ValueArg<std::string> clientID("c", "clientID", "Specify the clientID to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> username("u", "username", "Specify the username to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> password("p", "password", "Specify the password to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL", "Specify the brokerURL to connect to the MQTT broker with; default tcp://localhost:1883", false, "tcp://localhost:1883", "string", cmd); TCLAP::ValueArg<std::string> topicName("t", "destinationName", "Specify the name of the queue on the MQTT broker to publish to; default beaconEvents", false, "beaconEvents", "string", cmd); TCLAP::SwitchArg skipPublish("S", "skipPublish", "Indicate that the parsed beacons should not be published", false); TCLAP::SwitchArg asyncMode("A", "asyncMode", "Indicate that the parsed beacons should be published using async delivery mode", false); TCLAP::SwitchArg useQueues("Q", "useQueues", "Indicate that the destination type is a queue. If not given the default type is a topic.", false); TCLAP::ValueArg<std::string> hciDev("D", "hciDev", "Specify the name of the host controller interface to use; default hci0", false, "hci0", "string", cmd); MsgPublisherTypeConstraint pubTypeConstraint; TCLAP::ValueArg<std::string> pubType("P", "pubType", "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID", false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr); TCLAP::ValueArg<int> maxCount("C", "maxCount", "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit", false, 0, "int", cmd); TCLAP::ValueArg<int> batchCount("B", "batchCount", "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching", false, 0, "int", cmd); try { // Add the flag arguments cmd.add(skipPublish); cmd.add(asyncMode); cmd.add(useQueues); // Parse the argv array. printf("Parsing command line...\n"); cmd.parse( argc, argv ); printf("done\n"); } catch (TCLAP::ArgException &e) { fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str()); } // Remove any stop marker file if(remove(STOP_MARKER_FILE) == 0) { printf("Removed existing %s marker file\n", STOP_MARKER_FILE); } HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), topicName.getValue()); command.setSkipPublish(skipPublish.getValue()); command.setHciDev(hciDev.getValue()); command.setAsyncMode(asyncMode.getValue()); command.setPubType(pubTypeConstraint.toType(pubType.getValue())); if(maxCount.getValue() > 0) { maxEventCount = maxCount.getValue(); printf("Set maxEventCount: %ld\n", maxEventCount); } parserLogic.setBatchCount(batchCount.getValue()); if(heartbeatUUID.isSet()) { parserLogic.setScannerUUID(heartbeatUUID.getValue()); printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str()); } printf("Begin scanning...\n"); parserLogic.processHCI(command); parserLogic.cleanup(); printf("End scanning\n"); return 0; } <commit_msg>Be consistent in batchCount check and the use of a transacted session<commit_after>#include <cstdio> #include <string> #include <regex> #include <fstream> #include <sys/stat.h> // http://tclap.sourceforge.net/manual.html #include "tclap/CmdLine.h" #include "HCIDumpParser.h" #include "MsgPublisherTypeConstraint.h" static HCIDumpParser parserLogic; #define STOP_MARKER_FILE "STOP" inline bool stopMarkerExists() { struct stat buffer; bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0); if(stop) { printf("Found STOP marker file, will exit...\n"); } return stop; } static long eventCount = 0; static long maxEventCount = 0; static int64_t lastMarkerCheckTime = 0; /** * Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack */ extern "C" bool beacon_event_callback(const beacon_info *info) { #ifdef PRINT_DEBUG printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time); #endif parserLogic.beaconEvent(info); eventCount ++; // Check for a termination marker every 1000 events or 5 seconds bool stop = false; int64_t elapsed = info->time - lastMarkerCheckTime; if((eventCount % 1000) == 0 || elapsed > 5000) { lastMarkerCheckTime = info->time; stop = stopMarkerExists(); printf("beacon_event_callback, status eventCount=%d\n", eventCount); } // Check max event count limit if(maxEventCount > 0 && eventCount >= maxEventCount) stop = true; return stop; } using namespace std; /** * A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing * the hcidump output. */ int main(int argc, const char **argv) { printf("NativeScanner starting up...\n"); TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1"); // TCLAP::ValueArg<std::string> scannerID("s", "scannerID", "Specify the ID of the scanner reading the beacon events", true, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID", "Specify the UUID of the beacon used to signal the scanner heartbeat event", false, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile", "Specify a path to an hcidump file to parse for testing", false, "", "string", cmd); TCLAP::ValueArg<std::string> clientID("c", "clientID", "Specify the clientID to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> username("u", "username", "Specify the username to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> password("p", "password", "Specify the password to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL", "Specify the brokerURL to connect to the MQTT broker with; default tcp://localhost:1883", false, "tcp://localhost:1883", "string", cmd); TCLAP::ValueArg<std::string> topicName("t", "destinationName", "Specify the name of the queue on the MQTT broker to publish to; default beaconEvents", false, "beaconEvents", "string", cmd); TCLAP::SwitchArg skipPublish("S", "skipPublish", "Indicate that the parsed beacons should not be published", false); TCLAP::SwitchArg asyncMode("A", "asyncMode", "Indicate that the parsed beacons should be published using async delivery mode", false); TCLAP::SwitchArg useQueues("Q", "useQueues", "Indicate that the destination type is a queue. If not given the default type is a topic.", false); TCLAP::ValueArg<std::string> hciDev("D", "hciDev", "Specify the name of the host controller interface to use; default hci0", false, "hci0", "string", cmd); MsgPublisherTypeConstraint pubTypeConstraint; TCLAP::ValueArg<std::string> pubType("P", "pubType", "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID", false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr); TCLAP::ValueArg<int> maxCount("C", "maxCount", "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit", false, 0, "int", cmd); TCLAP::ValueArg<int> batchCount("B", "batchCount", "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching", false, 0, "int", cmd); try { // Add the flag arguments cmd.add(skipPublish); cmd.add(asyncMode); cmd.add(useQueues); // Parse the argv array. printf("Parsing command line...\n"); cmd.parse( argc, argv ); printf("done\n"); } catch (TCLAP::ArgException &e) { fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str()); } // Remove any stop marker file if(remove(STOP_MARKER_FILE) == 0) { printf("Removed existing %s marker file\n", STOP_MARKER_FILE); } HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), topicName.getValue()); command.setSkipPublish(skipPublish.getValue()); command.setHciDev(hciDev.getValue()); command.setAsyncMode(asyncMode.getValue()); command.setPubType(pubTypeConstraint.toType(pubType.getValue())); if(maxCount.getValue() > 0) { maxEventCount = maxCount.getValue(); printf("Set maxEventCount: %ld\n", maxEventCount); } parserLogic.setBatchCount(batchCount.getValue()); if(heartbeatUUID.isSet()) { parserLogic.setScannerUUID(heartbeatUUID.getValue()); printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str()); } printf("Begin scanning...\n"); parserLogic.processHCI(command); parserLogic.cleanup(); printf("End scanning\n"); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: ImageCompareCommand.cxx, v $ Language: C++ Date: $Date: 2008-11-09 18:18:52 $ Version: $Revision: 1.12 $ Copyright ( c ) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkNumericTraits.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkExtractImageFilter.h" #include "itkDifferenceImageFilter.h" #include "metaCommand.h" #include <iostream> #include <fstream> #ifdef __BORLANDC__ #define ITK_TEST_DIMENSION_MAX 5 #else #define ITK_TEST_DIMENSION_MAX 6 #endif int RegressionTestImage ( const char *, const char *, int, bool, double, int, int ); int main( int argc, char **argv ) { int bestBaselineStatus = 2001; // Process some command-line arguments intended for BatchMake MetaCommand command; // Option for setting the tolerable difference in intensity values // between the two images. command.SetOption( "toleranceIntensity", "i", false, "Acceptable differences in pixels intensity" ); command.AddOptionField( "toleranceIntensity", "value", MetaCommand::FLOAT, true ); // Option for setting the radius of the neighborhood around a pixel // to search for similar intensity values. command.SetOption( "toleranceRadius", "r", false, "Neighbor pixels to look for similar values" ); command.AddOptionField( "toleranceRadius", "value", MetaCommand::INT, true ); // Option for setting the number of pixel that can be tolerated to // have different intensities. command.SetOption( "toleranceNumberOfPixels", "n", false, "Number of Pixels that are acceptable to have intensity differences" ); command.AddOptionField( "toleranceNumberOfPixels", "value", MetaCommand::INT, true ); // Option for setting the filename of the test image. command.SetOption( "testImage", "t", true, "Filename of the image to be tested against the baseline images" ); command.AddOptionField( "testImage", "filename", MetaCommand::STRING, true ); // Option for setting the filename of multiple baseline images. command.SetOption( "baselineImages", "B", false, "List of baseline images <N> <image1> <image2>...<imageN>" ); command.AddOptionField( "baselineImages", "filename", MetaCommand::LIST, true ); // Option for setting the filename of a single baseline image. command.SetOption( "baselineImage", "b", false, "Baseline images filename" ); command.AddOptionField( "baselineImage", "filename", MetaCommand::STRING, true ); command.Parse( argc, argv ); double toleranceIntensity = 0.0; unsigned int toleranceRadius = 0; unsigned long toleranceNumberOfPixels = 0; std::string testImageFilename; std::string baselineImageFilename; // If a value of intensity tolerance was given in the command line if( command.GetOptionWasSet( "toleranceIntensity" ) ) { toleranceIntensity = command.GetValueAsInt( "toleranceIntensity", "value" ); } // If a value of neighborhood radius tolerance was given in the command // line. if( command.GetOptionWasSet( "toleranceRadius" ) ) { toleranceRadius = command.GetValueAsInt( "toleranceRadius", "value" ); } // If a value of number of pixels tolerance was given in the command line if( command.GetOptionWasSet( "toleranceNumberOfPixels" ) ) { toleranceNumberOfPixels = command.GetValueAsInt( "toleranceNumberOfPixels", "value" ); } // Get the filename of the image to be tested if( command.GetOptionWasSet( "testImage" ) ) { testImageFilename = command.GetValueAsString( "testImage", "filename" ); } std::list< std::string > baselineImageFilenames; baselineImageFilenames.clear(); bool singleBaselineImage = true; if( !command.GetOptionWasSet( "baselineImage" ) && !command.GetOptionWasSet( "baselineImages" ) ) { std::cerr << "You must provide a -BaselineImage or -BaselineImages option" << std::endl; return EXIT_FAILURE; } // Get the filename of the base line image if( command.GetOptionWasSet( "baselineImage" ) ) { singleBaselineImage = true; baselineImageFilename = command.GetValueAsString( "baselineImage", "filename" ); } // Get the filename of the base line image if( command.GetOptionWasSet( "baselineImages" ) ) { singleBaselineImage = false; baselineImageFilenames = command.GetValueAsList( "baselineImages" ); } std::string bestBaselineFilename; try { if( singleBaselineImage ) { bestBaselineStatus = RegressionTestImage( testImageFilename.c_str(), baselineImageFilename.c_str(), 0, false, toleranceIntensity, toleranceRadius, toleranceNumberOfPixels ); bestBaselineFilename = baselineImageFilename; } else { typedef std::list< std::string >::const_iterator nameIterator; nameIterator baselineImageItr = baselineImageFilenames.begin(); while( baselineImageItr != baselineImageFilenames.end() ) { const int currentStatus = RegressionTestImage( testImageFilename.c_str(), baselineImageItr->c_str(), 0, false, toleranceIntensity, toleranceRadius, toleranceNumberOfPixels ); if( currentStatus < bestBaselineStatus ) { bestBaselineStatus = currentStatus; bestBaselineFilename = *baselineImageItr; } if( bestBaselineStatus == 0 ) { break; } ++baselineImageItr; } } // generate images of our closest match if( bestBaselineStatus == 0 ) { RegressionTestImage( testImageFilename.c_str(), bestBaselineFilename.c_str(), 1, false, toleranceIntensity, toleranceRadius, toleranceNumberOfPixels ); } else { RegressionTestImage( testImageFilename.c_str(), bestBaselineFilename.c_str(), 1, true, toleranceIntensity, toleranceRadius, toleranceNumberOfPixels ); } } catch( itk::ExceptionObject& e ) { std::cerr << "ITK test driver caught an ITK exception:\n"; std::cerr << e << "\n"; bestBaselineStatus = -1; } catch( const std::exception& e ) { std::cerr << "ITK test driver caught an exception:\n"; std::cerr << e.what() << "\n"; bestBaselineStatus = -1; } catch( ... ) { std::cerr << "ITK test driver caught an unknown exception!!!\n"; bestBaselineStatus = -1; } std::cout << bestBaselineStatus << std::endl; return bestBaselineStatus; } // Regression Testing Code int RegressionTestImage ( const char *testImageFilename, const char *baselineImageFilename, int reportErrors, bool createDifferenceImage, double intensityTolerance, int radiusTolerance, int numberOfPixelsTolerance ) { // Use the factory mechanism to read the test and baseline files and // convert them to double typedef itk::Image< double, ITK_TEST_DIMENSION_MAX > ImageType; typedef itk::Image< unsigned char, ITK_TEST_DIMENSION_MAX > OutputType; typedef itk::Image< unsigned char, 2 > DiffOutputType; typedef itk::ImageFileReader< ImageType > ReaderType; // Read the baseline file ReaderType::Pointer baselineReader = ReaderType::New(); baselineReader->SetFileName( baselineImageFilename ); try { baselineReader->UpdateLargestPossibleRegion(); } catch ( itk::ExceptionObject& e ) { std::cerr << "Exception detected while reading " << baselineImageFilename << " : " << e; return 1000; } // Read the file generated by the test ReaderType::Pointer testReader = ReaderType::New(); testReader->SetFileName( testImageFilename ); try { testReader->UpdateLargestPossibleRegion(); } catch ( itk::ExceptionObject& e ) { std::cerr << "Exception detected while reading " << testImageFilename << " : " << e << std::endl; return 1000; } // The sizes of the baseline and test image must match ImageType::SizeType baselineSize; baselineSize = baselineReader->GetOutput()->GetLargestPossibleRegion(). GetSize(); ImageType::SizeType testSize; testSize = testReader->GetOutput()->GetLargestPossibleRegion().GetSize(); if ( baselineSize != testSize ) { std::cerr << "The size of the Baseline image and Test image do not match!" << std::endl; std::cerr << "Baseline image: " << baselineImageFilename << " has size " << baselineSize << std::endl; std::cerr << "Test image: " << testImageFilename << " has size " << testSize << std::endl; return 1; } // Now compare the two images typedef itk::DifferenceImageFilter<ImageType, ImageType> DiffType; DiffType::Pointer diff = DiffType::New(); diff->SetValidInput( baselineReader->GetOutput() ); diff->SetTestInput( testReader->GetOutput() ); diff->SetDifferenceThreshold( intensityTolerance ); diff->SetToleranceRadius( radiusTolerance ); diff->UpdateLargestPossibleRegion(); bool differenceFailed = false; double averageIntensityDifference = diff->GetTotalDifference(); unsigned long numberOfPixelsWithDifferences = diff-> GetNumberOfPixelsWithDifferences(); if( averageIntensityDifference > 0.0 ) { averageIntensityDifference /= numberOfPixelsWithDifferences; if( static_cast<int>( numberOfPixelsWithDifferences ) > numberOfPixelsTolerance ) { differenceFailed = true; } else { differenceFailed = false; } } else { differenceFailed = false; } if ( reportErrors ) { typedef itk::RescaleIntensityImageFilter< ImageType, OutputType > RescaleType; typedef itk::ExtractImageFilter< OutputType, DiffOutputType > ExtractType; typedef itk::ImageFileWriter< DiffOutputType > WriterType; typedef itk::ImageRegion< ITK_TEST_DIMENSION_MAX > RegionType; OutputType::IndexType index; index.Fill( 0 ); OutputType::SizeType size; size.Fill( 0 ); RescaleType::Pointer rescale = RescaleType::New(); rescale->SetOutputMinimum( itk::NumericTraits<unsigned char>::NonpositiveMin() ); rescale->SetOutputMaximum( itk::NumericTraits<unsigned char>::max() ); rescale->SetInput( diff->GetOutput() ); rescale->UpdateLargestPossibleRegion(); RegionType region; region.SetIndex( index ); size = rescale->GetOutput()->GetLargestPossibleRegion().GetSize(); for ( unsigned int i = 2; i < ITK_TEST_DIMENSION_MAX; i++ ) { size[i] = 0; } region.SetSize( size ); ExtractType::Pointer extract = ExtractType::New(); extract->SetInput( rescale->GetOutput() ); extract->SetExtractionRegion( region ); WriterType::Pointer writer = WriterType::New(); writer->SetInput( extract->GetOutput() ); if( createDifferenceImage ) { // if there are discrepencies, create an diff image std::cout << "<DartMeasurement name=\"ImageError\" type=\"numeric/double\">"; std::cout << averageIntensityDifference; std::cout << "</DartMeasurement>" << std::endl; std::cout << "<DartMeasurement name=\"NumberOfPixelsError\" type=\"numeric/int\">"; std::cout << numberOfPixelsWithDifferences; std::cout << "</DartMeasurement>" << std::endl; itksys_ios::ostringstream diffName; diffName << testImageFilename << ".diff.png"; try { rescale->SetInput( diff->GetOutput() ); rescale->Update(); } catch( const std::exception& e ) { std::cerr << "Error during rescale of " << diffName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during rescale of " << diffName.str() << std::endl; } writer->SetFileName( diffName.str().c_str() ); try { writer->Update(); } catch( const std::exception& e ) { std::cerr << "Error during write of " << diffName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during write of " << diffName.str() << std::endl; } std::cout << "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">"; std::cout << diffName.str(); std::cout << "</DartMeasurementFile>" << std::endl; } itksys_ios::ostringstream baseName; baseName << testImageFilename << ".base.png"; try { rescale->SetInput( baselineReader->GetOutput() ); rescale->Update(); } catch( const std::exception& e ) { std::cerr << "Error during rescale of " << baseName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during rescale of " << baseName.str() << std::endl; } try { writer->SetFileName( baseName.str().c_str() ); writer->Update(); } catch( const std::exception& e ) { std::cerr << "Error during write of " << baseName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during write of " << baseName.str() << std::endl; } std::cout << "<DartMeasurementFile name=\"BaselineImage\" type=\"image/png\">"; std::cout << baseName.str(); std::cout << "</DartMeasurementFile>" << std::endl; itksys_ios::ostringstream testName; testName << testImageFilename << ".test.png"; try { rescale->SetInput( testReader->GetOutput() ); rescale->Update(); } catch( const std::exception& e ) { std::cerr << "Error during rescale of " << testName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during rescale of " << testName.str() << std::endl; } try { writer->SetFileName( testName.str().c_str() ); writer->Update(); } catch( const std::exception& e ) { std::cerr << "Error during write of " << testName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during write of " << testName.str() << std::endl; } std::cout << "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">"; std::cout << testName.str(); std::cout << "</DartMeasurementFile>" << std::endl; } return differenceFailed; } <commit_msg>BUG: Was reading the -i (intensity tolerance) argument as an int instead of as a float<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: ImageCompareCommand.cxx, v $ Language: C++ Date: $Date: 2008-11-09 18:18:52 $ Version: $Revision: 1.12 $ Copyright ( c ) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkNumericTraits.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkExtractImageFilter.h" #include "itkDifferenceImageFilter.h" #include "metaCommand.h" #include <iostream> #include <fstream> #ifdef __BORLANDC__ #define ITK_TEST_DIMENSION_MAX 5 #else #define ITK_TEST_DIMENSION_MAX 6 #endif int RegressionTestImage ( const char *, const char *, int, bool, double, int, int ); int main( int argc, char **argv ) { int bestBaselineStatus = 2001; // Process some command-line arguments intended for BatchMake MetaCommand command; // Option for setting the tolerable difference in intensity values // between the two images. command.SetOption( "toleranceIntensity", "i", false, "Acceptable differences in pixels intensity" ); command.AddOptionField( "toleranceIntensity", "value", MetaCommand::FLOAT, true ); // Option for setting the radius of the neighborhood around a pixel // to search for similar intensity values. command.SetOption( "toleranceRadius", "r", false, "Neighbor pixels to look for similar values" ); command.AddOptionField( "toleranceRadius", "value", MetaCommand::INT, true ); // Option for setting the number of pixel that can be tolerated to // have different intensities. command.SetOption( "toleranceNumberOfPixels", "n", false, "Number of Pixels that are acceptable to have intensity differences" ); command.AddOptionField( "toleranceNumberOfPixels", "value", MetaCommand::INT, true ); // Option for setting the filename of the test image. command.SetOption( "testImage", "t", true, "Filename of the image to be tested against the baseline images" ); command.AddOptionField( "testImage", "filename", MetaCommand::STRING, true ); // Option for setting the filename of multiple baseline images. command.SetOption( "baselineImages", "B", false, "List of baseline images <N> <image1> <image2>...<imageN>" ); command.AddOptionField( "baselineImages", "filename", MetaCommand::LIST, true ); // Option for setting the filename of a single baseline image. command.SetOption( "baselineImage", "b", false, "Baseline images filename" ); command.AddOptionField( "baselineImage", "filename", MetaCommand::STRING, true ); command.Parse( argc, argv ); double toleranceIntensity = 0.0; unsigned int toleranceRadius = 0; unsigned long toleranceNumberOfPixels = 0; std::string testImageFilename; std::string baselineImageFilename; // If a value of intensity tolerance was given in the command line if( command.GetOptionWasSet( "toleranceIntensity" ) ) { toleranceIntensity = command.GetValueAsFloat( "toleranceIntensity", "value" ); } // If a value of neighborhood radius tolerance was given in the command // line. if( command.GetOptionWasSet( "toleranceRadius" ) ) { toleranceRadius = command.GetValueAsInt( "toleranceRadius", "value" ); } // If a value of number of pixels tolerance was given in the command line if( command.GetOptionWasSet( "toleranceNumberOfPixels" ) ) { toleranceNumberOfPixels = command.GetValueAsInt( "toleranceNumberOfPixels", "value" ); } // Get the filename of the image to be tested if( command.GetOptionWasSet( "testImage" ) ) { testImageFilename = command.GetValueAsString( "testImage", "filename" ); } std::list< std::string > baselineImageFilenames; baselineImageFilenames.clear(); bool singleBaselineImage = true; if( !command.GetOptionWasSet( "baselineImage" ) && !command.GetOptionWasSet( "baselineImages" ) ) { std::cerr << "You must provide a -BaselineImage or -BaselineImages option" << std::endl; return EXIT_FAILURE; } // Get the filename of the base line image if( command.GetOptionWasSet( "baselineImage" ) ) { singleBaselineImage = true; baselineImageFilename = command.GetValueAsString( "baselineImage", "filename" ); } // Get the filename of the base line image if( command.GetOptionWasSet( "baselineImages" ) ) { singleBaselineImage = false; baselineImageFilenames = command.GetValueAsList( "baselineImages" ); } std::string bestBaselineFilename; try { if( singleBaselineImage ) { bestBaselineStatus = RegressionTestImage( testImageFilename.c_str(), baselineImageFilename.c_str(), 0, false, toleranceIntensity, toleranceRadius, toleranceNumberOfPixels ); bestBaselineFilename = baselineImageFilename; } else { typedef std::list< std::string >::const_iterator nameIterator; nameIterator baselineImageItr = baselineImageFilenames.begin(); while( baselineImageItr != baselineImageFilenames.end() ) { const int currentStatus = RegressionTestImage( testImageFilename.c_str(), baselineImageItr->c_str(), 0, false, toleranceIntensity, toleranceRadius, toleranceNumberOfPixels ); if( currentStatus < bestBaselineStatus ) { bestBaselineStatus = currentStatus; bestBaselineFilename = *baselineImageItr; } if( bestBaselineStatus == 0 ) { break; } ++baselineImageItr; } } // generate images of our closest match if( bestBaselineStatus == 0 ) { RegressionTestImage( testImageFilename.c_str(), bestBaselineFilename.c_str(), 1, false, toleranceIntensity, toleranceRadius, toleranceNumberOfPixels ); } else { RegressionTestImage( testImageFilename.c_str(), bestBaselineFilename.c_str(), 1, true, toleranceIntensity, toleranceRadius, toleranceNumberOfPixels ); } } catch( itk::ExceptionObject& e ) { std::cerr << "ITK test driver caught an ITK exception:\n"; std::cerr << e << "\n"; bestBaselineStatus = -1; } catch( const std::exception& e ) { std::cerr << "ITK test driver caught an exception:\n"; std::cerr << e.what() << "\n"; bestBaselineStatus = -1; } catch( ... ) { std::cerr << "ITK test driver caught an unknown exception!!!\n"; bestBaselineStatus = -1; } std::cout << bestBaselineStatus << std::endl; return bestBaselineStatus; } // Regression Testing Code int RegressionTestImage ( const char *testImageFilename, const char *baselineImageFilename, int reportErrors, bool createDifferenceImage, double intensityTolerance, int radiusTolerance, int numberOfPixelsTolerance ) { // Use the factory mechanism to read the test and baseline files and // convert them to double typedef itk::Image< double, ITK_TEST_DIMENSION_MAX > ImageType; typedef itk::Image< unsigned char, ITK_TEST_DIMENSION_MAX > OutputType; typedef itk::Image< unsigned char, 2 > DiffOutputType; typedef itk::ImageFileReader< ImageType > ReaderType; // Read the baseline file ReaderType::Pointer baselineReader = ReaderType::New(); baselineReader->SetFileName( baselineImageFilename ); try { baselineReader->UpdateLargestPossibleRegion(); } catch ( itk::ExceptionObject& e ) { std::cerr << "Exception detected while reading " << baselineImageFilename << " : " << e; return 1000; } // Read the file generated by the test ReaderType::Pointer testReader = ReaderType::New(); testReader->SetFileName( testImageFilename ); try { testReader->UpdateLargestPossibleRegion(); } catch ( itk::ExceptionObject& e ) { std::cerr << "Exception detected while reading " << testImageFilename << " : " << e << std::endl; return 1000; } // The sizes of the baseline and test image must match ImageType::SizeType baselineSize; baselineSize = baselineReader->GetOutput()->GetLargestPossibleRegion(). GetSize(); ImageType::SizeType testSize; testSize = testReader->GetOutput()->GetLargestPossibleRegion().GetSize(); if ( baselineSize != testSize ) { std::cerr << "The size of the Baseline image and Test image do not match!" << std::endl; std::cerr << "Baseline image: " << baselineImageFilename << " has size " << baselineSize << std::endl; std::cerr << "Test image: " << testImageFilename << " has size " << testSize << std::endl; return 1; } // Now compare the two images typedef itk::DifferenceImageFilter<ImageType, ImageType> DiffType; DiffType::Pointer diff = DiffType::New(); diff->SetValidInput( baselineReader->GetOutput() ); diff->SetTestInput( testReader->GetOutput() ); diff->SetDifferenceThreshold( intensityTolerance ); diff->SetToleranceRadius( radiusTolerance ); diff->UpdateLargestPossibleRegion(); bool differenceFailed = false; double averageIntensityDifference = diff->GetTotalDifference(); unsigned long numberOfPixelsWithDifferences = diff-> GetNumberOfPixelsWithDifferences(); if( averageIntensityDifference > 0.0 ) { averageIntensityDifference /= numberOfPixelsWithDifferences; if( static_cast<int>( numberOfPixelsWithDifferences ) > numberOfPixelsTolerance ) { differenceFailed = true; } else { differenceFailed = false; } } else { differenceFailed = false; } if ( reportErrors ) { typedef itk::RescaleIntensityImageFilter< ImageType, OutputType > RescaleType; typedef itk::ExtractImageFilter< OutputType, DiffOutputType > ExtractType; typedef itk::ImageFileWriter< DiffOutputType > WriterType; typedef itk::ImageRegion< ITK_TEST_DIMENSION_MAX > RegionType; OutputType::IndexType index; index.Fill( 0 ); OutputType::SizeType size; size.Fill( 0 ); RescaleType::Pointer rescale = RescaleType::New(); rescale->SetOutputMinimum( itk::NumericTraits<unsigned char>::NonpositiveMin() ); rescale->SetOutputMaximum( itk::NumericTraits<unsigned char>::max() ); rescale->SetInput( diff->GetOutput() ); rescale->UpdateLargestPossibleRegion(); RegionType region; region.SetIndex( index ); size = rescale->GetOutput()->GetLargestPossibleRegion().GetSize(); for ( unsigned int i = 2; i < ITK_TEST_DIMENSION_MAX; i++ ) { size[i] = 0; } region.SetSize( size ); ExtractType::Pointer extract = ExtractType::New(); extract->SetInput( rescale->GetOutput() ); extract->SetExtractionRegion( region ); WriterType::Pointer writer = WriterType::New(); writer->SetInput( extract->GetOutput() ); if( createDifferenceImage ) { // if there are discrepencies, create an diff image std::cout << "<DartMeasurement name=\"ImageError\" type=\"numeric/double\">"; std::cout << averageIntensityDifference; std::cout << "</DartMeasurement>" << std::endl; std::cout << "<DartMeasurement name=\"NumberOfPixelsError\" type=\"numeric/int\">"; std::cout << numberOfPixelsWithDifferences; std::cout << "</DartMeasurement>" << std::endl; itksys_ios::ostringstream diffName; diffName << testImageFilename << ".diff.png"; try { rescale->SetInput( diff->GetOutput() ); rescale->Update(); } catch( const std::exception& e ) { std::cerr << "Error during rescale of " << diffName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during rescale of " << diffName.str() << std::endl; } writer->SetFileName( diffName.str().c_str() ); try { writer->Update(); } catch( const std::exception& e ) { std::cerr << "Error during write of " << diffName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during write of " << diffName.str() << std::endl; } std::cout << "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">"; std::cout << diffName.str(); std::cout << "</DartMeasurementFile>" << std::endl; } itksys_ios::ostringstream baseName; baseName << testImageFilename << ".base.png"; try { rescale->SetInput( baselineReader->GetOutput() ); rescale->Update(); } catch( const std::exception& e ) { std::cerr << "Error during rescale of " << baseName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during rescale of " << baseName.str() << std::endl; } try { writer->SetFileName( baseName.str().c_str() ); writer->Update(); } catch( const std::exception& e ) { std::cerr << "Error during write of " << baseName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during write of " << baseName.str() << std::endl; } std::cout << "<DartMeasurementFile name=\"BaselineImage\" type=\"image/png\">"; std::cout << baseName.str(); std::cout << "</DartMeasurementFile>" << std::endl; itksys_ios::ostringstream testName; testName << testImageFilename << ".test.png"; try { rescale->SetInput( testReader->GetOutput() ); rescale->Update(); } catch( const std::exception& e ) { std::cerr << "Error during rescale of " << testName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during rescale of " << testName.str() << std::endl; } try { writer->SetFileName( testName.str().c_str() ); writer->Update(); } catch( const std::exception& e ) { std::cerr << "Error during write of " << testName.str() << std::endl; std::cerr << e.what() << "\n"; } catch ( ... ) { std::cerr << "Error during write of " << testName.str() << std::endl; } std::cout << "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">"; std::cout << testName.str(); std::cout << "</DartMeasurementFile>" << std::endl; } return differenceFailed; } <|endoftext|>
<commit_before>//===--- CompilationGraph.cpp - The LLVM Compiler Driver --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open // Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Compilation graph - implementation. // //===----------------------------------------------------------------------===// #include "CompilationGraph.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/DOTGraphTraits.h" #include "llvm/Support/GraphWriter.h" #include <stdexcept> using namespace llvm; using namespace llvmcc; extern cl::list<std::string> InputFilenames; extern cl::opt<std::string> OutputFilename; CompilationGraph::CompilationGraph() { NodesMap["root"] = Node(this); } Node& CompilationGraph::getNode(const std::string& ToolName) { nodes_map_type::iterator I = NodesMap.find(ToolName); if (I == NodesMap.end()) throw std::runtime_error("Node " + ToolName + " is not in the graph"); return I->second; } const Node& CompilationGraph::getNode(const std::string& ToolName) const { nodes_map_type::const_iterator I = NodesMap.find(ToolName); if (I == NodesMap.end()) throw std::runtime_error("Node " + ToolName + " is not in the graph!"); return I->second; } const std::string& CompilationGraph::getLanguage(const sys::Path& File) const { LanguageMap::const_iterator Lang = ExtsToLangs.find(File.getSuffix()); if (Lang == ExtsToLangs.end()) throw std::runtime_error("Unknown suffix: " + File.getSuffix() + '!'); return Lang->second; } const CompilationGraph::tools_vector_type& CompilationGraph::getToolsVector(const std::string& LangName) const { tools_map_type::const_iterator I = ToolsMap.find(LangName); if (I == ToolsMap.end()) throw std::runtime_error("No tools corresponding to " + LangName + " found!"); return I->second; } void CompilationGraph::insertNode(Tool* V) { if (!NodesMap.count(V->Name())) { Node N; N.OwningGraph = this; N.ToolPtr = V; NodesMap[V->Name()] = N; } } void CompilationGraph::insertEdge(const std::string& A, Edge* E) { if (A == "root") { const Node& N = getNode(E->ToolName()); const std::string& InputLanguage = N.ToolPtr->InputLanguage(); ToolsMap[InputLanguage].push_back(E->ToolName()); // Needed to support iteration via GraphTraits. NodesMap["root"].AddEdge(E); } else { Node& N = getNode(A); N.AddEdge(E); } } // TOFIX: support edge properties. // TOFIX: support more interesting graph topologies. int CompilationGraph::Build (const sys::Path& tempDir) const { PathVector JoinList; const Tool* JoinTool = 0; sys::Path In, Out; // For each input file for (cl::list<std::string>::const_iterator B = InputFilenames.begin(), E = InputFilenames.end(); B != E; ++B) { In = sys::Path(*B); // Get to the head of the toolchain. const tools_vector_type& TV = getToolsVector(getLanguage(In)); if(TV.empty()) throw std::runtime_error("Tool names vector is empty!"); const Node* N = &getNode(*TV.begin()); // Pass it through the chain until we bump into a Join node or a // node that says that it is the last. bool Last = false; while(!Last) { const Tool* CurTool = N->ToolPtr.getPtr(); if(CurTool->IsJoin()) { JoinList.push_back(In); JoinTool = CurTool; break; } // Is this the last tool? if (!N->HasChildren() || CurTool->IsLast()) { // Check if the first tool is also the last if(Out.empty()) Out.set(In.getBasename()); else Out.appendComponent(In.getBasename()); Out.appendSuffix(CurTool->OutputSuffix()); Last = true; } else { Out = tempDir; Out.appendComponent(In.getBasename()); Out.appendSuffix(CurTool->OutputSuffix()); Out.makeUnique(true, NULL); Out.eraseFromDisk(); } if (CurTool->GenerateAction(In, Out).Execute() != 0) throw std::runtime_error("Tool returned error code!"); N = &getNode((*N->EdgesBegin())->ToolName()); In = Out; Out.clear(); } } if(JoinTool) { // If the final output name is empty, set it to "a.out" if (!OutputFilename.empty()) { Out = sys::Path(OutputFilename); } else { Out = sys::Path("a"); Out.appendSuffix(JoinTool->OutputSuffix()); } if (JoinTool->GenerateAction(JoinList, Out).Execute() != 0) throw std::runtime_error("Tool returned error code!"); } return 0; } namespace llvm { template <> struct DOTGraphTraits<llvmcc::CompilationGraph*> : public DefaultDOTGraphTraits { template<typename GraphType> static std::string getNodeLabel(const Node* N, const GraphType&) { if (N->ToolPtr) return N->ToolPtr->Name(); else return "root"; } }; } void CompilationGraph::writeGraph() { std::ofstream O("CompilationGraph.dot"); if(O.good()) { llvm::WriteGraph(this, "CompilationGraph"); O.close(); } else { throw std::runtime_error(""); } } void CompilationGraph::viewGraph() { llvm::ViewGraph(this, "compilation-graph"); } <commit_msg>Cosmetic change: if( -> if (<commit_after>//===--- CompilationGraph.cpp - The LLVM Compiler Driver --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open // Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Compilation graph - implementation. // //===----------------------------------------------------------------------===// #include "CompilationGraph.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/DOTGraphTraits.h" #include "llvm/Support/GraphWriter.h" #include <stdexcept> using namespace llvm; using namespace llvmcc; extern cl::list<std::string> InputFilenames; extern cl::opt<std::string> OutputFilename; CompilationGraph::CompilationGraph() { NodesMap["root"] = Node(this); } Node& CompilationGraph::getNode(const std::string& ToolName) { nodes_map_type::iterator I = NodesMap.find(ToolName); if (I == NodesMap.end()) throw std::runtime_error("Node " + ToolName + " is not in the graph"); return I->second; } const Node& CompilationGraph::getNode(const std::string& ToolName) const { nodes_map_type::const_iterator I = NodesMap.find(ToolName); if (I == NodesMap.end()) throw std::runtime_error("Node " + ToolName + " is not in the graph!"); return I->second; } const std::string& CompilationGraph::getLanguage(const sys::Path& File) const { LanguageMap::const_iterator Lang = ExtsToLangs.find(File.getSuffix()); if (Lang == ExtsToLangs.end()) throw std::runtime_error("Unknown suffix: " + File.getSuffix() + '!'); return Lang->second; } const CompilationGraph::tools_vector_type& CompilationGraph::getToolsVector(const std::string& LangName) const { tools_map_type::const_iterator I = ToolsMap.find(LangName); if (I == ToolsMap.end()) throw std::runtime_error("No tools corresponding to " + LangName + " found!"); return I->second; } void CompilationGraph::insertNode(Tool* V) { if (!NodesMap.count(V->Name())) { Node N; N.OwningGraph = this; N.ToolPtr = V; NodesMap[V->Name()] = N; } } void CompilationGraph::insertEdge(const std::string& A, Edge* E) { if (A == "root") { const Node& N = getNode(E->ToolName()); const std::string& InputLanguage = N.ToolPtr->InputLanguage(); ToolsMap[InputLanguage].push_back(E->ToolName()); // Needed to support iteration via GraphTraits. NodesMap["root"].AddEdge(E); } else { Node& N = getNode(A); N.AddEdge(E); } } // TOFIX: support edge properties. // TOFIX: support more interesting graph topologies. int CompilationGraph::Build (const sys::Path& tempDir) const { PathVector JoinList; const Tool* JoinTool = 0; sys::Path In, Out; // For each input file for (cl::list<std::string>::const_iterator B = InputFilenames.begin(), E = InputFilenames.end(); B != E; ++B) { In = sys::Path(*B); // Get to the head of the toolchain. const tools_vector_type& TV = getToolsVector(getLanguage(In)); if (TV.empty()) throw std::runtime_error("Tool names vector is empty!"); const Node* N = &getNode(*TV.begin()); // Pass it through the chain until we bump into a Join node or a // node that says that it is the last. bool Last = false; while(!Last) { const Tool* CurTool = N->ToolPtr.getPtr(); if (CurTool->IsJoin()) { JoinList.push_back(In); JoinTool = CurTool; break; } // Is this the last tool? if (!N->HasChildren() || CurTool->IsLast()) { // Check if the first tool is also the last if (Out.empty()) Out.set(In.getBasename()); else Out.appendComponent(In.getBasename()); Out.appendSuffix(CurTool->OutputSuffix()); Last = true; } else { Out = tempDir; Out.appendComponent(In.getBasename()); Out.appendSuffix(CurTool->OutputSuffix()); Out.makeUnique(true, NULL); Out.eraseFromDisk(); } if (CurTool->GenerateAction(In, Out).Execute() != 0) throw std::runtime_error("Tool returned error code!"); N = &getNode((*N->EdgesBegin())->ToolName()); In = Out; Out.clear(); } } if (JoinTool) { // If the final output name is empty, set it to "a.out" if (!OutputFilename.empty()) { Out = sys::Path(OutputFilename); } else { Out = sys::Path("a"); Out.appendSuffix(JoinTool->OutputSuffix()); } if (JoinTool->GenerateAction(JoinList, Out).Execute() != 0) throw std::runtime_error("Tool returned error code!"); } return 0; } namespace llvm { template <> struct DOTGraphTraits<llvmcc::CompilationGraph*> : public DefaultDOTGraphTraits { template<typename GraphType> static std::string getNodeLabel(const Node* N, const GraphType&) { if (N->ToolPtr) return N->ToolPtr->Name(); else return "root"; } }; } void CompilationGraph::writeGraph() { std::ofstream O("CompilationGraph.dot"); if (O.good()) { llvm::WriteGraph(this, "CompilationGraph"); O.close(); } else { throw std::runtime_error(""); } } void CompilationGraph::viewGraph() { llvm::ViewGraph(this, "compilation-graph"); } <|endoftext|>
<commit_before>#include "cvm.h" #include <dlfcn.h> #define STR2(s) #s #define STR(s) STR2(s) #ifdef __linux__ #define DAB_LIBC_NAME "libc.so.6" // LINUX #else #define DAB_LIBC_NAME "libc.dylib" // APPLE #endif DabValue DabVM::merge_arrays(const DabValue &arg0, const DabValue &arg1) { auto & a0 = arg0.array(); auto & a1 = arg1.array(); DabValue array_class = classes[CLASS_ARRAY]; DabValue value = array_class.create_instance(); auto & array = value.array(); array.resize(a0.size() + a1.size()); fprintf(stderr, "vm: merge %d and %d items into new %d-sized array\n", (int)a0.size(), (int)a1.size(), (int)array.size()); size_t i = 0; for (auto &item : a0) { array[i++] = item; } for (auto &item : a1) { array[i++] = item; } return value; } dab_function_t import_external_function(void *symbol, const DabFunctionReflection &reflection, Stack &stack) { return [symbol, &reflection, &stack](size_t n_args, size_t n_ret, void *blockaddr) { const auto &arg_klasses = reflection.arg_klasses; const auto ret_klass = reflection.ret_klass; assert(blockaddr == 0); assert(n_args == arg_klasses.size()); assert(n_ret == 1); if (false) { } #include "ffi_signatures.h" else { fprintf(stderr, "vm: unsupported signature\n"); exit(1); } }; } void DabVM::define_defaults() { define_default_classes(); auto make_import_function = [this](const char *name) { return [this, name](size_t n_args, size_t n_ret, void *blockaddr) { assert(blockaddr == 0); assert(n_args == 2 || n_args == 1); assert(n_ret == 1); std::string libc_name; if (n_args == 2) { auto _libc_name = stack.pop_value(); assert(_libc_name.class_index() == CLASS_STRING); libc_name = _libc_name.data.string; } auto method = stack.pop_value(); assert(method.class_index() == CLASS_METHOD); auto method_name = method.data.string; if (n_args == 1) { libc_name = method_name; } fprintf(stderr, "vm: readjust '%s' to libc function '%s'\n", method_name.c_str(), libc_name.c_str()); auto handle = dlopen(name, RTLD_LAZY); if (!handle) { fprintf(stderr, "vm: dlopen error: %s", dlerror()); exit(1); } fprintf(stderr, "vm: dlopen handle: %p\n", handle); auto symbol = dlsym(handle, libc_name.c_str()); if (!symbol) { fprintf(stderr, "vm: dlsym error: %s", dlerror()); exit(1); } fprintf(stderr, "vm: dlsym handle: %p\n", symbol); auto &function = functions[method_name]; function.regular = false; function.address = -1; function.extra = import_external_function(symbol, function.reflection, this->stack); stack.push_value(DabValue(nullptr)); }; }; { DabFunction fun; fun.name = "__import_libc"; fun.regular = false; fun.extra = make_import_function(DAB_LIBC_NAME); functions["__import_libc"] = fun; } { DabFunction fun; fun.name = "__import_sdl"; fun.regular = false; fun.extra = make_import_function("/usr/local/lib/libSDL2.dylib"); functions["__import_sdl"] = fun; } { DabFunction fun; fun.name = "__import_pq"; fun.regular = false; fun.extra = make_import_function("/usr/local/lib/libpq.dylib"); functions["__import_pq"] = fun; } { DabFunction fun; fun.name = "||"; fun.regular = false; fun.extra = [this](size_t n_args, size_t n_ret, void *blockaddr) { assert(blockaddr == 0); // dump(); assert(n_args == 2); assert(n_ret == 1); auto arg1 = stack.pop_value(); auto arg0 = stack.pop_value(); stack.push_value(arg0.truthy() ? arg0 : arg1); }; functions["||"] = fun; } { DabFunction fun; fun.name = "&&"; fun.regular = false; fun.extra = [this](size_t n_args, size_t n_ret, void *blockaddr) { assert(blockaddr == 0); // dump(); assert(n_args == 2); assert(n_ret == 1); auto arg1 = stack.pop_value(); auto arg0 = stack.pop_value(); stack.push_value(arg0.truthy() ? arg1 : arg0); }; functions["&&"] = fun; } } <commit_msg>vm: print dlopen debug only in verbose mode<commit_after>#include "cvm.h" #include <dlfcn.h> #define STR2(s) #s #define STR(s) STR2(s) #ifdef __linux__ #define DAB_LIBC_NAME "libc.so.6" // LINUX #else #define DAB_LIBC_NAME "libc.dylib" // APPLE #endif DabValue DabVM::merge_arrays(const DabValue &arg0, const DabValue &arg1) { auto & a0 = arg0.array(); auto & a1 = arg1.array(); DabValue array_class = classes[CLASS_ARRAY]; DabValue value = array_class.create_instance(); auto & array = value.array(); array.resize(a0.size() + a1.size()); fprintf(stderr, "vm: merge %d and %d items into new %d-sized array\n", (int)a0.size(), (int)a1.size(), (int)array.size()); size_t i = 0; for (auto &item : a0) { array[i++] = item; } for (auto &item : a1) { array[i++] = item; } return value; } dab_function_t import_external_function(void *symbol, const DabFunctionReflection &reflection, Stack &stack) { return [symbol, &reflection, &stack](size_t n_args, size_t n_ret, void *blockaddr) { const auto &arg_klasses = reflection.arg_klasses; const auto ret_klass = reflection.ret_klass; assert(blockaddr == 0); assert(n_args == arg_klasses.size()); assert(n_ret == 1); if (false) { } #include "ffi_signatures.h" else { fprintf(stderr, "vm: unsupported signature\n"); exit(1); } }; } void DabVM::define_defaults() { define_default_classes(); auto make_import_function = [this](const char *name) { return [this, name](size_t n_args, size_t n_ret, void *blockaddr) { assert(blockaddr == 0); assert(n_args == 2 || n_args == 1); assert(n_ret == 1); std::string libc_name; if (n_args == 2) { auto _libc_name = stack.pop_value(); assert(_libc_name.class_index() == CLASS_STRING); libc_name = _libc_name.data.string; } auto method = stack.pop_value(); assert(method.class_index() == CLASS_METHOD); auto method_name = method.data.string; if (n_args == 1) { libc_name = method_name; } fprintf(stderr, "vm: readjust '%s' to libc function '%s'\n", method_name.c_str(), libc_name.c_str()); auto handle = dlopen(name, RTLD_LAZY); if (!handle) { fprintf(stderr, "vm: dlopen error: %s", dlerror()); exit(1); } if (verbose) { fprintf(stderr, "vm: dlopen handle: %p\n", handle); } auto symbol = dlsym(handle, libc_name.c_str()); if (!symbol) { fprintf(stderr, "vm: dlsym error: %s", dlerror()); exit(1); } if (verbose) { fprintf(stderr, "vm: dlsym handle: %p\n", symbol); } auto &function = functions[method_name]; function.regular = false; function.address = -1; function.extra = import_external_function(symbol, function.reflection, this->stack); stack.push_value(DabValue(nullptr)); }; }; { DabFunction fun; fun.name = "__import_libc"; fun.regular = false; fun.extra = make_import_function(DAB_LIBC_NAME); functions["__import_libc"] = fun; } { DabFunction fun; fun.name = "__import_sdl"; fun.regular = false; fun.extra = make_import_function("/usr/local/lib/libSDL2.dylib"); functions["__import_sdl"] = fun; } { DabFunction fun; fun.name = "__import_pq"; fun.regular = false; fun.extra = make_import_function("/usr/local/lib/libpq.dylib"); functions["__import_pq"] = fun; } { DabFunction fun; fun.name = "||"; fun.regular = false; fun.extra = [this](size_t n_args, size_t n_ret, void *blockaddr) { assert(blockaddr == 0); // dump(); assert(n_args == 2); assert(n_ret == 1); auto arg1 = stack.pop_value(); auto arg0 = stack.pop_value(); stack.push_value(arg0.truthy() ? arg0 : arg1); }; functions["||"] = fun; } { DabFunction fun; fun.name = "&&"; fun.regular = false; fun.extra = [this](size_t n_args, size_t n_ret, void *blockaddr) { assert(blockaddr == 0); // dump(); assert(n_args == 2); assert(n_ret == 1); auto arg1 = stack.pop_value(); auto arg0 = stack.pop_value(); stack.push_value(arg0.truthy() ? arg1 : arg0); }; functions["&&"] = fun; } } <|endoftext|>
<commit_before>/******************************************************************************* * thrill/api/dia_base.cpp * * Part of Project Thrill - http://project-thrill.org * * Copyright (C) 2015 Sebastian Lamm <seba.lamm@gmail.com> * Copyright (C) 2016 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <thrill/api/dia_base.hpp> #include <thrill/common/json_logger.hpp> #include <thrill/common/logger.hpp> #include <thrill/common/stats_timer.hpp> #include <thrill/mem/allocator.hpp> #include <algorithm> #include <chrono> #include <deque> #include <functional> #include <iomanip> #include <set> #include <string> #include <utility> #include <vector> namespace thrill { namespace api { /******************************************************************************/ // DIABase StageBuilder class Stage { public: static constexpr bool debug = false; explicit Stage(const DIABasePtr& node) : node_(node), context_(node->context()) { } //! iterate over all target nodes into which this Stage pushes template <typename Lambda> void Targets(const Lambda& lambda) const { std::vector<DIABase*> children = node_->children(); std::reverse(children.begin(), children.end()); while (children.size()) { DIABase* child = children.back(); children.pop_back(); if (!child->CanExecute()) { // push children of Collapse onto stack std::vector<DIABase*> sub = child->children(); children.insert(children.end(), sub.begin(), sub.end()); lambda(child); } else { lambda(child); } } } //! compute a string to show all target nodes into which this Stage pushes. std::string TargetsString() const { std::ostringstream oss; std::vector<DIABase*> children = node_->children(); std::reverse(children.begin(), children.end()); oss << '['; while (children.size()) { DIABase* child = children.back(); children.pop_back(); if (child == nullptr) { oss << ']'; } else if (!child->CanExecute()) { // push children of Collapse onto stack std::vector<DIABase*> sub = child->children(); children.push_back(nullptr); children.insert(children.end(), sub.begin(), sub.end()); oss << *child << ' ' << '['; } else { oss << *child << ' '; } } oss << ']'; return oss.str(); } std::vector<size_t> TargetIds() const { std::vector<size_t> ids; Targets([&ids](DIABase* child) { ids.emplace_back(child->id()); }); return ids; } std::vector<DIABase*> TargetPtrs() const { std::vector<DIABase*> children; Targets([&children](DIABase* child) { children.emplace_back(child); }); return children; } void Execute() { sLOG << "START (EXECUTE) stage" << *node_ << "targets" << TargetsString(); std::vector<size_t> target_ids = TargetIds(); logger_ << "class" << "StageBuilder" << "event" << "execute-start" << "targets" << target_ids; DIAMemUse mem_use = node_->ExecuteMemUse(); if (mem_use.is_max()) mem_use = context_.mem_limit(); node_->set_mem_limit(mem_use); data::BlockPoolMemoryHolder mem_holder(context_.block_pool(), mem_use); common::StatsTimerStart timer; try { node_->Execute(); } catch (std::exception& e) { LOG1 << "StageBuilder: caught exception from Execute()" << " of stage " << *node_ << " - what(): " << e.what(); throw; } node_->set_state(DIAState::EXECUTED); timer.Stop(); sLOG << "FINISH (EXECUTE) stage" << *node_ << "targets" << TargetsString() << "took" << timer << "ms"; logger_ << "class" << "StageBuilder" << "event" << "execute-done" << "targets" << target_ids << "elapsed" << timer; } void PushData() { if (context_.consume() && node_->consume_counter() == 0) { sLOG1 << "StageBuilder: attempt to PushData on" << "stage" << *node_ << "failed, it was already consumed. Add .Keep()"; abort(); } sLOG << "START (PUSHDATA) stage" << *node_ << "targets" << TargetsString(); std::vector<size_t> target_ids = TargetIds(); logger_ << "class" << "StageBuilder" << "event" << "pushdata-start" << "targets" << target_ids; // collect memory requests of source node and all targeted children std::vector<DIABase*> targets = TargetPtrs(); const size_t mem_limit = context_.mem_limit(); std::vector<DIABase*> max_mem_nodes; size_t const_mem = 0; { // process node which will PushData() to targets DIAMemUse m = node_->PushDataMemUse(); if (m.is_max()) { max_mem_nodes.emplace_back(node_.get()); } else { const_mem += m.limit(); node_->set_mem_limit(m.limit()); } } { // process nodes which will receive data for (DIABase* target : TargetPtrs()) { DIAMemUse m = target->PreOpMemUse(); if (m.is_max()) { max_mem_nodes.emplace_back(target); } else { const_mem += m.limit(); target->set_mem_limit(m.limit()); } } } if (const_mem > mem_limit) { LOG1 << "StageBuilder: constant memory usage of DIANodes in Stage: " << const_mem << ", already exceeds Context's mem_limit: " << mem_limit; abort(); } // distribute remaining memory to nodes requesting maximum RAM amount if (max_mem_nodes.size()) { size_t remaining_mem = mem_limit - const_mem; remaining_mem /= max_mem_nodes.size(); if (context_.my_rank() == 0) { LOG1 << "StageBuilder: distribute remaining worker memory " << remaining_mem << " to " << max_mem_nodes.size() << " DIANodes"; } for (DIABase* target : max_mem_nodes) { target->set_mem_limit(remaining_mem); } // update const_mem: later allocate the mem limit of this worker const_mem = mem_limit; } // execute push data: hold memory for DIANodes, and remove filled // children afterwards data::BlockPoolMemoryHolder mem_holder(context_.block_pool(), const_mem); common::StatsTimerStart timer; try { node_->RunPushData(); } catch (std::exception& e) { LOG1 << "StageBuilder: caught exception from PushData()" << " of stage " << *node_ << " targets " << TargetsString() << " - what(): " << e.what(); throw; } node_->RemoveAllChildren(); timer.Stop(); sLOG << "FINISH (PUSHDATA) stage" << *node_ << "targets" << TargetsString() << "took" << timer << "ms"; logger_ << "class" << "StageBuilder" << "event" << "pushdata-done" << "targets" << target_ids << "elapsed" << timer; } //! order for std::set in FindStages() - this must be deterministic such //! that DIAs on different workers are executed in the same order. bool operator < (const Stage& s) const { return node_->id() < s.node_->id(); } //! shared pointer to node DIABasePtr node_; //! reference to Context of node Context& context_; //! reference to node's Logger. common::JsonLogger& logger_ { node_->logger_ }; //! temporary marker for toposort to detect cycles mutable bool cycle_mark_ = false; //! toposort seen marker mutable bool topo_seen_ = false; }; template <typename T> using mm_set = std::set<T, std::less<T>, mem::Allocator<T> >; //! Do a BFS on parents to find all DIANodes (Stages) needed to Execute or //! PushData to calculate this action node. static void FindStages(const DIABasePtr& action, mm_set<Stage>& stages) { static constexpr bool debug = Stage::debug; LOG << "Finding Stages:"; mem::deque<DIABasePtr> bfs_stack( mem::Allocator<DIABasePtr>(action->mem_manager())); bfs_stack.push_back(action); stages.insert(Stage(action)); while (!bfs_stack.empty()) { DIABasePtr curr = bfs_stack.front(); bfs_stack.pop_front(); for (const DIABasePtr& p : curr->parents()) { // if parents where not already seen, push onto stages if (stages.count(Stage(p))) continue; LOG << " Stage: " << *p; stages.insert(Stage(p)); if (p->CanExecute()) { // If parent was not executed push it to the BFS queue and // continue upwards. if state is EXECUTED, then we only need to // PushData(), which is already indicated by stages.insert(). if (p->state() == DIAState::NEW) bfs_stack.push_back(p); } else { // If parent cannot be executed (hold data) continue upward. bfs_stack.push_back(p); } } } } static void TopoSortVisit( const Stage& s, mm_set<Stage>& stages, mem::vector<Stage>& result) { // check markers die_unless(!s.cycle_mark_ && "Cycle in toposort of Stages? Impossible."); if (s.topo_seen_) return; s.cycle_mark_ = true; // iterate over all children of s which are in the to-be-calculate stages for (DIABase* child : s.node_->children()) { auto it = stages.find(Stage(child->shared_from_this())); // child not in stage set if (it == stages.end()) continue; // depth-first search TopoSortVisit(*it, stages, result); } s.topo_seen_ = true; s.cycle_mark_ = false; result.push_back(s); } static void TopoSortStages(mm_set<Stage>& stages, mem::vector<Stage>& result) { // iterate over all stages and visit nodes in DFS search for (const Stage& s : stages) { if (s.topo_seen_) continue; TopoSortVisit(s, stages, result); } } void DIABase::RunScope() { static constexpr bool debug = Stage::debug; LOG << "DIABase::Execute() this=" << *this; if (state_ == DIAState::EXECUTED) { LOG1 << "DIA node " << *this << " was already executed."; return; } if (!CanExecute()) { // CollapseNodes cannot be executed: execute their parent(s) for (const DIABasePtr& p : parents_) p->RunScope(); return; } mm_set<Stage> stages { mem::Allocator<Stage>(mem_manager()) }; FindStages(shared_from_this(), stages); mem::vector<Stage> toporder { mem::Allocator<Stage>(mem_manager()) }; TopoSortStages(stages, toporder); LOG << "Topological order"; for (auto top = toporder.rbegin(); top != toporder.rend(); ++top) { LOG << " " << *top->node_; } assert(toporder.front().node_.get() == this); while (toporder.size()) { Stage& s = toporder.back(); if (!s.node_->CanExecute()) { toporder.pop_back(); continue; } if (debug) mem::malloc_tracker_print_status(); if (s.node_->state() == DIAState::NEW) { s.Execute(); if (s.node_.get() != this) s.PushData(); } else if (s.node_->state() == DIAState::EXECUTED) { if (s.node_.get() != this) s.PushData(); } // remove from result stack, this may destroy the last shared_ptr // reference to a node. toporder.pop_back(); } } /******************************************************************************/ // DIABase //! make ostream-able. std::ostream& operator << (std::ostream& os, const DIABase& d) { return os << d.label() << '.' << d.id(); } } // namespace api } // namespace thrill /******************************************************************************/ <commit_msg>printing stages being executed by StageBuilder in output<commit_after>/******************************************************************************* * thrill/api/dia_base.cpp * * Part of Project Thrill - http://project-thrill.org * * Copyright (C) 2015 Sebastian Lamm <seba.lamm@gmail.com> * Copyright (C) 2016 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <thrill/api/dia_base.hpp> #include <thrill/common/json_logger.hpp> #include <thrill/common/logger.hpp> #include <thrill/common/stats_timer.hpp> #include <thrill/mem/allocator.hpp> #include <algorithm> #include <chrono> #include <deque> #include <functional> #include <iomanip> #include <set> #include <string> #include <utility> #include <vector> namespace thrill { namespace api { /******************************************************************************/ // DIABase StageBuilder class Stage { public: static constexpr bool debug = false; explicit Stage(const DIABasePtr& node) : node_(node), context_(node->context()) { } //! iterate over all target nodes into which this Stage pushes template <typename Lambda> void Targets(const Lambda& lambda) const { std::vector<DIABase*> children = node_->children(); std::reverse(children.begin(), children.end()); while (children.size()) { DIABase* child = children.back(); children.pop_back(); if (!child->CanExecute()) { // push children of Collapse onto stack std::vector<DIABase*> sub = child->children(); children.insert(children.end(), sub.begin(), sub.end()); lambda(child); } else { lambda(child); } } } //! compute a string to show all target nodes into which this Stage pushes. std::string TargetsString() const { std::ostringstream oss; std::vector<DIABase*> children = node_->children(); std::reverse(children.begin(), children.end()); bool first = true; oss << '['; while (children.size()) { DIABase* child = children.back(); children.pop_back(); if (child == nullptr) { oss << ']'; } else if (!child->CanExecute()) { // push children of Collapse onto stack std::vector<DIABase*> sub = child->children(); children.push_back(nullptr); children.insert(children.end(), sub.begin(), sub.end()); if (first) first = false; else oss << ' '; oss << *child << ' ' << '['; first = true; } else { if (first) first = false; else oss << ' '; oss << *child; } } oss << ']'; return oss.str(); } std::vector<size_t> TargetIds() const { std::vector<size_t> ids; Targets([&ids](DIABase* child) { ids.emplace_back(child->id()); }); return ids; } std::vector<DIABase*> TargetPtrs() const { std::vector<DIABase*> children; Targets([&children](DIABase* child) { children.emplace_back(child); }); return children; } void Execute() { sLOG << "START (EXECUTE) stage" << *node_ << "targets" << TargetsString(); if (context_.my_rank() == 0) { sLOG1 << "Execute() stage" << *node_; } std::vector<size_t> target_ids = TargetIds(); logger_ << "class" << "StageBuilder" << "event" << "execute-start" << "targets" << target_ids; DIAMemUse mem_use = node_->ExecuteMemUse(); if (mem_use.is_max()) mem_use = context_.mem_limit(); node_->set_mem_limit(mem_use); data::BlockPoolMemoryHolder mem_holder(context_.block_pool(), mem_use); common::StatsTimerStart timer; try { node_->Execute(); } catch (std::exception& e) { LOG1 << "StageBuilder: caught exception from Execute()" << " of stage " << *node_ << " - what(): " << e.what(); throw; } node_->set_state(DIAState::EXECUTED); timer.Stop(); sLOG << "FINISH (EXECUTE) stage" << *node_ << "targets" << TargetsString() << "took" << timer << "ms"; logger_ << "class" << "StageBuilder" << "event" << "execute-done" << "targets" << target_ids << "elapsed" << timer; } void PushData() { if (context_.consume() && node_->consume_counter() == 0) { sLOG1 << "StageBuilder: attempt to PushData on" << "stage" << *node_ << "failed, it was already consumed. Add .Keep()"; abort(); } sLOG << "START (PUSHDATA) stage" << *node_ << "targets" << TargetsString(); if (context_.my_rank() == 0) { sLOG1 << "PushData() stage" << *node_ << "with targets" << TargetsString(); } std::vector<size_t> target_ids = TargetIds(); logger_ << "class" << "StageBuilder" << "event" << "pushdata-start" << "targets" << target_ids; // collect memory requests of source node and all targeted children std::vector<DIABase*> targets = TargetPtrs(); const size_t mem_limit = context_.mem_limit(); std::vector<DIABase*> max_mem_nodes; size_t const_mem = 0; { // process node which will PushData() to targets DIAMemUse m = node_->PushDataMemUse(); if (m.is_max()) { max_mem_nodes.emplace_back(node_.get()); } else { const_mem += m.limit(); node_->set_mem_limit(m.limit()); } } { // process nodes which will receive data for (DIABase* target : TargetPtrs()) { DIAMemUse m = target->PreOpMemUse(); if (m.is_max()) { max_mem_nodes.emplace_back(target); } else { const_mem += m.limit(); target->set_mem_limit(m.limit()); } } } if (const_mem > mem_limit) { LOG1 << "StageBuilder: constant memory usage of DIANodes in Stage: " << const_mem << ", already exceeds Context's mem_limit: " << mem_limit; abort(); } // distribute remaining memory to nodes requesting maximum RAM amount if (max_mem_nodes.size()) { size_t remaining_mem = mem_limit - const_mem; remaining_mem /= max_mem_nodes.size(); if (context_.my_rank() == 0) { LOG << "StageBuilder: distribute remaining worker memory " << remaining_mem << " to " << max_mem_nodes.size() << " DIANodes"; } for (DIABase* target : max_mem_nodes) { target->set_mem_limit(remaining_mem); } // update const_mem: later allocate the mem limit of this worker const_mem = mem_limit; } // execute push data: hold memory for DIANodes, and remove filled // children afterwards data::BlockPoolMemoryHolder mem_holder(context_.block_pool(), const_mem); common::StatsTimerStart timer; try { node_->RunPushData(); } catch (std::exception& e) { LOG1 << "StageBuilder: caught exception from PushData()" << " of stage " << *node_ << " targets " << TargetsString() << " - what(): " << e.what(); throw; } node_->RemoveAllChildren(); timer.Stop(); sLOG << "FINISH (PUSHDATA) stage" << *node_ << "targets" << TargetsString() << "took" << timer << "ms"; logger_ << "class" << "StageBuilder" << "event" << "pushdata-done" << "targets" << target_ids << "elapsed" << timer; } //! order for std::set in FindStages() - this must be deterministic such //! that DIAs on different workers are executed in the same order. bool operator < (const Stage& s) const { return node_->id() < s.node_->id(); } //! shared pointer to node DIABasePtr node_; //! reference to Context of node Context& context_; //! reference to node's Logger. common::JsonLogger& logger_ { node_->logger_ }; //! temporary marker for toposort to detect cycles mutable bool cycle_mark_ = false; //! toposort seen marker mutable bool topo_seen_ = false; }; template <typename T> using mm_set = std::set<T, std::less<T>, mem::Allocator<T> >; //! Do a BFS on parents to find all DIANodes (Stages) needed to Execute or //! PushData to calculate this action node. static void FindStages(const DIABasePtr& action, mm_set<Stage>& stages) { static constexpr bool debug = Stage::debug; LOG << "Finding Stages:"; mem::deque<DIABasePtr> bfs_stack( mem::Allocator<DIABasePtr>(action->mem_manager())); bfs_stack.push_back(action); stages.insert(Stage(action)); while (!bfs_stack.empty()) { DIABasePtr curr = bfs_stack.front(); bfs_stack.pop_front(); for (const DIABasePtr& p : curr->parents()) { // if parents where not already seen, push onto stages if (stages.count(Stage(p))) continue; LOG << " Stage: " << *p; stages.insert(Stage(p)); if (p->CanExecute()) { // If parent was not executed push it to the BFS queue and // continue upwards. if state is EXECUTED, then we only need to // PushData(), which is already indicated by stages.insert(). if (p->state() == DIAState::NEW) bfs_stack.push_back(p); } else { // If parent cannot be executed (hold data) continue upward. bfs_stack.push_back(p); } } } } static void TopoSortVisit( const Stage& s, mm_set<Stage>& stages, mem::vector<Stage>& result) { // check markers die_unless(!s.cycle_mark_ && "Cycle in toposort of Stages? Impossible."); if (s.topo_seen_) return; s.cycle_mark_ = true; // iterate over all children of s which are in the to-be-calculate stages for (DIABase* child : s.node_->children()) { auto it = stages.find(Stage(child->shared_from_this())); // child not in stage set if (it == stages.end()) continue; // depth-first search TopoSortVisit(*it, stages, result); } s.topo_seen_ = true; s.cycle_mark_ = false; result.push_back(s); } static void TopoSortStages(mm_set<Stage>& stages, mem::vector<Stage>& result) { // iterate over all stages and visit nodes in DFS search for (const Stage& s : stages) { if (s.topo_seen_) continue; TopoSortVisit(s, stages, result); } } void DIABase::RunScope() { static constexpr bool debug = Stage::debug; LOG << "DIABase::Execute() this=" << *this; if (state_ == DIAState::EXECUTED) { LOG1 << "DIA node " << *this << " was already executed."; return; } if (!CanExecute()) { // CollapseNodes cannot be executed: execute their parent(s) for (const DIABasePtr& p : parents_) p->RunScope(); return; } mm_set<Stage> stages { mem::Allocator<Stage>(mem_manager()) }; FindStages(shared_from_this(), stages); mem::vector<Stage> toporder { mem::Allocator<Stage>(mem_manager()) }; TopoSortStages(stages, toporder); LOG << "Topological order"; for (auto top = toporder.rbegin(); top != toporder.rend(); ++top) { LOG << " " << *top->node_; } assert(toporder.front().node_.get() == this); while (toporder.size()) { Stage& s = toporder.back(); if (!s.node_->CanExecute()) { toporder.pop_back(); continue; } if (debug) mem::malloc_tracker_print_status(); if (s.node_->state() == DIAState::NEW) { s.Execute(); if (s.node_.get() != this) s.PushData(); } else if (s.node_->state() == DIAState::EXECUTED) { if (s.node_.get() != this) s.PushData(); } // remove from result stack, this may destroy the last shared_ptr // reference to a node. toporder.pop_back(); } } /******************************************************************************/ // DIABase //! make ostream-able. std::ostream& operator << (std::ostream& os, const DIABase& d) { return os << d.label() << '.' << d.id(); } } // namespace api } // namespace thrill /******************************************************************************/ <|endoftext|>
<commit_before>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. 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 WARRANNTY OF ANY KIND, EXPRESS OR IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* HIT_START * BUILD: %t %s * RUN: %t * HIT_END */ #include "test_common.h" #include <iostream> #include <complex> // Tolerance for error const double tolerance = 1e-6; const bool verbose = false; #define LEN 64 #define ALL_FUN \ OP(add) \ OP(sub) \ OP(mul) \ OP(div) \ OP(abs) \ OP(arg) \ OP(sin) \ OP(cos) #define OP(x) CK_##x, enum CalcKind { ALL_FUN }; #undef OP #define OP(x) case CK_##x: return #x; std::string getName(enum CalcKind CK) { switch(CK){ ALL_FUN } } #undef OP // Calculates function. // If the function has one argument, B is ignored. // If the function returns real number, converts it to a complex number. #define ONE_ARG(func) \ case CK_##func: \ return std::complex<FloatT>(std::func(A)); template<typename FloatT> __device__ __host__ std::complex<FloatT> calc(std::complex<FloatT> A, std::complex<FloatT> B, enum CalcKind CK) { switch(CK) { case CK_add: return A + B; case CK_sub: return A - B; case CK_mul: return A * B; case CK_div: return A / B; ONE_ARG(abs) ONE_ARG(arg) ONE_ARG(sin) ONE_ARG(cos) } } template<typename FloatT> __global__ void kernel(hipLaunchParm lp, std::complex<FloatT>* A, std::complex<FloatT>* B, std::complex<FloatT>* C, enum CalcKind CK) { int tx = threadIdx.x + blockIdx.x * blockDim.x; C[tx] = calc<FloatT>(A[tx], B[tx], CK); } template<typename FloatT> void test() { typedef std::complex<FloatT> ComplexT; ComplexT *A, *Ad, *B, *Bd, *C, *Cd, *D; A = new ComplexT[LEN]; B = new ComplexT[LEN]; C = new ComplexT[LEN]; D = new ComplexT[LEN]; hipMalloc((void**)&Ad, sizeof(ComplexT)*LEN); hipMalloc((void**)&Bd, sizeof(ComplexT)*LEN); hipMalloc((void**)&Cd, sizeof(ComplexT)*LEN); for (uint32_t i = 0; i < LEN; i++) { A[i] = ComplexT((i + 1) * 1.0f, (i + 2) * 1.0f); B[i] = A[i]; C[i] = A[i]; } hipMemcpy(Ad, A, sizeof(ComplexT)*LEN, hipMemcpyHostToDevice); hipMemcpy(Bd, B, sizeof(ComplexT)*LEN, hipMemcpyHostToDevice); // Run kernel for a calculation kind and verify by comparing with host // calculation result. Returns false if fails. auto test_fun = [&](enum CalcKind CK) { hipLaunchKernel(kernel<FloatT>, dim3(1), dim3(LEN), 0, 0, Ad, Bd, Cd, CK); hipMemcpy(C, Cd, sizeof(ComplexT)*LEN, hipMemcpyDeviceToHost); for (int i = 0; i < LEN; i++) { ComplexT Expected = calc(A[i], B[i], CK); FloatT error = std::abs(C[i] - Expected); if (std::abs(Expected) > tolerance) error /= std::abs(Expected); bool pass = error < tolerance; if (verbose || !pass) { std::cout << "Function: " << getName(CK) << " Operands: " << A[i] << " " << B[i] << " Result: " << C[i] << " Expected: " << Expected << " Error: " << error << " Pass: " << pass << std::endl; } if (!pass) return false; } return true; }; #define OP(x) assert(test_fun(CK_##x)); ALL_FUN #undef OP hipFree(Ad); hipFree(Bd); hipFree(Cd); delete[] A; delete[] B; delete[] C; delete[] D; } int main() { // ToDo: Fix bug in HCC causing linking error at -O0. #ifndef __HCC__ test<float>(); test<double>(); #endif passed(); return 0; } <commit_msg>[tests] Fixed build & disabled run of hipStdComplex on nvcc path<commit_after>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. 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 WARRANNTY OF ANY KIND, EXPRESS OR IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* HIT_START * BUILD: %t %s NVCC_OPTIONS -std=c++11 * RUN: %t EXCLUDE_HIP_PLATFORM nvcc * HIT_END */ #include "test_common.h" #include <iostream> #include <complex> // Tolerance for error const double tolerance = 1e-6; const bool verbose = false; #define LEN 64 #define ALL_FUN \ OP(add) \ OP(sub) \ OP(mul) \ OP(div) \ OP(abs) \ OP(arg) \ OP(sin) \ OP(cos) #define OP(x) CK_##x, enum CalcKind { ALL_FUN }; #undef OP #define OP(x) case CK_##x: return #x; std::string getName(enum CalcKind CK) { switch(CK){ ALL_FUN } } #undef OP // Calculates function. // If the function has one argument, B is ignored. // If the function returns real number, converts it to a complex number. #define ONE_ARG(func) \ case CK_##func: \ return std::complex<FloatT>(std::func(A)); template<typename FloatT> __device__ __host__ std::complex<FloatT> calc(std::complex<FloatT> A, std::complex<FloatT> B, enum CalcKind CK) { switch(CK) { case CK_add: return A + B; case CK_sub: return A - B; case CK_mul: return A * B; case CK_div: return A / B; ONE_ARG(abs) ONE_ARG(arg) ONE_ARG(sin) ONE_ARG(cos) } } template<typename FloatT> __global__ void kernel(hipLaunchParm lp, std::complex<FloatT>* A, std::complex<FloatT>* B, std::complex<FloatT>* C, enum CalcKind CK) { int tx = threadIdx.x + blockIdx.x * blockDim.x; C[tx] = calc<FloatT>(A[tx], B[tx], CK); } template<typename FloatT> void test() { typedef std::complex<FloatT> ComplexT; ComplexT *A, *Ad, *B, *Bd, *C, *Cd, *D; A = new ComplexT[LEN]; B = new ComplexT[LEN]; C = new ComplexT[LEN]; D = new ComplexT[LEN]; hipMalloc((void**)&Ad, sizeof(ComplexT)*LEN); hipMalloc((void**)&Bd, sizeof(ComplexT)*LEN); hipMalloc((void**)&Cd, sizeof(ComplexT)*LEN); for (uint32_t i = 0; i < LEN; i++) { A[i] = ComplexT((i + 1) * 1.0f, (i + 2) * 1.0f); B[i] = A[i]; C[i] = A[i]; } hipMemcpy(Ad, A, sizeof(ComplexT)*LEN, hipMemcpyHostToDevice); hipMemcpy(Bd, B, sizeof(ComplexT)*LEN, hipMemcpyHostToDevice); // Run kernel for a calculation kind and verify by comparing with host // calculation result. Returns false if fails. auto test_fun = [&](enum CalcKind CK) { hipLaunchKernel(kernel<FloatT>, dim3(1), dim3(LEN), 0, 0, Ad, Bd, Cd, CK); hipMemcpy(C, Cd, sizeof(ComplexT)*LEN, hipMemcpyDeviceToHost); for (int i = 0; i < LEN; i++) { ComplexT Expected = calc(A[i], B[i], CK); FloatT error = std::abs(C[i] - Expected); if (std::abs(Expected) > tolerance) error /= std::abs(Expected); bool pass = error < tolerance; if (verbose || !pass) { std::cout << "Function: " << getName(CK) << " Operands: " << A[i] << " " << B[i] << " Result: " << C[i] << " Expected: " << Expected << " Error: " << error << " Pass: " << pass << std::endl; } if (!pass) return false; } return true; }; #define OP(x) assert(test_fun(CK_##x)); ALL_FUN #undef OP hipFree(Ad); hipFree(Bd); hipFree(Cd); delete[] A; delete[] B; delete[] C; delete[] D; } int main() { // ToDo: Fix bug in HCC causing linking error at -O0. #ifndef __HCC__ test<float>(); test<double>(); #endif passed(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkOutputWindow.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkOutputWindow.h" #ifdef _WIN32 #include "vtkWin32OutputWindow.h" #endif #include "vtkObjectFactory.h" vtkOutputWindow* vtkOutputWindow::Instance = 0; void vtkOutputWindowDisplayText(const char* message) { vtkOutputWindow::GetInstance()->DisplayText(message); } vtkOutputWindow::vtkOutputWindow() { this->PromptUser = 0; } vtkOutputWindow::~vtkOutputWindow() { } void vtkOutputWindow::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "vtkOutputWindow Single instance = " << (void*)vtkOutputWindow::Instance; } // default implementation outputs to cerr only void vtkOutputWindow::DisplayText(const char* text) { cerr << text; if(this->PromptUser) { char c = 'n'; cerr << "\nDo you want to suppress any further messages (y,n)?." << endl; cin >> c; if(c == 'y') { vtkObject::GlobalWarningDisplayOff(); } } } class vtkOutputWindowSmartPointer { public: vtkOutputWindowSmartPointer() {}; void SetPointer(vtkOutputWindow* obj) { Pointer = obj; } ~vtkOutputWindowSmartPointer() { Pointer->Delete(); } private: vtkOutputWindow* Pointer; }; // Up the reference count so it behaves like New vtkOutputWindow* vtkOutputWindow::New() { vtkOutputWindow* ret = vtkOutputWindow::GetInstance(); ret->Register(NULL); return ret; } // Return the single instance of the vtkOutputWindow vtkOutputWindow* vtkOutputWindow::GetInstance() { // use this as a way of memory managment when the // program exits the static will be deleted which // will delete the Instance singleton static vtkOutputWindowSmartPointer smartPointer; if(!vtkOutputWindow::Instance) { // Try the factory first vtkOutputWindow::Instance = (vtkOutputWindow*) vtkObjectFactory::CreateInstance("vtkOutputWindow"); // if the factory did not provide one, then create it here if(!vtkOutputWindow::Instance) { #ifdef _WIN32 vtkOutputWindow::Instance = vtkWin32OutputWindow::New(); #else vtkOutputWindow::Instance = new vtkOutputWindow; #endif } // set the smart pointer to the instance, so // it will be UnRegister'ed at exit of the program smartPointer.SetPointer(vtkOutputWindow::Instance ); } // return the instance return vtkOutputWindow::Instance; } <commit_msg>ERR: fix PrintSelf defect<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkOutputWindow.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkOutputWindow.h" #ifdef _WIN32 #include "vtkWin32OutputWindow.h" #endif #include "vtkObjectFactory.h" vtkOutputWindow* vtkOutputWindow::Instance = 0; void vtkOutputWindowDisplayText(const char* message) { vtkOutputWindow::GetInstance()->DisplayText(message); } vtkOutputWindow::vtkOutputWindow() { this->PromptUser = 0; } vtkOutputWindow::~vtkOutputWindow() { } void vtkOutputWindow::PrintSelf(ostream& os, vtkIndent indent) { this->vtkObject::PrintSelf(os, indent); os << indent << "vtkOutputWindow Single instance = " << (void*)vtkOutputWindow::Instance << endl; os << indent << "PromptUser Flag: " << this->PromptUser << endl; } // default implementation outputs to cerr only void vtkOutputWindow::DisplayText(const char* text) { cerr << text; if(this->PromptUser) { char c = 'n'; cerr << "\nDo you want to suppress any further messages (y,n)?." << endl; cin >> c; if(c == 'y') { vtkObject::GlobalWarningDisplayOff(); } } } class vtkOutputWindowSmartPointer { public: vtkOutputWindowSmartPointer() {}; void SetPointer(vtkOutputWindow* obj) { Pointer = obj; } ~vtkOutputWindowSmartPointer() { Pointer->Delete(); } private: vtkOutputWindow* Pointer; }; // Up the reference count so it behaves like New vtkOutputWindow* vtkOutputWindow::New() { vtkOutputWindow* ret = vtkOutputWindow::GetInstance(); ret->Register(NULL); return ret; } // Return the single instance of the vtkOutputWindow vtkOutputWindow* vtkOutputWindow::GetInstance() { // use this as a way of memory managment when the // program exits the static will be deleted which // will delete the Instance singleton static vtkOutputWindowSmartPointer smartPointer; if(!vtkOutputWindow::Instance) { // Try the factory first vtkOutputWindow::Instance = (vtkOutputWindow*) vtkObjectFactory::CreateInstance("vtkOutputWindow"); // if the factory did not provide one, then create it here if(!vtkOutputWindow::Instance) { #ifdef _WIN32 vtkOutputWindow::Instance = vtkWin32OutputWindow::New(); #else vtkOutputWindow::Instance = new vtkOutputWindow; #endif } // set the smart pointer to the instance, so // it will be UnRegister'ed at exit of the program smartPointer.SetPointer(vtkOutputWindow::Instance ); } // return the instance return vtkOutputWindow::Instance; } <|endoftext|>
<commit_before>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2022 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 <chrono> // std::chrono #include <ctime> // std::time #include <iostream> // std::cout, std::cin, std::cerr #include <mutex> // std::mutex, std::scoped_lock #include <random> // std::generate_canonical, std::mt19937, std::random_device #include <stdint.h> // uint32_t etc. #include <thread> // std::thread #include <vector> // std::vector class Messenger { public: std::mutex my_mutex; }; class Random { public: Random(std::uniform_real_distribution<float>& distribution, std::mt19937& generator) : distribution { distribution }, generator { generator } { } float get_random() const { return this->distribution(this->generator); } std::mutex my_mutex; private: std::uniform_real_distribution<float>& distribution; std::mt19937& generator; }; class Fork { public: Fork() { // constructor. } std::mutex my_mutex; }; class Philosopher { public: Philosopher(Messenger& messenger, Random& random, const uint32_t id, Fork& left_fork, Fork& right_fork) : messenger { messenger }, random { random }, left_fork { left_fork }, right_fork { right_fork }, id { id } { // constructor. const std::lock_guard<std::mutex> messenger_lock(this->messenger.my_mutex); std::cout << "Philosopher " << this->id << " says hello!\n"; } void eat() const { const std::scoped_lock fork_lock(this->left_fork.my_mutex, this->right_fork.my_mutex); float eat_time = 0.0f; { const std::lock_guard<std::mutex> random_lock(this->random.my_mutex); eat_time = this->random.get_random(); } { const std::lock_guard<std::mutex> messenger_lock(this->messenger.my_mutex); std::cout << "Philosopher " << this->id << " is eating for " << eat_time << " seconds...\n"; } std::this_thread::sleep_for(std::chrono::duration<float>(eat_time)); } void think() const { float think_time = 0.0f; { const std::lock_guard<std::mutex> random_lock(this->random.my_mutex); think_time = this->random.get_random(); } { const std::lock_guard<std::mutex> messenger_lock(this->messenger.my_mutex); std::cout << "Philosopher " << this->id << " is thinking for " << think_time << " seconds...\n"; } std::this_thread::sleep_for(std::chrono::duration<float>(think_time)); } void philosophize() const { while (true) { eat(); think(); } } private: Messenger& messenger; Random& random; Fork& left_fork; Fork& right_fork; const uint32_t id; }; class Table { public: Table(const uint32_t n_philosophers, Messenger& messenger, Random& random) : n_philosophers { n_philosophers }, messenger { messenger }, random { random }, forks(n_philosophers) { // constructor. this->philosophers.reserve(this->n_philosophers); if (this->n_philosophers > 0) { this->philosophers.emplace_back(this->messenger, this->random, 0, this->forks.back(), this->forks.front()); } for (uint32_t id = 1; id < this->n_philosophers; id++) { this->philosophers.emplace_back(this->messenger, this->random, id, this->forks.at(id - 1), this->forks.at(id)); } this->threads.resize(this->n_philosophers); } void dine() { for (uint32_t i = 0; i < this->n_philosophers; i++) { this->threads.at(i) = std::thread { &Philosopher::philosophize, this->philosophers.at(i) }; } } void cleanup() { for (std::thread& my_thread : this->threads) { my_thread.join(); } } const uint32_t n_philosophers; Messenger& messenger; Random& random; std::vector<Fork> forks; std::vector<Philosopher> philosophers; std::vector<std::thread> threads; }; int main() { std::random_device random_device; std::uniform_real_distribution<float> distribution(0.0f, 0.1f); std::mt19937 generator(random_device()); Messenger messenger; Random random(distribution, generator); Table table(5, messenger, random); table.dine(); table.cleanup(); } <commit_msg>Edit whitespace.<commit_after>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2022 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 <chrono> // std::chrono #include <ctime> // std::time #include <iostream> // std::cout, std::cin, std::cerr #include <mutex> // std::mutex, std::scoped_lock #include <random> // std::generate_canonical, std::mt19937, std::random_device #include <stdint.h> // uint32_t etc. #include <thread> // std::thread #include <vector> // std::vector class Messenger { public: std::mutex my_mutex; }; class Random { public: Random(std::uniform_real_distribution<float>& distribution, std::mt19937& generator) : distribution { distribution }, generator { generator } { } float get_random() const { return this->distribution(this->generator); } std::mutex my_mutex; private: std::uniform_real_distribution<float>& distribution; std::mt19937& generator; }; class Fork { public: Fork() { // constructor. } std::mutex my_mutex; }; class Philosopher { public: Philosopher(Messenger& messenger, Random& random, const uint32_t id, Fork& left_fork, Fork& right_fork) : messenger { messenger }, random { random }, left_fork { left_fork }, right_fork { right_fork }, id { id } { // constructor. const std::lock_guard<std::mutex> messenger_lock(this->messenger.my_mutex); std::cout << "Philosopher " << this->id << " says hello!\n"; } void eat() const { const std::scoped_lock fork_lock(this->left_fork.my_mutex, this->right_fork.my_mutex); float eat_time = 0.0f; { const std::lock_guard<std::mutex> random_lock(this->random.my_mutex); eat_time = this->random.get_random(); } { const std::lock_guard<std::mutex> messenger_lock(this->messenger.my_mutex); std::cout << "Philosopher " << this->id << " is eating for " << eat_time << " seconds...\n"; } std::this_thread::sleep_for(std::chrono::duration<float>(eat_time)); } void think() const { float think_time = 0.0f; { const std::lock_guard<std::mutex> random_lock(this->random.my_mutex); think_time = this->random.get_random(); } { const std::lock_guard<std::mutex> messenger_lock(this->messenger.my_mutex); std::cout << "Philosopher " << this->id << " is thinking for " << think_time << " seconds...\n"; } std::this_thread::sleep_for(std::chrono::duration<float>(think_time)); } void philosophize() const { while (true) { eat(); think(); } } private: Messenger& messenger; Random& random; Fork& left_fork; Fork& right_fork; const uint32_t id; }; class Table { public: Table(const uint32_t n_philosophers, Messenger& messenger, Random& random) : n_philosophers { n_philosophers }, messenger { messenger }, random { random }, forks(n_philosophers) { // constructor. this->philosophers.reserve(this->n_philosophers); if (this->n_philosophers > 0) { this->philosophers.emplace_back(this->messenger, this->random, 0, this->forks.back(), this->forks.front()); } for (uint32_t id = 1; id < this->n_philosophers; id++) { this->philosophers.emplace_back(this->messenger, this->random, id, this->forks.at(id - 1), this->forks.at(id)); } this->threads.resize(this->n_philosophers); } void dine() { for (uint32_t i = 0; i < this->n_philosophers; i++) { this->threads.at(i) = std::thread { &Philosopher::philosophize, this->philosophers.at(i) }; } } void cleanup() { for (std::thread& my_thread : this->threads) { my_thread.join(); } } const uint32_t n_philosophers; Messenger& messenger; Random& random; std::vector<Fork> forks; std::vector<Philosopher> philosophers; std::vector<std::thread> threads; }; int main() { std::random_device random_device; std::uniform_real_distribution<float> distribution(0.0f, 0.1f); std::mt19937 generator(random_device()); Messenger messenger; Random random(distribution, generator); Table table(5, messenger, random); table.dine(); table.cleanup(); } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////// // ---- CORRECTION FRAMEWORK ---- // Class to cut on the number of AliTrackReference's // for each detector. Applies on pair of tracks (AliCFPair) /////////////////////////////////////////////////////////////////////////// // author : R. Vernet (renaud.vernet@cern.ch) /////////////////////////////////////////////////////////////////////////// #include "AliMCParticle.h" #include "AliCFPairAcceptanceCuts.h" #include "AliMCEvent.h" #include "TBits.h" #include "AliLog.h" ClassImp(AliCFPairAcceptanceCuts) //______________________________ AliCFPairAcceptanceCuts::AliCFPairAcceptanceCuts() : AliCFCutBase(), fMCInfo(0x0), fCutNeg(new AliCFAcceptanceCuts()), fCutPos(new AliCFAcceptanceCuts()), fBitmap(new TBits(0)) { // //Default Constructor // } //______________________________ AliCFPairAcceptanceCuts::AliCFPairAcceptanceCuts(const Char_t* name, const Char_t* title) : AliCFCutBase(name,title), fMCInfo(0x0), fCutNeg(new AliCFAcceptanceCuts(name,title)), fCutPos(new AliCFAcceptanceCuts(name,title)), fBitmap(new TBits(0)) { // //Named Constructor // } //______________________________ AliCFPairAcceptanceCuts::AliCFPairAcceptanceCuts(const AliCFPairAcceptanceCuts& c) : AliCFCutBase(c), fMCInfo(c.fMCInfo), fCutNeg(c.fCutNeg), fCutPos(c.fCutPos), fBitmap(c.fBitmap) { // //Copy Constructor // } //______________________________ AliCFPairAcceptanceCuts& AliCFPairAcceptanceCuts::operator=(const AliCFPairAcceptanceCuts& c) { // // Assignment operator // if (this != &c) { AliCFCutBase::operator=(c) ; fMCInfo = c.fMCInfo ; fCutNeg = c.fCutNeg ; fCutPos = c.fCutPos ; fBitmap = c.fBitmap ; } return *this ; } //__________________________________________________________ Bool_t AliCFPairAcceptanceCuts::IsSelected(TObject* obj) { // // checks the number of track references associated to 'obj' // 'obj' must be an AliMCParticle // // // check if selections on 'obj' are passed // 'obj' must be an AliMCParticle // SelectionBitMap(obj); // if (fIsQAOn) FillHistograms(obj,kFALSE); Bool_t isSelected = kTRUE; for (UInt_t icut=0; icut<fBitmap->GetNbits(); icut++) { if (!fBitmap->TestBitNumber(icut)) { isSelected = kFALSE; break; } } if (!isSelected) return kFALSE ; // if (fIsQAOn) FillHistograms(obj,kTRUE); return kTRUE; } //__________________________________________________________ void AliCFPairAcceptanceCuts::SelectionBitMap(TObject* obj) { // // test if the track passes the single cuts // and store the information in a bitmap // for (UInt_t i=0; i<kNCuts; i++) fBitmap->SetBitNumber(i,kFALSE); if (!obj) return; TString className(obj->ClassName()); if (className.CompareTo("AliMCParticle") != 0) { AliError("obj must point to an AliMCParticle !"); return ; } TParticle* part = (dynamic_cast<AliMCParticle*>(obj))->Particle() ; if (!part || part->GetNDaughters() !=2) return ; Int_t lab0 = part->GetDaughter(0); Int_t lab1 = part->GetDaughter(1); AliMCParticle* negDaughter = fMCInfo->GetTrack(lab0) ; AliMCParticle* posDaughter = fMCInfo->GetTrack(lab1) ; Int_t iCutBit = 0; if (fCutNeg->IsSelected(negDaughter)) fBitmap->SetBitNumber(iCutBit,kTRUE); iCutBit++; if (fCutPos->IsSelected(posDaughter)) fBitmap->SetBitNumber(iCutBit,kTRUE); } //______________________________ void AliCFPairAcceptanceCuts::SetEvtInfo(TObject* mcInfo) { // // Sets pointer to MC event information (AliMCEvent) // if (!mcInfo) { Error("SetEvtInfo","Pointer to MC Event is null !"); return; } TString className(mcInfo->ClassName()); if (className.CompareTo("AliMCEvent") != 0) { Error("SetEvtInfo","argument must point to an AliMCEvent !"); return ; } fMCInfo = (AliMCEvent*) mcInfo ; } <commit_msg>Cast to AliMCParticle* needed with new implementation of AliMCEvent<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////// // ---- CORRECTION FRAMEWORK ---- // Class to cut on the number of AliTrackReference's // for each detector. Applies on pair of tracks (AliCFPair) /////////////////////////////////////////////////////////////////////////// // author : R. Vernet (renaud.vernet@cern.ch) /////////////////////////////////////////////////////////////////////////// #include "AliMCParticle.h" #include "AliCFPairAcceptanceCuts.h" #include "AliMCEvent.h" #include "TBits.h" #include "AliLog.h" ClassImp(AliCFPairAcceptanceCuts) //______________________________ AliCFPairAcceptanceCuts::AliCFPairAcceptanceCuts() : AliCFCutBase(), fMCInfo(0x0), fCutNeg(new AliCFAcceptanceCuts()), fCutPos(new AliCFAcceptanceCuts()), fBitmap(new TBits(0)) { // //Default Constructor // } //______________________________ AliCFPairAcceptanceCuts::AliCFPairAcceptanceCuts(const Char_t* name, const Char_t* title) : AliCFCutBase(name,title), fMCInfo(0x0), fCutNeg(new AliCFAcceptanceCuts(name,title)), fCutPos(new AliCFAcceptanceCuts(name,title)), fBitmap(new TBits(0)) { // //Named Constructor // } //______________________________ AliCFPairAcceptanceCuts::AliCFPairAcceptanceCuts(const AliCFPairAcceptanceCuts& c) : AliCFCutBase(c), fMCInfo(c.fMCInfo), fCutNeg(c.fCutNeg), fCutPos(c.fCutPos), fBitmap(c.fBitmap) { // //Copy Constructor // } //______________________________ AliCFPairAcceptanceCuts& AliCFPairAcceptanceCuts::operator=(const AliCFPairAcceptanceCuts& c) { // // Assignment operator // if (this != &c) { AliCFCutBase::operator=(c) ; fMCInfo = c.fMCInfo ; fCutNeg = c.fCutNeg ; fCutPos = c.fCutPos ; fBitmap = c.fBitmap ; } return *this ; } //__________________________________________________________ Bool_t AliCFPairAcceptanceCuts::IsSelected(TObject* obj) { // // checks the number of track references associated to 'obj' // 'obj' must be an AliMCParticle // // // check if selections on 'obj' are passed // 'obj' must be an AliMCParticle // SelectionBitMap(obj); // if (fIsQAOn) FillHistograms(obj,kFALSE); Bool_t isSelected = kTRUE; for (UInt_t icut=0; icut<fBitmap->GetNbits(); icut++) { if (!fBitmap->TestBitNumber(icut)) { isSelected = kFALSE; break; } } if (!isSelected) return kFALSE ; // if (fIsQAOn) FillHistograms(obj,kTRUE); return kTRUE; } //__________________________________________________________ void AliCFPairAcceptanceCuts::SelectionBitMap(TObject* obj) { // // test if the track passes the single cuts // and store the information in a bitmap // for (UInt_t i=0; i<kNCuts; i++) fBitmap->SetBitNumber(i,kFALSE); if (!obj) return; TString className(obj->ClassName()); if (className.CompareTo("AliMCParticle") != 0) { AliError("obj must point to an AliMCParticle !"); return ; } TParticle* part = (dynamic_cast<AliMCParticle*>(obj))->Particle() ; if (!part || part->GetNDaughters() !=2) return ; Int_t lab0 = part->GetDaughter(0); Int_t lab1 = part->GetDaughter(1); AliMCParticle* negDaughter = (AliMCParticle*) fMCInfo->GetTrack(lab0) ; AliMCParticle* posDaughter = (AliMCParticle*) fMCInfo->GetTrack(lab1) ; Int_t iCutBit = 0; if (fCutNeg->IsSelected(negDaughter)) fBitmap->SetBitNumber(iCutBit,kTRUE); iCutBit++; if (fCutPos->IsSelected(posDaughter)) fBitmap->SetBitNumber(iCutBit,kTRUE); } //______________________________ void AliCFPairAcceptanceCuts::SetEvtInfo(TObject* mcInfo) { // // Sets pointer to MC event information (AliMCEvent) // if (!mcInfo) { Error("SetEvtInfo","Pointer to MC Event is null !"); return; } TString className(mcInfo->ClassName()); if (className.CompareTo("AliMCEvent") != 0) { Error("SetEvtInfo","argument must point to an AliMCEvent !"); return ; } fMCInfo = (AliMCEvent*) mcInfo ; } <|endoftext|>
<commit_before><commit_msg>New tests for `Variable::set`.<commit_after><|endoftext|>
<commit_before>/* * statusspec.cpp * StatusSpec project * * Copyright (c) 2014 thesupremecommander * BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause * */ #include "statusspec.h" AntiFreeze *g_AntiFreeze = nullptr; Killstreaks *g_Killstreaks = nullptr; LoadoutIcons *g_LoadoutIcons = nullptr; LocalPlayer *g_LocalPlayer = nullptr; MedigunInfo *g_MedigunInfo = nullptr; MultiPanel *g_MultiPanel = nullptr; PlayerAliases *g_PlayerAliases = nullptr; PlayerOutlines *g_PlayerOutlines = nullptr; StatusIcons *g_StatusIcons = nullptr; static IGameResources* gameResources = nullptr; static int getGlowEffectColorHook; ObserverInfo_t GetLocalPlayerObserverInfo() { int player = Interfaces::pEngineClient->GetLocalPlayer(); IClientEntity *playerEntity = Interfaces::pClientEntityList->GetClientEntity(player); ObserverInfo_t info; if (dynamic_cast<C_BasePlayer *>(playerEntity->GetBaseEntity())) { info.mode = Funcs::CallFunc_C_TFPlayer_GetObserverMode((C_TFPlayer *)playerEntity); info.target = Funcs::CallFunc_C_TFPlayer_GetObserverTarget((C_TFPlayer *)playerEntity); } return info; } int Detour_GetLocalPlayerIndex() { if (g_LocalPlayer) { if (g_LocalPlayer->IsEnabled()) { return g_LocalPlayer->GetLocalPlayerIndexOverride(); } } return Funcs::CallFunc_GetLocalPlayerIndex(); } void Hook_C_TFPlayer_GetGlowEffectColor(float *r, float *g, float *b) { if (g_PlayerOutlines) { if (g_PlayerOutlines->IsEnabled()) { C_TFPlayer *tfPlayer = META_IFACEPTR(C_TFPlayer); if (g_PlayerOutlines->GetGlowEffectColorOverride(tfPlayer, r, g, b)) { RETURN_META(MRES_SUPERCEDE); } } } RETURN_META(MRES_IGNORED); } void Hook_IBaseClientDLL_FrameStageNotify(ClientFrameStage_t curStage) { if (curStage == FRAME_RENDER_START) { if (g_LoadoutIcons) { if (g_LoadoutIcons->IsEnabled()) { g_LoadoutIcons->PreEntityUpdate(); } } if (g_MedigunInfo) { if (g_MedigunInfo->IsEnabled()) { g_MedigunInfo->PreEntityUpdate(); } } if (g_StatusIcons) { if (g_StatusIcons->IsEnabled()) { g_StatusIcons->PreEntityUpdate(); } } int maxEntity = Interfaces::pClientEntityList->GetHighestEntityIndex(); for (int i = 0; i < maxEntity; i++) { IClientEntity *entity = Interfaces::pClientEntityList->GetClientEntity(i); if (!entity) { continue; } if (!getGlowEffectColorHook && Entities::CheckClassBaseclass(entity->GetClientClass(), "DT_TFPlayer")) { getGlowEffectColorHook = Funcs::AddHook_C_TFPlayer_GetGlowEffectColor((C_TFPlayer *)entity, Hook_C_TFPlayer_GetGlowEffectColor); } if (g_AntiFreeze) { g_AntiFreeze->ProcessEntity(entity); } if (g_LoadoutIcons) { if (g_LoadoutIcons->IsEnabled()) { g_LoadoutIcons->ProcessEntity(entity); } } if (g_MedigunInfo) { if (g_MedigunInfo->IsEnabled()) { g_MedigunInfo->ProcessEntity(entity); } } if (g_PlayerOutlines) { g_PlayerOutlines->ProcessEntity(entity); } if (g_StatusIcons) { if (g_StatusIcons->IsEnabled()) { g_StatusIcons->ProcessEntity(entity); } } } if (g_AntiFreeze) { g_AntiFreeze->PostEntityUpdate(); } if (g_Killstreaks) { g_Killstreaks->PostEntityUpdate(); } if (g_LoadoutIcons) { if (g_LoadoutIcons->IsEnabled()) { g_LoadoutIcons->PostEntityUpdate(); } } if (g_LocalPlayer) { if (g_LocalPlayer->IsEnabled()) { g_LocalPlayer->PostEntityUpdate(); } } } RETURN_META(MRES_IGNORED); } bool Hook_IGameEventManager2_FireEvent(IGameEvent *event, bool bDontBroadcast) { IGameEvent *newEvent = Interfaces::pGameEventManager->DuplicateEvent(event); if (g_Killstreaks->FireEvent(newEvent)) { Interfaces::pGameEventManager->FreeEvent(event); RETURN_META_VALUE_NEWPARAMS(MRES_HANDLED, false, &IGameEventManager2::FireEvent, (newEvent, bDontBroadcast)); } else { Interfaces::pGameEventManager->FreeEvent(newEvent); RETURN_META_VALUE(MRES_IGNORED, false); } } bool Hook_IGameEventManager2_FireEventClientSide(IGameEvent *event) { IGameEvent *newEvent = Interfaces::pGameEventManager->DuplicateEvent(event); if (g_Killstreaks->FireEvent(newEvent)) { Interfaces::pGameEventManager->FreeEvent(event); RETURN_META_VALUE_NEWPARAMS(MRES_HANDLED, false, &IGameEventManager2::FireEventClientSide, (newEvent)); } else { Interfaces::pGameEventManager->FreeEvent(newEvent); RETURN_META_VALUE(MRES_IGNORED, false); } } void Hook_IPanel_PaintTraverse(vgui::VPANEL vguiPanel, bool forceRepaint, bool allowForce = true) { if (Interfaces::pEngineClient->IsDrawingLoadingImage() || !Interfaces::pEngineClient->IsInGame() || !Interfaces::pEngineClient->IsConnected() || Interfaces::pEngineClient->Con_IsVisible()) { RETURN_META(MRES_IGNORED); } if (g_AntiFreeze) { if (g_AntiFreeze->IsEnabled()) { g_AntiFreeze->Paint(vguiPanel); } } if (g_LoadoutIcons) { if (g_LoadoutIcons->IsEnabled()) { g_LoadoutIcons->Paint(vguiPanel); } } if (g_MedigunInfo) { if (g_MedigunInfo->IsEnabled()) { g_MedigunInfo->Paint(vguiPanel); } } if (g_PlayerOutlines) { if (g_PlayerOutlines->IsEnabled() && g_PlayerOutlines->IsFrequentOverrideEnabled()) { g_PlayerOutlines->Paint(vguiPanel); } } if (g_StatusIcons) { if (g_StatusIcons->IsEnabled()) { g_StatusIcons->Paint(vguiPanel); } else { g_StatusIcons->NoPaint(vguiPanel); } } RETURN_META(MRES_IGNORED); } void Hook_IPanel_SendMessage(vgui::VPANEL vguiPanel, KeyValues *params, vgui::VPANEL ifromPanel) { if (g_LoadoutIcons) { if (g_LoadoutIcons->IsEnabled()) { g_LoadoutIcons->InterceptMessage(vguiPanel, params, ifromPanel); } } if (g_StatusIcons) { if (g_StatusIcons->IsEnabled()) { g_StatusIcons->InterceptMessage(vguiPanel, params, ifromPanel); } } RETURN_META(MRES_IGNORED); } bool Hook_IVEngineClient_GetPlayerInfo(int ent_num, player_info_t *pinfo) { if (g_PlayerAliases) { if (g_PlayerAliases->IsEnabled()) { RETURN_META_VALUE(MRES_SUPERCEDE, g_PlayerAliases->GetPlayerInfoOverride(ent_num, pinfo)); } } RETURN_META_VALUE(MRES_IGNORED, false); } // The plugin is a static singleton that is exported as an interface StatusSpecPlugin g_StatusSpecPlugin; EXPOSE_SINGLE_INTERFACE_GLOBALVAR(StatusSpecPlugin, IServerPluginCallbacks, INTERFACEVERSION_ISERVERPLUGINCALLBACKS, g_StatusSpecPlugin); StatusSpecPlugin::StatusSpecPlugin() { } StatusSpecPlugin::~StatusSpecPlugin() { } bool StatusSpecPlugin::Load(CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory) { if (!Interfaces::Load(interfaceFactory, gameServerFactory)) { Warning("[%s] Unable to load required libraries!\n", PLUGIN_DESC); return false; } if (!Entities::PrepareOffsets()) { Warning("[%s] Unable to determine proper offsets!\n", PLUGIN_DESC); return false; } if (!Funcs::Load()) { Warning("[%s] Unable to initialize hooking!", PLUGIN_DESC); return false; } Funcs::AddDetour_GetLocalPlayerIndex(Detour_GetLocalPlayerIndex); Funcs::AddHook_IBaseClientDLL_FrameStageNotify(Interfaces::pClientDLL, Hook_IBaseClientDLL_FrameStageNotify); Funcs::AddHook_IGameEventManager2_FireEvent(Interfaces::pGameEventManager, Hook_IGameEventManager2_FireEvent); Funcs::AddHook_IGameEventManager2_FireEventClientSide(Interfaces::pGameEventManager, Hook_IGameEventManager2_FireEventClientSide); Funcs::AddHook_IPanel_PaintTraverse(g_pVGuiPanel, Hook_IPanel_PaintTraverse); Funcs::AddHook_IPanel_SendMessage(g_pVGuiPanel, Hook_IPanel_SendMessage); Funcs::AddHook_IVEngineClient_GetPlayerInfo(Interfaces::pEngineClient, Hook_IVEngineClient_GetPlayerInfo); ConVar_Register(); g_AntiFreeze = new AntiFreeze(); g_Killstreaks = new Killstreaks(); g_LoadoutIcons = new LoadoutIcons(); g_LocalPlayer = new LocalPlayer(); g_MedigunInfo = new MedigunInfo(); g_MultiPanel = new MultiPanel(); g_PlayerAliases = new PlayerAliases(); g_PlayerOutlines = new PlayerOutlines(); g_StatusIcons = new StatusIcons(); Msg("%s loaded!\n", PLUGIN_DESC); return true; } void StatusSpecPlugin::Unload(void) { delete g_AntiFreeze; delete g_Killstreaks; delete g_LoadoutIcons; delete g_LocalPlayer; delete g_MedigunInfo; delete g_MultiPanel; delete g_PlayerAliases; delete g_PlayerOutlines; delete g_StatusIcons; Funcs::Unload(); ConVar_Unregister(); Interfaces::Unload(); } void StatusSpecPlugin::Pause(void) { Funcs::Pause(); } void StatusSpecPlugin::UnPause(void) { Funcs::Unpause(); } const char *StatusSpecPlugin::GetPluginDescription(void) { return PLUGIN_DESC; } void StatusSpecPlugin::LevelInit(char const *pMapName) {} void StatusSpecPlugin::ServerActivate(edict_t *pEdictList, int edictCount, int clientMax) {} void StatusSpecPlugin::GameFrame(bool simulating) {} void StatusSpecPlugin::LevelShutdown(void) {} void StatusSpecPlugin::ClientActive(edict_t *pEntity) {} void StatusSpecPlugin::ClientDisconnect(edict_t *pEntity) {} void StatusSpecPlugin::ClientPutInServer(edict_t *pEntity, char const *playername) {} void StatusSpecPlugin::SetCommandClient(int index) {} void StatusSpecPlugin::ClientSettingsChanged(edict_t *pEdict) {} PLUGIN_RESULT StatusSpecPlugin::ClientConnect(bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen) { return PLUGIN_CONTINUE; } PLUGIN_RESULT StatusSpecPlugin::ClientCommand(edict_t *pEntity, const CCommand &args) { return PLUGIN_CONTINUE; } PLUGIN_RESULT StatusSpecPlugin::NetworkIDValidated(const char *pszUserName, const char *pszNetworkID) { return PLUGIN_CONTINUE; } void StatusSpecPlugin::OnQueryCvarValueFinished(QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue) {} void StatusSpecPlugin::OnEdictAllocated(edict_t *edict) {} void StatusSpecPlugin::OnEdictFreed(const edict_t *edict) {}<commit_msg>Don't run this if it isn't enabled.<commit_after>/* * statusspec.cpp * StatusSpec project * * Copyright (c) 2014 thesupremecommander * BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause * */ #include "statusspec.h" AntiFreeze *g_AntiFreeze = nullptr; Killstreaks *g_Killstreaks = nullptr; LoadoutIcons *g_LoadoutIcons = nullptr; LocalPlayer *g_LocalPlayer = nullptr; MedigunInfo *g_MedigunInfo = nullptr; MultiPanel *g_MultiPanel = nullptr; PlayerAliases *g_PlayerAliases = nullptr; PlayerOutlines *g_PlayerOutlines = nullptr; StatusIcons *g_StatusIcons = nullptr; static IGameResources* gameResources = nullptr; static int getGlowEffectColorHook; ObserverInfo_t GetLocalPlayerObserverInfo() { int player = Interfaces::pEngineClient->GetLocalPlayer(); IClientEntity *playerEntity = Interfaces::pClientEntityList->GetClientEntity(player); ObserverInfo_t info; if (dynamic_cast<C_BasePlayer *>(playerEntity->GetBaseEntity())) { info.mode = Funcs::CallFunc_C_TFPlayer_GetObserverMode((C_TFPlayer *)playerEntity); info.target = Funcs::CallFunc_C_TFPlayer_GetObserverTarget((C_TFPlayer *)playerEntity); } return info; } int Detour_GetLocalPlayerIndex() { if (g_LocalPlayer) { if (g_LocalPlayer->IsEnabled()) { return g_LocalPlayer->GetLocalPlayerIndexOverride(); } } return Funcs::CallFunc_GetLocalPlayerIndex(); } void Hook_C_TFPlayer_GetGlowEffectColor(float *r, float *g, float *b) { if (g_PlayerOutlines) { if (g_PlayerOutlines->IsEnabled()) { C_TFPlayer *tfPlayer = META_IFACEPTR(C_TFPlayer); if (g_PlayerOutlines->GetGlowEffectColorOverride(tfPlayer, r, g, b)) { RETURN_META(MRES_SUPERCEDE); } } } RETURN_META(MRES_IGNORED); } void Hook_IBaseClientDLL_FrameStageNotify(ClientFrameStage_t curStage) { if (curStage == FRAME_RENDER_START) { if (g_LoadoutIcons) { if (g_LoadoutIcons->IsEnabled()) { g_LoadoutIcons->PreEntityUpdate(); } } if (g_MedigunInfo) { if (g_MedigunInfo->IsEnabled()) { g_MedigunInfo->PreEntityUpdate(); } } if (g_StatusIcons) { if (g_StatusIcons->IsEnabled()) { g_StatusIcons->PreEntityUpdate(); } } int maxEntity = Interfaces::pClientEntityList->GetHighestEntityIndex(); for (int i = 0; i < maxEntity; i++) { IClientEntity *entity = Interfaces::pClientEntityList->GetClientEntity(i); if (!entity) { continue; } if (!getGlowEffectColorHook && Entities::CheckClassBaseclass(entity->GetClientClass(), "DT_TFPlayer")) { getGlowEffectColorHook = Funcs::AddHook_C_TFPlayer_GetGlowEffectColor((C_TFPlayer *)entity, Hook_C_TFPlayer_GetGlowEffectColor); } if (g_AntiFreeze) { g_AntiFreeze->ProcessEntity(entity); } if (g_LoadoutIcons) { if (g_LoadoutIcons->IsEnabled()) { g_LoadoutIcons->ProcessEntity(entity); } } if (g_MedigunInfo) { if (g_MedigunInfo->IsEnabled()) { g_MedigunInfo->ProcessEntity(entity); } } if (g_PlayerOutlines) { g_PlayerOutlines->ProcessEntity(entity); } if (g_StatusIcons) { if (g_StatusIcons->IsEnabled()) { g_StatusIcons->ProcessEntity(entity); } } } if (g_AntiFreeze) { g_AntiFreeze->PostEntityUpdate(); } if (g_Killstreaks) { g_Killstreaks->PostEntityUpdate(); } if (g_LoadoutIcons) { if (g_LoadoutIcons->IsEnabled()) { g_LoadoutIcons->PostEntityUpdate(); } } if (g_LocalPlayer) { if (g_LocalPlayer->IsEnabled()) { g_LocalPlayer->PostEntityUpdate(); } } } RETURN_META(MRES_IGNORED); } bool Hook_IGameEventManager2_FireEvent(IGameEvent *event, bool bDontBroadcast) { IGameEvent *newEvent = Interfaces::pGameEventManager->DuplicateEvent(event); if (g_Killstreaks) { if (g_Killstreaks->FireEvent(newEvent)) { Interfaces::pGameEventManager->FreeEvent(event); RETURN_META_VALUE_NEWPARAMS(MRES_HANDLED, false, &IGameEventManager2::FireEvent, (newEvent, bDontBroadcast)); } } Interfaces::pGameEventManager->FreeEvent(newEvent); RETURN_META_VALUE(MRES_IGNORED, false); } bool Hook_IGameEventManager2_FireEventClientSide(IGameEvent *event) { IGameEvent *newEvent = Interfaces::pGameEventManager->DuplicateEvent(event); if (g_Killstreaks) { if (g_Killstreaks->FireEvent(newEvent)) { Interfaces::pGameEventManager->FreeEvent(event); RETURN_META_VALUE_NEWPARAMS(MRES_HANDLED, false, &IGameEventManager2::FireEventClientSide, (newEvent)); } } Interfaces::pGameEventManager->FreeEvent(newEvent); RETURN_META_VALUE(MRES_IGNORED, false); } void Hook_IPanel_PaintTraverse(vgui::VPANEL vguiPanel, bool forceRepaint, bool allowForce = true) { if (Interfaces::pEngineClient->IsDrawingLoadingImage() || !Interfaces::pEngineClient->IsInGame() || !Interfaces::pEngineClient->IsConnected() || Interfaces::pEngineClient->Con_IsVisible()) { RETURN_META(MRES_IGNORED); } if (g_AntiFreeze) { if (g_AntiFreeze->IsEnabled()) { g_AntiFreeze->Paint(vguiPanel); } } if (g_LoadoutIcons) { if (g_LoadoutIcons->IsEnabled()) { g_LoadoutIcons->Paint(vguiPanel); } } if (g_MedigunInfo) { if (g_MedigunInfo->IsEnabled()) { g_MedigunInfo->Paint(vguiPanel); } } if (g_PlayerOutlines) { if (g_PlayerOutlines->IsEnabled() && g_PlayerOutlines->IsFrequentOverrideEnabled()) { g_PlayerOutlines->Paint(vguiPanel); } } if (g_StatusIcons) { if (g_StatusIcons->IsEnabled()) { g_StatusIcons->Paint(vguiPanel); } else { g_StatusIcons->NoPaint(vguiPanel); } } RETURN_META(MRES_IGNORED); } void Hook_IPanel_SendMessage(vgui::VPANEL vguiPanel, KeyValues *params, vgui::VPANEL ifromPanel) { if (g_LoadoutIcons) { if (g_LoadoutIcons->IsEnabled()) { g_LoadoutIcons->InterceptMessage(vguiPanel, params, ifromPanel); } } if (g_StatusIcons) { if (g_StatusIcons->IsEnabled()) { g_StatusIcons->InterceptMessage(vguiPanel, params, ifromPanel); } } RETURN_META(MRES_IGNORED); } bool Hook_IVEngineClient_GetPlayerInfo(int ent_num, player_info_t *pinfo) { if (g_PlayerAliases) { if (g_PlayerAliases->IsEnabled()) { RETURN_META_VALUE(MRES_SUPERCEDE, g_PlayerAliases->GetPlayerInfoOverride(ent_num, pinfo)); } } RETURN_META_VALUE(MRES_IGNORED, false); } // The plugin is a static singleton that is exported as an interface StatusSpecPlugin g_StatusSpecPlugin; EXPOSE_SINGLE_INTERFACE_GLOBALVAR(StatusSpecPlugin, IServerPluginCallbacks, INTERFACEVERSION_ISERVERPLUGINCALLBACKS, g_StatusSpecPlugin); StatusSpecPlugin::StatusSpecPlugin() { } StatusSpecPlugin::~StatusSpecPlugin() { } bool StatusSpecPlugin::Load(CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory) { if (!Interfaces::Load(interfaceFactory, gameServerFactory)) { Warning("[%s] Unable to load required libraries!\n", PLUGIN_DESC); return false; } if (!Entities::PrepareOffsets()) { Warning("[%s] Unable to determine proper offsets!\n", PLUGIN_DESC); return false; } if (!Funcs::Load()) { Warning("[%s] Unable to initialize hooking!", PLUGIN_DESC); return false; } Funcs::AddDetour_GetLocalPlayerIndex(Detour_GetLocalPlayerIndex); Funcs::AddHook_IBaseClientDLL_FrameStageNotify(Interfaces::pClientDLL, Hook_IBaseClientDLL_FrameStageNotify); Funcs::AddHook_IGameEventManager2_FireEvent(Interfaces::pGameEventManager, Hook_IGameEventManager2_FireEvent); Funcs::AddHook_IGameEventManager2_FireEventClientSide(Interfaces::pGameEventManager, Hook_IGameEventManager2_FireEventClientSide); Funcs::AddHook_IPanel_PaintTraverse(g_pVGuiPanel, Hook_IPanel_PaintTraverse); Funcs::AddHook_IPanel_SendMessage(g_pVGuiPanel, Hook_IPanel_SendMessage); Funcs::AddHook_IVEngineClient_GetPlayerInfo(Interfaces::pEngineClient, Hook_IVEngineClient_GetPlayerInfo); ConVar_Register(); g_AntiFreeze = new AntiFreeze(); g_Killstreaks = new Killstreaks(); g_LoadoutIcons = new LoadoutIcons(); g_LocalPlayer = new LocalPlayer(); g_MedigunInfo = new MedigunInfo(); g_MultiPanel = new MultiPanel(); g_PlayerAliases = new PlayerAliases(); g_PlayerOutlines = new PlayerOutlines(); g_StatusIcons = new StatusIcons(); Msg("%s loaded!\n", PLUGIN_DESC); return true; } void StatusSpecPlugin::Unload(void) { delete g_AntiFreeze; delete g_Killstreaks; delete g_LoadoutIcons; delete g_LocalPlayer; delete g_MedigunInfo; delete g_MultiPanel; delete g_PlayerAliases; delete g_PlayerOutlines; delete g_StatusIcons; Funcs::Unload(); ConVar_Unregister(); Interfaces::Unload(); } void StatusSpecPlugin::Pause(void) { Funcs::Pause(); } void StatusSpecPlugin::UnPause(void) { Funcs::Unpause(); } const char *StatusSpecPlugin::GetPluginDescription(void) { return PLUGIN_DESC; } void StatusSpecPlugin::LevelInit(char const *pMapName) {} void StatusSpecPlugin::ServerActivate(edict_t *pEdictList, int edictCount, int clientMax) {} void StatusSpecPlugin::GameFrame(bool simulating) {} void StatusSpecPlugin::LevelShutdown(void) {} void StatusSpecPlugin::ClientActive(edict_t *pEntity) {} void StatusSpecPlugin::ClientDisconnect(edict_t *pEntity) {} void StatusSpecPlugin::ClientPutInServer(edict_t *pEntity, char const *playername) {} void StatusSpecPlugin::SetCommandClient(int index) {} void StatusSpecPlugin::ClientSettingsChanged(edict_t *pEdict) {} PLUGIN_RESULT StatusSpecPlugin::ClientConnect(bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen) { return PLUGIN_CONTINUE; } PLUGIN_RESULT StatusSpecPlugin::ClientCommand(edict_t *pEntity, const CCommand &args) { return PLUGIN_CONTINUE; } PLUGIN_RESULT StatusSpecPlugin::NetworkIDValidated(const char *pszUserName, const char *pszNetworkID) { return PLUGIN_CONTINUE; } void StatusSpecPlugin::OnQueryCvarValueFinished(QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue) {} void StatusSpecPlugin::OnEdictAllocated(edict_t *edict) {} void StatusSpecPlugin::OnEdictFreed(const edict_t *edict) {}<|endoftext|>
<commit_before>//_________________________________________________________________________ // Macro that creates esd xml collections by querying the tags. // It addresses the following use cases: // o) The tag files are stored locally. // - One queries the tags by using simple string statements. // - One queries the tags by using the corresponding aliroot classes. // o) The tag files are stored in the file catalog. // In this case the first thing we do is to query the f.c. // and extract a collection (xml) of tag files. // - One queries the tags by using simple string statements. // - One queries the tags by using the corresponding aliroot classes. // // In all cases you create the xml file by using the CreateXMLCollection // of the AliTagAnalysisClass. The first argument of this method is the // name of the output xml collection which is stored locally. //_________________________________________________________________________ Bool_t CreateXML() { TStopwatch timer; timer.Start(); //needed in the case of the string statements gSystem->Load("libTreePlayer.so"); // Create A tag analysis object and impose some selection criteria AliTagAnalysis *TagAna = new AliTagAnalysis(); //Case where the tag files are stored locally //TagAna->ChainLocalTags("."); //Case where the tag files are stored in the file catalog //pp.xml is the xml collection of tag files that was produced //by querying the file catalog. TGrid::Connect("alien://pcapiserv01.cern.ch:10000","pchrist"); //TGrid::Connect("alien://"); TAlienCollection* coll = TAlienCollection::Open("pp.xml"); TGridResult* TagResult = coll->GetGridResult(""); TagAna->ChainGridTags(TagResult); //__________________________// //Usage of string statements// //__________________________// /*const char* fRunCuts = "fAliceRunId == 340"; const char* fEventCuts = "(fEventTag.fMaxPt >= 1.0)&&(fEventTag.fNumberOfTracks >= 11)&&(fEventTag.fNumberOfTracks <= 12)"; TagAna->CreateXMLCollection("global",fRunCuts,fEventCuts);*/ //________________________________________________// //Usage of AliRunTagCuts & AliEventTagCuts classes// //________________________________________________// // create a RunTagCut object AliRunTagCuts *RunCuts = new AliRunTagCuts(); RunCuts->SetRunId(340); // create an EventTagCut object AliEventTagCuts *EvCuts = new AliEventTagCuts(); EvCuts->SetMultiplicityRange(11,12); EvCuts->SetMaxPt(1.0); TagAna->CreateXMLCollection("global2",RunCuts,EvCuts); timer.Stop(); timer.Print(); return kTRUE; } <commit_msg>Changing the name of some event tag cuts setters to be compatible with the changes introduced by Markus.<commit_after>//_________________________________________________________________________ // Macro that creates esd xml collections by querying the tags. // It addresses the following use cases: // o) The tag files are stored locally. // - One queries the tags by using simple string statements. // - One queries the tags by using the corresponding aliroot classes. // o) The tag files are stored in the file catalog. // In this case the first thing we do is to query the f.c. // and extract a collection (xml) of tag files. // - One queries the tags by using simple string statements. // - One queries the tags by using the corresponding aliroot classes. // // In all cases you create the xml file by using the CreateXMLCollection // of the AliTagAnalysisClass. The first argument of this method is the // name of the output xml collection which is stored locally. //_________________________________________________________________________ Bool_t CreateXML() { TStopwatch timer; timer.Start(); //needed in the case of the string statements gSystem->Load("libTreePlayer.so"); // Create A tag analysis object and impose some selection criteria AliTagAnalysis *TagAna = new AliTagAnalysis(); //Case where the tag files are stored locally //TagAna->ChainLocalTags("."); //Case where the tag files are stored in the file catalog //pp.xml is the xml collection of tag files that was produced //by querying the file catalog. TGrid::Connect("alien://pcapiserv01.cern.ch:10000","pchrist"); //TGrid::Connect("alien://"); TAlienCollection* coll = TAlienCollection::Open("pp.xml"); TGridResult* TagResult = coll->GetGridResult(""); TagAna->ChainGridTags(TagResult); //__________________________// //Usage of string statements// //__________________________// /*const char* fRunCuts = "fAliceRunId == 340"; const char* fEventCuts = "(fEventTag.fTopPtMin >= 1.0)&&(fEventTag.fNumberOfTracks >= 11)&&(fEventTag.fNumberOfTracks <= 12)"; TagAna->CreateXMLCollection("global",fRunCuts,fEventCuts);*/ //________________________________________________// //Usage of AliRunTagCuts & AliEventTagCuts classes// //________________________________________________// // create a RunTagCut object AliRunTagCuts *RunCuts = new AliRunTagCuts(); RunCuts->SetRunId(340); // create an EventTagCut object AliEventTagCuts *EvCuts = new AliEventTagCuts(); EvCuts->SetMultiplicityRange(11,12); EvCuts->SetTopPtMin(1.0); TagAna->CreateXMLCollection("global2",RunCuts,EvCuts); timer.Stop(); timer.Print(); return kTRUE; } <|endoftext|>
<commit_before>// // Created by Miguel Rentes on 30/01/2017. // #include "STL.h" void printKMax(int arr[], int n, int k) { deque<int> mydeque; int greatest = 0, value = 0, index = 0, iteration = 0; /* * pushing all the greatest values on each k-elements to the front of the deque */ for (int i = 0; i < n; i++) { if (index < k) { value = arr[i]; if (value > greatest) greatest = value; if (index == k - 1) { mydeque.push_front(greatest); greatest = 0; index = 0; iteration++; i = iteration-1; } else { index++; } } } /* * pop-ing the greatest values from the back of the deque */ while(mydeque.size() > 0) { printf("%d ", mydeque.back()); mydeque.pop_back(); } printf("\n"); } int main(void) { int t; cin >> t; while (t > 0) { int n, k; cin >> n >> k; int i; int arr[n]; for (i = 0; i < n; i++) cin >> arr[i]; printKMax(arr, n, k); t--; } return EXIT_SUCCESS; }<commit_msg>Starts solution for the Deque-STL challenge.<commit_after>// // Created by Miguel Rentes on 30/01/2017. // #include "STL.h" void printKMax(int arr[], int n, int k) { deque<int> mydeque; int greatest = 0, value = 0, index = 0, iteration = 0; /* * pushing all the greatest values on each k-elements to the front of the deque */ for (int i = 0; i < n; i++) { if (index < k) { value = arr[i]; if (value > greatest) greatest = value; if (index == k - 1) { mydeque.push_front(greatest); greatest = 0; index = 0; iteration++; i = iteration-1; } else index++; } } /* * pop-ing the greatest values from the back of the deque */ while(mydeque.size() > 0) { printf("%d ", mydeque.back()); mydeque.pop_back(); } printf("\n"); } int main(void) { int t; cin >> t; while (t > 0) { int n, k; cin >> n >> k; int i; int arr[n]; for (i = 0; i < n; i++) cin >> arr[i]; printKMax(arr, n, k); t--; } return EXIT_SUCCESS; }<|endoftext|>
<commit_before>#include <coffee/core/plat/sensor/maemo/sensors.h> #include <coffee/core/plat/plat_file.h> #include <coffee/core/plat/plat_memory.h> #include <coffee/core/string_casting.h> #define const_string static const constexpr cstring namespace Coffee{ namespace Sensor{ namespace Maemo{ const_string LIS302DL_NAME_PATH = "/sys/class/i2c-adapter/i2c-3/3-001d/name"; const_string LIS302DL_DATA_PATH = "/sys/class/i2c-adapter/i2c-3/3-001d/coord"; const_string AIC34B_NAME_PATH = "/sys/class/i2c-adapter/i2c-2/2-0029/name"; const_string AIC34B_LUX_DATA_PATH = "/sys/class/i2c-adapter/i2c-2/2-0029/lux"; const_string AIC34B_AMBIENT_ADC0_DATA_PATH = "/sys/class/i2c-adapter/i2c-2/2-0029/adc0"; const_string AIC34B_AMBIENT_ADC1_DATA_PATH = "/sys/class/i2c-adapter/i2c-2/2-0029/adc1"; Vecf3 Maemo_SensorAPI::Gravity() { CString data = FileFun::sys_read(LIS302DL_DATA_PATH); Vecf3 v = {}; if(data.size() < 1) return v; size_t p_i = 0; size_t i = data.find(' '); size_t v_i = 0; while(i <= data.size()) { CString en = StrUtil::encapsulate(&data[0], i - p_i); v[v_i] = cast_string<scalar>(en) / 100.f; v_i++; p_i = i; i = data.find(' '); } return v; } scalar Maemo_SensorAPI::Lux() { return cast_string<scalar>(FileFun::sys_read(AIC34B_LUX_DATA_PATH)); } } } } <commit_msg> - Fix never-ending loop with sensor readings for Maemo<commit_after>#include <coffee/core/plat/sensor/maemo/sensors.h> #include <coffee/core/plat/plat_file.h> #include <coffee/core/plat/plat_memory.h> #include <coffee/core/string_casting.h> #define const_string static const constexpr cstring namespace Coffee{ namespace Sensor{ namespace Maemo{ const_string LIS302DL_NAME_PATH = "/sys/class/i2c-adapter/i2c-3/3-001d/name"; const_string LIS302DL_DATA_PATH = "/sys/class/i2c-adapter/i2c-3/3-001d/coord"; const_string AIC34B_NAME_PATH = "/sys/class/i2c-adapter/i2c-2/2-0029/name"; const_string AIC34B_LUX_DATA_PATH = "/sys/class/i2c-adapter/i2c-2/2-0029/lux"; const_string AIC34B_AMBIENT_ADC0_DATA_PATH = "/sys/class/i2c-adapter/i2c-2/2-0029/adc0"; const_string AIC34B_AMBIENT_ADC1_DATA_PATH = "/sys/class/i2c-adapter/i2c-2/2-0029/adc1"; Vecf3 Maemo_SensorAPI::Gravity() { CString data = FileFun::sys_read(LIS302DL_DATA_PATH); Vecf3 v = {}; if(data.size() < 1) return v; size_t p_i = 0; size_t i = data.find(' '); size_t v_i = 0; while(i <= data.size()) { CString en = StrUtil::encapsulate(&data[0], i - p_i); v[v_i] = cast_string<scalar>(en) / 100.f; v_i++; p_i = i; i = data.find(' ', p_i); } return v; } scalar Maemo_SensorAPI::Lux() { return cast_string<scalar>(FileFun::sys_read(AIC34B_LUX_DATA_PATH)); } } } } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * * ddl.cpp * file description * * Copyright(c) 2015, CMU * * /peloton/src/backend/bridge/ddl.cpp * *------------------------------------------------------------------------- */ #include <cassert> #include <iostream> #include "backend/bridge/ddl/ddl_table.h" #include "backend/bridge/ddl/ddl_database.h" #include "backend/bridge/ddl/ddl_index.h" #include "backend/bridge/ddl/ddl_transaction.h" #include "backend/bridge/ddl/ddl.h" #include "backend/common/logger.h" #include "postgres.h" #include "miscadmin.h" #include "c.h" namespace peloton { namespace bridge { //===--------------------------------------------------------------------===// // Utilities. //===--------------------------------------------------------------------===// /** * @brief Process utility statement. * @param parsetree Parse tree */ void DDL::ProcessUtility(Node *parsetree, const char *queryString, TransactionId txn_id){ assert(parsetree != nullptr); assert(queryString != nullptr); static std::vector<IndexInfo> index_infos; /* When we call a backend function from different thread, the thread's stack * is at a different location than the main thread's stack. so it sets up * reference point for stack depth checking */ set_stack_base(); // Process depending on type of utility statement switch (nodeTag(parsetree)) { StartTransactionCommand(); case T_CreatedbStmt: { DDLDatabase::ExecCreatedbStmt(parsetree); break; } case T_DropdbStmt: { DDLDatabase::ExecDropdbStmt(parsetree); break; } case T_CreateStmt: case T_CreateForeignTableStmt: { DDLTable::ExecCreateStmt(parsetree, index_infos); break; } case T_AlterTableStmt: { DDLTable::ExecAlterTableStmt(parsetree, queryString); break; } case T_DropStmt: { DDLTable::ExecDropStmt(parsetree); break; } case T_IndexStmt: { DDLIndex::ExecIndexStmt(parsetree, index_infos); break; } case T_VacuumStmt: { DDLDatabase::ExecVacuumStmt(parsetree); break; } CommitTransactionCommand(); case T_TransactionStmt: { TransactionStmt *stmt = (TransactionStmt *) parsetree; DDLTransaction::ExecTransactionStmt(stmt, txn_id); } break; default: { LOG_WARN("unrecognized node type: %d", (int) nodeTag(parsetree)); } break; } } } // namespace bridge } // namespace peloton <commit_msg>Minor fix<commit_after>/*------------------------------------------------------------------------- * * ddl.cpp * file description * * Copyright(c) 2015, CMU * * /peloton/src/backend/bridge/ddl.cpp * *------------------------------------------------------------------------- */ #include <cassert> #include <iostream> #include "backend/bridge/ddl/ddl_table.h" #include "backend/bridge/ddl/ddl_database.h" #include "backend/bridge/ddl/ddl_index.h" #include "backend/bridge/ddl/ddl_transaction.h" #include "backend/bridge/ddl/ddl.h" #include "backend/common/logger.h" #include "postgres.h" #include "miscadmin.h" #include "c.h" #include "access/xact.h" namespace peloton { namespace bridge { //===--------------------------------------------------------------------===// // Utilities. //===--------------------------------------------------------------------===// /** * @brief Process utility statement. * @param parsetree Parse tree */ void DDL::ProcessUtility(Node *parsetree, const char *queryString, TransactionId txn_id){ assert(parsetree != nullptr); assert(queryString != nullptr); static std::vector<IndexInfo> index_infos; /* When we call a backend function from different thread, the thread's stack * is at a different location than the main thread's stack. so it sets up * reference point for stack depth checking */ set_stack_base(); // Process depending on type of utility statement switch (nodeTag(parsetree)) { StartTransactionCommand(); case T_CreatedbStmt: { DDLDatabase::ExecCreatedbStmt(parsetree); break; } case T_DropdbStmt: { DDLDatabase::ExecDropdbStmt(parsetree); break; } case T_CreateStmt: case T_CreateForeignTableStmt: { DDLTable::ExecCreateStmt(parsetree, index_infos); break; } case T_AlterTableStmt: { DDLTable::ExecAlterTableStmt(parsetree, queryString); break; } case T_DropStmt: { DDLTable::ExecDropStmt(parsetree); break; } case T_IndexStmt: { DDLIndex::ExecIndexStmt(parsetree, index_infos); break; } case T_VacuumStmt: { DDLDatabase::ExecVacuumStmt(parsetree); break; } CommitTransactionCommand(); case T_TransactionStmt: { TransactionStmt *stmt = (TransactionStmt *) parsetree; DDLTransaction::ExecTransactionStmt(stmt, txn_id); } break; default: { LOG_WARN("unrecognized node type: %d", (int) nodeTag(parsetree)); } break; } } } // namespace bridge } // namespace peloton <|endoftext|>
<commit_before>#include "timer_system_time.h" #include "eal/lmice_eal_common.h" #include <sglib.h> #include <errno.h> #include <eal/lmice_eal_spinlock.h> typedef void (timer_callback) (void* pdata); /** * @brief The lm_timer_s struct 定时器 */ struct lm_timer_s { volatile int32_t state; // 状态 int32_t size; // 触发计数量 HANDLE event; // 响应事件 int64_t instid; // 场景编号 int64_t timerid; // 定时器编号 int64_t tick; // 周期 int64_t count; // 已完成触发数量 int64_t begin_tick; // 开始时间 }; enum lm_timer_e { TICK_TIMER_EMPTY = 1, TICK_TIMER_WORK = 2, TICK_INFINITY = -1, TICK_NOW = 0 }; //Declaration struct lm_timer_s lm_timer[128]; uint64_t lock_lm_timer = 0; void process_tick_timer() { int id; int ret; int64_t now = tcread(); ret = eal_spin_trylock(&lock_lm_timer); if(ret != 0) return; for(id = 0; id < sizeof(lm_timer)/sizeof(struct lm_timer_s); ++id ) { struct lm_timer_s *pt; pt = &lm_timer[id]; if(pt->state == TICK_TIMER_WORK) { /* 判断时间中断的仿真时间 */ if( pt->begin_tick + pt->tick < now) continue; /* 判断响应次数 */ if(pt->size == TICK_INFINITY /* 无限次数 */ || pt->count < pt->size) /* 响应数小于请求数 */ { ++pt->count; pt->begin_tick = now; SetEvent(pt->event); } else if(pt->count >= pt->size) /* 响应数大于等于请求数 */ { pt->state = TICK_TIMER_EMPTY; CloseHandle(pt->event); pt->event = NULL; } } } eal_spin_unlock(&lock_lm_timer); } /** * @brief create_tick_timer * @param instid * @param tick * @param size * @param begin_tick * @param event * @param timer_id * @return */ int create_tick_timer(int64_t instid, int tick, int size, int64_t begin_tick, HANDLE event, int* timer_id) { int ret; int id; ret = eal_spin_trylock(&lock_lm_timer); if(ret != 0) return EBUSY; ret = EADDRINUSE; for(id=0; id< sizeof(lm_timer)/sizeof(struct lm_timer_s); ++id ) { struct lm_timer_s *pt; pt = &lm_timer[id]; if(pt->state == TICK_TIMER_EMPTY) { int64_t now = tcread(); if(begin_tick == TICK_NOW) begin_tick = now; else if (begin_tick < now ) begin_tick = now; pt->state = TICK_TIMER_WORK; pt->size = size; pt->event = event; pt->instid = instid; pt->timerid = id; pt->tick = tick; pt->count = 0; pt->begin_tick = begin_tick; *timer_id = id; ret = 0; break; } } eal_spin_unlock(&lock_lm_timer); return ret; } /** * @brief delete_timer_oneshot * @param timer_id * @return 0- Success, else failed. */ int delete_tick_timer(int tc_id) { int ret; struct lm_timer_s *pt; if(tc_id >= sizeof(lm_timer)/sizeof(struct lm_timer_s)) return ERANGE; ret = eal_spin_trylock(&lock_lm_timer); if(ret != 0) return EBUSY; pt = &lm_timer[tc_id]; if(pt->state == TICK_TIMER_WORK) { pt->state = TICK_TIMER_EMPTY; CloseHandle(pt->event); pt->event = NULL; } eal_spin_unlock(&lock_lm_timer); return 0; } <commit_msg>timer<commit_after>#include "timer_system_time.h" #include "eal/lmice_eal_common.h" #include <sglib.h> #include <errno.h> #include <eal/lmice_eal_spinlock.h> /** * @brief The lm_timer_s struct 定时器 */ struct lm_timer_s { volatile int32_t state; // 状态 int32_t size; // 触发计数量 HANDLE event; // 响应事件 int64_t instid; // 场景编号 int64_t timerid; // 定时器编号 int64_t tick; // 周期 int64_t count; // 已完成触发数量 int64_t begin_tick; // 开始时间 }; enum lm_timer_e { TICK_TIMER_EMPTY = 1, TICK_TIMER_WORK = 2, TICK_INFINITY = -1, TICK_NOW = 0 }; //Declaration #define MAX_TICK_TIMER_SIZE 128 struct lm_timer_s lm_timer[MAX_TICK_TIMER_SIZE]; uint64_t lock_lm_timer = 0; void process_tick_timer() { int id; int ret; int64_t now = tcread(); ret = eal_spin_trylock(&lock_lm_timer); if(ret != 0) return; for(id = 0; id < sizeof(lm_timer)/sizeof(struct lm_timer_s); ++id ) { struct lm_timer_s *pt; pt = &lm_timer[id]; if(pt->state == TICK_TIMER_WORK) { /* 判断时间中断的仿真时间 */ if( pt->begin_tick + pt->tick < now) continue; /* 判断响应次数 */ if(pt->size == TICK_INFINITY /* 无限次数 */ || pt->count < pt->size) /* 响应数小于请求数 */ { ++pt->count; pt->begin_tick = now; SetEvent(pt->event); } else if(pt->count >= pt->size) /* 响应数大于等于请求数 */ { pt->state = TICK_TIMER_EMPTY; CloseHandle(pt->event); pt->event = NULL; } } } eal_spin_unlock(&lock_lm_timer); } /** * @brief create_tick_timer * @param instid * @param tick * @param size * @param begin_tick * @param event * @param timer_id * @return */ int create_tick_timer(int64_t instid, int tick, int size, int64_t begin_tick, HANDLE event, int* timer_id) { int ret; int id; ret = eal_spin_trylock(&lock_lm_timer); if(ret != 0) return EBUSY; ret = EADDRINUSE; for(id=0; id< sizeof(lm_timer)/sizeof(struct lm_timer_s); ++id ) { struct lm_timer_s *pt; pt = &lm_timer[id]; if(pt->state == TICK_TIMER_EMPTY) { int64_t now = tcread(); if(begin_tick == TICK_NOW) begin_tick = now; else if (begin_tick < now ) begin_tick = now; pt->state = TICK_TIMER_WORK; pt->size = size; pt->event = event; pt->instid = instid; pt->timerid = id; pt->tick = tick; pt->count = 0; pt->begin_tick = begin_tick; *timer_id = id; ret = 0; break; } } eal_spin_unlock(&lock_lm_timer); return ret; } /** * @brief delete_timer_oneshot * @param timer_id * @return 0- Success, else failed. */ int delete_tick_timer(int tc_id) { int ret; struct lm_timer_s *pt; if(tc_id >= sizeof(lm_timer)/sizeof(struct lm_timer_s)) return ERANGE; ret = eal_spin_trylock(&lock_lm_timer); if(ret != 0) return EBUSY; pt = &lm_timer[tc_id]; if(pt->state == TICK_TIMER_WORK) { pt->state = TICK_TIMER_EMPTY; CloseHandle(pt->event); pt->event = NULL; } eal_spin_unlock(&lock_lm_timer); return 0; } <|endoftext|>
<commit_before>/* *********************************************************************************************************************** * * Copyright (c) 2021 Google LLC. All Rights Reserved. * * 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 "llpc.h" #include "llpcShaderCache.h" #include "vkgcDefs.h" #include "vkgcMetroHash.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallVector.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <algorithm> #include <atomic> #include <chrono> #include <list> #include <numeric> #include <random> #include <thread> using namespace llvm; using ::testing::ElementsAreArray; namespace Llpc { namespace { constexpr Vkgc::GfxIpVersion GfxIp = {9, 0, 0}; // Test class for tests that initialize a runtime ShaderCache. class ShaderCacheTest : public ::testing::Test { public: // Creates a new empty runtime ShaderCache. void SetUp() override { m_auxCreateInfo.shaderCacheMode = ShaderCacheMode::ShaderCacheEnableRuntime; m_auxCreateInfo.gfxIp = GfxIp; Result result = m_cache.init(&m_llpcCacheCreateInfo, &m_auxCreateInfo); EXPECT_EQ(result, Result::Success); } // Returns the ShaderCache object. ShaderCache &getCache() { return m_cache; } // Creates a hash from four dwords. static MetroHash::Hash hashFromDWords(unsigned a, unsigned b, unsigned c, unsigned d) { MetroHash::Hash hash = {}; hash.dwords[0] = a; hash.dwords[1] = b; hash.dwords[2] = c; hash.dwords[3] = d; return hash; } // Creates an ArrayRef from the given blob and its size. static ArrayRef<char> charArrayFromBlob(const void *blob, size_t size) { return {reinterpret_cast<const char *>(blob), size}; } private: ShaderCache m_cache; ShaderCacheCreateInfo m_llpcCacheCreateInfo = {}; ShaderCacheAuxCreateInfo m_auxCreateInfo = {}; }; // cppcheck-suppress syntaxError TEST_F(ShaderCacheTest, CreateEmpty) { ShaderCache &cache = getCache(); size_t size = 0; cache.Serialize(nullptr, &size); EXPECT_EQ(size, sizeof(ShaderCacheSerializedHeader)); } TEST_F(ShaderCacheTest, InsertOne) { ShaderCache &cache = getCache(); const auto hash = hashFromDWords(1, 2, 3, 4); SmallVector<char> cacheEntry(64); std::iota(cacheEntry.begin(), cacheEntry.end(), 0); CacheEntryHandle handle = nullptr; // Check if the entry is inside without allocating on miss. ShaderEntryState state = cache.findShader(hash, false, &handle); EXPECT_EQ(state, ShaderEntryState::Unavailable); EXPECT_EQ(handle, nullptr); // Check again but allocate this time. state = cache.findShader(hash, true, &handle); EXPECT_EQ(state, ShaderEntryState::Compiling); EXPECT_NE(handle, nullptr); // Insert the new entry. cache.insertShader(handle, cacheEntry.data(), cacheEntry.size()); // The entry should be in the cache now. CacheEntryHandle newHandle = nullptr; state = cache.findShader(hash, false, &newHandle); EXPECT_EQ(state, ShaderEntryState::Ready); EXPECT_EQ(handle, newHandle); // Make sure that the content matches the inserted entry. const void *blob = nullptr; size_t blobSize = 0; Result result = cache.retrieveShader(handle, &blob, &blobSize); EXPECT_EQ(result, Result::Success); EXPECT_EQ(blobSize, cacheEntry.size()); EXPECT_NE(blob, nullptr); EXPECT_THAT(charArrayFromBlob(blob, blobSize), ElementsAreArray(cacheEntry)); size_t cacheSize = 0; cache.Serialize(nullptr, &cacheSize); EXPECT_GE(cacheSize, sizeof(ShaderCacheSerializedHeader) + blobSize); } TEST_F(ShaderCacheTest, InsertsShaders) { ShaderCache &cache = getCache(); SmallVector<char> cacheEntry(64); constexpr size_t numShaders = 128; SmallVector<MetroHash::Hash, 0> hashes(numShaders); for (auto &hashAndIndex : enumerate(hashes)) hashAndIndex.value() = hashFromDWords(static_cast<unsigned>(hashAndIndex.index()), 2, 3, 4); for (auto &hash : hashes) { CacheEntryHandle handle = nullptr; // Check if the entry is inside without allocating on miss. ShaderEntryState state = cache.findShader(hash, false, &handle); EXPECT_EQ(state, ShaderEntryState::Unavailable); EXPECT_EQ(handle, nullptr); // Check again but allocate this time. state = cache.findShader(hash, true, &handle); EXPECT_EQ(state, ShaderEntryState::Compiling); EXPECT_NE(handle, nullptr); // Insert the new entry. cache.insertShader(handle, cacheEntry.data(), cacheEntry.size()); } // All entries should be in the cache now. for (auto &hash : hashes) { CacheEntryHandle newHandle = nullptr; ShaderEntryState state = cache.findShader(hash, false, &newHandle); EXPECT_EQ(state, ShaderEntryState::Ready); EXPECT_NE(newHandle, nullptr); } size_t cacheSize = 0; cache.Serialize(nullptr, &cacheSize); EXPECT_GE(cacheSize, sizeof(ShaderCacheSerializedHeader) + (numShaders * cacheEntry.size())); } // This test tries to insert the same shader with N threads. We expect to see one insertion // and N - 1 hits, for each shader. // Disable it can fail or hang with the wait time in `ShaderCache::findShader` changed. // TODO: Reenable when ShaderCache is fixed. TEST_F(ShaderCacheTest, DISABLED_InsertsShadersMultithreaded) { ShaderCache &cache = getCache(); SmallVector<char> cacheEntry(64); constexpr size_t numShaders = 128; constexpr size_t numThreads = 8; constexpr unsigned maxWaitTimeMilliseconds = 4; SmallVector<MetroHash::Hash, 0> hashes(numShaders); for (auto &hashAndIndex : enumerate(hashes)) hashAndIndex.value() = hashFromDWords(static_cast<unsigned>(hashAndIndex.index()), 2, 3, 4); // Initialize the generator with a deterministic seed. std::mt19937 generator(std::random_device{}()); std::uniform_int_distribution<unsigned> waitTimeDistribution(0, maxWaitTimeMilliseconds * 1000); auto getWaitTime = [&generator, &waitTimeDistribution] { return std::chrono::microseconds(waitTimeDistribution(generator)); }; for (auto &hash : hashes) { std::atomic<size_t> numInsertions{0}; std::atomic<size_t> numHits{0}; std::list<std::thread> threads; for (size_t i = 0; i != numThreads; ++i) { threads.emplace_back([&cache, &cacheEntry, &getWaitTime, &hash, &numInsertions, &numHits] { CacheEntryHandle handle = nullptr; ShaderEntryState state = cache.findShader(hash, true, &handle); EXPECT_NE(handle, nullptr); if (state == ShaderEntryState::Compiling) { // Insert the new entry. Sleep to simulate compilation time. std::this_thread::sleep_for(getWaitTime()); cache.insertShader(handle, cacheEntry.data(), cacheEntry.size()); ++numInsertions; } else { EXPECT_EQ(state, ShaderEntryState::Ready); ++numHits; } }); } // Wait for all threads to finish. for (std::thread &t : threads) t.join(); EXPECT_EQ(numInsertions, 1); EXPECT_EQ(numHits, numThreads - 1); } // All entries should be in the cache now. for (auto &hash : hashes) { CacheEntryHandle newHandle = nullptr; ShaderEntryState state = cache.findShader(hash, false, &newHandle); EXPECT_EQ(state, ShaderEntryState::Ready); EXPECT_NE(newHandle, nullptr); } size_t cacheSize = 0; cache.Serialize(nullptr, &cacheSize); EXPECT_GE(cacheSize, sizeof(ShaderCacheSerializedHeader) + (numShaders * cacheEntry.size())); } } // namespace } // namespace Llpc <commit_msg>Enable multithreaded ShaderCache test<commit_after>/* *********************************************************************************************************************** * * Copyright (c) 2021 Google LLC. All Rights Reserved. * * 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 "llpc.h" #include "llpcShaderCache.h" #include "vkgcDefs.h" #include "vkgcMetroHash.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallVector.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <algorithm> #include <atomic> #include <chrono> #include <list> #include <numeric> #include <random> #include <thread> using namespace llvm; using ::testing::ElementsAreArray; namespace Llpc { namespace { constexpr Vkgc::GfxIpVersion GfxIp = {9, 0, 0}; // Test class for tests that initialize a runtime ShaderCache. class ShaderCacheTest : public ::testing::Test { public: // Creates a new empty runtime ShaderCache. void SetUp() override { m_auxCreateInfo.shaderCacheMode = ShaderCacheMode::ShaderCacheEnableRuntime; m_auxCreateInfo.gfxIp = GfxIp; Result result = m_cache.init(&m_llpcCacheCreateInfo, &m_auxCreateInfo); EXPECT_EQ(result, Result::Success); } // Returns the ShaderCache object. ShaderCache &getCache() { return m_cache; } // Creates a hash from four dwords. static MetroHash::Hash hashFromDWords(unsigned a, unsigned b, unsigned c, unsigned d) { MetroHash::Hash hash = {}; hash.dwords[0] = a; hash.dwords[1] = b; hash.dwords[2] = c; hash.dwords[3] = d; return hash; } // Creates an ArrayRef from the given blob and its size. static ArrayRef<char> charArrayFromBlob(const void *blob, size_t size) { return {reinterpret_cast<const char *>(blob), size}; } private: ShaderCache m_cache; ShaderCacheCreateInfo m_llpcCacheCreateInfo = {}; ShaderCacheAuxCreateInfo m_auxCreateInfo = {}; }; // cppcheck-suppress syntaxError TEST_F(ShaderCacheTest, CreateEmpty) { ShaderCache &cache = getCache(); size_t size = 0; cache.Serialize(nullptr, &size); EXPECT_EQ(size, sizeof(ShaderCacheSerializedHeader)); } TEST_F(ShaderCacheTest, InsertOne) { ShaderCache &cache = getCache(); const auto hash = hashFromDWords(1, 2, 3, 4); SmallVector<char> cacheEntry(64); std::iota(cacheEntry.begin(), cacheEntry.end(), 0); CacheEntryHandle handle = nullptr; // Check if the entry is inside without allocating on miss. ShaderEntryState state = cache.findShader(hash, false, &handle); EXPECT_EQ(state, ShaderEntryState::Unavailable); EXPECT_EQ(handle, nullptr); // Check again but allocate this time. state = cache.findShader(hash, true, &handle); EXPECT_EQ(state, ShaderEntryState::Compiling); EXPECT_NE(handle, nullptr); // Insert the new entry. cache.insertShader(handle, cacheEntry.data(), cacheEntry.size()); // The entry should be in the cache now. CacheEntryHandle newHandle = nullptr; state = cache.findShader(hash, false, &newHandle); EXPECT_EQ(state, ShaderEntryState::Ready); EXPECT_EQ(handle, newHandle); // Make sure that the content matches the inserted entry. const void *blob = nullptr; size_t blobSize = 0; Result result = cache.retrieveShader(handle, &blob, &blobSize); EXPECT_EQ(result, Result::Success); EXPECT_EQ(blobSize, cacheEntry.size()); EXPECT_NE(blob, nullptr); EXPECT_THAT(charArrayFromBlob(blob, blobSize), ElementsAreArray(cacheEntry)); size_t cacheSize = 0; cache.Serialize(nullptr, &cacheSize); EXPECT_GE(cacheSize, sizeof(ShaderCacheSerializedHeader) + blobSize); } TEST_F(ShaderCacheTest, InsertsShaders) { ShaderCache &cache = getCache(); SmallVector<char> cacheEntry(64); constexpr size_t numShaders = 128; SmallVector<MetroHash::Hash, 0> hashes(numShaders); for (auto &hashAndIndex : enumerate(hashes)) hashAndIndex.value() = hashFromDWords(static_cast<unsigned>(hashAndIndex.index()), 2, 3, 4); for (auto &hash : hashes) { CacheEntryHandle handle = nullptr; // Check if the entry is inside without allocating on miss. ShaderEntryState state = cache.findShader(hash, false, &handle); EXPECT_EQ(state, ShaderEntryState::Unavailable); EXPECT_EQ(handle, nullptr); // Check again but allocate this time. state = cache.findShader(hash, true, &handle); EXPECT_EQ(state, ShaderEntryState::Compiling); EXPECT_NE(handle, nullptr); // Insert the new entry. cache.insertShader(handle, cacheEntry.data(), cacheEntry.size()); } // All entries should be in the cache now. for (auto &hash : hashes) { CacheEntryHandle newHandle = nullptr; ShaderEntryState state = cache.findShader(hash, false, &newHandle); EXPECT_EQ(state, ShaderEntryState::Ready); EXPECT_NE(newHandle, nullptr); } size_t cacheSize = 0; cache.Serialize(nullptr, &cacheSize); EXPECT_GE(cacheSize, sizeof(ShaderCacheSerializedHeader) + (numShaders * cacheEntry.size())); } // This test tries to insert the same shader with N threads. We expect to see one insertion // and N - 1 hits, for each shader. // Disable it can fail or hang with the wait time in `ShaderCache::findShader` changed. TEST_F(ShaderCacheTest, InsertsShadersMultithreaded) { ShaderCache &cache = getCache(); SmallVector<char> cacheEntry(64); constexpr size_t numShaders = 128; constexpr size_t numThreads = 8; constexpr unsigned maxWaitTimeMilliseconds = 4; SmallVector<MetroHash::Hash, 0> hashes(numShaders); for (auto &hashAndIndex : enumerate(hashes)) hashAndIndex.value() = hashFromDWords(static_cast<unsigned>(hashAndIndex.index()), 2, 3, 4); // Initialize the generator with a deterministic seed. std::mt19937 generator(std::random_device{}()); std::uniform_int_distribution<unsigned> waitTimeDistribution(0, maxWaitTimeMilliseconds * 1000); auto getWaitTime = [&generator, &waitTimeDistribution] { return std::chrono::microseconds(waitTimeDistribution(generator)); }; for (auto &hash : hashes) { std::atomic<size_t> numInsertions{0}; std::atomic<size_t> numHits{0}; std::list<std::thread> threads; for (size_t i = 0; i != numThreads; ++i) { threads.emplace_back([&cache, &cacheEntry, &getWaitTime, &hash, &numInsertions, &numHits] { CacheEntryHandle handle = nullptr; ShaderEntryState state = cache.findShader(hash, true, &handle); EXPECT_NE(handle, nullptr); if (state == ShaderEntryState::Compiling) { // Insert the new entry. Sleep to simulate compilation time. std::this_thread::sleep_for(getWaitTime()); cache.insertShader(handle, cacheEntry.data(), cacheEntry.size()); ++numInsertions; } else { EXPECT_EQ(state, ShaderEntryState::Ready); ++numHits; } }); } // Wait for all threads to finish. for (std::thread &t : threads) t.join(); EXPECT_EQ(numInsertions, 1); EXPECT_EQ(numHits, numThreads - 1); } // All entries should be in the cache now. for (auto &hash : hashes) { CacheEntryHandle newHandle = nullptr; ShaderEntryState state = cache.findShader(hash, false, &newHandle); EXPECT_EQ(state, ShaderEntryState::Ready); EXPECT_NE(newHandle, nullptr); } size_t cacheSize = 0; cache.Serialize(nullptr, &cacheSize); EXPECT_GE(cacheSize, sizeof(ShaderCacheSerializedHeader) + (numShaders * cacheEntry.size())); } } // namespace } // namespace Llpc <|endoftext|>
<commit_before>// RUN: cat %s | %cling -Xclang -verify // RUN: cat %s | %cling | FileCheck %s #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/StoredValueRef.h" cling::StoredValueRef V; V // CHECK: (cling::StoredValueRef) <<<invalid>>> @0x{{.*}} gCling->evaluate("return 1;", V); V // CHECK: (cling::StoredValueRef) boxes [(int) 1] long LongV = 17; gCling->evaluate("LongV;", V); V // CHECK: (cling::StoredValueRef) boxes [(long) 17] int* IntP = (int*)0x12; gCling->evaluate("IntP;", V); V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12] cling::StoredValueRef Result; gCling->evaluate("V", Result); // Here we check whether the type is trivially copiable and for cling::StoredValueRef it is not. Result // CHECK: (cling::StoredValueRef) boxes [(void) @0x{{.*}}] V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12] // Savannah #96277 gCling->evaluate("double sin(double); double one = sin(3.141/2);", V); V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00] gCling->process("double sin(double); double one = sin(3.141/2);", &V); V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00] one // CHECK: (double) 1.000 int one; // expected-error {{redefinition of 'one' with a different type: 'int' vs 'double'}} expected-note {{previous definition is here}} // Make sure that PR#98434 doesn't get reintroduced. void f(int); gCling->evaluate("f", V); // end PR#98434 <commit_msg>Make sure that the value is valid.a<commit_after>// RUN: cat %s | %cling -Xclang -verify // RUN: cat %s | %cling | FileCheck %s #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/StoredValueRef.h" cling::StoredValueRef V; V // CHECK: (cling::StoredValueRef) <<<invalid>>> @0x{{.*}} gCling->evaluate("return 1;", V); V // CHECK: (cling::StoredValueRef) boxes [(int) 1] long LongV = 17; gCling->evaluate("LongV;", V); V // CHECK: (cling::StoredValueRef) boxes [(long) 17] int* IntP = (int*)0x12; gCling->evaluate("IntP;", V); V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12] cling::StoredValueRef Result; gCling->evaluate("V", Result); // Here we check whether the type is trivially copiable and for cling::StoredValueRef it is not. Result // CHECK: (cling::StoredValueRef) boxes [(void) @0x{{.*}}] V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12] // Savannah #96277 gCling->evaluate("double sin(double); double one = sin(3.141/2);", V); V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00] gCling->process("double sin(double); double one = sin(3.141/2);", &V); V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00] one // CHECK: (double) 1.000 int one; // expected-error {{redefinition of 'one' with a different type: 'int' vs 'double'}} expected-note {{previous definition is here}} // Make sure that PR#98434 doesn't get reintroduced. void f(int); gCling->evaluate("f", V); V.isValid() //CHECK: (_Bool) true // end PR#98434 <|endoftext|>
<commit_before>//===--------------------------------------------------------------------------------*- C++ -*-===// // _____ _ // / ____| (_) // | (___ ___ __ _ _ _ ___ _ __ _ // \___ \ / _ \/ _` | | | |/ _ \| |/ _` | // ____) | __/ (_| | |_| | (_) | | (_| | // |_____/ \___|\__, |\__,_|\___/|_|\__,_| - Game Engine (2016-2017) // | | // |_| // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "sequoia-engine/Unittest/TestFile.h" #include "sequoia-engine/Core/Exception.h" #include "sequoia-engine/Core/Memory.h" #include "sequoia-engine/Core/StringRef.h" #include "sequoia-engine/Core/UtfString.h" #include "sequoia-engine/Unittest/TestEnvironment.h" #include <fstream> #include <sstream> namespace sequoia { namespace unittest { TestFile::TestFile(const platform::Path& path, FileType type) : File(type == FileType::Unknown ? File::TypeFromExtension(platform::toAnsiString(path.extension())) : type), path_(path) {} const Byte* TestFile::getData() { if(data_.empty()) load(); return data_.data(); } std::size_t TestFile::getNumBytes() { if(data_.empty()) load(); return data_.size(); } void TestFile::load() { std::ios_base::openmode mode = std::ios_base::in; if(isBinary()) mode |= std::ios_base::binary; std::ifstream file(platform::toAnsiString(path_).c_str(), mode); if(!file.is_open()) SEQUOIA_THROW(core::Exception, "cannot load file: '{}'", path_.c_str()); // Allocate memory file.seekg(0, std::ios_base::end); data_.resize(file.tellg()); file.seekg(0, std::ios_base::beg); // Read ASCII file file.read(reinterpret_cast<char*>(data_.data()), data_.size()); } std::string TestFile::getPath() const noexcept { return platform::toAnsiString(path_); } std::size_t TestFile::hash() const noexcept { return std::hash<std::string>()(getPath()); } bool TestFile::equals(const core::File* other) const noexcept { return getPath() == other->getPath(); } std::string TestFile::getFilename() const noexcept { return platform::toAnsiString(path_.filename()); } std::string TestFile::getExtension() const noexcept { return platform::toAnsiString(path_.extension()); } } // namespace unittest } // namespace sequoia <commit_msg>Fix unsupported formatting of wstring<commit_after>//===--------------------------------------------------------------------------------*- C++ -*-===// // _____ _ // / ____| (_) // | (___ ___ __ _ _ _ ___ _ __ _ // \___ \ / _ \/ _` | | | |/ _ \| |/ _` | // ____) | __/ (_| | |_| | (_) | | (_| | // |_____/ \___|\__, |\__,_|\___/|_|\__,_| - Game Engine (2016-2017) // | | // |_| // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "sequoia-engine/Unittest/TestFile.h" #include "sequoia-engine/Core/Exception.h" #include "sequoia-engine/Core/Memory.h" #include "sequoia-engine/Core/StringRef.h" #include "sequoia-engine/Core/UtfString.h" #include "sequoia-engine/Unittest/TestEnvironment.h" #include <fstream> #include <sstream> namespace sequoia { namespace unittest { TestFile::TestFile(const platform::Path& path, FileType type) : File(type == FileType::Unknown ? File::TypeFromExtension(platform::toAnsiString(path.extension())) : type), path_(path) {} const Byte* TestFile::getData() { if(data_.empty()) load(); return data_.data(); } std::size_t TestFile::getNumBytes() { if(data_.empty()) load(); return data_.size(); } void TestFile::load() { std::ios_base::openmode mode = std::ios_base::in; if(isBinary()) mode |= std::ios_base::binary; std::string pathStr = platform::toAnsiString(path_); std::ifstream file(pathStr.c_str(), mode); if(!file.is_open()) SEQUOIA_THROW(core::Exception, "cannot load file: '{}'", pathStr.c_str()); // Allocate memory file.seekg(0, std::ios_base::end); data_.resize(file.tellg()); file.seekg(0, std::ios_base::beg); // Read ASCII file file.read(reinterpret_cast<char*>(data_.data()), data_.size()); } std::string TestFile::getPath() const noexcept { return platform::toAnsiString(path_); } std::size_t TestFile::hash() const noexcept { return std::hash<std::string>()(getPath()); } bool TestFile::equals(const core::File* other) const noexcept { return getPath() == other->getPath(); } std::string TestFile::getFilename() const noexcept { return platform::toAnsiString(path_.filename()); } std::string TestFile::getExtension() const noexcept { return platform::toAnsiString(path_.extension()); } } // namespace unittest } // namespace sequoia <|endoftext|>
<commit_before>/* * File: AlarmClockTest.cpp * Author: Craig Cogdill * Created: October 15, 2015 10:45am * Modifier: Amanda Carbonari * Modified Date: January 5, 2015 3:45pm */ #include "AlarmClockTest.h" #include "AlarmClock.h" #include "StopWatch.h" #include <chrono> #include <iostream> #include <thread> std::atomic<unsigned int> AlarmClockTest::mFakeSleepUs(0); namespace { typedef std::chrono::microseconds microseconds; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::seconds seconds; unsigned int kFakeSleepLeeway = 100; template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) { while (!alerter.Expired()); } template<typename Duration> unsigned int ConvertToMicroSeconds(Duration t) { return std::chrono::duration_cast<microseconds>(t).count(); } template<typename Duration> unsigned int ConvertToMilliSeconds(Duration t) { return std::chrono::duration_cast<milliseconds>(t).count(); } unsigned int FakeSleep(unsigned int usToSleep) { AlarmClockTest::mFakeSleepUs.store(usToSleep); std::this_thread::sleep_for(microseconds(10)); return 0; } } TEST_F(AlarmClockTest, GetUsSleepTimeInUs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(us, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetUsSleepTimeInMs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(ConvertToMilliSeconds(microseconds(us)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInMs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ms, alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInUs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ConvertToMicroSeconds(milliseconds(ms)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInUs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMicroSeconds(seconds(sec)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInMs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMilliSeconds(seconds(sec)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, microsecondsLessThan500ms) { int us = 900; cout << "TEST: Creating Alarm Clock" << endl; AlarmClock<microseconds> alerter(us, FakeSleep); cout << "TEST: Expecting false for expired" << endl; EXPECT_FALSE(alerter.Expired()); cout << "TEST: Waiting for alarm clock to expire" << endl; WaitForAlarmClockToExpire(alerter); cout << "TEST: Expecting true for expired" << endl; EXPECT_TRUE(alerter.Expired()); cout << "TEST: Expecting greater than" << endl; EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); cout << "TEST: Expecting less than" << endl; EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); cout << "TEST: About to destruct" << endl; } TEST_F(AlarmClockTest, microsecondsGreaterThan500ms) { int us = 600000; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, weirdNumberOfMicroseconds) { int us = 724509; StopWatch sw; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, millisecondsLessThan500) { unsigned int ms = 100; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, oneSecondInMilliseconds) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, millisecondsNotDivisibleBy500) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, secondsSimple) { unsigned int sec = 1; AlarmClock<seconds> alerter(sec, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, LongTimeout_ImmediatelyDestructed) { unsigned int sec = 1000; StopWatch sw; std::unique_ptr<AlarmClock<seconds>> acPtr(new AlarmClock<seconds>(sec, FakeSleep)); EXPECT_FALSE(acPtr->Expired()); acPtr.reset(); EXPECT_TRUE(sw.ElapsedSec() < 2); } TEST_F(AlarmClockTest, milliseconds_ResetAfterExpired) { // First run int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_ResetBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsAfterExpired) { // First run int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset again after it has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsMixed) { int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } <commit_msg>Fixing unit tests<commit_after>/* * File: AlarmClockTest.cpp * Author: Craig Cogdill * Created: October 15, 2015 10:45am * Modifier: Amanda Carbonari * Modified Date: January 5, 2015 3:45pm */ #include "AlarmClockTest.h" #include "AlarmClock.h" #include "StopWatch.h" #include <chrono> #include <iostream> #include <thread> std::atomic<unsigned int> AlarmClockTest::mFakeSleepUs(0); namespace { typedef std::chrono::microseconds microseconds; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::seconds seconds; unsigned int kFakeSleepLeeway = 100; template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) { while (!alerter.Expired()); } template<typename Duration> unsigned int ConvertToMicroSeconds(Duration t) { return std::chrono::duration_cast<microseconds>(t).count(); } template<typename Duration> unsigned int ConvertToMilliSeconds(Duration t) { return std::chrono::duration_cast<milliseconds>(t).count(); } unsigned int FakeSleep(unsigned int usToSleep) { AlarmClockTest::mFakeSleepUs.store(usToSleep); std::this_thread::sleep_for(microseconds(100)); return 0; } } TEST_F(AlarmClockTest, GetUsSleepTimeInUs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(us, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetUsSleepTimeInMs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(ConvertToMilliSeconds(microseconds(us)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInMs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ms, alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInUs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ConvertToMicroSeconds(milliseconds(ms)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInUs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMicroSeconds(seconds(sec)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInMs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMilliSeconds(seconds(sec)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, microsecondsLessThan500ms) { int us = 900; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, microsecondsGreaterThan500ms) { int us = 600000; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, weirdNumberOfMicroseconds) { int us = 724509; StopWatch sw; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, millisecondsLessThan500) { unsigned int ms = 100; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, oneSecondInMilliseconds) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, millisecondsNotDivisibleBy500) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, secondsSimple) { unsigned int sec = 1; AlarmClock<seconds> alerter(sec, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, LongTimeout_ImmediatelyDestructed) { unsigned int sec = 1000; StopWatch sw; std::unique_ptr<AlarmClock<seconds>> acPtr(new AlarmClock<seconds>(sec, FakeSleep)); EXPECT_FALSE(acPtr->Expired()); acPtr.reset(); EXPECT_TRUE(sw.ElapsedSec() < 2); } TEST_F(AlarmClockTest, milliseconds_ResetAfterExpired) { // First run int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_ResetBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsAfterExpired) { // First run int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset again after it has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsMixed) { int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } <|endoftext|>
<commit_before>/* * File: AlarmClockTest.cpp * Author: Craig Cogdill * Created: October 15, 2015 10:45am * Modifier: Amanda Carbonari * Modified Date: January 5, 2015 3:45pm */ #include "AlarmClockTest.h" #include "AlarmClock.h" #include "StopWatch.h" #include <chrono> #include <iostream> #include <thread> std::atomic<unsigned int> AlarmClockTest::mFakeSleepUs(0); namespace { typedef std::chrono::microseconds microseconds; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::seconds seconds; unsigned int kFakeSleepLeeway = 100; template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) { // cout << "WAIT: Entering while" << endl; while (!alerter.Expired()); // cout << "WAIT: Exiting" << endl; } template<typename Duration> unsigned int ConvertToMicroSeconds(Duration t) { return std::chrono::duration_cast<microseconds>(t).count(); } template<typename Duration> unsigned int ConvertToMilliSeconds(Duration t) { return std::chrono::duration_cast<milliseconds>(t).count(); } unsigned int FakeSleep(unsigned int usToSleep) { AlarmClockTest::mFakeSleepUs.store(usToSleep); std::this_thread::sleep_for(microseconds(100)); return 0; } } TEST_F(AlarmClockTest, GetUsSleepTimeInUs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(us, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetUsSleepTimeInMs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(ConvertToMilliSeconds(microseconds(us)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInMs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ms, alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInUs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ConvertToMicroSeconds(milliseconds(ms)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInUs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMicroSeconds(seconds(sec)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInMs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMilliSeconds(seconds(sec)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, microsecondsLessThan500ms) { int us = 900; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, microsecondsGreaterThan500ms) { int us = 600000; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, weirdNumberOfMicroseconds) { int us = 724509; StopWatch sw; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, millisecondsLessThan500) { unsigned int ms = 100; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, oneSecondInMilliseconds) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, millisecondsNotDivisibleBy500) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, secondsSimple) { unsigned int sec = 1; AlarmClock<seconds> alerter(sec, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } // Not working, not sure what it's supposed to be testing? TEST_F(AlarmClockTest, LongTimeout_ImmediatelyDestructed) { unsigned int sec = 1000; StopWatch sw; // cout << "TEST: Creating pointer" << endl; std::unique_ptr<AlarmClock<seconds>> acPtr(new AlarmClock<seconds>(sec, FakeSleep)); // cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(acPtr->Expired()); this_thread::sleep_for(microseconds(10)); // cout << "TEST: resetting pointer" << endl; acPtr.reset(); // cout << "TEST: expecting true for elapsed seconds" << endl; EXPECT_TRUE(sw.ElapsedSec() < 2); // cout << "TEST: calling destructor" << endl; } TEST_F(AlarmClockTest, milliseconds_ResetAfterExpired) { // First run int ms = 750; // cout << "TEST: creating alarm clock" << endl; AlarmClock<milliseconds> alerter(ms, FakeSleep); // cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(alerter.Expired()); // cout << "TEST: waiting for alarm clock to expire" << endl; WaitForAlarmClockToExpire(alerter); // cout << "TEST: expecting true for expired" << endl; EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired // cout << "TEST: resetting alarm clock" << endl; alerter.Reset(); // cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(alerter.Expired()); // cout << "TEST: waiting for alarm clock to expire" << endl; WaitForAlarmClockToExpire(alerter); // cout << "TEST: expecting true for expired" << endl; EXPECT_TRUE(alerter.Expired()); // cout << "TEST: finished and calling destrcutor" << endl; this_thread::sleep_for(microseconds(100)); } TEST_F(AlarmClockTest, milliseconds_ResetBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsAfterExpired) { // First run int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset again after it has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsMixed) { int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } <commit_msg>Chasing down concurrency issues<commit_after>/* * File: AlarmClockTest.cpp * Author: Craig Cogdill * Created: October 15, 2015 10:45am * Modifier: Amanda Carbonari * Modified Date: January 5, 2015 3:45pm */ #include "AlarmClockTest.h" #include "AlarmClock.h" #include "StopWatch.h" #include <chrono> #include <iostream> #include <thread> std::atomic<unsigned int> AlarmClockTest::mFakeSleepUs(0); namespace { typedef std::chrono::microseconds microseconds; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::seconds seconds; unsigned int kFakeSleepLeeway = 100; template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) { // cout << "WAIT: Entering while" << endl; while (!alerter.Expired()); // cout << "WAIT: Exiting" << endl; } template<typename Duration> unsigned int ConvertToMicroSeconds(Duration t) { return std::chrono::duration_cast<microseconds>(t).count(); } template<typename Duration> unsigned int ConvertToMilliSeconds(Duration t) { return std::chrono::duration_cast<milliseconds>(t).count(); } unsigned int FakeSleep(unsigned int usToSleep) { AlarmClockTest::mFakeSleepUs.store(usToSleep); std::this_thread::sleep_for(microseconds(100)); return 0; } } TEST_F(AlarmClockTest, GetUsSleepTimeInUs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(us, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetUsSleepTimeInMs) { int us = 123456; AlarmClock<microseconds> alerter(us); EXPECT_EQ(ConvertToMilliSeconds(microseconds(us)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInMs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ms, alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, GetMsSleepTimeInUs) { int ms = 123456; AlarmClock<milliseconds> alerter(ms); EXPECT_EQ(ConvertToMicroSeconds(milliseconds(ms)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInUs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMicroSeconds(seconds(sec)), alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, GetSecSleepTimeInMs) { int sec = 1; AlarmClock<seconds> alerter(sec); EXPECT_EQ(ConvertToMilliSeconds(seconds(sec)), alerter.SleepTimeMs()); } TEST_F(AlarmClockTest, microsecondsLessThan500ms) { int us = 900; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, microsecondsGreaterThan500ms) { int us = 600000; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, weirdNumberOfMicroseconds) { int us = 724509; StopWatch sw; AlarmClock<microseconds> alerter(us, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, us); } TEST_F(AlarmClockTest, millisecondsLessThan500) { unsigned int ms = 100; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, oneSecondInMilliseconds) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, millisecondsNotDivisibleBy500) { unsigned int ms = 1000; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } TEST_F(AlarmClockTest, secondsSimple) { unsigned int sec = 1; AlarmClock<seconds> alerter(sec, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway); EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()); } // Not working, not sure what it's supposed to be testing? TEST_F(AlarmClockTest, LongTimeout_ImmediatelyDestructed) { unsigned int sec = 1000; StopWatch sw; // cout << "TEST: Creating pointer" << endl; std::unique_ptr<AlarmClock<seconds>> acPtr(new AlarmClock<seconds>(sec, FakeSleep)); // cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(acPtr->Expired()); this_thread::sleep_for(microseconds(10)); // cout << "TEST: resetting pointer" << endl; acPtr.reset(); // cout << "TEST: expecting true for elapsed seconds" << endl; EXPECT_TRUE(sw.ElapsedSec() < 2); // cout << "TEST: calling destructor" << endl; } TEST_F(AlarmClockTest, milliseconds_ResetAfterExpired) { // First run int ms = 750; // cout << "TEST: creating alarm clock" << endl; AlarmClock<milliseconds> alerter(ms, FakeSleep); // cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(alerter.Expired()); // cout << "TEST: waiting for alarm clock to expire" << endl; WaitForAlarmClockToExpire(alerter); // cout << "TEST: expecting true for expired" << endl; EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired // cout << "TEST: resetting alarm clock" << endl; alerter.Reset(); // cout << "TEST: expecting false for expired" << endl; EXPECT_FALSE(alerter.Expired()); // cout << "TEST: waiting for alarm clock to expire" << endl; WaitForAlarmClockToExpire(alerter); // cout << "TEST: expecting true for expired" << endl; EXPECT_TRUE(alerter.Expired()); // cout << "TEST: finished and calling destrcutor" << endl; } TEST_F(AlarmClockTest, milliseconds_ResetBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsAfterExpired) { // First run int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset after AlarmClock has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); // Reset again after it has expired alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsBeforeExpired) { int ms = 7500; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } TEST_F(AlarmClockTest, milliseconds_MultipleResetsMixed) { int ms = 750; AlarmClock<milliseconds> alerter(ms, FakeSleep); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); alerter.Reset(); EXPECT_FALSE(alerter.Expired()); WaitForAlarmClockToExpire(alerter); EXPECT_TRUE(alerter.Expired()); } <|endoftext|>
<commit_before>#include "catch.hpp" #include <chig/Context.hpp> #include <chig/GraphFunction.hpp> #include <chig/LangModule.hpp> using namespace chig; TEST_CASE("JsonSerializer", "[json]") { GIVEN("A default constructed Context and GraphFunction named hello") { Context c; GraphFunction func(c, "hello"); WHEN("We create some nodes and try to dump json") { std::vector<std::pair<llvm::Type*, std::string>> inputs = { {llvm::Type::getInt32Ty(c.context), "in1"}}; auto entry = func.insertNode(std::make_unique<EntryNodeType>(c, inputs), 32, 32); auto ifNode = func.insertNode(c.getNodeType("lang", "if", {}), 44.f, 23.f); connectExec(*entry, 0, *ifNode, 0); connectData(*entry, 0, *ifNode, 0); auto dumpedJSON = func.toJSON(); THEN("It should be the same as the sample!") { using namespace nlohmann; auto correctJSON = R"ENDJSON( { "type": "function", "name": "hello", "nodes": [ { "type": "lang:entry", "location": [32.0,32.0], "data": { "in1": "lang:i32" } }, { "type": "lang:if", "location": [44.0,23.0], "data": null } ], "connections": [ { "type": "exec", "input": [0,0], "output": [1,0] }, { "type": "data", "input": [0,0], "output": [1,0] } ] } )ENDJSON"_json; REQUIRE(dumpedJSON == correctJSON); } } } } <commit_msg>Fix test case<commit_after>#include "catch.hpp" #include <chig/Context.hpp> #include <chig/GraphFunction.hpp> #include <chig/LangModule.hpp> using namespace chig; TEST_CASE("JsonSerializer", "[json]") { GIVEN("A default constructed Context with a LangModule and GraphFunction named hello") { Context c; c.addModule(std::make_unique<LangModule>(c)); GraphFunction func(c, "hello"); WHEN("We create some nodes and try to dump json") { std::vector<std::pair<llvm::Type*, std::string>> inputs = { {llvm::Type::getInt32Ty(c.context), "in1"}}; auto entry = func.insertNode(std::make_unique<EntryNodeType>(c, inputs), 32, 32); auto ifNode = func.insertNode(c.getNodeType("lang", "if", {}), 44.f, 23.f); connectExec(*entry, 0, *ifNode, 0); connectData(*entry, 0, *ifNode, 0); auto dumpedJSON = func.toJSON(); THEN("It should be the same as the sample!") { using namespace nlohmann; auto correctJSON = R"ENDJSON( { "type": "function", "name": "hello", "nodes": [ { "type": "lang:entry", "location": [32.0,32.0], "data": { "in1": "lang:i32" } }, { "type": "lang:if", "location": [44.0,23.0], "data": null } ], "connections": [ { "type": "exec", "input": [0,0], "output": [1,0] }, { "type": "data", "input": [0,0], "output": [1,0] } ] } )ENDJSON"_json; REQUIRE(dumpedJSON == correctJSON); } } } } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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 <tchar.h> #include "webkit/glue/plugins/plugin_list.h" #include "base/basictypes.h" #include "base/command_line.h" #include "base/path_service.h" #include "base/registry.h" #include "base/string_util.h" #include "webkit/activex_shim/npp_impl.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_lib.h" #include "webkit/glue/webkit_glue.h" namespace { const TCHAR kRegistryApps[] = _T("Software\\Microsoft\\Windows\\CurrentVersion\\App Paths"); const TCHAR kRegistryFirefox[] = _T("firefox.exe"); const TCHAR kRegistryAcrobat[] = _T("Acrobat.exe"); const TCHAR kRegistryAcrobatReader[] = _T("AcroRd32.exe"); const TCHAR kRegistryWindowsMedia[] = _T("wmplayer.exe"); const TCHAR kRegistryQuickTime[] = _T("QuickTimePlayer.exe"); const TCHAR kRegistryPath[] = _T("Path"); const TCHAR kRegistryMozillaPlugins[] = _T("SOFTWARE\\MozillaPlugins"); const TCHAR kRegistryFirefoxInstalled[] = _T("SOFTWARE\\Mozilla\\Mozilla Firefox"); const TCHAR kMozillaActiveXPlugin[] = _T("npmozax.dll"); const TCHAR kNewWMPPlugin[] = _T("np-mswmp.dll"); const TCHAR kOldWMPPlugin[] = _T("npdsplay.dll"); const TCHAR kYahooApplicationStatePlugin[] = _T("npystate.dll"); const TCHAR kRegistryJava[] = _T("Software\\JavaSoft\\Java Runtime Environment"); const TCHAR kRegistryBrowserJavaVersion[] = _T("BrowserJavaVersion"); const TCHAR kRegistryCurrentJavaVersion[] = _T("CurrentVersion"); const TCHAR kRegistryJavaHome[] = _T("JavaHome"); #ifdef GEARS_STATIC_LIB // defined in gears/base/common/module.cc NPError API_CALL Gears_NP_GetEntryPoints(NPPluginFuncs* funcs); NPError API_CALL Gears_NP_Initialize(NPNetscapeFuncs* funcs); NPError API_CALL Gears_NP_Shutdown(void); #endif // The application path where we expect to find plugins. void GetAppDirectory(std::set<FilePath>* plugin_dirs) { std::wstring app_path; // TODO(avi): use PathService directly if (!webkit_glue::GetApplicationDirectory(&app_path)) return; app_path.append(L"\\plugins"); plugin_dirs->insert(FilePath(app_path)); } // The executable path where we expect to find plugins. void GetExeDirectory(std::set<FilePath>* plugin_dirs) { std::wstring exe_path; // TODO(avi): use PathService directly if (!webkit_glue::GetExeDirectory(&exe_path)) return; exe_path.append(L"\\plugins"); plugin_dirs->insert(FilePath(exe_path)); } // Gets the installed path for a registered app. bool GetInstalledPath(const TCHAR* app, FilePath* out) { std::wstring reg_path(kRegistryApps); reg_path.append(L"\\"); reg_path.append(app); RegKey key(HKEY_LOCAL_MACHINE, reg_path.c_str()); std::wstring path; if (key.ReadValue(kRegistryPath, &path)) { *out = FilePath(path); return true; } return false; } // Search the registry at the given path and detect plugin directories. void GetPluginsInRegistryDirectory( HKEY root_key, const std::wstring& registry_folder, std::set<FilePath>* plugin_dirs) { for (RegistryKeyIterator iter(root_key, registry_folder.c_str()); iter.Valid(); ++iter) { // Use the registry to gather plugin across the file system. std::wstring reg_path = registry_folder; reg_path.append(L"\\"); reg_path.append(iter.Name()); RegKey key(root_key, reg_path.c_str()); std::wstring path; if (key.ReadValue(kRegistryPath, &path)) plugin_dirs->insert(FilePath(path).DirName()); } } // Enumerate through the registry key to find all installed FireFox paths. // FireFox 3 beta and version 2 can coexist. See bug: 1025003 void GetFirefoxInstalledPaths(std::vector<FilePath>* out) { RegistryKeyIterator it(HKEY_LOCAL_MACHINE, kRegistryFirefoxInstalled); for (; it.Valid(); ++it) { std::wstring full_path = std::wstring(kRegistryFirefoxInstalled) + L"\\" + it.Name() + L"\\Main"; RegKey key(HKEY_LOCAL_MACHINE, full_path.c_str(), KEY_READ); std::wstring install_dir; if (!key.ReadValue(L"Install Directory", &install_dir)) continue; out->push_back(FilePath(install_dir)); } } // Get plugin directory locations from the Firefox install path. This is kind // of a kludge, but it helps us locate the flash player for users that // already have it for firefox. Not having to download yet-another-plugin // is a good thing. void GetFirefoxDirectory(std::set<FilePath>* plugin_dirs) { std::vector<FilePath> paths; GetFirefoxInstalledPaths(&paths); for (unsigned int i = 0; i < paths.size(); ++i) { plugin_dirs->insert(paths[i].Append(L"plugins")); } GetPluginsInRegistryDirectory( HKEY_CURRENT_USER, kRegistryMozillaPlugins, plugin_dirs); GetPluginsInRegistryDirectory( HKEY_LOCAL_MACHINE, kRegistryMozillaPlugins, plugin_dirs); std::wstring firefox_app_data_plugin_path; if (PathService::Get(base::DIR_APP_DATA, &firefox_app_data_plugin_path)) { firefox_app_data_plugin_path += L"\\Mozilla\\plugins"; plugin_dirs->insert(FilePath(firefox_app_data_plugin_path)); } } // Hardcoded logic to detect Acrobat plugins locations. void GetAcrobatDirectory(std::set<FilePath>* plugin_dirs) { FilePath path; if (!GetInstalledPath(kRegistryAcrobatReader, &path) && !GetInstalledPath(kRegistryAcrobat, &path)) { return; } plugin_dirs->insert(path.Append(L"Browser")); } // Hardcoded logic to detect QuickTime plugin location. void GetQuicktimeDirectory(std::set<FilePath>* plugin_dirs) { FilePath path; if (GetInstalledPath(kRegistryQuickTime, &path)) plugin_dirs->insert(path.Append(L"plugins")); } // Hardcoded logic to detect Windows Media Player plugin location. void GetWindowsMediaDirectory(std::set<FilePath>* plugin_dirs) { FilePath path; if (GetInstalledPath(kRegistryWindowsMedia, &path)) plugin_dirs->insert(path); } // Hardcoded logic to detect Java plugin location. void GetJavaDirectory(std::set<FilePath>* plugin_dirs) { // Load the new NPAPI Java plugin // 1. Open the main JRE key under HKLM RegKey java_key(HKEY_LOCAL_MACHINE, kRegistryJava, KEY_QUERY_VALUE); // 2. Read the current Java version std::wstring java_version; if (!java_key.ReadValue(kRegistryBrowserJavaVersion, &java_version)) java_key.ReadValue(kRegistryCurrentJavaVersion, &java_version); if (!java_version.empty()) { java_key.OpenKey(java_version.c_str(), KEY_QUERY_VALUE); // 3. Install path of the JRE binaries is specified in "JavaHome" // value under the Java version key. std::wstring java_plugin_directory; if (java_key.ReadValue(kRegistryJavaHome, &java_plugin_directory)) { // 4. The new plugin resides under the 'bin/new_plugin' // subdirectory. DCHECK(!java_plugin_directory.empty()); java_plugin_directory.append(L"\\bin\\new_plugin"); // 5. We don't know the exact name of the DLL but it's in the form // NP*.dll so just invoke LoadPlugins on this path. plugin_dirs->insert(FilePath(java_plugin_directory)); } } } } namespace NPAPI { void PluginList::PlatformInit() { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); dont_load_new_wmp_ = command_line.HasSwitch(kUseOldWMPPluginSwitch); use_internal_activex_shim_ = !command_line.HasSwitch(kNoNativeActiveXShimSwitch); const PluginVersionInfo builtin_plugins[] = { { FilePath(kActiveXShimFileName), L"ActiveX Plug-in", L"ActiveX Plug-in provides a shim to support ActiveX controls", L"1, 0, 0, 1", L"application/x-oleobject|application/oleobject", L"*|*", L"", { activex_shim::ActiveX_Shim_NP_GetEntryPoints, activex_shim::ActiveX_Shim_NP_Initialize, activex_shim::ActiveX_Shim_NP_Shutdown } }, { FilePath(kActiveXShimFileNameForMediaPlayer), kActiveXShimFileNameForMediaPlayer, L"Windows Media Player", L"1, 0, 0, 1", L"application/x-ms-wmp|application/asx|video/x-ms-asf-plugin|" L"application/x-mplayer2|video/x-ms-asf|video/x-ms-wm|audio/x-ms-wma|" L"audio/x-ms-wax|video/x-ms-wmv|video/x-ms-wvx", L"*|*|*|*|asf,asx,*|wm,*|wma,*|wax,*|wmv,*|wvx,*", L"", { activex_shim::ActiveX_Shim_NP_GetEntryPoints, activex_shim::ActiveX_Shim_NP_Initialize, activex_shim::ActiveX_Shim_NP_Shutdown } }, #ifdef GEARS_STATIC_LIB { FilePath(kGearsPluginLibraryName), L"Gears", L"Statically linked Gears", L"1, 0, 0, 1", L"application/x-googlegears", L"", L"", { Gears_NP_GetEntryPoints, Gears_NP_Initialize, Gears_NP_Shutdown } }, #endif }; for (int i = 0; i < arraysize(builtin_plugins); ++i) internal_plugins_.push_back(builtin_plugins[i]); } void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) { // We use a set for uniqueness, which we require, over order, which we do not. std::set<FilePath> dirs; // Load from the application-specific area GetAppDirectory(&dirs); // Load from the executable area GetExeDirectory(&dirs); // Load Java GetJavaDirectory(&dirs); // Load firefox plugins too. This is mainly to try to locate // a pre-installed Flash player. GetFirefoxDirectory(&dirs); // Firefox hard-codes the paths of some popular plugins to ensure that // the plugins are found. We are going to copy this as well. GetAcrobatDirectory(&dirs); GetQuicktimeDirectory(&dirs); GetWindowsMediaDirectory(&dirs); for (std::set<FilePath>::iterator i = dirs.begin(); i != dirs.end(); ++i) plugin_dirs->push_back(*i); } void PluginList::LoadPluginsFromDir(const FilePath &path) { WIN32_FIND_DATA find_file_data; HANDLE find_handle; std::wstring dir = path.value(); // FindFirstFile requires that you specify a wildcard for directories. dir.append(L"\\NP*.DLL"); find_handle = FindFirstFile(dir.c_str(), &find_file_data); if (find_handle == INVALID_HANDLE_VALUE) return; do { if (!(find_file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { FilePath filename = path.Append(find_file_data.cFileName); LoadPlugin(filename); } } while (FindNextFile(find_handle, &find_file_data) != 0); DCHECK(GetLastError() == ERROR_NO_MORE_FILES); FindClose(find_handle); } // Compares Windows style version strings (i.e. 1,2,3,4). Returns true if b's // version is newer than a's, or false if it's equal or older. bool IsNewerVersion(const std::wstring& a, const std::wstring& b) { std::vector<std::wstring> a_ver, b_ver; SplitString(a, ',', &a_ver); SplitString(b, ',', &b_ver); if (a_ver.size() != b_ver.size()) return false; for (size_t i = 0; i < a_ver.size(); i++) { int cur_a = StringToInt(a_ver[i]); int cur_b = StringToInt(b_ver[i]); if (cur_a > cur_b) return false; if (cur_a < cur_b) return true; } return false; } bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info) { // Version check for (size_t i = 0; i < plugins_.size(); ++i) { if (plugins_[i].path.BaseName() == info.path.BaseName() && !IsNewerVersion(plugins_[i].version, info.version)) { return false; // We already have a loaded plugin whose version is newer. } } // Troublemakers std::wstring filename = StringToLowerASCII(info.path.BaseName().value()); // Depends on XPCOM. if (filename == kMozillaActiveXPlugin) return false; // Disable the Yahoo Application State plugin as it crashes the plugin // process on return from NPObjectStub::OnInvoke. Please refer to // http://b/issue?id=1372124 for more information. if (filename == kYahooApplicationStatePlugin) return false; // Special WMP handling // We will use the ActiveX shim to handle embedded WMP media. if (use_internal_activex_shim_) { if (filename == kNewWMPPlugin || filename == kOldWMPPlugin) return false; } else { // If both the new and old WMP plugins exist, only load the new one. if (filename == kNewWMPPlugin) { if (dont_load_new_wmp_) return false; for (size_t i = 0; i < plugins_.size(); ++i) { if (plugins_[i].path.BaseName().value() == kOldWMPPlugin) { plugins_.erase(plugins_.begin() + i); break; } } } else if (filename == kOldWMPPlugin) { for (size_t i = 0; i < plugins_.size(); ++i) { if (plugins_[i].path.BaseName().value() == kNewWMPPlugin) return false; } } } return true; } void PluginList::LoadInternalPlugins() { #ifdef GEARS_STATIC_LIB LoadPlugin(FilePath(kGearsPluginLibraryName)); #endif if (!use_internal_activex_shim_) return; LoadPlugin(FilePath(kActiveXShimFileName)); LoadPlugin(FilePath(kActiveXShimFileNameForMediaPlayer)); } } // namespace NPAPI <commit_msg>Disable the WanWang protocol handler plugin (npww.dll) as it crashes during shutdown.<commit_after>// Copyright (c) 2006-2008 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 <tchar.h> #include "webkit/glue/plugins/plugin_list.h" #include "base/basictypes.h" #include "base/command_line.h" #include "base/path_service.h" #include "base/registry.h" #include "base/string_util.h" #include "webkit/activex_shim/npp_impl.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_lib.h" #include "webkit/glue/webkit_glue.h" namespace { const TCHAR kRegistryApps[] = _T("Software\\Microsoft\\Windows\\CurrentVersion\\App Paths"); const TCHAR kRegistryFirefox[] = _T("firefox.exe"); const TCHAR kRegistryAcrobat[] = _T("Acrobat.exe"); const TCHAR kRegistryAcrobatReader[] = _T("AcroRd32.exe"); const TCHAR kRegistryWindowsMedia[] = _T("wmplayer.exe"); const TCHAR kRegistryQuickTime[] = _T("QuickTimePlayer.exe"); const TCHAR kRegistryPath[] = _T("Path"); const TCHAR kRegistryMozillaPlugins[] = _T("SOFTWARE\\MozillaPlugins"); const TCHAR kRegistryFirefoxInstalled[] = _T("SOFTWARE\\Mozilla\\Mozilla Firefox"); const TCHAR kMozillaActiveXPlugin[] = _T("npmozax.dll"); const TCHAR kNewWMPPlugin[] = _T("np-mswmp.dll"); const TCHAR kOldWMPPlugin[] = _T("npdsplay.dll"); const TCHAR kYahooApplicationStatePlugin[] = _T("npystate.dll"); const TCHAR kWanWangProtocolHandlerPlugin[] = _T("npww.dll"); const TCHAR kRegistryJava[] = _T("Software\\JavaSoft\\Java Runtime Environment"); const TCHAR kRegistryBrowserJavaVersion[] = _T("BrowserJavaVersion"); const TCHAR kRegistryCurrentJavaVersion[] = _T("CurrentVersion"); const TCHAR kRegistryJavaHome[] = _T("JavaHome"); #ifdef GEARS_STATIC_LIB // defined in gears/base/common/module.cc NPError API_CALL Gears_NP_GetEntryPoints(NPPluginFuncs* funcs); NPError API_CALL Gears_NP_Initialize(NPNetscapeFuncs* funcs); NPError API_CALL Gears_NP_Shutdown(void); #endif // The application path where we expect to find plugins. void GetAppDirectory(std::set<FilePath>* plugin_dirs) { std::wstring app_path; // TODO(avi): use PathService directly if (!webkit_glue::GetApplicationDirectory(&app_path)) return; app_path.append(L"\\plugins"); plugin_dirs->insert(FilePath(app_path)); } // The executable path where we expect to find plugins. void GetExeDirectory(std::set<FilePath>* plugin_dirs) { std::wstring exe_path; // TODO(avi): use PathService directly if (!webkit_glue::GetExeDirectory(&exe_path)) return; exe_path.append(L"\\plugins"); plugin_dirs->insert(FilePath(exe_path)); } // Gets the installed path for a registered app. bool GetInstalledPath(const TCHAR* app, FilePath* out) { std::wstring reg_path(kRegistryApps); reg_path.append(L"\\"); reg_path.append(app); RegKey key(HKEY_LOCAL_MACHINE, reg_path.c_str()); std::wstring path; if (key.ReadValue(kRegistryPath, &path)) { *out = FilePath(path); return true; } return false; } // Search the registry at the given path and detect plugin directories. void GetPluginsInRegistryDirectory( HKEY root_key, const std::wstring& registry_folder, std::set<FilePath>* plugin_dirs) { for (RegistryKeyIterator iter(root_key, registry_folder.c_str()); iter.Valid(); ++iter) { // Use the registry to gather plugin across the file system. std::wstring reg_path = registry_folder; reg_path.append(L"\\"); reg_path.append(iter.Name()); RegKey key(root_key, reg_path.c_str()); std::wstring path; if (key.ReadValue(kRegistryPath, &path)) plugin_dirs->insert(FilePath(path).DirName()); } } // Enumerate through the registry key to find all installed FireFox paths. // FireFox 3 beta and version 2 can coexist. See bug: 1025003 void GetFirefoxInstalledPaths(std::vector<FilePath>* out) { RegistryKeyIterator it(HKEY_LOCAL_MACHINE, kRegistryFirefoxInstalled); for (; it.Valid(); ++it) { std::wstring full_path = std::wstring(kRegistryFirefoxInstalled) + L"\\" + it.Name() + L"\\Main"; RegKey key(HKEY_LOCAL_MACHINE, full_path.c_str(), KEY_READ); std::wstring install_dir; if (!key.ReadValue(L"Install Directory", &install_dir)) continue; out->push_back(FilePath(install_dir)); } } // Get plugin directory locations from the Firefox install path. This is kind // of a kludge, but it helps us locate the flash player for users that // already have it for firefox. Not having to download yet-another-plugin // is a good thing. void GetFirefoxDirectory(std::set<FilePath>* plugin_dirs) { std::vector<FilePath> paths; GetFirefoxInstalledPaths(&paths); for (unsigned int i = 0; i < paths.size(); ++i) { plugin_dirs->insert(paths[i].Append(L"plugins")); } GetPluginsInRegistryDirectory( HKEY_CURRENT_USER, kRegistryMozillaPlugins, plugin_dirs); GetPluginsInRegistryDirectory( HKEY_LOCAL_MACHINE, kRegistryMozillaPlugins, plugin_dirs); std::wstring firefox_app_data_plugin_path; if (PathService::Get(base::DIR_APP_DATA, &firefox_app_data_plugin_path)) { firefox_app_data_plugin_path += L"\\Mozilla\\plugins"; plugin_dirs->insert(FilePath(firefox_app_data_plugin_path)); } } // Hardcoded logic to detect Acrobat plugins locations. void GetAcrobatDirectory(std::set<FilePath>* plugin_dirs) { FilePath path; if (!GetInstalledPath(kRegistryAcrobatReader, &path) && !GetInstalledPath(kRegistryAcrobat, &path)) { return; } plugin_dirs->insert(path.Append(L"Browser")); } // Hardcoded logic to detect QuickTime plugin location. void GetQuicktimeDirectory(std::set<FilePath>* plugin_dirs) { FilePath path; if (GetInstalledPath(kRegistryQuickTime, &path)) plugin_dirs->insert(path.Append(L"plugins")); } // Hardcoded logic to detect Windows Media Player plugin location. void GetWindowsMediaDirectory(std::set<FilePath>* plugin_dirs) { FilePath path; if (GetInstalledPath(kRegistryWindowsMedia, &path)) plugin_dirs->insert(path); } // Hardcoded logic to detect Java plugin location. void GetJavaDirectory(std::set<FilePath>* plugin_dirs) { // Load the new NPAPI Java plugin // 1. Open the main JRE key under HKLM RegKey java_key(HKEY_LOCAL_MACHINE, kRegistryJava, KEY_QUERY_VALUE); // 2. Read the current Java version std::wstring java_version; if (!java_key.ReadValue(kRegistryBrowserJavaVersion, &java_version)) java_key.ReadValue(kRegistryCurrentJavaVersion, &java_version); if (!java_version.empty()) { java_key.OpenKey(java_version.c_str(), KEY_QUERY_VALUE); // 3. Install path of the JRE binaries is specified in "JavaHome" // value under the Java version key. std::wstring java_plugin_directory; if (java_key.ReadValue(kRegistryJavaHome, &java_plugin_directory)) { // 4. The new plugin resides under the 'bin/new_plugin' // subdirectory. DCHECK(!java_plugin_directory.empty()); java_plugin_directory.append(L"\\bin\\new_plugin"); // 5. We don't know the exact name of the DLL but it's in the form // NP*.dll so just invoke LoadPlugins on this path. plugin_dirs->insert(FilePath(java_plugin_directory)); } } } } namespace NPAPI { void PluginList::PlatformInit() { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); dont_load_new_wmp_ = command_line.HasSwitch(kUseOldWMPPluginSwitch); use_internal_activex_shim_ = !command_line.HasSwitch(kNoNativeActiveXShimSwitch); const PluginVersionInfo builtin_plugins[] = { { FilePath(kActiveXShimFileName), L"ActiveX Plug-in", L"ActiveX Plug-in provides a shim to support ActiveX controls", L"1, 0, 0, 1", L"application/x-oleobject|application/oleobject", L"*|*", L"", { activex_shim::ActiveX_Shim_NP_GetEntryPoints, activex_shim::ActiveX_Shim_NP_Initialize, activex_shim::ActiveX_Shim_NP_Shutdown } }, { FilePath(kActiveXShimFileNameForMediaPlayer), kActiveXShimFileNameForMediaPlayer, L"Windows Media Player", L"1, 0, 0, 1", L"application/x-ms-wmp|application/asx|video/x-ms-asf-plugin|" L"application/x-mplayer2|video/x-ms-asf|video/x-ms-wm|audio/x-ms-wma|" L"audio/x-ms-wax|video/x-ms-wmv|video/x-ms-wvx", L"*|*|*|*|asf,asx,*|wm,*|wma,*|wax,*|wmv,*|wvx,*", L"", { activex_shim::ActiveX_Shim_NP_GetEntryPoints, activex_shim::ActiveX_Shim_NP_Initialize, activex_shim::ActiveX_Shim_NP_Shutdown } }, #ifdef GEARS_STATIC_LIB { FilePath(kGearsPluginLibraryName), L"Gears", L"Statically linked Gears", L"1, 0, 0, 1", L"application/x-googlegears", L"", L"", { Gears_NP_GetEntryPoints, Gears_NP_Initialize, Gears_NP_Shutdown } }, #endif }; for (int i = 0; i < arraysize(builtin_plugins); ++i) internal_plugins_.push_back(builtin_plugins[i]); } void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) { // We use a set for uniqueness, which we require, over order, which we do not. std::set<FilePath> dirs; // Load from the application-specific area GetAppDirectory(&dirs); // Load from the executable area GetExeDirectory(&dirs); // Load Java GetJavaDirectory(&dirs); // Load firefox plugins too. This is mainly to try to locate // a pre-installed Flash player. GetFirefoxDirectory(&dirs); // Firefox hard-codes the paths of some popular plugins to ensure that // the plugins are found. We are going to copy this as well. GetAcrobatDirectory(&dirs); GetQuicktimeDirectory(&dirs); GetWindowsMediaDirectory(&dirs); for (std::set<FilePath>::iterator i = dirs.begin(); i != dirs.end(); ++i) plugin_dirs->push_back(*i); } void PluginList::LoadPluginsFromDir(const FilePath &path) { WIN32_FIND_DATA find_file_data; HANDLE find_handle; std::wstring dir = path.value(); // FindFirstFile requires that you specify a wildcard for directories. dir.append(L"\\NP*.DLL"); find_handle = FindFirstFile(dir.c_str(), &find_file_data); if (find_handle == INVALID_HANDLE_VALUE) return; do { if (!(find_file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { FilePath filename = path.Append(find_file_data.cFileName); LoadPlugin(filename); } } while (FindNextFile(find_handle, &find_file_data) != 0); DCHECK(GetLastError() == ERROR_NO_MORE_FILES); FindClose(find_handle); } // Compares Windows style version strings (i.e. 1,2,3,4). Returns true if b's // version is newer than a's, or false if it's equal or older. bool IsNewerVersion(const std::wstring& a, const std::wstring& b) { std::vector<std::wstring> a_ver, b_ver; SplitString(a, ',', &a_ver); SplitString(b, ',', &b_ver); if (a_ver.size() != b_ver.size()) return false; for (size_t i = 0; i < a_ver.size(); i++) { int cur_a = StringToInt(a_ver[i]); int cur_b = StringToInt(b_ver[i]); if (cur_a > cur_b) return false; if (cur_a < cur_b) return true; } return false; } bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info) { // Version check for (size_t i = 0; i < plugins_.size(); ++i) { if (plugins_[i].path.BaseName() == info.path.BaseName() && !IsNewerVersion(plugins_[i].version, info.version)) { return false; // We already have a loaded plugin whose version is newer. } } // Troublemakers std::wstring filename = StringToLowerASCII(info.path.BaseName().value()); // Depends on XPCOM. if (filename == kMozillaActiveXPlugin) return false; // Disable the Yahoo Application State plugin as it crashes the plugin // process on return from NPObjectStub::OnInvoke. Please refer to // http://b/issue?id=1372124 for more information. if (filename == kYahooApplicationStatePlugin) return false; // Disable the WangWang protocol handler plugin (npww.dll) as it crashes // chrome during shutdown. Firefox also disables this plugin. // Please refer to http://code.google.com/p/chromium/issues/detail?id=3953 // for more information. if (filename == kWanWangProtocolHandlerPlugin) return false; // Special WMP handling // We will use the ActiveX shim to handle embedded WMP media. if (use_internal_activex_shim_) { if (filename == kNewWMPPlugin || filename == kOldWMPPlugin) return false; } else { // If both the new and old WMP plugins exist, only load the new one. if (filename == kNewWMPPlugin) { if (dont_load_new_wmp_) return false; for (size_t i = 0; i < plugins_.size(); ++i) { if (plugins_[i].path.BaseName().value() == kOldWMPPlugin) { plugins_.erase(plugins_.begin() + i); break; } } } else if (filename == kOldWMPPlugin) { for (size_t i = 0; i < plugins_.size(); ++i) { if (plugins_[i].path.BaseName().value() == kNewWMPPlugin) return false; } } } return true; } void PluginList::LoadInternalPlugins() { #ifdef GEARS_STATIC_LIB LoadPlugin(FilePath(kGearsPluginLibraryName)); #endif if (!use_internal_activex_shim_) return; LoadPlugin(FilePath(kActiveXShimFileName)); LoadPlugin(FilePath(kActiveXShimFileNameForMediaPlayer)); } } // namespace NPAPI <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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 "v8_binding.h" #include "AtomicString.h" #include "CString.h" #include "MathExtras.h" #include "PlatformString.h" #include "StringBuffer.h" #include <v8.h> namespace WebCore { // WebCoreStringResource is a helper class for v8ExternalString. It is used // to manage the life-cycle of the underlying buffer of the external string. class WebCoreStringResource: public v8::String::ExternalStringResource { public: explicit WebCoreStringResource(const String& str) : impl_(str.impl()) { } virtual ~WebCoreStringResource() {} const uint16_t* data() const { return reinterpret_cast<const uint16_t*>(impl_.characters()); } size_t length() const { return impl_.length(); } String webcore_string() { return impl_; } private: // A shallow copy of the string. // Keeps the string buffer alive until the V8 engine garbage collects it. String impl_; }; String v8StringToWebCoreString( v8::Handle<v8::String> v8_str, bool externalize) { WebCoreStringResource* str_resource = static_cast<WebCoreStringResource*>( v8_str->GetExternalStringResource()); if (str_resource) { return str_resource->webcore_string(); } int length = v8_str->Length(); if (length == 0) { // Avoid trying to morph empty strings, as they do not have enough room to // contain the external reference. return StringImpl::empty(); } UChar* buffer; String result = String::createUninitialized(length, buffer); v8_str->Write(reinterpret_cast<uint16_t*>(buffer), 0, length); if (externalize) { WebCoreStringResource* resource = new WebCoreStringResource(result); if (!v8_str->MakeExternal(resource)) { // In case of a failure delete the external resource as it was not used. delete resource; } } return result; } String v8ValueToWebCoreString(v8::Handle<v8::Value> obj) { if (obj->IsString()) { v8::Handle<v8::String> v8_str = v8::Handle<v8::String>::Cast(obj); String webCoreString = v8StringToWebCoreString(v8_str, true); return webCoreString; } else if (obj->IsInt32()) { int value = obj->Int32Value(); // Most numbers used are <= 100. Even if they aren't used // there's very little in using the space. const int kLowNumbers = 100; static AtomicString lowNumbers[kLowNumbers + 1]; String webCoreString; if (0 <= value && value <= kLowNumbers) { webCoreString = lowNumbers[value]; if (!webCoreString) { AtomicString valueString = AtomicString(String::number(value)); lowNumbers[value] = valueString; webCoreString = valueString; } } else { webCoreString = String::number(value); } return webCoreString; } else { v8::TryCatch block; v8::Handle<v8::String> v8_str = obj->ToString(); return v8StringToWebCoreString(v8_str, false); } } AtomicString v8StringToAtomicWebCoreString(v8::Handle<v8::String> v8_str) { String str = v8StringToWebCoreString(v8_str, true); return AtomicString(str); } AtomicString v8ValueToAtomicWebCoreString(v8::Handle<v8::Value> v8_str) { String str = v8ValueToWebCoreString(v8_str); return AtomicString(str); } v8::Handle<v8::String> v8String(const String& str) { if (!str.length()) return v8::String::Empty(); return v8::String::NewExternal(new WebCoreStringResource(str)); } v8::Local<v8::String> v8ExternalString(const String& str) { if (!str.length()) return v8::String::Empty(); return v8::String::NewExternal(new WebCoreStringResource(str)); } } // namespace WebCore <commit_msg>Re-introduce check for empty handles after calling toString when converting a JavaScript object to a WebCore string.<commit_after>// Copyright (c) 2006-2008 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 "v8_binding.h" #include "AtomicString.h" #include "CString.h" #include "MathExtras.h" #include "PlatformString.h" #include "StringBuffer.h" #include <v8.h> namespace WebCore { // WebCoreStringResource is a helper class for v8ExternalString. It is used // to manage the life-cycle of the underlying buffer of the external string. class WebCoreStringResource: public v8::String::ExternalStringResource { public: explicit WebCoreStringResource(const String& str) : impl_(str.impl()) { } virtual ~WebCoreStringResource() {} const uint16_t* data() const { return reinterpret_cast<const uint16_t*>(impl_.characters()); } size_t length() const { return impl_.length(); } String webcore_string() { return impl_; } private: // A shallow copy of the string. // Keeps the string buffer alive until the V8 engine garbage collects it. String impl_; }; String v8StringToWebCoreString( v8::Handle<v8::String> v8_str, bool externalize) { WebCoreStringResource* str_resource = static_cast<WebCoreStringResource*>( v8_str->GetExternalStringResource()); if (str_resource) { return str_resource->webcore_string(); } int length = v8_str->Length(); if (length == 0) { // Avoid trying to morph empty strings, as they do not have enough room to // contain the external reference. return StringImpl::empty(); } UChar* buffer; String result = String::createUninitialized(length, buffer); v8_str->Write(reinterpret_cast<uint16_t*>(buffer), 0, length); if (externalize) { WebCoreStringResource* resource = new WebCoreStringResource(result); if (!v8_str->MakeExternal(resource)) { // In case of a failure delete the external resource as it was not used. delete resource; } } return result; } String v8ValueToWebCoreString(v8::Handle<v8::Value> obj) { if (obj->IsString()) { v8::Handle<v8::String> v8_str = v8::Handle<v8::String>::Cast(obj); String webCoreString = v8StringToWebCoreString(v8_str, true); return webCoreString; } else if (obj->IsInt32()) { int value = obj->Int32Value(); // Most numbers used are <= 100. Even if they aren't used // there's very little in using the space. const int kLowNumbers = 100; static AtomicString lowNumbers[kLowNumbers + 1]; String webCoreString; if (0 <= value && value <= kLowNumbers) { webCoreString = lowNumbers[value]; if (!webCoreString) { AtomicString valueString = AtomicString(String::number(value)); lowNumbers[value] = valueString; webCoreString = valueString; } } else { webCoreString = String::number(value); } return webCoreString; } else { v8::TryCatch block; v8::Handle<v8::String> v8_str = obj->ToString(); // Check for empty handles to handle the case where an exception // is thrown as part of invoking toString on the object. if (v8_str.IsEmpty()) return StringImpl::empty(); return v8StringToWebCoreString(v8_str, false); } } AtomicString v8StringToAtomicWebCoreString(v8::Handle<v8::String> v8_str) { String str = v8StringToWebCoreString(v8_str, true); return AtomicString(str); } AtomicString v8ValueToAtomicWebCoreString(v8::Handle<v8::Value> v8_str) { String str = v8ValueToWebCoreString(v8_str); return AtomicString(str); } v8::Handle<v8::String> v8String(const String& str) { if (!str.length()) return v8::String::Empty(); return v8::String::NewExternal(new WebCoreStringResource(str)); } v8::Local<v8::String> v8ExternalString(const String& str) { if (!str.length()) return v8::String::Empty(); return v8::String::NewExternal(new WebCoreStringResource(str)); } } // namespace WebCore <|endoftext|>
<commit_before>/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ #include "CustomXmlWriter.h" #include "../../Common/DocxFormat/Source/DocxFormat/CustomXml.h" #include "../../ASCOfficePPTXFile/ASCOfficeDrawingConverter.h" namespace Writers { CustomXmlWriter::CustomXmlWriter(std::wstring sDir, NSBinPptxRW::CDrawingConverter* pDrawingConverter) : m_sDir(sDir), m_pDrawingConverter(pDrawingConverter) { m_nCount = 0; } void CustomXmlWriter::WriteCustom(const std::wstring& sCustomXmlPropertiesContent, const std::wstring& sCustomXmlContent, bool bGlossaryMode) { m_nCount++; std::wstring sCustomXmlDir = m_sDir + FILE_SEPARATOR_STR; sCustomXmlDir += OOX::FileTypes::CustomXmlProps.DefaultDirectory().GetPath(); std::wstring sCustomXmlRelsDir = sCustomXmlDir + FILE_SEPARATOR_STR + L"_rels"; std::wstring sCustomXMLPropsFilename = OOX::FileTypes::CustomXmlProps.DefaultFileName().GetBasename(); sCustomXMLPropsFilename += std::to_wstring(m_nCount) + OOX::FileTypes::CustomXmlProps.DefaultFileName().GetExtention(); NSFile::CFileBinary::SaveToFile(sCustomXmlDir + FILE_SEPARATOR_STR + sCustomXMLPropsFilename, sCustomXmlPropertiesContent); std::wstring sCustomXmlFilename; sCustomXmlFilename = OOX::FileTypes::CustomXml.DefaultFileName().GetBasename() + std::to_wstring(m_nCount); sCustomXmlFilename += OOX::FileTypes::CustomXml.DefaultFileName().GetExtention(); NSFile::CFileBinary::SaveToFile(sCustomXmlDir + FILE_SEPARATOR_STR + sCustomXmlFilename, sCustomXmlContent); m_pDrawingConverter->SetDstContentRels(); unsigned int lId; m_pDrawingConverter->WriteRels(OOX::FileTypes::CustomXmlProps.RelationType(), sCustomXMLPropsFilename, L"", &lId); m_pDrawingConverter->SaveDstContentRels(sCustomXmlRelsDir + FILE_SEPARATOR_STR + sCustomXmlFilename + L".rels"); arItems.push_back(std::make_pair(sCustomXmlFilename, bGlossaryMode)); } void CustomXmlWriter::WriteCustomSettings(const std::wstring& sUrl, const std::wstring& sXml, bool bGlossaryMode) { m_nCount++; OOX::CCustomXMLProps oCustomXMLProps(NULL); OOX::CCustomXMLProps::CShemaRef* pShemaRef = new OOX::CCustomXMLProps::CShemaRef(); pShemaRef->m_sUri = sUrl; //todo guid oCustomXMLProps.m_oItemID.FromString(L"{5D0AEA6B-E499-4EEF-98A3-AFBB261C493E}"); oCustomXMLProps.m_oShemaRefs.Init(); oCustomXMLProps.m_oShemaRefs->m_arrItems.push_back(pShemaRef); std::wstring sCustomXmlPropsDir = m_sDir + FILE_SEPARATOR_STR; sCustomXmlPropsDir += OOX::FileTypes::CustomXmlProps.DefaultDirectory().GetPath(); NSDirectory::CreateDirectories(sCustomXmlPropsDir); std::wstring sCustomXMLPropsFilename = OOX::FileTypes::CustomXmlProps.DefaultFileName().GetBasename(); sCustomXMLPropsFilename += std::to_wstring(m_nCount) + OOX::FileTypes::CustomXmlProps.DefaultFileName().GetExtention(); oCustomXMLProps.write(OOX::CPath(sCustomXmlPropsDir + FILE_SEPARATOR_STR + sCustomXMLPropsFilename), OOX::CPath(sCustomXmlPropsDir), *m_pDrawingConverter->GetContentTypes()); std::wstring sCustomXmlFilename; sCustomXmlFilename = OOX::FileTypes::CustomXml.DefaultFileName().GetBasename() + std::to_wstring(m_nCount); sCustomXmlFilename += OOX::FileTypes::CustomXml.DefaultFileName().GetExtention(); std::wstring sCustomXmlDir = m_sDir + FILE_SEPARATOR_STR + OOX::FileTypes::CustomXml.DefaultDirectory().GetPath(); std::wstring sCustomXmlRelsDir = sCustomXmlDir + FILE_SEPARATOR_STR + L"_rels"; NSDirectory::CreateDirectories(sCustomXmlRelsDir); m_pDrawingConverter->SetDstContentRels(); unsigned int lId; m_pDrawingConverter->WriteRels(OOX::FileTypes::CustomXmlProps.RelationType(), sCustomXMLPropsFilename, L"", &lId); m_pDrawingConverter->SaveDstContentRels(sCustomXmlRelsDir + FILE_SEPARATOR_STR + sCustomXmlFilename + L".rels"); NSFile::CFileBinary::SaveToFile(sCustomXmlDir + FILE_SEPARATOR_STR + sCustomXmlFilename, sXml); arItems.push_back(std::make_pair(sCustomXmlFilename, bGlossaryMode)); } } <commit_msg>[x2t] Fix bug 49613; Write CustomXml in ContentTypes.xml<commit_after>/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ #include "CustomXmlWriter.h" #include "../../Common/DocxFormat/Source/DocxFormat/CustomXml.h" #include "../../ASCOfficePPTXFile/ASCOfficeDrawingConverter.h" namespace Writers { CustomXmlWriter::CustomXmlWriter(std::wstring sDir, NSBinPptxRW::CDrawingConverter* pDrawingConverter) : m_sDir(sDir), m_pDrawingConverter(pDrawingConverter) { m_nCount = 0; } void CustomXmlWriter::WriteCustom(const std::wstring& sCustomXmlPropertiesContent, const std::wstring& sCustomXmlContent, bool bGlossaryMode) { m_nCount++; std::wstring sCustomXmlDir = m_sDir + FILE_SEPARATOR_STR; sCustomXmlDir += OOX::FileTypes::CustomXmlProps.DefaultDirectory().GetPath(); std::wstring sCustomXmlRelsDir = sCustomXmlDir + FILE_SEPARATOR_STR + L"_rels"; std::wstring sCustomXMLPropsFilename = OOX::FileTypes::CustomXmlProps.DefaultFileName().GetBasename(); sCustomXMLPropsFilename += std::to_wstring(m_nCount) + OOX::FileTypes::CustomXmlProps.DefaultFileName().GetExtention(); NSFile::CFileBinary::SaveToFile(sCustomXmlDir + FILE_SEPARATOR_STR + sCustomXMLPropsFilename, sCustomXmlPropertiesContent); OOX::CContentTypes& oContentTypes = *m_pDrawingConverter->GetContentTypes(); oContentTypes.Registration( OOX::FileTypes::CustomXmlProps.OverrideType(), OOX::FileTypes::CustomXmlProps.DefaultDirectory(), sCustomXMLPropsFilename ); std::wstring sCustomXmlFilename; sCustomXmlFilename = OOX::FileTypes::CustomXml.DefaultFileName().GetBasename() + std::to_wstring(m_nCount); sCustomXmlFilename += OOX::FileTypes::CustomXml.DefaultFileName().GetExtention(); NSFile::CFileBinary::SaveToFile(sCustomXmlDir + FILE_SEPARATOR_STR + sCustomXmlFilename, sCustomXmlContent); m_pDrawingConverter->SetDstContentRels(); unsigned int lId; m_pDrawingConverter->WriteRels(OOX::FileTypes::CustomXmlProps.RelationType(), sCustomXMLPropsFilename, L"", &lId); m_pDrawingConverter->SaveDstContentRels(sCustomXmlRelsDir + FILE_SEPARATOR_STR + sCustomXmlFilename + L".rels"); arItems.push_back(std::make_pair(sCustomXmlFilename, bGlossaryMode)); } void CustomXmlWriter::WriteCustomSettings(const std::wstring& sUrl, const std::wstring& sXml, bool bGlossaryMode) { m_nCount++; OOX::CCustomXMLProps oCustomXMLProps(NULL); OOX::CCustomXMLProps::CShemaRef* pShemaRef = new OOX::CCustomXMLProps::CShemaRef(); pShemaRef->m_sUri = sUrl; //todo guid oCustomXMLProps.m_oItemID.FromString(L"{5D0AEA6B-E499-4EEF-98A3-AFBB261C493E}"); oCustomXMLProps.m_oShemaRefs.Init(); oCustomXMLProps.m_oShemaRefs->m_arrItems.push_back(pShemaRef); std::wstring sCustomXmlPropsDir = m_sDir + FILE_SEPARATOR_STR; sCustomXmlPropsDir += OOX::FileTypes::CustomXmlProps.DefaultDirectory().GetPath(); NSDirectory::CreateDirectories(sCustomXmlPropsDir); std::wstring sCustomXMLPropsFilename = OOX::FileTypes::CustomXmlProps.DefaultFileName().GetBasename(); sCustomXMLPropsFilename += std::to_wstring(m_nCount) + OOX::FileTypes::CustomXmlProps.DefaultFileName().GetExtention(); oCustomXMLProps.write(OOX::CPath(sCustomXmlPropsDir + FILE_SEPARATOR_STR + sCustomXMLPropsFilename), OOX::CPath(sCustomXmlPropsDir), *m_pDrawingConverter->GetContentTypes()); std::wstring sCustomXmlFilename; sCustomXmlFilename = OOX::FileTypes::CustomXml.DefaultFileName().GetBasename() + std::to_wstring(m_nCount); sCustomXmlFilename += OOX::FileTypes::CustomXml.DefaultFileName().GetExtention(); std::wstring sCustomXmlDir = m_sDir + FILE_SEPARATOR_STR + OOX::FileTypes::CustomXml.DefaultDirectory().GetPath(); std::wstring sCustomXmlRelsDir = sCustomXmlDir + FILE_SEPARATOR_STR + L"_rels"; NSDirectory::CreateDirectories(sCustomXmlRelsDir); m_pDrawingConverter->SetDstContentRels(); unsigned int lId; m_pDrawingConverter->WriteRels(OOX::FileTypes::CustomXmlProps.RelationType(), sCustomXMLPropsFilename, L"", &lId); m_pDrawingConverter->SaveDstContentRels(sCustomXmlRelsDir + FILE_SEPARATOR_STR + sCustomXmlFilename + L".rels"); NSFile::CFileBinary::SaveToFile(sCustomXmlDir + FILE_SEPARATOR_STR + sCustomXmlFilename, sXml); arItems.push_back(std::make_pair(sCustomXmlFilename, bGlossaryMode)); } } <|endoftext|>
<commit_before>/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2011 Steven Lovegrove, Richard Newcombe * * 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 <pangolin/platform.h> #include <iostream> #include <sstream> #include <string> #include <map> #include <mutex> #include <cstdlib> #include <memory> #include <pangolin/gl/gl.h> #include <pangolin/gl/gldraw.h> #include <pangolin/factory/factory_registry.h> #include <pangolin/display/display.h> #include <pangolin/display/process.h> #include <pangolin/console/ConsoleView.h> #include <pangolin/utils/simple_math.h> #include <pangolin/utils/timer.h> #include <pangolin/utils/type_convert.h> #include <pangolin/image/image_io.h> #include <pangolin/var/var.h> #include "pangolin_gl.h" extern const unsigned char AnonymousPro_ttf[]; namespace pangolin { typedef std::map<std::string,std::shared_ptr<PangolinGl> > ContextMap; // Map of active contexts ContextMap contexts; std::recursive_mutex contexts_mutex; // Context active for current thread __thread PangolinGl* context = 0; void SetCurrentContext(PangolinGl* newcontext) { context = newcontext; } PangolinGl* GetCurrentContext() { return context; } PangolinGl *FindContext(const std::string& name) { contexts_mutex.lock(); ContextMap::iterator ic = contexts.find(name); PangolinGl* context = (ic == contexts.end()) ? 0 : ic->second.get(); contexts_mutex.unlock(); return context; } WindowInterface& CreateWindowAndBind(std::string window_title, int w, int h, const Params& params) { std::unique_lock<std::recursive_mutex> l(contexts_mutex); pangolin::Uri win_uri; if(const char* extra_params = std::getenv("PANGOLIN_WINDOW_URI")) { // Take any defaults from the environment win_uri = pangolin::ParseUri(extra_params); }else{ // Otherwise revert to 'default' scheme. win_uri.scheme = "default"; } // Override with anything the program specified for(const auto& param : params.params) { if(param.first != "scheme") win_uri.params.push_back(param); } // Special params that shouldn't get passed to window factory win_uri.scheme = win_uri.Get("scheme", win_uri.scheme); const std::string default_font = win_uri.Get<std::string>("default_font",""); const int default_font_size = win_uri.Get("default_font_size", 18); win_uri.Remove("scheme"); win_uri.Remove("default_font"); win_uri.Remove("default_font_size"); // Additional arguments we will send to factory win_uri.Set("w", w); win_uri.Set("h", h); win_uri.Set("window_title", window_title); auto context = std::make_shared<PangolinGl>(); context->window = ConstructWindow(win_uri); assert(context->window); RegisterNewContext(window_title, context); context->window->CloseSignal.connect( [](){ pangolin::Quit(); }); context->window->ResizeSignal.connect( [](WindowResizeEvent event){ process::Resize(event.width, event.height); }); context->window->KeyboardSignal.connect( [](KeyboardEvent event) { process::Keyboard(event.key, event.x, event.y, event.pressed, event.key_modifiers); }); context->window->MouseSignal.connect( [](MouseEvent event){ process::Mouse(event.button, event.pressed, event.x, event.y, event.key_modifiers); }); context->window->MouseMotionSignal.connect( [](MouseMotionEvent event){ process::MouseMotion(event.x, event.y, event.key_modifiers); }); context->window->PassiveMouseMotionSignal.connect( [](MouseMotionEvent event){ process::PassiveMouseMotion(event.x, event.y, event.key_modifiers); }); context->window->SpecialInputSignal.connect( [](SpecialInputEvent event){ process::SpecialInput(event.inType, event.x, event.y, event.p[0], event.p[1], event.p[2], event.p[3], event.key_modifiers); }); // If there is a special font request if( !default_font.empty() ) { const std::string font_filename = PathExpand(default_font); context->font = std::make_shared<GlFont>(font_filename, default_font_size); }else{ context->font = std::make_shared<GlFont>(AnonymousPro_ttf, default_font_size); } context->MakeCurrent(); glewInit(); // And finally process pending window events (such as resize) now that we've setup our callbacks. context->window->ProcessEvents(); return *context->window; } // Assumption: unique lock is held on contexts_mutex for multi-threaded operation void RegisterNewContext(const std::string& name, std::shared_ptr<PangolinGl> newcontext) { // Set defaults newcontext->base.left = 0.0; newcontext->base.bottom = 0.0; newcontext->base.top = 1.0; newcontext->base.right = 1.0; newcontext->base.aspect = 0; newcontext->base.handler = &StaticHandler; // Create and add if( contexts.find(name) != contexts.end() ) { throw std::runtime_error("Context already exists."); } contexts[name] = newcontext; // Process the following as if this context is now current. PangolinGl *oldContext = context; context = newcontext.get(); // Default key bindings can be overridden RegisterKeyPressCallback(PANGO_KEY_ESCAPE, Quit ); RegisterKeyPressCallback('\t', [](){ShowFullscreen(TrueFalseToggle::Toggle);} ); RegisterKeyPressCallback('`', [](){ShowConsole(TrueFalseToggle::Toggle);} ); context = oldContext; } WindowInterface* GetBoundWindow() { return context->window.get(); } void DestroyWindow(const std::string& name) { contexts_mutex.lock(); ContextMap::iterator ic = contexts.find(name); PangolinGl *context_to_destroy = (ic == contexts.end()) ? 0 : ic->second.get(); if (context_to_destroy == context) { context = nullptr; } size_t erased = contexts.erase(name); if(erased == 0) { pango_print_warn("Context '%s' doesn't exist for deletion.\n", name.c_str()); } contexts_mutex.unlock(); } void BindToContext(std::string name) { std::unique_lock<std::recursive_mutex> l(contexts_mutex); // N.B. context is modified prior to invoking MakeCurrent so that // state management callbacks (such as Resize()) can be correctly // processed. PangolinGl *context_to_bind = FindContext(name); if( !context_to_bind ) { std::shared_ptr<PangolinGl> newcontext(new PangolinGl()); RegisterNewContext(name, newcontext); }else{ context_to_bind->MakeCurrent(); } } void Quit() { context->quit = true; } void QuitAll() { for(auto nc : contexts) { nc.second->quit = true; } } bool ShouldQuit() { return !context || context->quit; } void ShowFullscreen(TrueFalseToggle on_off) { if(context && context->window) context->window->ShowFullscreen(on_off); } void FinishFrame() { if(context) context->FinishFrame(); } View& DisplayBase() { return context->base; } View& CreateDisplay() { int iguid = rand(); std::stringstream ssguid; ssguid << iguid; return Display(ssguid.str()); } void ShowConsole(TrueFalseToggle on_off) { if( !context->console_view) { Uri interpreter_uri = ParseUri("python://"); try { // Instantiate interpreter std::shared_ptr<InterpreterInterface> interpreter = FactoryRegistry::I()->Construct<InterpreterInterface>(interpreter_uri); assert(interpreter); // Create console and let the pangolin context take ownership context->console_view = std::make_unique<ConsoleView>(interpreter); context->console_view->zorder = std::numeric_limits<int>::max(); DisplayBase().AddDisplay(*context->console_view); context->console_view->SetFocus(); } catch (std::exception&) { } }else{ context->console_view->Show( to_bool(on_off, context->console_view->IsShown()) ); if(context->console_view->IsShown()) { context->console_view->SetFocus(); } } } View& Display(const std::string& name) { // Get / Create View ViewMap::iterator vi = context->named_managed_views.find(name); if( vi != context->named_managed_views.end() ) { return *(vi->second); }else{ View * v = new View(); context->named_managed_views[name] = v; v->handler = &StaticHandler; context->base.views.push_back(v); return *v; } } void RegisterKeyPressCallback(int key, std::function<void(int)> func) { context->keypress_hooks[key] = func; } void RegisterKeyPressCallback(int key, std::function<void(void)> func) { context->keypress_hooks[key] = [=](int){func();}; } void SaveWindowOnRender(const std::string& filename, const Viewport& v) { context->screen_capture.push(std::pair<std::string,Viewport>(filename, v) ); } void SaveWindowNow(const std::string& filename_hint, const Viewport& v) { const Viewport to_save = v.area() ? v.Intersect(DisplayBase().v) : DisplayBase().v; std::string filename = filename_hint; if(FileLowercaseExtention(filename) == "") filename += ".png"; try { glFlush(); TypedImage buffer = ReadFramebuffer(to_save, "RGBA32"); SaveImage(buffer, filename, false); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } } } <commit_msg>[display] fix bad QuitAll() bug that would presumably prevent it from working at all.<commit_after>/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2011 Steven Lovegrove, Richard Newcombe * * 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 <pangolin/platform.h> #include <iostream> #include <sstream> #include <string> #include <map> #include <mutex> #include <cstdlib> #include <memory> #include <pangolin/gl/gl.h> #include <pangolin/gl/gldraw.h> #include <pangolin/factory/factory_registry.h> #include <pangolin/display/display.h> #include <pangolin/display/process.h> #include <pangolin/console/ConsoleView.h> #include <pangolin/utils/simple_math.h> #include <pangolin/utils/timer.h> #include <pangolin/utils/type_convert.h> #include <pangolin/image/image_io.h> #include <pangolin/var/var.h> #include "pangolin_gl.h" extern const unsigned char AnonymousPro_ttf[]; namespace pangolin { typedef std::map<std::string,std::shared_ptr<PangolinGl> > ContextMap; // Map of active contexts ContextMap contexts; std::recursive_mutex contexts_mutex; // Context active for current thread __thread PangolinGl* context = 0; void SetCurrentContext(PangolinGl* newcontext) { context = newcontext; } PangolinGl* GetCurrentContext() { return context; } PangolinGl *FindContext(const std::string& name) { contexts_mutex.lock(); ContextMap::iterator ic = contexts.find(name); PangolinGl* context = (ic == contexts.end()) ? 0 : ic->second.get(); contexts_mutex.unlock(); return context; } WindowInterface& CreateWindowAndBind(std::string window_title, int w, int h, const Params& params) { std::unique_lock<std::recursive_mutex> l(contexts_mutex); pangolin::Uri win_uri; if(const char* extra_params = std::getenv("PANGOLIN_WINDOW_URI")) { // Take any defaults from the environment win_uri = pangolin::ParseUri(extra_params); }else{ // Otherwise revert to 'default' scheme. win_uri.scheme = "default"; } // Override with anything the program specified for(const auto& param : params.params) { if(param.first != "scheme") win_uri.params.push_back(param); } // Special params that shouldn't get passed to window factory win_uri.scheme = win_uri.Get("scheme", win_uri.scheme); const std::string default_font = win_uri.Get<std::string>("default_font",""); const int default_font_size = win_uri.Get("default_font_size", 18); win_uri.Remove("scheme"); win_uri.Remove("default_font"); win_uri.Remove("default_font_size"); // Additional arguments we will send to factory win_uri.Set("w", w); win_uri.Set("h", h); win_uri.Set("window_title", window_title); auto context = std::make_shared<PangolinGl>(); context->window = ConstructWindow(win_uri); assert(context->window); RegisterNewContext(window_title, context); context->window->CloseSignal.connect( [](){ pangolin::Quit(); }); context->window->ResizeSignal.connect( [](WindowResizeEvent event){ process::Resize(event.width, event.height); }); context->window->KeyboardSignal.connect( [](KeyboardEvent event) { process::Keyboard(event.key, event.x, event.y, event.pressed, event.key_modifiers); }); context->window->MouseSignal.connect( [](MouseEvent event){ process::Mouse(event.button, event.pressed, event.x, event.y, event.key_modifiers); }); context->window->MouseMotionSignal.connect( [](MouseMotionEvent event){ process::MouseMotion(event.x, event.y, event.key_modifiers); }); context->window->PassiveMouseMotionSignal.connect( [](MouseMotionEvent event){ process::PassiveMouseMotion(event.x, event.y, event.key_modifiers); }); context->window->SpecialInputSignal.connect( [](SpecialInputEvent event){ process::SpecialInput(event.inType, event.x, event.y, event.p[0], event.p[1], event.p[2], event.p[3], event.key_modifiers); }); // If there is a special font request if( !default_font.empty() ) { const std::string font_filename = PathExpand(default_font); context->font = std::make_shared<GlFont>(font_filename, default_font_size); }else{ context->font = std::make_shared<GlFont>(AnonymousPro_ttf, default_font_size); } context->MakeCurrent(); glewInit(); // And finally process pending window events (such as resize) now that we've setup our callbacks. context->window->ProcessEvents(); return *context->window; } // Assumption: unique lock is held on contexts_mutex for multi-threaded operation void RegisterNewContext(const std::string& name, std::shared_ptr<PangolinGl> newcontext) { // Set defaults newcontext->base.left = 0.0; newcontext->base.bottom = 0.0; newcontext->base.top = 1.0; newcontext->base.right = 1.0; newcontext->base.aspect = 0; newcontext->base.handler = &StaticHandler; // Create and add if( contexts.find(name) != contexts.end() ) { throw std::runtime_error("Context already exists."); } contexts[name] = newcontext; // Process the following as if this context is now current. PangolinGl *oldContext = context; context = newcontext.get(); // Default key bindings can be overridden RegisterKeyPressCallback(PANGO_KEY_ESCAPE, Quit ); RegisterKeyPressCallback('\t', [](){ShowFullscreen(TrueFalseToggle::Toggle);} ); RegisterKeyPressCallback('`', [](){ShowConsole(TrueFalseToggle::Toggle);} ); context = oldContext; } WindowInterface* GetBoundWindow() { return context->window.get(); } void DestroyWindow(const std::string& name) { contexts_mutex.lock(); ContextMap::iterator ic = contexts.find(name); PangolinGl *context_to_destroy = (ic == contexts.end()) ? 0 : ic->second.get(); if (context_to_destroy == context) { context = nullptr; } size_t erased = contexts.erase(name); if(erased == 0) { pango_print_warn("Context '%s' doesn't exist for deletion.\n", name.c_str()); } contexts_mutex.unlock(); } void BindToContext(std::string name) { std::unique_lock<std::recursive_mutex> l(contexts_mutex); // N.B. context is modified prior to invoking MakeCurrent so that // state management callbacks (such as Resize()) can be correctly // processed. PangolinGl *context_to_bind = FindContext(name); if( !context_to_bind ) { std::shared_ptr<PangolinGl> newcontext(new PangolinGl()); RegisterNewContext(name, newcontext); }else{ context_to_bind->MakeCurrent(); } } void Quit() { context->quit = true; } void QuitAll() { for(auto& nc : contexts) { nc.second->quit = true; } } bool ShouldQuit() { return !context || context->quit; } void ShowFullscreen(TrueFalseToggle on_off) { if(context && context->window) context->window->ShowFullscreen(on_off); } void FinishFrame() { if(context) context->FinishFrame(); } View& DisplayBase() { return context->base; } View& CreateDisplay() { int iguid = rand(); std::stringstream ssguid; ssguid << iguid; return Display(ssguid.str()); } void ShowConsole(TrueFalseToggle on_off) { if( !context->console_view) { Uri interpreter_uri = ParseUri("python://"); try { // Instantiate interpreter std::shared_ptr<InterpreterInterface> interpreter = FactoryRegistry::I()->Construct<InterpreterInterface>(interpreter_uri); assert(interpreter); // Create console and let the pangolin context take ownership context->console_view = std::make_unique<ConsoleView>(interpreter); context->console_view->zorder = std::numeric_limits<int>::max(); DisplayBase().AddDisplay(*context->console_view); context->console_view->SetFocus(); } catch (std::exception&) { } }else{ context->console_view->Show( to_bool(on_off, context->console_view->IsShown()) ); if(context->console_view->IsShown()) { context->console_view->SetFocus(); } } } View& Display(const std::string& name) { // Get / Create View ViewMap::iterator vi = context->named_managed_views.find(name); if( vi != context->named_managed_views.end() ) { return *(vi->second); }else{ View * v = new View(); context->named_managed_views[name] = v; v->handler = &StaticHandler; context->base.views.push_back(v); return *v; } } void RegisterKeyPressCallback(int key, std::function<void(int)> func) { context->keypress_hooks[key] = func; } void RegisterKeyPressCallback(int key, std::function<void(void)> func) { context->keypress_hooks[key] = [=](int){func();}; } void SaveWindowOnRender(const std::string& filename, const Viewport& v) { context->screen_capture.push(std::pair<std::string,Viewport>(filename, v) ); } void SaveWindowNow(const std::string& filename_hint, const Viewport& v) { const Viewport to_save = v.area() ? v.Intersect(DisplayBase().v) : DisplayBase().v; std::string filename = filename_hint; if(FileLowercaseExtention(filename) == "") filename += ".png"; try { glFlush(); TypedImage buffer = ReadFramebuffer(to_save, "RGBA32"); SaveImage(buffer, filename, false); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } } } <|endoftext|>
<commit_before>#include "string_util.h" #include <cmath> #include <cstdarg> #include <array> #include <memory> #include <sstream> #include "arraysize.h" namespace benchmark { namespace { // kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta. const char kBigSIUnits[] = "kMGTPEZY"; // Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi. const char kBigIECUnits[] = "KMGTPEZY"; // milli, micro, nano, pico, femto, atto, zepto, yocto. const char kSmallSIUnits[] = "munpfazy"; // We require that all three arrays have the same size. static_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits), "SI and IEC unit arrays must be the same size"); static_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits), "Small SI and Big SI unit arrays must be the same size"); static const int64_t kUnitsSize = arraysize(kBigSIUnits); } // end anonymous namespace void ToExponentAndMantissa(double val, double thresh, int precision, double one_k, std::string* mantissa, int64_t* exponent) { std::stringstream mantissa_stream; if (val < 0) { mantissa_stream << "-"; val = -val; } // Adjust threshold so that it never excludes things which can't be rendered // in 'precision' digits. const double adjusted_threshold = std::max(thresh, 1.0 / std::pow(10.0, precision)); const double big_threshold = adjusted_threshold * one_k; const double small_threshold = adjusted_threshold; if (val > big_threshold) { // Positive powers double scaled = val; for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) { scaled /= one_k; if (scaled <= big_threshold) { mantissa_stream << scaled; *exponent = i + 1; *mantissa = mantissa_stream.str(); return; } } mantissa_stream << val; *exponent = 0; } else if (val < small_threshold) { // Negative powers double scaled = val; for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) { scaled *= one_k; if (scaled >= small_threshold) { mantissa_stream << scaled; *exponent = -static_cast<int64_t>(i + 1); *mantissa = mantissa_stream.str(); return; } } mantissa_stream << val; *exponent = 0; } else { mantissa_stream << val; *exponent = 0; } *mantissa = mantissa_stream.str(); } std::string ExponentToPrefix(int64_t exponent, bool iec) { if (exponent == 0) return ""; const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1); if (index >= kUnitsSize) return ""; const char* array = (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits); if (iec) return array[index] + std::string("i"); else return std::string(1, array[index]); } std::string ToBinaryStringFullySpecified(double value, double threshold, int precision) { std::string mantissa; int64_t exponent; ToExponentAndMantissa(value, threshold, precision, 1024.0, &mantissa, &exponent); return mantissa + ExponentToPrefix(exponent, false); } void AppendHumanReadable(int n, std::string* str) { std::stringstream ss; // Round down to the nearest SI prefix. ss << "/" << ToBinaryStringFullySpecified(n, 1.0, 0); *str += ss.str(); } std::string HumanReadableNumber(double n) { // 1.1 means that figures up to 1.1k should be shown with the next unit down; // this softens edge effects. // 1 means that we should show one decimal place of precision. return ToBinaryStringFullySpecified(n, 1.1, 1); } std::string StringPrintFImp(const char *msg, va_list args) { // we might need a second shot at this, so pre-emptivly make a copy va_list args_cp; va_copy(args_cp, args); // TODO(ericwf): use std::array for first attempt to avoid one memory // allocation guess what the size might be std::array<char, 256> local_buff; std::size_t size = local_buff.size(); auto ret = std::vsnprintf(local_buff.data(), size, msg, args_cp); va_end(args_cp); // handle empty expansion if (ret == 0) return std::string{}; if (static_cast<std::size_t>(ret) < size) return std::string(local_buff.data()); // we did not provide a long enough buffer on our first attempt. // add 1 to size to account for null-byte in size cast to prevent overflow size = static_cast<std::size_t>(ret) + 1; auto buff_ptr = std::unique_ptr<char[]>(new char[size]); ret = std::vsnprintf(buff_ptr.get(), size, msg, args); return std::string(buff_ptr.get()); } std::string StringPrintF(const char* format, ...) { va_list args; va_start(args, format); std::string tmp = StringPrintFImp(format, args); va_end(args); return tmp; } void ReplaceAll(std::string* str, const std::string& from, const std::string& to) { std::size_t start = 0; while((start = str->find(from, start)) != std::string::npos) { str->replace(start, from.length(), to); start += to.length(); } } } // end namespace benchmark <commit_msg>Changed "std::vsnprintf" to "vsnprintf" to be able to build with the android-ndk.<commit_after>#include "string_util.h" #include <cmath> #include <cstdarg> #include <array> #include <memory> #include <sstream> #include <stdio.h> #include "arraysize.h" namespace benchmark { namespace { // kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta. const char kBigSIUnits[] = "kMGTPEZY"; // Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi. const char kBigIECUnits[] = "KMGTPEZY"; // milli, micro, nano, pico, femto, atto, zepto, yocto. const char kSmallSIUnits[] = "munpfazy"; // We require that all three arrays have the same size. static_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits), "SI and IEC unit arrays must be the same size"); static_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits), "Small SI and Big SI unit arrays must be the same size"); static const int64_t kUnitsSize = arraysize(kBigSIUnits); } // end anonymous namespace void ToExponentAndMantissa(double val, double thresh, int precision, double one_k, std::string* mantissa, int64_t* exponent) { std::stringstream mantissa_stream; if (val < 0) { mantissa_stream << "-"; val = -val; } // Adjust threshold so that it never excludes things which can't be rendered // in 'precision' digits. const double adjusted_threshold = std::max(thresh, 1.0 / std::pow(10.0, precision)); const double big_threshold = adjusted_threshold * one_k; const double small_threshold = adjusted_threshold; if (val > big_threshold) { // Positive powers double scaled = val; for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) { scaled /= one_k; if (scaled <= big_threshold) { mantissa_stream << scaled; *exponent = i + 1; *mantissa = mantissa_stream.str(); return; } } mantissa_stream << val; *exponent = 0; } else if (val < small_threshold) { // Negative powers double scaled = val; for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) { scaled *= one_k; if (scaled >= small_threshold) { mantissa_stream << scaled; *exponent = -static_cast<int64_t>(i + 1); *mantissa = mantissa_stream.str(); return; } } mantissa_stream << val; *exponent = 0; } else { mantissa_stream << val; *exponent = 0; } *mantissa = mantissa_stream.str(); } std::string ExponentToPrefix(int64_t exponent, bool iec) { if (exponent == 0) return ""; const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1); if (index >= kUnitsSize) return ""; const char* array = (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits); if (iec) return array[index] + std::string("i"); else return std::string(1, array[index]); } std::string ToBinaryStringFullySpecified(double value, double threshold, int precision) { std::string mantissa; int64_t exponent; ToExponentAndMantissa(value, threshold, precision, 1024.0, &mantissa, &exponent); return mantissa + ExponentToPrefix(exponent, false); } void AppendHumanReadable(int n, std::string* str) { std::stringstream ss; // Round down to the nearest SI prefix. ss << "/" << ToBinaryStringFullySpecified(n, 1.0, 0); *str += ss.str(); } std::string HumanReadableNumber(double n) { // 1.1 means that figures up to 1.1k should be shown with the next unit down; // this softens edge effects. // 1 means that we should show one decimal place of precision. return ToBinaryStringFullySpecified(n, 1.1, 1); } std::string StringPrintFImp(const char *msg, va_list args) { // we might need a second shot at this, so pre-emptivly make a copy va_list args_cp; va_copy(args_cp, args); // TODO(ericwf): use std::array for first attempt to avoid one memory // allocation guess what the size might be std::array<char, 256> local_buff; std::size_t size = local_buff.size(); auto ret = vsnprintf(local_buff.data(), size, msg, args_cp); va_end(args_cp); // handle empty expansion if (ret == 0) return std::string{}; if (static_cast<std::size_t>(ret) < size) return std::string(local_buff.data()); // we did not provide a long enough buffer on our first attempt. // add 1 to size to account for null-byte in size cast to prevent overflow size = static_cast<std::size_t>(ret) + 1; auto buff_ptr = std::unique_ptr<char[]>(new char[size]); ret = vsnprintf(buff_ptr.get(), size, msg, args); return std::string(buff_ptr.get()); } std::string StringPrintF(const char* format, ...) { va_list args; va_start(args, format); std::string tmp = StringPrintFImp(format, args); va_end(args); return tmp; } void ReplaceAll(std::string* str, const std::string& from, const std::string& to) { std::size_t start = 0; while((start = str->find(from, start)) != std::string::npos) { str->replace(start, from.length(), to); start += to.length(); } } } // end namespace benchmark <|endoftext|>
<commit_before>#include "file_handler.hpp" #include "elf_file.hpp" FileHandler::FileHandler() {}; bool FileHandler::open(const std::string &filename) { FileUnit *file; /* check file type * TODO: use error codes instead of bool */ file = new ELFFile(filename); if (file->getOpenStatus()) { openFiles.push_back(file); return true; } /* check other file types */ /* unknown file format */ return false; } bool FileHandler::close(FileUnit *file) { return false; } bool FileHandler::save(FileUnit *file) { return file->save(file->getName()); } bool FileHandler::save(FileUnit *file, std::string &newName) { return file->save(newName); } FileHandler::~FileHandler() {} <commit_msg>Add FileHandler destructor<commit_after>#include "file_handler.hpp" #include "elf_file.hpp" FileHandler::FileHandler() {}; bool FileHandler::open(const std::string &filename) { FileUnit *file; /* check file type * TODO: use error codes instead of bool */ file = new ELFFile(filename); if (file->getOpenStatus()) { openFiles.push_back(file); return true; } /* check other file types */ /* unknown file format */ return false; } bool FileHandler::close(FileUnit *file) { return false; } bool FileHandler::save(FileUnit *file) { return file->save(file->getName()); } bool FileHandler::save(FileUnit *file, std::string &newName) { return file->save(newName); } FileHandler::~FileHandler() { while (!openFiles.empty()) { delete openFiles.back(); openFiles.pop_back(); } } <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "frtconnectionpool.h" #include <vespa/vespalib/util/host_name.h> #include <vespa/vespalib/util/size_literals.h> #include <vespa/fnet/frt/supervisor.h> #include <vespa/fnet/transport.h> #include <vespa/fastos/thread.h> #include <vespa/log/log.h> LOG_SETUP(".config.frt.frtconnectionpool"); namespace config { FRTConnectionPool::FRTConnectionKey::FRTConnectionKey(int idx, const vespalib::string& hostname) : _idx(idx), _hostname(hostname) { } int FRTConnectionPool::FRTConnectionKey::operator<(const FRTConnectionPool::FRTConnectionKey& right) const { return _idx < right._idx; } int FRTConnectionPool::FRTConnectionKey::operator==(const FRTConnectionKey& right) const { return _hostname == right._hostname; } FRTConnectionPool::FRTConnectionPool(FNET_Transport & transport, const ServerSpec & spec, const TimingValues & timingValues) : _supervisor(std::make_unique<FRT_Supervisor>(& transport)), _selectIdx(0), _hostname("") { for (size_t i(0); i < spec.numHosts(); i++) { FRTConnectionKey key(i, spec.getHost(i)); _connections[key] = std::make_shared<FRTConnection>(spec.getHost(i), *_supervisor, timingValues); } setHostname(); } FRTConnectionPool::~FRTConnectionPool() { LOG(debug, "Shutting down %lu connections", _connections.size()); syncTransport(); _connections.clear(); syncTransport(); } void FRTConnectionPool::syncTransport() { _supervisor->GetTransport()->sync(); } Connection * FRTConnectionPool::getCurrent() { if (_hostname.compare("") == 0) { return getNextRoundRobin(); } else { return getNextHashBased(); } } FRTConnection * FRTConnectionPool::getNextRoundRobin() { auto ready = getReadySources(); auto suspended = getSuspendedSources(); FRTConnection* nextFRTConnection = nullptr; if ( ! ready.empty()) { unsigned int sel = _selectIdx % (int)ready.size(); LOG_ASSERT(sel < ready.size()); _selectIdx = sel + 1; nextFRTConnection = ready[sel]; } else if ( ! suspended.empty()) { unsigned int sel = _selectIdx % (int)suspended.size(); LOG_ASSERT(sel < suspended.size()); _selectIdx = sel + 1; nextFRTConnection = suspended[sel]; } return nextFRTConnection; } namespace { /** * Implementation of the Java hashCode function for the String class. * * Ensures that the same hostname maps to the same configserver/proxy * for both language implementations. * * @param s the string to compute the hash from * @return the hash value */ int hashCode(const vespalib::string & s) { int hashval = 0; for (int i = 0; i < (int) s.length(); i++) { hashval = 31 * hashval + s[i]; } return hashval; } } FRTConnection * FRTConnectionPool::getNextHashBased() { auto ready = getReadySources(); auto suspended = getSuspendedSources(); FRTConnection* nextFRTConnection = nullptr; if ( ! ready.empty()) { unsigned int sel = std::abs(hashCode(_hostname) % (int)ready.size()); LOG_ASSERT(sel < ready.size()); nextFRTConnection = ready[sel]; } else if ( ! suspended.empty() ){ unsigned int sel = std::abs(hashCode(_hostname) % (int)suspended.size()); LOG_ASSERT(sel < suspended.size()); nextFRTConnection = suspended[sel]; } return nextFRTConnection; } std::vector<FRTConnection *> FRTConnectionPool::getReadySources() const { std::vector<FRTConnection*> readySources; for (const auto & entry : _connections) { FRTConnection* source = entry.second.get(); vespalib::system_time timestamp = vespalib::system_clock::now(); if (source->getSuspendedUntil() < timestamp) { readySources.push_back(source); } } return readySources; } std::vector<FRTConnection *> FRTConnectionPool::getSuspendedSources() const { std::vector<FRTConnection*> suspendedSources; for (const auto & entry : _connections) { FRTConnection* source = entry.second.get(); vespalib::system_time timestamp = vespalib::system_clock::now(); if (source->getSuspendedUntil() >= timestamp) { suspendedSources.push_back(source); } } return suspendedSources; } void FRTConnectionPool::setHostname() { setHostname(vespalib::HostName::get()); } FNET_Scheduler * FRTConnectionPool::getScheduler() { return _supervisor->GetScheduler(); } FRTConnectionPoolWithTransport::FRTConnectionPoolWithTransport(std::unique_ptr<FastOS_ThreadPool> threadPool, std::unique_ptr<FNET_Transport> transport, const ServerSpec & spec, const TimingValues & timingValues) : _threadPool(std::move(threadPool)), _transport(std::move(transport)), _connectionPool(std::make_unique<FRTConnectionPool>(*_transport, spec, timingValues)) { _transport->Start(_threadPool.get()); } FRTConnectionPoolWithTransport::~FRTConnectionPoolWithTransport() { syncTransport(); _transport->ShutDown(true); } } <commit_msg>Avoid signed integer overflow in hashCode() which could trigger undefined behavior.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "frtconnectionpool.h" #include <vespa/vespalib/util/host_name.h> #include <vespa/vespalib/util/size_literals.h> #include <vespa/fnet/frt/supervisor.h> #include <vespa/fnet/transport.h> #include <vespa/fastos/thread.h> #include <vespa/log/log.h> LOG_SETUP(".config.frt.frtconnectionpool"); namespace config { FRTConnectionPool::FRTConnectionKey::FRTConnectionKey(int idx, const vespalib::string& hostname) : _idx(idx), _hostname(hostname) { } int FRTConnectionPool::FRTConnectionKey::operator<(const FRTConnectionPool::FRTConnectionKey& right) const { return _idx < right._idx; } int FRTConnectionPool::FRTConnectionKey::operator==(const FRTConnectionKey& right) const { return _hostname == right._hostname; } FRTConnectionPool::FRTConnectionPool(FNET_Transport & transport, const ServerSpec & spec, const TimingValues & timingValues) : _supervisor(std::make_unique<FRT_Supervisor>(& transport)), _selectIdx(0), _hostname("") { for (size_t i(0); i < spec.numHosts(); i++) { FRTConnectionKey key(i, spec.getHost(i)); _connections[key] = std::make_shared<FRTConnection>(spec.getHost(i), *_supervisor, timingValues); } setHostname(); } FRTConnectionPool::~FRTConnectionPool() { LOG(debug, "Shutting down %lu connections", _connections.size()); syncTransport(); _connections.clear(); syncTransport(); } void FRTConnectionPool::syncTransport() { _supervisor->GetTransport()->sync(); } Connection * FRTConnectionPool::getCurrent() { if (_hostname.compare("") == 0) { return getNextRoundRobin(); } else { return getNextHashBased(); } } FRTConnection * FRTConnectionPool::getNextRoundRobin() { auto ready = getReadySources(); auto suspended = getSuspendedSources(); FRTConnection* nextFRTConnection = nullptr; if ( ! ready.empty()) { unsigned int sel = _selectIdx % (int)ready.size(); LOG_ASSERT(sel < ready.size()); _selectIdx = sel + 1; nextFRTConnection = ready[sel]; } else if ( ! suspended.empty()) { unsigned int sel = _selectIdx % (int)suspended.size(); LOG_ASSERT(sel < suspended.size()); _selectIdx = sel + 1; nextFRTConnection = suspended[sel]; } return nextFRTConnection; } namespace { /** * Implementation of the Java hashCode function for the String class. * * Ensures that the same hostname maps to the same configserver/proxy * for both language implementations. * * @param s the string to compute the hash from * @return the hash value */ int hashCode(const vespalib::string & s) { unsigned int hashval = 0; for (int i = 0; i < (int) s.length(); i++) { hashval = 31 * hashval + s[i]; } return hashval; } } FRTConnection * FRTConnectionPool::getNextHashBased() { auto ready = getReadySources(); auto suspended = getSuspendedSources(); FRTConnection* nextFRTConnection = nullptr; if ( ! ready.empty()) { unsigned int sel = std::abs(hashCode(_hostname) % (int)ready.size()); LOG_ASSERT(sel < ready.size()); nextFRTConnection = ready[sel]; } else if ( ! suspended.empty() ){ unsigned int sel = std::abs(hashCode(_hostname) % (int)suspended.size()); LOG_ASSERT(sel < suspended.size()); nextFRTConnection = suspended[sel]; } return nextFRTConnection; } std::vector<FRTConnection *> FRTConnectionPool::getReadySources() const { std::vector<FRTConnection*> readySources; for (const auto & entry : _connections) { FRTConnection* source = entry.second.get(); vespalib::system_time timestamp = vespalib::system_clock::now(); if (source->getSuspendedUntil() < timestamp) { readySources.push_back(source); } } return readySources; } std::vector<FRTConnection *> FRTConnectionPool::getSuspendedSources() const { std::vector<FRTConnection*> suspendedSources; for (const auto & entry : _connections) { FRTConnection* source = entry.second.get(); vespalib::system_time timestamp = vespalib::system_clock::now(); if (source->getSuspendedUntil() >= timestamp) { suspendedSources.push_back(source); } } return suspendedSources; } void FRTConnectionPool::setHostname() { setHostname(vespalib::HostName::get()); } FNET_Scheduler * FRTConnectionPool::getScheduler() { return _supervisor->GetScheduler(); } FRTConnectionPoolWithTransport::FRTConnectionPoolWithTransport(std::unique_ptr<FastOS_ThreadPool> threadPool, std::unique_ptr<FNET_Transport> transport, const ServerSpec & spec, const TimingValues & timingValues) : _threadPool(std::move(threadPool)), _transport(std::move(transport)), _connectionPool(std::make_unique<FRTConnectionPool>(*_transport, spec, timingValues)) { _transport->Start(_threadPool.get()); } FRTConnectionPoolWithTransport::~FRTConnectionPoolWithTransport() { syncTransport(); _transport->ShutDown(true); } } <|endoftext|>
<commit_before>/* Timbre.cc: Sound timbre handling * * Copyright 2016, 2018 Vincent Damewood * * 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> #include <map> #include <string> #include "Phase.h" #include "SampleRate.h" #include "Timbre.h" using Seirina::Audio::Phase; typedef double (*fpWave)(Phase); static double square(Phase phase) { return phase < 0.5 ? 1.0 : -1.0; } static double sine(Phase phase) { return sin(phase * M_PI * 2); } static double absine(Phase phase) { return fabs(sin((phase+1.0/6.0) * M_PI)) * 2.0 - 1.0; } static double saw(Phase phase) { return fmod(phase + 0.5, 1.0) * 2.0 - 1.0; } static double triangle(Phase phase) { double d = fmod(phase + 0.25, 1.0); return (d <= 0.5 ? d : 1.0 - d) * 4.0 - 1.0; } static std::map<std::string, fpWave> Waveforms { {std::string("sine"), sine}, {std::string("absine"), absine}, {std::string("saw"), saw}, {std::string("square"), square}, {std::string("triangle"), triangle}, }; double phase(double frequency, int sample) { using Seirina::Audio::SampleRate; double CycleLength = SampleRate::Cd/frequency; return std::fmod(sample, CycleLength)/CycleLength; } class Timbre::Pimpl { public: Pimpl(fpWave NewWaveForm) { Waveform = NewWaveForm; } fpWave Waveform; }; Timbre::Timbre(const char* NewWaveFormName) { fpWave NewWaveForm = Waveforms[std::string(NewWaveFormName)]; p = new Pimpl(NewWaveForm); } Timbre::Timbre(const Timbre& src) : p(new Pimpl(src.p->Waveform)) { } Timbre::~Timbre() { //delete p; } Seirina::Audio::Sample Timbre::GetSample(Note note, int sequence) { return Seirina::Audio::Sample( p->Waveform(phase(note.Pitch().Frequency(), sequence))); } <commit_msg>Make Timber use new WaveForm classes<commit_after>/* Timbre.cc: Sound timbre handling * * Copyright 2016, 2018, 2019 Vincent Damewood * * 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> #include <map> #include <string> #include "Phase.h" #include "SampleRate.h" #include "SimpleWaves.h" #include "Timbre.h" using Seirina::Audio::WaveForm; using Seirina::Audio::AbsineWave; using Seirina::Audio::SineWave; using Seirina::Audio::SquareWave; using Seirina::Audio::TriangleWave; using Seirina::Audio::SawtoothWave; static std::map<std::string, WaveForm*> Waveforms { {std::string("sine"), new SineWave()}, {std::string("absine"), new AbsineWave()}, {std::string("saw"), new SawtoothWave()}, {std::string("square"), new SquareWave()}, {std::string("triangle"), new TriangleWave()}, }; double phase(double frequency, int sample) { using Seirina::Audio::SampleRate; double CycleLength = SampleRate::Cd/frequency; return std::fmod(sample, CycleLength)/CycleLength; } class Timbre::Pimpl { public: Pimpl(WaveForm* NewWaveForm) : waveform(NewWaveForm) { } WaveForm* waveform; }; Timbre::Timbre(const char* NewWaveFormName) : p(new Pimpl(Waveforms[std::string(NewWaveFormName)])) { //WaveForm* NewWaveForm = ; //p = ; } Timbre::Timbre(const Timbre& src) : p(new Pimpl(src.p->waveform)) { } Timbre::~Timbre() { //delete p; } Seirina::Audio::Sample Timbre::GetSample(Note note, int sequence) { return Seirina::Audio::Sample( p->waveform->GetSample(phase(note.Pitch().Frequency(), sequence))); } <|endoftext|>
<commit_before>#include <vector> #include <iostream> #include <algorithm> #include <limits> using namespace std; #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include "treehash/boosted-treehash.hh" extern "C" { #include "timers.h" } void fill_random(uint64_t * data, size_t n) { const int rfd = open("/dev/urandom", O_RDONLY); if (-1 == rfd) { const int err = errno; fprintf(stderr, "%s\n", strerror(err)); exit(err); } char * const cdata = (char *)data; for (size_t i = 0; i < n; i += read(rfd, &cdata[i], sizeof(uint64_t)*n-i)); (void)close(rfd); } uint64_t * alloc_random(size_t n) { uint64_t * ans = (uint64_t *)malloc(sizeof(uint64_t) * n); if (!ans) { fprintf(stderr, "Failed allocation of %zd words\n", n); exit(1); } fill_random(ans, n); return ans; } uint64_t sum = 0; template<size_t N> ticks bench(const void * r, const uint64_t * data, const size_t i) { const ticks start = startRDTSC(); sum += boosted_treehash<N>(r, data, i); const ticks finish = startRDTSC(); return finish-start; } int main() { size_t max_len = 2048; const uint64_t * const data = alloc_random(max_len); const void * const r64 = alloc_random(128); size_t iters = 10000; const size_t max_depth = 9; vector<vector<ticks> > cycles(max_depth, vector<ticks>(iters)); size_t samples = 100; cout << "# length percentile optimal-treeboost " << endl; for (size_t i = 1; i < max_len; i = 1 + 1.001*i) { for (size_t j = 0; j < iters; ++j) { cycles[0][j] = bench<1>(r64, data, i); cycles[1][j] = bench<2>(r64, data, i); cycles[2][j] = bench<3>(r64, data, i); cycles[3][j] = bench<4>(r64, data, i); cycles[4][j] = bench<5>(r64, data, i); cycles[5][j] = bench<6>(r64, data, i); cycles[6][j] = bench<7>(r64, data, i); cycles[7][j] = bench<8>(r64, data, i); cycles[8][j] = bench<9>(r64, data, i); } for (size_t j = 0; j < max_depth; ++j) { sort(cycles[j].begin(), cycles[j].end(), std::greater<ticks>()); } for (size_t j = 0; j <= samples; ++j) { size_t loc = (iters * j)/samples; if (loc >= iters) loc = iters-1; ticks min_val = numeric_limits<ticks>::max(); int min_idx = -1; for (size_t k = 0; k < max_depth; ++k) { if (cycles[k][loc] < min_val) { min_val = cycles[k][loc]; min_idx = k; } } /* for (size_t k = 0; k < max_depth; ++k) { min_val = min(min_val, cycles[k][loc]); } */ cout << i << " " << j << " " << min_idx << endl; } cout << endl; } cerr << "# ignore " << sum << endl; }; <commit_msg>Remove unused code in boosted tree params<commit_after>#include <vector> #include <iostream> #include <algorithm> #include <limits> using namespace std; #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include "treehash/boosted-treehash.hh" extern "C" { #include "timers.h" } void fill_random(uint64_t * data, size_t n) { const int rfd = open("/dev/urandom", O_RDONLY); if (-1 == rfd) { const int err = errno; fprintf(stderr, "%s\n", strerror(err)); exit(err); } char * const cdata = (char *)data; for (size_t i = 0; i < n; i += read(rfd, &cdata[i], sizeof(uint64_t)*n-i)); (void)close(rfd); } uint64_t * alloc_random(size_t n) { uint64_t * ans = (uint64_t *)malloc(sizeof(uint64_t) * n); if (!ans) { fprintf(stderr, "Failed allocation of %zd words\n", n); exit(1); } fill_random(ans, n); return ans; } uint64_t sum = 0; template<size_t N> ticks bench(const void * r, const uint64_t * data, const size_t i) { const ticks start = startRDTSC(); sum += boosted_treehash<N>(r, data, i); const ticks finish = startRDTSC(); return finish-start; } int main() { size_t max_len = 2048; const uint64_t * const data = alloc_random(max_len); const void * const r64 = alloc_random(128); size_t iters = 10000; const size_t max_depth = 9; vector<vector<ticks> > cycles(max_depth, vector<ticks>(iters)); size_t samples = 100; cout << "# length percentile optimal-treeboost " << endl; for (size_t i = 1; i < max_len; i = 1 + 1.001*i) { for (size_t j = 0; j < iters; ++j) { cycles[0][j] = bench<1>(r64, data, i); cycles[1][j] = bench<2>(r64, data, i); cycles[2][j] = bench<3>(r64, data, i); cycles[3][j] = bench<4>(r64, data, i); cycles[4][j] = bench<5>(r64, data, i); cycles[5][j] = bench<6>(r64, data, i); cycles[6][j] = bench<7>(r64, data, i); cycles[7][j] = bench<8>(r64, data, i); cycles[8][j] = bench<9>(r64, data, i); } for (size_t j = 0; j < max_depth; ++j) { sort(cycles[j].begin(), cycles[j].end(), std::greater<ticks>()); } for (size_t j = 0; j <= samples; ++j) { size_t loc = (iters * j)/samples; if (loc >= iters) loc = iters-1; ticks min_val = numeric_limits<ticks>::max(); int min_idx = -1; for (size_t k = 0; k < max_depth; ++k) { if (cycles[k][loc] < min_val) { min_val = cycles[k][loc]; min_idx = k; } } cout << i << " " << j << " " << min_idx << endl; } cout << endl; } cerr << "# ignore " << sum << endl; }; <|endoftext|>
<commit_before>/* * Copyright (C) 2010-2011 Dmitry Marakasov * * This file is part of glosm. * * glosm 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. * * glosm 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 glosm. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef ID_MAP_HH #define ID_MAP_HH #include <vector> /** * Custom std::map-like container for storing OSM data effeciently. * * Uses lower bits of object id as a hash for no calculation overhead * and pooled data storage to pack elements effeciently. * * Interface and usage semantics are the same as for std::map */ template <typename I, typename T, int BUCKET_COUNT_ORDER = 0, int REHASH_GROWTH_ORDER = 1, int ITEMS_PER_CHUNK = 16*65536> class id_map { static const size_t chunk_size = ITEMS_PER_CHUNK; public: typedef I key_type; typedef T mapped_type; typedef std::pair<const I, T> value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; private: struct hash_node { value_type data; hash_node* next; }; typedef hash_node* hash_node_ptr; typedef const hash_node* const_hash_node_ptr; public: struct iterator { typedef iterator _self; typedef id_map<I, T, BUCKET_COUNT_ORDER, REHASH_GROWTH_ORDER, ITEMS_PER_CHUNK> _map; typedef const _map* const_map_ptr; typedef typename _map::pointer pointer; typedef typename _map::reference reference; typedef typename _map::hash_node_ptr hash_node_ptr; const_map_ptr map; hash_node_ptr current; iterator() : map(), current() {} iterator(const_map_ptr m) : map(m), current() {} iterator(const_map_ptr m, hash_node_ptr c) : map(m), current(c) {} _self& operator++() { if (current->next) current = current->next; else current = map->findfirstafter(current->data.first); return *this; } _self operator++(int) { _self tmp = *this; if (current->next) current = current->next; else current = map->findfirstafter(current->data.first); return tmp; } reference operator*() const { return current->data; } pointer operator->() const { return &current->data; } bool operator==(const _self& x) const { return x.current == current; } bool operator!=(const _self& x) const { return x.current != current; } }; struct const_iterator { typedef const_iterator _self; typedef id_map<I, T, BUCKET_COUNT_ORDER, REHASH_GROWTH_ORDER, ITEMS_PER_CHUNK> _map; typedef const _map* const_map_ptr; typedef typename _map::iterator iterator; typedef typename _map::const_pointer pointer; typedef typename _map::const_reference reference; typedef typename _map::const_hash_node_ptr const_hash_node_ptr; const_map_ptr map; const_hash_node_ptr current; const_iterator() : map(), current() {} const_iterator(const_map_ptr m) : map(m) {} const_iterator(const_map_ptr m, const_hash_node_ptr c) : map(m), current(c) {} const_iterator(const iterator& it): map(it.map), current(it.current) {} _self& operator++() { if (current->next) current = current->next; else current = map->findfirstafter(current->data.first); return *this; } _self operator++(int) { _self tmp = *this; if (current->next) current = current->next; else current = map->findfirstafter(current->data.first); return tmp; } reference operator*() const { return current->data; } pointer operator->() const { return &current->data; } bool operator==(const _self& x) const { return x.current == current; } bool operator!=(const _self& x) const { return x.current != current; } }; public: typedef std::vector<hash_node*> chunk_list; public: id_map() { init(); } virtual ~id_map() { deinit(); } std::pair<iterator, bool> insert(const value_type& v) { if (REHASH_GROWTH_ORDER > 0 && count > nbuckets * 2) rehash(REHASH_GROWTH_ORDER); hash_node* t = reinterpret_cast<hash_node*>(alloc()); new((void*)&t->data)value_type(v); /* No checking for existing element done - we assume OSM * data to not have objects with duplicate id's */ t->next = buckets[v.first & (nbuckets-1)]; buckets[v.first & (nbuckets-1)] = t; count++; return std::make_pair(iterator(this, t), true); } size_t size() const { return count; } void clear() { deinit(); init(); } iterator find(key_type v) { for (hash_node* n = buckets[v & (nbuckets-1)]; n; n = n->next) if (n->data.first == v) return iterator(this, n); return end(); } const_iterator find(key_type v) const { for (const hash_node* n = buckets[v & (nbuckets-1)]; n; n = n->next) if (n->data.first == v) return const_iterator(this, n); return end(); } iterator begin() { if (count == 0) return end(); return iterator(this, findfirst()); } const_iterator begin() const { if (count == 0) return end(); return const_iterator(this, findfirst()); } iterator end() { return iterator(this, NULL); } const_iterator end() const { return const_iterator(this, NULL); } protected: hash_node* findfirst() const { for (hash_node** b = buckets; b < buckets + nbuckets; ++b) if (*b != NULL) return *b; return NULL; } hash_node* findfirstfor(key_type v) const { for (hash_node** b = buckets + (v & (nbuckets-1)); b < buckets + nbuckets; ++b) if (*b != NULL) return *b; return NULL; } hash_node* findfirstafter(key_type v) const { for (hash_node** b = buckets + (v & (nbuckets-1)) + 1; b < buckets + nbuckets; ++b) if (*b != NULL) return *b; return NULL; } hash_node* alloc() { if (last_chunk_free == 0) { /* chunk filled; allocate new one */ chunks.push_back(reinterpret_cast<hash_node*>(::operator new(chunk_size*sizeof(hash_node)))); current_ptr = chunks.back(); last_chunk_free = chunk_size; } hash_node* ret = current_ptr; current_ptr++; last_chunk_free--; return ret; } void rehash(int k) { int newnbuckets = nbuckets * (1 << k); hash_node** newbuckets = new hash_node*[newnbuckets]; memset(newbuckets, 0, newnbuckets * sizeof(hash_node*)); for (hash_node** b = buckets; b < buckets + nbuckets; ++b) { for (hash_node* n = *b; n != NULL; ) { hash_node* cur = n; n = n->next; cur->next = newbuckets[cur->data.first & (newnbuckets-1)]; newbuckets[cur->data.first & (newnbuckets-1)] = cur; } } nbuckets = newnbuckets; delete[] buckets; buckets = newbuckets; } void deinit() { for (typename chunk_list::iterator c = chunks.begin(); c != chunks.end(); ++c) { /* Call destructors for assigned elements */ for (hash_node* i = *c; i < ((*c == chunks.back()) ? (*c + chunk_size - last_chunk_free) : (*c + chunk_size)); ++i) { i->data.~value_type(); } ::operator delete(*c); } chunks.clear(); delete[] buckets; } void init() { count = 0; last_chunk_free = 0; nbuckets = 1 << BUCKET_COUNT_ORDER; buckets = new hash_node*[nbuckets]; memset(buckets, 0, nbuckets * sizeof(hash_node*)); } protected: /* hash table */ size_t nbuckets; /* always power of 2, so nbuckets-1 is bitmask for hashing */ hash_node** buckets; size_t count; /* @todo superfluous - may be derived from nchunks and urrent_ptr */ /* memory pool */ chunk_list chunks; size_t last_chunk_free; hash_node* current_ptr; /* @todo superfluous - either last_chunk free or current_ptr should be removed */ }; #endif <commit_msg>Rework id_map, add support for removing elements<commit_after>/* * Copyright (C) 2010-2011 Dmitry Marakasov * * This file is part of glosm. * * glosm 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. * * glosm 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 glosm. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef ID_MAP_HH #define ID_MAP_HH #include <vector> #include <cassert> /** * Custom std::map-like container for storing OSM data effeciently. * * Uses lower bits of object id as a hash for no calculation overhead * and pooled data storage to pack elements effeciently. * * Interface and usage semantics are the same as for std::map */ template <typename I, typename T, int PAGE_SIZE = 1048576> class id_map { public: typedef I key_type; typedef T mapped_type; typedef std::pair<const I, T> value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; private: struct hash_node { value_type data; hash_node* next; }; typedef hash_node* hash_node_ptr; typedef const hash_node* const_hash_node_ptr; class page { public: typedef hash_node* iterator; typedef const hash_node* const_iterator; public: page() : count_(0), data_(reinterpret_cast<hash_node*>(::operator new(PAGE_SIZE))) { assert(sizeof(hash_node) <= PAGE_SIZE); } /* copy ctor and operator = transfer data ownership * this is rather ugly, but I it seems like the best way * to do it conveniently with stl containers (else, we'll * have to use vector of pointers and spend extra code on * exception safety and stuff */ page(const page& other) : count_(other.count_), data_(other.data_) { other.count_ = 0; other.data_ = NULL; } page& operator=(const page& other) { count_ = other.count_; data_ = other.data_; other.count_ = 0; other.data_ = NULL; return *this; } ~page() { if (data_) { for (hash_node* i = data_; i < data_ + count_; ++i) i->data.~value_type(); ::operator delete(data_); } } inline size_t used() const { return count_; } inline size_t free() const { return capacity() - count_; } inline size_t capacity() const { return PAGE_SIZE/sizeof(hash_node); } inline bool full() const { return free() == 0; } inline bool empty() const { return count_ == 0; } inline hash_node& front() const { return *data_; } inline hash_node& back() const { return *(data_ + count_ - 1); } iterator begin() { return data_; } const_iterator begin() const { return data_; } iterator end() { return data_ + count_; } const_iterator end() const { return data_ + count_; } hash_node* push(const value_type& v, hash_node* next = NULL) { assert(free() > 0); new(reinterpret_cast<void*>(&((data_ + count_)->data))) value_type(v); (data_ + count_)->next = next; return data_ + count_++; } void pop() { assert(count_ > 0); data_[count_-1].data.~value_type(); --count_; } private: mutable int count_; mutable hash_node* data_; }; typedef std::vector<page> page_list; typedef std::vector<hash_node*> hashtable; private: size_t count_; hashtable buckets_; page_list pages_; public: class iterator; class const_iterator { public: typedef const_iterator self; private: typedef id_map<I, T, PAGE_SIZE> map; typedef const map* const_map_ptr; typedef typename map::iterator iterator; typedef typename map::const_pointer pointer; typedef typename map::const_reference reference; typedef typename map::const_hash_node_ptr const_hash_node_ptr; const_map_ptr map_; const_hash_node_ptr current_; public: const_iterator() : map_(), current_() {} const_iterator(const_map_ptr m) : map_(m), current_() {} const_iterator(const_map_ptr m, const_hash_node_ptr c) : map_(m), current_(c) {} const_iterator(const iterator& it): map_(it.map_), current_(it.current_) {} self& operator++() { if (current_->next) current_ = current_->next; else current_ = map_->findfirstafter(current_->data.first); return *this; } self operator++(int) { self tmp = *this; if (current_->next) current_ = current_->next; else current_ = map_->findfirstafter(current_->data.first); return tmp; } reference operator*() const { return current_->data; } pointer operator->() const { return &current_->data; } bool operator==(const self& x) const { return x.current_ == current_; } bool operator!=(const self& x) const { return x.current_ != current_; } }; class iterator { friend class const_iterator; public: typedef iterator self; private: typedef id_map<I, T, PAGE_SIZE> map; typedef const map* const_map_ptr; typedef typename map::pointer pointer; typedef typename map::reference reference; typedef typename map::hash_node_ptr hash_node_ptr; private: const_map_ptr map_; hash_node_ptr current_; public: iterator() : map_(), current_() {} iterator(const_map_ptr m) : map_(m), current_() {} iterator(const_map_ptr m, hash_node_ptr c) : map_(m), current_(c) {} self& operator++() { if (current_->next) current_ = current_->next; else current_ = map_->findfirstafter(current_->data.first); return *this; } self operator++(int) { self tmp = *this; if (current_->next) current_ = current_->next; else current_ = map_->findfirstafter(current_->data.first); return tmp; } reference operator*() const { return current_->data; } pointer operator->() const { return &current_->data; } bool operator==(const self& x) const { return x.current_ == current_; } bool operator!=(const self& x) const { return x.current_ != current_; } }; public: id_map(int nbuckets = 1024) : count_(0), buckets_(nbuckets, NULL) { } virtual ~id_map() { } std::pair<iterator, bool> insert(const value_type& v) { if (count_ >= buckets_.size()) rehash(buckets_.size() * 2); if (pages_.empty() || pages_.back().full()) pages_.push_back(page()); int bucket = v.first & (buckets_.size() - 1); buckets_[bucket] = pages_.back().push(v, buckets_[bucket]); ++count_; return std::make_pair(iterator(this, buckets_[bucket]), true); } /* erases last added element from the map * !! assumes that there's no other way for elements to be erased !! * if some other erase() is added, this should be rewritten */ void erase_last() { assert(!pages_.empty()); /* external invaiant */ assert(!pages_.back().empty()); /* internal invariant */ /* remove element from the hash table */ int bucket = pages_.back().back().data.first & (buckets_.size() - 1); assert(buckets_[bucket] == &pages_.back().back()); buckets_[bucket] = buckets_[bucket]->next; /* remove element from the storage */ pages_.back().pop(); if (pages_.back().empty()) pages_.pop_back(); --count_; } inline size_t size() const { return count_; } inline bool empty() const { return count_ == 0; } void clear() { buckets_.clear(); pages_.clear(); count_ = 0; } iterator find(key_type v) { int bucket = v & (buckets_.size() - 1); for (hash_node* n = buckets_[bucket]; n; n = n->next) if (n->data.first == v) return iterator(this, n); return end(); } const_iterator find(key_type v) const { int bucket = v & (buckets_.size() - 1); for (const hash_node* n = buckets_[bucket]; n; n = n->next) if (n->data.first == v) return const_iterator(this, n); return end(); } iterator begin() { if (count_ == 0) return end(); return iterator(this, findfirst()); } const_iterator begin() const { if (count_ == 0) return end(); return const_iterator(this, findfirst()); } iterator end() { return iterator(this, NULL); } const_iterator end() const { return const_iterator(this, NULL); } void swap(id_map<I, T, PAGE_SIZE>& other) { buckets_.swap(other.buckets_); pages_.swap(other.pages_); std::swap(count_, other.count_); } void rehash(size_t size) { assert(size > 0); assert((size & (size - 1)) == 0); // power of two hashtable newbuckets(size, NULL); for (typename page_list::iterator p = pages_.begin(); p != pages_.end(); ++p) { for (typename page::iterator i = p->begin(); i != p->end(); ++i) { int bucket = i->data.first & (newbuckets.size() - 1); i->next = newbuckets[bucket]; newbuckets[bucket] = i; } } buckets_.swap(newbuckets); } protected: hash_node* findfirst() const { for (typename hashtable::const_iterator i = buckets_.begin(); i != buckets_.end(); ++i) if (*i != NULL) return *i; return NULL; } hash_node* findfirstfor(key_type v) const { int bucket = v & (buckets_.size() - 1); for (typename hashtable::const_iterator i = buckets_.begin() + bucket; i != buckets_.end(); ++i) if (*i != NULL) return *i; return NULL; } hash_node* findfirstafter(key_type v) const { int bucket = v & (buckets_.size() - 1); for (typename hashtable::const_iterator i = buckets_.begin() + bucket + 1; i != buckets_.end(); ++i) if (*i != NULL) return *i; return NULL; } }; #endif <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <thrift/lib/cpp2/server/Cpp2Worker.h> #include <glog/logging.h> #include <folly/String.h> #include <folly/io/async/AsyncSSLSocket.h> #include <folly/io/async/EventBaseLocal.h> #include <folly/portability/Sockets.h> #include <thrift/lib/cpp/async/TAsyncSSLSocket.h> #include <thrift/lib/cpp/async/TAsyncSocket.h> #include <thrift/lib/cpp/concurrency/Util.h> #include <thrift/lib/cpp2/server/Cpp2Connection.h> #include <thrift/lib/cpp2/server/ThriftServer.h> #include <thrift/lib/cpp2/server/peeking/PeekingManager.h> #include <thrift/lib/thrift/gen-cpp2/RpcMetadata_types.h> #include <wangle/acceptor/EvbHandshakeHelper.h> #include <wangle/acceptor/SSLAcceptorHandshakeHelper.h> #include <wangle/acceptor/UnencryptedAcceptorHandshakeHelper.h> namespace apache { namespace thrift { using namespace apache::thrift::server; using namespace apache::thrift::transport; using namespace apache::thrift::async; using apache::thrift::concurrency::Util; using std::shared_ptr; namespace { folly::LeakySingleton<folly::EventBaseLocal<RequestsRegistry>> registry; } void Cpp2Worker::initRequestsRegistry() { auto* evb = getEventBase(); auto memPerReq = server_->getMaxDebugPayloadMemoryPerRequest(); auto memPerWorker = server_->getMaxDebugPayloadMemoryPerWorker(); auto maxFinished = server_->getMaxFinishedDebugPayloadsPerWorker(); std::weak_ptr<Cpp2Worker> self_weak = shared_from_this(); evb->runInEventBaseThread([=, self_weak = std::move(self_weak)]() { if (auto self = self_weak.lock()) { self->requestsRegistry_ = &registry.get().getOrCreate( *evb, memPerReq, memPerWorker, maxFinished); } }); } void Cpp2Worker::onNewConnection( folly::AsyncTransportWrapper::UniquePtr sock, const folly::SocketAddress* addr, const std::string& nextProtocolName, wangle::SecureTransportType secureTransportType, const wangle::TransportInfo& tinfo) { auto* observer = server_->getObserver(); uint32_t maxConnection = server_->getMaxConnections(); if (maxConnection > 0 && (getConnectionManager()->getNumConnections() >= maxConnection / server_->getNumIOWorkerThreads())) { if (observer) { observer->connDropped(); observer->connRejected(); } return; } const auto& func = server_->getZeroCopyEnableFunc(); if (func && sock) { sock->setZeroCopy(true); sock->setZeroCopyEnableFunc(func); } // log nextProtocolName to scuba if (!nextProtocolName.empty()) { server_->setTransport(nextProtocolName); } // Check the security protocol switch (secureTransportType) { // If no security, peek into the socket to determine type case wangle::SecureTransportType::NONE: { auto peekingManager = new PeekingManager( shared_from_this(), *addr, nextProtocolName, secureTransportType, tinfo, server_); peekingManager->start(std::move(sock), server_->getObserverShared()); break; } case wangle::SecureTransportType::TLS: // Use the announced protocol to determine the correct handler if (!nextProtocolName.empty()) { for (auto& routingHandler : *server_->getRoutingHandlers()) { if (routingHandler->canAcceptEncryptedConnection(nextProtocolName)) { VLOG(4) << "Cpp2Worker: Routing encrypted connection for protocol " << nextProtocolName; routingHandler->handleConnection( getConnectionManager(), std::move(sock), addr, tinfo, shared_from_this()); return; } } } // Default to header handleHeader(std::move(sock), addr); break; case wangle::SecureTransportType::ZERO: LOG(ERROR) << "Unsupported Secure Transport Type: ZERO"; break; default: LOG(ERROR) << "Unsupported Secure Transport Type"; break; } } void Cpp2Worker::handleHeader( folly::AsyncTransportWrapper::UniquePtr sock, const folly::SocketAddress* addr) { auto fd = sock->getUnderlyingTransport<folly::AsyncSocket>() ->getNetworkSocket() .toFd(); VLOG(4) << "Cpp2Worker: Creating connection for socket " << fd; auto thriftTransport = createThriftTransport(std::move(sock)); auto connection = std::make_shared<Cpp2Connection>( std::move(thriftTransport), addr, shared_from_this(), nullptr); Acceptor::addConnection(connection.get()); connection->addConnection(connection); // set compression algorithm to be used on this connection auto compression = fizzPeeker_.getNegotiatedParameters().compression; if (compression != CompressionAlgorithm::NONE) { connection->setNegotiatedCompressionAlgorithm(compression); } connection->start(); VLOG(4) << "Cpp2Worker: created connection for socket " << fd; auto observer = server_->getObserver(); if (observer) { observer->connAccepted(); observer->activeConnections( getConnectionManager()->getNumConnections() * server_->getNumIOWorkerThreads()); } } std::shared_ptr<folly::AsyncTransportWrapper> Cpp2Worker::createThriftTransport( folly::AsyncTransportWrapper::UniquePtr sock) { auto fizzServer = dynamic_cast<fizz::server::AsyncFizzServer*>(sock.get()); if (fizzServer) { auto asyncSock = sock->getUnderlyingTransport<async::TAsyncSocket>(); if (asyncSock) { markSocketAccepted(asyncSock); } // give up ownership sock.release(); return std::shared_ptr<fizz::server::AsyncFizzServer>( fizzServer, fizz::server::AsyncFizzServer::Destructor()); } TAsyncSocket* tsock = dynamic_cast<TAsyncSocket*>(sock.release()); CHECK(tsock); auto asyncSocket = std::shared_ptr<TAsyncSocket>(tsock, TAsyncSocket::Destructor()); markSocketAccepted(asyncSocket.get()); return asyncSocket; } void Cpp2Worker::markSocketAccepted(TAsyncSocket* sock) { sock->setShutdownSocketSet(server_->wShutdownSocketSet_); } void Cpp2Worker::plaintextConnectionReady( folly::AsyncTransportWrapper::UniquePtr sock, const folly::SocketAddress& clientAddr, const std::string& nextProtocolName, wangle::SecureTransportType secureTransportType, wangle::TransportInfo& tinfo) { auto asyncSocket = sock->getUnderlyingTransport<folly::AsyncSocket>(); CHECK(asyncSocket) << "Underlying socket is not a AsyncSocket type"; asyncSocket->setShutdownSocketSet(server_->wShutdownSocketSet_); auto peekingManager = new PeekingManager( shared_from_this(), clientAddr, nextProtocolName, secureTransportType, tinfo, server_, /* checkTLS */ true); peekingManager->start(std::move(sock), server_->getObserverShared()); } void Cpp2Worker::useExistingChannel( const std::shared_ptr<HeaderServerChannel>& serverChannel) { folly::SocketAddress address; auto conn = std::make_shared<Cpp2Connection>( nullptr, &address, shared_from_this(), serverChannel); Acceptor::getConnectionManager()->addConnection(conn.get(), false); conn->addConnection(conn); conn->start(); } void Cpp2Worker::stopDuplex(std::shared_ptr<ThriftServer> myServer) { // They better have given us the correct ThriftServer DCHECK(server_ == myServer.get()); // This does not really fully drain everything but at least // prevents the connections from accepting new requests wangle::Acceptor::drainAllConnections(); // Capture a shared_ptr to our ThriftServer making sure it will outlive us // Otherwise our raw pointer to it (server_) will be jeopardized. duplexServer_ = myServer; } void Cpp2Worker::updateSSLStats( const folly::AsyncTransportWrapper* sock, std::chrono::milliseconds /* acceptLatency */, wangle::SSLErrorEnum error, const folly::exception_wrapper& /*ex*/) noexcept { if (!sock) { return; } auto observer = getServer()->getObserver(); if (!observer) { return; } auto fizz = sock->getUnderlyingTransport<fizz::server::AsyncFizzServer>(); if (fizz) { if (sock->good() && error == wangle::SSLErrorEnum::NO_ERROR) { observer->tlsComplete(); auto pskType = fizz->getState().pskType(); if (pskType && *pskType == fizz::PskType::Resumption) { observer->tlsResumption(); } if (fizz->getPeerCertificate()) { observer->tlsWithClientCert(); } } else { observer->tlsError(); } } else { auto socket = sock->getUnderlyingTransport<folly::AsyncSSLSocket>(); if (!socket) { return; } if (socket->good() && error == wangle::SSLErrorEnum::NO_ERROR) { observer->tlsComplete(); if (socket->getSSLSessionReused()) { observer->tlsResumption(); } if (socket->getPeerCertificate()) { observer->tlsWithClientCert(); } } else { observer->tlsError(); } } } wangle::AcceptorHandshakeHelper::UniquePtr Cpp2Worker::createSSLHelper( const std::vector<uint8_t>& bytes, const folly::SocketAddress& clientAddr, std::chrono::steady_clock::time_point acceptTime, wangle::TransportInfo& tInfo) { if (accConfig_.fizzConfig.enableFizz) { return getFizzPeeker()->getHelper(bytes, clientAddr, acceptTime, tInfo); } return defaultPeekingCallback_.getHelper( bytes, clientAddr, acceptTime, tInfo); } bool Cpp2Worker::shouldPerformSSL( const std::vector<uint8_t>& bytes, const folly::SocketAddress& clientAddr) { auto sslPolicy = getSSLPolicy(); if (sslPolicy == SSLPolicy::REQUIRED) { if (isPlaintextAllowedOnLoopback()) { // loopback clients may still be sending TLS so we need to ensure that // it doesn't appear that way in addition to verifying it's loopback. return !( clientAddr.isLoopbackAddress() && !TLSHelper::looksLikeTLS(bytes)); } return true; } else { return sslPolicy != SSLPolicy::DISABLED && TLSHelper::looksLikeTLS(bytes); } } wangle::AcceptorHandshakeHelper::UniquePtr Cpp2Worker::getHelper( const std::vector<uint8_t>& bytes, const folly::SocketAddress& clientAddr, std::chrono::steady_clock::time_point acceptTime, wangle::TransportInfo& ti) { if (!shouldPerformSSL(bytes, clientAddr)) { return wangle::AcceptorHandshakeHelper::UniquePtr( new wangle::UnencryptedAcceptorHandshakeHelper()); } auto sslAcceptor = createSSLHelper(bytes, clientAddr, acceptTime, ti); // If we have a nonzero dedicated ssl handshake pool, offload the SSL // handshakes with EvbHandshakeHelper. if (server_->sslHandshakePool_->numThreads() > 0) { return wangle::EvbHandshakeHelper::UniquePtr(new wangle::EvbHandshakeHelper( std::move(sslAcceptor), server_->sslHandshakePool_->getEventBase())); } else { return sslAcceptor; } } void Cpp2Worker::requestStop() { getEventBase()->runInEventBaseThreadAndWait([&] { if (stopping_) { return; } stopping_ = true; if (activeRequests_ == 0) { stopBaton_.post(); } }); } void Cpp2Worker::waitForStop(std::chrono::system_clock::time_point deadline) { if (!stopBaton_.try_wait_until(deadline)) { LOG(ERROR) << "Failed to join outstanding requests."; } } Cpp2Worker::ActiveRequestsGuard Cpp2Worker::getActiveRequestsGuard() { DCHECK(!stopping_ || activeRequests_); ++activeRequests_; return Cpp2Worker::ActiveRequestsGuard(this); } } // namespace thrift } // namespace apache <commit_msg>Let Cpp2Worker drop connections when stopping<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <thrift/lib/cpp2/server/Cpp2Worker.h> #include <glog/logging.h> #include <folly/String.h> #include <folly/io/async/AsyncSSLSocket.h> #include <folly/io/async/EventBaseLocal.h> #include <folly/portability/Sockets.h> #include <thrift/lib/cpp/async/TAsyncSSLSocket.h> #include <thrift/lib/cpp/async/TAsyncSocket.h> #include <thrift/lib/cpp/concurrency/Util.h> #include <thrift/lib/cpp2/server/Cpp2Connection.h> #include <thrift/lib/cpp2/server/ThriftServer.h> #include <thrift/lib/cpp2/server/peeking/PeekingManager.h> #include <thrift/lib/thrift/gen-cpp2/RpcMetadata_types.h> #include <wangle/acceptor/EvbHandshakeHelper.h> #include <wangle/acceptor/SSLAcceptorHandshakeHelper.h> #include <wangle/acceptor/UnencryptedAcceptorHandshakeHelper.h> namespace apache { namespace thrift { using namespace apache::thrift::server; using namespace apache::thrift::transport; using namespace apache::thrift::async; using apache::thrift::concurrency::Util; using std::shared_ptr; namespace { folly::LeakySingleton<folly::EventBaseLocal<RequestsRegistry>> registry; } void Cpp2Worker::initRequestsRegistry() { auto* evb = getEventBase(); auto memPerReq = server_->getMaxDebugPayloadMemoryPerRequest(); auto memPerWorker = server_->getMaxDebugPayloadMemoryPerWorker(); auto maxFinished = server_->getMaxFinishedDebugPayloadsPerWorker(); std::weak_ptr<Cpp2Worker> self_weak = shared_from_this(); evb->runInEventBaseThread([=, self_weak = std::move(self_weak)]() { if (auto self = self_weak.lock()) { self->requestsRegistry_ = &registry.get().getOrCreate( *evb, memPerReq, memPerWorker, maxFinished); } }); } void Cpp2Worker::onNewConnection( folly::AsyncTransportWrapper::UniquePtr sock, const folly::SocketAddress* addr, const std::string& nextProtocolName, wangle::SecureTransportType secureTransportType, const wangle::TransportInfo& tinfo) { // This is possible if the connection was accepted before stopListening() // call, but handshake was finished after stopCPUWorkers() call. if (stopping_) { return; } auto* observer = server_->getObserver(); uint32_t maxConnection = server_->getMaxConnections(); if (maxConnection > 0 && (getConnectionManager()->getNumConnections() >= maxConnection / server_->getNumIOWorkerThreads())) { if (observer) { observer->connDropped(); observer->connRejected(); } return; } const auto& func = server_->getZeroCopyEnableFunc(); if (func && sock) { sock->setZeroCopy(true); sock->setZeroCopyEnableFunc(func); } // log nextProtocolName to scuba if (!nextProtocolName.empty()) { server_->setTransport(nextProtocolName); } // Check the security protocol switch (secureTransportType) { // If no security, peek into the socket to determine type case wangle::SecureTransportType::NONE: { auto peekingManager = new PeekingManager( shared_from_this(), *addr, nextProtocolName, secureTransportType, tinfo, server_); peekingManager->start(std::move(sock), server_->getObserverShared()); break; } case wangle::SecureTransportType::TLS: // Use the announced protocol to determine the correct handler if (!nextProtocolName.empty()) { for (auto& routingHandler : *server_->getRoutingHandlers()) { if (routingHandler->canAcceptEncryptedConnection(nextProtocolName)) { VLOG(4) << "Cpp2Worker: Routing encrypted connection for protocol " << nextProtocolName; routingHandler->handleConnection( getConnectionManager(), std::move(sock), addr, tinfo, shared_from_this()); return; } } } // Default to header handleHeader(std::move(sock), addr); break; case wangle::SecureTransportType::ZERO: LOG(ERROR) << "Unsupported Secure Transport Type: ZERO"; break; default: LOG(ERROR) << "Unsupported Secure Transport Type"; break; } } void Cpp2Worker::handleHeader( folly::AsyncTransportWrapper::UniquePtr sock, const folly::SocketAddress* addr) { auto fd = sock->getUnderlyingTransport<folly::AsyncSocket>() ->getNetworkSocket() .toFd(); VLOG(4) << "Cpp2Worker: Creating connection for socket " << fd; auto thriftTransport = createThriftTransport(std::move(sock)); auto connection = std::make_shared<Cpp2Connection>( std::move(thriftTransport), addr, shared_from_this(), nullptr); Acceptor::addConnection(connection.get()); connection->addConnection(connection); // set compression algorithm to be used on this connection auto compression = fizzPeeker_.getNegotiatedParameters().compression; if (compression != CompressionAlgorithm::NONE) { connection->setNegotiatedCompressionAlgorithm(compression); } connection->start(); VLOG(4) << "Cpp2Worker: created connection for socket " << fd; auto observer = server_->getObserver(); if (observer) { observer->connAccepted(); observer->activeConnections( getConnectionManager()->getNumConnections() * server_->getNumIOWorkerThreads()); } } std::shared_ptr<folly::AsyncTransportWrapper> Cpp2Worker::createThriftTransport( folly::AsyncTransportWrapper::UniquePtr sock) { auto fizzServer = dynamic_cast<fizz::server::AsyncFizzServer*>(sock.get()); if (fizzServer) { auto asyncSock = sock->getUnderlyingTransport<async::TAsyncSocket>(); if (asyncSock) { markSocketAccepted(asyncSock); } // give up ownership sock.release(); return std::shared_ptr<fizz::server::AsyncFizzServer>( fizzServer, fizz::server::AsyncFizzServer::Destructor()); } TAsyncSocket* tsock = dynamic_cast<TAsyncSocket*>(sock.release()); CHECK(tsock); auto asyncSocket = std::shared_ptr<TAsyncSocket>(tsock, TAsyncSocket::Destructor()); markSocketAccepted(asyncSocket.get()); return asyncSocket; } void Cpp2Worker::markSocketAccepted(TAsyncSocket* sock) { sock->setShutdownSocketSet(server_->wShutdownSocketSet_); } void Cpp2Worker::plaintextConnectionReady( folly::AsyncTransportWrapper::UniquePtr sock, const folly::SocketAddress& clientAddr, const std::string& nextProtocolName, wangle::SecureTransportType secureTransportType, wangle::TransportInfo& tinfo) { auto asyncSocket = sock->getUnderlyingTransport<folly::AsyncSocket>(); CHECK(asyncSocket) << "Underlying socket is not a AsyncSocket type"; asyncSocket->setShutdownSocketSet(server_->wShutdownSocketSet_); auto peekingManager = new PeekingManager( shared_from_this(), clientAddr, nextProtocolName, secureTransportType, tinfo, server_, /* checkTLS */ true); peekingManager->start(std::move(sock), server_->getObserverShared()); } void Cpp2Worker::useExistingChannel( const std::shared_ptr<HeaderServerChannel>& serverChannel) { folly::SocketAddress address; auto conn = std::make_shared<Cpp2Connection>( nullptr, &address, shared_from_this(), serverChannel); Acceptor::getConnectionManager()->addConnection(conn.get(), false); conn->addConnection(conn); conn->start(); } void Cpp2Worker::stopDuplex(std::shared_ptr<ThriftServer> myServer) { // They better have given us the correct ThriftServer DCHECK(server_ == myServer.get()); // This does not really fully drain everything but at least // prevents the connections from accepting new requests wangle::Acceptor::drainAllConnections(); // Capture a shared_ptr to our ThriftServer making sure it will outlive us // Otherwise our raw pointer to it (server_) will be jeopardized. duplexServer_ = myServer; } void Cpp2Worker::updateSSLStats( const folly::AsyncTransportWrapper* sock, std::chrono::milliseconds /* acceptLatency */, wangle::SSLErrorEnum error, const folly::exception_wrapper& /*ex*/) noexcept { if (!sock) { return; } auto observer = getServer()->getObserver(); if (!observer) { return; } auto fizz = sock->getUnderlyingTransport<fizz::server::AsyncFizzServer>(); if (fizz) { if (sock->good() && error == wangle::SSLErrorEnum::NO_ERROR) { observer->tlsComplete(); auto pskType = fizz->getState().pskType(); if (pskType && *pskType == fizz::PskType::Resumption) { observer->tlsResumption(); } if (fizz->getPeerCertificate()) { observer->tlsWithClientCert(); } } else { observer->tlsError(); } } else { auto socket = sock->getUnderlyingTransport<folly::AsyncSSLSocket>(); if (!socket) { return; } if (socket->good() && error == wangle::SSLErrorEnum::NO_ERROR) { observer->tlsComplete(); if (socket->getSSLSessionReused()) { observer->tlsResumption(); } if (socket->getPeerCertificate()) { observer->tlsWithClientCert(); } } else { observer->tlsError(); } } } wangle::AcceptorHandshakeHelper::UniquePtr Cpp2Worker::createSSLHelper( const std::vector<uint8_t>& bytes, const folly::SocketAddress& clientAddr, std::chrono::steady_clock::time_point acceptTime, wangle::TransportInfo& tInfo) { if (accConfig_.fizzConfig.enableFizz) { return getFizzPeeker()->getHelper(bytes, clientAddr, acceptTime, tInfo); } return defaultPeekingCallback_.getHelper( bytes, clientAddr, acceptTime, tInfo); } bool Cpp2Worker::shouldPerformSSL( const std::vector<uint8_t>& bytes, const folly::SocketAddress& clientAddr) { auto sslPolicy = getSSLPolicy(); if (sslPolicy == SSLPolicy::REQUIRED) { if (isPlaintextAllowedOnLoopback()) { // loopback clients may still be sending TLS so we need to ensure that // it doesn't appear that way in addition to verifying it's loopback. return !( clientAddr.isLoopbackAddress() && !TLSHelper::looksLikeTLS(bytes)); } return true; } else { return sslPolicy != SSLPolicy::DISABLED && TLSHelper::looksLikeTLS(bytes); } } wangle::AcceptorHandshakeHelper::UniquePtr Cpp2Worker::getHelper( const std::vector<uint8_t>& bytes, const folly::SocketAddress& clientAddr, std::chrono::steady_clock::time_point acceptTime, wangle::TransportInfo& ti) { if (!shouldPerformSSL(bytes, clientAddr)) { return wangle::AcceptorHandshakeHelper::UniquePtr( new wangle::UnencryptedAcceptorHandshakeHelper()); } auto sslAcceptor = createSSLHelper(bytes, clientAddr, acceptTime, ti); // If we have a nonzero dedicated ssl handshake pool, offload the SSL // handshakes with EvbHandshakeHelper. if (server_->sslHandshakePool_->numThreads() > 0) { return wangle::EvbHandshakeHelper::UniquePtr(new wangle::EvbHandshakeHelper( std::move(sslAcceptor), server_->sslHandshakePool_->getEventBase())); } else { return sslAcceptor; } } void Cpp2Worker::requestStop() { getEventBase()->runInEventBaseThreadAndWait([&] { if (stopping_) { return; } stopping_ = true; if (activeRequests_ == 0) { stopBaton_.post(); } }); } void Cpp2Worker::waitForStop(std::chrono::system_clock::time_point deadline) { if (!stopBaton_.try_wait_until(deadline)) { LOG(ERROR) << "Failed to join outstanding requests."; } } Cpp2Worker::ActiveRequestsGuard Cpp2Worker::getActiveRequestsGuard() { DCHECK(!stopping_ || activeRequests_); ++activeRequests_; return Cpp2Worker::ActiveRequestsGuard(this); } } // namespace thrift } // namespace apache <|endoftext|>
<commit_before>/** @file SimpleStepper.cpp @author Evert Chin @brief Fast and Simple Stepper Driver * This file may be redistributed under the terms of the MIT license. * A copy of this license has been included with this distribution in the file LICENSE. */ #include "SimpleStepper.h" #include "TimerOne.h" SimpleStepper *SimpleStepper::firstInstance; SimpleStepper::SimpleStepper(uint8_t dirpin, uint8_t steppin){ if(!firstInstance){ firstInstance = this; } this->dirPin = Pin(dirpin); this->stepPin = Pin(steppin); } void SimpleStepper::init(){ dirPin.setOutput(); stepPin.setOutput(); Timer1.initialize(); Timer1.attachInterrupt(SimpleStepper::ticking); Timer1.stop(); this->pause(); } void SimpleStepper::setPulse(long pulse){ Timer1.setPeriod(pulse); } bool SimpleStepper::step(long steps, uint8_t direction){ if(this->isStepping()){ return false; } this->ticksRemaining = steps * 2; //converting steps to ticks if(direction == HIGH){ this->dirPin.setHigh(); } else { this->dirPin.setLow(); } return true; } bool SimpleStepper::step(long steps, uint8_t direction, long pulse){ if(this->isStepping()){ return false; } this->resume(); this->setPulse(pulse); return this->step(steps, direction); } long getRemainingSteps(){ return ticksRemaining/2; } //returns the remaining steps long SimpleStepper::stop(){ //each step = 2 ticks long stepsRemaining = this->getRemainingSteps(); Timer1.stop(); if(ticksRemaining & 1){ ticksRemaining = 1; } else{ ticksRemaining = 0; } Timer1.start(); return stepsRemaining; } void SimpleStepper::pause(){ paused = true; Timer1.stop(); } void SimpleStepper::resume(){ if(paused){ Timer1.start(); paused = false; } } bool SimpleStepper::isStepping(){ return (ticksRemaining > 0); } bool SimpleStepper::isStopped(){ return (ticksRemaining <= 0); } bool SimpleStepper::isPaused(){ return paused; } void SimpleStepper::ticking(){ if(firstInstance->ticksRemaining > 0){ //generate high/low signal for the stepper driver firstInstance->stepPin.toggleState(); --firstInstance->ticksRemaining; } } <commit_msg>Fixed a typo<commit_after>/** @file SimpleStepper.cpp @author Evert Chin @brief Fast and Simple Stepper Driver * This file may be redistributed under the terms of the MIT license. * A copy of this license has been included with this distribution in the file LICENSE. */ #include "SimpleStepper.h" #include "TimerOne.h" SimpleStepper *SimpleStepper::firstInstance; SimpleStepper::SimpleStepper(uint8_t dirpin, uint8_t steppin){ if(!firstInstance){ firstInstance = this; } this->dirPin = Pin(dirpin); this->stepPin = Pin(steppin); } void SimpleStepper::init(){ dirPin.setOutput(); stepPin.setOutput(); Timer1.initialize(); Timer1.attachInterrupt(SimpleStepper::ticking); Timer1.stop(); this->pause(); } void SimpleStepper::setPulse(long pulse){ Timer1.setPeriod(pulse); } bool SimpleStepper::step(long steps, uint8_t direction){ if(this->isStepping()){ return false; } this->ticksRemaining = steps * 2; //converting steps to ticks if(direction == HIGH){ this->dirPin.setHigh(); } else { this->dirPin.setLow(); } return true; } bool SimpleStepper::step(long steps, uint8_t direction, long pulse){ if(this->isStepping()){ return false; } this->resume(); this->setPulse(pulse); return this->step(steps, direction); } long SimpleStepper::getRemainingSteps(){ return ticksRemaining/2; } //returns the remaining steps long SimpleStepper::stop(){ //each step = 2 ticks long stepsRemaining = this->getRemainingSteps(); Timer1.stop(); if(ticksRemaining & 1){ ticksRemaining = 1; } else{ ticksRemaining = 0; } Timer1.start(); return stepsRemaining; } void SimpleStepper::pause(){ paused = true; Timer1.stop(); } void SimpleStepper::resume(){ if(paused){ Timer1.start(); paused = false; } } bool SimpleStepper::isStepping(){ return (ticksRemaining > 0); } bool SimpleStepper::isStopped(){ return (ticksRemaining <= 0); } bool SimpleStepper::isPaused(){ return paused; } void SimpleStepper::ticking(){ if(firstInstance->ticksRemaining > 0){ //generate high/low signal for the stepper driver firstInstance->stepPin.toggleState(); --firstInstance->ticksRemaining; } } <|endoftext|>
<commit_before> #include "cache_size.h" #include <iostream> int main(int argc, char* argv[]) { static constexpr long kCacheSize = 8 * 1024 * 1024; static constexpr long kIterations = 2; static constexpr long kTestSizes = 4; std::vector<int> candidates(kTestSizes); for (int i = 0; i < kTestSizes; i++) { candidates.at(i) = i + 1; } for (int i = 0; i < kIterations; i++) { int passed_tests = 0; for (int candidate_large : candidates) { uint64_t res_large = FindFirstElementReadingTime(kCacheSize * candidate_large); for (int candidate_small : candidates) { uint64_t res_small = FindFirstElementReadingTime(kCacheSize / candidate_small); if (res_large <= res_small) { std::cout << "test failed" << std::endl; } else { std::cout << "test passed" << std::endl; passed_tests++; } } } std::cout << "In total out of " << kTestSizes * kTestSizes << " comparisons " << passed_tests << " were successfully passed." << std::endl; } return 0; } <commit_msg>added comments<commit_after> #include "cache_size.h" #include <iostream> // Measure how often measuring time is able to accurately determine cache hits // and cache misses based on the buffer size under analysis and the cache size // it checks whether buffer sizes that fit in cache have less reading time or // not int main(int argc, char* argv[]) { static constexpr long kCacheSize = 8 * 1024 * 1024; static constexpr long kIterations = 2; static constexpr long kTestSizes = 4; // generates a list of numbers that are used to determine the size of buffers std::vector<int> candidates(kTestSizes); for (int i = 1; i < kTestSizes + 1; i++) { candidates.at(i - 1) = 2 * i; } int total_passed_tests = 0; for (int i = 0; i < kIterations; i++) { int passed_tests = 0; for (int candidate_large : candidates) { uint64_t res_large = FindMaxReadingTime(kCacheSize * candidate_large); for (int candidate_small : candidates) { uint64_t res_small = FindMaxReadingTime(kCacheSize / candidate_small); // we expect that buffer sizes < cache size always have less reading // times as they all should result in cache hits while buffer sizes > // cache size suffer from cache misses, so they must take longer to be // read if (res_large <= res_small) { std::cout << "test failed" << std::endl; } else { std::cout << "test passed" << std::endl; passed_tests++; } } } std::cout << "In total out of " << kTestSizes * kTestSizes << " comparisons " << passed_tests << " were successfully passed." << std::endl; total_passed_tests += passed_tests; } std::cout << total_passed_tests * 100 / (kIterations * kTestSizes * kTestSizes) << "% of tests passed." << std::endl; return 0; } <|endoftext|>
<commit_before>#include "SoundService.hpp" #include "Resource.hpp" #include "Log.hpp" namespace Core { SoundService::SoundService() : mEngineObj(NULL), mEngine(NULL), mOutputMixObj(NULL), mBGMPlayerObj(NULL), mBGMPlayer(NULL), mBGMPlayerSeek(NULL), mPlayerObj(), mPlayer(), mPlayerQueue(), mSounds(), mSoundCount(0) { LOGI("Creating SoundService."); } SoundService::~SoundService() { LOGI("Destroying SoundService."); for (int32_t i = 0; i < mSoundCount; ++i) { delete mSounds[i]; mSoundCount = 0; } delete mPlaylist; } Status SoundService::Start() { LOGI("Starting SoundService."); SLresult lRes; const SLuint32 lEngineMixIIDCount = 0; const SLInterfaceID lEngineMixIIDs[] = {}; const SLboolean lEngineMixReqs[] = {}; const SLuint32 lOutputMixIIDCount = 0; const SLInterfaceID lOutputMixIIDs[] = {}; const SLboolean lOutputMixReqs[] = {}; // Creates OpenSL ES engine and dumps its capabilities. lRes = slCreateEngine(&mEngineObj, 0, NULL, lEngineMixIIDCount, lEngineMixIIDs, lEngineMixReqs); if (lRes != SL_RESULT_SUCCESS) { goto ERROR; } lRes = (*mEngineObj)->Realize(mEngineObj,SL_BOOLEAN_FALSE); if (lRes != SL_RESULT_SUCCESS) { goto ERROR; } lRes = (*mEngineObj)->GetInterface(mEngineObj, SL_IID_ENGINE, &mEngine); if (lRes != SL_RESULT_SUCCESS) { goto ERROR; } // Creates audio output. lRes = (*mEngine)->CreateOutputMix(mEngine, &mOutputMixObj, lOutputMixIIDCount, lOutputMixIIDs, lOutputMixReqs); lRes = (*mOutputMixObj)->Realize(mOutputMixObj, SL_BOOLEAN_FALSE); // Set-up sound player. if (StartSoundPlayer() != STATUS_OK) { goto ERROR; } // Loads resources for (int32_t i = 0; i < mSoundCount; ++i) { if (mSounds[i]->Load() != STATUS_OK) { goto ERROR; } } return STATUS_OK; ERROR: LOGE("Error while starting SoundService"); Stop(); return STATUS_KO; } void SoundService::Stop() { LOGI("Stopping SoundService."); // Stops and destroys BGM player. StopBGM(); // Destroys sound player. for(int i = 0; i < MAX_SOUNDS; i++) { if (mPlayerObj[i] != NULL) { (*mPlayerObj[i])->Destroy(mPlayerObj[i]); mPlayerObj[i] = NULL; mPlayer[i] = NULL; mPlayerQueue[i] = NULL; } } // Destroys audio output and engine. if (mOutputMixObj != NULL) { (*mOutputMixObj)->Destroy(mOutputMixObj); mOutputMixObj = NULL; } if (mEngineObj != NULL) { (*mEngineObj)->Destroy(mEngineObj); mEngineObj = NULL; mEngine = NULL; } // Frees sound resources. for (int32_t i = 0; i < mSoundCount; ++i) { mSounds[i]->Unload(); } } Status SoundService::StartSoundPlayer() { LOGI("Starting sound player."); SLresult lRes; // Set-up sound audio source. SLDataLocator_AndroidSimpleBufferQueue lDataLocatorIn; lDataLocatorIn.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; // At most one buffer in the queue. lDataLocatorIn.numBuffers = 1; SLDataFormat_PCM lDataFormat; lDataFormat.formatType = SL_DATAFORMAT_PCM; lDataFormat.numChannels = 1; // Mono sound. lDataFormat.samplesPerSec = SL_SAMPLINGRATE_11_025; lDataFormat.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; lDataFormat.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; lDataFormat.channelMask = SL_SPEAKER_FRONT_CENTER; lDataFormat.endianness = SL_BYTEORDER_LITTLEENDIAN; SLDataSource lDataSource; lDataSource.pLocator = &lDataLocatorIn; lDataSource.pFormat = &lDataFormat; SLDataLocator_OutputMix lDataLocatorOut; lDataLocatorOut.locatorType = SL_DATALOCATOR_OUTPUTMIX; lDataLocatorOut.outputMix = mOutputMixObj; SLDataSink lDataSink; lDataSink.pLocator = &lDataLocatorOut; lDataSink.pFormat = NULL; // Creates the sounds player and retrieves its interfaces. const SLuint32 lSoundPlayerIIDCount = 1; const SLInterfaceID lSoundPlayerIIDs[] = { SL_IID_BUFFERQUEUE }; const SLboolean lSoundPlayerReqs[] = { SL_BOOLEAN_TRUE }; for(int i = 0; i < MAX_SOUNDS; i++){ lRes = (*mEngine)->CreateAudioPlayer(mEngine, &mPlayerObj[i], &lDataSource, &lDataSink, lSoundPlayerIIDCount, lSoundPlayerIIDs, lSoundPlayerReqs); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mPlayerObj[i])->Realize(mPlayerObj[i], SL_BOOLEAN_FALSE); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mPlayerObj[i])->GetInterface(mPlayerObj[i], SL_IID_PLAY, &mPlayer[i]); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mPlayerObj[i])->GetInterface(mPlayerObj[i], SL_IID_BUFFERQUEUE, &mPlayerQueue[i]); if (lRes != SL_RESULT_SUCCESS) goto ERROR; // Starts the sound player. Nothing can be heard while the // sound queue remains empty. lRes = (*mPlayer[i])->SetPlayState(mPlayer[i], SL_PLAYSTATE_PLAYING); if (lRes != SL_RESULT_SUCCESS) goto ERROR; } return STATUS_OK; ERROR: LOGE("Error while starting SoundPlayer"); return STATUS_KO; } Status SoundService::PlayBGMPlaylist(const char* pPath) { SLresult lRes; mPlaylist = new Playlist(pPath); SLDataLocator_AndroidSimpleBufferQueue lDataLocatorIn; lDataLocatorIn.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; // At most one buffer in the queue. lDataLocatorIn.numBuffers = 1; SLDataFormat_PCM lDataFormat; lDataFormat.formatType = SL_DATAFORMAT_PCM; lDataFormat.numChannels = 1; // Mono sound. lDataFormat.samplesPerSec = SL_SAMPLINGRATE_11_025; lDataFormat.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; lDataFormat.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; lDataFormat.channelMask = SL_SPEAKER_FRONT_CENTER; lDataFormat.endianness = SL_BYTEORDER_LITTLEENDIAN; // Here you can set USB settings. SLDataSource lDataSource; lDataSource.pLocator = &lDataLocatorIn; lDataSource.pFormat = &lDataFormat; SLDataLocator_OutputMix lDataLocatorOut; lDataLocatorOut.locatorType = SL_DATALOCATOR_OUTPUTMIX; lDataLocatorOut.outputMix = mOutputMixObj; SLDataSink lDataSink; lDataSink.pLocator = &lDataLocatorOut; lDataSink.pFormat = NULL; // Creates BGM player and retrieves its interfaces. const SLuint32 lBGMPlayerIIDCount = 2; const SLInterfaceID lBGMPlayerIIDs[] = { SL_IID_BUFFERQUEUE, SL_IID_PLAY}; const SLboolean lBGMPlayerReqs[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; lRes = (*mEngine)->CreateAudioPlayer(mEngine, &mBGMPlayerObj, &lDataSource, &lDataSink, lBGMPlayerIIDCount, lBGMPlayerIIDs, lBGMPlayerReqs); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mBGMPlayerObj)->Realize(mBGMPlayerObj, SL_BOOLEAN_FALSE); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mBGMPlayerObj)->GetInterface(mBGMPlayerObj, SL_IID_PLAY, &mBGMPlayer); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mBGMPlayerObj)->GetInterface(mBGMPlayerObj, SL_IID_BUFFERQUEUE, &mBGMPlayerQueue); if (lRes != SL_RESULT_SUCCESS) goto ERROR; // Enables looping and starts playing. lRes = (*mBGMPlayerQueue)->RegisterCallback(mBGMPlayerQueue, bqPlayerCallback, (void*)mPlaylist); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mBGMPlayer)->SetPlayState(mBGMPlayer, SL_PLAYSTATE_PLAYING); if (lRes != SL_RESULT_SUCCESS) goto ERROR; Sound *snd; snd = mPlaylist->GetSound(); (*mBGMPlayerQueue)->Enqueue(mBGMPlayerQueue, snd->GetPCMData(), snd->GetPCMLength()); return STATUS_OK; ERROR: return STATUS_KO; } void SoundService::StopBGM() { if (mBGMPlayer != NULL) { SLuint32 lBGMPlayerState; (*mBGMPlayerObj)->GetState(mBGMPlayerObj,&lBGMPlayerState); if (lBGMPlayerState == SL_OBJECT_STATE_REALIZED) { (*mBGMPlayer)->SetPlayState(mBGMPlayer,SL_PLAYSTATE_PAUSED); (*mBGMPlayerObj)->Destroy(mBGMPlayerObj); mBGMPlayerObj = NULL; mBGMPlayer = NULL; mBGMPlayerSeek = NULL; } } } Sound* SoundService::RegisterSound(const char* pPath) { // Finds out if texture already loaded. for (int32_t i = 0; i < mSoundCount; ++i) { if (strcmp(pPath, mSounds[i]->GetPath()) == 0) { return mSounds[i]; } } Sound* lSound = new Sound(pPath); mSounds[mSoundCount++] = lSound; return lSound; } void SoundService::PlaySound(Sound* pSound) { SLresult lRes; SLuint32 lPlayerState; SLBufferQueueState state; int i; int16_t* lBuffer; off_t lLength; for(i = 0; i < MAX_SOUNDS; i++) { lRes = (*(mPlayerQueue[i]))->GetState(mPlayerQueue[i], &state); if (lRes != SL_RESULT_SUCCESS) goto ERROR; if(state.count == 0) break; } lBuffer = (int16_t*) pSound->GetPCMData(); lLength = pSound->GetPCMLength(); // Removes any sound from the queue. lRes = (*mPlayerQueue[i])->Clear(mPlayerQueue[i]); if (lRes != SL_RESULT_SUCCESS) goto ERROR; // Plays the new sound. lRes = (*mPlayerQueue[i])->Enqueue(mPlayerQueue[i], lBuffer, lLength); if (lRes != SL_RESULT_SUCCESS) goto ERROR; return; ERROR: LOGE("Error trying to play sound"); } void SoundService::bqPlayerCallback(SLBufferQueueItf bq, void *context){ LOGI("BGM Track done. Loading next one"); Sound* snd = ((Playlist*)context)->Next(); (*bq)->Enqueue(bq, snd->GetPCMData(), snd->GetPCMLength()); } void SoundService::SetBGMState(SLuint32 state) { (*mBGMPlayer)->SetPlayState(mBGMPlayer, state); } void SoundService::SetSFXState(SLuint32 state) { for(int i = 0; i < MAX_SOUNDS; i++){ (*mPlayer[i])->SetPlayState(mPlayer[i], state); } } void SoundService::PauseBGM() { SetBGMState(SL_PLAYSTATE_PAUSED); } void SoundService::PauseSFX() { SetSFXState(SL_PLAYSTATE_PAUSED); } void SoundService::PauseAll() { PauseBGM(); PauseSFX(); } void SoundService::ResumeBGM() { SetBGMState(SL_PLAYSTATE_PLAYING); } void SoundService::ResumeSFX() { SetSFXState(SL_PLAYSTATE_PLAYING); } void SoundService::ResumeAll() { ResumeBGM(); ResumeSFX(); } } <commit_msg>Fixed BGMPlayerSeek compile error<commit_after>#include "SoundService.hpp" #include "Resource.hpp" #include "Log.hpp" namespace Core { SoundService::SoundService() : mEngineObj(NULL), mEngine(NULL), mOutputMixObj(NULL), mBGMPlayerObj(NULL), mBGMPlayer(NULL), mPlayerObj(), mPlayer(), mPlayerQueue(), mSounds(), mSoundCount(0) { LOGI("Creating SoundService."); } SoundService::~SoundService() { LOGI("Destroying SoundService."); for (int32_t i = 0; i < mSoundCount; ++i) { delete mSounds[i]; mSoundCount = 0; } delete mPlaylist; } Status SoundService::Start() { LOGI("Starting SoundService."); SLresult lRes; const SLuint32 lEngineMixIIDCount = 0; const SLInterfaceID lEngineMixIIDs[] = {}; const SLboolean lEngineMixReqs[] = {}; const SLuint32 lOutputMixIIDCount = 0; const SLInterfaceID lOutputMixIIDs[] = {}; const SLboolean lOutputMixReqs[] = {}; // Creates OpenSL ES engine and dumps its capabilities. lRes = slCreateEngine(&mEngineObj, 0, NULL, lEngineMixIIDCount, lEngineMixIIDs, lEngineMixReqs); if (lRes != SL_RESULT_SUCCESS) { goto ERROR; } lRes = (*mEngineObj)->Realize(mEngineObj,SL_BOOLEAN_FALSE); if (lRes != SL_RESULT_SUCCESS) { goto ERROR; } lRes = (*mEngineObj)->GetInterface(mEngineObj, SL_IID_ENGINE, &mEngine); if (lRes != SL_RESULT_SUCCESS) { goto ERROR; } // Creates audio output. lRes = (*mEngine)->CreateOutputMix(mEngine, &mOutputMixObj, lOutputMixIIDCount, lOutputMixIIDs, lOutputMixReqs); lRes = (*mOutputMixObj)->Realize(mOutputMixObj, SL_BOOLEAN_FALSE); // Set-up sound player. if (StartSoundPlayer() != STATUS_OK) { goto ERROR; } // Loads resources for (int32_t i = 0; i < mSoundCount; ++i) { if (mSounds[i]->Load() != STATUS_OK) { goto ERROR; } } return STATUS_OK; ERROR: LOGE("Error while starting SoundService"); Stop(); return STATUS_KO; } void SoundService::Stop() { LOGI("Stopping SoundService."); // Stops and destroys BGM player. StopBGM(); // Destroys sound player. for(int i = 0; i < MAX_SOUNDS; i++) { if (mPlayerObj[i] != NULL) { (*mPlayerObj[i])->Destroy(mPlayerObj[i]); mPlayerObj[i] = NULL; mPlayer[i] = NULL; mPlayerQueue[i] = NULL; } } // Destroys audio output and engine. if (mOutputMixObj != NULL) { (*mOutputMixObj)->Destroy(mOutputMixObj); mOutputMixObj = NULL; } if (mEngineObj != NULL) { (*mEngineObj)->Destroy(mEngineObj); mEngineObj = NULL; mEngine = NULL; } // Frees sound resources. for (int32_t i = 0; i < mSoundCount; ++i) { mSounds[i]->Unload(); } } Status SoundService::StartSoundPlayer() { LOGI("Starting sound player."); SLresult lRes; // Set-up sound audio source. SLDataLocator_AndroidSimpleBufferQueue lDataLocatorIn; lDataLocatorIn.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; // At most one buffer in the queue. lDataLocatorIn.numBuffers = 1; SLDataFormat_PCM lDataFormat; lDataFormat.formatType = SL_DATAFORMAT_PCM; lDataFormat.numChannels = 1; // Mono sound. lDataFormat.samplesPerSec = SL_SAMPLINGRATE_11_025; lDataFormat.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; lDataFormat.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; lDataFormat.channelMask = SL_SPEAKER_FRONT_CENTER; lDataFormat.endianness = SL_BYTEORDER_LITTLEENDIAN; SLDataSource lDataSource; lDataSource.pLocator = &lDataLocatorIn; lDataSource.pFormat = &lDataFormat; SLDataLocator_OutputMix lDataLocatorOut; lDataLocatorOut.locatorType = SL_DATALOCATOR_OUTPUTMIX; lDataLocatorOut.outputMix = mOutputMixObj; SLDataSink lDataSink; lDataSink.pLocator = &lDataLocatorOut; lDataSink.pFormat = NULL; // Creates the sounds player and retrieves its interfaces. const SLuint32 lSoundPlayerIIDCount = 1; const SLInterfaceID lSoundPlayerIIDs[] = { SL_IID_BUFFERQUEUE }; const SLboolean lSoundPlayerReqs[] = { SL_BOOLEAN_TRUE }; for(int i = 0; i < MAX_SOUNDS; i++){ lRes = (*mEngine)->CreateAudioPlayer(mEngine, &mPlayerObj[i], &lDataSource, &lDataSink, lSoundPlayerIIDCount, lSoundPlayerIIDs, lSoundPlayerReqs); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mPlayerObj[i])->Realize(mPlayerObj[i], SL_BOOLEAN_FALSE); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mPlayerObj[i])->GetInterface(mPlayerObj[i], SL_IID_PLAY, &mPlayer[i]); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mPlayerObj[i])->GetInterface(mPlayerObj[i], SL_IID_BUFFERQUEUE, &mPlayerQueue[i]); if (lRes != SL_RESULT_SUCCESS) goto ERROR; // Starts the sound player. Nothing can be heard while the // sound queue remains empty. lRes = (*mPlayer[i])->SetPlayState(mPlayer[i], SL_PLAYSTATE_PLAYING); if (lRes != SL_RESULT_SUCCESS) goto ERROR; } return STATUS_OK; ERROR: LOGE("Error while starting SoundPlayer"); return STATUS_KO; } Status SoundService::PlayBGMPlaylist(const char* pPath) { SLresult lRes; mPlaylist = new Playlist(pPath); SLDataLocator_AndroidSimpleBufferQueue lDataLocatorIn; lDataLocatorIn.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; // At most one buffer in the queue. lDataLocatorIn.numBuffers = 1; SLDataFormat_PCM lDataFormat; lDataFormat.formatType = SL_DATAFORMAT_PCM; lDataFormat.numChannels = 1; // Mono sound. lDataFormat.samplesPerSec = SL_SAMPLINGRATE_11_025; lDataFormat.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; lDataFormat.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; lDataFormat.channelMask = SL_SPEAKER_FRONT_CENTER; lDataFormat.endianness = SL_BYTEORDER_LITTLEENDIAN; // Here you can set USB settings. SLDataSource lDataSource; lDataSource.pLocator = &lDataLocatorIn; lDataSource.pFormat = &lDataFormat; SLDataLocator_OutputMix lDataLocatorOut; lDataLocatorOut.locatorType = SL_DATALOCATOR_OUTPUTMIX; lDataLocatorOut.outputMix = mOutputMixObj; SLDataSink lDataSink; lDataSink.pLocator = &lDataLocatorOut; lDataSink.pFormat = NULL; // Creates BGM player and retrieves its interfaces. const SLuint32 lBGMPlayerIIDCount = 2; const SLInterfaceID lBGMPlayerIIDs[] = { SL_IID_BUFFERQUEUE, SL_IID_PLAY}; const SLboolean lBGMPlayerReqs[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; lRes = (*mEngine)->CreateAudioPlayer(mEngine, &mBGMPlayerObj, &lDataSource, &lDataSink, lBGMPlayerIIDCount, lBGMPlayerIIDs, lBGMPlayerReqs); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mBGMPlayerObj)->Realize(mBGMPlayerObj, SL_BOOLEAN_FALSE); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mBGMPlayerObj)->GetInterface(mBGMPlayerObj, SL_IID_PLAY, &mBGMPlayer); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mBGMPlayerObj)->GetInterface(mBGMPlayerObj, SL_IID_BUFFERQUEUE, &mBGMPlayerQueue); if (lRes != SL_RESULT_SUCCESS) goto ERROR; // Enables looping and starts playing. lRes = (*mBGMPlayerQueue)->RegisterCallback(mBGMPlayerQueue, bqPlayerCallback, (void*)mPlaylist); if (lRes != SL_RESULT_SUCCESS) goto ERROR; lRes = (*mBGMPlayer)->SetPlayState(mBGMPlayer, SL_PLAYSTATE_PLAYING); if (lRes != SL_RESULT_SUCCESS) goto ERROR; Sound *snd; snd = mPlaylist->GetSound(); (*mBGMPlayerQueue)->Enqueue(mBGMPlayerQueue, snd->GetPCMData(), snd->GetPCMLength()); return STATUS_OK; ERROR: return STATUS_KO; } void SoundService::StopBGM() { if (mBGMPlayer != NULL) { SLuint32 lBGMPlayerState; (*mBGMPlayerObj)->GetState(mBGMPlayerObj,&lBGMPlayerState); if (lBGMPlayerState == SL_OBJECT_STATE_REALIZED) { (*mBGMPlayer)->SetPlayState(mBGMPlayer,SL_PLAYSTATE_PAUSED); (*mBGMPlayerObj)->Destroy(mBGMPlayerObj); mBGMPlayerObj = NULL; mBGMPlayer = NULL; } } } Sound* SoundService::RegisterSound(const char* pPath) { // Finds out if texture already loaded. for (int32_t i = 0; i < mSoundCount; ++i) { if (strcmp(pPath, mSounds[i]->GetPath()) == 0) { return mSounds[i]; } } Sound* lSound = new Sound(pPath); mSounds[mSoundCount++] = lSound; return lSound; } void SoundService::PlaySound(Sound* pSound) { SLresult lRes; SLuint32 lPlayerState; SLBufferQueueState state; int i; int16_t* lBuffer; off_t lLength; for(i = 0; i < MAX_SOUNDS; i++) { lRes = (*(mPlayerQueue[i]))->GetState(mPlayerQueue[i], &state); if (lRes != SL_RESULT_SUCCESS) goto ERROR; if(state.count == 0) break; } lBuffer = (int16_t*) pSound->GetPCMData(); lLength = pSound->GetPCMLength(); // Removes any sound from the queue. lRes = (*mPlayerQueue[i])->Clear(mPlayerQueue[i]); if (lRes != SL_RESULT_SUCCESS) goto ERROR; // Plays the new sound. lRes = (*mPlayerQueue[i])->Enqueue(mPlayerQueue[i], lBuffer, lLength); if (lRes != SL_RESULT_SUCCESS) goto ERROR; return; ERROR: LOGE("Error trying to play sound"); } void SoundService::bqPlayerCallback(SLBufferQueueItf bq, void *context){ LOGI("BGM Track done. Loading next one"); Sound* snd = ((Playlist*)context)->Next(); (*bq)->Enqueue(bq, snd->GetPCMData(), snd->GetPCMLength()); } void SoundService::SetBGMState(SLuint32 state) { (*mBGMPlayer)->SetPlayState(mBGMPlayer, state); } void SoundService::SetSFXState(SLuint32 state) { for(int i = 0; i < MAX_SOUNDS; i++){ (*mPlayer[i])->SetPlayState(mPlayer[i], state); } } void SoundService::PauseBGM() { SetBGMState(SL_PLAYSTATE_PAUSED); } void SoundService::PauseSFX() { SetSFXState(SL_PLAYSTATE_PAUSED); } void SoundService::PauseAll() { PauseBGM(); PauseSFX(); } void SoundService::ResumeBGM() { SetBGMState(SL_PLAYSTATE_PLAYING); } void SoundService::ResumeSFX() { SetSFXState(SL_PLAYSTATE_PLAYING); } void SoundService::ResumeAll() { ResumeBGM(); ResumeSFX(); } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "itkImageRegionIteratorWithIndex.h" #include "otbGenericRSTransform.h" #include "otbBCOInterpolateImageFunction.h" // MapProjection handler #include "otbWrapperMapProjectionParametersHandler.h" namespace otb { namespace Wrapper { class GeneratePlyFile : public Application { public: /** Standard class typedefs. */ typedef GeneratePlyFile Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(GeneratePlyFile, otb::Application); typedef otb::BCOInterpolateImageFunction<FloatVectorImageType> InterpolatorType; typedef otb::GenericRSTransform<double,3,3> RSTransformType; typedef itk::ImageRegionIteratorWithIndex<FloatVectorImageType> IteratorType; private: GeneratePlyFile(){} void DoInit() { SetName("GeneratePlyFile"); SetDescription("Generate a 3D Ply file from a DEM and a color image."); SetDocName("Ply 3D files generation"); SetDocLongDescription("Generate a 3D Ply file from a DEM and a color image."); SetDocLimitations(" "); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag(Tags::Geometry); AddParameter(ParameterType_InputImage,"indem","The input DEM"); SetParameterDescription("indem", "The input DEM"); AddParameter(ParameterType_Choice,"mode", "Conversion Mode"); AddChoice("mode.dem","DEM"); SetParameterDescription("mode.dem","DEM conversion mode"); AddChoice("mode.3dgrid","3D grid"); SetParameterDescription("mode.3dgrid","3D grid conversion mode"); // Build the Output Map Projection MapProjectionParametersHandler::AddMapProjectionParameters(this, "map"); AddParameter(ParameterType_InputImage,"incolor","The input color image"); SetParameterDescription("incolor", "The input color image"); AddParameter(ParameterType_OutputFilename,"out","The output Ply file"); SetParameterDescription("out","The output Ply file"); // Doc example SetDocExampleParameterValue("indem","image_dem.tif"); SetDocExampleParameterValue("out","out.ply"); SetDocExampleParameterValue("incolor","image_color.tif"); } void DoUpdateParameters() { // Update the UTM zone params MapProjectionParametersHandler::InitializeUTMParameters(this, "incolor", "map"); } void DoExecute() { std::string outfname = GetParameterString("out"); FloatVectorImageType::Pointer demPtr = this->GetParameterImage("indem"); demPtr->Update(); FloatVectorImageType::Pointer colorPtr = this->GetParameterImage("incolor"); // First, find the footprint in the color image IteratorType it(demPtr,demPtr->GetLargestPossibleRegion()); it.GoToBegin(); FloatImageType::IndexType lr, ul; typedef typename FloatImageType::IndexType::IndexValueType IndexValueType; lr.Fill(itk::NumericTraits<IndexValueType>::Zero); ul.Fill(itk::NumericTraits<IndexValueType>::Zero); bool firstLoop = true; RSTransformType::Pointer rsTransform = RSTransformType::New(); RSTransformType::Pointer toMap = RSTransformType::New(); toMap->SetOutputProjectionRef(MapProjectionParametersHandler::GetProjectionRefFromChoice(this, "map")); if(GetParameterString("mode")=="dem") { otbAppLogINFO("DEM mode"); rsTransform->SetInputProjectionRef(demPtr->GetProjectionRef()); toMap->SetInputProjectionRef(demPtr->GetProjectionRef()); } rsTransform->SetOutputProjectionRef(colorPtr->GetProjectionRef()); rsTransform->SetOutputKeywordList(colorPtr->GetImageKeywordlist()); rsTransform->InstanciateTransform(); toMap->InstanciateTransform(); unsigned long nbValidPoints = 0; // First pass is to find the color footprint while(!it.IsAtEnd()) { RSTransformType::InputPointType dem3dPoint; bool valid = true; if(GetParameterString("mode")=="dem") { FloatImageType::PointType demPoint; demPtr->TransformIndexToPhysicalPoint(it.GetIndex(),demPoint); dem3dPoint[0]=demPoint[0]; dem3dPoint[1]=demPoint[1]; dem3dPoint[2]=it.Get()[0]; if(dem3dPoint[2] <= -32768) { valid=false; } } else { dem3dPoint[0]=it.Get()[0]; dem3dPoint[1]=it.Get()[1]; dem3dPoint[2]=it.Get()[2]; if(it.Get()[4] < 1) { valid = false; } } if(valid) { ++nbValidPoints; RSTransformType::InputPointType color3dPoint = rsTransform->TransformPoint(dem3dPoint); FloatVectorImageType::PointType color2dPoint; color2dPoint[0] = color3dPoint[0]; color2dPoint[1] = color3dPoint[1]; FloatVectorImageType::IndexType color2dIndex; colorPtr->TransformPhysicalPointToIndex(color2dPoint,color2dIndex); // std::cout<<"DEM point: "<<dem3dPoint<<std::endl; // std::cout<<"Color point: "<<color3dPoint<<std::endl; // std::cout<<"Color index: "<<color2dIndex<<std::endl; // std::cout<<"Valid: "<<valid<<std::endl; // std::cout<<"Flag: "<<it.Get()[4]<<std::endl; if(colorPtr->GetLargestPossibleRegion().IsInside(color2dIndex)) { if(firstLoop) { lr = color2dIndex; ul = color2dIndex; firstLoop = false; } else { ul[0] = std::min(ul[0],color2dIndex[0]); ul[1] = std::min(ul[1],color2dIndex[1]); lr[0] = std::max(lr[0],color2dIndex[0]); lr[1] = std::max(lr[1],color2dIndex[1]); } } } ++it; } FloatVectorImageType::RegionType region; region.SetIndex(ul); FloatVectorImageType::SizeType size; size[0] = static_cast<unsigned int>(lr[0]-ul[0]); size[1] = static_cast<unsigned int>(lr[1]-ul[1]); region.SetSize(size); otbAppLogINFO(<<"Number of valid points: "<<nbValidPoints); otbAppLogINFO(<<"Color region estimated: "<<region); // Now read the appropriate color region colorPtr->SetRequestedRegion(region); colorPtr->Update(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage(colorPtr); // Start writing ply file std::ofstream ofs(outfname.c_str()); std::ostringstream oss; oss<<std::fixed; oss.precision(12); ofs<<"ply"<<std::endl; ofs<<"format ascii 1.0"<<std::endl; ofs<<"element vertex "<<nbValidPoints<<std::endl; ofs<<"property float x"<<std::endl; ofs<<"property float y"<<std::endl; ofs<<"property float z"<<std::endl; ofs<<"property uchar red"<<std::endl; ofs<<"property uchar green"<<std::endl; ofs<<"property uchar blue"<<std::endl; ofs<<"end_header"<<std::endl; // And loop again to generate the ply file it.GoToBegin(); while(!it.IsAtEnd()) { RSTransformType::InputPointType dem3dPoint; bool valid = true; if(GetParameterString("mode")=="dem") { FloatImageType::PointType demPoint; demPtr->TransformIndexToPhysicalPoint(it.GetIndex(),demPoint); dem3dPoint[0]=demPoint[0]; dem3dPoint[1]=demPoint[1]; dem3dPoint[2]=it.Get()[0]; valid =(dem3dPoint[2] > -32768); } else { dem3dPoint[0]=it.Get()[0]; dem3dPoint[1]=it.Get()[1]; dem3dPoint[2]=it.Get()[2]; valid = (it.Get()[4]>0); } if(valid) { RSTransformType::InputPointType color3dPoint = rsTransform->TransformPoint(dem3dPoint); FloatVectorImageType::PointType color2dPoint; color2dPoint[0] = color3dPoint[0]; color2dPoint[1] = color3dPoint[1]; FloatVectorImageType::PixelType color = interpolator->Evaluate(color2dPoint); double red,green,blue; if(color.Size() == 4) { red = color[0]; green = (0.9 * color[1] + 0.1 * color[3]); blue = color[2]; } else { red = color[0]; green = red; blue = red; } // Clamp red = (red>255?255:(red<0?0:red)); green = (green>255?255:(green<0?0:green)); blue = (blue>255?255:(blue<0?0:blue)); RSTransformType::InputPointType map3dPoint; map3dPoint = toMap->TransformPoint(dem3dPoint); oss.str(""); oss<<map3dPoint[0]<<" "<<map3dPoint[1]<<" "<<map3dPoint[2]<<" "<<(int)red<<" "<<(int)green<<" " <<(int)blue<<std::endl; std::string tmp = oss.str(); // std::replace(tmp.begin(),tmp.end(),'.',','); ofs<<tmp; } ++it; } } }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::GeneratePlyFile) <commit_msg>COMP: typename outside template for gcc4.6 and MSVC compiler<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "itkImageRegionIteratorWithIndex.h" #include "otbGenericRSTransform.h" #include "otbBCOInterpolateImageFunction.h" // MapProjection handler #include "otbWrapperMapProjectionParametersHandler.h" namespace otb { namespace Wrapper { class GeneratePlyFile : public Application { public: /** Standard class typedefs. */ typedef GeneratePlyFile Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(GeneratePlyFile, otb::Application); typedef otb::BCOInterpolateImageFunction<FloatVectorImageType> InterpolatorType; typedef otb::GenericRSTransform<double,3,3> RSTransformType; typedef itk::ImageRegionIteratorWithIndex<FloatVectorImageType> IteratorType; private: GeneratePlyFile(){} void DoInit() { SetName("GeneratePlyFile"); SetDescription("Generate a 3D Ply file from a DEM and a color image."); SetDocName("Ply 3D files generation"); SetDocLongDescription("Generate a 3D Ply file from a DEM and a color image."); SetDocLimitations(" "); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag(Tags::Geometry); AddParameter(ParameterType_InputImage,"indem","The input DEM"); SetParameterDescription("indem", "The input DEM"); AddParameter(ParameterType_Choice,"mode", "Conversion Mode"); AddChoice("mode.dem","DEM"); SetParameterDescription("mode.dem","DEM conversion mode"); AddChoice("mode.3dgrid","3D grid"); SetParameterDescription("mode.3dgrid","3D grid conversion mode"); // Build the Output Map Projection MapProjectionParametersHandler::AddMapProjectionParameters(this, "map"); AddParameter(ParameterType_InputImage,"incolor","The input color image"); SetParameterDescription("incolor", "The input color image"); AddParameter(ParameterType_OutputFilename,"out","The output Ply file"); SetParameterDescription("out","The output Ply file"); // Doc example SetDocExampleParameterValue("indem","image_dem.tif"); SetDocExampleParameterValue("out","out.ply"); SetDocExampleParameterValue("incolor","image_color.tif"); } void DoUpdateParameters() { // Update the UTM zone params MapProjectionParametersHandler::InitializeUTMParameters(this, "incolor", "map"); } void DoExecute() { std::string outfname = GetParameterString("out"); FloatVectorImageType::Pointer demPtr = this->GetParameterImage("indem"); demPtr->Update(); FloatVectorImageType::Pointer colorPtr = this->GetParameterImage("incolor"); // First, find the footprint in the color image IteratorType it(demPtr,demPtr->GetLargestPossibleRegion()); it.GoToBegin(); FloatImageType::IndexType lr, ul; typedef FloatImageType::IndexType::IndexValueType IndexValueType; lr.Fill(itk::NumericTraits<IndexValueType>::Zero); ul.Fill(itk::NumericTraits<IndexValueType>::Zero); bool firstLoop = true; RSTransformType::Pointer rsTransform = RSTransformType::New(); RSTransformType::Pointer toMap = RSTransformType::New(); toMap->SetOutputProjectionRef(MapProjectionParametersHandler::GetProjectionRefFromChoice(this, "map")); if(GetParameterString("mode")=="dem") { otbAppLogINFO("DEM mode"); rsTransform->SetInputProjectionRef(demPtr->GetProjectionRef()); toMap->SetInputProjectionRef(demPtr->GetProjectionRef()); } rsTransform->SetOutputProjectionRef(colorPtr->GetProjectionRef()); rsTransform->SetOutputKeywordList(colorPtr->GetImageKeywordlist()); rsTransform->InstanciateTransform(); toMap->InstanciateTransform(); unsigned long nbValidPoints = 0; // First pass is to find the color footprint while(!it.IsAtEnd()) { RSTransformType::InputPointType dem3dPoint; bool valid = true; if(GetParameterString("mode")=="dem") { FloatImageType::PointType demPoint; demPtr->TransformIndexToPhysicalPoint(it.GetIndex(),demPoint); dem3dPoint[0]=demPoint[0]; dem3dPoint[1]=demPoint[1]; dem3dPoint[2]=it.Get()[0]; if(dem3dPoint[2] <= -32768) { valid=false; } } else { dem3dPoint[0]=it.Get()[0]; dem3dPoint[1]=it.Get()[1]; dem3dPoint[2]=it.Get()[2]; if(it.Get()[4] < 1) { valid = false; } } if(valid) { ++nbValidPoints; RSTransformType::InputPointType color3dPoint = rsTransform->TransformPoint(dem3dPoint); FloatVectorImageType::PointType color2dPoint; color2dPoint[0] = color3dPoint[0]; color2dPoint[1] = color3dPoint[1]; FloatVectorImageType::IndexType color2dIndex; colorPtr->TransformPhysicalPointToIndex(color2dPoint,color2dIndex); // std::cout<<"DEM point: "<<dem3dPoint<<std::endl; // std::cout<<"Color point: "<<color3dPoint<<std::endl; // std::cout<<"Color index: "<<color2dIndex<<std::endl; // std::cout<<"Valid: "<<valid<<std::endl; // std::cout<<"Flag: "<<it.Get()[4]<<std::endl; if(colorPtr->GetLargestPossibleRegion().IsInside(color2dIndex)) { if(firstLoop) { lr = color2dIndex; ul = color2dIndex; firstLoop = false; } else { ul[0] = std::min(ul[0],color2dIndex[0]); ul[1] = std::min(ul[1],color2dIndex[1]); lr[0] = std::max(lr[0],color2dIndex[0]); lr[1] = std::max(lr[1],color2dIndex[1]); } } } ++it; } FloatVectorImageType::RegionType region; region.SetIndex(ul); FloatVectorImageType::SizeType size; size[0] = static_cast<unsigned int>(lr[0]-ul[0]); size[1] = static_cast<unsigned int>(lr[1]-ul[1]); region.SetSize(size); otbAppLogINFO(<<"Number of valid points: "<<nbValidPoints); otbAppLogINFO(<<"Color region estimated: "<<region); // Now read the appropriate color region colorPtr->SetRequestedRegion(region); colorPtr->Update(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage(colorPtr); // Start writing ply file std::ofstream ofs(outfname.c_str()); std::ostringstream oss; oss<<std::fixed; oss.precision(12); ofs<<"ply"<<std::endl; ofs<<"format ascii 1.0"<<std::endl; ofs<<"element vertex "<<nbValidPoints<<std::endl; ofs<<"property float x"<<std::endl; ofs<<"property float y"<<std::endl; ofs<<"property float z"<<std::endl; ofs<<"property uchar red"<<std::endl; ofs<<"property uchar green"<<std::endl; ofs<<"property uchar blue"<<std::endl; ofs<<"end_header"<<std::endl; // And loop again to generate the ply file it.GoToBegin(); while(!it.IsAtEnd()) { RSTransformType::InputPointType dem3dPoint; bool valid = true; if(GetParameterString("mode")=="dem") { FloatImageType::PointType demPoint; demPtr->TransformIndexToPhysicalPoint(it.GetIndex(),demPoint); dem3dPoint[0]=demPoint[0]; dem3dPoint[1]=demPoint[1]; dem3dPoint[2]=it.Get()[0]; valid =(dem3dPoint[2] > -32768); } else { dem3dPoint[0]=it.Get()[0]; dem3dPoint[1]=it.Get()[1]; dem3dPoint[2]=it.Get()[2]; valid = (it.Get()[4]>0); } if(valid) { RSTransformType::InputPointType color3dPoint = rsTransform->TransformPoint(dem3dPoint); FloatVectorImageType::PointType color2dPoint; color2dPoint[0] = color3dPoint[0]; color2dPoint[1] = color3dPoint[1]; FloatVectorImageType::PixelType color = interpolator->Evaluate(color2dPoint); double red,green,blue; if(color.Size() == 4) { red = color[0]; green = (0.9 * color[1] + 0.1 * color[3]); blue = color[2]; } else { red = color[0]; green = red; blue = red; } // Clamp red = (red>255?255:(red<0?0:red)); green = (green>255?255:(green<0?0:green)); blue = (blue>255?255:(blue<0?0:blue)); RSTransformType::InputPointType map3dPoint; map3dPoint = toMap->TransformPoint(dem3dPoint); oss.str(""); oss<<map3dPoint[0]<<" "<<map3dPoint[1]<<" "<<map3dPoint[2]<<" "<<(int)red<<" "<<(int)green<<" " <<(int)blue<<std::endl; std::string tmp = oss.str(); // std::replace(tmp.begin(),tmp.end(),'.',','); ofs<<tmp; } ++it; } } }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::GeneratePlyFile) <|endoftext|>
<commit_before>/* * This audio sample firstly makes use of the audio::DelayNode, but also demonstrates some more complex methods of control, * like feedback and controlling an audio::Param with other audio::Node's. * * author: Richard Eakin (2014) */ #include "cinder/app/AppNative.h" #include "cinder/app/RendererGl.h" #include "cinder/Rand.h" #include "cinder/Perlin.h" #include "cinder/gl/GlslProg.h" #include "cinder/Timeline.h" #include "cinder/Log.h" #include "cinder/audio/Context.h" #include "cinder/audio/GenNode.h" #include "cinder/audio/NodeEffects.h" #include "cinder/audio/Utilities.h" #include "cinder/gl/VboMesh.h" #include "Resources.h" const float MAX_VOLUME = 0.6f; const size_t MAX_SPLASHES = 200; const float MAX_RADIUS = 300; const float MAX_PITCH_MIDI = 80; const float MIN_PITCH_MIDI = 40; using namespace ci; using namespace ci::app; using namespace std; struct Splash { vec2 mCenter; vec3 mColorHsv; Anim<float> mRadius, mAlpha; }; class DelayFeedback : public AppNative { public: void prepareSettings( Settings *settings ); void setup(); void mouseDrag( MouseEvent event ) override; void mouseUp( MouseEvent event ) override; void keyDown( KeyEvent event ) override; void update(); void draw(); void setVariableDelayMod(); void addSplash( const vec2 &pos ); float quantizePitch( const vec2 &pos ); void loadMesh(); void loadGlsl(); audio::GenOscNodeRef mOsc; audio::DelayNodeRef mDelay; audio::GainNodeRef mGain; std::list<Splash> mSplashes; Perlin mPerlin; gl::GlslProgRef mGlsl; gl::VboMeshRef mMesh; }; void DelayFeedback::prepareSettings( Settings *settings ) { settings->setWindowPos( 200, 200 ); settings->setWindowSize( 1000, 800 ); } void DelayFeedback::setup() { loadGlsl(); loadMesh(); gl::enableAlphaBlending(); // The basic audio::Node's used here are an oscillator with a triangle waveform, a gain, and a delay. // The complexity in the sound comes from how they are connected and controlled. auto ctx = audio::master(); mOsc = ctx->makeNode( new audio::GenOscNode ); mGain = ctx->makeNode( new audio::GainNode( 0 ) ); mDelay = ctx->makeNode( new audio::DelayNode ); mOsc->setWaveform( audio::WaveformType::TRIANGLE ); // The Delay's length Param is itself controlled with Node's, which is configured next. setVariableDelayMod(); // Now we connect up the Node's so that the signal immediately reaches the Context's OutputNode, but it also // feedback in a cycle to create an echo. To control the level of feedback and prevent ringing, a one-off GainNode // is used with a value of 0.5, which gives a fairly natural sounding decay. auto feedbackGain = audio::master()->makeNode( new audio::GainNode( 0.5f ) ); feedbackGain->setName( "FeedbackGain" ); mOsc >> mGain >> ctx->getOutput(); mGain >> mDelay >> feedbackGain >> mDelay >> ctx->getOutput(); mOsc->enable(); ctx->enable(); console() << "--------- context audio graph: --------------------" << endl; console() << ctx->printGraphToString(); console() << "---------------------------------------------------" << endl; } // This method adds a low-frequency oscillator to the delay length, which makes a 'flanging' effect. void DelayFeedback::setVariableDelayMod() { mDelay->setMaxDelaySeconds( 2 ); auto ctx = audio::master(); auto osc = ctx->makeNode( new audio::GenSineNode( 0.00113f, audio::Node::Format().autoEnable() ) ); auto mul = ctx->makeNode( new audio::GainNode( 0.3f ) ); auto add = ctx->makeNode( new audio::AddNode( 0.343f ) ); osc >> mul >> add; mDelay->getParamDelaySeconds()->setProcessor( add ); } void DelayFeedback::addSplash( const vec2 &pos ) { mSplashes.push_back( Splash() ); auto &splash = mSplashes.back(); splash.mCenter = pos; splash.mAlpha = 1; float radiusMin = ( 1 - (float)pos.y / (float)getWindowHeight() ) * MAX_RADIUS / 2; splash.mRadius = randFloat( radiusMin, 30 ); float endRadius = randFloat( MAX_RADIUS * 0.9f, MAX_RADIUS ); timeline().apply( &splash.mRadius, endRadius, 7, EaseOutExpo() ); timeline().apply( &splash.mAlpha, 0.0f, 7 ); float h = math<float>::min( 1, mPerlin.fBm( normalize( pos ) ) * 7 ); splash.mColorHsv = vec3( fabsf( h ), 1, 1 ); } // returns a quantized pitch (in hertz) within the lydian dominant scale float DelayFeedback::quantizePitch( const vec2 &pos ) { const size_t scaleLength = 7; float scale[scaleLength] = { 0, 2, 4, 6, 7, 9, 10 }; int pitchMidi = lroundf( lmap( pos.x, 0.0f, (float)getWindowWidth(), MIN_PITCH_MIDI, MAX_PITCH_MIDI ) ); bool quantized = false; while( ! quantized ) { int note = pitchMidi % 12; for( size_t i = 0; i < scaleLength; i++ ) { if( note == scale[i] ) { quantized = true; break; } } if( ! quantized ) pitchMidi--; } return audio::midiToFreq( pitchMidi ); } void DelayFeedback::mouseDrag( MouseEvent event ) { float freq = quantizePitch( event.getPos() ); float gain = 1.0f - (float)event.getPos().y / (float)getWindowHeight(); gain *= MAX_VOLUME; mOsc->getParamFreq()->applyRamp( freq, 0.04f ); mGain->getParam()->applyRamp( gain, 0.1f ); addSplash( event.getPos() ); } void DelayFeedback::mouseUp( MouseEvent event ) { mGain->getParam()->applyRamp( 0, 1.5, audio::Param::Options().rampFn( &audio::rampOutQuad ) ); } void DelayFeedback::keyDown( KeyEvent event ) { if( event.getChar() == 's' ) loadGlsl(); if( event.getChar() == 'f' ) setFullScreen( ! isFullScreen() ); } void DelayFeedback::update() { // trim splashes if( mSplashes.size() > MAX_SPLASHES ) { size_t trimCount = mSplashes.size() - MAX_SPLASHES; for( size_t i = 0; i < trimCount; i++ ) mSplashes.pop_front(); } } void DelayFeedback::draw() { gl::clear(); if( ! mGlsl || ! mMesh ) return; gl::ScopedGlslProg glslScope( mGlsl ); for( const auto &splash : mSplashes ) { float radiusNormalized = splash.mRadius / MAX_RADIUS; mGlsl->uniform( "uRadius", radiusNormalized ); Color splashColor( CM_HSV, splash.mColorHsv ); gl::color( splashColor.r, splashColor.g, splashColor.b, splash.mAlpha() ); gl::pushModelView(); gl::translate( splash.mCenter ); gl::draw( mMesh ); gl::popModelView(); } } void DelayFeedback::loadMesh() { Rectf boundingBox( - MAX_RADIUS, - MAX_RADIUS, MAX_RADIUS, MAX_RADIUS ); TriMesh mesh( TriMesh::Format().positions( 2 ).texCoords( 2 ) ); mesh.appendVertex( boundingBox.getUpperLeft() ); mesh.appendTexCoord( vec2( -1, -1 ) ); mesh.appendVertex( boundingBox.getLowerLeft() ); mesh.appendTexCoord( vec2( -1, 1 ) ); mesh.appendVertex( boundingBox.getUpperRight() ); mesh.appendTexCoord( vec2( 1, -1 ) ); mesh.appendVertex( boundingBox.getLowerRight() ); mesh.appendTexCoord( vec2( 1, 1 ) ); mesh.appendTriangle( 0, 1, 2 ); mesh.appendTriangle( 2, 1, 3 ); mMesh = gl::VboMesh::create( mesh ); } void DelayFeedback::loadGlsl() { try { mGlsl = gl::GlslProg::create( loadResource( SMOOTH_CIRCLE_GLSL_VERT ), loadResource( SMOOTH_CIRCLE_GLSL_FRAG ) ); } catch( std::exception &exc ) { CI_LOG_E( "failed to load shader, what: " << exc.what() ); } } CINDER_APP_NATIVE( DelayFeedback, RendererGl ) <commit_msg>DelayFeedback sample uses Batch<commit_after>/* * This audio sample firstly makes use of the audio::DelayNode, but also demonstrates some more complex methods of control, * like feedback and controlling an audio::Param with other audio::Node's. * * author: Richard Eakin (2014) */ #include "cinder/app/AppNative.h" #include "cinder/app/RendererGl.h" #include "cinder/Rand.h" #include "cinder/Perlin.h" #include "cinder/gl/GlslProg.h" #include "cinder/Timeline.h" #include "cinder/Log.h" #include "cinder/TriMesh.h" #include "cinder/gl/Batch.h" #include "cinder/audio/Context.h" #include "cinder/audio/GenNode.h" #include "cinder/audio/NodeEffects.h" #include "cinder/audio/Utilities.h" #include "Resources.h" const float MAX_VOLUME = 0.6f; const size_t MAX_SPLASHES = 200; const float MAX_RADIUS = 300; const float MAX_PITCH_MIDI = 80; const float MIN_PITCH_MIDI = 40; using namespace ci; using namespace ci::app; using namespace std; struct Splash { vec2 mCenter; vec3 mColorHsv; Anim<float> mRadius, mAlpha; }; class DelayFeedback : public AppNative { public: void prepareSettings( Settings *settings ); void setup(); void mouseDrag( MouseEvent event ) override; void mouseUp( MouseEvent event ) override; void keyDown( KeyEvent event ) override; void update(); void draw(); void setVariableDelayMod(); void addSplash( const vec2 &pos ); float quantizePitch( const vec2 &pos ); void loadBatch(); audio::GenOscNodeRef mOsc; audio::DelayNodeRef mDelay; audio::GainNodeRef mGain; std::list<Splash> mSplashes; Perlin mPerlin; gl::BatchRef mBatch; }; void DelayFeedback::prepareSettings( Settings *settings ) { settings->setWindowPos( 200, 200 ); settings->setWindowSize( 1000, 800 ); } void DelayFeedback::setup() { loadBatch(); gl::enableAlphaBlending(); // The basic audio::Node's used here are an oscillator with a triangle waveform, a gain, and a delay. // The complexity in the sound comes from how they are connected and controlled. auto ctx = audio::master(); mOsc = ctx->makeNode( new audio::GenOscNode ); mGain = ctx->makeNode( new audio::GainNode( 0 ) ); mDelay = ctx->makeNode( new audio::DelayNode ); mOsc->setWaveform( audio::WaveformType::TRIANGLE ); // The Delay's length Param is itself controlled with Node's, which is configured next. setVariableDelayMod(); // Now we connect up the Node's so that the signal immediately reaches the Context's OutputNode, but it also // feedback in a cycle to create an echo. To control the level of feedback and prevent ringing, a one-off GainNode // is used with a value of 0.5, which gives a fairly natural sounding decay. auto feedbackGain = audio::master()->makeNode( new audio::GainNode( 0.5f ) ); feedbackGain->setName( "FeedbackGain" ); mOsc >> mGain >> ctx->getOutput(); mGain >> mDelay >> feedbackGain >> mDelay >> ctx->getOutput(); mOsc->enable(); ctx->enable(); console() << "--------- context audio graph: --------------------" << endl; console() << ctx->printGraphToString(); console() << "---------------------------------------------------" << endl; } // This method adds a low-frequency oscillator to the delay length, which makes a 'flanging' effect. void DelayFeedback::setVariableDelayMod() { mDelay->setMaxDelaySeconds( 2 ); auto ctx = audio::master(); auto osc = ctx->makeNode( new audio::GenSineNode( 0.00113f, audio::Node::Format().autoEnable() ) ); auto mul = ctx->makeNode( new audio::GainNode( 0.3f ) ); auto add = ctx->makeNode( new audio::AddNode( 0.343f ) ); osc >> mul >> add; mDelay->getParamDelaySeconds()->setProcessor( add ); } void DelayFeedback::addSplash( const vec2 &pos ) { mSplashes.push_back( Splash() ); auto &splash = mSplashes.back(); splash.mCenter = pos; splash.mAlpha = 1; float radiusMin = ( 1 - (float)pos.y / (float)getWindowHeight() ) * MAX_RADIUS / 2; splash.mRadius = randFloat( radiusMin, 30 ); float endRadius = randFloat( MAX_RADIUS * 0.9f, MAX_RADIUS ); timeline().apply( &splash.mRadius, endRadius, 7, EaseOutExpo() ); timeline().apply( &splash.mAlpha, 0.0f, 7 ); float h = math<float>::min( 1, mPerlin.fBm( normalize( pos ) ) * 7 ); splash.mColorHsv = vec3( fabsf( h ), 1, 1 ); } // returns a quantized pitch (in hertz) within the lydian dominant scale float DelayFeedback::quantizePitch( const vec2 &pos ) { const size_t scaleLength = 7; float scale[scaleLength] = { 0, 2, 4, 6, 7, 9, 10 }; int pitchMidi = lroundf( lmap( pos.x, 0.0f, (float)getWindowWidth(), MIN_PITCH_MIDI, MAX_PITCH_MIDI ) ); bool quantized = false; while( ! quantized ) { int note = pitchMidi % 12; for( size_t i = 0; i < scaleLength; i++ ) { if( note == scale[i] ) { quantized = true; break; } } if( ! quantized ) pitchMidi--; } return audio::midiToFreq( pitchMidi ); } void DelayFeedback::mouseDrag( MouseEvent event ) { float freq = quantizePitch( event.getPos() ); float gain = 1.0f - (float)event.getPos().y / (float)getWindowHeight(); gain *= MAX_VOLUME; mOsc->getParamFreq()->applyRamp( freq, 0.04f ); mGain->getParam()->applyRamp( gain, 0.1f ); addSplash( event.getPos() ); } void DelayFeedback::mouseUp( MouseEvent event ) { mGain->getParam()->applyRamp( 0, 1.5, audio::Param::Options().rampFn( &audio::rampOutQuad ) ); } void DelayFeedback::keyDown( KeyEvent event ) { if( event.getChar() == 'f' ) setFullScreen( ! isFullScreen() ); } void DelayFeedback::update() { // trim splashes if( mSplashes.size() > MAX_SPLASHES ) { size_t trimCount = mSplashes.size() - MAX_SPLASHES; for( size_t i = 0; i < trimCount; i++ ) mSplashes.pop_front(); } } void DelayFeedback::draw() { gl::clear(); if( ! mBatch ) return; gl::ScopedGlslProg glslScope( mBatch->getGlslProg() ); for( const auto &splash : mSplashes ) { float radiusNormalized = splash.mRadius / MAX_RADIUS; mBatch->getGlslProg()->uniform( "uRadius", radiusNormalized ); gl::ScopedModelMatrix matrixScope; gl::translate( splash.mCenter ); Color splashColor( CM_HSV, splash.mColorHsv ); gl::color( splashColor.r, splashColor.g, splashColor.b, splash.mAlpha() ); mBatch->draw(); } } void DelayFeedback::loadBatch() { gl::GlslProgRef glsl; try { glsl = gl::GlslProg::create( loadResource( SMOOTH_CIRCLE_GLSL_VERT ), loadResource( SMOOTH_CIRCLE_GLSL_FRAG ) ); } catch( std::exception &exc ) { CI_LOG_E( "failed to load shader, what: " << exc.what() ); return; } Rectf boundingBox( - MAX_RADIUS, - MAX_RADIUS, MAX_RADIUS, MAX_RADIUS ); TriMesh mesh( TriMesh::Format().positions( 2 ).texCoords( 2 ) ); mesh.appendVertex( boundingBox.getUpperLeft() ); mesh.appendTexCoord( vec2( -1, -1 ) ); mesh.appendVertex( boundingBox.getLowerLeft() ); mesh.appendTexCoord( vec2( -1, 1 ) ); mesh.appendVertex( boundingBox.getUpperRight() ); mesh.appendTexCoord( vec2( 1, -1 ) ); mesh.appendVertex( boundingBox.getLowerRight() ); mesh.appendTexCoord( vec2( 1, 1 ) ); mesh.appendTriangle( 0, 1, 2 ); mesh.appendTriangle( 2, 1, 3 ); mBatch = gl::Batch::create( mesh, glsl ); } CINDER_APP_NATIVE( DelayFeedback, RendererGl ) <|endoftext|>
<commit_before>// Copyright (c) 2013, Andre Gaschler, Quirin Fischer // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "FileUtils.h" #include <iostream> namespace boundingmesh { FileFormat getFileFormat(std::string filename) { std::string file_extension = filename.substr(filename.rfind(".") + 1); if (file_extension == "off") return Off; else if (file_extension == "obj") return Obj; else if (file_extension == "stl") return Stl; else if (file_extension == "wrl") return Wrl; else { std::cout << "Detected unsupported file format: " << file_extension << std::endl; return Invalid; } } std::shared_ptr<boundingmesh::Mesh> loadMesh(std::string filename, bool debugOutput) { FileFormat file_format = Invalid; std::shared_ptr<boundingmesh::Mesh> mesh = std::make_shared<boundingmesh::Mesh>(); file_format = getFileFormat(filename); if (file_format == Off) mesh->loadOff(filename); else if (file_format == Obj) mesh->loadObj(filename); else if (file_format == Wrl) mesh->loadWrl(filename, -1, debugOutput); else { std::cout << "Couldn't load mesh from " << filename << std::endl; return NULL; } return mesh; } }<commit_msg>Addressing Issue #11: Unable to open STL files (#14)<commit_after>// Copyright (c) 2013, Andre Gaschler, Quirin Fischer // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "FileUtils.h" #include <iostream> namespace boundingmesh { FileFormat getFileFormat(std::string filename) { std::string file_extension = filename.substr(filename.rfind(".") + 1); if (file_extension == "off") return Off; else if (file_extension == "obj") return Obj; else if (file_extension == "stl") return Stl; else if (file_extension == "wrl") return Wrl; else { std::cout << "Detected unsupported file format: " << file_extension << std::endl; return Invalid; } } std::shared_ptr<boundingmesh::Mesh> loadMesh(std::string filename, bool debugOutput) { FileFormat file_format = Invalid; std::shared_ptr<boundingmesh::Mesh> mesh = std::make_shared<boundingmesh::Mesh>(); file_format = getFileFormat(filename); if (file_format == Off) mesh->loadOff(filename); else if (file_format == Obj) mesh->loadObj(filename); else if (file_format == Wrl) mesh->loadWrl(filename, -1, debugOutput); else if (file_format == Stl) mesh->loadStl(filename); else { std::cout << "Couldn't load mesh from " << filename << std::endl; return NULL; } return mesh; } } <|endoftext|>
<commit_before>#include <shogun/classifier/mkl/MKLClassification.h> #ifdef USE_SVMLIGHT #include <shogun/classifier/svm/SVMLight.h> #endif //USE_SVMLIGHT #include <shogun/classifier/svm/LibSVM.h> using namespace shogun; CMKLClassification::CMKLClassification(CSVM* s) : CMKL(s) { if (!s) { #ifdef USE_SVMLIGHT s=new CSVMLight(); #endif //USE_SVMLIGHT if (!s) s=new CLibSVM(); set_svm(s); } } CMKLClassification::~CMKLClassification() { } float64_t CMKLClassification::compute_sum_alpha() { float64_t suma=0; int32_t nsv=svm->get_num_support_vectors(); for (int32_t i=0; i<nsv; i++) suma+=CMath::abs(svm->get_alpha(i)); return suma; } void CMKLClassification::init_training() { ASSERT(m_labels && m_labels->get_num_labels() && m_labels->get_label_type() == LT_BINARY) } <commit_msg>proper error messages<commit_after>#include <shogun/classifier/mkl/MKLClassification.h> #ifdef USE_SVMLIGHT #include <shogun/classifier/svm/SVMLight.h> #endif //USE_SVMLIGHT #include <shogun/classifier/svm/LibSVM.h> using namespace shogun; CMKLClassification::CMKLClassification(CSVM* s) : CMKL(s) { if (!s) { #ifdef USE_SVMLIGHT s=new CSVMLight(); #endif //USE_SVMLIGHT if (!s) s=new CLibSVM(); set_svm(s); } } CMKLClassification::~CMKLClassification() { } float64_t CMKLClassification::compute_sum_alpha() { float64_t suma=0; int32_t nsv=svm->get_num_support_vectors(); for (int32_t i=0; i<nsv; i++) suma+=CMath::abs(svm->get_alpha(i)); return suma; } void CMKLClassification::init_training() { REQUIRE(m_labels, "Labels not set.\n"); REQUIRE(m_labels->get_num_labels(), "Number of labels is zero.\n"); REQUIRE(m_labels->get_label_type() == LT_BINARY, "Labels must be binary.\n"); } <|endoftext|>
<commit_before>#include "ros/ros.h" #include <gtest/gtest.h> #include "geometry_msgs/Wrench.h" #include "maelstrom_msgs/ThrusterForces.h" class AllocatorTest : public ::testing::Test { public: AllocatorTest() { pub = nh.advertise<geometry_msgs::Wrench>("rov_forces", 10); sub = nh.subscribe("thruster_forces", 10, &AllocatorTest::Callback, this); message_received = false; } void SetUp() { while (!IsNodeReady()) ros::spinOnce(); } void Publish(double surge, double sway, double heave, double roll, double pitch, double yaw) { geometry_msgs::Wrench msg; msg.force.x = surge; msg.force.y = sway; msg.force.z = heave; msg.torque.x = roll; msg.torque.y = pitch; msg.torque.z = yaw; pub.publish(msg); } void WaitForMessage() { while (!message_received) ros::spinOnce(); } double F_A; double F_B; double F_C; double F_D; double F_E; double F_F; static const double MAX_ERROR = 1e-6; // Max absolute error 1 micronewton private: ros::NodeHandle nh; ros::Publisher pub; ros::Subscriber sub; bool message_received; void Callback(const maelstrom_msgs::ThrusterForces& msg) { F_A = msg.F1; F_B = msg.F2; F_C = msg.F3; F_D = msg.F4; F_E = msg.F5; F_F = msg.F6; message_received = true; } bool IsNodeReady() { return (pub.getNumSubscribers() > 0) && (sub.getNumPublishers() > 0); } }; TEST_F(AllocatorTest, CheckResponsiveness) { Publish(0, 0, 0, 0, 0, 0); WaitForMessage(); } TEST_F(AllocatorTest, ZeroInput) { Publish(0, 0, 0, 0, 0, 0); WaitForMessage(); EXPECT_NEAR(F_A, 0, MAX_ERROR); EXPECT_NEAR(F_B, 0, MAX_ERROR); EXPECT_NEAR(F_C, 0, MAX_ERROR); EXPECT_NEAR(F_D, 0, MAX_ERROR); EXPECT_NEAR(F_E, 0, MAX_ERROR); EXPECT_NEAR(F_F, 0, MAX_ERROR); } TEST_F(AllocatorTest, Forward) { Publish(1, 0, 0, 0, 0, 0); WaitForMessage(); EXPECT_TRUE(F_A < 0); EXPECT_TRUE(F_B > 0); EXPECT_TRUE(F_C < 0); EXPECT_TRUE(F_D > 0); EXPECT_TRUE(F_E > 0); EXPECT_TRUE(F_F < 0); } TEST_F(AllocatorTest, Sideways) { Publish(0, 1, 0, 0, 0, 0); WaitForMessage(); EXPECT_NEAR(F_A, 0, MAX_ERROR); EXPECT_TRUE(F_B < 0); EXPECT_TRUE(F_C < 0); EXPECT_NEAR(F_D, 0, MAX_ERROR); EXPECT_TRUE(F_E > 0); EXPECT_TRUE(F_F > 0); } TEST_F(AllocatorTest, Downward) { Publish(0, 0, 1, 0, 0, 0); WaitForMessage(); EXPECT_TRUE(F_A > 0); EXPECT_NEAR(F_B, 0, MAX_ERROR); EXPECT_NEAR(F_C, 0, MAX_ERROR); EXPECT_TRUE(F_D > 0); EXPECT_NEAR(F_E, 0, MAX_ERROR); EXPECT_NEAR(F_F, 0, MAX_ERROR); } TEST_F(AllocatorTest, TiltUp) { Publish(0, 0, 0, 0, 1, 0); WaitForMessage(); EXPECT_TRUE(F_A < 0); EXPECT_NEAR(F_B, 0, MAX_ERROR); EXPECT_NEAR(F_C, 0, MAX_ERROR); EXPECT_TRUE(F_D > 0); EXPECT_NEAR(F_E, 0, MAX_ERROR); EXPECT_NEAR(F_F, 0, MAX_ERROR); } TEST_F(AllocatorTest, TurnRight) { Publish(0, 0, 0, 0, 0, 1); WaitForMessage(); EXPECT_NEAR(F_A, 0, MAX_ERROR); EXPECT_TRUE(F_B < 0); EXPECT_TRUE(F_C > 0); EXPECT_NEAR(F_D, 0, MAX_ERROR); EXPECT_TRUE(F_E > 0); EXPECT_TRUE(F_F < 0); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "allocator_test"); int ret = RUN_ALL_TESTS(); ros::shutdown(); return ret; } <commit_msg>Update thruster names<commit_after>#include "ros/ros.h" #include <gtest/gtest.h> #include "geometry_msgs/Wrench.h" #include "maelstrom_msgs/ThrusterForces.h" class AllocatorTest : public ::testing::Test { public: AllocatorTest() { pub = nh.advertise<geometry_msgs::Wrench>("rov_forces", 10); sub = nh.subscribe("thruster_forces", 10, &AllocatorTest::Callback, this); message_received = false; } void SetUp() { while (!IsNodeReady()) ros::spinOnce(); } void Publish(double surge, double sway, double heave, double roll, double pitch, double yaw) { geometry_msgs::Wrench msg; msg.force.x = surge; msg.force.y = sway; msg.force.z = heave; msg.torque.x = roll; msg.torque.y = pitch; msg.torque.z = yaw; pub.publish(msg); } void WaitForMessage() { while (!message_received) ros::spinOnce(); } double F1; double F2; double F3; double F4; double F5; double F6; static const double MAX_ERROR = 1e-6; // Max absolute error 1 micronewton private: ros::NodeHandle nh; ros::Publisher pub; ros::Subscriber sub; bool message_received; void Callback(const maelstrom_msgs::ThrusterForces& msg) { F1 = msg.F1; F2 = msg.F2; F3 = msg.F3; F4 = msg.F4; F5 = msg.F5; F6 = msg.F6; message_received = true; } bool IsNodeReady() { return (pub.getNumSubscribers() > 0) && (sub.getNumPublishers() > 0); } }; TEST_F(AllocatorTest, CheckResponsiveness) { Publish(0, 0, 0, 0, 0, 0); WaitForMessage(); } TEST_F(AllocatorTest, ZeroInput) { Publish(0, 0, 0, 0, 0, 0); WaitForMessage(); EXPECT_NEAR(F1, 0, MAX_ERROR); EXPECT_NEAR(F2, 0, MAX_ERROR); EXPECT_NEAR(F3, 0, MAX_ERROR); EXPECT_NEAR(F4, 0, MAX_ERROR); EXPECT_NEAR(F5, 0, MAX_ERROR); EXPECT_NEAR(F6, 0, MAX_ERROR); } TEST_F(AllocatorTest, Forward) { Publish(1, 0, 0, 0, 0, 0); WaitForMessage(); EXPECT_TRUE(F1 < 0); EXPECT_TRUE(F2 > 0); EXPECT_TRUE(F3 < 0); EXPECT_TRUE(F4 > 0); EXPECT_TRUE(F5 > 0); EXPECT_TRUE(F6 < 0); } TEST_F(AllocatorTest, Sideways) { Publish(0, 1, 0, 0, 0, 0); WaitForMessage(); EXPECT_NEAR(F1, 0, MAX_ERROR); EXPECT_TRUE(F2 < 0); EXPECT_TRUE(F3 < 0); EXPECT_NEAR(F4, 0, MAX_ERROR); EXPECT_TRUE(F5 > 0); EXPECT_TRUE(F6 > 0); } TEST_F(AllocatorTest, Downward) { Publish(0, 0, 1, 0, 0, 0); WaitForMessage(); EXPECT_TRUE(F1 > 0); EXPECT_NEAR(F2, 0, MAX_ERROR); EXPECT_NEAR(F3, 0, MAX_ERROR); EXPECT_TRUE(F4 > 0); EXPECT_NEAR(F5, 0, MAX_ERROR); EXPECT_NEAR(F6, 0, MAX_ERROR); } TEST_F(AllocatorTest, TiltUp) { Publish(0, 0, 0, 0, 1, 0); WaitForMessage(); EXPECT_TRUE(F1 < 0); EXPECT_NEAR(F2, 0, MAX_ERROR); EXPECT_NEAR(F3, 0, MAX_ERROR); EXPECT_TRUE(F4 > 0); EXPECT_NEAR(F5, 0, MAX_ERROR); EXPECT_NEAR(F6, 0, MAX_ERROR); } TEST_F(AllocatorTest, TurnRight) { Publish(0, 0, 0, 0, 0, 1); WaitForMessage(); EXPECT_NEAR(F1, 0, MAX_ERROR); EXPECT_TRUE(F2 < 0); EXPECT_TRUE(F3 > 0); EXPECT_NEAR(F4, 0, MAX_ERROR); EXPECT_TRUE(F5 > 0); EXPECT_TRUE(F6 < 0); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "allocator_test"); int ret = RUN_ALL_TESTS(); ros::shutdown(); return ret; } <|endoftext|>
<commit_before>#include "console.h" #include "util/bitmap.h" #include "util/font.h" #include "util/funcs.h" #include "util/file-system.h" #include "input/input-manager.h" #include "input/input-map.h" #include "globals.h" #include <string> #include <sstream> using namespace std; namespace ConsoleInput{ static int Toggle = 254; static int Backspace = 9; static int Esc = 8; static int Control = 7; } ConsoleEnd Console::endl; const std::string Console::DEFAULT_FONT = Global::DEFAULT_FONT; Console::Console(const int maxHeight, const std::string & font): state(Closed), maxHeight(maxHeight), height(0), font(font), textHeight(15), textWidth(15), offset(0){ const int delay = 10; input.set(Keyboard::Key_TILDE, delay * 2, false, ConsoleInput::Toggle); input.set(Keyboard::Key_BACKSPACE, delay, false, ConsoleInput::Backspace); input.set(Keyboard::Key_ESC, delay, false, ConsoleInput::Esc); input.set(Keyboard::Key_LCONTROL, 0, false, ConsoleInput::Control); /* ugh, do we really have to enumerate every key?? */ input.set(Keyboard::Key_A, delay, false, 'a'); input.set(Keyboard::Key_B, delay, false, 'b'); input.set(Keyboard::Key_C, delay, false, 'c'); input.set(Keyboard::Key_D, delay, false, 'd'); input.set(Keyboard::Key_E, delay, false, 'e'); input.set(Keyboard::Key_F, delay, false, 'f'); input.set(Keyboard::Key_G, delay, false, 'g'); input.set(Keyboard::Key_H, delay, false, 'h'); input.set(Keyboard::Key_I, delay, false, 'i'); input.set(Keyboard::Key_J, delay, false, 'j'); input.set(Keyboard::Key_K, delay, false, 'k'); input.set(Keyboard::Key_L, delay, false, 'l'); input.set(Keyboard::Key_M, delay, false, 'm'); input.set(Keyboard::Key_N, delay, false, 'n'); input.set(Keyboard::Key_O, delay, false, 'o'); input.set(Keyboard::Key_P, delay, false, 'p'); input.set(Keyboard::Key_Q, delay, false, 'q'); input.set(Keyboard::Key_R, delay, false, 'r'); input.set(Keyboard::Key_S, delay, false, 's'); input.set(Keyboard::Key_T, delay, false, 't'); input.set(Keyboard::Key_U, delay, false, 'u'); input.set(Keyboard::Key_V, delay, false, 'v'); input.set(Keyboard::Key_W, delay, false, 'w'); input.set(Keyboard::Key_X, delay, false, 'x'); input.set(Keyboard::Key_Y, delay, false, 'y'); input.set(Keyboard::Key_Z, delay, false, 'z'); } Console::~Console(){ } void Console::act(){ double speed = 10.0; switch (state){ case Closed : { break; } case Open : { break; } case Closing : { int distance = height; height -= (int)((double)distance / speed + 1.0); if (height <= 0){ height = 0; state = Closed; } break; } case Opening : { int distance = maxHeight - height; height += (int)((double)distance / speed + 1.0); if (height >= maxHeight){ height = maxHeight; state = Open; } break; } } checkStream(); } static bool isChar(char c){ return c >= 'a' && c <= 'z'; } bool Console::doInput() throw (ReturnException) { InputMap<char>::Output inputState = InputManager::getMap(input); if (inputState[ConsoleInput::Toggle]){ toggle(); return false; } /* ctrl-X keys */ if (inputState[ConsoleInput::Control]){ /* standard linux console commands */ if (inputState['u']){ clearInput(); /* ignore any other input */ return true; } } for (InputMap<char>::Output::iterator it = inputState.begin(); it != inputState.end(); it++){ char c = (*it).first; bool pressed = (*it).second; if (pressed && isChar(c)){ currentCommand << c; } } if (inputState[ConsoleInput::Esc]){ throw ReturnException(); } if (inputState[ConsoleInput::Backspace]){ backspace(); } return true; } void Console::draw(const Bitmap & work){ /* if we can show something */ if (height > 0){ Bitmap::drawingMode(Bitmap::MODE_TRANS); Bitmap::transBlender(0, 0, 0, 160); work.rectangleFill(0, 0, work.getWidth(), height, Bitmap::makeColor(200,0,0)); work.horizontalLine(0, height, work.getWidth(), Bitmap::makeColor(200, 200, 200)); const Font & font = Font::getFont(Filesystem::find(getFont()), textWidth, textHeight); //font.printf(0, height - font.getHeight(), Bitmap::makeColor(255, 255, 255), work, "Console!", 0 ); Bitmap::drawingMode(Bitmap::MODE_SOLID); // if (state == Open){ if (!lines.empty()){ int start = height - font.getHeight() * 2; for (std::vector<std::string>::reverse_iterator i = lines.rbegin(); i != lines.rend() && start > 0; ++i){ std::string str = *i; font.printf(0, start, Bitmap::makeColor(255,255,255), work, str, 0); start -= font.getHeight(); } } font.printf(0, height - font.getHeight(), Bitmap::makeColor(255,255,255), work, "> " + currentCommand.str(), 0); // } } } void Console::toggle(){ switch (state){ case Open: case Opening: { state = Closing; break; } case Closed: case Closing: { state = Opening; break; } } } void Console::backspace(){ string now = currentCommand.str(); now = now.substr(0, now.size()-1); currentCommand.str(now); currentCommand.rdbuf()->pubseekoff(0, ios_base::end, ios_base::out); currentCommand.clear(); } void Console::clearInput(){ currentCommand.str(string()); currentCommand.rdbuf()->pubseekoff(0, ios_base::end, ios_base::out); currentCommand.clear(); } Console & Console::operator<<(const ConsoleEnd & e){ checkStream(); return *this; } void Console::clear(){ lines.clear(); textInput.str(""); textInput.clear(); } std::stringstream & Console::add(){ checkStream(); return textInput; } void Console::checkStream(){ if (!textInput.str().empty()){ lines.push_back(textInput.str()); textInput.str(""); } } <commit_msg>console: enter and space<commit_after>#include "console.h" #include "util/bitmap.h" #include "util/font.h" #include "util/funcs.h" #include "util/file-system.h" #include "input/input-manager.h" #include "input/input-map.h" #include "globals.h" #include <string> #include <sstream> using namespace std; namespace ConsoleInput{ static int Toggle = 254; static int Backspace = 9; static int Esc = 8; static int Control = 7; static int Enter = 6; } ConsoleEnd Console::endl; const std::string Console::DEFAULT_FONT = Global::DEFAULT_FONT; Console::Console(const int maxHeight, const std::string & font): state(Closed), maxHeight(maxHeight), height(0), font(font), textHeight(15), textWidth(15), offset(0){ const int delay = 10; input.set(Keyboard::Key_TILDE, delay * 2, false, ConsoleInput::Toggle); input.set(Keyboard::Key_BACKSPACE, delay, false, ConsoleInput::Backspace); input.set(Keyboard::Key_ESC, delay, false, ConsoleInput::Esc); input.set(Keyboard::Key_LCONTROL, 0, false, ConsoleInput::Control); input.set(Keyboard::Key_ENTER, 0, false, ConsoleInput::Enter); /* ugh, do we really have to enumerate every key?? */ input.set(Keyboard::Key_A, delay, false, 'a'); input.set(Keyboard::Key_B, delay, false, 'b'); input.set(Keyboard::Key_C, delay, false, 'c'); input.set(Keyboard::Key_D, delay, false, 'd'); input.set(Keyboard::Key_E, delay, false, 'e'); input.set(Keyboard::Key_F, delay, false, 'f'); input.set(Keyboard::Key_G, delay, false, 'g'); input.set(Keyboard::Key_H, delay, false, 'h'); input.set(Keyboard::Key_I, delay, false, 'i'); input.set(Keyboard::Key_J, delay, false, 'j'); input.set(Keyboard::Key_K, delay, false, 'k'); input.set(Keyboard::Key_L, delay, false, 'l'); input.set(Keyboard::Key_M, delay, false, 'm'); input.set(Keyboard::Key_N, delay, false, 'n'); input.set(Keyboard::Key_O, delay, false, 'o'); input.set(Keyboard::Key_P, delay, false, 'p'); input.set(Keyboard::Key_Q, delay, false, 'q'); input.set(Keyboard::Key_R, delay, false, 'r'); input.set(Keyboard::Key_S, delay, false, 's'); input.set(Keyboard::Key_T, delay, false, 't'); input.set(Keyboard::Key_U, delay, false, 'u'); input.set(Keyboard::Key_V, delay, false, 'v'); input.set(Keyboard::Key_W, delay, false, 'w'); input.set(Keyboard::Key_X, delay, false, 'x'); input.set(Keyboard::Key_Y, delay, false, 'y'); input.set(Keyboard::Key_Z, delay, false, 'z'); input.set(Keyboard::Key_SPACE, delay, false, ' '); } Console::~Console(){ } void Console::act(){ double speed = 10.0; switch (state){ case Closed : { break; } case Open : { break; } case Closing : { int distance = height; height -= (int)((double)distance / speed + 1.0); if (height <= 0){ height = 0; state = Closed; } break; } case Opening : { int distance = maxHeight - height; height += (int)((double)distance / speed + 1.0); if (height >= maxHeight){ height = maxHeight; state = Open; } break; } } checkStream(); } static bool isChar(char c){ return (c >= 'a' && c <= 'z') || (c == ' '); } /* console input */ bool Console::doInput() throw (ReturnException) { InputMap<char>::Output inputState = InputManager::getMap(input); /* the order of reading input is arbitrary right now. I'm not * sure it matters what order things are done in, but probably * a few corner cases exist. When they come up please document them. */ if (inputState[ConsoleInput::Toggle]){ toggle(); return false; } if (inputState[ConsoleInput::Enter]){ if (currentCommand.str() != ""){ lines.push_back(currentCommand.str()); } clearInput(); } /* ctrl-X keys */ if (inputState[ConsoleInput::Control]){ /* standard linux console commands */ if (inputState['u']){ clearInput(); /* ignore any other input */ return true; } } for (InputMap<char>::Output::iterator it = inputState.begin(); it != inputState.end(); it++){ char c = (*it).first; bool pressed = (*it).second; if (pressed && isChar(c)){ currentCommand << c; } } if (inputState[ConsoleInput::Esc]){ throw ReturnException(); } if (inputState[ConsoleInput::Backspace]){ backspace(); } return true; } void Console::draw(const Bitmap & work){ /* if we can show something */ if (height > 0){ Bitmap::drawingMode(Bitmap::MODE_TRANS); Bitmap::transBlender(0, 0, 0, 160); work.rectangleFill(0, 0, work.getWidth(), height, Bitmap::makeColor(200,0,0)); work.horizontalLine(0, height, work.getWidth(), Bitmap::makeColor(200, 200, 200)); const Font & font = Font::getFont(Filesystem::find(getFont()), textWidth, textHeight); //font.printf(0, height - font.getHeight(), Bitmap::makeColor(255, 255, 255), work, "Console!", 0 ); Bitmap::drawingMode(Bitmap::MODE_SOLID); // if (state == Open){ if (!lines.empty()){ int start = height - font.getHeight() * 2; for (std::vector<std::string>::reverse_iterator i = lines.rbegin(); i != lines.rend() && start > 0; ++i){ std::string str = *i; font.printf(0, start, Bitmap::makeColor(255,255,255), work, str, 0); start -= font.getHeight(); } } font.printf(0, height - font.getHeight(), Bitmap::makeColor(255,255,255), work, "> " + currentCommand.str(), 0); // } } } void Console::toggle(){ switch (state){ case Open: case Opening: { state = Closing; break; } case Closed: case Closing: { state = Opening; break; } } } void Console::backspace(){ string now = currentCommand.str(); now = now.substr(0, now.size()-1); currentCommand.str(now); currentCommand.rdbuf()->pubseekoff(0, ios_base::end, ios_base::out); currentCommand.clear(); } void Console::clearInput(){ currentCommand.str(string()); currentCommand.rdbuf()->pubseekoff(0, ios_base::end, ios_base::out); currentCommand.clear(); } Console & Console::operator<<(const ConsoleEnd & e){ checkStream(); return *this; } void Console::clear(){ lines.clear(); textInput.str(""); textInput.clear(); } std::stringstream & Console::add(){ checkStream(); return textInput; } void Console::checkStream(){ if (!textInput.str().empty()){ lines.push_back(textInput.str()); textInput.str(""); } } <|endoftext|>
<commit_before> #include "EthStratumClient.h" using boost::asio::ip::tcp; EthStratumClient::EthStratumClient(GenericFarm<EthashProofOfWork> * f, string const & host, string const & port, string const & user, string const & pass) : m_socket(m_io_service) { m_host = host; m_port = port; m_user = user; m_pass = pass; m_authorized = false; m_running = true; m_precompute = true; m_pending = 0; p_farm = f; connect(); } EthStratumClient::~EthStratumClient() { } void EthStratumClient::connect() { tcp::resolver r(m_io_service); tcp::resolver::query q(m_host, m_port); r.async_resolve(q, boost::bind(&EthStratumClient::resolve_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator)); boost::thread t(boost::bind(&boost::asio::io_service::run, &m_io_service)); } void EthStratumClient::reconnect() { m_socket.close(); m_io_service.reset(); m_authorized = false; cnote << "Reconnecting in 3 seconds..."; boost::asio::deadline_timer timer(m_io_service, boost::posix_time::seconds(3)); timer.wait(); connect(); } void EthStratumClient::disconnect() { cnote << "Disconnecting"; m_running = false; m_socket.close(); m_io_service.stop(); } void EthStratumClient::resolve_handler(const boost::system::error_code& ec, tcp::resolver::iterator i) { if (!ec) { async_connect(m_socket, i, boost::bind(&EthStratumClient::connect_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator)); } else { cerr << "Could not resolve host" << m_host + ":" + m_port + ", " << ec.message(); disconnect(); } } void EthStratumClient::connect_handler(const boost::system::error_code& ec, tcp::resolver::iterator i) { if (!ec) { cnote << "Connected to stratum server " << m_host << ":" << m_port; std::ostream os(&m_requestBuffer); os << "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}\n"; async_write(m_socket, m_requestBuffer, boost::bind(&EthStratumClient::handleResponse, this, boost::asio::placeholders::error)); } else { cwarn << "Could not connect to stratum server " << m_host << ":" << m_port << ", " << ec.message(); reconnect(); } } void EthStratumClient::readline() { if (m_pending == 0) { async_read_until(m_socket, m_responseBuffer, "\n", boost::bind(&EthStratumClient::readResponse, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); m_pending++; } } void EthStratumClient::handleResponse(const boost::system::error_code& ec) { if (!ec) { readline(); } else { cwarn << "Handle response failed: " << ec.message(); } } void EthStratumClient::readResponse(const boost::system::error_code& ec, std::size_t bytes_transferred) { m_pending = m_pending > 0 ? m_pending - 1 : 0; if (!ec) { std::istream is(&m_responseBuffer); std::string response; getline(is, response); if (response.front() == '{' && response.back() == '}') { Json::Value responseObject; Json::Reader reader; if (reader.parse(response.c_str(), responseObject)) { processReponse(responseObject); m_response = response; } else { cwarn << "Parse response failed: " << reader.getFormattedErrorMessages(); } } else { cwarn << "Discarding incomplete response"; } readline(); } else { cwarn << "Read response failed: " << ec.message(); reconnect(); } } void EthStratumClient::processReponse(Json::Value& responseObject) { Json::Value error = responseObject.get("error", new Json::Value); if (error.isArray()) { string msg = error.get(1, "Unknown error").asString(); cnote << msg; } std::ostream os(&m_requestBuffer); Json::Value params; int id = responseObject.get("id", Json::Value::null).asInt(); switch (id) { case 1: cnote << "Subscribed to stratum server"; os << "{\"id\": 2, \"method\": \"mining.authorize\", \"params\": [\"" << m_user << "\",\"" << m_pass << "\"]}\n"; async_write(m_socket, m_requestBuffer, boost::bind(&EthStratumClient::handleResponse, this, boost::asio::placeholders::error)); break; case 2: m_authorized = responseObject.get("result", Json::Value::null).asBool(); if (!m_authorized) { disconnect(); return; } cnote << "Authorized worker " << m_user; break; case 4: if (responseObject.get("result", false).asBool()) cnote << "B-) Submitted and accepted."; else cwarn << ":-( Not accepted."; break; default: string method = responseObject.get("method", "").asString(); if (method == "mining.notify") { params = responseObject.get("params", Json::Value::null); if (params.isArray()) { m_job = params.get((Json::Value::ArrayIndex)0, "").asString(); string sHeaderHash = params.get((Json::Value::ArrayIndex)1, "").asString(); string sSeedHash = params.get((Json::Value::ArrayIndex)2, "").asString(); string sShareTarget = params.get((Json::Value::ArrayIndex)3, "").asString(); bool cleanJobs = params.get((Json::Value::ArrayIndex)4, "").asBool(); if (sHeaderHash != "" && sSeedHash != "" && sShareTarget != "") { cnote << "Received new job #" + m_job; cnote << "Header hash: 0x" + sHeaderHash; cnote << "Seed hash: 0x" + sSeedHash; cnote << "Share target: 0x" + sShareTarget; h256 seedHash = h256(sSeedHash); h256 headerHash = h256(sHeaderHash); EthashAux::FullType dag; if (seedHash != m_current.seedHash) cnote << "Grabbing DAG for" << seedHash; if (!(dag = EthashAux::full(seedHash, true, [&](unsigned _pc){ cout << "\rCreating DAG. " << _pc << "% done..." << flush; return 0; }))) BOOST_THROW_EXCEPTION(DAGCreationFailure()); if (m_precompute) EthashAux::computeFull(sha3(seedHash), true); if (headerHash != m_current.headerHash) { m_current.headerHash = h256(sHeaderHash); m_current.seedHash = seedHash; m_current.boundary = h256(sShareTarget);// , h256::AlignRight); p_farm->setWork(m_current); } } } } else if (method == "mining.set_difficulty") { } else if (method == "client.get_version") { os << "{\"error\": null, \"id\" : " << id << ", \"result\" : \"" << ETH_PROJECT_VERSION << "\"}\n"; async_write(m_socket, m_requestBuffer, boost::bind(&EthStratumClient::handleResponse, this, boost::asio::placeholders::error)); } break; } } bool EthStratumClient::submit(EthashProofOfWork::Solution solution) { cnote << "Solution found; Submitting to" << m_host << "..."; cnote << " Nonce:" << solution.nonce.hex(); cnote << " Mixhash:" << solution.mixHash.hex(); cnote << " Header-hash:" << m_current.headerHash.hex(); cnote << " Seedhash:" << m_current.seedHash.hex(); cnote << " Target: " << h256(m_current.boundary).hex(); cnote << " Ethash: " << h256(EthashAux::eval(m_current.seedHash, m_current.headerHash, solution.nonce).value).hex(); if (EthashAux::eval(m_current.seedHash, m_current.headerHash, solution.nonce).value < m_current.boundary) { string json = "{\"id\": 4, \"method\": \"mining.submit\", \"params\": [\"" + m_user + "\",\"" + m_job + "\",\"0x" + solution.nonce.hex() + "\",\"0x" + m_current.headerHash.hex() + "\",\"0x" + solution.mixHash.hex() + "\"]}\n"; std::ostream os(&m_requestBuffer); os << json; async_write(m_socket, m_requestBuffer, boost::bind(&EthStratumClient::handleResponse, this, boost::asio::placeholders::error)); return true; } else cwarn << "FAILURE: GPU gave incorrect result!"; return false; } <commit_msg>I need to output a random line to console, or async resolve fail<commit_after> #include "EthStratumClient.h" using boost::asio::ip::tcp; EthStratumClient::EthStratumClient(GenericFarm<EthashProofOfWork> * f, string const & host, string const & port, string const & user, string const & pass) : m_socket(m_io_service) { m_host = host; m_port = port; m_user = user; m_pass = pass; m_authorized = false; m_running = true; m_precompute = true; m_pending = 0; p_farm = f; connect(); } EthStratumClient::~EthStratumClient() { } void EthStratumClient::connect() { tcp::resolver r(m_io_service); tcp::resolver::query q(m_host, m_port); r.async_resolve(q, boost::bind(&EthStratumClient::resolve_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator)); cnote << "This line fix 'Could not resolve host' ??? dunno why ??"; boost::thread t(boost::bind(&boost::asio::io_service::run, &m_io_service)); } void EthStratumClient::reconnect() { m_socket.close(); m_io_service.reset(); m_authorized = false; cnote << "Reconnecting in 3 seconds..."; boost::asio::deadline_timer timer(m_io_service, boost::posix_time::seconds(3)); timer.wait(); connect(); } void EthStratumClient::disconnect() { cnote << "Disconnecting"; m_running = false; m_socket.close(); m_io_service.stop(); } void EthStratumClient::resolve_handler(const boost::system::error_code& ec, tcp::resolver::iterator i) { if (!ec) { async_connect(m_socket, i, boost::bind(&EthStratumClient::connect_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator)); } else { cerr << "Could not resolve host" << m_host + ":" + m_port + ", " << ec.message(); disconnect(); } } void EthStratumClient::connect_handler(const boost::system::error_code& ec, tcp::resolver::iterator i) { if (!ec) { cnote << "Connected to stratum server " << m_host << ":" << m_port; std::ostream os(&m_requestBuffer); os << "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}\n"; async_write(m_socket, m_requestBuffer, boost::bind(&EthStratumClient::handleResponse, this, boost::asio::placeholders::error)); } else { cwarn << "Could not connect to stratum server " << m_host << ":" << m_port << ", " << ec.message(); reconnect(); } } void EthStratumClient::readline() { if (m_pending == 0) { async_read_until(m_socket, m_responseBuffer, "\n", boost::bind(&EthStratumClient::readResponse, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); m_pending++; } } void EthStratumClient::handleResponse(const boost::system::error_code& ec) { if (!ec) { readline(); } else { cwarn << "Handle response failed: " << ec.message(); } } void EthStratumClient::readResponse(const boost::system::error_code& ec, std::size_t bytes_transferred) { m_pending = m_pending > 0 ? m_pending - 1 : 0; if (!ec) { std::istream is(&m_responseBuffer); std::string response; getline(is, response); if (response.front() == '{' && response.back() == '}') { Json::Value responseObject; Json::Reader reader; if (reader.parse(response.c_str(), responseObject)) { processReponse(responseObject); m_response = response; } else { cwarn << "Parse response failed: " << reader.getFormattedErrorMessages(); } } else { cwarn << "Discarding incomplete response"; } readline(); } else { cwarn << "Read response failed: " << ec.message(); reconnect(); } } void EthStratumClient::processReponse(Json::Value& responseObject) { Json::Value error = responseObject.get("error", new Json::Value); if (error.isArray()) { string msg = error.get(1, "Unknown error").asString(); cnote << msg; } std::ostream os(&m_requestBuffer); Json::Value params; int id = responseObject.get("id", Json::Value::null).asInt(); switch (id) { case 1: cnote << "Subscribed to stratum server"; os << "{\"id\": 2, \"method\": \"mining.authorize\", \"params\": [\"" << m_user << "\",\"" << m_pass << "\"]}\n"; async_write(m_socket, m_requestBuffer, boost::bind(&EthStratumClient::handleResponse, this, boost::asio::placeholders::error)); break; case 2: m_authorized = responseObject.get("result", Json::Value::null).asBool(); if (!m_authorized) { disconnect(); return; } cnote << "Authorized worker " << m_user; break; case 4: if (responseObject.get("result", false).asBool()) cnote << "B-) Submitted and accepted."; else cwarn << ":-( Not accepted."; break; default: string method = responseObject.get("method", "").asString(); if (method == "mining.notify") { params = responseObject.get("params", Json::Value::null); if (params.isArray()) { m_job = params.get((Json::Value::ArrayIndex)0, "").asString(); string sHeaderHash = params.get((Json::Value::ArrayIndex)1, "").asString(); string sSeedHash = params.get((Json::Value::ArrayIndex)2, "").asString(); string sShareTarget = params.get((Json::Value::ArrayIndex)3, "").asString(); bool cleanJobs = params.get((Json::Value::ArrayIndex)4, "").asBool(); if (sHeaderHash != "" && sSeedHash != "" && sShareTarget != "") { cnote << "Received new job #" + m_job; cnote << "Header hash: 0x" + sHeaderHash; cnote << "Seed hash: 0x" + sSeedHash; cnote << "Share target: 0x" + sShareTarget; h256 seedHash = h256(sSeedHash); h256 headerHash = h256(sHeaderHash); EthashAux::FullType dag; if (seedHash != m_current.seedHash) cnote << "Grabbing DAG for" << seedHash; if (!(dag = EthashAux::full(seedHash, true, [&](unsigned _pc){ cout << "\rCreating DAG. " << _pc << "% done..." << flush; return 0; }))) BOOST_THROW_EXCEPTION(DAGCreationFailure()); if (m_precompute) EthashAux::computeFull(sha3(seedHash), true); if (headerHash != m_current.headerHash) { m_current.headerHash = h256(sHeaderHash); m_current.seedHash = seedHash; m_current.boundary = h256(sShareTarget);// , h256::AlignRight); p_farm->setWork(m_current); } } } } else if (method == "mining.set_difficulty") { } else if (method == "client.get_version") { os << "{\"error\": null, \"id\" : " << id << ", \"result\" : \"" << ETH_PROJECT_VERSION << "\"}\n"; async_write(m_socket, m_requestBuffer, boost::bind(&EthStratumClient::handleResponse, this, boost::asio::placeholders::error)); } break; } } bool EthStratumClient::submit(EthashProofOfWork::Solution solution) { cnote << "Solution found; Submitting to" << m_host << "..."; cnote << " Nonce:" << solution.nonce.hex(); cnote << " Mixhash:" << solution.mixHash.hex(); cnote << " Header-hash:" << m_current.headerHash.hex(); cnote << " Seedhash:" << m_current.seedHash.hex(); cnote << " Target: " << h256(m_current.boundary).hex(); cnote << " Ethash: " << h256(EthashAux::eval(m_current.seedHash, m_current.headerHash, solution.nonce).value).hex(); if (EthashAux::eval(m_current.seedHash, m_current.headerHash, solution.nonce).value < m_current.boundary) { string json = "{\"id\": 4, \"method\": \"mining.submit\", \"params\": [\"" + m_user + "\",\"" + m_job + "\",\"0x" + solution.nonce.hex() + "\",\"0x" + m_current.headerHash.hex() + "\",\"0x" + solution.mixHash.hex() + "\"]}\n"; std::ostream os(&m_requestBuffer); os << json; async_write(m_socket, m_requestBuffer, boost::bind(&EthStratumClient::handleResponse, this, boost::asio::placeholders::error)); return true; } else cwarn << "FAILURE: GPU gave incorrect result!"; return false; } <|endoftext|>
<commit_before>#include <node.h> #include <initializer_list> #include "Pump.h" #include "calculator/PumpEfficiency.h" #include "calculator/OptimalPumpEfficiency.h" #include "calculator/MotorRatedPower.h" #include "calculator/OptimalMotorRatedPower.h" #include "calculator/MotorShaftPower.h" #include "calculator/OptimalMotorShaftPower.h" #include "calculator/PumpShaftPower.h" #include "calculator/OptimalPumpShaftPower.h" #include "calculator/MotorEfficiency.h" #include "calculator/OptimalMotorEfficiency.h" #include "calculator/MotorPowerFactor.h" #include "calculator/OptimalMotorPowerFactor.h" #include "calculator/MotorCurrent.h" #include "calculator/OptimalMotorCurrent.h" #include "calculator/MotorPower.h" #include "calculator/OptimalMotorPower.h" #include "AnnualEnergy.h" #include "AnnualCost.h" #include "AnnualSavingsPotential.h" #include "OptimizationRating.h" using namespace v8; Local<Array> r; Isolate* iso; Local<Object> inp; void set(std::initializer_list <double> args) { for (auto d : args) { r->Set(r->Length(),Number::New(iso,d)); } } double get(const char *nm) { return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue(); } void Results(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); r = Array::New(iso); inp = args[0]->ToObject(); auto loadMeth = get("motor_field_power")>0 ? FieldData::LoadEstimationMethod::POWER : FieldData::LoadEstimationMethod::CURRENT; auto drive = static_cast<Pump::Drive>(get("drive")); auto effCls = static_cast<Motor::EfficiencyClass>(get("efficiency_class")); double mp = get("motor_field_power")>0 ? get("motor_field_power") : (new MotorPower(0,get("motor_field_current"),0,get("field_voltage")))->calculate();//motor power (makes no sense, it IS motor power), motor a, motorpf double mc = get("motor_field_current")>0 ? get("motor_field_current") : (new MotorCurrent(0,get("motor_field_power"),get("field_voltage")))->calculate();//motor a, motor power, recursive arg!! set({ (new PumpEfficiency(get("specific_gravity"),get("flow"),get("head"),0))->calculate(),//pumpShaftPower (new OptimalPumpEfficiency(static_cast<Pump::Style>(get("style")),get("pump_rated_speed"),get("viscosity"),get("stages"),get("flow"),get("head"),static_cast<Pump::Speed>(!get("speed"))))->calculate(),// get("motor_rated_power"), (new OptimalMotorRatedPower(0,get("margin")))->calculate(),//motorshaftpower (new MotorShaftPower(0,0))->calculate(),//motor eff, motor power (sometimes inp? sometimes calc) (new OptimalMotorShaftPower(0,drive))->calculate(),//pumpshaftpower (new PumpShaftPower(0,drive))->calculate(),//motorshaftpower (new OptimalPumpShaftPower(get("flow"),get("head"),get("specific_gravity"),0))->calculate(),//pumpeff (new MotorEfficiency(get("line"),get("motor_rated_speed"),effCls,get("motor_rated_power"), loadMeth,0,0,get("field_voltage")))->calculate(),//motorKwh??, motor amps (new OptimalMotorEfficiency(get("motor_rated_power"),0))->calculate(),//motor shaft power (new MotorPowerFactor(get("line"),get("rpm"),effCls,get("power_rating"), loadMeth,0,0,get("field_voltage")))->calculate(),//motor kwh,motor a (new OptimalMotorPowerFactor(get("motor_rated_power"),0))->calculate(),//motor power mc, (new OptimalMotorCurrent(0,get("field_voltage")))->calculate(),//opt motor power mp, (new OptimalMotorPower(0,0))->calculate(),//motorshaftpower, motor eff (new AnnualEnergy(mp,get("fraction")))->calculate(),//motorpower (new AnnualEnergy(0,get("fraction")))->calculate(),//opt motorpower (new AnnualCost(0,get("cost")))->calculate(),//ex ann energy (new AnnualCost(0,get("cost")))->calculate(),//opt ann energy -1, (new AnnualSavingsPotential(0,0))->calculate(),//ex an cost, opt an cost -1, (new OptimizationRating(0,0))->calculate()//ex an cost, opt an cost }); args.GetReturnValue().Set(r); } void init(Local<Object> exports) { NODE_SET_METHOD(exports, "results", Results); } NODE_MODULE(bridge, init) <commit_msg>no message<commit_after>#include <node.h> #include <initializer_list> #include "Pump.h" #include "calculator/PumpEfficiency.h" #include "calculator/OptimalPumpEfficiency.h" #include "calculator/MotorRatedPower.h" #include "calculator/OptimalMotorRatedPower.h" #include "calculator/MotorShaftPower.h" #include "calculator/OptimalMotorShaftPower.h" #include "calculator/PumpShaftPower.h" #include "calculator/OptimalPumpShaftPower.h" #include "calculator/MotorEfficiency.h" #include "calculator/OptimalMotorEfficiency.h" #include "calculator/MotorPowerFactor.h" #include "calculator/OptimalMotorPowerFactor.h" #include "calculator/MotorCurrent.h" #include "calculator/OptimalMotorCurrent.h" #include "calculator/MotorPower.h" #include "calculator/OptimalMotorPower.h" #include "AnnualEnergy.h" #include "AnnualCost.h" #include "AnnualSavingsPotential.h" #include "OptimizationRating.h" using namespace v8; Local<Array> r; Isolate* iso; Local<Object> inp; void set(std::initializer_list <double> args) { for (auto d : args) { r->Set(r->Length(),Number::New(iso,d)); } } double get(const char *nm) { return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue(); } void Results(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); r = Array::New(iso); inp = args[0]->ToObject(); auto drive = static_cast<Pump::Drive>(get("drive")); auto effCls = static_cast<Motor::EfficiencyClass>(get("efficiency_class")); auto loadMeth = FieldData::LoadEstimationMethod::POWER; double mp = get("motor_field_power"); double mc = get("motor_field_current"); if (mc>0) { loadMeth = FieldData::LoadEstimationMethod::CURRENT; mp = (new MotorPower(0,mc,0,get("field_voltage")))->calculate();//motor power (makes no sense, it IS motor power), motor a, motorpf } else { mc = (new MotorCurrent(0,mp,get("field_voltage")))->calculate();//motor a, motor power, recursive arg!! } set({ (new PumpEfficiency(get("specific_gravity"),get("flow"),get("head"),0))->calculate(),//pumpShaftPower (new OptimalPumpEfficiency(static_cast<Pump::Style>(get("style")), get("pump_rated_speed"),get("viscosity"),get("stages"),get("flow"),get("head"),static_cast<Pump::Speed>(!get("speed"))))->calculate(),// get("motor_rated_power"), (new OptimalMotorRatedPower(0,get("margin")))->calculate(),//motorshaftpower (new MotorShaftPower(0,mp))->calculate(),//motor eff (new OptimalMotorShaftPower(0,drive))->calculate(),//pumpshaftpower (new PumpShaftPower(0,drive))->calculate(),//motorshaftpower (new OptimalPumpShaftPower(get("flow"),get("head"),get("specific_gravity"),0))->calculate(),//pumpeff (new MotorEfficiency(get("line"),get("motor_rated_speed"),effCls,get("motor_rated_power"), loadMeth,0,mc,get("field_voltage")))->calculate(),//motorKwh?? (new OptimalMotorEfficiency(get("motor_rated_power"),0))->calculate(),//motor shaft power (new MotorPowerFactor(get("line"),get("rpm"),effCls,get("power_rating"), loadMeth,0,mc,get("field_voltage")))->calculate(),//motor kwh (new OptimalMotorPowerFactor(get("motor_rated_power"),0))->calculate(),//opt motor power? mc, (new OptimalMotorCurrent(0,get("field_voltage")))->calculate(),//opt motor power mp, (new OptimalMotorPower(0,0))->calculate(),//motorshaftpower, motor eff (new AnnualEnergy(mp,get("fraction")))->calculate(),//motorpower (new AnnualEnergy(0,get("fraction")))->calculate(),//opt motorpower (new AnnualCost(0,get("cost")))->calculate(),//ex ann energy (new AnnualCost(0,get("cost")))->calculate(),//opt ann energy -1, (new AnnualSavingsPotential(0,0))->calculate(),//ex an cost, opt an cost -1, (new OptimizationRating(0,0))->calculate()//ex an cost, opt an cost }); args.GetReturnValue().Set(r); } void init(Local<Object> exports) { NODE_SET_METHOD(exports, "results", Results); } NODE_MODULE(bridge, init) <|endoftext|>
<commit_before>//******************************************************************* //glfont2.cpp -- glFont Version 2.0 implementation //Copyright (c) 1998-2002 Brad Fish //See glfont.html for terms of use //May 14, 2002 //******************************************************************* //STL headers #include <string> #include <utility> #include <iostream> #include <fstream> using namespace std; //OpenGL headers #ifdef _WINDOWS #include <windows.h> #endif #include <GL/gl.h> //glFont header #include "glfont2.h" using namespace glfont; #ifdef __BIG_ENDIAN__ inline void endian_swap(int& x) { x = (x>>24) | ((x<<8) & 0x00FF0000) | ((x>>8) & 0x0000FF00) | (x<<24); } #endif //******************************************************************* //GLFont Class Implementation //******************************************************************* GLFont::GLFont () { //Initialize header to safe state header.tex = -1; header.tex_width = 0; header.tex_height = 0; header.start_char = 0; header.end_char = 0; header.chars = NULL; } //******************************************************************* GLFont::~GLFont () { //Destroy the font Destroy(); } //******************************************************************* bool GLFont::Create (const char *file_name, int tex) { ifstream input; int num_chars, num_tex_bytes; char *tex_bytes; //Destroy the old font if there was one, just to be safe Destroy(); //Open input file input.open(file_name, ios::in | ios::binary); if (!input) return false; //Read the header from file //There is 4 byte space between the header data and the beginning of the //characters. this presumably was used to account for the 4 bytes taken //up by the pointer to the character array //on 64-bit the sizeof(header) is no longer correct and it reads to many //bytes input.read((char *)&header, sizeof(header) - (sizeof(void*) - 4)); header.tex = tex; //Allocate space for character array #ifdef __BIG_ENDIAN__ endian_swap(header.end_char); endian_swap(header.start_char); #endif num_chars = header.end_char - header.start_char + 1; if ((header.chars = new GLFontChar[num_chars]) == NULL) return false; //Read character array for(int i=0; i < num_chars; i++) input.read((char *)&header.chars[i], sizeof(GLFontChar)); //Read texture pixel data num_tex_bytes = header.tex_width * header.tex_height * 2; tex_bytes = new char[num_tex_bytes]; input.read(tex_bytes, num_tex_bytes); //Create OpenGL texture glBindTexture(GL_TEXTURE_2D, tex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexImage2D(GL_TEXTURE_2D, 0, 2, header.tex_width, header.tex_height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (void *)tex_bytes); //Free texture pixels memory delete[] tex_bytes; //Close input file input.close(); //Return successfully //Uncomment to print out the data structure. Useful for finding differences between systems /* cout << "Start: " << header.start_char << ", End: " << header.end_char << ", Chars: " << header.chars << endl; cout << "Height: " << header.tex_height << ", Width: " << header.tex_width << endl; //Read character array for(int i=header.start_char; i < header.end_char; i++) { GLFontChar c = header.chars[i - header.start_char]; cout << "Char: " << i << ", dx: " << c.dx << ", dy: " << c.dy << endl; cout << "ty1: " << c.ty1 << ", ty2: " << c.ty2 << ", tx1: " << c.tx1 << ", tx2: " << c.tx2 << endl; }*/ return true; } //******************************************************************* bool GLFont::Create (const std::string &file_name, int tex) { return Create(file_name.c_str(), tex); } //******************************************************************* void GLFont::Destroy (void) { //Delete the character array if necessary if (header.chars) { delete[] header.chars; header.chars = NULL; } } //******************************************************************* void GLFont::GetTexSize (std::pair<int, int> *size) { //Retrieve texture size size->first = header.tex_width; size->second = header.tex_height; } //******************************************************************* int GLFont::GetTexWidth (void) { //Return texture width return header.tex_width; } //******************************************************************* int GLFont::GetTexHeight (void) { //Return texture height return header.tex_height; } //******************************************************************* void GLFont::GetCharInterval (std::pair<int, int> *interval) { //Retrieve character interval interval->first = header.start_char; interval->second = header.end_char; } //******************************************************************* int GLFont::GetStartChar (void) { //Return start character return header.start_char; } //******************************************************************* int GLFont::GetEndChar (void) { //Return end character return header.end_char; } //******************************************************************* void GLFont::GetCharSize (int c, std::pair<int, int> *size) { //Make sure character is in range if (c < header.start_char || c > header.end_char) { //Not a valid character, so it obviously has no size size->first = 0; size->second = 0; } else { GLFontChar *glfont_char; //Retrieve character size glfont_char = &header.chars[c - header.start_char]; size->first = (int)(glfont_char->dx * header.tex_width); size->second = (int)(glfont_char->dy * header.tex_height); } } //******************************************************************* int GLFont::GetCharWidth (int c) { //Make sure in range if (c < header.start_char || c > header.end_char) return 0; else { GLFontChar *glfont_char; //Retrieve character width glfont_char = &header.chars[c - header.start_char]; return (int)(glfont_char->dx * header.tex_width); } } //******************************************************************* int GLFont::GetCharHeight (int c) { //Make sure in range if (c < header.start_char || c > header.end_char) return 0; else { GLFontChar *glfont_char; //Retrieve character height glfont_char = &header.chars[c - header.start_char]; return (int)(glfont_char->dy * header.tex_height); } } //******************************************************************* void GLFont::Begin (void) { //Bind to font texture glBindTexture(GL_TEXTURE_2D, header.tex); } //******************************************************************* wchar_t GLFont::get_unaccented_character( wchar_t c) { switch(c) { case 225: case 224: return 'a'; case 193: case 192: return 'A'; case 233: case 232: return 'e'; case 201: case 200: return 'E'; case 237: case 236: return 'i'; case 205: case 204: return 'I'; case 243: case 242: return 'o'; case 211: case 210: return 'O'; case 250: case 249: return 'u'; case 218: case 217: return 'U'; case 241: return 'n'; case 209: return 'N'; case 252: return 'u'; case 220: return 'U'; default: return c; } } //End of file <commit_msg>GLFont2: indent GLFont::get_unaccented_character() function code<commit_after>//******************************************************************* //glfont2.cpp -- glFont Version 2.0 implementation //Copyright (c) 1998-2002 Brad Fish //See glfont.html for terms of use //May 14, 2002 //******************************************************************* //STL headers #include <string> #include <utility> #include <iostream> #include <fstream> using namespace std; //OpenGL headers #ifdef _WINDOWS #include <windows.h> #endif #include <GL/gl.h> //glFont header #include "glfont2.h" using namespace glfont; #ifdef __BIG_ENDIAN__ inline void endian_swap(int& x) { x = (x>>24) | ((x<<8) & 0x00FF0000) | ((x>>8) & 0x0000FF00) | (x<<24); } #endif //******************************************************************* //GLFont Class Implementation //******************************************************************* GLFont::GLFont () { //Initialize header to safe state header.tex = -1; header.tex_width = 0; header.tex_height = 0; header.start_char = 0; header.end_char = 0; header.chars = NULL; } //******************************************************************* GLFont::~GLFont () { //Destroy the font Destroy(); } //******************************************************************* bool GLFont::Create (const char *file_name, int tex) { ifstream input; int num_chars, num_tex_bytes; char *tex_bytes; //Destroy the old font if there was one, just to be safe Destroy(); //Open input file input.open(file_name, ios::in | ios::binary); if (!input) return false; //Read the header from file //There is 4 byte space between the header data and the beginning of the //characters. this presumably was used to account for the 4 bytes taken //up by the pointer to the character array //on 64-bit the sizeof(header) is no longer correct and it reads to many //bytes input.read((char *)&header, sizeof(header) - (sizeof(void*) - 4)); header.tex = tex; //Allocate space for character array #ifdef __BIG_ENDIAN__ endian_swap(header.end_char); endian_swap(header.start_char); #endif num_chars = header.end_char - header.start_char + 1; if ((header.chars = new GLFontChar[num_chars]) == NULL) return false; //Read character array for(int i=0; i < num_chars; i++) input.read((char *)&header.chars[i], sizeof(GLFontChar)); //Read texture pixel data num_tex_bytes = header.tex_width * header.tex_height * 2; tex_bytes = new char[num_tex_bytes]; input.read(tex_bytes, num_tex_bytes); //Create OpenGL texture glBindTexture(GL_TEXTURE_2D, tex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexImage2D(GL_TEXTURE_2D, 0, 2, header.tex_width, header.tex_height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (void *)tex_bytes); //Free texture pixels memory delete[] tex_bytes; //Close input file input.close(); //Return successfully //Uncomment to print out the data structure. Useful for finding differences between systems /* cout << "Start: " << header.start_char << ", End: " << header.end_char << ", Chars: " << header.chars << endl; cout << "Height: " << header.tex_height << ", Width: " << header.tex_width << endl; //Read character array for(int i=header.start_char; i < header.end_char; i++) { GLFontChar c = header.chars[i - header.start_char]; cout << "Char: " << i << ", dx: " << c.dx << ", dy: " << c.dy << endl; cout << "ty1: " << c.ty1 << ", ty2: " << c.ty2 << ", tx1: " << c.tx1 << ", tx2: " << c.tx2 << endl; }*/ return true; } //******************************************************************* bool GLFont::Create (const std::string &file_name, int tex) { return Create(file_name.c_str(), tex); } //******************************************************************* void GLFont::Destroy (void) { //Delete the character array if necessary if (header.chars) { delete[] header.chars; header.chars = NULL; } } //******************************************************************* void GLFont::GetTexSize (std::pair<int, int> *size) { //Retrieve texture size size->first = header.tex_width; size->second = header.tex_height; } //******************************************************************* int GLFont::GetTexWidth (void) { //Return texture width return header.tex_width; } //******************************************************************* int GLFont::GetTexHeight (void) { //Return texture height return header.tex_height; } //******************************************************************* void GLFont::GetCharInterval (std::pair<int, int> *interval) { //Retrieve character interval interval->first = header.start_char; interval->second = header.end_char; } //******************************************************************* int GLFont::GetStartChar (void) { //Return start character return header.start_char; } //******************************************************************* int GLFont::GetEndChar (void) { //Return end character return header.end_char; } //******************************************************************* void GLFont::GetCharSize (int c, std::pair<int, int> *size) { //Make sure character is in range if (c < header.start_char || c > header.end_char) { //Not a valid character, so it obviously has no size size->first = 0; size->second = 0; } else { GLFontChar *glfont_char; //Retrieve character size glfont_char = &header.chars[c - header.start_char]; size->first = (int)(glfont_char->dx * header.tex_width); size->second = (int)(glfont_char->dy * header.tex_height); } } //******************************************************************* int GLFont::GetCharWidth (int c) { //Make sure in range if (c < header.start_char || c > header.end_char) return 0; else { GLFontChar *glfont_char; //Retrieve character width glfont_char = &header.chars[c - header.start_char]; return (int)(glfont_char->dx * header.tex_width); } } //******************************************************************* int GLFont::GetCharHeight (int c) { //Make sure in range if (c < header.start_char || c > header.end_char) return 0; else { GLFontChar *glfont_char; //Retrieve character height glfont_char = &header.chars[c - header.start_char]; return (int)(glfont_char->dy * header.tex_height); } } //******************************************************************* void GLFont::Begin (void) { //Bind to font texture glBindTexture(GL_TEXTURE_2D, header.tex); } //******************************************************************* wchar_t GLFont::get_unaccented_character( wchar_t c) { switch(c) { case 225: case 224: return 'a'; case 193: case 192: return 'A'; case 233: case 232: return 'e'; case 201: case 200: return 'E'; case 237: case 236: return 'i'; case 205: case 204: return 'I'; case 243: case 242: return 'o'; case 211: case 210: return 'O'; case 250: case 249: return 'u'; case 218: case 217: return 'U'; case 241: return 'n'; case 209: return 'N'; case 252: return 'u'; case 220: return 'U'; default: return c; } } //End of file <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: impdialog.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2004-09-08 15:59:21 $ * * 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 IMPDIALOG_HXX #define IMPDIALOG_HXX #include "pdffilter.hxx" #include <vcl/dialog.hxx> #include <vcl/button.hxx> #include <vcl/fixed.hxx> #include <vcl/field.hxx> #include <vcl/edit.hxx> #include <vcl/lstbox.hxx> #include <vcl/combobox.hxx> #include <svtools/FilterConfigItem.hxx> // ---------------- // - ImpPDFDialog - // ---------------- class ResMgr; class ImpPDFDialog : public ModalDialog { private: FixedLine maFlPages; RadioButton maRbAll; RadioButton maRbRange; RadioButton maRbSelection; Edit maEdPages; FixedLine maFlCompression; RadioButton maRbLosslessCompression; RadioButton maRbJPEGCompression; FixedText maFtQuality; NumericField maNfQuality; CheckBox maCbReduceImageResolution; FixedText maFtReduceImageResolution; ComboBox maCoReduceImageResolution; FixedLine maFlGeneral; CheckBox maCbTaggedPDF; FixedText maFtTaggedPDF; CheckBox maCbExportNotes; FixedText maFtExportNotes; CheckBox maCbTransitionEffects; FixedText maFtTransitionEffects; FixedText maFtFormsFormat; ListBox maLbFormsFormat; OKButton maBtnOK; CancelButton maBtnCancel; HelpButton maBtnHelp; FilterConfigItem maConfigItem; Any maSelection; sal_Bool mbIsPresentation; DECL_LINK( TogglePagesHdl, void* ); DECL_LINK( ToggleCompressionHdl, void* ); DECL_LINK( ToggleReduceImageResolutionHdl, void* ); public: ImpPDFDialog( Window* pParent, ResMgr& rResMgr, Sequence< PropertyValue >& rFilterData, const Reference< XComponent >& rDoc ); ~ImpPDFDialog(); Sequence< PropertyValue > GetFilterData(); }; #endif // IMPDIALOG_HXX <commit_msg>INTEGRATION: CWS pdf02 (1.8.4); FILE MERGED 2004/10/08 11:55:41 pl 1.8.4.1: #i35137# use metric field with percent units<commit_after>/************************************************************************* * * $RCSfile: impdialog.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: pjunck $ $Date: 2004-10-28 09:40:04 $ * * 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 IMPDIALOG_HXX #define IMPDIALOG_HXX #include "pdffilter.hxx" #include <vcl/dialog.hxx> #include <vcl/button.hxx> #include <vcl/fixed.hxx> #include <vcl/field.hxx> #include <vcl/edit.hxx> #include <vcl/lstbox.hxx> #include <vcl/combobox.hxx> #include <svtools/FilterConfigItem.hxx> // ---------------- // - ImpPDFDialog - // ---------------- class ResMgr; class ImpPDFDialog : public ModalDialog { private: FixedLine maFlPages; RadioButton maRbAll; RadioButton maRbRange; RadioButton maRbSelection; Edit maEdPages; FixedLine maFlCompression; RadioButton maRbLosslessCompression; RadioButton maRbJPEGCompression; FixedText maFtQuality; MetricField maNfQuality; CheckBox maCbReduceImageResolution; FixedText maFtReduceImageResolution; ComboBox maCoReduceImageResolution; FixedLine maFlGeneral; CheckBox maCbTaggedPDF; FixedText maFtTaggedPDF; CheckBox maCbExportNotes; FixedText maFtExportNotes; CheckBox maCbTransitionEffects; FixedText maFtTransitionEffects; FixedText maFtFormsFormat; ListBox maLbFormsFormat; OKButton maBtnOK; CancelButton maBtnCancel; HelpButton maBtnHelp; FilterConfigItem maConfigItem; Any maSelection; sal_Bool mbIsPresentation; DECL_LINK( TogglePagesHdl, void* ); DECL_LINK( ToggleCompressionHdl, void* ); DECL_LINK( ToggleReduceImageResolutionHdl, void* ); public: ImpPDFDialog( Window* pParent, ResMgr& rResMgr, Sequence< PropertyValue >& rFilterData, const Reference< XComponent >& rDoc ); ~ImpPDFDialog(); Sequence< PropertyValue > GetFilterData(); }; #endif // IMPDIALOG_HXX <|endoftext|>
<commit_before>/** * @author See Contributors.txt for code contributors and overview of BadgerDB. * * @section LICENSE * Copyright (c) 2012 Database Group, Computer Sciences Department, University of Wisconsin-Madison. */ #include <memory> #include <iostream> #include "buffer.h" #include "exceptions/buffer_exceeded_exception.h" #include "exceptions/page_not_pinned_exception.h" #include "exceptions/page_pinned_exception.h" #include "exceptions/bad_buffer_exception.h" #include "exceptions/hash_not_found_exception.h" namespace badgerdb { // Constructor for BufMgr BufMgr::BufMgr(std::uint32_t bufs) : numBufs(bufs) { bufDescTable = new BufDesc[bufs]; for (FrameId i = 0; i < bufs; i++) { bufDescTable[i].frameNo = i; bufDescTable[i].valid = false; } bufPool = new Page[bufs]; int htsize = ((((int) (bufs * 1.2))*2)/2)+1; hashTable = new BufHashTbl (htsize); // allocate the buffer hash table clockHand = bufs - 1; } // Destructor for BufMgr BufMgr::~BufMgr() { } // Advances clock to next frame in the buffer pool void BufMgr::advanceClock() { } // Allocate a free frame void BufMgr::allocBuf(FrameId & frame) { } // Reads the given page from the file into a frame and returns the pointer to page // If the requested page is already present in the buffer pool, // pointer to that frame is returned // Else a new frame is allocated from the buffer pool for reading the page void BufMgr::readPage(File* file, const PageId pageNo, Page*& page) { } // Unpin a page from memory since it is no longer required for it to remain in memory void BufMgr::unPinPage(File* file, const PageId pageNo, const bool dirty) { } // Writes out all dirty pages of the file to disk // All frames assigned to the file need to be unpinned from buffer pool before this works // Else ERROR void BufMgr::flushFile(const File* file) { } // Allocates a new, empty page in the file and returns the Page object // The new page is also assigned a frame in the buffer pool void BufMgr::allocPage(File* file, PageId &pageNo, Page*& page) { } // Delete a page from file and also from buffer pool if present // Don't need to check if page is dirty void BufMgr::disposePage(File* file, const PageId PageNo) { } // Print member variable values // Don't change this void BufMgr::printSelf(void) { BufDesc* tmpbuf; int validFrames = 0; for (std::uint32_t i = 0; i < numBufs; i++) { tmpbuf = &(bufDescTable[i]); std::cout << "FrameNo:" << i << " "; tmpbuf->Print(); if (tmpbuf->valid == true) validFrames++; } std::cout << "Total Number of Valid Frames:" << validFrames << "\n"; } } <commit_msg>Started readPage, allocPage, and disposePage<commit_after>/** * @author See Contributors.txt for code contributors and overview of BadgerDB. * * @section LICENSE * Copyright (c) 2012 Database Group, Computer Sciences Department, University of Wisconsin-Madison. */ #include <memory> #include <iostream> #include "buffer.h" #include "exceptions/buffer_exceeded_exception.h" #include "exceptions/page_not_pinned_exception.h" #include "exceptions/page_pinned_exception.h" #include "exceptions/bad_buffer_exception.h" #include "exceptions/hash_not_found_exception.h" namespace badgerdb { // Constructor for BufMgr BufMgr::BufMgr(std::uint32_t bufs) : numBufs(bufs) { bufDescTable = new BufDesc[bufs]; for (FrameId i = 0; i < bufs; i++) { bufDescTable[i].frameNo = i; bufDescTable[i].valid = false; } bufPool = new Page[bufs]; int htsize = ((((int) (bufs * 1.2))*2)/2)+1; hashTable = new BufHashTbl (htsize); // allocate the buffer hash table clockHand = bufs - 1; } // Destructor for BufMgr BufMgr::~BufMgr() { } // Advances clock to next frame in the buffer pool void BufMgr::advanceClock() { // FrameId (uint32_t) clockHand // Check if clockHand has reached numBufs - 1 if (clockHand == numBufs - 1) { clockHand = 0; } else { clockHand++; } } // Allocate a free frame void BufMgr::allocBuf(FrameId & frame) { } // Reads the given page from the file into a frame and returns the pointer to page // If the requested page is already present in the buffer pool, // pointer to that frame is returned // Else a new frame is allocated from the buffer pool for reading the page void BufMgr::readPage(File* file, const PageId pageNo, Page*& page) { // Pointer might fudge this up Page pageRead = file.readPage(pageNo, false); // second param prevents reading unused pages } // Unpin a page from memory since it is no longer required for it to remain in memory void BufMgr::unPinPage(File* file, const PageId pageNo, const bool dirty) { } // Writes out all dirty pages of the file to disk // All frames assigned to the file need to be unpinned from buffer pool before this works // Else ERROR void BufMgr::flushFile(const File* file) { } // Allocates a new, empty page in the file and returns the Page object // The new page is also assigned a frame in the buffer pool void BufMgr::allocPage(File* file, PageId &pageNo, Page*& page) { // Gotta do some pointer BS with these Page newPage = file.allocatePage(); PageId newPageNumber = newPage.page_number(); } // Delete a page from file and also from buffer pool if present // Don't need to check if page is dirty void BufMgr::disposePage(File* file, const PageId PageNo) { // must either use or be similar to these I think file.deletePage(PageNo); } // Print member variable values // Don't change this void BufMgr::printSelf(void) { BufDesc* tmpbuf; int validFrames = 0; for (std::uint32_t i = 0; i < numBufs; i++) { tmpbuf = &(bufDescTable[i]); std::cout << "FrameNo:" << i << " "; tmpbuf->Print(); if (tmpbuf->valid == true) validFrames++; } std::cout << "Total Number of Valid Frames:" << validFrames << "\n"; } } <|endoftext|>
<commit_before>#include <cstdio> #include <memory> #include <boost/filesystem.hpp> #include "paxos/bootstrap.hpp" #include "paxos/handler.hpp" #include "paxos/serialization.hpp" namespace paxos { void EmptyDecreeHandler::operator()(std::string entry) { } CompositeHandler::CompositeHandler() : handlers() { } CompositeHandler::CompositeHandler(Handler handler) : handlers() { AddHandler(handler); } void CompositeHandler::operator()(std::string entry) { for (auto h : handlers) { h(entry); } } void CompositeHandler::AddHandler(Handler handler) { handlers.push_back(handler); } HandleAddReplica::HandleAddReplica( std::string location, Replica legislator, std::shared_ptr<ReplicaSet>& legislators, std::shared_ptr<Signal> signal, std::function<void( std::shared_ptr<ReplicaSet>, std::ostream&)> save_replicaset) : location(location), legislator(legislator), legislators(legislators), signal(signal), save_replicaset(save_replicaset) { } void HandleAddReplica::operator()(std::string entry) { UpdateReplicaSetDecree decree = Deserialize<UpdateReplicaSetDecree>(entry); legislators->Add(decree.replica); std::ofstream replicasetfile( (boost::filesystem::path(location) / boost::filesystem::path(ReplicasetFilename)).string()); save_replicaset(legislators, replicasetfile); // Only decree author sends bootstrap. if (decree.author.hostname == legislator.hostname && decree.author.port == legislator.port) { std::vector<boost::filesystem::directory_entry> filepaths; if(boost::filesystem::is_directory(location)) { std::copy(boost::filesystem::directory_iterator(location), boost::filesystem::directory_iterator(), std::back_inserter(filepaths)); } SendBootstrap( location, decree.remote_directory, filepaths, [&](BootstrapFile file){ NetworkFileSender<BoostTransport> sender; sender.SendFile(decree.replica, file); }); signal->Set(true); } } HandleRemoveReplica::HandleRemoveReplica( std::string location, Replica legislator, std::shared_ptr<ReplicaSet>& legislators, std::shared_ptr<Signal> signal, std::function<void( std::shared_ptr<ReplicaSet>, std::ostream&)> save_replicaset) : location(location), legislator(legislator), legislators(legislators), signal(signal), save_replicaset(save_replicaset) { } void HandleRemoveReplica::operator()(std::string entry) { UpdateReplicaSetDecree decree = Deserialize<UpdateReplicaSetDecree>(entry); legislators->Remove(decree.replica); std::ofstream replicasetfile( (boost::filesystem::path(location) / boost::filesystem::path(ReplicasetFilename)).string()); save_replicaset(legislators, replicasetfile); if (decree.author.hostname == legislator.hostname && decree.author.port == legislator.port) { signal->Set(true); } } } <commit_msg>Fix possible hang during remove replica<commit_after>#include <cstdio> #include <memory> #include <boost/filesystem.hpp> #include "paxos/bootstrap.hpp" #include "paxos/handler.hpp" #include "paxos/serialization.hpp" namespace paxos { void EmptyDecreeHandler::operator()(std::string entry) { } CompositeHandler::CompositeHandler() : handlers() { } CompositeHandler::CompositeHandler(Handler handler) : handlers() { AddHandler(handler); } void CompositeHandler::operator()(std::string entry) { for (auto h : handlers) { h(entry); } } void CompositeHandler::AddHandler(Handler handler) { handlers.push_back(handler); } HandleAddReplica::HandleAddReplica( std::string location, Replica legislator, std::shared_ptr<ReplicaSet>& legislators, std::shared_ptr<Signal> signal, std::function<void( std::shared_ptr<ReplicaSet>, std::ostream&)> save_replicaset) : location(location), legislator(legislator), legislators(legislators), signal(signal), save_replicaset(save_replicaset) { } void HandleAddReplica::operator()(std::string entry) { UpdateReplicaSetDecree decree = Deserialize<UpdateReplicaSetDecree>(entry); legislators->Add(decree.replica); std::ofstream replicasetfile( (boost::filesystem::path(location) / boost::filesystem::path(ReplicasetFilename)).string()); save_replicaset(legislators, replicasetfile); // Only decree author sends bootstrap. if (decree.author.hostname == legislator.hostname && decree.author.port == legislator.port) { std::vector<boost::filesystem::directory_entry> filepaths; if(boost::filesystem::is_directory(location)) { std::copy(boost::filesystem::directory_iterator(location), boost::filesystem::directory_iterator(), std::back_inserter(filepaths)); } SendBootstrap( location, decree.remote_directory, filepaths, [&](BootstrapFile file){ NetworkFileSender<BoostTransport> sender; sender.SendFile(decree.replica, file); }); signal->Set(true); } } HandleRemoveReplica::HandleRemoveReplica( std::string location, Replica legislator, std::shared_ptr<ReplicaSet>& legislators, std::shared_ptr<Signal> signal, std::function<void( std::shared_ptr<ReplicaSet>, std::ostream&)> save_replicaset) : location(location), legislator(legislator), legislators(legislators), signal(signal), save_replicaset(save_replicaset) { } void HandleRemoveReplica::operator()(std::string entry) { UpdateReplicaSetDecree decree = Deserialize<UpdateReplicaSetDecree>(entry); legislators->Remove(decree.replica); std::ofstream replicasetfile( (boost::filesystem::path(location) / boost::filesystem::path(ReplicasetFilename)).string()); save_replicaset(legislators, replicasetfile); signal->Set(true); } } <|endoftext|>
<commit_before>/* * Circles implementation for the GauntletII project. */ #include "Effect.h" #define SPRITE_WIDTH 9 #define SPRITE_HEIGHT 9 static uint8_t heartData[SPRITE_WIDTH * SPRITE_HEIGHT] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static uint8_t ghostData[SPRITE_WIDTH * SPRITE_HEIGHT] = { 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, }; class Sprite : public Effect { private: int spriteWidth, spriteHeight; public: Sprite(CRGB *leds, int width, int height) : Effect(leds, width, height), spriteWidth(SPRITE_WIDTH), spriteHeight(SPRITE_HEIGHT) { } void start() { for (int i = 0; i < 400; i++) { if (random(100) > 98) { blit(ghostData, 178, random(0, width - spriteWidth), random(0, height - spriteHeight)); } else { blit(heartData, 0, random(0, width - spriteWidth), random(0, height - spriteHeight)); } LEDS.show(); delay(100); for (int i = 0; i < width * height; i++) { leds[i].fadeToBlackBy(64); } } } void blit(uint8_t *sprite, uint8_t hue, int x, int y) { uint8_t saturation = random(8, 16) * 16; for (int spx = 0; spx < spriteWidth; spx++) { for (int spy = 0; spy < spriteHeight; spy++) { if (inXRange(spx + x) && inYRange(spy + y)) { uint8_t spritePixel = sprite[spy * spriteHeight + spx]; if (spritePixel) { pixel(spx + x, spy + y) = CHSV(hue, saturation, spritePixel); } } } } } }; <commit_msg>rename LEDS > FastLED<commit_after>/* * Circles implementation for the GauntletII project. */ #include "Effect.h" #define SPRITE_WIDTH 9 #define SPRITE_HEIGHT 9 static uint8_t heartData[SPRITE_WIDTH * SPRITE_HEIGHT] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static uint8_t ghostData[SPRITE_WIDTH * SPRITE_HEIGHT] = { 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, }; class Sprite : public Effect { private: int spriteWidth, spriteHeight; public: Sprite(CRGB *leds, int width, int height) : Effect(leds, width, height), spriteWidth(SPRITE_WIDTH), spriteHeight(SPRITE_HEIGHT) { } void start() { for (int i = 0; i < 400; i++) { if (random(100) > 98) { blit(ghostData, 178, random(0, width - spriteWidth), random(0, height - spriteHeight)); } else { blit(heartData, 0, random(0, width - spriteWidth), random(0, height - spriteHeight)); } FastLED.show(); delay(100); for (int i = 0; i < width * height; i++) { leds[i].fadeToBlackBy(64); } } } void blit(uint8_t *sprite, uint8_t hue, int x, int y) { uint8_t saturation = random(8, 16) * 16; for (int spx = 0; spx < spriteWidth; spx++) { for (int spy = 0; spy < spriteHeight; spy++) { if (inXRange(spx + x) && inYRange(spy + y)) { uint8_t spritePixel = sprite[spy * spriteHeight + spx]; if (spritePixel) { pixel(spx + x, spy + y) = CHSV(hue, saturation, spritePixel); } } } } } }; <|endoftext|>
<commit_before>/* * Copyright(c) Records For Living, Inc. 2004-2012. All rights reserved */ // TEST Foundation::Traveral #include "Stroika/Foundation/StroikaPreComp.h" #include "Stroika/Foundation/Debug/Assertions.h" #include "Stroika/Foundation/Configuration/Enumeration.h" #include "Stroika/Foundation/Traversal/DiscreteRange.h" #include "Stroika/Foundation/Traversal/Range.h" #include "../TestHarness/TestHarness.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Traversal; namespace { void Test_1_BasicRange_ () { { Range<int> r (3, 5); VerifyTestResult (not r.empty ()); VerifyTestResult (r.Contains (3)); } { Range<int> r1 (3, 5); Range<int> r2 (5, 6); VerifyTestResult (not r1.Overlaps (r2)); VerifyTestResult (not r2.Overlaps (r1)); Range<int> r3 = r1; VerifyTestResult (r1.Overlaps (r3)); VerifyTestResult (r3.Overlaps (r1)); } } void Test_2_BasicDiscreteRangeIteration_ () { #if 0 { DiscreteRange<int> r (3, 5); VerifyTestResult (not r.empty ()); VerifyTestResult (r.Contains (3)); } { int nItemsHit = 0; int lastItemHit = 0; for (auto i : DiscreteRange<int> (3, 5)) { nItemsHit++; VerifyTestResult (lastItemHit < i); lastItemHit = i; } VerifyTestResult (lastItemHit == 5); /// IN DISCUSSION - OPEN ENDED RHS? } #endif } } namespace { void Test_3_SimpleDiscreteRangeWithEnumsTest_ () { // NYI - but do stuff like: enum class Color { red, blue, green, Define_Start_End_Count (red, green) }; #if 0 { int nItemsHit = 0; Color lastItemHit = Color::red; for (auto i : DiscreteRange<Color> (Optional<Color> (), Optional<Color> ())) { nItemsHit++; VerifyTestResult (lastItemHit < i); lastItemHit = i; } nItemsHit (lastItemHit == 3); VerifyTestResult (lastItemHit == Color::green); } #endif } } namespace { void DoRegressionTests_ () { Test_1_BasicRange_ (); Test_2_BasicDiscreteRangeIteration_ (); Test_3_SimpleDiscreteRangeWithEnumsTest_ (); } } int main (int argc, const char* argv[]) { Stroika::TestHarness::Setup (); Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); return EXIT_SUCCESS; } <commit_msg>more Range type regression tests (not working yet - just to document idea)<commit_after>/* * Copyright(c) Records For Living, Inc. 2004-2012. All rights reserved */ // TEST Foundation::Traveral #include "Stroika/Foundation/StroikaPreComp.h" #include "Stroika/Foundation/Debug/Assertions.h" #include "Stroika/Foundation/Configuration/Enumeration.h" #include "Stroika/Foundation/Traversal/DiscreteRange.h" #include "Stroika/Foundation/Traversal/Range.h" #include "../TestHarness/TestHarness.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Traversal; namespace { void Test_1_BasicRange_ () { { Range<int> r (3, 5); VerifyTestResult (not r.empty ()); VerifyTestResult (r.Contains (3)); } { Range<int> r1 (3, 5); Range<int> r2 (5, 6); VerifyTestResult (not r1.Overlaps (r2)); VerifyTestResult (not r2.Overlaps (r1)); Range<int> r3 = r1; VerifyTestResult (r1.Overlaps (r3)); VerifyTestResult (r3.Overlaps (r1)); } } void Test_2_BasicDiscreteRangeIteration_ () { #if 0 { DiscreteRange<int> r (3, 5); VerifyTestResult (not r.empty ()); VerifyTestResult (r.Contains (3)); } { int nItemsHit = 0; int lastItemHit = 0; for (auto i : DiscreteRange<int> (3, 5)) { nItemsHit++; VerifyTestResult (lastItemHit < i); lastItemHit = i; } VerifyTestResult (lastItemHit == 5); /// IN DISCUSSION - OPEN ENDED RHS? } #endif } } namespace { void Test_3_SimpleDiscreteRangeWithEnumsTest_ () { // NYI - but do stuff like: enum class Color { red, blue, green, Define_Start_End_Count (red, green) }; #if 0 { int nItemsHit = 0; Color lastItemHit = Color::red; for (auto i : DiscreteRange<Color> (Optional<Color> (), Optional<Color> ())) { nItemsHit++; VerifyTestResult (lastItemHit < i); lastItemHit = i; } nItemsHit (lastItemHit == 3); VerifyTestResult (lastItemHit == Color::green); } { int nItemsHit = 0; Color lastItemHit = Color::red; DiscreteRange<Color> (Optional<Color> (), Optional<Color> ()).Apply ([&nItemsHit, &lastItemHit] (Color c) { nItemsHit++; VerifyTestResult (lastItemHit < i); lastItemHit = i; }); nItemsHit (lastItemHit == 3); VerifyTestResult (lastItemHit == Color::green); } #endif } } namespace { void DoRegressionTests_ () { Test_1_BasicRange_ (); Test_2_BasicDiscreteRangeIteration_ (); Test_3_SimpleDiscreteRangeWithEnumsTest_ (); } } int main (int argc, const char* argv[]) { Stroika::TestHarness::Setup (); Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dbregisterednamesconfig.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-06-27 17:00:31 $ * * 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_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif #include "dbregisterednamesconfig.hxx" #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #include <svx/svxids.hrc> #ifndef _UNOTOOLS_CONFIGNODE_HXX_ #include <unotools/confignode.hxx> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XNAMINGSERVICE_HPP_ #include <com/sun/star/uno/XNamingService.hpp> #endif #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef SVX_DBREGISTERSETTING_HXX #include "dbregistersettings.hxx" #endif #ifndef _OFFAPP_CONNPOOLOPTIONS_HXX_ #include "connpooloptions.hxx" #endif //........................................................................ namespace svx { //........................................................................ using namespace ::utl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; //-------------------------------------------------------------------- static const ::rtl::OUString& getDbRegisteredNamesNodeName() { static ::rtl::OUString s_sNodeName = ::rtl::OUString::createFromAscii("org.openoffice.Office.DataAccess/RegisteredNames"); return s_sNodeName; } //-------------------------------------------------------------------- static const ::rtl::OUString& getDbNameNodeName() { static ::rtl::OUString s_sNodeName = ::rtl::OUString::createFromAscii("Name"); return s_sNodeName; } //-------------------------------------------------------------------- static const ::rtl::OUString& getDbLocationNodeName() { static ::rtl::OUString s_sNodeName = ::rtl::OUString::createFromAscii("Location"); return s_sNodeName; } //==================================================================== //= DbRegisteredNamesConfig //==================================================================== //-------------------------------------------------------------------- void DbRegisteredNamesConfig::GetOptions(SfxItemSet& _rFillItems) { // the config node where all pooling relevant info are stored under OConfigurationTreeRoot aDbRegisteredNamesRoot = OConfigurationTreeRoot::createWithServiceFactory( ::comphelper::getProcessServiceFactory(), getDbRegisteredNamesNodeName(), -1, OConfigurationTreeRoot::CM_READONLY); TNameLocationMap aSettings; // then look for which of them settings are stored in the configuration Sequence< ::rtl::OUString > aDriverKeys = aDbRegisteredNamesRoot.getNodeNames(); const ::rtl::OUString* pDriverKeys = aDriverKeys.getConstArray(); const ::rtl::OUString* pDriverKeysEnd = pDriverKeys + aDriverKeys.getLength(); for (;pDriverKeys != pDriverKeysEnd; ++pDriverKeys) { // the name of the driver in this round OConfigurationNode aThisDriverSettings = aDbRegisteredNamesRoot.openNode(*pDriverKeys); ::rtl::OUString sName, sLocation; aThisDriverSettings.getNodeValue(getDbNameNodeName()) >>= sName; aThisDriverSettings.getNodeValue(getDbLocationNodeName()) >>= sLocation; sLocation = SvtPathOptions().SubstituteVariable(sLocation); aSettings.insert(TNameLocationMap::value_type(sName,sLocation)); } _rFillItems.Put(DatabaseMapItem(SID_SB_DB_REGISTER, aSettings)); } //-------------------------------------------------------------------- void DbRegisteredNamesConfig::SetOptions(const SfxItemSet& _rSourceItems) { // the config node where all pooling relevant info are stored under OConfigurationTreeRoot aDbRegisteredNamesRoot = OConfigurationTreeRoot::createWithServiceFactory( ::comphelper::getProcessServiceFactory(), getDbRegisteredNamesNodeName(), -1, OConfigurationTreeRoot::CM_UPDATABLE); if (!aDbRegisteredNamesRoot.isValid()) // already asserted by the OConfigurationTreeRoot return; sal_Bool bNeedCommit = sal_False; // the settings for the single drivers SFX_ITEMSET_GET( _rSourceItems, pDriverSettings, DatabaseMapItem, SID_SB_DB_REGISTER, sal_True ); if (pDriverSettings) { Reference< XNameAccess > xDatabaseContext = Reference< XNameAccess >(::comphelper::getProcessServiceFactory()->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.DatabaseContext"))), UNO_QUERY); Reference< XNamingService> xNamingService(xDatabaseContext,UNO_QUERY); ::rtl::OUString sName, sLocation; OConfigurationNode aThisDriverSettings; const TNameLocationMap& rNewSettings = pDriverSettings->getSettings(); TNameLocationMap::const_iterator aEnd = rNewSettings.end(); for ( TNameLocationMap::const_iterator aLoop = rNewSettings.begin(); aLoop != aEnd; ++aLoop ) { // need the name as ::rtl::OUString sName = aLoop->first; // the sub-node for this driver if (aDbRegisteredNamesRoot.hasByName(sName)) { aThisDriverSettings = aDbRegisteredNamesRoot.openNode(sName); // set the values aThisDriverSettings.setNodeValue(getDbNameNodeName(), makeAny(sName)); aThisDriverSettings.setNodeValue(getDbLocationNodeName(), makeAny(aLoop->second)); bNeedCommit = sal_True; } else xNamingService->registerObject(sName,Reference< ::com::sun::star::uno::XInterface >(xDatabaseContext->getByName(aLoop->second),UNO_QUERY)); } if (bNeedCommit) aDbRegisteredNamesRoot.commit(); // delete unused entry Sequence< ::rtl::OUString > aDriverKeys = xDatabaseContext->getElementNames(); const ::rtl::OUString* pDriverKeys = aDriverKeys.getConstArray(); const ::rtl::OUString* pDriverKeysEnd = pDriverKeys + aDriverKeys.getLength(); for (;pDriverKeys != pDriverKeysEnd; ++pDriverKeys) { if ( rNewSettings.find(*pDriverKeys) == rNewSettings.end() ) xNamingService->revokeObject(*pDriverKeys); } } } //........................................................................ } // namespace svx //........................................................................ <commit_msg>INTEGRATION: CWS dba24a (1.7.76); FILE MERGED 2007/09/04 07:22:36 oj 1.7.76.1: #i72987# check for url<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dbregisterednamesconfig.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-09-26 14:36:52 $ * * 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_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif #include "dbregisterednamesconfig.hxx" #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #include <svx/svxids.hrc> #ifndef _UNOTOOLS_CONFIGNODE_HXX_ #include <unotools/confignode.hxx> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XNAMINGSERVICE_HPP_ #include <com/sun/star/uno/XNamingService.hpp> #endif #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef SVX_DBREGISTERSETTING_HXX #include "dbregistersettings.hxx" #endif #ifndef _OFFAPP_CONNPOOLOPTIONS_HXX_ #include "connpooloptions.hxx" #endif //........................................................................ namespace svx { //........................................................................ using namespace ::utl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; //-------------------------------------------------------------------- static const ::rtl::OUString& getDbRegisteredNamesNodeName() { static ::rtl::OUString s_sNodeName = ::rtl::OUString::createFromAscii("org.openoffice.Office.DataAccess/RegisteredNames"); return s_sNodeName; } //-------------------------------------------------------------------- static const ::rtl::OUString& getDbNameNodeName() { static ::rtl::OUString s_sNodeName = ::rtl::OUString::createFromAscii("Name"); return s_sNodeName; } //-------------------------------------------------------------------- static const ::rtl::OUString& getDbLocationNodeName() { static ::rtl::OUString s_sNodeName = ::rtl::OUString::createFromAscii("Location"); return s_sNodeName; } //==================================================================== //= DbRegisteredNamesConfig //==================================================================== //-------------------------------------------------------------------- void DbRegisteredNamesConfig::GetOptions(SfxItemSet& _rFillItems) { // the config node where all pooling relevant info are stored under OConfigurationTreeRoot aDbRegisteredNamesRoot = OConfigurationTreeRoot::createWithServiceFactory( ::comphelper::getProcessServiceFactory(), getDbRegisteredNamesNodeName(), -1, OConfigurationTreeRoot::CM_READONLY); TNameLocationMap aSettings; // then look for which of them settings are stored in the configuration Sequence< ::rtl::OUString > aDriverKeys = aDbRegisteredNamesRoot.getNodeNames(); const ::rtl::OUString* pDriverKeys = aDriverKeys.getConstArray(); const ::rtl::OUString* pDriverKeysEnd = pDriverKeys + aDriverKeys.getLength(); for (;pDriverKeys != pDriverKeysEnd; ++pDriverKeys) { // the name of the driver in this round OConfigurationNode aThisDriverSettings = aDbRegisteredNamesRoot.openNode(*pDriverKeys); ::rtl::OUString sName, sLocation; aThisDriverSettings.getNodeValue(getDbNameNodeName()) >>= sName; aThisDriverSettings.getNodeValue(getDbLocationNodeName()) >>= sLocation; sLocation = SvtPathOptions().SubstituteVariable(sLocation); aSettings.insert(TNameLocationMap::value_type(sName,sLocation)); } _rFillItems.Put(DatabaseMapItem(SID_SB_DB_REGISTER, aSettings)); } //-------------------------------------------------------------------- void DbRegisteredNamesConfig::SetOptions(const SfxItemSet& _rSourceItems) { // the config node where all pooling relevant info are stored under OConfigurationTreeRoot aDbRegisteredNamesRoot = OConfigurationTreeRoot::createWithServiceFactory( ::comphelper::getProcessServiceFactory(), getDbRegisteredNamesNodeName(), -1, OConfigurationTreeRoot::CM_UPDATABLE); if (!aDbRegisteredNamesRoot.isValid()) // already asserted by the OConfigurationTreeRoot return; sal_Bool bNeedCommit = sal_False; // the settings for the single drivers SFX_ITEMSET_GET( _rSourceItems, pDriverSettings, DatabaseMapItem, SID_SB_DB_REGISTER, sal_True ); if (pDriverSettings) { Reference< XNameAccess > xDatabaseContext = Reference< XNameAccess >(::comphelper::getProcessServiceFactory()->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.DatabaseContext"))), UNO_QUERY); Reference< XNamingService> xNamingService(xDatabaseContext,UNO_QUERY); ::rtl::OUString sName, sLocation; OConfigurationNode aThisDriverSettings; const TNameLocationMap& rNewSettings = pDriverSettings->getSettings(); TNameLocationMap::const_iterator aEnd = rNewSettings.end(); for ( TNameLocationMap::const_iterator aLoop = rNewSettings.begin(); aLoop != aEnd; ++aLoop ) { // need the name as ::rtl::OUString sName = aLoop->first; // the sub-node for this driver if (aDbRegisteredNamesRoot.hasByName(sName)) { aThisDriverSettings = aDbRegisteredNamesRoot.openNode(sName); // set the values aThisDriverSettings.setNodeValue(getDbNameNodeName(), makeAny(sName)); aThisDriverSettings.setNodeValue(getDbLocationNodeName(), makeAny(aLoop->second)); bNeedCommit = sal_True; } else { try { xNamingService->registerObject(sName,Reference< ::com::sun::star::uno::XInterface >(xDatabaseContext->getByName(aLoop->second),UNO_QUERY)); } catch(Exception&) { OSL_ENSURE(0,"Could not register new database!"); } } } if (bNeedCommit) aDbRegisteredNamesRoot.commit(); // delete unused entry Sequence< ::rtl::OUString > aDriverKeys = xDatabaseContext->getElementNames(); const ::rtl::OUString* pDriverKeys = aDriverKeys.getConstArray(); const ::rtl::OUString* pDriverKeysEnd = pDriverKeys + aDriverKeys.getLength(); for (;pDriverKeys != pDriverKeysEnd; ++pDriverKeys) { if ( rNewSettings.find(*pDriverKeys) == rNewSettings.end() ) xNamingService->revokeObject(*pDriverKeys); } } } //........................................................................ } // namespace svx //........................................................................ <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "PositionTracker.h" /* implementation system headers */ #include <iostream> #include <string> /* implementation common headers */ #include "MathUtils.h" /* private */ /* protected */ /* public: */ PositionTracker::PositionTracker() { return; } PositionTracker::PositionTracker(const PositionTracker& tracker) : _trackedItem(tracker._trackedItem), _waypointDistance(tracker._waypointDistance) { return; } PositionTracker::~PositionTracker() { // clear out all the tracked items vectors for (std::map<std::string, TrackedItemVector>::iterator jano = _trackedItem.begin(); jano != _trackedItem.end(); jano++) { TrackedItemVector& trackSet = (*jano).second; for (unsigned int i = 0; i != trackSet.size(); i++) { /* sanity clear */ trackSet[i]->id = UNSET_ID; trackSet[i]->intID = 0; trackSet[i]->strID = std::string(""); trackSet[i]->lastUpdate = TimeKeeper::getNullTime(); trackSet[i]->position[0] = trackSet[i]->position[1] = trackSet[i]->position[2] = 0.0; trackSet[i]->forgotten = true; delete trackSet[i]; } } _trackedItem.clear(); // clear out any waypoints _waypointDistance.clear(); return; } /* Linear O(n) time to track a new item since the entire vector is * searched. if the item is not found, an item is created and added. */ unsigned short PositionTracker::track(const std::string id, std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; for (unsigned int i = 0; i != trackSet.size(); i++) { switch (trackSet[i]->id) { case STR_ID: if (id == trackSet[i]->strID) { return i; } break; case INT_ID: case UNSET_ID: break; default: std::cerr << "Unknown tracker ID type (id == " << trackSet[i]->id << ")" << std::endl; break; } } // the item was not found, so create it item_t *newTracking = new item_t; newTracking->id = STR_ID; newTracking->intID = 0; newTracking->strID = id; newTracking->lastUpdate = TimeKeeper::getNullTime(); newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0; newTracking->forgotten = false; // and add it trackSet.push_back(newTracking); // nothing is deleted so should be last index return trackSet.size() - 1; } /* alternative track() passing our own id */ unsigned short PositionTracker::track(long int id, std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; for (unsigned int i = 0; i != trackSet.size(); i++) { switch (trackSet[i]->id) { case INT_ID: if (id == trackSet[i]->intID) { return i; } break; case STR_ID: case UNSET_ID: break; default: std::cerr << "Unknown tracker ID type (id == " << trackSet[i]->id << ")" << std::endl; break; } } // the item was not found, so create it item_t *newTracking = new item_t; newTracking->id = INT_ID; newTracking->intID = id; newTracking->strID = std::string(""); newTracking->lastUpdate = TimeKeeper::getNullTime(); newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0; newTracking->forgotten = false; // and add it trackSet.push_back(newTracking); // nothing is deleted so should be last index return trackSet.size() - 1; } bool PositionTracker::update(unsigned short int token, const std::string id, const double position[3], std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; if ((token >= trackSet.size()) || (trackSet[token]->id != STR_ID) || (trackSet[token]->strID != id) || (trackSet[token]->forgotten)) { return false; } trackSet[token]->position[0] = position[0]; trackSet[token]->position[1] = position[1]; trackSet[token]->position[2] = position[2]; trackSet[token]->lastUpdate = TimeKeeper::getCurrent(); return true; } bool PositionTracker::update(unsigned short int token, const std::string id, const float position[3], std::string group) { double pos[3]; pos[0] = (double)position[0]; pos[1] = (double)position[1]; pos[2] = (double)position[2]; return update(token, id, pos, group); } bool PositionTracker::update(unsigned short int token, long int id, const double position[3], std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; if ((token >= trackSet.size()) || (trackSet[token]->id != INT_ID) || (trackSet[token]->intID != id) || (trackSet[token]->forgotten)) { return false; } trackSet[token]->position[0] = position[0]; trackSet[token]->position[1] = position[1]; trackSet[token]->position[2] = position[2]; trackSet[token]->lastUpdate = TimeKeeper::getCurrent(); return true; } bool PositionTracker::update(unsigned short int token, long int id, const float position[3], std::string group) { double pos[3]; pos[0] = (double)position[0]; pos[1] = (double)position[1]; pos[2] = (double)position[2]; return update(token, id, pos, group); } bool PositionTracker::addWaypoint(const double from[3], const double to[3], double distance) { unsigned short int fromToken, toToken; bool updated; bool foundPoint; unsigned int i; TrackedItemVector& waypointSet = _trackedItem[std::string("__waypoint__")]; // see if the first point already exists foundPoint = false; for (i = 0; i != waypointSet.size(); i++) { if ((waypointSet[i]->position[0] = from[0]) && (waypointSet[i]->position[1] = from[1]) && (waypointSet[i]->position[2] = from[2])) { foundPoint = true; fromToken = waypointSet[i]->intID; } } if (!foundPoint) { // add the first point unsigned short int nextID = waypointSet.size(); fromToken = track((long int)nextID, std::string("__waypoint__")); updated = update(fromToken, nextID, from, std::string("__waypoint__")); if (!updated) { std::cerr << "Unable to add waypoint?!" << std::endl; return false; } } // see if the second point already exists foundPoint = false; for (i = 0; i != waypointSet.size(); i++) { if ((waypointSet[i]->position[0] = to[0]) && (waypointSet[i]->position[1] = to[1]) && (waypointSet[i]->position[2] = to[2])) { foundPoint = true; toToken = waypointSet[i]->intID; } } if (!foundPoint) { // add the second point unsigned short int nextID = waypointSet.size(); toToken = track((long int)nextID, std::string("__waypoint__")); updated = update(toToken, nextID, to, std::string("__waypoint__")); if (!updated) { std::cerr << "Unable to add waypoint?!" << std::endl; return false; } } // compute and use real distance if distance passed was negative if (distance < 0.0) { distance = distanceBetween(fromToken, toToken, std::string("__waypoint__"), std::string("__waypoint__")); } std::pair<unsigned short int, unsigned short int> waypoint = std::make_pair(fromToken, toToken); // see if the waypoint pair have already been added /* std::map<std::pair<unsigned short int, unsigned short int>, double>::iterator jano = _waypointDistance.find(waypoint); if (jano != _waypointDistance.end()) { // waypoint already added, but set distance anyways (might be an update) (*jano).second = distance; } */ _waypointDistance[waypoint] = distance; return true; } bool PositionTracker::addWaypoint(const float from[3], const float to[3], double distance) { double fromPos[3], toPos[3]; fromPos[0] = from[0]; fromPos[1] = from[1]; fromPos[2] = from[2]; toPos[0] = to[0]; toPos[1] = to[1]; toPos[2] = to[2]; return addWaypoint(fromPos, toPos, distance); } bool PositionTracker::forget(unsigned short int token, const std::string id, std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; if ((token >= trackSet.size()) || (trackSet[token]->id != STR_ID) || (trackSet[token]->strID != id) || (trackSet[token]->forgotten)) { return false; } trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0; trackSet[token]->forgotten = true; return true; } bool PositionTracker::forget(unsigned short int token, long int id, std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; if ((token >= trackSet.size()) || (trackSet[token]->id != INT_ID) || (trackSet[token]->intID != id) || (trackSet[token]->forgotten)) { return false; } trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0; trackSet[token]->forgotten = true; return true; } double PositionTracker::distanceBetween(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const { // this indirection nastiness is needed to maintain constness std::map <std::string, TrackedItemVector>::const_iterator fromIterator = _trackedItem.find(fromGroup); std::map <std::string, TrackedItemVector>::const_iterator toIterator = _trackedItem.find(toGroup); const TrackedItemVector& fromSet = (*fromIterator).second; const TrackedItemVector& toSet = (*toIterator).second; if ((fromToken > fromSet.size()) || (toToken > toSet.size()) || (fromToken == toToken)) { return 0.0; } // basic Cartesian 3-space formula for distance between two points double distanceSquared = (((fromSet[fromToken]->position[0] - toSet[toToken]->position[0]) * (fromSet[fromToken]->position[0] - toSet[toToken]->position[0])) + ((fromSet[fromToken]->position[1] - toSet[toToken]->position[1]) * (fromSet[fromToken]->position[1] - toSet[toToken]->position[1])) + ((fromSet[fromToken]->position[2] - toSet[toToken]->position[2]) * (fromSet[fromToken]->position[2] - toSet[toToken]->position[2]))); return math_util::fastsqrt((float)distanceSquared); } double PositionTracker::waypointDistance(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const { double separationDistance = distanceBetween(fromToken, toToken, fromGroup, toGroup); double shortestDistance = separationDistance; // horrible linear search std::map<std::pair<unsigned short int, unsigned short int>, double>::const_iterator waypointIterator; for (waypointIterator = _waypointDistance.begin(); waypointIterator != _waypointDistance.end(); waypointIterator++) { double fromDist, toDist, waypointDist; fromDist = distanceBetween(fromToken, (*waypointIterator).first.first, fromGroup, std::string("__waypoint__")); toDist = distanceBetween((*waypointIterator).first.second, toToken, std::string("__waypoint__"), toGroup); waypointDist = fromDist + (*waypointIterator).second + toDist; if (waypointDist < shortestDistance) { shortestDistance = waypointDist; } } return shortestDistance; } unsigned short int PositionTracker::trackedCount(std::string group) const { std::map <std::string, TrackedItemVector>::const_iterator i = _trackedItem.find(group); const TrackedItemVector& trackSet = (*i).second; return trackSet.size(); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>warnings<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "PositionTracker.h" /* implementation system headers */ #include <iostream> #include <string> /* implementation common headers */ #include "MathUtils.h" /* private */ /* protected */ /* public: */ PositionTracker::PositionTracker() { return; } PositionTracker::PositionTracker(const PositionTracker& tracker) : _trackedItem(tracker._trackedItem), _waypointDistance(tracker._waypointDistance) { return; } PositionTracker::~PositionTracker() { // clear out all the tracked items vectors for (std::map<std::string, TrackedItemVector>::iterator jano = _trackedItem.begin(); jano != _trackedItem.end(); jano++) { TrackedItemVector& trackSet = (*jano).second; for (unsigned int i = 0; i != trackSet.size(); i++) { /* sanity clear */ trackSet[i]->id = UNSET_ID; trackSet[i]->intID = 0; trackSet[i]->strID = std::string(""); trackSet[i]->lastUpdate = TimeKeeper::getNullTime(); trackSet[i]->position[0] = trackSet[i]->position[1] = trackSet[i]->position[2] = 0.0; trackSet[i]->forgotten = true; delete trackSet[i]; } } _trackedItem.clear(); // clear out any waypoints _waypointDistance.clear(); return; } /* Linear O(n) time to track a new item since the entire vector is * searched. if the item is not found, an item is created and added. */ unsigned short PositionTracker::track(const std::string id, std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; for (unsigned int i = 0; i != trackSet.size(); i++) { switch (trackSet[i]->id) { case STR_ID: if (id == trackSet[i]->strID) { return i; } break; case INT_ID: case UNSET_ID: break; default: std::cerr << "Unknown tracker ID type (id == " << trackSet[i]->id << ")" << std::endl; break; } } // the item was not found, so create it item_t *newTracking = new item_t; newTracking->id = STR_ID; newTracking->intID = 0; newTracking->strID = id; newTracking->lastUpdate = TimeKeeper::getNullTime(); newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0; newTracking->forgotten = false; // and add it trackSet.push_back(newTracking); // nothing is deleted so should be last index return trackSet.size() - 1; } /* alternative track() passing our own id */ unsigned short PositionTracker::track(long int id, std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; for (unsigned int i = 0; i != trackSet.size(); i++) { switch (trackSet[i]->id) { case INT_ID: if (id == trackSet[i]->intID) { return i; } break; case STR_ID: case UNSET_ID: break; default: std::cerr << "Unknown tracker ID type (id == " << trackSet[i]->id << ")" << std::endl; break; } } // the item was not found, so create it item_t *newTracking = new item_t; newTracking->id = INT_ID; newTracking->intID = id; newTracking->strID = std::string(""); newTracking->lastUpdate = TimeKeeper::getNullTime(); newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0; newTracking->forgotten = false; // and add it trackSet.push_back(newTracking); // nothing is deleted so should be last index return trackSet.size() - 1; } bool PositionTracker::update(unsigned short int token, const std::string id, const double position[3], std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; if ((token >= trackSet.size()) || (trackSet[token]->id != STR_ID) || (trackSet[token]->strID != id) || (trackSet[token]->forgotten)) { return false; } trackSet[token]->position[0] = position[0]; trackSet[token]->position[1] = position[1]; trackSet[token]->position[2] = position[2]; trackSet[token]->lastUpdate = TimeKeeper::getCurrent(); return true; } bool PositionTracker::update(unsigned short int token, const std::string id, const float position[3], std::string group) { double pos[3]; pos[0] = (double)position[0]; pos[1] = (double)position[1]; pos[2] = (double)position[2]; return update(token, id, pos, group); } bool PositionTracker::update(unsigned short int token, long int id, const double position[3], std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; if ((token >= trackSet.size()) || (trackSet[token]->id != INT_ID) || (trackSet[token]->intID != id) || (trackSet[token]->forgotten)) { return false; } trackSet[token]->position[0] = position[0]; trackSet[token]->position[1] = position[1]; trackSet[token]->position[2] = position[2]; trackSet[token]->lastUpdate = TimeKeeper::getCurrent(); return true; } bool PositionTracker::update(unsigned short int token, long int id, const float position[3], std::string group) { double pos[3]; pos[0] = (double)position[0]; pos[1] = (double)position[1]; pos[2] = (double)position[2]; return update(token, id, pos, group); } bool PositionTracker::addWaypoint(const double from[3], const double to[3], double distance) { unsigned short int fromToken, toToken; bool updated; bool foundPoint; unsigned int i; TrackedItemVector& waypointSet = _trackedItem[std::string("__waypoint__")]; // see if the first point already exists foundPoint = false; for (i = 0; i != waypointSet.size(); i++) { if ((waypointSet[i]->position[0] = from[0]) && (waypointSet[i]->position[1] = from[1]) && (waypointSet[i]->position[2] = from[2])) { foundPoint = true; fromToken = (unsigned short)waypointSet[i]->intID; } } if (!foundPoint) { // add the first point unsigned short int nextID = waypointSet.size(); fromToken = track((long int)nextID, std::string("__waypoint__")); updated = update(fromToken, nextID, from, std::string("__waypoint__")); if (!updated) { std::cerr << "Unable to add waypoint?!" << std::endl; return false; } } // see if the second point already exists foundPoint = false; for (i = 0; i != waypointSet.size(); i++) { if ((waypointSet[i]->position[0] = to[0]) && (waypointSet[i]->position[1] = to[1]) && (waypointSet[i]->position[2] = to[2])) { foundPoint = true; toToken = (unsigned short)waypointSet[i]->intID; } } if (!foundPoint) { // add the second point unsigned short int nextID = waypointSet.size(); toToken = track((long int)nextID, std::string("__waypoint__")); updated = update(toToken, nextID, to, std::string("__waypoint__")); if (!updated) { std::cerr << "Unable to add waypoint?!" << std::endl; return false; } } // compute and use real distance if distance passed was negative if (distance < 0.0) { distance = distanceBetween(fromToken, toToken, std::string("__waypoint__"), std::string("__waypoint__")); } std::pair<unsigned short int, unsigned short int> waypoint = std::make_pair(fromToken, toToken); // see if the waypoint pair have already been added /* std::map<std::pair<unsigned short int, unsigned short int>, double>::iterator jano = _waypointDistance.find(waypoint); if (jano != _waypointDistance.end()) { // waypoint already added, but set distance anyways (might be an update) (*jano).second = distance; } */ _waypointDistance[waypoint] = distance; return true; } bool PositionTracker::addWaypoint(const float from[3], const float to[3], double distance) { double fromPos[3], toPos[3]; fromPos[0] = from[0]; fromPos[1] = from[1]; fromPos[2] = from[2]; toPos[0] = to[0]; toPos[1] = to[1]; toPos[2] = to[2]; return addWaypoint(fromPos, toPos, distance); } bool PositionTracker::forget(unsigned short int token, const std::string id, std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; if ((token >= trackSet.size()) || (trackSet[token]->id != STR_ID) || (trackSet[token]->strID != id) || (trackSet[token]->forgotten)) { return false; } trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0; trackSet[token]->forgotten = true; return true; } bool PositionTracker::forget(unsigned short int token, long int id, std::string group) { TrackedItemVector& trackSet = _trackedItem[group]; if ((token >= trackSet.size()) || (trackSet[token]->id != INT_ID) || (trackSet[token]->intID != id) || (trackSet[token]->forgotten)) { return false; } trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0; trackSet[token]->forgotten = true; return true; } double PositionTracker::distanceBetween(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const { // this indirection nastiness is needed to maintain constness std::map <std::string, TrackedItemVector>::const_iterator fromIterator = _trackedItem.find(fromGroup); std::map <std::string, TrackedItemVector>::const_iterator toIterator = _trackedItem.find(toGroup); const TrackedItemVector& fromSet = (*fromIterator).second; const TrackedItemVector& toSet = (*toIterator).second; if ((fromToken > fromSet.size()) || (toToken > toSet.size()) || (fromToken == toToken)) { return 0.0; } // basic Cartesian 3-space formula for distance between two points double distanceSquared = (((fromSet[fromToken]->position[0] - toSet[toToken]->position[0]) * (fromSet[fromToken]->position[0] - toSet[toToken]->position[0])) + ((fromSet[fromToken]->position[1] - toSet[toToken]->position[1]) * (fromSet[fromToken]->position[1] - toSet[toToken]->position[1])) + ((fromSet[fromToken]->position[2] - toSet[toToken]->position[2]) * (fromSet[fromToken]->position[2] - toSet[toToken]->position[2]))); return math_util::fastsqrt((float)distanceSquared); } double PositionTracker::waypointDistance(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const { double separationDistance = distanceBetween(fromToken, toToken, fromGroup, toGroup); double shortestDistance = separationDistance; // horrible linear search std::map<std::pair<unsigned short int, unsigned short int>, double>::const_iterator waypointIterator; for (waypointIterator = _waypointDistance.begin(); waypointIterator != _waypointDistance.end(); waypointIterator++) { double fromDist, toDist, waypointDist; fromDist = distanceBetween(fromToken, (*waypointIterator).first.first, fromGroup, std::string("__waypoint__")); toDist = distanceBetween((*waypointIterator).first.second, toToken, std::string("__waypoint__"), toGroup); waypointDist = fromDist + (*waypointIterator).second + toDist; if (waypointDist < shortestDistance) { shortestDistance = waypointDist; } } return shortestDistance; } unsigned short int PositionTracker::trackedCount(std::string group) const { std::map <std::string, TrackedItemVector>::const_iterator i = _trackedItem.find(group); const TrackedItemVector& trackSet = (*i).second; return trackSet.size(); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include "VGroup.h" #include "VGlobal.h" using std::vector; VBase* VGroup::Add(VBase* object) { if (object == nullptr) { VLog("Cannot add nullptr to a VGroup"); return nullptr; } if (object == this) { VLogError("Cannot add itself to it's own list"); return nullptr; } if (GetIndexOfItem(object) >= 0) return nullptr; if (MaxSize > 0 && length >= static_cast<int>(MaxSize)) { return object; } int index = FirstNULL(); if (index != -1) { members[index] = object; } else { members.push_back(object); } object->RefCount++; length++; return object; } VBase* VGroup::Remove(VBase* object, bool splice) { if (members.size() == 0) return nullptr; auto pos = GetIndexOfItem(object); if (pos < 0) return nullptr; if (splice) { members.erase(members.begin() + pos); } else { members[pos] = nullptr; } object->RefCount--; length--; return object; } VBase* VGroup::FirstAvailable() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && !base->exists) { return members[i]; } } return nullptr; } int VGroup::FirstNULL() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base == nullptr) { return i; } } return -1; } VBase* VGroup::FirstExisting() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists) { return members[i]; } } return nullptr; } VBase* VGroup::FirstAlive() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists && base->alive) { return members[i]; } } return nullptr; } VBase* VGroup::FirstDead() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && !base->alive) { return members[i]; } } return nullptr; } int VGroup::CountAlive() { int count = 0; for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists && base->alive) { count++; } } return count; } int VGroup::CountDead() { int count = 0; for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && !base->alive) { count++; } } return count; } VBase* VGroup::GetRandom(int min, int max) { min = min >= 0 ? min : 0; max = max - 1 < (int)members.size() - 1 && max > 0 ? max : (int)members.size(); return members[VGlobal::p()->Random->GetInt(max - 1, min)]; } void VGroup::ForEach(std::function<void(VBase*)> function, bool recursive) { VBase* base = nullptr; for (int i = 0; i < length; i++) { base = dynamic_cast<VBase*>(members[i]); if (base != nullptr) { function(base); if (recursive) { VGroup* group = dynamic_cast<VGroup*>(base); if (group != nullptr) { group->ForEachAlive(function, recursive); } } } } } void VGroup::ForEachAlive(std::function<void(VBase*)> function, bool recursive) { VBase* base = nullptr; for (int i = 0; i < length; i++) { base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists && base->alive) { function(base); if (recursive) { VGroup* group = dynamic_cast<VGroup*>(base); if (group != nullptr) { group->ForEachAlive(function, recursive); continue; } } } } } void VGroup::ForEachDead(std::function<void(VBase*)> function, bool recursive) { VBase* base = nullptr; for (int i = 0; i < length; i++) { base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && !base->alive) { function(base); if (recursive) { VGroup* group = dynamic_cast<VGroup*>(base); if (group != nullptr) { group->ForEachAlive(function, recursive); } } } } } void VGroup::ForEachExists(std::function<void(VBase*)> function, bool recursive) { VBase* base = nullptr; for (int i = 0; i < length; i++) { base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists) { function(base); if (recursive) { VGroup* group = dynamic_cast<VGroup*>(base); if (group != nullptr) { group->ForEachAlive(function, recursive); } } } } } VBase* VGroup::GetGroupItem(int index) { if (index >= 0 && index < length) { return members[index]; } return nullptr; } int VGroup::GetIndexOfItem(VBase* object) { auto index = std::find(members.begin(), members.end(), object); if (index == members.end()) return -1; return index - members.begin(); } void VGroup::OrganiseNULLS() { for (unsigned int i = 0; i < members.size(); i++) { int first = FirstNULL(); if (first == -1) return; if (members[i] && first < (int)i) { Swap(first, i); } } } void VGroup::Swap(int a, int b) { if (a < 0 || a >= length) return; if (b < 0 || b >= length) return; VBase* temp = members[a]; members[a] = members[b]; members[b] = temp; } void VGroup::Sort(std::function<bool(VBase*, VBase*)> func) { std::sort(members.begin(), members.end(), func); } void VGroup::Reverse() { std::reverse(members.begin(), members.end()); OrganiseNULLS(); } void VGroup::Clear() { for (int i = 0; i < length; i++) { if (members[i] != nullptr) { if (members[i]->RefCount > 1) { members[i]->RefCount--; members[i] = nullptr; } } } length = 0; members.clear(); members.shrink_to_fit(); } void VGroup::Destroy() { VSUPERCLASS::Destroy(); for (unsigned int i = 0; i < members.size(); i++) { if (members[i] != nullptr) { if (members[i]->RefCount <= 1) { members[i]->Destroy(); delete members[i]; members[i] = nullptr; } else { members[i]->RefCount--; members[i] = nullptr; } } } Clear(); } void VGroup::Kill() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists) base->Kill(); } VSUPERCLASS::Kill(); } void VGroup::Revive() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && !base->exists) base->Revive(); } VSUPERCLASS::Revive(); } void VGroup::Update(float dt) { if (!active) return; for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists && base->active) { base->Update(dt); } } } #include "VRenderGroup.h" void VGroup::Draw(sf::RenderTarget& RenderTarget) { if (!visible) return; for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists && base->visible) { base->Draw(RenderTarget); } } #if _DEBUG if (VGlobal::p()->DrawDebug) { int memberLength = members.size(); debuggingVertices.resize(memberLength * 8); for (unsigned int i = 0; i < members.size(); i++) { VObject* object = dynamic_cast<VObject*>(members[i]); if (object == nullptr && members[i]->type == RENDERGROUP) { VRenderGroup* renderGroup = dynamic_cast<VRenderGroup*>(members[i]); object = renderGroup->Sprite.get(); } if (object == nullptr) continue; if (object->alive) { debuggingVertices[0 + (i * 8)].position = object->Position; debuggingVertices[0 + (i * 8)].color = object->DebugColor; debuggingVertices[1 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, 0); debuggingVertices[1 + (i * 8)].color = object->DebugColor; debuggingVertices[2 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, 0); debuggingVertices[2 + (i * 8)].color = object->DebugColor; debuggingVertices[3 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, object->Size.y); debuggingVertices[3 + (i * 8)].color = object->DebugColor; debuggingVertices[4 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, object->Size.y); debuggingVertices[4 + (i * 8)].color = object->DebugColor; debuggingVertices[5 + (i * 8)].position = object->Position + sf::Vector2f(0, object->Size.y); debuggingVertices[5 + (i * 8)].color = object->DebugColor; debuggingVertices[6 + (i * 8)].position = object->Position + sf::Vector2f(0, object->Size.y); debuggingVertices[6 + (i * 8)].color = object->DebugColor; debuggingVertices[7 + (i * 8)].position = object->Position; debuggingVertices[7 + (i * 8)].color = object->DebugColor; } else { debuggingVertices[0 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[1 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[2 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[3 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[4 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[5 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[6 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[7 + (i * 8)].color = sf::Color::Transparent; } } RenderTarget.draw(debuggingVertices); } else { debuggingVertices.clear(); } #endif }<commit_msg>Throws error if you try to add more objects than specified in the group.<commit_after>#include "VGroup.h" #include "VGlobal.h" using std::vector; VBase* VGroup::Add(VBase* object) { if (object == nullptr) { VLog("Cannot add nullptr to a VGroup"); return nullptr; } if (object == this) { VLogError("Cannot add itself to it's own list"); return nullptr; } if (GetIndexOfItem(object) >= 0) return nullptr; if (MaxSize > 0 && length >= static_cast<int>(MaxSize)) { VLogError("Maximum amount of objects already reached."); return nullptr; } int index = FirstNULL(); if (index != -1) { members[index] = object; } else { members.push_back(object); } object->RefCount++; length++; return object; } VBase* VGroup::Remove(VBase* object, bool splice) { if (members.size() == 0) return nullptr; auto pos = GetIndexOfItem(object); if (pos < 0) return nullptr; if (splice) { members.erase(members.begin() + pos); } else { members[pos] = nullptr; } object->RefCount--; length--; return object; } VBase* VGroup::FirstAvailable() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && !base->exists) { return members[i]; } } return nullptr; } int VGroup::FirstNULL() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base == nullptr) { return i; } } return -1; } VBase* VGroup::FirstExisting() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists) { return members[i]; } } return nullptr; } VBase* VGroup::FirstAlive() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists && base->alive) { return members[i]; } } return nullptr; } VBase* VGroup::FirstDead() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && !base->alive) { return members[i]; } } return nullptr; } int VGroup::CountAlive() { int count = 0; for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists && base->alive) { count++; } } return count; } int VGroup::CountDead() { int count = 0; for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && !base->alive) { count++; } } return count; } VBase* VGroup::GetRandom(int min, int max) { min = min >= 0 ? min : 0; max = max - 1 < (int)members.size() - 1 && max > 0 ? max : (int)members.size(); return members[VGlobal::p()->Random->GetInt(max - 1, min)]; } void VGroup::ForEach(std::function<void(VBase*)> function, bool recursive) { VBase* base = nullptr; for (int i = 0; i < length; i++) { base = dynamic_cast<VBase*>(members[i]); if (base != nullptr) { function(base); if (recursive) { VGroup* group = dynamic_cast<VGroup*>(base); if (group != nullptr) { group->ForEachAlive(function, recursive); } } } } } void VGroup::ForEachAlive(std::function<void(VBase*)> function, bool recursive) { VBase* base = nullptr; for (int i = 0; i < length; i++) { base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists && base->alive) { function(base); if (recursive) { VGroup* group = dynamic_cast<VGroup*>(base); if (group != nullptr) { group->ForEachAlive(function, recursive); continue; } } } } } void VGroup::ForEachDead(std::function<void(VBase*)> function, bool recursive) { VBase* base = nullptr; for (int i = 0; i < length; i++) { base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && !base->alive) { function(base); if (recursive) { VGroup* group = dynamic_cast<VGroup*>(base); if (group != nullptr) { group->ForEachAlive(function, recursive); } } } } } void VGroup::ForEachExists(std::function<void(VBase*)> function, bool recursive) { VBase* base = nullptr; for (int i = 0; i < length; i++) { base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists) { function(base); if (recursive) { VGroup* group = dynamic_cast<VGroup*>(base); if (group != nullptr) { group->ForEachAlive(function, recursive); } } } } } VBase* VGroup::GetGroupItem(int index) { if (index >= 0 && index < length) { return members[index]; } return nullptr; } int VGroup::GetIndexOfItem(VBase* object) { auto index = std::find(members.begin(), members.end(), object); if (index == members.end()) return -1; return index - members.begin(); } void VGroup::OrganiseNULLS() { for (unsigned int i = 0; i < members.size(); i++) { int first = FirstNULL(); if (first == -1) return; if (members[i] && first < (int)i) { Swap(first, i); } } } void VGroup::Swap(int a, int b) { if (a < 0 || a >= length) return; if (b < 0 || b >= length) return; VBase* temp = members[a]; members[a] = members[b]; members[b] = temp; } void VGroup::Sort(std::function<bool(VBase*, VBase*)> func) { std::sort(members.begin(), members.end(), func); } void VGroup::Reverse() { std::reverse(members.begin(), members.end()); OrganiseNULLS(); } void VGroup::Clear() { for (int i = 0; i < length; i++) { if (members[i] != nullptr) { if (members[i]->RefCount > 1) { members[i]->RefCount--; members[i] = nullptr; } } } length = 0; members.clear(); members.shrink_to_fit(); } void VGroup::Destroy() { VSUPERCLASS::Destroy(); for (unsigned int i = 0; i < members.size(); i++) { if (members[i] != nullptr) { if (members[i]->RefCount <= 1) { members[i]->Destroy(); delete members[i]; members[i] = nullptr; } else { members[i]->RefCount--; members[i] = nullptr; } } } Clear(); } void VGroup::Kill() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists) base->Kill(); } VSUPERCLASS::Kill(); } void VGroup::Revive() { for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && !base->exists) base->Revive(); } VSUPERCLASS::Revive(); } void VGroup::Update(float dt) { if (!active) return; for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists && base->active) { base->Update(dt); } } } #include "VRenderGroup.h" void VGroup::Draw(sf::RenderTarget& RenderTarget) { if (!visible) return; for (unsigned int i = 0; i < members.size(); i++) { VBase* base = dynamic_cast<VBase*>(members[i]); if (base != nullptr && base->exists && base->visible) { base->Draw(RenderTarget); } } #if _DEBUG if (VGlobal::p()->DrawDebug) { int memberLength = members.size(); debuggingVertices.resize(memberLength * 8); for (unsigned int i = 0; i < members.size(); i++) { VObject* object = dynamic_cast<VObject*>(members[i]); if (object == nullptr && members[i]->type == RENDERGROUP) { VRenderGroup* renderGroup = dynamic_cast<VRenderGroup*>(members[i]); object = renderGroup->Sprite.get(); } if (object == nullptr) continue; if (object->alive) { debuggingVertices[0 + (i * 8)].position = object->Position; debuggingVertices[0 + (i * 8)].color = object->DebugColor; debuggingVertices[1 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, 0); debuggingVertices[1 + (i * 8)].color = object->DebugColor; debuggingVertices[2 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, 0); debuggingVertices[2 + (i * 8)].color = object->DebugColor; debuggingVertices[3 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, object->Size.y); debuggingVertices[3 + (i * 8)].color = object->DebugColor; debuggingVertices[4 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, object->Size.y); debuggingVertices[4 + (i * 8)].color = object->DebugColor; debuggingVertices[5 + (i * 8)].position = object->Position + sf::Vector2f(0, object->Size.y); debuggingVertices[5 + (i * 8)].color = object->DebugColor; debuggingVertices[6 + (i * 8)].position = object->Position + sf::Vector2f(0, object->Size.y); debuggingVertices[6 + (i * 8)].color = object->DebugColor; debuggingVertices[7 + (i * 8)].position = object->Position; debuggingVertices[7 + (i * 8)].color = object->DebugColor; } else { debuggingVertices[0 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[1 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[2 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[3 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[4 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[5 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[6 + (i * 8)].color = sf::Color::Transparent; debuggingVertices[7 + (i * 8)].color = sf::Color::Transparent; } } RenderTarget.draw(debuggingVertices); } else { debuggingVertices.clear(); } #endif }<|endoftext|>
<commit_before>/********************************************************************************* - Contact: Brigitte Cheynis b.cheynis@ipnl.in2p3.fr - Link: http - Raw data test file : /afs/cern.ch/user/c/cheynis/public/run546.dat - Reference run number : 6360 - Run Type: PHYSICS - DA Type: LDC - Number of events needed: >=100 - Input Files: argument list - Output Files: local files V00Log.txt, VZERO_Histos.root, V0_Ped_Width_Gain.dat FXS file V0_Ped_Width_Gain.dat - Trigger types used: PHYSICS_EVENT **********************************************************************************/ /********************************************************************************** * * * VZERO Detector Algorithm used for extracting calibration parameters * * * * This program reads the DDL data file passed as argument using the monitoring * * library. * * It computes calibration parameters, populates local "./V0_Ped_Width_Gain.dat" * * file and exports it to the FES. * * We have 128 channels instead of 64 as expected for V0 due to the two sets of * * charge integrators which are used by the FEE ... * * The program reports about its processing progress. * * * ***********************************************************************************/ // DATE #include "event.h" #include "monitor.h" #include "daqDA.h" //AliRoot #include <AliVZERORawStream.h> #include <AliRawReaderDate.h> #include <AliRawReader.h> #include <AliDAQ.h> // standard #include <stdio.h> #include <stdlib.h> //ROOT #include "TROOT.h" #include "TPluginManager.h" #include <TFile.h> #include <TH1F.h> #include <TMath.h> /* Main routine --- Arguments: list of DATE raw data files */ int main(int argc, char **argv) { /* magic line from Cvetan */ gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo", "*", "TStreamerInfo", "RIO", "TStreamerInfo()"); int status; // printf(" argc = %d, argv = %s \n",argc, &(**argv)); Int_t kHighCut = 50; // high cut on pedestal distribution - to be tuned Int_t kLowCut = 30; // low cut on signal distribution - to be tuned Double_t ADCmean[128]; Double_t PEDmean[128]; Double_t PEDsigma[128]; //___________________________________________________ // Book HISTOGRAMS - dynamics of p-p collisions - char ADCname[6]; char PEDname[6]; TH1F *hADCname[128]; TH1F *hPEDname[128]; char texte[12]; for (Int_t i=0; i<128; i++) { sprintf(ADCname,"hADC%d",i); sprintf(texte,"ADC cell%d",i); hADCname[i] = new TH1F(ADCname,texte,1024,0,1023); sprintf(PEDname,"hPED%d",i); sprintf(texte,"PED cell%d",i); hPEDname[i] = new TH1F(PEDname,texte,1024,0,1023);} //___________________________________________________ /* log start of process */ printf("VZERO DA program started\n"); /* check that we got some arguments = list of files */ if (argc<2) { printf("Wrong number of arguments\n"); return -1;} /* open result file to be exported to FES */ FILE *fp=NULL; fp=fopen("./V0_Ped_Width_Gain.dat","a"); if (fp==NULL) { printf("Failed to open result file\n"); return -1;} /* open log file to inform user */ FILE *flog=NULL; flog=fopen("./V00log.txt","a"); if (flog==NULL) { printf("Failed to open log file\n"); return -1; } /* report progress */ daqDA_progressReport(10); /* init counters on events */ int nevents_physics=0; int nevents_total=0; /* read the data files, considering n files */ int n; for (n=1;n<argc;n++) { status=monitorSetDataSource( argv[n] ); if (status!=0) { printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status)); return -1; } /* report progress - here indexed on the number of files */ daqDA_progressReport(10+80*n/argc); /* read the data file */ for(;;) { struct eventHeaderStruct *event; eventTypeType eventT; /* get next event */ status=monitorGetEventDynamic((void **)&event); if (status==MON_ERR_EOF) break; /* end of monitoring file has been reached */ if (status!=0) { printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status)); return -1; } /* retry if got no event */ if (event==NULL) break; /* decode event */ eventT=event->eventType; switch (event->eventType){ case START_OF_RUN: break; case END_OF_RUN: printf("End Of Run detected\n"); break; case PHYSICS_EVENT: nevents_physics++; fprintf(flog,"Run #%lu, event size: %lu, BC:%u, Orbit:%u, Period:%u\n", (unsigned long)event->eventRunNb, (unsigned long)event->eventSize, EVENT_ID_GET_BUNCH_CROSSING(event->eventId), EVENT_ID_GET_ORBIT(event->eventId), EVENT_ID_GET_PERIOD(event->eventId) ); AliRawReader *rawReader = new AliRawReaderDate((void*)event); AliVZERORawStream* rawStream = new AliVZERORawStream(rawReader); rawStream->Next(); for(Int_t i=0; i<64; i++) { if(!rawStream->GetIntegratorFlag(i,10)) hADCname[i]->Fill(float(rawStream->GetADC(i))); // even integrator - fills 0 to 63 else hADCname[i+64]->Fill(float(rawStream->GetADC(i))); // odd integrator - fills 64 to 123 for(Int_t j=0; j<21; j++) { if(j==10) continue; if(!rawStream->GetIntegratorFlag(i,j)) { hPEDname[i]->Fill(float(rawStream->GetPedestal(i,j))); } // even integrator else { hPEDname[i+64]->Fill(float(rawStream->GetPedestal(i,j))); } // odd integrator } } delete rawStream; rawStream = 0x0; delete rawReader; rawReader = 0x0; } // end of switch on event type nevents_total++; /* free resources */ free(event); } // loop over events } // loop over data files //________________________________________________________________________ // Computes mean values, dumps them into the output text file for(Int_t i=0; i<128; i++) { hPEDname[i]->GetXaxis()->SetRange(0,kHighCut); PEDmean[i] = hPEDname[i]->GetMean(); PEDsigma[i] = hPEDname[i]->GetRMS(); hADCname[i]->GetXaxis()->SetRange(kLowCut,1023); ADCmean[i] = hADCname[i]->GetMean() ; fprintf(fp," %.3f %.3f %.3f\n",PEDmean[i],PEDsigma[i],ADCmean[i]); } //________________________________________________________________________ // Write root file with histos for users further check - just in case - TFile *histoFile = new TFile("VZERO_histos.root","RECREATE"); for (Int_t i=0; i<128; i++) { hADCname[i]->GetXaxis()->SetRange(0,1023); hADCname[i]->Write(); hPEDname[i]->Write(); } histoFile->Close(); delete histoFile; //________________________________________________________________________ /* write report */ fprintf(flog,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total); printf("Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total); /* close result and log files */ fclose(fp); fclose(flog); /* report progress */ daqDA_progressReport(90); /* export result file to FES */ status=daqDA_FES_storeFile("./V0_Ped_Width_Gain.dat","V00da_results"); if (status) { printf("Failed to export file : %d\n",status); return -1; } /* report progress */ daqDA_progressReport(100); return status; } <commit_msg>Calibration DA revisited<commit_after>/********************************************************************************* - Contact: Brigitte Cheynis b.cheynis@ipnl.in2p3.fr - Link: http - Raw data test file : - Reference run number : - Run Type: PHYSICS - DA Type: MON - Number of events needed: >=500 - Input Files: argument list - Output Files: local files VZERO_Histos.root, V0_Ped_Width_Gain.dat FXS file V0_Ped_Width_Gain.dat - Trigger types used: PHYSICS_EVENT **********************************************************************************/ /********************************************************************************** * * * VZERO Detector Algorithm used for extracting calibration parameters * * * * This program connects to the DAQ data source passed as argument. * * It computes calibration parameters, populates local "./V0_Ped_Width_Gain.dat" * * file and exports it to the FES. * * The program exits when being asked to shut down (daqDA_checkshutdown) * * or End of Run event. * * We have 128 channels instead of 64 as expected for V0 due to the two sets of * * charge integrators which are used by the FEE ... * * * ***********************************************************************************/ // DATE #include "event.h" #include "monitor.h" #include "daqDA.h" //AliRoot #include <AliVZERORawStream.h> #include <AliRawReaderDate.h> #include <AliRawReader.h> #include <AliDAQ.h> // standard #include <stdio.h> #include <stdlib.h> //ROOT #include "TROOT.h" #include "TPluginManager.h" #include <TFile.h> #include <TH1F.h> #include <TMath.h> /* Main routine --- Arguments: monitoring data source */ int main(int argc, char **argv) { /* magic line from Cvetan */ gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo", "*", "TStreamerInfo", "RIO", "TStreamerInfo()"); int status; if (argc!=2) { printf("Wrong number of arguments\n"); return -1; } // printf(" argc = %d, argv = %s \n",argc, &(**argv)); Int_t kHighCut = 50; // high cut on pedestal distribution - to be tuned Int_t kLowCut = 30; // low cut on signal distribution - to be tuned Double_t ADCmean[128]; Double_t ADCsigma[128]; Double_t PEDmean[128]; Double_t PEDsigma[128]; //___________________________________________________ // Book HISTOGRAMS - dynamics of p-p collisions - char ADCname[6]; char PEDname[6]; TH1F *hADCname[128]; TH1F *hPEDname[128]; char texte[12]; for (Int_t i=0; i<128; i++) { sprintf(ADCname,"hADC%d",i); sprintf(texte,"ADC cell%d",i); hADCname[i] = new TH1F(ADCname,texte,1024,0,1023); sprintf(PEDname,"hPED%d",i); sprintf(texte,"PED cell%d",i); hPEDname[i] = new TH1F(PEDname,texte,1024,0,1023); } //___________________________________________________ /* open result file to be exported to FES */ FILE *fp=NULL; fp=fopen("./V0_Ped_Width_Gain.dat","a"); if (fp==NULL) { printf("Failed to open result file\n"); return -1;} /* define data source : this is argument 1 */ status=monitorSetDataSource( argv[1] ); if (status!=0) { printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status)); return -1; } /* declare monitoring program */ status=monitorDeclareMp( __FILE__ ); if (status!=0) { printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status)); return -1; } /* define wait event timeout - 1s max */ monitorSetNowait(); monitorSetNoWaitNetworkTimeout(1000); /* init counters on events */ int nevents_physics=0; int nevents_total=0; /* loop on events (infinite) */ for(;;) { struct eventHeaderStruct *event; eventTypeType eventT; /* check shutdown condition */ if (daqDA_checkShutdown()) {break;} /* get next event (blocking call until timeout) */ status=monitorGetEventDynamic((void **)&event); if (status==MON_ERR_EOF) { printf ("End of File detected\n"); break; /* end of monitoring file has been reached */ } if (status!=0) { printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status)); break; } /* retry if got no event */ if (event==NULL) continue; /* decode event */ eventT=event->eventType; switch (event->eventType){ case START_OF_RUN: break; case END_OF_RUN: printf("End Of Run detected\n"); break; case PHYSICS_EVENT: nevents_physics++; // fprintf(flog,"Run #%lu, event size: %lu, BC:%u, Orbit:%u, Period:%u\n", // (unsigned long)event->eventRunNb, // (unsigned long)event->eventSize, // EVENT_ID_GET_BUNCH_CROSSING(event->eventId), // EVENT_ID_GET_ORBIT(event->eventId), // EVENT_ID_GET_PERIOD(event->eventId) ); AliRawReader *rawReader = new AliRawReaderDate((void*)event); AliVZERORawStream* rawStream = new AliVZERORawStream(rawReader); rawStream->Next(); for(Int_t i=0; i<64; i++) { if(!rawStream->GetIntegratorFlag(i,10)) hADCname[i]->Fill(float(rawStream->GetADC(i))); // even integrator - fills 0 to 63 else hADCname[i+64]->Fill(float(rawStream->GetADC(i))); // odd integrator - fills 64 to 123 for(Int_t j=0; j<21; j++) { if(j==10) continue; if(!rawStream->GetIntegratorFlag(i,j)) { hPEDname[i]->Fill(float(rawStream->GetPedestal(i,j))); } // even integrator else { hPEDname[i+64]->Fill(float(rawStream->GetPedestal(i,j))); } // odd integrator } } delete rawStream; rawStream = 0x0; delete rawReader; rawReader = 0x0; } // end of switch on event type nevents_total++; /* free resources */ free(event); /* exit when last event received, no need to wait for TERM signal */ if (eventT==END_OF_RUN) { printf("End Of Run event detected\n"); break; } } // loop over events //________________________________________________________________________ // Computes mean values, dumps them into the output text file for(Int_t i=0; i<128; i++) { hPEDname[i]->GetXaxis()->SetRange(0,kHighCut); PEDmean[i] = hPEDname[i]->GetMean(); PEDsigma[i] = hPEDname[i]->GetRMS(); hADCname[i]->GetXaxis()->SetRange(kLowCut,1023); ADCmean[i] = hADCname[i]->GetMean(); ADCsigma[i] = hADCname[i]->GetRMS(); fprintf(fp," %.3f %.3f %.3f %.3f\n",PEDmean[i],PEDsigma[i],ADCmean[i],ADCsigma[i]); } //________________________________________________________________________ // Write root file with histos for users further check - just in case - TFile *histoFile = new TFile("VZERO_histos.root","RECREATE"); for (Int_t i=0; i<128; i++) { hADCname[i]->GetXaxis()->SetRange(0,1023); hADCname[i]->Write(); hPEDname[i]->Write(); } histoFile->Close(); delete histoFile; //________________________________________________________________________ /* close result file */ fclose(fp); /* export result file to FES */ status=daqDA_FES_storeFile("./V0_Ped_Width_Gain.dat","V00da_results"); if (status) { printf("Failed to export file : %d\n",status); return -1; } return status; } <|endoftext|>
<commit_before>//===- DataStructure.cpp - Analysis for data structure identification -------=// // // Implement the LLVM data structure analysis library. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/DataStructure.h" #include "llvm/Module.h" #include "llvm/Function.h" #include <fstream> #include <algorithm> //===----------------------------------------------------------------------===// // DataStructure Class Implementation // AnalysisID DataStructure::ID(AnalysisID::create<DataStructure>()); // releaseMemory - If the pass pipeline is done with this pass, we can release // our memory... here... void DataStructure::releaseMemory() { for (InfoMap::iterator I = DSInfo.begin(), E = DSInfo.end(); I != E; ++I) { delete I->second.first; delete I->second.second; } // Empty map so next time memory is released, data structures are not // re-deleted. DSInfo.clear(); } // print - Print out the analysis results... void DataStructure::print(std::ostream &O, Module *M) const { for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) if (!(*I)->isExternal()) { string Filename = "ds." + (*I)->getName() + ".dot"; O << "Writing '" << Filename << "'...\n"; ofstream F(Filename.c_str()); if (F.good()) { F << "digraph DataStructures {\n" << "\tnode [shape=Mrecord];\n" << "\tedge [arrowtail=\"dot\"];\n" << "\tsize=\"10,7.5\";\n" << "\trotate=\"90\";\n"; getDSGraph(*I).printFunction(F, "Local"); getClosedDSGraph(*I).printFunction(F, "Closed"); F << "}\n"; } else { O << " error opening file for writing!\n"; } } } //===----------------------------------------------------------------------===// // PointerVal Class Implementation // void PointerVal::print(std::ostream &O) const { if (Node) { O << " Node: " << Node->getCaption() << "[" << Index << "]\n"; } else { O << " NULL NODE\n"; } } //===----------------------------------------------------------------------===// // PointerValSet Class Implementation // void PointerValSet::addRefs() { for (unsigned i = 0, e = Vals.size(); i != e; ++i) Vals[i].Node->addReferrer(this); } void PointerValSet::dropRefs() { for (unsigned i = 0, e = Vals.size(); i != e; ++i) Vals[i].Node->removeReferrer(this); } const PointerValSet &PointerValSet::operator=(const PointerValSet &PVS) { dropRefs(); Vals.clear(); Vals = PVS.Vals; addRefs(); return *this; } // operator< - Allow insertion into a map... bool PointerValSet::operator<(const PointerValSet &PVS) const { if (Vals.size() < PVS.Vals.size()) return true; if (Vals.size() > PVS.Vals.size()) return false; if (Vals.size() == 1) return Vals[0] < PVS.Vals[0]; // Most common case vector<PointerVal> S1(Vals), S2(PVS.Vals); sort(S1.begin(), S1.end()); sort(S2.begin(), S2.end()); return S1 < S2; } bool PointerValSet::operator==(const PointerValSet &PVS) const { if (Vals.size() != PVS.Vals.size()) return false; if (Vals.size() == 1) return Vals[0] == PVS.Vals[0]; // Most common case... vector<PointerVal> S1(Vals), S2(PVS.Vals); sort(S1.begin(), S1.end()); sort(S2.begin(), S2.end()); return S1 == S2; } bool PointerValSet::add(const PointerVal &PV, Value *Pointer) { if (std::find(Vals.begin(), Vals.end(), PV) != Vals.end()) return false; Vals.push_back(PV); if (Pointer) PV.Node->addPointer(Pointer); PV.Node->addReferrer(this); return true; } // removePointerTo - Remove a single pointer val that points to the specified // node... void PointerValSet::removePointerTo(DSNode *Node) { vector<PointerVal>::iterator I = std::find(Vals.begin(), Vals.end(), Node); assert(I != Vals.end() && "Couldn't remove nonexistent edge!"); Vals.erase(I); Node->removeReferrer(this); } void PointerValSet::print(std::ostream &O) const { for (unsigned i = 0, e = Vals.size(); i != e; ++i) Vals[i].print(O); } <commit_msg>Add hack to get timing of analysis<commit_after>//===- DataStructure.cpp - Analysis for data structure identification -------=// // // Implement the LLVM data structure analysis library. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/DataStructure.h" #include "llvm/Module.h" #include "llvm/Function.h" #include <fstream> #include <algorithm> //===----------------------------------------------------------------------===// // DataStructure Class Implementation // AnalysisID DataStructure::ID(AnalysisID::create<DataStructure>()); // releaseMemory - If the pass pipeline is done with this pass, we can release // our memory... here... void DataStructure::releaseMemory() { for (InfoMap::iterator I = DSInfo.begin(), E = DSInfo.end(); I != E; ++I) { delete I->second.first; delete I->second.second; } // Empty map so next time memory is released, data structures are not // re-deleted. DSInfo.clear(); } // FIXME REMOVE #include <sys/time.h> #include "Support/CommandLine.h" cl::Flag Time("t", "Print analysis time..."); // print - Print out the analysis results... void DataStructure::print(std::ostream &O, Module *M) const { if (Time) { timeval TV1, TV2; gettimeofday(&TV1, 0); for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) if (!(*I)->isExternal()) { getDSGraph(*I); getClosedDSGraph(*I); } gettimeofday(&TV2, 0); cerr << "Analysis took " << (TV2.tv_sec-TV1.tv_sec)*1000000+(TV2.tv_usec-TV1.tv_usec) << " microseconds.\n"; } for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) if (!(*I)->isExternal()) { string Filename = "ds." + (*I)->getName() + ".dot"; O << "Writing '" << Filename << "'...\n"; ofstream F(Filename.c_str()); if (F.good()) { F << "digraph DataStructures {\n" << "\tnode [shape=Mrecord];\n" << "\tedge [arrowtail=\"dot\"];\n" << "\tsize=\"10,7.5\";\n" << "\trotate=\"90\";\n"; getDSGraph(*I).printFunction(F, "Local"); getClosedDSGraph(*I).printFunction(F, "Closed"); F << "}\n"; } else { O << " error opening file for writing!\n"; } O << (*I)->getName() << " " << getDSGraph(*I).getGraphSize() << " " << getClosedDSGraph(*I).getGraphSize() << "\n"; } } //===----------------------------------------------------------------------===// // PointerVal Class Implementation // void PointerVal::print(std::ostream &O) const { if (Node) { O << " Node: " << Node->getCaption() << "[" << Index << "]\n"; } else { O << " NULL NODE\n"; } } //===----------------------------------------------------------------------===// // PointerValSet Class Implementation // void PointerValSet::addRefs() { for (unsigned i = 0, e = Vals.size(); i != e; ++i) Vals[i].Node->addReferrer(this); } void PointerValSet::dropRefs() { for (unsigned i = 0, e = Vals.size(); i != e; ++i) Vals[i].Node->removeReferrer(this); } const PointerValSet &PointerValSet::operator=(const PointerValSet &PVS) { dropRefs(); Vals.clear(); Vals = PVS.Vals; addRefs(); return *this; } // operator< - Allow insertion into a map... bool PointerValSet::operator<(const PointerValSet &PVS) const { if (Vals.size() < PVS.Vals.size()) return true; if (Vals.size() > PVS.Vals.size()) return false; if (Vals.size() == 1) return Vals[0] < PVS.Vals[0]; // Most common case vector<PointerVal> S1(Vals), S2(PVS.Vals); sort(S1.begin(), S1.end()); sort(S2.begin(), S2.end()); return S1 < S2; } bool PointerValSet::operator==(const PointerValSet &PVS) const { if (Vals.size() != PVS.Vals.size()) return false; if (Vals.size() == 1) return Vals[0] == PVS.Vals[0]; // Most common case... vector<PointerVal> S1(Vals), S2(PVS.Vals); sort(S1.begin(), S1.end()); sort(S2.begin(), S2.end()); return S1 == S2; } bool PointerValSet::add(const PointerVal &PV, Value *Pointer) { if (std::find(Vals.begin(), Vals.end(), PV) != Vals.end()) return false; Vals.push_back(PV); if (Pointer) PV.Node->addPointer(Pointer); PV.Node->addReferrer(this); return true; } // removePointerTo - Remove a single pointer val that points to the specified // node... void PointerValSet::removePointerTo(DSNode *Node) { vector<PointerVal>::iterator I = std::find(Vals.begin(), Vals.end(), Node); assert(I != Vals.end() && "Couldn't remove nonexistent edge!"); Vals.erase(I); Node->removeReferrer(this); } void PointerValSet::print(std::ostream &O) const { for (unsigned i = 0, e = Vals.size(); i != e; ++i) Vals[i].print(O); } <|endoftext|>
<commit_before>//===-- R600ControlFlowFinalizer.cpp - Finalize Control Flow Inst----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file /// This pass compute turns all control flow pseudo instructions into native one /// computing their address on the fly ; it also sets STACK_SIZE info. //===----------------------------------------------------------------------===// #define DEBUG_TYPE "r600cf" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "AMDGPU.h" #include "R600Defines.h" #include "R600InstrInfo.h" #include "R600MachineFunctionInfo.h" #include "R600RegisterInfo.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" namespace llvm { class R600ControlFlowFinalizer : public MachineFunctionPass { private: enum ControlFlowInstruction { CF_TC, CF_CALL_FS, CF_WHILE_LOOP, CF_END_LOOP, CF_LOOP_BREAK, CF_LOOP_CONTINUE, CF_JUMP, CF_ELSE, CF_POP }; static char ID; const R600InstrInfo *TII; unsigned MaxFetchInst; const AMDGPUSubtarget &ST; bool isFetch(const MachineInstr *MI) const { switch (MI->getOpcode()) { case AMDGPU::TEX_VTX_CONSTBUF: case AMDGPU::TEX_VTX_TEXBUF: case AMDGPU::TEX_LD: case AMDGPU::TEX_GET_TEXTURE_RESINFO: case AMDGPU::TEX_GET_GRADIENTS_H: case AMDGPU::TEX_GET_GRADIENTS_V: case AMDGPU::TEX_SET_GRADIENTS_H: case AMDGPU::TEX_SET_GRADIENTS_V: case AMDGPU::TEX_SAMPLE: case AMDGPU::TEX_SAMPLE_C: case AMDGPU::TEX_SAMPLE_L: case AMDGPU::TEX_SAMPLE_C_L: case AMDGPU::TEX_SAMPLE_LB: case AMDGPU::TEX_SAMPLE_C_LB: case AMDGPU::TEX_SAMPLE_G: case AMDGPU::TEX_SAMPLE_C_G: case AMDGPU::TXD: case AMDGPU::TXD_SHADOW: case AMDGPU::VTX_READ_GLOBAL_8_eg: case AMDGPU::VTX_READ_GLOBAL_32_eg: case AMDGPU::VTX_READ_GLOBAL_128_eg: case AMDGPU::VTX_READ_PARAM_8_eg: case AMDGPU::VTX_READ_PARAM_16_eg: case AMDGPU::VTX_READ_PARAM_32_eg: case AMDGPU::VTX_READ_PARAM_128_eg: return true; default: return false; } } bool IsTrivialInst(MachineInstr *MI) const { switch (MI->getOpcode()) { case AMDGPU::KILL: case AMDGPU::RETURN: return true; default: return false; } } const MCInstrDesc &getHWInstrDesc(ControlFlowInstruction CFI) const { if (ST.device()->getGeneration() <= AMDGPUDeviceInfo::HD4XXX) { switch (CFI) { case CF_TC: return TII->get(AMDGPU::CF_TC_R600); case CF_CALL_FS: return TII->get(AMDGPU::CF_CALL_FS_R600); case CF_WHILE_LOOP: return TII->get(AMDGPU::WHILE_LOOP_R600); case CF_END_LOOP: return TII->get(AMDGPU::END_LOOP_R600); case CF_LOOP_BREAK: return TII->get(AMDGPU::LOOP_BREAK_R600); case CF_LOOP_CONTINUE: return TII->get(AMDGPU::CF_CONTINUE_R600); case CF_JUMP: return TII->get(AMDGPU::CF_JUMP_R600); case CF_ELSE: return TII->get(AMDGPU::CF_ELSE_R600); case CF_POP: return TII->get(AMDGPU::POP_R600); } } else { switch (CFI) { case CF_TC: return TII->get(AMDGPU::CF_TC_EG); case CF_CALL_FS: return TII->get(AMDGPU::CF_CALL_FS_EG); case CF_WHILE_LOOP: return TII->get(AMDGPU::WHILE_LOOP_EG); case CF_END_LOOP: return TII->get(AMDGPU::END_LOOP_EG); case CF_LOOP_BREAK: return TII->get(AMDGPU::LOOP_BREAK_EG); case CF_LOOP_CONTINUE: return TII->get(AMDGPU::CF_CONTINUE_EG); case CF_JUMP: return TII->get(AMDGPU::CF_JUMP_EG); case CF_ELSE: return TII->get(AMDGPU::CF_ELSE_EG); case CF_POP: return TII->get(AMDGPU::POP_EG); } } } MachineBasicBlock::iterator MakeFetchClause(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned CfAddress) const { MachineBasicBlock::iterator ClauseHead = I; unsigned AluInstCount = 0; for (MachineBasicBlock::iterator E = MBB.end(); I != E; ++I) { if (IsTrivialInst(I)) continue; if (!isFetch(I)) break; AluInstCount ++; if (AluInstCount > MaxFetchInst) break; } BuildMI(MBB, ClauseHead, MBB.findDebugLoc(ClauseHead), getHWInstrDesc(CF_TC)) .addImm(CfAddress) // ADDR .addImm(AluInstCount); // COUNT return I; } void CounterPropagateAddr(MachineInstr *MI, unsigned Addr) const { MI->getOperand(0).setImm(Addr + MI->getOperand(0).getImm()); } void CounterPropagateAddr(std::set<MachineInstr *> MIs, unsigned Addr) const { for (std::set<MachineInstr *>::iterator It = MIs.begin(), E = MIs.end(); It != E; ++It) { MachineInstr *MI = *It; CounterPropagateAddr(MI, Addr); } } public: R600ControlFlowFinalizer(TargetMachine &tm) : MachineFunctionPass(ID), TII (static_cast<const R600InstrInfo *>(tm.getInstrInfo())), ST(tm.getSubtarget<AMDGPUSubtarget>()) { const AMDGPUSubtarget &ST = tm.getSubtarget<AMDGPUSubtarget>(); if (ST.device()->getGeneration() <= AMDGPUDeviceInfo::HD4XXX) MaxFetchInst = 8; else MaxFetchInst = 16; } virtual bool runOnMachineFunction(MachineFunction &MF) { unsigned MaxStack = 0; unsigned CurrentStack = 0; for (MachineFunction::iterator MB = MF.begin(), ME = MF.end(); MB != ME; ++MB) { MachineBasicBlock &MBB = *MB; unsigned CfCount = 0; std::vector<std::pair<unsigned, std::set<MachineInstr *> > > LoopStack; std::vector<MachineInstr * > IfThenElseStack; R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>(); if (MFI->ShaderType == 1) { BuildMI(MBB, MBB.begin(), MBB.findDebugLoc(MBB.begin()), getHWInstrDesc(CF_CALL_FS)); CfCount++; } for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) { if (isFetch(I)) { DEBUG(dbgs() << CfCount << ":"; I->dump();); I = MakeFetchClause(MBB, I, 0); CfCount++; continue; } MachineBasicBlock::iterator MI = I; I++; switch (MI->getOpcode()) { case AMDGPU::CF_ALU_PUSH_BEFORE: CurrentStack++; MaxStack = std::max(MaxStack, CurrentStack); case AMDGPU::CF_ALU: case AMDGPU::EG_ExportBuf: case AMDGPU::EG_ExportSwz: case AMDGPU::R600_ExportBuf: case AMDGPU::R600_ExportSwz: case AMDGPU::RAT_WRITE_CACHELESS_32_eg: case AMDGPU::RAT_WRITE_CACHELESS_128_eg: DEBUG(dbgs() << CfCount << ":"; MI->dump();); CfCount++; break; case AMDGPU::WHILELOOP: { CurrentStack++; MaxStack = std::max(MaxStack, CurrentStack); MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_WHILE_LOOP)) .addImm(1); std::pair<unsigned, std::set<MachineInstr *> > Pair(CfCount, std::set<MachineInstr *>()); Pair.second.insert(MIb); LoopStack.push_back(Pair); MI->eraseFromParent(); CfCount++; break; } case AMDGPU::ENDLOOP: { CurrentStack--; std::pair<unsigned, std::set<MachineInstr *> > Pair = LoopStack.back(); LoopStack.pop_back(); CounterPropagateAddr(Pair.second, CfCount); BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_END_LOOP)) .addImm(Pair.first + 1); MI->eraseFromParent(); CfCount++; break; } case AMDGPU::IF_PREDICATE_SET: { MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_JUMP)) .addImm(0) .addImm(0); IfThenElseStack.push_back(MIb); DEBUG(dbgs() << CfCount << ":"; MIb->dump();); MI->eraseFromParent(); CfCount++; break; } case AMDGPU::ELSE: { MachineInstr * JumpInst = IfThenElseStack.back(); IfThenElseStack.pop_back(); CounterPropagateAddr(JumpInst, CfCount); MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_ELSE)) .addImm(0) .addImm(1); DEBUG(dbgs() << CfCount << ":"; MIb->dump();); IfThenElseStack.push_back(MIb); MI->eraseFromParent(); CfCount++; break; } case AMDGPU::ENDIF: { CurrentStack--; MachineInstr *IfOrElseInst = IfThenElseStack.back(); IfThenElseStack.pop_back(); CounterPropagateAddr(IfOrElseInst, CfCount + 1); MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_POP)) .addImm(CfCount + 1) .addImm(1); DEBUG(dbgs() << CfCount << ":"; MIb->dump();); MI->eraseFromParent(); CfCount++; break; } case AMDGPU::PREDICATED_BREAK: { CurrentStack--; CfCount += 3; BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_JUMP)) .addImm(CfCount) .addImm(1); MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_LOOP_BREAK)) .addImm(0); BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_POP)) .addImm(CfCount) .addImm(1); LoopStack.back().second.insert(MIb); MI->eraseFromParent(); break; } case AMDGPU::CONTINUE: { MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_LOOP_CONTINUE)) .addImm(0); LoopStack.back().second.insert(MIb); MI->eraseFromParent(); CfCount++; break; } default: break; } } BuildMI(MBB, MBB.begin(), MBB.findDebugLoc(MBB.begin()), TII->get(AMDGPU::STACK_SIZE)) .addImm(MaxStack); } return false; } const char *getPassName() const { return "R600 Control Flow Finalizer Pass"; } }; char R600ControlFlowFinalizer::ID = 0; } llvm::FunctionPass *llvm::createR600ControlFlowFinalizer(TargetMachine &TM) { return new R600ControlFlowFinalizer(TM); } <commit_msg>Whitespace.<commit_after>//===-- R600ControlFlowFinalizer.cpp - Finalize Control Flow Inst----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file /// This pass compute turns all control flow pseudo instructions into native one /// computing their address on the fly ; it also sets STACK_SIZE info. //===----------------------------------------------------------------------===// #define DEBUG_TYPE "r600cf" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "AMDGPU.h" #include "R600Defines.h" #include "R600InstrInfo.h" #include "R600MachineFunctionInfo.h" #include "R600RegisterInfo.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" namespace llvm { class R600ControlFlowFinalizer : public MachineFunctionPass { private: enum ControlFlowInstruction { CF_TC, CF_CALL_FS, CF_WHILE_LOOP, CF_END_LOOP, CF_LOOP_BREAK, CF_LOOP_CONTINUE, CF_JUMP, CF_ELSE, CF_POP }; static char ID; const R600InstrInfo *TII; unsigned MaxFetchInst; const AMDGPUSubtarget &ST; bool isFetch(const MachineInstr *MI) const { switch (MI->getOpcode()) { case AMDGPU::TEX_VTX_CONSTBUF: case AMDGPU::TEX_VTX_TEXBUF: case AMDGPU::TEX_LD: case AMDGPU::TEX_GET_TEXTURE_RESINFO: case AMDGPU::TEX_GET_GRADIENTS_H: case AMDGPU::TEX_GET_GRADIENTS_V: case AMDGPU::TEX_SET_GRADIENTS_H: case AMDGPU::TEX_SET_GRADIENTS_V: case AMDGPU::TEX_SAMPLE: case AMDGPU::TEX_SAMPLE_C: case AMDGPU::TEX_SAMPLE_L: case AMDGPU::TEX_SAMPLE_C_L: case AMDGPU::TEX_SAMPLE_LB: case AMDGPU::TEX_SAMPLE_C_LB: case AMDGPU::TEX_SAMPLE_G: case AMDGPU::TEX_SAMPLE_C_G: case AMDGPU::TXD: case AMDGPU::TXD_SHADOW: case AMDGPU::VTX_READ_GLOBAL_8_eg: case AMDGPU::VTX_READ_GLOBAL_32_eg: case AMDGPU::VTX_READ_GLOBAL_128_eg: case AMDGPU::VTX_READ_PARAM_8_eg: case AMDGPU::VTX_READ_PARAM_16_eg: case AMDGPU::VTX_READ_PARAM_32_eg: case AMDGPU::VTX_READ_PARAM_128_eg: return true; default: return false; } } bool IsTrivialInst(MachineInstr *MI) const { switch (MI->getOpcode()) { case AMDGPU::KILL: case AMDGPU::RETURN: return true; default: return false; } } const MCInstrDesc &getHWInstrDesc(ControlFlowInstruction CFI) const { if (ST.device()->getGeneration() <= AMDGPUDeviceInfo::HD4XXX) { switch (CFI) { case CF_TC: return TII->get(AMDGPU::CF_TC_R600); case CF_CALL_FS: return TII->get(AMDGPU::CF_CALL_FS_R600); case CF_WHILE_LOOP: return TII->get(AMDGPU::WHILE_LOOP_R600); case CF_END_LOOP: return TII->get(AMDGPU::END_LOOP_R600); case CF_LOOP_BREAK: return TII->get(AMDGPU::LOOP_BREAK_R600); case CF_LOOP_CONTINUE: return TII->get(AMDGPU::CF_CONTINUE_R600); case CF_JUMP: return TII->get(AMDGPU::CF_JUMP_R600); case CF_ELSE: return TII->get(AMDGPU::CF_ELSE_R600); case CF_POP: return TII->get(AMDGPU::POP_R600); } } else { switch (CFI) { case CF_TC: return TII->get(AMDGPU::CF_TC_EG); case CF_CALL_FS: return TII->get(AMDGPU::CF_CALL_FS_EG); case CF_WHILE_LOOP: return TII->get(AMDGPU::WHILE_LOOP_EG); case CF_END_LOOP: return TII->get(AMDGPU::END_LOOP_EG); case CF_LOOP_BREAK: return TII->get(AMDGPU::LOOP_BREAK_EG); case CF_LOOP_CONTINUE: return TII->get(AMDGPU::CF_CONTINUE_EG); case CF_JUMP: return TII->get(AMDGPU::CF_JUMP_EG); case CF_ELSE: return TII->get(AMDGPU::CF_ELSE_EG); case CF_POP: return TII->get(AMDGPU::POP_EG); } } } MachineBasicBlock::iterator MakeFetchClause(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned CfAddress) const { MachineBasicBlock::iterator ClauseHead = I; unsigned AluInstCount = 0; for (MachineBasicBlock::iterator E = MBB.end(); I != E; ++I) { if (IsTrivialInst(I)) continue; if (!isFetch(I)) break; AluInstCount ++; if (AluInstCount > MaxFetchInst) break; } BuildMI(MBB, ClauseHead, MBB.findDebugLoc(ClauseHead), getHWInstrDesc(CF_TC)) .addImm(CfAddress) // ADDR .addImm(AluInstCount); // COUNT return I; } void CounterPropagateAddr(MachineInstr *MI, unsigned Addr) const { MI->getOperand(0).setImm(Addr + MI->getOperand(0).getImm()); } void CounterPropagateAddr(std::set<MachineInstr *> MIs, unsigned Addr) const { for (std::set<MachineInstr *>::iterator It = MIs.begin(), E = MIs.end(); It != E; ++It) { MachineInstr *MI = *It; CounterPropagateAddr(MI, Addr); } } public: R600ControlFlowFinalizer(TargetMachine &tm) : MachineFunctionPass(ID), TII (static_cast<const R600InstrInfo *>(tm.getInstrInfo())), ST(tm.getSubtarget<AMDGPUSubtarget>()) { const AMDGPUSubtarget &ST = tm.getSubtarget<AMDGPUSubtarget>(); if (ST.device()->getGeneration() <= AMDGPUDeviceInfo::HD4XXX) MaxFetchInst = 8; else MaxFetchInst = 16; } virtual bool runOnMachineFunction(MachineFunction &MF) { unsigned MaxStack = 0; unsigned CurrentStack = 0; for (MachineFunction::iterator MB = MF.begin(), ME = MF.end(); MB != ME; ++MB) { MachineBasicBlock &MBB = *MB; unsigned CfCount = 0; std::vector<std::pair<unsigned, std::set<MachineInstr *> > > LoopStack; std::vector<MachineInstr * > IfThenElseStack; R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>(); if (MFI->ShaderType == 1) { BuildMI(MBB, MBB.begin(), MBB.findDebugLoc(MBB.begin()), getHWInstrDesc(CF_CALL_FS)); CfCount++; } for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) { if (isFetch(I)) { DEBUG(dbgs() << CfCount << ":"; I->dump();); I = MakeFetchClause(MBB, I, 0); CfCount++; continue; } MachineBasicBlock::iterator MI = I; I++; switch (MI->getOpcode()) { case AMDGPU::CF_ALU_PUSH_BEFORE: CurrentStack++; MaxStack = std::max(MaxStack, CurrentStack); case AMDGPU::CF_ALU: case AMDGPU::EG_ExportBuf: case AMDGPU::EG_ExportSwz: case AMDGPU::R600_ExportBuf: case AMDGPU::R600_ExportSwz: case AMDGPU::RAT_WRITE_CACHELESS_32_eg: case AMDGPU::RAT_WRITE_CACHELESS_128_eg: DEBUG(dbgs() << CfCount << ":"; MI->dump();); CfCount++; break; case AMDGPU::WHILELOOP: { CurrentStack++; MaxStack = std::max(MaxStack, CurrentStack); MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_WHILE_LOOP)) .addImm(1); std::pair<unsigned, std::set<MachineInstr *> > Pair(CfCount, std::set<MachineInstr *>()); Pair.second.insert(MIb); LoopStack.push_back(Pair); MI->eraseFromParent(); CfCount++; break; } case AMDGPU::ENDLOOP: { CurrentStack--; std::pair<unsigned, std::set<MachineInstr *> > Pair = LoopStack.back(); LoopStack.pop_back(); CounterPropagateAddr(Pair.second, CfCount); BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_END_LOOP)) .addImm(Pair.first + 1); MI->eraseFromParent(); CfCount++; break; } case AMDGPU::IF_PREDICATE_SET: { MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_JUMP)) .addImm(0) .addImm(0); IfThenElseStack.push_back(MIb); DEBUG(dbgs() << CfCount << ":"; MIb->dump();); MI->eraseFromParent(); CfCount++; break; } case AMDGPU::ELSE: { MachineInstr * JumpInst = IfThenElseStack.back(); IfThenElseStack.pop_back(); CounterPropagateAddr(JumpInst, CfCount); MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_ELSE)) .addImm(0) .addImm(1); DEBUG(dbgs() << CfCount << ":"; MIb->dump();); IfThenElseStack.push_back(MIb); MI->eraseFromParent(); CfCount++; break; } case AMDGPU::ENDIF: { CurrentStack--; MachineInstr *IfOrElseInst = IfThenElseStack.back(); IfThenElseStack.pop_back(); CounterPropagateAddr(IfOrElseInst, CfCount + 1); MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_POP)) .addImm(CfCount + 1) .addImm(1); DEBUG(dbgs() << CfCount << ":"; MIb->dump();); MI->eraseFromParent(); CfCount++; break; } case AMDGPU::PREDICATED_BREAK: { CurrentStack--; CfCount += 3; BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_JUMP)) .addImm(CfCount) .addImm(1); MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_LOOP_BREAK)) .addImm(0); BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_POP)) .addImm(CfCount) .addImm(1); LoopStack.back().second.insert(MIb); MI->eraseFromParent(); break; } case AMDGPU::CONTINUE: { MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_LOOP_CONTINUE)) .addImm(0); LoopStack.back().second.insert(MIb); MI->eraseFromParent(); CfCount++; break; } default: break; } } BuildMI(MBB, MBB.begin(), MBB.findDebugLoc(MBB.begin()), TII->get(AMDGPU::STACK_SIZE)) .addImm(MaxStack); } return false; } const char *getPassName() const { return "R600 Control Flow Finalizer Pass"; } }; char R600ControlFlowFinalizer::ID = 0; } llvm::FunctionPass *llvm::createR600ControlFlowFinalizer(TargetMachine &TM) { return new R600ControlFlowFinalizer(TM); } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) */ /* */ /* 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. */ /* -------------------------------------------------------------------------- */ /* ************************************************************************** */ /* User Pool */ /* ************************************************************************** */ #include "UserPool.h" #include "NebulaLog.h" #include "Nebula.h" #include "AuthManager.h" #include "SSLTools.h" #include <fstream> #include <sys/types.h> #include <pwd.h> #include <stdlib.h> const char * UserPool::CORE_AUTH = "core"; const char * UserPool::SERVER_AUTH = "server"; const char * UserPool::PUBLIC_AUTH = "public"; const char * UserPool::DEFAULT_AUTH = "default"; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ time_t UserPool::_session_expiration_time; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ UserPool::UserPool(SqlDB * db, time_t __session_expiration_time): PoolSQL(db,User::table) { int one_uid = -1; ostringstream oss; string one_token; string one_name; string one_pass; string one_auth_file; const char * one_auth; ifstream file; _session_expiration_time = __session_expiration_time; if (get(0,false) != 0) { return; } // User oneadmin needs to be added in the bootstrap one_auth = getenv("ONE_AUTH"); if (!one_auth) { struct passwd * pw_ent; pw_ent = getpwuid(getuid()); if ((pw_ent != NULL) && (pw_ent->pw_dir != NULL)) { one_auth_file = pw_ent->pw_dir; one_auth_file += "/.one/one_auth"; one_auth = one_auth_file.c_str(); } else { oss << "Could not get one_auth file location"; } } file.open(one_auth); if (file.good()) { getline(file,one_token); if (file.fail()) { oss << "Error reading file: " << one_auth; } else { if (User::split_secret(one_token,one_name,one_pass) == 0) { string error_str; allocate(&one_uid, GroupPool::ONEADMIN_ID, one_name, GroupPool::ONEADMIN_NAME, one_pass, UserPool::CORE_AUTH, true, error_str); } else { oss << "Wrong format must be <username>:<password>"; } } } else { oss << "Cloud not open file: " << one_auth; } file.close(); if (one_uid != 0) { NebulaLog::log("ONE",Log::ERROR,oss); throw; } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::allocate ( int * oid, int gid, const string& uname, const string& gname, const string& password, const string& auth, bool enabled, string& error_str) { Nebula& nd = Nebula::instance(); User * user; GroupPool * gpool; Group * group; string auth_driver = auth; string upass = password; ostringstream oss; // Check username and password if ( !User::pass_is_valid(password, error_str) ) { goto error_pass; } if ( !User::name_is_valid(uname, error_str) ) { goto error_name; } // Check for duplicates user = get(uname,false); if ( user !=0 ) { goto error_duplicated; } // Set auth driver and hash password for CORE_AUTH if (auth_driver.empty()) { auth_driver = UserPool::CORE_AUTH; } if (auth_driver == UserPool::CORE_AUTH) { upass = SSLTools::sha1_digest(password); } // Build a new User object user = new User(-1, gid, uname, gname, upass, auth_driver, enabled); // Insert the Object in the pool *oid = PoolSQL::allocate(user, error_str); if ( *oid < 0 ) { return *oid; } // Adds User to group gpool = nd.get_gpool(); group = gpool->get(gid, true); if( group == 0 ) { return -1; } group->add_user(*oid); gpool->update(group); group->unlock(); return *oid; error_pass: oss << error_str << "."; goto error_common; error_name: oss << error_str << "."; goto error_common; error_duplicated: oss << "NAME is already taken by USER " << user->get_oid() << "."; goto error_common; error_common: *oid = -1; error_str = oss.str(); return *oid; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ bool UserPool::authenticate_internal(User * user, const string& token, int& user_id, int& group_id, string& uname, string& gname) { bool result = false; ostringstream oss; string password; string auth_driver; string username; Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); username = user->name; password = user->password; user_id = user->oid; group_id = user->gid; uname = user->name; gname = user->gname; auth_driver = user->auth_driver; result = user->valid_session(token); user->unlock(); if (result) { return true; } AuthRequest ar(user_id, group_id); if ( auth_driver == UserPool::CORE_AUTH ) { ar.add_authenticate("",username,password,token); if (!ar.core_authenticate()) { goto auth_failure; } } else if (auth_driver == UserPool::PUBLIC_AUTH ) { goto auth_failure_public; } else if ( authm != 0 ) //use auth driver if it was loaded { //Initialize authentication request and call the driver ar.add_authenticate(auth_driver,username,password,token); authm->trigger(AuthManager::AUTHENTICATE,&ar); ar.wait(); if (ar.result!=true) //User was not authenticated { goto auth_failure_driver; } } else { goto auth_failure_nodriver; } user = get(user_id, true); if (user != 0) { user->set_session(token, _session_expiration_time); user->unlock(); } return true; auth_failure_public: oss << "User: " << username << " attempted a direct authentication."; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_driver: oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_nodriver: NebulaLog::log("AuM",Log::ERROR, "Auth Error: Authentication driver not enabled. " "Check AUTH_MAD in oned.conf"); auth_failure: user_id = -1; group_id = -1; uname = ""; gname = ""; return false; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ bool UserPool::authenticate_server(User * user, const string& token, int& user_id, int& group_id, string& uname, string& gname) { bool result = false; ostringstream oss; string server_password; string auth_driver; string server_username; string target_username; string second_token; Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); server_username = user->name; server_password = user->password; auth_driver = user->auth_driver; AuthRequest ar(user->oid, user->gid); user->unlock(); // token = target_username:second_token int rc = User::split_secret(token,target_username,second_token); if ( rc != 0 ) { goto wrong_server_token; } user = get(target_username,true); if ( user == 0 ) { goto auth_failure_user; } user_id = user->oid; group_id = user->gid; uname = user->name; gname = user->gname; result = user->valid_session(second_token); user->unlock(); if (result) { return true; } if ( authm == 0 ) { goto auth_failure_nodriver; } //Initialize authentication request and call the driver ar.add_authenticate(auth_driver,server_username,server_password,token); authm->trigger(AuthManager::AUTHENTICATE,&ar); ar.wait(); if (ar.result!=true) //User was not authenticated { goto auth_failure_driver; } user = get(user_id, true); if (user != 0) { user->set_session(second_token, _session_expiration_time); user->unlock(); } return true; wrong_server_token: oss << "Wrong token format"; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_user: oss << "User: " << target_username << " does not exist. Returned by server auth"; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_driver: oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_nodriver: NebulaLog::log("AuM",Log::ERROR, "Auth Error: Authentication driver not enabled. " "Check AUTH_MAD in oned.conf"); auth_failure: user_id = -1; group_id = -1; uname = ""; gname = ""; return false; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ bool UserPool::authenticate_external(const string& username, const string& token, int& user_id, int& group_id, string& uname, string& gname) { ostringstream oss; istringstream is; string driver_name; string mad_name; string mad_pass; string error_str; Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); AuthRequest ar(-1,-1); if (authm == 0) { goto auth_failure_nodriver; } //Initialize authentication request and call the driver ar.add_authenticate(UserPool::DEFAULT_AUTH, username,"-",token); authm->trigger(AuthManager::AUTHENTICATE, &ar); ar.wait(); if (ar.result != true) //User was not authenticated { goto auth_failure_driver; } is.str(ar.message); user_id = -1; if ( is.good() ) { is >> driver_name >> ws; } if ( !is.fail() ) { is >> mad_name >> ws; } if ( !is.fail() ) { getline(is, mad_pass); } if ( !is.fail() ) { allocate(&user_id, GroupPool::USERS_ID, mad_name, GroupPool::USERS_NAME, mad_pass, driver_name, true, error_str); } if ( user_id == -1 ) { goto auth_failure_user; } group_id = GroupPool::USERS_ID; uname = mad_name; gname = GroupPool::USERS_NAME; return true; auth_failure_user: oss << "Can't create user: " << error_str << ". Driver response: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_driver: oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_nodriver: NebulaLog::log("AuM",Log::ERROR, "Auth Error: Authentication driver not enabled. " "Check AUTH_MAD in oned.conf"); auth_failure: user_id = -1; group_id = -1; uname = ""; gname = ""; return false; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ bool UserPool::authenticate(const string& session, int& user_id, int& group_id, string& uname, string& gname) { User * user = 0; string username; string token; int rc; bool ar; rc = User::split_secret(session,username,token); if ( rc != 0 ) { return false; } user = get(username,true); if (user != 0 ) //User known to OpenNebula { if ( user->get_auth_driver() == UserPool::SERVER_AUTH ) { ar = authenticate_server(user,token,user_id,group_id,uname,gname); } else { ar = authenticate_internal(user,token,user_id,group_id,uname,gname); } } else { ar = authenticate_external(username,token,user_id,group_id,uname,gname); } return ar; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::authorize(AuthRequest& ar) { Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); int rc = -1; if (authm == 0) { if (ar.core_authorize()) { rc = 0; } } else { authm->trigger(AuthManager::AUTHORIZE,&ar); ar.wait(); if (ar.result==true) { rc = 0; } else { ostringstream oss; oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); } } return rc; } <commit_msg>bug #847: Make drivers with name matching server* a server driver<commit_after>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) */ /* */ /* 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. */ /* -------------------------------------------------------------------------- */ /* ************************************************************************** */ /* User Pool */ /* ************************************************************************** */ #include "UserPool.h" #include "NebulaLog.h" #include "Nebula.h" #include "AuthManager.h" #include "SSLTools.h" #include <fstream> #include <sys/types.h> #include <pwd.h> #include <stdlib.h> const char * UserPool::CORE_AUTH = "core"; const char * UserPool::SERVER_AUTH = "server*"; const char * UserPool::PUBLIC_AUTH = "public"; const char * UserPool::DEFAULT_AUTH = "default"; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ time_t UserPool::_session_expiration_time; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ UserPool::UserPool(SqlDB * db, time_t __session_expiration_time): PoolSQL(db,User::table) { int one_uid = -1; ostringstream oss; string one_token; string one_name; string one_pass; string one_auth_file; const char * one_auth; ifstream file; _session_expiration_time = __session_expiration_time; if (get(0,false) != 0) { return; } // User oneadmin needs to be added in the bootstrap one_auth = getenv("ONE_AUTH"); if (!one_auth) { struct passwd * pw_ent; pw_ent = getpwuid(getuid()); if ((pw_ent != NULL) && (pw_ent->pw_dir != NULL)) { one_auth_file = pw_ent->pw_dir; one_auth_file += "/.one/one_auth"; one_auth = one_auth_file.c_str(); } else { oss << "Could not get one_auth file location"; } } file.open(one_auth); if (file.good()) { getline(file,one_token); if (file.fail()) { oss << "Error reading file: " << one_auth; } else { if (User::split_secret(one_token,one_name,one_pass) == 0) { string error_str; allocate(&one_uid, GroupPool::ONEADMIN_ID, one_name, GroupPool::ONEADMIN_NAME, one_pass, UserPool::CORE_AUTH, true, error_str); } else { oss << "Wrong format must be <username>:<password>"; } } } else { oss << "Cloud not open file: " << one_auth; } file.close(); if (one_uid != 0) { NebulaLog::log("ONE",Log::ERROR,oss); throw; } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::allocate ( int * oid, int gid, const string& uname, const string& gname, const string& password, const string& auth, bool enabled, string& error_str) { Nebula& nd = Nebula::instance(); User * user; GroupPool * gpool; Group * group; string auth_driver = auth; string upass = password; ostringstream oss; // Check username and password if ( !User::pass_is_valid(password, error_str) ) { goto error_pass; } if ( !User::name_is_valid(uname, error_str) ) { goto error_name; } // Check for duplicates user = get(uname,false); if ( user !=0 ) { goto error_duplicated; } // Set auth driver and hash password for CORE_AUTH if (auth_driver.empty()) { auth_driver = UserPool::CORE_AUTH; } if (auth_driver == UserPool::CORE_AUTH) { upass = SSLTools::sha1_digest(password); } // Build a new User object user = new User(-1, gid, uname, gname, upass, auth_driver, enabled); // Insert the Object in the pool *oid = PoolSQL::allocate(user, error_str); if ( *oid < 0 ) { return *oid; } // Adds User to group gpool = nd.get_gpool(); group = gpool->get(gid, true); if( group == 0 ) { return -1; } group->add_user(*oid); gpool->update(group); group->unlock(); return *oid; error_pass: oss << error_str << "."; goto error_common; error_name: oss << error_str << "."; goto error_common; error_duplicated: oss << "NAME is already taken by USER " << user->get_oid() << "."; goto error_common; error_common: *oid = -1; error_str = oss.str(); return *oid; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ bool UserPool::authenticate_internal(User * user, const string& token, int& user_id, int& group_id, string& uname, string& gname) { bool result = false; ostringstream oss; string password; string auth_driver; string username; Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); username = user->name; password = user->password; user_id = user->oid; group_id = user->gid; uname = user->name; gname = user->gname; auth_driver = user->auth_driver; result = user->valid_session(token); user->unlock(); if (result) { return true; } AuthRequest ar(user_id, group_id); if ( auth_driver == UserPool::CORE_AUTH ) { ar.add_authenticate("",username,password,token); if (!ar.core_authenticate()) { goto auth_failure; } } else if (auth_driver == UserPool::PUBLIC_AUTH ) { goto auth_failure_public; } else if ( authm != 0 ) //use auth driver if it was loaded { //Initialize authentication request and call the driver ar.add_authenticate(auth_driver,username,password,token); authm->trigger(AuthManager::AUTHENTICATE,&ar); ar.wait(); if (ar.result!=true) //User was not authenticated { goto auth_failure_driver; } } else { goto auth_failure_nodriver; } user = get(user_id, true); if (user != 0) { user->set_session(token, _session_expiration_time); user->unlock(); } return true; auth_failure_public: oss << "User: " << username << " attempted a direct authentication."; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_driver: oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_nodriver: NebulaLog::log("AuM",Log::ERROR, "Auth Error: Authentication driver not enabled. " "Check AUTH_MAD in oned.conf"); auth_failure: user_id = -1; group_id = -1; uname = ""; gname = ""; return false; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ bool UserPool::authenticate_server(User * user, const string& token, int& user_id, int& group_id, string& uname, string& gname) { bool result = false; ostringstream oss; string server_password; string auth_driver; string server_username; string target_username; string second_token; Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); server_username = user->name; server_password = user->password; auth_driver = user->auth_driver; AuthRequest ar(user->oid, user->gid); user->unlock(); // token = target_username:second_token int rc = User::split_secret(token,target_username,second_token); if ( rc != 0 ) { goto wrong_server_token; } user = get(target_username,true); if ( user == 0 ) { goto auth_failure_user; } user_id = user->oid; group_id = user->gid; uname = user->name; gname = user->gname; result = user->valid_session(second_token); user->unlock(); if (result) { return true; } if ( authm == 0 ) { goto auth_failure_nodriver; } //Initialize authentication request and call the driver ar.add_authenticate(auth_driver,server_username,server_password,token); authm->trigger(AuthManager::AUTHENTICATE,&ar); ar.wait(); if (ar.result!=true) //User was not authenticated { goto auth_failure_driver; } user = get(user_id, true); if (user != 0) { user->set_session(second_token, _session_expiration_time); user->unlock(); } return true; wrong_server_token: oss << "Wrong token format"; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_user: oss << "User: " << target_username << " does not exist. Returned by server auth"; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_driver: oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_nodriver: NebulaLog::log("AuM",Log::ERROR, "Auth Error: Authentication driver not enabled. " "Check AUTH_MAD in oned.conf"); auth_failure: user_id = -1; group_id = -1; uname = ""; gname = ""; return false; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ bool UserPool::authenticate_external(const string& username, const string& token, int& user_id, int& group_id, string& uname, string& gname) { ostringstream oss; istringstream is; string driver_name; string mad_name; string mad_pass; string error_str; Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); AuthRequest ar(-1,-1); if (authm == 0) { goto auth_failure_nodriver; } //Initialize authentication request and call the driver ar.add_authenticate(UserPool::DEFAULT_AUTH, username,"-",token); authm->trigger(AuthManager::AUTHENTICATE, &ar); ar.wait(); if (ar.result != true) //User was not authenticated { goto auth_failure_driver; } is.str(ar.message); user_id = -1; if ( is.good() ) { is >> driver_name >> ws; } if ( !is.fail() ) { is >> mad_name >> ws; } if ( !is.fail() ) { getline(is, mad_pass); } if ( !is.fail() ) { allocate(&user_id, GroupPool::USERS_ID, mad_name, GroupPool::USERS_NAME, mad_pass, driver_name, true, error_str); } if ( user_id == -1 ) { goto auth_failure_user; } group_id = GroupPool::USERS_ID; uname = mad_name; gname = GroupPool::USERS_NAME; return true; auth_failure_user: oss << "Can't create user: " << error_str << ". Driver response: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_driver: oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); goto auth_failure; auth_failure_nodriver: NebulaLog::log("AuM",Log::ERROR, "Auth Error: Authentication driver not enabled. " "Check AUTH_MAD in oned.conf"); auth_failure: user_id = -1; group_id = -1; uname = ""; gname = ""; return false; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ bool UserPool::authenticate(const string& session, int& user_id, int& group_id, string& uname, string& gname) { User * user = 0; string username; string token; int rc; bool ar; rc = User::split_secret(session,username,token); if ( rc != 0 ) { return false; } user = get(username,true); if (user != 0 ) //User known to OpenNebula { string driver = user->get_auth_driver(); if ( fnmatch(UserPool::SERVER_AUTH, driver.c_str(), 0) == 0 ) { ar = authenticate_server(user,token,user_id,group_id,uname,gname); } else { ar = authenticate_internal(user,token,user_id,group_id,uname,gname); } } else { ar = authenticate_external(username,token,user_id,group_id,uname,gname); } return ar; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::authorize(AuthRequest& ar) { Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); int rc = -1; if (authm == 0) { if (ar.core_authorize()) { rc = 0; } } else { authm->trigger(AuthManager::AUTHORIZE,&ar); ar.wait(); if (ar.result==true) { rc = 0; } else { ostringstream oss; oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); } } return rc; } <|endoftext|>
<commit_before>#include <stdio.h> #include <fcntl.h> #include <gphoto2/gphoto2-camera.h> Camera *camera; GPContext *context; void error_func (GPContext *context, const char *format, va_list args, void *data) { fprintf (stderr, "*** Contexterror ***\n"); vfprintf (stderr, format, args); fprintf (stderr, "\n"); } void message_func (GPContext *context, const char *format, va_list args, void *data) { vprintf (format, args); printf ("\n"); } int main (int argc, char *argv[]) { gp_camera_new (&camera); context = gp_context_new(); // set callbacks for camera messages gp_context_set_error_func (context, error_func, NULL); gp_context_set_message_func (context, message_func, NULL); } <commit_msg>removed bad code<commit_after><|endoftext|>
<commit_before>#pragma once #include <charconv> #pragma GCC diagnostic push #ifdef __clang__ #pragma GCC diagnostic ignored "-Wold-style-cast" #pragma GCC diagnostic ignored "-Wimplicit-int-conversion" #pragma GCC diagnostic ignored "-Wshift-sign-overflow" #pragma GCC diagnostic ignored "-Wundef" #endif #include <date/date.h> #include <date/iso_week.h> #pragma GCC diagnostic pop #include "acmacs-base/fmt.hh" // #include "acmacs-base/sfinae.hh" // ---------------------------------------------------------------------- namespace date { class date_parse_error : public std::runtime_error { public: using std::runtime_error::runtime_error; }; using period_diff_t = int; enum class throw_on_error { no, yes }; enum class allow_incomplete { no, yes }; enum class month_first { no, yes }; // European vs. US if parts are separated by slashes constexpr year_month_day invalid_date() { return year{0} / 0 / 0; } inline year_month_day today() { return floor<days>(std::chrono::system_clock::now()); } inline size_t current_year() { return static_cast<size_t>(static_cast<int>(today().year())); } inline auto get_year(const year_month_day& dt) { return static_cast<size_t>(static_cast<int>(dt.year())); } inline auto year_ok(const year_month_day& dt) { const auto ye = get_year(dt); return ye >= 1900 && ye <= current_year(); } inline auto get_month(const year_month_day& dt) { return static_cast<unsigned>(dt.month()); } inline auto month_ok(const year_month_day& dt) { const auto mont = get_month(dt); return mont > 0 && mont <= 12; } inline auto get_day(const year_month_day& dt) { return static_cast<unsigned>(dt.day()); } inline std::string display(const year_month_day& dt, const char* fmt = "%Y-%m-%d") { return dt.ok() ? format(fmt, dt) : std::string{"*invalid-date*"}; } inline std::string display(const year_month_day& dt, allow_incomplete allow) { if (dt.ok()) { return format("%Y-%m-%d", dt); } else if (allow == allow_incomplete::yes) { if (get_month(dt) == 0) return fmt::format("{}", get_year(dt)); else if (get_day(dt) == 0) return fmt::format("{}-{:02d}", get_year(dt), get_month(dt)); else return fmt::format("{}-{:02d}-{:02d}", get_year(dt), get_month(dt), get_day(dt)); } else return fmt::format("*invalid-date: {}-{}-{}*", get_year(dt), get_month(dt), get_day(dt)); } inline auto month_3(const year_month_day& dt) { return format("%b", dt); } inline auto year_2(const year_month_day& dt) { return format("%y", dt); } inline auto year_4(const year_month_day& dt) { return format("%Y", dt); } inline auto month3_year2(const year_month_day& dt) { return format("%b %y", dt); } inline auto monthtext(const year_month_day& dt) { return format("%B", dt); } inline auto monthtext_year(const year_month_day& dt) { return format("%B %Y", dt); } inline auto year4_month2(const year_month_day& dt) { return format("%Y-%m", dt); } inline auto year4_month2_day2(const year_month_day& dt) { return format("%Y-%m-%d", dt); } inline auto beginning_of_month(const year_month_day& dt) { unsigned mont = static_cast<unsigned>(dt.month()); if (mont == 0) mont = 7; return year_month_day(dt.year(), month{mont}, day{1}); } inline auto beginning_of_year(const year_month_day& dt) { return year_month_day(dt.year(), month{1}, day{1}); } inline auto beginning_of_week(const year_month_day& dt) { const auto make = [](const iso_week::year_weeknum_weekday& yw) { return year_month_day{iso_week::year_weeknum_weekday(yw.year(), yw.weeknum(), iso_week::weekday{Monday})}; }; if (static_cast<unsigned>(dt.day()) == 0) { if (static_cast<unsigned>(dt.month()) == 0) return make(iso_week::year_weeknum_weekday(dt.year() / month{7} / day{1})); else return make(iso_week::year_weeknum_weekday(dt.year() / dt.month() / day{1})); } else { return make(iso_week::year_weeknum_weekday(dt)); } } // returns date for the last day of the year-month stored in this inline auto end_of_month(const year_month_day& dt) { return year_month_day(year_month_day_last(dt.year(), month_day_last(dt.month()))); } inline auto years_ago(const year_month_day& dt, period_diff_t number_of_years) { return dt - date::years(number_of_years); } inline auto months_ago(const year_month_day& dt, period_diff_t number_of_months) { return dt - date::months(number_of_months); } inline auto weeks_ago(const year_month_day& dt, period_diff_t number_of_weeks) { return static_cast<date::sys_days>(dt) - date::weeks(number_of_weeks); } inline auto days_ago(const year_month_day& dt, period_diff_t number_of_days) { return static_cast<date::sys_days>(dt) - date::days(number_of_days); } inline auto next_month(const year_month_day& dt) { return dt + date::months(1); } inline auto next_year(const year_month_day& dt) { return dt + date::years(1); } inline auto next_week(const year_month_day& dt) { return year_month_day{static_cast<sys_days>(dt) + date::weeks(1)}; } inline auto next_day(const year_month_day& dt) { return year_month_day{static_cast<sys_days>(dt) + date::days(1)}; } inline auto& increment_month(year_month_day& dt, period_diff_t number_of_months = 1) { dt += date::months(number_of_months); return dt; } inline auto& decrement_month(year_month_day& dt, period_diff_t number_of_months = 1) { dt -= date::months(number_of_months); return dt; } inline auto& increment_year(year_month_day& dt, period_diff_t number_of_years = 1) { dt += date::years(number_of_years); return dt; } inline auto& decrement_year(year_month_day& dt, period_diff_t number_of_years = 1) { dt -= date::years(number_of_years); return dt; } inline auto& increment_week(year_month_day& dt, period_diff_t number_of_weeks = 1) { dt = static_cast<date::sys_days>(dt) + date::weeks{number_of_weeks}; return dt; } inline auto& decrement_week(year_month_day& dt, period_diff_t number_of_weeks = 1) { dt = static_cast<date::sys_days>(dt) - date::weeks{number_of_weeks}; return dt; } inline auto& increment_day(year_month_day& dt, period_diff_t number_of_days = 1) { dt = static_cast<date::sys_days>(dt) + date::days{number_of_days}; return dt; } inline auto& decrement_day(year_month_day& dt, period_diff_t number_of_days = 1) { dt = static_cast<date::sys_days>(dt) - date::days{number_of_days}; return dt; } inline year_month_day from_string(std::string_view source, const char* fmt, throw_on_error toe = throw_on_error::yes) { year_month_day result = invalid_date(); std::istringstream in(std::string{source}); if (from_stream(in, fmt, result)) { if (static_cast<size_t>(in.tellg()) < source.size()) { if (toe == throw_on_error::yes) throw date_parse_error(fmt::format("cannot parse date from \"{}\" (read fewer symbols than available)", source)); else return invalid_date(); } if (result.year() < year{30}) result += years(2000); else if (result.year() < year{100}) result += years(1900); } return result; } inline year_month_day from_string(std::string_view source, allow_incomplete allow = allow_incomplete::no, throw_on_error toe = throw_on_error::yes, month_first mf = month_first::no) { if (source.empty()) { if (toe == throw_on_error::yes) throw date_parse_error(fmt::format("cannot parse date from \"{}\"", source)); return invalid_date(); } using fmt_order_t = std::vector<const char*>; const auto fmt_order = [mf]() -> fmt_order_t { const auto month_first_no = [] { return fmt_order_t{"%Y-%m-%d", "%Y%m%d", "%d/%m/%Y", "%m/%d/%Y", "%Y/%m/%d", "%B%n %d%n %Y", "%B %d,%n %Y", "%b%n %d%n %Y", "%b %d,%n %Y"}; }; const auto month_first_yes = [] { return fmt_order_t{"%Y-%m-%d", "%Y%m%d", "%m/%d/%Y", "%d/%m/%Y", "%Y/%m/%d", "%B%n %d%n %Y", "%B %d,%n %Y", "%b%n %d%n %Y", "%b %d,%n %Y"}; }; switch (mf) { case month_first::no: return month_first_no(); case month_first::yes: return month_first_yes(); } return month_first_no(); // hey g++-10 }; for (const char* fmt : fmt_order()) { // if (const auto result = from_string(std::forward<S>(source), fmt); result.ok()) if (const auto result = from_string(source, fmt, toe); result.ok() /* && year_ok(result) */) return result; } if (allow == allow_incomplete::yes) { for (const char* fmt : {"%Y-00-00", "%Y-%m-00", "%Y-%m", "%Y%m", "%Y"}) { // date lib cannot parse incomplete date constexpr int invalid = 99999; struct tm tm; tm.tm_mon = tm.tm_mday = invalid; if (strptime(source.data(), fmt, &tm) == &*source.end()) { if (tm.tm_mon == invalid) return year{tm.tm_year + 1900} / 0 / 0; else return year{tm.tm_year + 1900} / month{static_cast<unsigned>(tm.tm_mon) + 1} / 0; } } } if (toe == throw_on_error::yes) throw date_parse_error(fmt::format("cannot parse date from \"{}\" (allow_incomplete: {})", source, allow == allow_incomplete::yes)); return invalid_date(); } inline year year_from_string(std::string_view source) { int yr; if (const auto [p, ec] = std::from_chars(&*source.begin(), &*source.end(), yr); ec == std::errc{} && p == &*source.end()) return year{yr}; else return year{9999}; } inline month month_from_string(std::string_view source) { unsigned mo; if (const auto [p, ec] = std::from_chars(&*source.begin(), &*source.end(), mo); ec == std::errc{} && p == &*source.end()) return month{mo}; else return month{99}; } inline day day_from_string(std::string_view source) { unsigned dy; if (const auto [p, ec] = std::from_chars(&*source.begin(), &*source.end(), dy); ec == std::errc{} && p == &*source.end()) return day{dy}; else return day{99}; } inline std::string current_date_time() { const auto now = std::chrono::system_clock::now(); const auto in_time_t = std::chrono::system_clock::to_time_t(now); return fmt::format("{:%Y-%m-%d %H:%M:%S %Z}", *std::localtime(&in_time_t)); } inline period_diff_t days_between_dates(const year_month_day& a, const year_month_day& b) { return std::chrono::duration_cast<days>(static_cast<sys_days>(b) - static_cast<sys_days>(a)).count(); } inline period_diff_t weeks_between_dates(const year_month_day& a, const year_month_day& b) { return std::chrono::duration_cast<weeks>(static_cast<sys_days>(b) - static_cast<sys_days>(a)).count(); } inline period_diff_t months_between_dates(const year_month_day& a, const year_month_day& b) { return std::chrono::duration_cast<months>(static_cast<sys_days>(b) - static_cast<sys_days>(a)).count(); } inline period_diff_t calendar_months_between_dates(const year_month_day& a, const year_month_day& b) { return std::chrono::duration_cast<months>(static_cast<sys_days>(beginning_of_month(b)) - static_cast<sys_days>(beginning_of_month(a))).count(); } inline period_diff_t calendar_months_between_dates_inclusive(const year_month_day& a, const year_month_day& b) { return calendar_months_between_dates(a, b) + 1; } inline period_diff_t years_between_dates(const year_month_day& a, const year_month_day& b) { return std::chrono::duration_cast<years>(static_cast<sys_days>(b) - static_cast<sys_days>(a)).count(); } } // namespace date // ---------------------------------------------------------------------- template <typename T> struct fmt::formatter<T, std::enable_if_t<std::is_base_of<date::year_month_day, T>::value, char>> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const date::year_month_day& dt, FormatCtx& ctx) { return fmt::formatter<std::string>::format(date::display(dt, date::allow_incomplete::yes), ctx); } }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>minor fix<commit_after>#pragma once #include <charconv> #pragma GCC diagnostic push #ifdef __clang__ #pragma GCC diagnostic ignored "-Wold-style-cast" #pragma GCC diagnostic ignored "-Wimplicit-int-conversion" #pragma GCC diagnostic ignored "-Wshift-sign-overflow" #pragma GCC diagnostic ignored "-Wundef" #endif #include <date/date.h> #include <date/iso_week.h> #pragma GCC diagnostic pop #include "acmacs-base/fmt.hh" // #include "acmacs-base/sfinae.hh" // ---------------------------------------------------------------------- namespace date { class date_parse_error : public std::runtime_error { public: using std::runtime_error::runtime_error; }; using period_diff_t = int; enum class throw_on_error { no, yes }; enum class allow_incomplete { no, yes }; enum class month_first { no, yes }; // European vs. US if parts are separated by slashes constexpr year_month_day invalid_date() { return year{0} / 0 / 0; } inline year_month_day today() { return floor<days>(std::chrono::system_clock::now()); } inline size_t current_year() { return static_cast<size_t>(static_cast<int>(today().year())); } inline auto get_year(const year_month_day& dt) { return static_cast<size_t>(static_cast<int>(dt.year())); } inline auto year_ok(const year_month_day& dt) { const auto ye = get_year(dt); return ye >= 1900 && ye <= current_year(); } inline auto get_month(const year_month_day& dt) { return static_cast<unsigned>(dt.month()); } inline auto month_ok(const year_month_day& dt) { const auto mont = get_month(dt); return mont > 0 && mont <= 12; } inline auto get_day(const year_month_day& dt) { return static_cast<unsigned>(dt.day()); } inline std::string display(const year_month_day& dt, const char* fmt = "%Y-%m-%d") { return dt.ok() ? format(fmt, dt) : std::string{"invalid-date"}; } inline std::string display(const year_month_day& dt, allow_incomplete allow) { if (dt.ok()) { return format("%Y-%m-%d", dt); } else if (allow == allow_incomplete::yes) { if (get_month(dt) == 0) return fmt::format("{}", get_year(dt)); else if (get_day(dt) == 0) return fmt::format("{}-{:02d}", get_year(dt), get_month(dt)); else return fmt::format("{}-{:02d}-{:02d}", get_year(dt), get_month(dt), get_day(dt)); } else return fmt::format("*invalid-date: {}-{}-{}*", get_year(dt), get_month(dt), get_day(dt)); } inline auto month_3(const year_month_day& dt) { return format("%b", dt); } inline auto year_2(const year_month_day& dt) { return format("%y", dt); } inline auto year_4(const year_month_day& dt) { return format("%Y", dt); } inline auto month3_year2(const year_month_day& dt) { return format("%b %y", dt); } inline auto monthtext(const year_month_day& dt) { return format("%B", dt); } inline auto monthtext_year(const year_month_day& dt) { return format("%B %Y", dt); } inline auto year4_month2(const year_month_day& dt) { return format("%Y-%m", dt); } inline auto year4_month2_day2(const year_month_day& dt) { return format("%Y-%m-%d", dt); } inline auto beginning_of_month(const year_month_day& dt) { unsigned mont = static_cast<unsigned>(dt.month()); if (mont == 0) mont = 7; return year_month_day(dt.year(), month{mont}, day{1}); } inline auto beginning_of_year(const year_month_day& dt) { return year_month_day(dt.year(), month{1}, day{1}); } inline auto beginning_of_week(const year_month_day& dt) { const auto make = [](const iso_week::year_weeknum_weekday& yw) { return year_month_day{iso_week::year_weeknum_weekday(yw.year(), yw.weeknum(), iso_week::weekday{Monday})}; }; if (static_cast<unsigned>(dt.day()) == 0) { if (static_cast<unsigned>(dt.month()) == 0) return make(iso_week::year_weeknum_weekday(dt.year() / month{7} / day{1})); else return make(iso_week::year_weeknum_weekday(dt.year() / dt.month() / day{1})); } else { return make(iso_week::year_weeknum_weekday(dt)); } } // returns date for the last day of the year-month stored in this inline auto end_of_month(const year_month_day& dt) { return year_month_day(year_month_day_last(dt.year(), month_day_last(dt.month()))); } inline auto years_ago(const year_month_day& dt, period_diff_t number_of_years) { return dt - date::years(number_of_years); } inline auto months_ago(const year_month_day& dt, period_diff_t number_of_months) { return dt - date::months(number_of_months); } inline auto weeks_ago(const year_month_day& dt, period_diff_t number_of_weeks) { return static_cast<date::sys_days>(dt) - date::weeks(number_of_weeks); } inline auto days_ago(const year_month_day& dt, period_diff_t number_of_days) { return static_cast<date::sys_days>(dt) - date::days(number_of_days); } inline auto next_month(const year_month_day& dt) { return dt + date::months(1); } inline auto next_year(const year_month_day& dt) { return dt + date::years(1); } inline auto next_week(const year_month_day& dt) { return year_month_day{static_cast<sys_days>(dt) + date::weeks(1)}; } inline auto next_day(const year_month_day& dt) { return year_month_day{static_cast<sys_days>(dt) + date::days(1)}; } inline auto& increment_month(year_month_day& dt, period_diff_t number_of_months = 1) { dt += date::months(number_of_months); return dt; } inline auto& decrement_month(year_month_day& dt, period_diff_t number_of_months = 1) { dt -= date::months(number_of_months); return dt; } inline auto& increment_year(year_month_day& dt, period_diff_t number_of_years = 1) { dt += date::years(number_of_years); return dt; } inline auto& decrement_year(year_month_day& dt, period_diff_t number_of_years = 1) { dt -= date::years(number_of_years); return dt; } inline auto& increment_week(year_month_day& dt, period_diff_t number_of_weeks = 1) { dt = static_cast<date::sys_days>(dt) + date::weeks{number_of_weeks}; return dt; } inline auto& decrement_week(year_month_day& dt, period_diff_t number_of_weeks = 1) { dt = static_cast<date::sys_days>(dt) - date::weeks{number_of_weeks}; return dt; } inline auto& increment_day(year_month_day& dt, period_diff_t number_of_days = 1) { dt = static_cast<date::sys_days>(dt) + date::days{number_of_days}; return dt; } inline auto& decrement_day(year_month_day& dt, period_diff_t number_of_days = 1) { dt = static_cast<date::sys_days>(dt) - date::days{number_of_days}; return dt; } inline year_month_day from_string(std::string_view source, const char* fmt, throw_on_error toe = throw_on_error::yes) { year_month_day result = invalid_date(); std::istringstream in(std::string{source}); if (from_stream(in, fmt, result)) { if (static_cast<size_t>(in.tellg()) < source.size()) { if (toe == throw_on_error::yes) throw date_parse_error(fmt::format("cannot parse date from \"{}\" (read fewer symbols than available)", source)); else return invalid_date(); } if (result.year() < year{30}) result += years(2000); else if (result.year() < year{100}) result += years(1900); } return result; } inline year_month_day from_string(std::string_view source, allow_incomplete allow = allow_incomplete::no, throw_on_error toe = throw_on_error::yes, month_first mf = month_first::no) { if (source.empty()) { if (toe == throw_on_error::yes) throw date_parse_error(fmt::format("cannot parse date from \"{}\"", source)); return invalid_date(); } using fmt_order_t = std::vector<const char*>; const auto fmt_order = [mf]() -> fmt_order_t { const auto month_first_no = [] { return fmt_order_t{"%Y-%m-%d", "%Y%m%d", "%d/%m/%Y", "%m/%d/%Y", "%Y/%m/%d", "%B%n %d%n %Y", "%B %d,%n %Y", "%b%n %d%n %Y", "%b %d,%n %Y"}; }; const auto month_first_yes = [] { return fmt_order_t{"%Y-%m-%d", "%Y%m%d", "%m/%d/%Y", "%d/%m/%Y", "%Y/%m/%d", "%B%n %d%n %Y", "%B %d,%n %Y", "%b%n %d%n %Y", "%b %d,%n %Y"}; }; switch (mf) { case month_first::no: return month_first_no(); case month_first::yes: return month_first_yes(); } return month_first_no(); // hey g++-10 }; for (const char* fmt : fmt_order()) { // if (const auto result = from_string(std::forward<S>(source), fmt); result.ok()) if (const auto result = from_string(source, fmt, toe); result.ok() /* && year_ok(result) */) return result; } if (allow == allow_incomplete::yes) { for (const char* fmt : {"%Y-00-00", "%Y-%m-00", "%Y-%m", "%Y%m", "%Y"}) { // date lib cannot parse incomplete date constexpr int invalid = 99999; struct tm tm; tm.tm_mon = tm.tm_mday = invalid; if (strptime(source.data(), fmt, &tm) == &*source.end()) { if (tm.tm_mon == invalid) return year{tm.tm_year + 1900} / 0 / 0; else return year{tm.tm_year + 1900} / month{static_cast<unsigned>(tm.tm_mon) + 1} / 0; } } } if (toe == throw_on_error::yes) throw date_parse_error(fmt::format("cannot parse date from \"{}\" (allow_incomplete: {})", source, allow == allow_incomplete::yes)); return invalid_date(); } inline year year_from_string(std::string_view source) { int yr; if (const auto [p, ec] = std::from_chars(&*source.begin(), &*source.end(), yr); ec == std::errc{} && p == &*source.end()) return year{yr}; else return year{9999}; } inline month month_from_string(std::string_view source) { unsigned mo; if (const auto [p, ec] = std::from_chars(&*source.begin(), &*source.end(), mo); ec == std::errc{} && p == &*source.end()) return month{mo}; else return month{99}; } inline day day_from_string(std::string_view source) { unsigned dy; if (const auto [p, ec] = std::from_chars(&*source.begin(), &*source.end(), dy); ec == std::errc{} && p == &*source.end()) return day{dy}; else return day{99}; } inline std::string current_date_time() { const auto now = std::chrono::system_clock::now(); const auto in_time_t = std::chrono::system_clock::to_time_t(now); return fmt::format("{:%Y-%m-%d %H:%M:%S %Z}", *std::localtime(&in_time_t)); } inline period_diff_t days_between_dates(const year_month_day& a, const year_month_day& b) { return std::chrono::duration_cast<days>(static_cast<sys_days>(b) - static_cast<sys_days>(a)).count(); } inline period_diff_t weeks_between_dates(const year_month_day& a, const year_month_day& b) { return std::chrono::duration_cast<weeks>(static_cast<sys_days>(b) - static_cast<sys_days>(a)).count(); } inline period_diff_t months_between_dates(const year_month_day& a, const year_month_day& b) { return std::chrono::duration_cast<months>(static_cast<sys_days>(b) - static_cast<sys_days>(a)).count(); } inline period_diff_t calendar_months_between_dates(const year_month_day& a, const year_month_day& b) { return std::chrono::duration_cast<months>(static_cast<sys_days>(beginning_of_month(b)) - static_cast<sys_days>(beginning_of_month(a))).count(); } inline period_diff_t calendar_months_between_dates_inclusive(const year_month_day& a, const year_month_day& b) { return calendar_months_between_dates(a, b) + 1; } inline period_diff_t years_between_dates(const year_month_day& a, const year_month_day& b) { return std::chrono::duration_cast<years>(static_cast<sys_days>(b) - static_cast<sys_days>(a)).count(); } } // namespace date // ---------------------------------------------------------------------- template <typename T> struct fmt::formatter<T, std::enable_if_t<std::is_base_of<date::year_month_day, T>::value, char>> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const date::year_month_day& dt, FormatCtx& ctx) { return fmt::formatter<std::string>::format(date::display(dt, date::allow_incomplete::yes), ctx); } }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Aaron Kennedy <aaron.kennedy@jollamobile.com> ** ** This file is part of lipstick. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QDBusConnection> #include "lipstickcompositorwindow.h" #include "lipstickcompositor.h" #include "windowmodel.h" WindowModel::WindowModel() : m_complete(false) { LipstickCompositor *c = LipstickCompositor::instance(); if (!c) { qWarning("WindowModel: Compositor must be created before WindowModel"); } else { c->m_windowModels.append(this); } QDBusConnection dbus = QDBusConnection::sessionBus(); dbus.registerObject("/WindowModel", this, QDBusConnection::ExportAllSlots); dbus.registerService("org.nemomobile.lipstick"); } WindowModel::~WindowModel() { LipstickCompositor *c = LipstickCompositor::instance(); if (c) c->m_windowModels.removeAll(this); } int WindowModel::itemCount() const { return m_items.count(); } int WindowModel::windowId(int index) const { if (index < 0 || index >= m_items.count()) return 0; return m_items.at(index); } int WindowModel::rowCount(const QModelIndex &) const { return m_items.count(); } QVariant WindowModel::data(const QModelIndex &index, int role) const { int idx = index.row(); if (idx < 0 || idx >= m_items.count()) return QVariant(); LipstickCompositor *c = LipstickCompositor::instance(); if (role == Qt::UserRole + 1) { return m_items.at(idx); } else if (role == Qt::UserRole + 2) { QWaylandSurface *s = c->surfaceForId(m_items.at(idx)); return s?s->processId():0; } else if (role == Qt::UserRole + 3) { LipstickCompositorWindow *w = static_cast<LipstickCompositorWindow *>(c->windowForId(m_items.at(idx))); return w->title(); } else { return QVariant(); } } QHash<int, QByteArray> WindowModel::roleNames() const { QHash<int, QByteArray> roles; roles[Qt::UserRole + 1] = "window"; roles[Qt::UserRole + 2] = "processId"; roles[Qt::UserRole + 3] = "title"; return roles; } void WindowModel::classBegin() { } void WindowModel::componentComplete() { m_complete = true; refresh(); } /*! Reimplement this method to provide custom filtering. */ bool WindowModel::approveWindow(LipstickCompositorWindow *window) { return window->isInProcess() == false; } void WindowModel::addItem(int id) { if (!m_complete) return; LipstickCompositor *c = LipstickCompositor::instance(); LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(c->windowForId(id)); if (!approveWindow(window)) return; beginInsertRows(QModelIndex(), m_items.count(), m_items.count()); m_items.append(id); endInsertRows(); emit itemAdded(m_items.count() - 1); emit itemCountChanged(); } void WindowModel::remItem(int id) { if (!m_complete) return; int idx = m_items.indexOf(id); if (idx == -1) return; beginRemoveRows(QModelIndex(), idx, idx); m_items.removeAt(idx); endRemoveRows(); emit itemCountChanged(); } void WindowModel::titleChanged(int id) { if (!m_complete) return; int idx = m_items.indexOf(id); if (idx == -1) return; emit dataChanged(index(idx, 0), index(idx, 0)); } void WindowModel::refresh() { LipstickCompositor *c = LipstickCompositor::instance(); if (!m_complete || !c) return; beginResetModel(); m_items.clear(); for (QHash<int, LipstickCompositorWindow *>::ConstIterator iter = c->m_mappedSurfaces.begin(); iter != c->m_mappedSurfaces.end(); ++iter) { if (approveWindow(iter.value())) m_items.append(iter.key()); } endResetModel(); } // used by mapplauncherd to bring a binary to the front void WindowModel::launchProcess(const QString &binaryName) { LipstickCompositor *c = LipstickCompositor::instance(); if (!m_complete || !c) return; for (QHash<int, LipstickCompositorWindow *>::ConstIterator iter = c->m_mappedSurfaces.begin(); iter != c->m_mappedSurfaces.end(); ++iter) { LipstickCompositorWindow *win = iter.value(); if (!approveWindow(win)) continue; QString pidFile = QString::fromLatin1("/proc/%1/cmdline").arg(win->processId()); QFile f(pidFile); if (!f.open(QIODevice::ReadOnly)) { qWarning() << Q_FUNC_INFO << "Cannot open cmdline for " << pidFile; continue; } // cmdline contains a \0, so we use constData to truncate that away QByteArray proc = QByteArray(f.readAll().constData()); if (proc != binaryName) continue; win->surface()->raiseRequested(); break; } } <commit_msg>[compositor] don't add overlay windows to WindowModel<commit_after>/*************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Aaron Kennedy <aaron.kennedy@jollamobile.com> ** ** This file is part of lipstick. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QDBusConnection> #include "lipstickcompositorwindow.h" #include "lipstickcompositor.h" #include "windowmodel.h" WindowModel::WindowModel() : m_complete(false) { LipstickCompositor *c = LipstickCompositor::instance(); if (!c) { qWarning("WindowModel: Compositor must be created before WindowModel"); } else { c->m_windowModels.append(this); } QDBusConnection dbus = QDBusConnection::sessionBus(); dbus.registerObject("/WindowModel", this, QDBusConnection::ExportAllSlots); dbus.registerService("org.nemomobile.lipstick"); } WindowModel::~WindowModel() { LipstickCompositor *c = LipstickCompositor::instance(); if (c) c->m_windowModels.removeAll(this); } int WindowModel::itemCount() const { return m_items.count(); } int WindowModel::windowId(int index) const { if (index < 0 || index >= m_items.count()) return 0; return m_items.at(index); } int WindowModel::rowCount(const QModelIndex &) const { return m_items.count(); } QVariant WindowModel::data(const QModelIndex &index, int role) const { int idx = index.row(); if (idx < 0 || idx >= m_items.count()) return QVariant(); LipstickCompositor *c = LipstickCompositor::instance(); if (role == Qt::UserRole + 1) { return m_items.at(idx); } else if (role == Qt::UserRole + 2) { QWaylandSurface *s = c->surfaceForId(m_items.at(idx)); return s?s->processId():0; } else if (role == Qt::UserRole + 3) { LipstickCompositorWindow *w = static_cast<LipstickCompositorWindow *>(c->windowForId(m_items.at(idx))); return w->title(); } else { return QVariant(); } } QHash<int, QByteArray> WindowModel::roleNames() const { QHash<int, QByteArray> roles; roles[Qt::UserRole + 1] = "window"; roles[Qt::UserRole + 2] = "processId"; roles[Qt::UserRole + 3] = "title"; return roles; } void WindowModel::classBegin() { } void WindowModel::componentComplete() { m_complete = true; refresh(); } /*! Reimplement this method to provide custom filtering. */ bool WindowModel::approveWindow(LipstickCompositorWindow *window) { return window->isInProcess() == false && window->category() != QLatin1String("overlay"); } void WindowModel::addItem(int id) { if (!m_complete) return; LipstickCompositor *c = LipstickCompositor::instance(); LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(c->windowForId(id)); if (!approveWindow(window)) return; beginInsertRows(QModelIndex(), m_items.count(), m_items.count()); m_items.append(id); endInsertRows(); emit itemAdded(m_items.count() - 1); emit itemCountChanged(); } void WindowModel::remItem(int id) { if (!m_complete) return; int idx = m_items.indexOf(id); if (idx == -1) return; beginRemoveRows(QModelIndex(), idx, idx); m_items.removeAt(idx); endRemoveRows(); emit itemCountChanged(); } void WindowModel::titleChanged(int id) { if (!m_complete) return; int idx = m_items.indexOf(id); if (idx == -1) return; emit dataChanged(index(idx, 0), index(idx, 0)); } void WindowModel::refresh() { LipstickCompositor *c = LipstickCompositor::instance(); if (!m_complete || !c) return; beginResetModel(); m_items.clear(); for (QHash<int, LipstickCompositorWindow *>::ConstIterator iter = c->m_mappedSurfaces.begin(); iter != c->m_mappedSurfaces.end(); ++iter) { if (approveWindow(iter.value())) m_items.append(iter.key()); } endResetModel(); } // used by mapplauncherd to bring a binary to the front void WindowModel::launchProcess(const QString &binaryName) { LipstickCompositor *c = LipstickCompositor::instance(); if (!m_complete || !c) return; for (QHash<int, LipstickCompositorWindow *>::ConstIterator iter = c->m_mappedSurfaces.begin(); iter != c->m_mappedSurfaces.end(); ++iter) { LipstickCompositorWindow *win = iter.value(); if (!approveWindow(win)) continue; QString pidFile = QString::fromLatin1("/proc/%1/cmdline").arg(win->processId()); QFile f(pidFile); if (!f.open(QIODevice::ReadOnly)) { qWarning() << Q_FUNC_INFO << "Cannot open cmdline for " << pidFile; continue; } // cmdline contains a \0, so we use constData to truncate that away QByteArray proc = QByteArray(f.readAll().constData()); if (proc != binaryName) continue; win->surface()->raiseRequested(); break; } } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ /* this file holds a little stash of stuff that you get from param() that various functions need in the sysapi. If for some reason you want to change your config file stuff, then call sysapi_reconfig() and the sysapi library will use the correct answers. If any function inside of sysapi is called before a reconfig, it preforms one, but only once. This is done to increase performance of the functions in sysapi because they might be called very often, to where a hash table might even be too slow. So if you are writing code and know that some config parameters have changed, then call this function to inform the sysapi of what has happened. -pete 05/07/99 */ #include "condor_common.h" #include "condor_config.h" #include "condor_string.h" #include "sysapi.h" #include "sysapi_externs.h" /* needed by idle_time.C and last_x_event.c */ #ifndef WIN32 StringList *_sysapi_console_devices = NULL; #endif /* this is not configured here, but is global, look in last_x_event.c */ int _sysapi_last_x_event = 0; /* needed by free_fs_blocks.c */ #ifndef WIN32 int _sysapi_reserve_afs_cache = FALSE; #endif int _sysapi_reserve_disk = 0; /* needed by idle_time.C */ #ifndef WIN32 int _sysapi_startd_has_bad_utmp = FALSE; #endif #ifdef LINUX int _sysapi_count_hyperthread_cpus = FALSE; #endif /* needed by everyone, if this is false, then call sysapi_reconfig() */ int _sysapi_config = 0; /* needed by ncpus.c */ int _sysapi_ncpus = 0; int _sysapi_max_ncpus = 0; /* needed by phys_mem.c */ int _sysapi_memory = 0; int _sysapi_reserve_memory = 0; /* needed by ckptpltfrm.c */ char *_sysapi_ckptpltfrm = NULL; /* needed by load_avg.c */ int _sysapi_getload = 0; BEGIN_C_DECLS /* The function that configures the above variables each time it is called. This function is meant to be called outside of the library to configure it */ void sysapi_reconfig(void) { char *tmp = NULL; #ifndef WIN32 /* configuration set up for idle_time.C */ if( _sysapi_console_devices ) { delete( _sysapi_console_devices ); _sysapi_console_devices = NULL; } tmp = param( "CONSOLE_DEVICES" ); if( tmp ) { _sysapi_console_devices = new StringList(); if (_sysapi_console_devices == NULL) { EXCEPT( "Out of memory in sysapi_reconfig()!" ); } _sysapi_console_devices->initializeFromString( tmp ); // if "/dev/" is prepended to any of the device names, strip it // here, since later on we're expecting the bare device name if( _sysapi_console_devices ) { char *devname = NULL; const char* striptxt = "/dev/"; const unsigned int striplen = strlen( striptxt ); _sysapi_console_devices->rewind(); while( (devname = _sysapi_console_devices->next()) ) { if( strncmp( devname, striptxt, striplen ) == 0 && strlen( devname ) > striplen ) { char *tmpname = strnewp( devname ); _sysapi_console_devices->deleteCurrent(); _sysapi_console_devices->insert( tmpname + striplen ); delete[] tmpname; } } } free( tmp ); } _sysapi_startd_has_bad_utmp = param_boolean_int( "STARTD_HAS_BAD_UTMP", FALSE ); /* configuration setup for free_fs_blocks.c */ _sysapi_reserve_afs_cache = param_boolean_int( "RESERVE_AFS_CACHE", FALSE ); #endif /* ! WIN32 */ _sysapi_reserve_disk = param_integer_c( "RESERVED_DISK", 0, INT_MIN, INT_MAX ); _sysapi_reserve_disk *= 1024; /* Parameter is in meg */ _sysapi_ncpus = param_integer_c( "NUM_CPUS", 0, 0, INT_MAX ); _sysapi_max_ncpus = param_integer_c( "MAX_NUM_CPUS", 0, 0, INT_MAX ); if(_sysapi_max_ncpus < 0) { _sysapi_max_ncpus = 0; } _sysapi_memory = param_integer_c( "MEMORY", 0, 0, INT_MAX ); _sysapi_reserve_memory = param_integer_c( "RESERVED_MEMORY", 0, INT_MIN, INT_MAX ); /* _sysapi_ckptpltfrm is either set to NULL, or whatever CHECKPOINT_PLATFORM says in the config file. If set to NULL, then _sysapi_ckptpltfrm will be properly initialized after the first call to sysapi_ckptpltfrm() */ if (_sysapi_ckptpltfrm != NULL) { free(_sysapi_ckptpltfrm); _sysapi_ckptpltfrm = NULL; } tmp = param( "CHECKPOINT_PLATFORM" ); if (tmp != NULL) { _sysapi_ckptpltfrm = strdup(tmp); free(tmp); } _sysapi_getload = param_boolean_int("SYSAPI_GET_LOADAVG",1); #ifdef LINUX /* Should we count hyper threads? */ int _sysapi_count_hyperthread_cpus = param_boolean_int("COUNT_HYPERTHREAD_CPUS", 1); #endif /* tell the library I have configured myself */ _sysapi_config = TRUE; } /* this function is to be called by any and all sysapi functions in sysapi.h */ /* except of course, for sysapi_reconfig() */ void sysapi_internal_reconfig(void) { if (_sysapi_config == FALSE) { sysapi_reconfig(); } } END_C_DECLS <commit_msg>Fixed 7.3.2 bug handling COUNT_HYPERTHREAD_CPUS. It was treated as False in all cases.<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ /* this file holds a little stash of stuff that you get from param() that various functions need in the sysapi. If for some reason you want to change your config file stuff, then call sysapi_reconfig() and the sysapi library will use the correct answers. If any function inside of sysapi is called before a reconfig, it preforms one, but only once. This is done to increase performance of the functions in sysapi because they might be called very often, to where a hash table might even be too slow. So if you are writing code and know that some config parameters have changed, then call this function to inform the sysapi of what has happened. -pete 05/07/99 */ #include "condor_common.h" #include "condor_config.h" #include "condor_string.h" #include "sysapi.h" #include "sysapi_externs.h" /* needed by idle_time.C and last_x_event.c */ #ifndef WIN32 StringList *_sysapi_console_devices = NULL; #endif /* this is not configured here, but is global, look in last_x_event.c */ int _sysapi_last_x_event = 0; /* needed by free_fs_blocks.c */ #ifndef WIN32 int _sysapi_reserve_afs_cache = FALSE; #endif int _sysapi_reserve_disk = 0; /* needed by idle_time.C */ #ifndef WIN32 int _sysapi_startd_has_bad_utmp = FALSE; #endif #ifdef LINUX int _sysapi_count_hyperthread_cpus = FALSE; #endif /* needed by everyone, if this is false, then call sysapi_reconfig() */ int _sysapi_config = 0; /* needed by ncpus.c */ int _sysapi_ncpus = 0; int _sysapi_max_ncpus = 0; /* needed by phys_mem.c */ int _sysapi_memory = 0; int _sysapi_reserve_memory = 0; /* needed by ckptpltfrm.c */ char *_sysapi_ckptpltfrm = NULL; /* needed by load_avg.c */ int _sysapi_getload = 0; BEGIN_C_DECLS /* The function that configures the above variables each time it is called. This function is meant to be called outside of the library to configure it */ void sysapi_reconfig(void) { char *tmp = NULL; #ifndef WIN32 /* configuration set up for idle_time.C */ if( _sysapi_console_devices ) { delete( _sysapi_console_devices ); _sysapi_console_devices = NULL; } tmp = param( "CONSOLE_DEVICES" ); if( tmp ) { _sysapi_console_devices = new StringList(); if (_sysapi_console_devices == NULL) { EXCEPT( "Out of memory in sysapi_reconfig()!" ); } _sysapi_console_devices->initializeFromString( tmp ); // if "/dev/" is prepended to any of the device names, strip it // here, since later on we're expecting the bare device name if( _sysapi_console_devices ) { char *devname = NULL; const char* striptxt = "/dev/"; const unsigned int striplen = strlen( striptxt ); _sysapi_console_devices->rewind(); while( (devname = _sysapi_console_devices->next()) ) { if( strncmp( devname, striptxt, striplen ) == 0 && strlen( devname ) > striplen ) { char *tmpname = strnewp( devname ); _sysapi_console_devices->deleteCurrent(); _sysapi_console_devices->insert( tmpname + striplen ); delete[] tmpname; } } } free( tmp ); } _sysapi_startd_has_bad_utmp = param_boolean_int( "STARTD_HAS_BAD_UTMP", FALSE ); /* configuration setup for free_fs_blocks.c */ _sysapi_reserve_afs_cache = param_boolean_int( "RESERVE_AFS_CACHE", FALSE ); #endif /* ! WIN32 */ _sysapi_reserve_disk = param_integer_c( "RESERVED_DISK", 0, INT_MIN, INT_MAX ); _sysapi_reserve_disk *= 1024; /* Parameter is in meg */ _sysapi_ncpus = param_integer_c( "NUM_CPUS", 0, 0, INT_MAX ); _sysapi_max_ncpus = param_integer_c( "MAX_NUM_CPUS", 0, 0, INT_MAX ); if(_sysapi_max_ncpus < 0) { _sysapi_max_ncpus = 0; } _sysapi_memory = param_integer_c( "MEMORY", 0, 0, INT_MAX ); _sysapi_reserve_memory = param_integer_c( "RESERVED_MEMORY", 0, INT_MIN, INT_MAX ); /* _sysapi_ckptpltfrm is either set to NULL, or whatever CHECKPOINT_PLATFORM says in the config file. If set to NULL, then _sysapi_ckptpltfrm will be properly initialized after the first call to sysapi_ckptpltfrm() */ if (_sysapi_ckptpltfrm != NULL) { free(_sysapi_ckptpltfrm); _sysapi_ckptpltfrm = NULL; } tmp = param( "CHECKPOINT_PLATFORM" ); if (tmp != NULL) { _sysapi_ckptpltfrm = strdup(tmp); free(tmp); } _sysapi_getload = param_boolean_int("SYSAPI_GET_LOADAVG",1); #ifdef LINUX /* Should we count hyper threads? */ _sysapi_count_hyperthread_cpus = param_boolean_int("COUNT_HYPERTHREAD_CPUS", 1); #endif /* tell the library I have configured myself */ _sysapi_config = TRUE; } /* this function is to be called by any and all sysapi functions in sysapi.h */ /* except of course, for sysapi_reconfig() */ void sysapi_internal_reconfig(void) { if (_sysapi_config == FALSE) { sysapi_reconfig(); } } END_C_DECLS <|endoftext|>
<commit_before>/*++ Copyright (c) 2006 Microsoft Corporation Module Name: trace.cpp Abstract: Trace message support. Author: Leonardo de Moura (leonardo) 2006-09-13. Revision History: --*/ #include"trace.h" #include"str_hashtable.h" #ifdef _TRACE std::ofstream tout(".z3-trace"); #endif bool g_enable_all_trace_tags = false; str_hashtable* g_enabled_trace_tags = 0; static str_hashtable& get_enabled_trace_tags() { if (!g_enabled_trace_tags) { g_enabled_trace_tags = alloc(str_hashtable); } return *g_enabled_trace_tags; } void finalize_trace() { dealloc(g_enabled_trace_tags); g_enabled_trace_tags = 0; } void enable_trace(const char * tag) { get_enabled_trace_tags().insert(const_cast<char *>(tag)); } void enable_all_trace(bool flag) { g_enable_all_trace_tags = flag; } void disable_trace(const char * tag) { get_enabled_trace_tags().erase(const_cast<char *>(tag)); } bool is_trace_enabled(const char * tag) { return g_enable_all_trace_tags || (g_enabled_trace_tags && get_enabled_trace_tags().contains(const_cast<char *>(tag))); } void close_trace() { #ifdef _TRACE tout.close(); #endif } void open_trace() { #ifdef _TRACE tout.open(".z3-trace"); #endif } <commit_msg>fix build on CentOS<commit_after>/*++ Copyright (c) 2006 Microsoft Corporation Module Name: trace.cpp Abstract: Trace message support. Author: Leonardo de Moura (leonardo) 2006-09-13. Revision History: --*/ #include"trace.h" #include"str_hashtable.h" #ifdef _TRACE std::ofstream tout(".z3-trace"); #endif static bool g_enable_all_trace_tags = false; static str_hashtable* g_enabled_trace_tags = 0; static str_hashtable& get_enabled_trace_tags() { if (!g_enabled_trace_tags) { g_enabled_trace_tags = alloc(str_hashtable); } return *g_enabled_trace_tags; } void finalize_trace() { dealloc(g_enabled_trace_tags); g_enabled_trace_tags = 0; } void enable_trace(const char * tag) { get_enabled_trace_tags().insert(const_cast<char *>(tag)); } void enable_all_trace(bool flag) { g_enable_all_trace_tags = flag; } void disable_trace(const char * tag) { get_enabled_trace_tags().erase(const_cast<char *>(tag)); } bool is_trace_enabled(const char * tag) { return g_enable_all_trace_tags || (g_enabled_trace_tags && get_enabled_trace_tags().contains(const_cast<char *>(tag))); } void close_trace() { #ifdef _TRACE tout.close(); #endif } void open_trace() { #ifdef _TRACE tout.open(".z3-trace"); #endif } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/util/buildinfo.h> #include <inviwo/core/util/assertion.h> #include <inviwo/core/util/filesystem.h> #include <fstream> #include <sstream> #include <locale> namespace inviwo { namespace util { // helper struct to define arbitrary separator characters in a locale // usage: // std::stringstream stream; // stream.imbue(std::locale(stream.getloc(), new CsvWhitespace)); struct IniSeparator : std::ctype<char> { static const mask* makeTable() { // copy table of C locale static std::vector<mask> m(classic_table(), classic_table() + table_size); m[' '] &= ~space; // remove space as whitespace m['='] |= space; return &m[0]; } IniSeparator(std::size_t refs = 0) : ctype(makeTable(), false, refs) {} }; BuildInfo getBuildInfo() { auto dir = filesystem::getExecutablePath() + "/inviwo_buildinfo.ini"; std::ifstream in(dir.c_str(), std::ios::in); if (!in.is_open()) { return {}; } BuildInfo buildInfo; std::istringstream iss; iss.imbue(std::locale(iss.getloc(), new IniSeparator())); enum class Section { Unknown, Date, Hashes }; std::string line; Section currentSection = Section::Unknown; while (std::getline(in, line)) { line = trim(line); // ignore comment, i.e. line starts with ';' if (line.empty() || line[0] == ';') { continue; } if (line == "[date]") { currentSection = Section::Date; } else if (line == "[hashes]") { currentSection = Section::Hashes; } else if (line[0] == '[') { currentSection = Section::Unknown; } else { // read in key value pairs iss.clear(); iss.str(line); std::string key; std::string value; if (!(iss >> key >> value)) { // invalid key-value pair, ignore it continue; } switch (currentSection) { case Section::Date: { int valuei = std::stoi(value); if (key == "year") { buildInfo.year = valuei; } else if (key == "month") { buildInfo.month = valuei; } else if (key == "day") { buildInfo.day = valuei; } else if (key == "hour") { buildInfo.hour = valuei; } else if (key == "minute") { buildInfo.minute = valuei; } else if (key == "second") { buildInfo.second = valuei; } break; } case Section::Hashes: buildInfo.githashes.push_back({ key, value }); break; case Section::Unknown: default: break; } } } return buildInfo; } } // namespace util } // namespace inviwo <commit_msg>Core: buildinfo fix<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/util/buildinfo.h> #include <inviwo/core/util/assertion.h> #include <inviwo/core/util/filesystem.h> #include <fstream> #include <sstream> #include <locale> namespace inviwo { namespace util { // helper struct to define arbitrary separator characters in a locale // usage: // std::stringstream stream; // stream.imbue(std::locale(stream.getloc(), new CsvWhitespace)); struct IniSeparator : std::ctype<char> { static const mask* makeTable() { // copy table of C locale static std::vector<mask> m(classic_table(), classic_table() + table_size); m[' '] &= ~space; // remove space as whitespace m['='] |= space; return &m[0]; } IniSeparator(std::size_t refs = 0) : ctype(makeTable(), false, refs) {} }; BuildInfo getBuildInfo() { auto dir = filesystem::getFileDirectory(filesystem::getExecutablePath()) + "/inviwo_buildinfo.ini"; LogInfoCustom("BUILDINFO", dir); std::ifstream in(dir.c_str(), std::ios::in); if (!in.is_open()) { return {}; } BuildInfo buildInfo; std::istringstream iss; iss.imbue(std::locale(iss.getloc(), new IniSeparator())); enum class Section { Unknown, Date, Hashes }; std::string line; Section currentSection = Section::Unknown; while (std::getline(in, line)) { line = trim(line); // ignore comment, i.e. line starts with ';' if (line.empty() || line[0] == ';') { continue; } if (line == "[date]") { currentSection = Section::Date; } else if (line == "[hashes]") { currentSection = Section::Hashes; } else if (line[0] == '[') { currentSection = Section::Unknown; } else { // read in key value pairs iss.clear(); iss.str(line); std::string key; std::string value; if (!(iss >> key >> value)) { // invalid key-value pair, ignore it continue; } switch (currentSection) { case Section::Date: { int valuei = std::stoi(value); if (key == "year") { buildInfo.year = valuei; } else if (key == "month") { buildInfo.month = valuei; } else if (key == "day") { buildInfo.day = valuei; } else if (key == "hour") { buildInfo.hour = valuei; } else if (key == "minute") { buildInfo.minute = valuei; } else if (key == "second") { buildInfo.second = valuei; } break; } case Section::Hashes: buildInfo.githashes.push_back({ key, value }); break; case Section::Unknown: default: break; } } } return buildInfo; } } // namespace util } // namespace inviwo <|endoftext|>
<commit_before><commit_msg>Delete rgb_send.cpp<commit_after><|endoftext|>
<commit_before>// // XorLinkedList.h // FunnyCoding // // Created by Xplorld on 2016/3/27. // Copyright © 2016年 xplorld. All rights reserved. // #ifndef XorLinkedList_hpp #define XorLinkedList_hpp #include <utility> #include <iterator> #include <cstdint> #include <cassert> #include <tuple> #include <type_traits> #include "is_container_SFINAE.h" template <typename T> class XorLinkedList { private: template <bool is_const> class iterator_; template <bool is_const> class reverse_iterator_; public: typedef iterator_<false> iterator; typedef iterator_<true> const_iterator; typedef reverse_iterator_<false> reverse_iterator; typedef reverse_iterator_<true> const_reverse_iterator; private: class node { friend XorLinkedList; friend iterator; uintptr_t xorptr; T value; node(T &&v) noexcept(std::is_nothrow_move_constructible<T>::value) : xorptr(0),value(std::move(v)){} node(const T &v) noexcept(std::is_nothrow_constructible<T, const T &>::value) : xorptr(0),value(v){} //copy template < typename input_iterator> node(const input_iterator v) noexcept(std::is_nothrow_constructible<T, const input_iterator>::value) : xorptr(0),value(*v){} //copy, not move node* join(T &&v); node* join(const T& v); template < typename input_iterator> node* join(const input_iterator v); template < typename input_iterator> static std::tuple<node *, node *,size_t> newList(input_iterator begin,input_iterator end); template < typename input_iterator> static std::tuple<node *, node *,size_t> newList(std::move_iterator<input_iterator> begin,std::move_iterator<input_iterator> end); //do not declare as method, since `curr` may be nullptr static node *another(node* curr, node* one) noexcept; //->another ~node() ; }; //Wrapper so that List can put on the stack //and befriend RAII node *head = nullptr; //last `Node` that is not nullptr node *tail = nullptr; size_t size_ = 0; template <bool is_const = false> class iterator_ : public std::iterator <std::bidirectional_iterator_tag,typename std::conditional<is_const, const T, T>::type> { friend iterator_<true>; friend iterator_<false>; //node is still non-const node *prev = nullptr; node *curr = nullptr; public: iterator_(node *prev, node *curr) : prev(prev),curr(curr) {} //only allow non-const to const iterator_(const iterator_<false> &copyFrom) : prev(copyFrom.prev),curr(copyFrom.curr) {} typename iterator_::reference operator*() {assert(curr != nullptr && "dereference null iterator!"); return curr->value; } typename iterator_::pointer operator->() {return std::addressof(operator*());} iterator_ &operator++() noexcept ; //++i iterator_ operator++ ( int ) noexcept; //i++ iterator_ &operator--() noexcept ; //--i iterator_ operator-- ( int ) noexcept; //i-- void swap(iterator_ & other) noexcept; explicit operator bool() const noexcept {return prev == nullptr && curr == nullptr;} bool operator == (const iterator_& rhs) const {return curr == rhs.curr && prev == rhs.prev;} bool operator != (const iterator_& rhs) const {return curr != rhs.curr || prev != rhs.prev;} }; template<bool is_const = false> class reverse_iterator_ : public std::reverse_iterator<iterator_<is_const>> { public: friend reverse_iterator_<true>; reverse_iterator_(node *curr, node *next): std::reverse_iterator<iterator_<is_const>> ( iterator_<is_const>(curr, next) ) {} reverse_iterator_(const reverse_iterator_<false> &copyFrom): std::reverse_iterator<iterator_<is_const>> ( iterator_<is_const>(copyFrom.current) ) {} explicit operator bool() const noexcept { return (bool)this->current; } }; public: XorLinkedList() : head(nullptr), tail(nullptr), size_(0) {} XorLinkedList(const T* v) : head(new node(v)), tail(head), size_(1) {} XorLinkedList(const T& v) : head(new node(v)), tail(head), size_(1) {} XorLinkedList(T&& v) : head(new node(std::move(v))), tail(head), size_(1) {} XorLinkedList(std::initializer_list<T> array) : XorLinkedList(array.begin(),array.end()) {} template <typename Container, class = typename std::enable_if<is_container<Container>::value>::type> explicit XorLinkedList(Container container) : XorLinkedList(std::make_move_iterator(container.begin()), std::make_move_iterator(container.end())) {} XorLinkedList(T *array,size_t count) : XorLinkedList(array,array+count) {} template < typename input_iterator> XorLinkedList(input_iterator begin,input_iterator end); //move constructor XorLinkedList(XorLinkedList&& another); //copy XorLinkedList(XorLinkedList const &another) : XorLinkedList(another.cbegin(),another.cend()) {} void append(const T &v); //no need to delete tail, it will be deleted by Node deconstructer recursively //head is nullptr if empty; OK to delete ~XorLinkedList() {delete head;} size_t size() {return size_;} iterator begin() { return iterator(nullptr, head);} iterator end() { return iterator(tail, nullptr);} const_iterator cbegin() const { return const_iterator(nullptr, head);} const_iterator cend() const { return const_iterator(tail, nullptr);} reverse_iterator rbegin() { return reverse_iterator(tail, nullptr);} reverse_iterator rend() { return reverse_iterator(nullptr, head);} const_reverse_iterator crbegin() const { return const_reverse_iterator(tail, nullptr);} const_reverse_iterator crend() const { return const_reverse_iterator(nullptr, head);} }; #define PtrToInt(p) reinterpret_cast<uintptr_t>((void *)(p)) #define IntToPtr(i) reinterpret_cast<node *>((i)) template <typename T> template <typename input_iterator> typename std::tuple< typename XorLinkedList<T>::node *, typename XorLinkedList<T>::node *, size_t> XorLinkedList<T>::node::newList(input_iterator begin,input_iterator end) { node *list = nullptr,*tail = nullptr; size_t size = 0; try { assert(begin != end && "input feed is empty"); list = new node(std::addressof(*begin)); //cast iter to pointer ++begin; ++size; tail = list; while (begin != end){ tail = tail->join(std::addressof(*begin)); ++begin; ++size; } } catch(...) { delete list; throw; } return std::make_tuple(list, tail,size); } template <typename T> template < typename input_iterator> typename std::tuple< typename XorLinkedList<T>::node *, typename XorLinkedList<T>::node *, size_t> XorLinkedList<T>::node::newList(std::move_iterator<input_iterator> begin,std::move_iterator<input_iterator> end) { node *list = nullptr,*tail = nullptr; size_t size = 0; try { assert(begin != end && "input feed is empty"); list = new node(std::move(begin)); ++begin; ++size; tail = list; while (begin != end){ tail = tail->join(std::move(begin)); ++begin; ++size; } } catch(...) { delete list; throw; } return std::make_tuple(list, tail,size); } template <typename T> typename XorLinkedList<T>::node * XorLinkedList<T>::node::another(node*curr, node* one) noexcept { if (curr == nullptr) { return nullptr; } return IntToPtr(PtrToInt(one) ^ curr->xorptr); } template <typename T> XorLinkedList<T>::node::~node() { auto B = another(this,nullptr); if (B) { //A -> B -> C //I am head A! auto C = another(B,this); B->xorptr = PtrToInt(C); delete B; } // else { //I am tail //do nothing // } } template <typename T> typename XorLinkedList<T>::node * XorLinkedList<T>::node::join(const T &v) { //A->B, C. //B.p = A, C.p = 0 node *endNode = this; node *newNode = new node(std::move(v)); endNode->xorptr = endNode->xorptr ^ PtrToInt((void *)newNode); newNode->xorptr = PtrToInt((void *)endNode); //A->B->C //B.p = A^C, C.p = B^0 = B return newNode; } template <typename T> template < typename input_iterator> typename XorLinkedList<T>::node * XorLinkedList<T>::node::join(const input_iterator v) { //A->B, C. //B.p = A, C.p = 0 node *endNode = this; node *newNode = new node(v); endNode->xorptr = endNode->xorptr ^ PtrToInt((void *)newNode); newNode->xorptr = PtrToInt((void *)endNode); //A->B->C //B.p = A^C, C.p = B^0 = B return newNode; } template <typename T> typename XorLinkedList<T>::node * XorLinkedList<T>::node::join(T&& v) { //A->B, C. //B.p = A, C.p = 0 node *endNode = this; node *newNode = new node(std::move(v)); endNode->xorptr = endNode->xorptr ^ PtrToInt((void *)newNode); newNode->xorptr = PtrToInt((void *)endNode); //A->B->C //B.p = A^C, C.p = B^0 = B return newNode; } #undef PtrToInt #undef IntToPtr template <typename T> template <bool is_const> typename XorLinkedList<T>::template iterator_<is_const> & XorLinkedList<T>::iterator_<is_const>::operator++() noexcept{ node *nextNode = node::another(curr,prev); prev = curr; curr = nextNode; return *this; } template <typename T> template <bool is_const> typename XorLinkedList<T>::template iterator_<is_const> XorLinkedList<T>::iterator_<is_const>::operator++( int ) noexcept{ iterator_ nowIter = iterator_(prev,curr); operator++(); return nowIter; } template <typename T> template <bool is_const> typename XorLinkedList<T>::template iterator_<is_const> & XorLinkedList<T>::iterator_<is_const>::operator--() noexcept { node *prevNode = node::another(prev,curr); curr = prev; prev = prevNode; return *this; } template <typename T> template <bool is_const> typename XorLinkedList<T>::template iterator_<is_const> XorLinkedList<T>::iterator_<is_const>::operator-- ( int ) noexcept { iterator_ nowIter = iterator_(prev,curr); operator--(); return nowIter; } template <typename T> template <bool is_const> void XorLinkedList<T>::iterator_<is_const>::swap(XorLinkedList<T>::iterator_<is_const> &other) noexcept { using std::swap; swap(prev, other.prev); swap(curr, other.curr); } template <typename T> template <typename input_iterator> XorLinkedList<T>::XorLinkedList(input_iterator begin,input_iterator end) { auto tuple = node::newList(begin,end); head = std::get<0>(tuple); tail = std::get<1>(tuple); size_ = std::get<2>(tuple); } template <typename T> XorLinkedList<T>::XorLinkedList(XorLinkedList&& another) { head = another.head; tail = another.tail; size_ = another.size_; another.head = nullptr; another.tail = nullptr; another.size_ = 0; } template <typename T> void XorLinkedList<T>::append(const T &v){ if (tail) { tail = tail->join(std::addressof(v)); } else { //empty linked list head = new node(std::addressof(v)); tail = head; } size_++; } #endif /* XorLinkedList_hpp */ <commit_msg>reorder and reindent typedefs and methods<commit_after>// // XorLinkedList.h // FunnyCoding // // Created by Xplorld on 2016/3/27. // Copyright © 2016年 xplorld. All rights reserved. // #ifndef XorLinkedList_hpp #define XorLinkedList_hpp #include <utility> #include <iterator> #include <cstdint> #include <cassert> #include <tuple> #include <type_traits> #include "is_container_SFINAE.h" template <typename T> class XorLinkedList { class node { friend XorLinkedList; uintptr_t xorptr; T value; node(T &&v) noexcept(std::is_nothrow_move_constructible<T>::value) : xorptr(0),value(std::move(v)){} node(const T &v) noexcept(std::is_nothrow_constructible<T, const T &>::value) : xorptr(0),value(v){} //copy template < typename input_iterator> node(const input_iterator v) noexcept(std::is_nothrow_constructible<T, const input_iterator>::value) : xorptr(0),value(*v){} //copy, not move node* join(T &&v); node* join(const T& v); template < typename input_iterator> node* join(const input_iterator v); template < typename input_iterator> static std::tuple<node *, node *,size_t> newList(input_iterator begin,input_iterator end); template < typename input_iterator> static std::tuple<node *, node *,size_t> newList(std::move_iterator<input_iterator> begin,std::move_iterator<input_iterator> end); //do not declare as method, since `curr` may be nullptr static node *another(node* curr, node* one) noexcept; //->another ~node() ; }; //Wrapper so that List can put on the stack //and befriend RAII node *head = nullptr; //last `Node` that is not nullptr node *tail = nullptr; size_t size_ = 0; template <bool is_const = false> class iterator_ : public std::iterator <std::bidirectional_iterator_tag,typename std::conditional<is_const, const T, T>::type> { friend iterator_<true>; //node is still non-const node *prev = nullptr; node *curr = nullptr; public: iterator_(node *prev, node *curr) : prev(prev),curr(curr) {} //only allow non-const to const iterator_(const iterator_<false> &copyFrom) : prev(copyFrom.prev),curr(copyFrom.curr) {} typename iterator_::reference operator*() {assert(curr != nullptr && "dereference null iterator!"); return curr->value; } typename iterator_::pointer operator->() {return std::addressof(operator*());} iterator_ &operator++() noexcept ; //++i iterator_ operator++ ( int ) noexcept; //i++ iterator_ &operator--() noexcept ; //--i iterator_ operator-- ( int ) noexcept; //i-- void swap(iterator_ & other) noexcept; explicit operator bool() const noexcept {return prev == nullptr && curr == nullptr;} bool operator == (const iterator_& rhs) const {return curr == rhs.curr && prev == rhs.prev;} bool operator != (const iterator_& rhs) const {return curr != rhs.curr || prev != rhs.prev;} }; template<bool is_const = false> class reverse_iterator_ : public std::reverse_iterator<iterator_<is_const>> { public: friend reverse_iterator_<true>; reverse_iterator_(node *curr, node *next): std::reverse_iterator<iterator_<is_const>> ( iterator_<is_const>(curr, next) ) {} reverse_iterator_(const reverse_iterator_<false> &copyFrom): std::reverse_iterator<iterator_<is_const>> ( iterator_<is_const>(copyFrom.current) ) {} explicit operator bool() const noexcept { return (bool)this->current; } }; public: XorLinkedList() : head(nullptr), tail(nullptr), size_(0) {} XorLinkedList(const T* v) : head(new node(v)), tail(head), size_(1) {} XorLinkedList(const T& v) : head(new node(v)), tail(head), size_(1) {} XorLinkedList(T&& v) : head(new node(std::move(v))), tail(head), size_(1) {} XorLinkedList(std::initializer_list<T> array) : XorLinkedList(array.begin(),array.end()) {} template <typename Container, class = typename std::enable_if<is_container<Container>::value>::type> explicit XorLinkedList(Container container) : XorLinkedList(std::make_move_iterator(container.begin()), std::make_move_iterator(container.end())) {} XorLinkedList(T *array,size_t count) : XorLinkedList(array,array+count) {} template < typename input_iterator> XorLinkedList(input_iterator begin,input_iterator end); //move constructor XorLinkedList(XorLinkedList&& another); //copy XorLinkedList(XorLinkedList const &another) : XorLinkedList(another.cbegin(),another.cend()) {} void append(const T &v); //no need to delete tail, it will be deleted by Node deconstructer recursively //head is nullptr if empty; OK to delete ~XorLinkedList() {delete head;} size_t size() {return size_;} typedef iterator_<false> iterator; typedef iterator_<true> const_iterator; typedef reverse_iterator_<false> reverse_iterator; typedef reverse_iterator_<true> const_reverse_iterator; iterator begin() { return iterator(nullptr, head);} iterator end() { return iterator(tail, nullptr);} const_iterator cbegin() const { return const_iterator(nullptr, head);} const_iterator cend() const { return const_iterator(tail, nullptr);} reverse_iterator rbegin() { return reverse_iterator(tail, nullptr);} reverse_iterator rend() { return reverse_iterator(nullptr, head);} const_reverse_iterator crbegin() const { return const_reverse_iterator(tail, nullptr);} const_reverse_iterator crend() const { return const_reverse_iterator(nullptr, head);} }; #define PtrToInt(p) reinterpret_cast<uintptr_t>((void *)(p)) #define IntToPtr(i) reinterpret_cast<node *>((i)) template <typename T> template <typename input_iterator> typename std::tuple< typename XorLinkedList<T>::node *, typename XorLinkedList<T>::node *, size_t> XorLinkedList<T>::node::newList(input_iterator begin,input_iterator end) { node *list = nullptr,*tail = nullptr; size_t size = 0; try { assert(begin != end && "input feed is empty"); list = new node(std::addressof(*begin)); //cast iter to pointer ++begin; ++size; tail = list; while (begin != end){ tail = tail->join(std::addressof(*begin)); ++begin; ++size; } } catch(...) { delete list; throw; } return std::make_tuple(list, tail,size); } template <typename T> template < typename input_iterator> typename std::tuple< typename XorLinkedList<T>::node *, typename XorLinkedList<T>::node *, size_t> XorLinkedList<T>::node::newList(std::move_iterator<input_iterator> begin,std::move_iterator<input_iterator> end) { node *list = nullptr,*tail = nullptr; size_t size = 0; try { assert(begin != end && "input feed is empty"); list = new node(std::move(begin)); ++begin; ++size; tail = list; while (begin != end){ tail = tail->join(std::move(begin)); ++begin; ++size; } } catch(...) { delete list; throw; } return std::make_tuple(list, tail,size); } template <typename T> typename XorLinkedList<T>::node * XorLinkedList<T>::node::another(node*curr, node* one) noexcept { if (curr == nullptr) { return nullptr; } return IntToPtr(PtrToInt(one) ^ curr->xorptr); } template <typename T> XorLinkedList<T>::node::~node() { auto B = another(this,nullptr); if (B) { //A -> B -> C //I am head A! auto C = another(B,this); B->xorptr = PtrToInt(C); delete B; } // else { //I am tail //do nothing // } } template <typename T> typename XorLinkedList<T>::node * XorLinkedList<T>::node::join(const T &v) { //A->B, C. //B.p = A, C.p = 0 node *endNode = this; node *newNode = new node(std::move(v)); endNode->xorptr = endNode->xorptr ^ PtrToInt((void *)newNode); newNode->xorptr = PtrToInt((void *)endNode); //A->B->C //B.p = A^C, C.p = B^0 = B return newNode; } template <typename T> template < typename input_iterator> typename XorLinkedList<T>::node * XorLinkedList<T>::node::join(const input_iterator v) { //A->B, C. //B.p = A, C.p = 0 node *endNode = this; node *newNode = new node(v); endNode->xorptr = endNode->xorptr ^ PtrToInt((void *)newNode); newNode->xorptr = PtrToInt((void *)endNode); //A->B->C //B.p = A^C, C.p = B^0 = B return newNode; } template <typename T> typename XorLinkedList<T>::node * XorLinkedList<T>::node::join(T&& v) { //A->B, C. //B.p = A, C.p = 0 node *endNode = this; node *newNode = new node(std::move(v)); endNode->xorptr = endNode->xorptr ^ PtrToInt((void *)newNode); newNode->xorptr = PtrToInt((void *)endNode); //A->B->C //B.p = A^C, C.p = B^0 = B return newNode; } #undef PtrToInt #undef IntToPtr template <typename T> template <bool is_const> typename XorLinkedList<T>::template iterator_<is_const> & XorLinkedList<T>::iterator_<is_const>::operator++() noexcept{ node *nextNode = node::another(curr,prev); prev = curr; curr = nextNode; return *this; } template <typename T> template <bool is_const> typename XorLinkedList<T>::template iterator_<is_const> XorLinkedList<T>::iterator_<is_const>::operator++( int ) noexcept{ iterator_ nowIter = iterator_(prev,curr); operator++(); return nowIter; } template <typename T> template <bool is_const> typename XorLinkedList<T>::template iterator_<is_const> & XorLinkedList<T>::iterator_<is_const>::operator--() noexcept { node *prevNode = node::another(prev,curr); curr = prev; prev = prevNode; return *this; } template <typename T> template <bool is_const> typename XorLinkedList<T>::template iterator_<is_const> XorLinkedList<T>::iterator_<is_const>::operator-- ( int ) noexcept { iterator_ nowIter = iterator_(prev,curr); operator--(); return nowIter; } template <typename T> template <bool is_const> void XorLinkedList<T>::iterator_<is_const>::swap(XorLinkedList<T>::iterator_<is_const> &other) noexcept { using std::swap; swap(prev, other.prev); swap(curr, other.curr); } template <typename T> template <typename input_iterator> XorLinkedList<T>::XorLinkedList(input_iterator begin,input_iterator end) { auto tuple = node::newList(begin,end); head = std::get<0>(tuple); tail = std::get<1>(tuple); size_ = std::get<2>(tuple); } template <typename T> XorLinkedList<T>::XorLinkedList(XorLinkedList&& another) { head = another.head; tail = another.tail; size_ = another.size_; another.head = nullptr; another.tail = nullptr; another.size_ = 0; } template <typename T> void XorLinkedList<T>::append(const T &v){ if (tail) { tail = tail->join(std::addressof(v)); } else { //empty linked list head = new node(std::addressof(v)); tail = head; } size_++; } #endif /* XorLinkedList_hpp */ <|endoftext|>
<commit_before>/* Copyright (c) 2017, EPL-Vizards * 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 the EPL-Vizards 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 EPL-Vizards 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. */ /*! * \file PluginsWindows.cpp */ #include "PluginsWindow.hpp" #include "MainWindow.hpp" #include "ui_pluginswindow.h" #include <QCloseEvent> using namespace EPL_Viz; PluginsWindow *PluginsWindow::create(MainWindow *mw) { if (instance) { // The window already exists, focus it QApplication::setActiveWindow(instance); return nullptr; } else { // The window needs to be created instance = new PluginsWindow(mw); return instance; } } PluginsWindow::PluginsWindow(MainWindow *mw) : QMainWindow(mw), ui(new Ui::PluginsWindow) { ui->setupUi(this); setAttribute(Qt::WA_QuitOnClose); // Quit the application if this is the last window connect(this, SIGNAL(cleanUp()), ui->editor, SLOT(cleanUp())); QString pluginPath = QString::fromStdString(mw->getSettingsWin()->getConfig().pythonPluginsDir); QDir pluginFolder = QDir(pluginPath); if (pluginFolder.exists()) { // Load plugins in the plugin folder QStringListIterator plugins(pluginFolder.entryList(QDir::Files)); // Open plugins in the plugin folder while (plugins.hasNext()) { emit fileOpened(QUrl::fromLocalFile(pluginPath + "/" + plugins.next())); } } } PluginsWindow::~PluginsWindow() { instance = nullptr; delete ui; } PluginEditorWidget *PluginsWindow::getEditor() { return ui->editor; } void PluginsWindow::closeEvent(QCloseEvent *event) { emit cleanUp(); event->accept(); // The application will now quit if this is the last window delete this; // Delete this window } void PluginsWindow::open() { QUrl file = QFileDialog::getOpenFileUrl(0, "Open Python file", QString(), "Python files (*.py);;All Files (*)"); if (file == QUrl()) return; emit fileOpened(file); } void PluginsWindow::closeFile() { QListWidgetItem *item = ui->pluginList->currentItem(); if (item) { QString name = item->text(); if (name.endsWith('*')) name.chop(1); ui->editor->closeDocument(name); delete ui->pluginList->takeItem(ui->pluginList->row(item)); } } PluginsWindow *PluginsWindow::instance; <commit_msg>Added default path for appimage python samples<commit_after>/* Copyright (c) 2017, EPL-Vizards * 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 the EPL-Vizards 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 EPL-Vizards 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. */ /*! * \file PluginsWindows.cpp */ #include "defines.hpp" #include "PluginsWindow.hpp" #include "MainWindow.hpp" #include "ui_pluginswindow.h" #include <QCloseEvent> using namespace EPL_Viz; using namespace EPL_DataCollect::constants; PluginsWindow *PluginsWindow::create(MainWindow *mw) { if (instance) { // The window already exists, focus it QApplication::setActiveWindow(instance); return nullptr; } else { // The window needs to be created instance = new PluginsWindow(mw); return instance; } } PluginsWindow::PluginsWindow(MainWindow *mw) : QMainWindow(mw), ui(new Ui::PluginsWindow) { ui->setupUi(this); setAttribute(Qt::WA_QuitOnClose); // Quit the application if this is the last window connect(this, SIGNAL(cleanUp()), ui->editor, SLOT(cleanUp())); QString pluginPath = QString::fromStdString(mw->getSettingsWin()->getConfig().pythonPluginsDir); QDir pluginFolder = QDir(pluginPath); if (pluginFolder.exists()) { // Load plugins in the plugin folder QStringListIterator plugins(pluginFolder.entryList(QDir::Files)); // Open plugins in the plugin folder while (plugins.hasNext()) { emit fileOpened(QUrl::fromLocalFile(pluginPath + "/" + plugins.next())); } } } PluginsWindow::~PluginsWindow() { instance = nullptr; delete ui; } PluginEditorWidget *PluginsWindow::getEditor() { return ui->editor; } void PluginsWindow::closeEvent(QCloseEvent *event) { emit cleanUp(); event->accept(); // The application will now quit if this is the last window delete this; // Delete this window } void PluginsWindow::open() { char * appImageDir = getenv("APPDIR"); QString defaultPath = QString(EPL_DC_INSTALL_PREFIX.c_str()) + "/share/eplViz/plugins/samples"; if (appImageDir) { defaultPath = QString(appImageDir) + "/usr/share/eplViz/plugins/samples"; } QUrl file = QFileDialog::getOpenFileUrl( 0, "Open Python file", QUrl::fromLocalFile(defaultPath), "Python files (*.py);;All Files (*)"); if (file == QUrl()) return; emit fileOpened(file); } void PluginsWindow::closeFile() { QListWidgetItem *item = ui->pluginList->currentItem(); if (item) { QString name = item->text(); if (name.endsWith('*')) name.chop(1); ui->editor->closeDocument(name); delete ui->pluginList->takeItem(ui->pluginList->row(item)); } } PluginsWindow *PluginsWindow::instance; <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the QtMediaHub project on http://www.gitorious.org. Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Nokia Corporation (qt-info@nokia.com)** You may use this file under the terms of the BSD license as follows: "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 Nokia Corporation and its Subsidiary(-ies) 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 "playlist.h" #include <QList> #include <QMetaEnum> #include <QModelIndex> //#define PLAYLIST_DEBUG Playlist::Playlist(QObject *parent) : QAbstractListModel(parent) , m_playMode(Normal) { QHash<int, QByteArray> roleNames = QAbstractListModel::roleNames(); roleNames[Qt::DisplayRole] = "display"; roleNames[PreviewUrlRole] = "previewUrl"; roleNames[FilePathRole] = "filePath"; roleNames[FileNameRole] = "fileName"; roleNames[FileUrlRole] = "fileUrl"; roleNames[MediaInfoTypeRole] = "type"; roleNames[FileSizeRole] = "fileSize"; roleNames[FileDateTimeRole] = "fileDateTime"; roleNames[MediaInfoRole] = "mediaInfo"; setRoleNames(roleNames); } Playlist::~Playlist() { } QVariant Playlist::data(const QModelIndex &index, int role) const { QVariant rv; if (!index.isValid()) return rv; if (0 <= index.row() && index.row() < content.size()) { MediaInfo *info = content.at(index.row()); if (role == Qt::DisplayRole || role == FileNameRole) return info->name; else if (role == PreviewUrlRole) { int idx = MediaModel::staticMetaObject.indexOfEnumerator("MediaType"); QMetaEnum e = MediaModel::staticMetaObject.enumerator(idx); QString urlBase = "image://" + QString::fromLatin1(e.valueToKey(info->type)).toLower() + "model"; return QUrl(urlBase + info->thumbnail); } else if (role == FileUrlRole) { return QUrl::fromLocalFile(info->filePath); } else if (role == FilePathRole) { return info->filePath; } else if (role == MediaInfoTypeRole) { int idx = MediaModel::staticMetaObject.indexOfEnumerator("MediaInfoType"); QMetaEnum e = MediaModel::staticMetaObject.enumerator(idx); return QString::fromLatin1(e.valueToKey(info->type)); } else if (role == FileSizeRole) { return info->fileSize; } else if (role == FileDateTimeRole) { return info->fileDateTime; } else if (role == MediaInfoRole) { return qVariantFromValue(info); } } return rv; } int Playlist::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return content.count(); } void Playlist::addSubTree(MediaInfo *info) { sort(info); foreach (MediaInfo *i, info->children) { if (i->type == MediaModel::Directory) addSubTree(i); else if (i->type == MediaModel::File) append(i); } } QModelIndex Playlist::add(MediaInfo *info, PlaylistRoles role, DepthRoles depth) { if (!info) return QModelIndex(); if (role == Playlist::Replace && count() > 0) { beginRemoveRows(QModelIndex(), 0, count()-1); content.clear(); endRemoveRows(); } int pos = content.indexOf(info); if (pos == -1) { if (depth == Playlist::Single) { if (info->type == MediaModel::File) append(info); else addSubTree(info); } else if (depth == Playlist::Flat) { if (info->parent) { sort(info); foreach (MediaInfo *i, info->parent->children) if (i->type == MediaModel::File) append(i); } else append(info); } else { if (info->type == MediaModel::Directory || info->type == MediaModel::SearchPath) addSubTree(info); else append(info); } pos = content.indexOf(info); } #ifdef PLAYLIST_DEBUG dump(); #endif if (info->type != MediaModel::File && content.count() > 0) pos = 0; return index(pos); } void Playlist::dump() const { qDebug() << "playlist:" << content.count() << "elements"; for (int i = 0; i < content.count(); i++) { qDebug() << " " << content[i]->filePath; } } QModelIndex Playlist::index(int row ) const { return QAbstractListModel::index(row, 0, QModelIndex()); } QModelIndex Playlist::indexFromMediaInfo(MediaInfo *info) const { if (!info) return QModelIndex(); return index(content.indexOf(info)); } QModelIndex Playlist::playNextIndex(const QModelIndex &idx) const { QModelIndex next; if (m_playMode == Shuffle) { next = index(int((qreal(qrand())/RAND_MAX)*count())); } else { if (idx.row() >= count()-1) next = index(0); else next = index(idx.row()+1); } return next; } QModelIndex Playlist::playPreviousIndex(const QModelIndex &idx) const { QModelIndex prev; if (idx.row() <= 0) prev = index(count()-1); else prev = index(idx.row()-1); return prev; } void Playlist::setPlayMode(Playlist::PlayModeRoles mode) { if (m_playMode != mode) { m_playMode = mode; emit playModeChanged(); } } void Playlist::append(MediaInfo *info) { int start = count()-1 < 0 ? 0 : count()-1; int end = count() < 0 ? 1 : count(); emit beginInsertRows(QModelIndex(), start, end); content.append(info); emit endInsertRows(); } bool playlistNameLessThan(MediaInfo *info1, MediaInfo *info2) { if (info1->type == MediaModel::DotDot || info2->type == MediaModel::AddNewSource) return true; if (info1->type == MediaModel::AddNewSource || info2->type == MediaModel::DotDot) return false; return QString::localeAwareCompare(info1->name.toLower(), info2->name.toLower()) < 0; } void Playlist::sort(MediaInfo *info) { emit layoutAboutToBeChanged(); qSort(info->children.begin(), info->children.end(), playlistNameLessThan); // ## do this recursively for every Directory? emit layoutChanged(); } <commit_msg>slideshow improvements<commit_after>/**************************************************************************** This file is part of the QtMediaHub project on http://www.gitorious.org. Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Nokia Corporation (qt-info@nokia.com)** You may use this file under the terms of the BSD license as follows: "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 Nokia Corporation and its Subsidiary(-ies) 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 "playlist.h" #include <QList> #include <QMetaEnum> #include <QModelIndex> #define PLAYLIST_DEBUG Playlist::Playlist(QObject *parent) : QAbstractListModel(parent) , m_playMode(Normal) { QHash<int, QByteArray> roleNames = QAbstractListModel::roleNames(); roleNames[Qt::DisplayRole] = "display"; roleNames[PreviewUrlRole] = "previewUrl"; roleNames[FilePathRole] = "filePath"; roleNames[FileNameRole] = "fileName"; roleNames[FileUrlRole] = "fileUrl"; roleNames[MediaInfoTypeRole] = "type"; roleNames[FileSizeRole] = "fileSize"; roleNames[FileDateTimeRole] = "fileDateTime"; roleNames[MediaInfoRole] = "mediaInfo"; setRoleNames(roleNames); } Playlist::~Playlist() { } QVariant Playlist::data(const QModelIndex &index, int role) const { QVariant rv; if (!index.isValid()) return rv; if (0 <= index.row() && index.row() < content.size()) { MediaInfo *info = content.at(index.row()); if (role == Qt::DisplayRole || role == FileNameRole) return info->name; else if (role == PreviewUrlRole) { int idx = MediaModel::staticMetaObject.indexOfEnumerator("MediaType"); QMetaEnum e = MediaModel::staticMetaObject.enumerator(idx); QString urlBase = "image://" + QString::fromLatin1(e.valueToKey(info->type)).toLower() + "model"; return QUrl(urlBase + info->thumbnail); } else if (role == FileUrlRole) { return QUrl::fromLocalFile(info->filePath); } else if (role == FilePathRole) { return info->filePath; } else if (role == MediaInfoTypeRole) { int idx = MediaModel::staticMetaObject.indexOfEnumerator("MediaInfoType"); QMetaEnum e = MediaModel::staticMetaObject.enumerator(idx); return QString::fromLatin1(e.valueToKey(info->type)); } else if (role == FileSizeRole) { return info->fileSize; } else if (role == FileDateTimeRole) { return info->fileDateTime; } else if (role == MediaInfoRole) { return qVariantFromValue(info); } } return rv; } int Playlist::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return content.count(); } void Playlist::addSubTree(MediaInfo *info) { sort(info); foreach (MediaInfo *i, info->children) { if (i->type == MediaModel::Directory) addSubTree(i); else if (i->type == MediaModel::File) append(i); } } QModelIndex Playlist::add(MediaInfo *info, PlaylistRoles role, DepthRoles depth) { if (!info) return QModelIndex(); if (role == Playlist::Replace && count() > 0) { beginRemoveRows(QModelIndex(), 0, count()-1); content.clear(); endRemoveRows(); } int pos = content.indexOf(info); if (pos == -1) { if (depth == Playlist::Single) { if (info->type == MediaModel::File) append(info); else addSubTree(info); } else if (depth == Playlist::Flat) { if (info->parent) { sort(info); foreach (MediaInfo *i, info->parent->children) { qDebug() << i->filePath; if (i->type == MediaModel::File) append(i); } } else append(info); } else { if (info->type == MediaModel::Directory || info->type == MediaModel::SearchPath) addSubTree(info); else append(info); } pos = content.indexOf(info); } #ifdef PLAYLIST_DEBUG dump(); #endif if (info->type != MediaModel::File && content.count() > 0) pos = 0; return index(pos); } void Playlist::dump() const { qDebug() << "playlist:" << content.count() << "elements"; for (int i = 0; i < content.count(); i++) { qDebug() << " " << content[i]->filePath; } } QModelIndex Playlist::index(int row ) const { return QAbstractListModel::index(row, 0, QModelIndex()); } QModelIndex Playlist::indexFromMediaInfo(MediaInfo *info) const { if (!info) return QModelIndex(); return index(content.indexOf(info)); } QModelIndex Playlist::playNextIndex(const QModelIndex &idx) const { QModelIndex next; if (m_playMode == Shuffle) { next = index(int((qreal(qrand())/RAND_MAX)*count())); } else { if (idx.row() >= count()-1) next = index(0); else next = index(idx.row()+1); } return next; } QModelIndex Playlist::playPreviousIndex(const QModelIndex &idx) const { QModelIndex prev; if (idx.row() <= 0) prev = index(count()-1); else prev = index(idx.row()-1); return prev; } void Playlist::setPlayMode(Playlist::PlayModeRoles mode) { if (m_playMode != mode) { m_playMode = mode; emit playModeChanged(); } } void Playlist::append(MediaInfo *info) { int start = count()-1 < 0 ? 0 : count()-1; int end = count() < 0 ? 1 : count(); emit beginInsertRows(QModelIndex(), start, end); content.append(info); emit endInsertRows(); } bool playlistNameLessThan(MediaInfo *info1, MediaInfo *info2) { if (info1->type == MediaModel::DotDot || info2->type == MediaModel::AddNewSource) return true; if (info1->type == MediaModel::AddNewSource || info2->type == MediaModel::DotDot) return false; return QString::localeAwareCompare(info1->name.toLower(), info2->name.toLower()) < 0; } void Playlist::sort(MediaInfo *info) { emit layoutAboutToBeChanged(); qSort(info->children.begin(), info->children.end(), playlistNameLessThan); // ## do this recursively for every Directory? emit layoutChanged(); } <|endoftext|>
<commit_before>#include "threadedjobmixin.h" #include <qgpgme/dataprovider.h> #include <gpgme++/data.h> #include <QString> #include <QStringList> #include <QByteArray> #include <boost/mem_fn.hpp> #include <algorithm> using namespace Kleo; using namespace GpgME; using namespace boost; static const unsigned int GetAuditLogFlags = Context::AuditLogWithHelp|Context::HtmlAuditLog; QString _detail::audit_log_as_html( Context * ctx ) { if ( !ctx ) return QString(); QGpgME::QByteArrayDataProvider dp; Data data( &dp ); assert( !data.isNull() ); if ( const Error err = ctx->getAuditLog( data, GetAuditLogFlags ) ) return QString::fromLocal8Bit( err.asString() ); else return QString::fromUtf8( dp.data().data() ); } static QList<QByteArray> from_sl( const QStringList & sl ) { QList<QByteArray> result; std::transform( sl.begin(), sl.end(), std::back_inserter( result ), mem_fn( &QString::toUtf8 ) ); return result; } static QList<QByteArray> single( const QByteArray & ba ) { QList<QByteArray> result; result.push_back( ba ); return result; } _detail::PatternConverter::PatternConverter( const QByteArray & ba ) : m_list( single( ba ) ), m_patterns( 0 ) {} _detail::PatternConverter::PatternConverter( const QString & s ) : m_list( single( s.toUtf8() ) ), m_patterns( 0 ) {} _detail::PatternConverter::PatternConverter( const QList<QByteArray> & lba ) : m_list( lba ), m_patterns( 0 ) {} _detail::PatternConverter::PatternConverter( const QStringList & sl ) : m_list( from_sl( sl ) ), m_patterns( 0 ) {} const char ** _detail::PatternConverter::patterns() const { if ( !m_patterns ) { m_patterns = new const char*[ m_list.size() + 1 ]; const char ** end = std::transform( m_list.begin(), m_list.end(), m_patterns, mem_fn( &QByteArray::constData ) ); *end = 0; } return m_patterns; } _detail::PatternConverter::~PatternConverter() { delete [] m_patterns; } <commit_msg>++license<commit_after>/* threadedjobmixin.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2008 Klarälvdalens Datakonsult AB Libkleopatra 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 2 of the License, or (at your option) any later version. Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "threadedjobmixin.h" #include <qgpgme/dataprovider.h> #include <gpgme++/data.h> #include <QString> #include <QStringList> #include <QByteArray> #include <boost/mem_fn.hpp> #include <algorithm> using namespace Kleo; using namespace GpgME; using namespace boost; static const unsigned int GetAuditLogFlags = Context::AuditLogWithHelp|Context::HtmlAuditLog; QString _detail::audit_log_as_html( Context * ctx ) { if ( !ctx ) return QString(); QGpgME::QByteArrayDataProvider dp; Data data( &dp ); assert( !data.isNull() ); if ( const Error err = ctx->getAuditLog( data, GetAuditLogFlags ) ) return QString::fromLocal8Bit( err.asString() ); else return QString::fromUtf8( dp.data().data() ); } static QList<QByteArray> from_sl( const QStringList & sl ) { QList<QByteArray> result; std::transform( sl.begin(), sl.end(), std::back_inserter( result ), mem_fn( &QString::toUtf8 ) ); return result; } static QList<QByteArray> single( const QByteArray & ba ) { QList<QByteArray> result; result.push_back( ba ); return result; } _detail::PatternConverter::PatternConverter( const QByteArray & ba ) : m_list( single( ba ) ), m_patterns( 0 ) {} _detail::PatternConverter::PatternConverter( const QString & s ) : m_list( single( s.toUtf8() ) ), m_patterns( 0 ) {} _detail::PatternConverter::PatternConverter( const QList<QByteArray> & lba ) : m_list( lba ), m_patterns( 0 ) {} _detail::PatternConverter::PatternConverter( const QStringList & sl ) : m_list( from_sl( sl ) ), m_patterns( 0 ) {} const char ** _detail::PatternConverter::patterns() const { if ( !m_patterns ) { m_patterns = new const char*[ m_list.size() + 1 ]; const char ** end = std::transform( m_list.begin(), m_list.end(), m_patterns, mem_fn( &QByteArray::constData ) ); *end = 0; } return m_patterns; } _detail::PatternConverter::~PatternConverter() { delete [] m_patterns; } <|endoftext|>
<commit_before>/** Canvas : Basic UI canvas specific to the MoMa. * * Created by Mickal Tits on 03/07/2015 * @file mmCanvas.cpp * @brief MotionMachine source file for Canvas class. * @copyright Numediart Institute, UMONS (c) 2014-2015 * */ #include "mmCanvas.h" using namespace std; using namespace MoMa; /** Static vectors storing addresses of the canvas*/ vector<Canvas*> Canvas::mainCanvas; vector<Canvas*> Canvas::allCanvas; vector<Canvas*> Canvas::closedCanvas; int Canvas::_limit(0); Canvas::Canvas( SceneApp *app, string title, Position position, Position alignment, Canvas *relative, Canvas *parent, int group, bool minified ) : ofxUISuperCanvas( title ), _app(app), _relative(relative), _parent(parent), _group(group-1), _position(position), _alignment(alignment), _minified(minified) { setupCanvas(); } Canvas::Canvas( SceneApp *app, std::string title, Canvas *parent, int group, bool minified ) : ofxUISuperCanvas( title ), _app(app), _relative(NULL), _parent(parent), _group(group-1), _position(DEFAULT), _alignment(DEFAULT), _minified(minified) { setupCanvas(); } void Canvas::setupCanvas() { _allIndex = allCanvas.size(); allCanvas.push_back(this); childrenCanvas.reserve(1); if(_parent == NULL) { _index = mainCanvas.size(); mainCanvas.push_back(this); } else { if(_group<0) _group = 0; if(_group+1 > _parent->childrenCanvas.size()) _parent->childrenCanvas.resize(_group+1); _index = _parent->childrenCanvas[_group].size(); _parent->childrenCanvas[_group].push_back(this); setVisible(false); } ofAddListener( newGUIEvent, this, &Canvas::guiEvent ); setColorBack( ofColor( MoMa::DarkTurquoise, 190 ) ); _isInitialized = false; savedMode = _app->activeMode; _isCanvasHit = false; _isShortCutDisabled = false; } void Canvas::initCanvas() { autoSizeToFitWidgets(); //fit to widgets of the herited class setMinified(false); //(temporary for canvas placement) Position position(_position), alignment(_alignment); Canvas* relative(_relative); if(_index == 0) _limit = 0; if( ( relative == NULL && position == DEFAULT && _index > 0 ) || ( relative == NULL && position == DEFAULT && _parent != NULL ) ) { // Default relative placement ( first canvas (index = 0) placed on // Top/Right corner; next ones placed below, right edge aligned ) if(_parent != NULL) { //Children placement if(_index != 0) relative = _parent->childrenCanvas[_group][_index-1]; //Child placed relative to the previous child else relative = _parent; //First cihld placed relative to the parent } else relative = mainCanvas[_index-1]; //Main canvas placed relative to previous canvas float H = getRect()->getHeight(); float W = getRect()->getWidth(); float relativeX = relative->getRect()->getX(); float relativeY = relative->getRect()->getY(); float relativeH = relative->getRect()->getHeight(); float relativeW = relative->getRect()->getWidth(); if(relativeY + relativeH + 10 + H < ofGetHeight() && _limit <1 ) { // test window bottom limit position = BELOW; alignment = RIGHT; } else if(relativeX - 10 - W > 0 && _limit < 2) { // test window left limit position = LEFT; if(_limit == 0) alignment = BOTTOM; else alignment = BELOW; _limit = 1; } else if(relativeY - 10 - H > 0 && _limit < 3) { // test window top limit position = ABOVE; if(_limit == 1 ) alignment = LEFTSIDE; else alignment = LEFT; _limit = 2; } else if(relativeX + relativeW + 10 + W < ofGetWidth() - 10 - mainCanvas[0]->getRect()->getWidth() - 10 && _limit < 4) { // test window right limit (taking into account the first Canvas canvas supposed to be on the top/right corner) position = RIGHT; if(_limit == 2 ) alignment = TOP; else alignment = ABOVE; _limit = 3; } else { relative = NULL; _limit = 4; cout << "Too much mainCanvas for default handle\n"; setPosition(0,0); return; } } setPos(position,alignment,relative); setMinified(_minified); _isInitialized = true; } void Canvas::setPos(Position position, Position alignment, Canvas *relative) { float H = this->getRect()->getHeight(); float W = this->getRect()->getWidth(); //Default : Top, Right float xPos = ofGetWidth() - W - 10; float yPos = 10; if(relative == NULL) { // Set positions relative to main OF Window if(position == LEFT || position == LEFTSIDE || alignment == LEFT || alignment == LEFTSIDE ) xPos = 10; if(position == BELOW || position == BOTTOM || alignment == BELOW || alignment == BOTTOM ) yPos = ofGetHeight() - H - 10; } else { // Set relative positions float relativeX = relative->getRect()->getX(); float relativeY = relative->getRect()->getY(); float relativeH = relative->getRect()->getHeight(); float relativeW = relative->getRect()->getWidth(); // Default: Below, right edges aligned xPos = relativeX + relativeW - W; yPos = relativeY + relativeH + 10; switch( position ) { case LEFTSIDE : xPos = 10; break; case RIGHTSIDE : xPos = ofGetWidth() - W - 10; break; case LEFT : xPos = relativeX - W - 10; break; case RIGHT : xPos = relativeX + relativeW + 10; break; case TOP : yPos = 10; break; case BOTTOM : yPos = ofGetHeight() - H - 10; break; case ABOVE : yPos = relativeY - 10 - H; break; case BELOW : yPos = relativeY + relativeH + 10; break; case DEFAULT: break; } switch( alignment ) { case LEFTSIDE : xPos = 10; break; case RIGHTSIDE : xPos = ofGetWidth() - W - 10; break; case LEFT : xPos = relativeX; break; //Align left edges case RIGHT : xPos = xPos = relativeX + relativeW - W; break; //Align right edges case TOP : yPos = 10; break; case BOTTOM : yPos = ofGetHeight() - H - 10; break; case ABOVE : yPos = relativeY; break; //Align upper edges case BELOW : yPos = relativeY + relativeH - H; break; //Align below edges case DEFAULT: break; } } setPosition(xPos,yPos); } void Canvas::resetPositions() { _limit = 0; /*for(int i=0;i<mainCanvas.size();i++) { mainCanvas[i]->initUI(); mainCanvas[i]->closeChildren(); }*/ for(int i=0;i<allCanvas.size();i++) { allCanvas[i]->initCanvas(); } } void Canvas::remove() { //delete children for(int g=0;g<childrenCanvas.size();g++) { for(int i=0;i<childrenCanvas[g].size();i++) { childrenCanvas[g][i]->remove(); if(childrenCanvas.size()<=g) break; } } //erase from canvas groups if(_parent == NULL) { mainCanvas.erase(mainCanvas.begin()+_index); } else { _parent->childrenCanvas[_group].erase(_parent->childrenCanvas[_group].begin()+_index); if( _parent->childrenCanvas[_group].size() == 0 ) _parent->childrenCanvas.erase( _parent->childrenCanvas.begin()+_group ); } allCanvas.erase(allCanvas.begin()+_allIndex); delete this; } void Canvas::deleteCanvas() { for(int i=0;i<allCanvas.size();i++) { if(allCanvas[i] != NULL) delete(allCanvas[i]); } } void Canvas::openChildren(int group) { if(group < childrenCanvas.size() ) { //closeChildren(); for(int i=0;i<childrenCanvas[group].size();i++) { childrenCanvas[group][i]->initCanvas(); childrenCanvas[group][i]->setVisible(true); } } else cout << "That group of children canvas does not exist\n"; } void Canvas::openChild(int index, int group) { if(group < childrenCanvas.size() && index < childrenCanvas[group].size() ) { closeChildren(); childrenCanvas[group][index]->initCanvas(); childrenCanvas[group][index]->setVisible(true); } else cout << "That child canvas does not exist\n"; } bool Canvas::childrenOpened(int group) { bool opened = false; if(group < childrenCanvas.size() ) { for(int i=0;i<childrenCanvas[group].size();i++) { opened = opened || childrenCanvas[group][i]->isVisible(); } } else cout << "That group of children canvas does not exist\n"; return opened; } bool Canvas::canvasOpened() { for(int i=0;i<allCanvas.size();i++) { if( allCanvas[i]->isVisible() ) return true; } return false; } void Canvas::closeChildren() { for(int g=0;g<childrenCanvas.size();g++) { for(int i=0;i<childrenCanvas[g].size();i++) { childrenCanvas[g][i]->setVisible(false); } } } void Canvas::closeChildren(int group) { if(group < childrenCanvas.size() ) { for(int i=0;i<childrenCanvas[group].size();i++) { childrenCanvas[group][i]->setVisible(false); } } else cout << "That group of children canvas does not exist\n"; } void Canvas::openMainCanvas() { for(int i=0;i<mainCanvas.size();i++) { mainCanvas[i]->initCanvas(); mainCanvas[i]->setVisible(true); } closedCanvas.clear(); } void Canvas::closeMainCanvas() { for(int i=0;i<mainCanvas.size();i++) { mainCanvas[i]->setVisible(false); } } void Canvas::closeAllCanvas() { closedCanvas.clear(); for(int i=0;i<allCanvas.size();i++) { if(allCanvas[i]->isVisible() ) { allCanvas[i]->setVisible(false); closedCanvas.push_back(allCanvas[i]); } } } void Canvas::reopenCanvas() { for(int i=0;i<closedCanvas.size();i++) { closedCanvas[i]->setVisible(true); } closedCanvas.clear(); } void Canvas::mainView() { closeAllCanvas(); openMainCanvas(); } void Canvas::windowResized(int w, int h) { //resetPositions(); } void Canvas::onMousePressed( ofMouseEventArgs &data ) { if( isHit( data.x, data.y ) && !_isCanvasHit ) { _isCanvasHit = true; savedMode = _app->activeMode; // save mode previous to click _app->setActiveMode( CANVAS ); // switch to Canvas } ofxUISuperCanvas::onMousePressed(data); } void Canvas::onMouseReleased( ofMouseEventArgs &data ) { if(_isCanvasHit) { _app->setActiveMode( savedMode ); // restore previous mode _isCanvasHit = false; } ofxUISuperCanvas::onMouseReleased(data); } void Canvas::update() { } void Canvas::guiEvent( ofxUIEventArgs &e ) { // disable shortcuts when focus is on a textbox if(hasKeyBoard) { _app->disableShortcuts(); _isShortCutDisabled = true; } else if(_isShortCutDisabled) { _app->enableShortcuts(); _isShortCutDisabled = false; } /*if(e.widget->getKind() == OFX_UI_WIDGET_TEXTINPUT) { ofxUITextInput *ti = (ofxUITextInput *) e.widget; if(ti->getInputTriggerType() == OFX_UI_TEXTINPUT_ON_FOCUS) { _app->disableShortcuts(); } else if(ti->getInputTriggerType() == OFX_UI_TEXTINPUT_ON_UNFOCUS) { _app->enableShortcuts(); } }*/ canvasEvent(e); } void Canvas::canvasEvent( ofxUIEventArgs &e ) { } <commit_msg>mmCanvas debugged (more robust remove function)<commit_after>/** Canvas : Basic UI canvas specific to the MoMa. * * Created by Mickal Tits on 03/07/2015 * @file mmCanvas.cpp * @brief MotionMachine source file for Canvas class. * @copyright Numediart Institute, UMONS (c) 2014-2015 * */ #include "mmCanvas.h" using namespace std; using namespace MoMa; /** Static vectors storing addresses of the canvas*/ vector<Canvas*> Canvas::mainCanvas; vector<Canvas*> Canvas::allCanvas; vector<Canvas*> Canvas::closedCanvas; int Canvas::_limit(0); Canvas::Canvas( SceneApp *app, string title, Position position, Position alignment, Canvas *relative, Canvas *parent, int group, bool minified ) : ofxUISuperCanvas( title ), _app(app), _relative(relative), _parent(parent), _group(group-1), _position(position), _alignment(alignment), _minified(minified) { setupCanvas(); } Canvas::Canvas( SceneApp *app, std::string title, Canvas *parent, int group, bool minified ) : ofxUISuperCanvas( title ), _app(app), _relative(NULL), _parent(parent), _group(group-1), _position(DEFAULT), _alignment(DEFAULT), _minified(minified) { setupCanvas(); } void Canvas::setupCanvas() { _allIndex = allCanvas.size(); allCanvas.push_back(this); childrenCanvas.reserve(1); if(_parent == NULL) { _index = mainCanvas.size(); mainCanvas.push_back(this); } else { if(_group<0) _group = 0; if(_group+1 > _parent->childrenCanvas.size()) _parent->childrenCanvas.resize(_group+1); _index = _parent->childrenCanvas[_group].size(); _parent->childrenCanvas[_group].push_back(this); setVisible(false); } ofAddListener( newGUIEvent, this, &Canvas::guiEvent ); setColorBack( ofColor( MoMa::DarkTurquoise, 190 ) ); _isInitialized = false; savedMode = _app->activeMode; _isCanvasHit = false; _isShortCutDisabled = false; } void Canvas::initCanvas() { autoSizeToFitWidgets(); //fit to widgets of the herited class setMinified(false); //(temporary for canvas placement) Position position(_position), alignment(_alignment); Canvas* relative(_relative); if(_index == 0) _limit = 0; if( ( relative == NULL && position == DEFAULT && _index > 0 ) || ( relative == NULL && position == DEFAULT && _parent != NULL ) ) { // Default relative placement ( first canvas (index = 0) placed on // Top/Right corner; next ones placed below, right edge aligned ) if(_parent != NULL) { //Children placement if(_index != 0) relative = _parent->childrenCanvas[_group][_index-1]; //Child placed relative to the previous child else relative = _parent; //First cihld placed relative to the parent } else relative = mainCanvas[_index-1]; //Main canvas placed relative to previous canvas float H = getRect()->getHeight(); float W = getRect()->getWidth(); float relativeX = relative->getRect()->getX(); float relativeY = relative->getRect()->getY(); float relativeH = relative->getRect()->getHeight(); float relativeW = relative->getRect()->getWidth(); if(relativeY + relativeH + 10 + H < ofGetHeight() && _limit <1 ) { // test window bottom limit position = BELOW; alignment = RIGHT; } else if(relativeX - 10 - W > 0 && _limit < 2) { // test window left limit position = LEFT; if(_limit == 0) alignment = BOTTOM; else alignment = BELOW; _limit = 1; } else if(relativeY - 10 - H > 0 && _limit < 3) { // test window top limit position = ABOVE; if(_limit == 1 ) alignment = LEFTSIDE; else alignment = LEFT; _limit = 2; } else if(relativeX + relativeW + 10 + W < ofGetWidth() - 10 - mainCanvas[0]->getRect()->getWidth() - 10 && _limit < 4) { // test window right limit (taking into account the first Canvas canvas supposed to be on the top/right corner) position = RIGHT; if(_limit == 2 ) alignment = TOP; else alignment = ABOVE; _limit = 3; } else { relative = NULL; _limit = 4; cout << "Too much mainCanvas for default handle\n"; setPosition(0,0); return; } } setPos(position,alignment,relative); setMinified(_minified); _isInitialized = true; } void Canvas::setPos(Position position, Position alignment, Canvas *relative) { float H = this->getRect()->getHeight(); float W = this->getRect()->getWidth(); //Default : Top, Right float xPos = ofGetWidth() - W - 10; float yPos = 10; if(relative == NULL) { // Set positions relative to main OF Window if(position == LEFT || position == LEFTSIDE || alignment == LEFT || alignment == LEFTSIDE ) xPos = 10; if(position == BELOW || position == BOTTOM || alignment == BELOW || alignment == BOTTOM ) yPos = ofGetHeight() - H - 10; } else { // Set relative positions float relativeX = relative->getRect()->getX(); float relativeY = relative->getRect()->getY(); float relativeH = relative->getRect()->getHeight(); float relativeW = relative->getRect()->getWidth(); // Default: Below, right edges aligned xPos = relativeX + relativeW - W; yPos = relativeY + relativeH + 10; switch( position ) { case LEFTSIDE : xPos = 10; break; case RIGHTSIDE : xPos = ofGetWidth() - W - 10; break; case LEFT : xPos = relativeX - W - 10; break; case RIGHT : xPos = relativeX + relativeW + 10; break; case TOP : yPos = 10; break; case BOTTOM : yPos = ofGetHeight() - H - 10; break; case ABOVE : yPos = relativeY - 10 - H; break; case BELOW : yPos = relativeY + relativeH + 10; break; case DEFAULT: break; } switch( alignment ) { case LEFTSIDE : xPos = 10; break; case RIGHTSIDE : xPos = ofGetWidth() - W - 10; break; case LEFT : xPos = relativeX; break; //Align left edges case RIGHT : xPos = xPos = relativeX + relativeW - W; break; //Align right edges case TOP : yPos = 10; break; case BOTTOM : yPos = ofGetHeight() - H - 10; break; case ABOVE : yPos = relativeY; break; //Align upper edges case BELOW : yPos = relativeY + relativeH - H; break; //Align below edges case DEFAULT: break; } } setPosition(xPos,yPos); } void Canvas::resetPositions() { _limit = 0; /*for(int i=0;i<mainCanvas.size();i++) { mainCanvas[i]->initUI(); mainCanvas[i]->closeChildren(); }*/ for(int i=0;i<allCanvas.size();i++) { allCanvas[i]->initCanvas(); } } void Canvas::remove() { //delete children for(int g=0;g<childrenCanvas.size();g++) { for(int i=0;i<childrenCanvas[g].size();i++) { childrenCanvas[g][i]->remove(); if(childrenCanvas.size()<=g) break; } } //erase from canvas groups, and update indexes of all other canvas if(_parent == NULL) { mainCanvas.erase(mainCanvas.begin()+_index); for(int i = _index;i<mainCanvas.size();i++) { mainCanvas[i]->_index--; } } else { _parent->childrenCanvas[_group].erase(_parent->childrenCanvas[_group].begin()+_index); for(int i = _index;i<childrenCanvas[_group].size();i++) { childrenCanvas[_group][i]->_index--; } if( _parent->childrenCanvas[_group].size() == 0 ) _parent->childrenCanvas.erase( _parent->childrenCanvas.begin()+_group ); for(int i = _group;i<childrenCanvas.size();i++) { for(int j = 0; j<childrenCanvas[i].size(); j++) { childrenCanvas[i][j]->_group--; } } } allCanvas.erase(allCanvas.begin()+_allIndex); for(int i = _allIndex;i<allCanvas.size();i++) { allCanvas[i]->_allIndex--; } delete this; } void Canvas::deleteCanvas() { for(int i=0;i<allCanvas.size();i++) { if(allCanvas[i] != NULL) delete(allCanvas[i]); } } void Canvas::openChildren(int group) { if(group < childrenCanvas.size() ) { //closeChildren(); for(int i=0;i<childrenCanvas[group].size();i++) { childrenCanvas[group][i]->initCanvas(); childrenCanvas[group][i]->setVisible(true); } } else cout << "That group of children canvas does not exist\n"; } void Canvas::openChild(int index, int group) { if(group < childrenCanvas.size() && index < childrenCanvas[group].size() ) { closeChildren(); childrenCanvas[group][index]->initCanvas(); childrenCanvas[group][index]->setVisible(true); } else cout << "That child canvas does not exist\n"; } bool Canvas::childrenOpened(int group) { bool opened = false; if(group < childrenCanvas.size() ) { for(int i=0;i<childrenCanvas[group].size();i++) { opened = opened || childrenCanvas[group][i]->isVisible(); } } else cout << "That group of children canvas does not exist\n"; return opened; } bool Canvas::canvasOpened() { for(int i=0;i<allCanvas.size();i++) { if( allCanvas[i]->isVisible() ) return true; } return false; } void Canvas::closeChildren() { for(int g=0;g<childrenCanvas.size();g++) { for(int i=0;i<childrenCanvas[g].size();i++) { childrenCanvas[g][i]->setVisible(false); } } } void Canvas::closeChildren(int group) { if(group < childrenCanvas.size() ) { for(int i=0;i<childrenCanvas[group].size();i++) { childrenCanvas[group][i]->setVisible(false); } } else cout << "That group of children canvas does not exist\n"; } void Canvas::openMainCanvas() { for(int i=0;i<mainCanvas.size();i++) { mainCanvas[i]->initCanvas(); mainCanvas[i]->setVisible(true); } closedCanvas.clear(); } void Canvas::closeMainCanvas() { for(int i=0;i<mainCanvas.size();i++) { mainCanvas[i]->setVisible(false); } } void Canvas::closeAllCanvas() { closedCanvas.clear(); for(int i=0;i<allCanvas.size();i++) { if(allCanvas[i]->isVisible() ) { allCanvas[i]->setVisible(false); closedCanvas.push_back(allCanvas[i]); } } } void Canvas::reopenCanvas() { for(int i=0;i<closedCanvas.size();i++) { closedCanvas[i]->setVisible(true); } closedCanvas.clear(); } void Canvas::mainView() { closeAllCanvas(); openMainCanvas(); } void Canvas::windowResized(int w, int h) { //resetPositions(); } void Canvas::onMousePressed( ofMouseEventArgs &data ) { if( isHit( data.x, data.y ) && !_isCanvasHit ) { _isCanvasHit = true; savedMode = _app->activeMode; // save mode previous to click _app->setActiveMode( CANVAS ); // switch to Canvas } ofxUISuperCanvas::onMousePressed(data); } void Canvas::onMouseReleased( ofMouseEventArgs &data ) { if(_isCanvasHit) { _app->setActiveMode( savedMode ); // restore previous mode _isCanvasHit = false; } ofxUISuperCanvas::onMouseReleased(data); } void Canvas::update() { } void Canvas::guiEvent( ofxUIEventArgs &e ) { // disable shortcuts when focus is on a textbox if(hasKeyBoard) { _app->disableShortcuts(); _isShortCutDisabled = true; } else if(_isShortCutDisabled) { _app->enableShortcuts(); _isShortCutDisabled = false; } /*if(e.widget->getKind() == OFX_UI_WIDGET_TEXTINPUT) { ofxUITextInput *ti = (ofxUITextInput *) e.widget; if(ti->getInputTriggerType() == OFX_UI_TEXTINPUT_ON_FOCUS) { _app->disableShortcuts(); } else if(ti->getInputTriggerType() == OFX_UI_TEXTINPUT_ON_UNFOCUS) { _app->enableShortcuts(); } }*/ canvasEvent(e); } void Canvas::canvasEvent( ofxUIEventArgs &e ) { } <|endoftext|>
<commit_before>#include <time.h> // NOT TESTED!!!!!! class diddy { public: // only accurate to 1 second static int systemMillisecs() { time_t seconds; seconds = time (NULL); return seconds * 1000; } static void flushKeys() { for( int i=0;i<512;++i ){ app->input->keyStates[i]&=0x100; } } static int getUpdateRate() { return app->updateRate; } static void showMouse() { ShowCursor(true); } static void hideMouse() { ShowCursor(false); } }; <commit_msg>"Fixed" iOS target so Diddy will not compile for iOS.<commit_after>#include <time.h> // flushkeys and getUpdateRate does not work, due to the ordering of the imports in monkey class diddy { public: // only accurate to 1 second static int systemMillisecs() { time_t seconds; seconds = time (NULL); return seconds * 1000; } static void flushKeys() { for( int i=0;i<512;++i ){ //app->input->keyStates[i]&=0x100; } } static int getUpdateRate() { return 0; //return app->updateRate; } static void showMouse() { } static void hideMouse() { } }; <|endoftext|>
<commit_before>#include "Tester.h" #include <algorithm> extern bool Verbose; extern bool ExtraVerbose; MockCallback::MockCallback() { // Start locked. The locked will be released when waiting for parsing to be completed m_parsingMutex.lock(); } bool MockCallback::waitForParsingComplete() { std::unique_lock<std::mutex> lock( m_parsingMutex, std::adopt_lock ); m_done = false; m_discoveryCompleted = false; // Wait for a while, generating snapshots can be heavy... return m_parsingCompleteVar.wait_for( lock, std::chrono::seconds( 30 ), [this]() { return m_done; }); } void MockCallback::onDiscoveryCompleted(const std::string& entryPoint ) { if ( entryPoint.empty() == true ) return; std::lock_guard<std::mutex> lock( m_parsingMutex ); m_discoveryCompleted = true; } void MockCallback::onParsingStatsUpdated(uint32_t percent) { if ( percent == 100 ) { std::lock_guard<std::mutex> lock( m_parsingMutex ); if ( m_discoveryCompleted == false ) return; m_done = true; m_parsingCompleteVar.notify_all(); } } void Tests::SetUp() { unlink("test.db"); m_cb.reset( new MockCallback ); m_ml.reset( new MediaLibraryTester ); if ( ExtraVerbose == true ) m_ml->setVerbosity( LogLevel::Debug ); else if ( Verbose == true ) m_ml->setVerbosity( LogLevel::Info ); m_ml->initialize( "test.db", "/tmp", m_cb.get() ); } void Tests::checkVideoTracks( const rapidjson::Value& expectedTracks, const std::vector<VideoTrackPtr>& tracks ) { // There is no reliable way of discriminating between tracks, so we just assume the test case will // only check for simple cases... like a single track? ASSERT_TRUE( expectedTracks.IsArray() ); ASSERT_EQ( expectedTracks.Size(), tracks.size() ); for ( auto i = 0u; i < expectedTracks.Size(); ++i ) { const auto& track = tracks[i]; const auto& expectedTrack = expectedTracks[i]; ASSERT_TRUE( expectedTrack.IsObject() ); if ( expectedTrack.HasMember( "codec" ) ) ASSERT_STRCASEEQ( expectedTrack["codec"].GetString(), track->codec().c_str() ); if ( expectedTrack.HasMember( "width" ) ) ASSERT_EQ( expectedTrack["width"].GetUint(), track->width() ); if ( expectedTrack.HasMember( "height" ) ) ASSERT_EQ( expectedTrack["height"].GetUint(), track->height() ); if ( expectedTrack.HasMember( "fps" ) ) ASSERT_EQ( expectedTrack["fps"].GetDouble(), track->fps() ); } } void Tests::checkAudioTracks(const rapidjson::Value& expectedTracks, const std::vector<AudioTrackPtr>& tracks) { ASSERT_TRUE( expectedTracks.IsArray() ); ASSERT_EQ( expectedTracks.Size(), tracks.size() ); for ( auto i = 0u; i < expectedTracks.Size(); ++i ) { const auto& track = tracks[i]; const auto& expectedTrack = expectedTracks[i]; ASSERT_TRUE( expectedTrack.IsObject() ); if ( expectedTrack.HasMember( "codec" ) ) ASSERT_STRCASEEQ( expectedTrack["codec"].GetString(), track->codec().c_str() ); if ( expectedTrack.HasMember( "sampleRate" ) ) ASSERT_EQ( expectedTrack["sampleRate"].GetUint(), track->sampleRate() ); if ( expectedTrack.HasMember( "nbChannels" ) ) ASSERT_EQ( expectedTrack["nbChannels"].GetUint(), track->nbChannels() ); if ( expectedTrack.HasMember( "bitrate" ) ) ASSERT_EQ( expectedTrack["bitrate"].GetUint(), track->bitrate() ); } } void Tests::checkMedias(const rapidjson::Value& expectedMedias) { ASSERT_TRUE( expectedMedias.IsArray() ); auto medias = m_ml->files(); for ( auto i = 0u; i < expectedMedias.Size(); ++i ) { const auto& expectedMedia = expectedMedias[i]; ASSERT_TRUE( expectedMedia.HasMember( "title" ) ); const auto expectedTitle = expectedMedia["title"].GetString(); auto it = std::find_if( begin( medias ), end( medias ), [expectedTitle](const MediaPtr& m) { return strcasecmp( expectedTitle, m->title().c_str() ) == 0; }); ASSERT_NE( end( medias ), it ); const auto& media = *it; medias.erase( it ); if ( expectedMedia.HasMember( "nbVideoTracks" ) || expectedMedia.HasMember( "videoTracks" ) ) { auto videoTracks = media->videoTracks(); if ( expectedMedia.HasMember( "nbVideoTracks" ) ) ASSERT_EQ( expectedMedia[ "nbVideoTracks" ].GetUint(), videoTracks.size() ); if ( expectedMedia.HasMember( "videoTracks" ) ) checkVideoTracks( expectedMedia["videoTracks"], videoTracks ); } if ( expectedMedia.HasMember( "nbAudioTracks" ) || expectedMedia.HasMember( "audioTracks" ) ) { auto audioTracks = media->audioTracks(); if ( expectedMedia.HasMember( "nbAudioTracks" ) ) ASSERT_EQ( expectedMedia[ "nbAudioTracks" ].GetUint(), audioTracks.size() ); if ( expectedMedia.HasMember( "audioTracks" ) ) checkAudioTracks( expectedMedia[ "audioTracks" ], audioTracks ); } if ( expectedMedia.HasMember( "snapshotExpected" ) == true ) { auto snapshotExpected = expectedMedia["snapshotExpected"].GetBool(); ASSERT_EQ( !snapshotExpected, media->thumbnail().empty() ); } } } void Tests::checkAlbums( const rapidjson::Value& expectedAlbums, std::vector<AlbumPtr> albums ) { ASSERT_TRUE( expectedAlbums.IsArray() ); ASSERT_EQ( expectedAlbums.Size(), albums.size() ); for ( auto i = 0u; i < expectedAlbums.Size(); ++i ) { const auto& expectedAlbum = expectedAlbums[i]; ASSERT_TRUE( expectedAlbum.HasMember( "title" ) ); // Start by checking if the album was found auto it = std::find_if( begin( albums ), end( albums ), [this, &expectedAlbum](const AlbumPtr& a) { const auto expectedTitle = expectedAlbum["title"].GetString(); if ( strcasecmp( a->title().c_str(), expectedTitle ) != 0 ) return false; if ( expectedAlbum.HasMember( "artist" ) ) { const auto expectedArtist = expectedAlbum["artist"].GetString(); auto artist = a->albumArtist(); if ( artist != nullptr && strcasecmp( artist->name().c_str(), expectedArtist ) != 0 ) return false; } if ( expectedAlbum.HasMember( "artists" ) ) { const auto& expectedArtists = expectedAlbum["artists"]; auto artists = a->artists( false ); if ( expectedArtists.Size() != artists.size() ) return false; for ( auto i = 0u; i < expectedArtists.Size(); ++i ) { auto expectedArtist = expectedArtists[i].GetString(); auto it = std::find_if( begin( artists ), end( artists), [expectedArtist](const ArtistPtr& a) { return strcasecmp( expectedArtist, a->name().c_str() ) == 0; }); if ( it == end( artists ) ) return false; } } if ( expectedAlbum.HasMember( "nbTracks" ) || expectedAlbum.HasMember( "tracks" ) ) { const auto tracks = a->tracks( SortingCriteria::Default, false ); if ( expectedAlbum.HasMember( "nbTracks" ) ) { if ( expectedAlbum["nbTracks"].GetUint() != tracks.size() ) return false; } if ( expectedAlbum.HasMember( "tracks" ) ) { bool tracksOk = false; checkAlbumTracks( a.get(), tracks, expectedAlbum["tracks"], tracksOk ); if ( tracksOk == false ) return false; } } if ( expectedAlbum.HasMember( "releaseYear" ) ) { const auto releaseYear = expectedAlbum["releaseYear"].GetUint(); if ( a->releaseYear() != releaseYear ) return false; } return true; }); ASSERT_NE( end( albums ), it ); albums.erase( it ); } } void Tests::checkArtists(const rapidjson::Value& expectedArtists, std::vector<ArtistPtr> artists) { ASSERT_TRUE( expectedArtists.IsArray() ); ASSERT_EQ( expectedArtists.Size(), artists.size() ); for ( auto i = 0u; i < expectedArtists.Size(); ++i ) { const auto& expectedArtist = expectedArtists[i]; auto it = std::find_if( begin( artists ), end( artists ), [&expectedArtist, this](const ArtistPtr& artist) { if ( expectedArtist.HasMember( "name" ) ) { if ( strcasecmp( expectedArtist["name"].GetString(), artist->name().c_str() ) != 0 ) return false; } if ( expectedArtist.HasMember( "id" ) ) { if ( expectedArtist["id"].GetUint() != artist->id() ) return false; } if ( expectedArtist.HasMember( "nbAlbums" ) || expectedArtist.HasMember( "albums" ) ) { auto albums = artist->albums( SortingCriteria::Default, false ); if ( expectedArtist.HasMember( "nbAlbums" ) ) { if ( albums.size() != expectedArtist["nbAlbums"].GetUint() ) return false; if ( expectedArtist.HasMember( "albums" ) ) checkAlbums( expectedArtist["albums"], albums ); } } if ( expectedArtist.HasMember( "nbTracks" ) ) { auto tracks = artist->media( SortingCriteria::Default, false ); if ( expectedArtist["nbTracks"].GetUint() != tracks.size() ) return false; } return true; }); ASSERT_NE( it, end( artists ) ); } } void Tests::checkAlbumTracks( const IAlbum* album, const std::vector<MediaPtr>& tracks, const rapidjson::Value& expectedTracks, bool& found ) const { found = false; // Don't mandate all tracks to be defined for ( auto i = 0u; i < expectedTracks.Size(); ++i ) { const auto& expectedTrack = expectedTracks[i]; ASSERT_TRUE( expectedTrack.HasMember( "title" ) ); auto expectedTitle = expectedTrack["title"].GetString(); auto it = std::find_if( begin( tracks ), end( tracks ), [expectedTitle](const MediaPtr& media) { return strcasecmp( expectedTitle, media->title().c_str() ) == 0; }); if ( it == end( tracks ) ) return ; const auto track = *it; const auto albumTrack = track->albumTrack(); if ( expectedTrack.HasMember( "number" ) ) { if ( expectedTrack["number"].GetUint() != albumTrack->trackNumber() ) return ; } if ( expectedTrack.HasMember( "artist" ) ) { auto artist = albumTrack->artist(); if ( artist == nullptr ) return ; if ( strlen( expectedTrack["artist"].GetString() ) == 0 && artist->id() != UnknownArtistID ) return ; else if ( strcasecmp( expectedTrack["artist"].GetString(), artist->name().c_str() ) != 0 ) return ; } if ( expectedTrack.HasMember( "genre" ) ) { auto genre = albumTrack->genre(); if ( genre == nullptr || strcasecmp( expectedTrack["genre"].GetString(), genre->name().c_str() ) != 0 ) return ; } if ( expectedTrack.HasMember( "releaseYear" ) ) { if ( track->releaseDate() != expectedTrack["releaseYear"].GetUint() ) return; } if ( expectedTrack.HasMember( "cd" ) ) { if ( expectedTrack["cd"].GetUint() != albumTrack->discNumber() ) return; } // Always check if the album link is correct. This isn't part of finding the proper album, so just fail hard // if the check fails. const auto trackAlbum = albumTrack->album(); ASSERT_NE( nullptr, trackAlbum ); ASSERT_EQ( album->id(), trackAlbum->id() ); } found = true; } <commit_msg>tests: samples: Reduce timeout<commit_after>#include "Tester.h" #include <algorithm> extern bool Verbose; extern bool ExtraVerbose; MockCallback::MockCallback() { // Start locked. The locked will be released when waiting for parsing to be completed m_parsingMutex.lock(); } bool MockCallback::waitForParsingComplete() { std::unique_lock<std::mutex> lock( m_parsingMutex, std::adopt_lock ); m_done = false; m_discoveryCompleted = false; // Wait for a while, generating snapshots can be heavy... return m_parsingCompleteVar.wait_for( lock, std::chrono::seconds( 5 ), [this]() { return m_done; }); } void MockCallback::onDiscoveryCompleted(const std::string& entryPoint ) { if ( entryPoint.empty() == true ) return; std::lock_guard<std::mutex> lock( m_parsingMutex ); m_discoveryCompleted = true; } void MockCallback::onParsingStatsUpdated(uint32_t percent) { if ( percent == 100 ) { std::lock_guard<std::mutex> lock( m_parsingMutex ); if ( m_discoveryCompleted == false ) return; m_done = true; m_parsingCompleteVar.notify_all(); } } void Tests::SetUp() { unlink("test.db"); m_cb.reset( new MockCallback ); m_ml.reset( new MediaLibraryTester ); if ( ExtraVerbose == true ) m_ml->setVerbosity( LogLevel::Debug ); else if ( Verbose == true ) m_ml->setVerbosity( LogLevel::Info ); m_ml->initialize( "test.db", "/tmp", m_cb.get() ); } void Tests::checkVideoTracks( const rapidjson::Value& expectedTracks, const std::vector<VideoTrackPtr>& tracks ) { // There is no reliable way of discriminating between tracks, so we just assume the test case will // only check for simple cases... like a single track? ASSERT_TRUE( expectedTracks.IsArray() ); ASSERT_EQ( expectedTracks.Size(), tracks.size() ); for ( auto i = 0u; i < expectedTracks.Size(); ++i ) { const auto& track = tracks[i]; const auto& expectedTrack = expectedTracks[i]; ASSERT_TRUE( expectedTrack.IsObject() ); if ( expectedTrack.HasMember( "codec" ) ) ASSERT_STRCASEEQ( expectedTrack["codec"].GetString(), track->codec().c_str() ); if ( expectedTrack.HasMember( "width" ) ) ASSERT_EQ( expectedTrack["width"].GetUint(), track->width() ); if ( expectedTrack.HasMember( "height" ) ) ASSERT_EQ( expectedTrack["height"].GetUint(), track->height() ); if ( expectedTrack.HasMember( "fps" ) ) ASSERT_EQ( expectedTrack["fps"].GetDouble(), track->fps() ); } } void Tests::checkAudioTracks(const rapidjson::Value& expectedTracks, const std::vector<AudioTrackPtr>& tracks) { ASSERT_TRUE( expectedTracks.IsArray() ); ASSERT_EQ( expectedTracks.Size(), tracks.size() ); for ( auto i = 0u; i < expectedTracks.Size(); ++i ) { const auto& track = tracks[i]; const auto& expectedTrack = expectedTracks[i]; ASSERT_TRUE( expectedTrack.IsObject() ); if ( expectedTrack.HasMember( "codec" ) ) ASSERT_STRCASEEQ( expectedTrack["codec"].GetString(), track->codec().c_str() ); if ( expectedTrack.HasMember( "sampleRate" ) ) ASSERT_EQ( expectedTrack["sampleRate"].GetUint(), track->sampleRate() ); if ( expectedTrack.HasMember( "nbChannels" ) ) ASSERT_EQ( expectedTrack["nbChannels"].GetUint(), track->nbChannels() ); if ( expectedTrack.HasMember( "bitrate" ) ) ASSERT_EQ( expectedTrack["bitrate"].GetUint(), track->bitrate() ); } } void Tests::checkMedias(const rapidjson::Value& expectedMedias) { ASSERT_TRUE( expectedMedias.IsArray() ); auto medias = m_ml->files(); for ( auto i = 0u; i < expectedMedias.Size(); ++i ) { const auto& expectedMedia = expectedMedias[i]; ASSERT_TRUE( expectedMedia.HasMember( "title" ) ); const auto expectedTitle = expectedMedia["title"].GetString(); auto it = std::find_if( begin( medias ), end( medias ), [expectedTitle](const MediaPtr& m) { return strcasecmp( expectedTitle, m->title().c_str() ) == 0; }); ASSERT_NE( end( medias ), it ); const auto& media = *it; medias.erase( it ); if ( expectedMedia.HasMember( "nbVideoTracks" ) || expectedMedia.HasMember( "videoTracks" ) ) { auto videoTracks = media->videoTracks(); if ( expectedMedia.HasMember( "nbVideoTracks" ) ) ASSERT_EQ( expectedMedia[ "nbVideoTracks" ].GetUint(), videoTracks.size() ); if ( expectedMedia.HasMember( "videoTracks" ) ) checkVideoTracks( expectedMedia["videoTracks"], videoTracks ); } if ( expectedMedia.HasMember( "nbAudioTracks" ) || expectedMedia.HasMember( "audioTracks" ) ) { auto audioTracks = media->audioTracks(); if ( expectedMedia.HasMember( "nbAudioTracks" ) ) ASSERT_EQ( expectedMedia[ "nbAudioTracks" ].GetUint(), audioTracks.size() ); if ( expectedMedia.HasMember( "audioTracks" ) ) checkAudioTracks( expectedMedia[ "audioTracks" ], audioTracks ); } if ( expectedMedia.HasMember( "snapshotExpected" ) == true ) { auto snapshotExpected = expectedMedia["snapshotExpected"].GetBool(); ASSERT_EQ( !snapshotExpected, media->thumbnail().empty() ); } } } void Tests::checkAlbums( const rapidjson::Value& expectedAlbums, std::vector<AlbumPtr> albums ) { ASSERT_TRUE( expectedAlbums.IsArray() ); ASSERT_EQ( expectedAlbums.Size(), albums.size() ); for ( auto i = 0u; i < expectedAlbums.Size(); ++i ) { const auto& expectedAlbum = expectedAlbums[i]; ASSERT_TRUE( expectedAlbum.HasMember( "title" ) ); // Start by checking if the album was found auto it = std::find_if( begin( albums ), end( albums ), [this, &expectedAlbum](const AlbumPtr& a) { const auto expectedTitle = expectedAlbum["title"].GetString(); if ( strcasecmp( a->title().c_str(), expectedTitle ) != 0 ) return false; if ( expectedAlbum.HasMember( "artist" ) ) { const auto expectedArtist = expectedAlbum["artist"].GetString(); auto artist = a->albumArtist(); if ( artist != nullptr && strcasecmp( artist->name().c_str(), expectedArtist ) != 0 ) return false; } if ( expectedAlbum.HasMember( "artists" ) ) { const auto& expectedArtists = expectedAlbum["artists"]; auto artists = a->artists( false ); if ( expectedArtists.Size() != artists.size() ) return false; for ( auto i = 0u; i < expectedArtists.Size(); ++i ) { auto expectedArtist = expectedArtists[i].GetString(); auto it = std::find_if( begin( artists ), end( artists), [expectedArtist](const ArtistPtr& a) { return strcasecmp( expectedArtist, a->name().c_str() ) == 0; }); if ( it == end( artists ) ) return false; } } if ( expectedAlbum.HasMember( "nbTracks" ) || expectedAlbum.HasMember( "tracks" ) ) { const auto tracks = a->tracks( SortingCriteria::Default, false ); if ( expectedAlbum.HasMember( "nbTracks" ) ) { if ( expectedAlbum["nbTracks"].GetUint() != tracks.size() ) return false; } if ( expectedAlbum.HasMember( "tracks" ) ) { bool tracksOk = false; checkAlbumTracks( a.get(), tracks, expectedAlbum["tracks"], tracksOk ); if ( tracksOk == false ) return false; } } if ( expectedAlbum.HasMember( "releaseYear" ) ) { const auto releaseYear = expectedAlbum["releaseYear"].GetUint(); if ( a->releaseYear() != releaseYear ) return false; } return true; }); ASSERT_NE( end( albums ), it ); albums.erase( it ); } } void Tests::checkArtists(const rapidjson::Value& expectedArtists, std::vector<ArtistPtr> artists) { ASSERT_TRUE( expectedArtists.IsArray() ); ASSERT_EQ( expectedArtists.Size(), artists.size() ); for ( auto i = 0u; i < expectedArtists.Size(); ++i ) { const auto& expectedArtist = expectedArtists[i]; auto it = std::find_if( begin( artists ), end( artists ), [&expectedArtist, this](const ArtistPtr& artist) { if ( expectedArtist.HasMember( "name" ) ) { if ( strcasecmp( expectedArtist["name"].GetString(), artist->name().c_str() ) != 0 ) return false; } if ( expectedArtist.HasMember( "id" ) ) { if ( expectedArtist["id"].GetUint() != artist->id() ) return false; } if ( expectedArtist.HasMember( "nbAlbums" ) || expectedArtist.HasMember( "albums" ) ) { auto albums = artist->albums( SortingCriteria::Default, false ); if ( expectedArtist.HasMember( "nbAlbums" ) ) { if ( albums.size() != expectedArtist["nbAlbums"].GetUint() ) return false; if ( expectedArtist.HasMember( "albums" ) ) checkAlbums( expectedArtist["albums"], albums ); } } if ( expectedArtist.HasMember( "nbTracks" ) ) { auto tracks = artist->media( SortingCriteria::Default, false ); if ( expectedArtist["nbTracks"].GetUint() != tracks.size() ) return false; } return true; }); ASSERT_NE( it, end( artists ) ); } } void Tests::checkAlbumTracks( const IAlbum* album, const std::vector<MediaPtr>& tracks, const rapidjson::Value& expectedTracks, bool& found ) const { found = false; // Don't mandate all tracks to be defined for ( auto i = 0u; i < expectedTracks.Size(); ++i ) { const auto& expectedTrack = expectedTracks[i]; ASSERT_TRUE( expectedTrack.HasMember( "title" ) ); auto expectedTitle = expectedTrack["title"].GetString(); auto it = std::find_if( begin( tracks ), end( tracks ), [expectedTitle](const MediaPtr& media) { return strcasecmp( expectedTitle, media->title().c_str() ) == 0; }); if ( it == end( tracks ) ) return ; const auto track = *it; const auto albumTrack = track->albumTrack(); if ( expectedTrack.HasMember( "number" ) ) { if ( expectedTrack["number"].GetUint() != albumTrack->trackNumber() ) return ; } if ( expectedTrack.HasMember( "artist" ) ) { auto artist = albumTrack->artist(); if ( artist == nullptr ) return ; if ( strlen( expectedTrack["artist"].GetString() ) == 0 && artist->id() != UnknownArtistID ) return ; else if ( strcasecmp( expectedTrack["artist"].GetString(), artist->name().c_str() ) != 0 ) return ; } if ( expectedTrack.HasMember( "genre" ) ) { auto genre = albumTrack->genre(); if ( genre == nullptr || strcasecmp( expectedTrack["genre"].GetString(), genre->name().c_str() ) != 0 ) return ; } if ( expectedTrack.HasMember( "releaseYear" ) ) { if ( track->releaseDate() != expectedTrack["releaseYear"].GetUint() ) return; } if ( expectedTrack.HasMember( "cd" ) ) { if ( expectedTrack["cd"].GetUint() != albumTrack->discNumber() ) return; } // Always check if the album link is correct. This isn't part of finding the proper album, so just fail hard // if the check fails. const auto trackAlbum = albumTrack->album(); ASSERT_NE( nullptr, trackAlbum ); ASSERT_EQ( album->id(), trackAlbum->id() ); } found = true; } <|endoftext|>
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file EvaluateExtatom.cpp * @author Thomas Krennwallner * @date Sat Jan 19 20:18:36 CEST 2008 * * @brief Evaluate external atoms. * * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include "dlvhex/globals.h" #include "dlvhex/EvaluateExtatom.h" #include <sstream> #include <algorithm> DLVHEX_NAMESPACE_BEGIN EvaluateExtatom::EvaluateExtatom(const ExternalAtom* ea, PluginContainer& c) : externalAtom(ea), container(c) { } void EvaluateExtatom::groundInputList(const AtomSet& i, std::vector<Tuple>& inputArguments) const { if (externalAtom->pureGroundInput()) { // take the original input list inputArguments.push_back(externalAtom->getInputTerms()); } else // nonground input list { // // now that we know there are variable input arguments // (otherwise there wouldn't be such a dependency), we can start // constructing the input list from the result of the auxiliary // rules // AtomSet arglist; // // get all the facts from i that match the auxiliary head atom // the arguments of those facts will be our input lists! // i.matchPredicate(externalAtom->getAuxPredicate(), arglist); // // for each auxiliary fact we create a new input list for the // external atom, i.e., we evaluate our external atom n = // |arglist| times. // for (AtomSet::const_iterator argi = arglist.begin(); argi != arglist.end(); ++argi) { inputArguments.push_back(argi->getArguments()); } } } /** * @brief Check the answers returned from the external atom, and * remove ill-formed tuples. * * Check whether the answers in the output list are * (1) ground * (2) conform to the output pattern, i.e., * &rdf[uri](S,rdf:subClassOf,O) shall only return tuples of form * <s, rdf:subClassOf, o>, and not for instance <s, * rdf:subPropertyOf, o>, we have to filter them out (do we?) */ struct CheckOutput : public std::binary_function<const Term, const Term, bool> { bool operator() (const Term& t1, const Term& t2) const { // answers must be ground, otw. programming error in the plugin assert(t1.isInt() || t1.isString() || t1.isSymbol()); // pattern tuple values must coincide if (t2.isInt() || t2.isString() || t2.isSymbol()) { return t1 == t2; } else // t2.isVariable() -> t1 is a variable binding for t2 { return true; } } }; void EvaluateExtatom::evaluate(const AtomSet& i, AtomSet& result) const throw (PluginError) { const std::string& fnc = externalAtom->getFunctionName(); boost::shared_ptr<PluginAtom> pluginAtom = container.getAtom(fnc); if (!pluginAtom) { throw PluginError("Could not find plugin for external atom " + fnc); } std::vector<Tuple> inputArguments; groundInputList(i, inputArguments); // // evaluate external atom for each input tuple we have extracted in // groundInputList() // for (std::vector<Tuple>::const_iterator inputi = inputArguments.begin(); inputi != inputArguments.end(); ++inputi) { AtomSet inputSet; const std::vector<PluginAtom::InputType>& inputtypes = pluginAtom->getInputTypes(); Tuple::const_iterator termit = inputi->begin(); // // extract input set from i according to the input parameters // for (std::vector<PluginAtom::InputType>::const_iterator typeit = inputtypes.begin(); termit != inputi->end() && typeit != inputtypes.end(); ++termit, ++typeit) { // // at this point, the entire input list must be ground! // assert(!termit->isVariable()); switch(*typeit) { case PluginAtom::CONSTANT: // // nothing to do, the constant will be passed directly to the plugin // break; case PluginAtom::PREDICATE: // // collect all facts from interpretation that we need for the input // of the external atom // /// @todo: since matchpredicate doesn't neet the output list, do we /// need that factlist here? i.matchPredicate(termit->getString(), inputSet); break; default: // // not a specified type - worst case, now we have to pass the // entire interpretation. we simply overwrite a previously // created inputSet, because there can't be specified input // types after this one anyway - TUPLE must always be after // CONSTANT and PREDICATE, see PluginAtom! // //inputSet = i; break; } } // // build a query object: // - interpretation // - input list // - actual arguments of the external atom (maybe it is partly ground, // then the plugin can be more efficient) // PluginAtom::Query query(inputSet, *inputi, externalAtom->getArguments()); PluginAtom::Answer answer; try { if( 1 == Globals::Instance()->getOption("UseExtAtomCache") ) pluginAtom->retrieveCached(query, answer); else pluginAtom->retrieve(query, answer); } catch (PluginError& e) { std::ostringstream atomstr; atomstr << externalAtom->getFunctionName() << "[" << externalAtom->getInputTerms() << "](" << externalAtom->getArguments() << ")" << " in line " << externalAtom->getLine(); e.setContext(atomstr.str()); throw e; } // // build result with the replacement name for each answer tuple // boost::shared_ptr<std::vector<Tuple> > answers = answer.getTuples(); for (std::vector<Tuple>::const_iterator s = answers->begin(); s != answers->end(); ++s) { if (s->size() != externalAtom->getArguments().size()) { throw PluginError("External atom " + externalAtom->getFunctionName() + " returned tuple of incompatible size."); } // check if this answer from pluginatom conforms to the external atom's arguments std::pair<Tuple::const_iterator,Tuple::const_iterator> mismatched = std::mismatch(s->begin(), s->end(), externalAtom->getArguments().begin(), CheckOutput() ); if (mismatched.first == s->end()) // no mismatch found -> add this tuple to the result { // the replacement atom contains both the input and the output list! // (*inputi must be ground here, since it comes from // groundInputList(i, inputArguments)) Tuple resultTuple(*inputi); // add output list resultTuple.insert(resultTuple.end(), s->begin(), s->end()); // setup new atom with appropriate replacement name AtomPtr ap(new Atom(externalAtom->getReplacementName(), resultTuple)); result.insert(ap); } else { // found a mismatch, ignore this answer tuple } } } } DLVHEX_NAMESPACE_END // vim:ts=8: // Local Variables: // mode: C++ // End: <commit_msg>added benchmarking<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file EvaluateExtatom.cpp * @author Thomas Krennwallner * @date Sat Jan 19 20:18:36 CEST 2008 * * @brief Evaluate external atoms. * * */ #ifdef HAVE_CONFIG_H #include "config.h" // activate benchmarking if activated by configure option --enable-debug # ifdef DLVHEX_DEBUG # define DLVHEX_BENCHMARK # endif #endif // HAVE_CONFIG_H #include "dlvhex/globals.h" #include "dlvhex/EvaluateExtatom.h" #include "dlvhex/Benchmarking.h" #include <sstream> #include <algorithm> DLVHEX_NAMESPACE_BEGIN EvaluateExtatom::EvaluateExtatom(const ExternalAtom* ea, PluginContainer& c) : externalAtom(ea), container(c) { } void EvaluateExtatom::groundInputList(const AtomSet& i, std::vector<Tuple>& inputArguments) const { if (externalAtom->pureGroundInput()) { // take the original input list inputArguments.push_back(externalAtom->getInputTerms()); } else // nonground input list { // // now that we know there are variable input arguments // (otherwise there wouldn't be such a dependency), we can start // constructing the input list from the result of the auxiliary // rules // AtomSet arglist; // // get all the facts from i that match the auxiliary head atom // the arguments of those facts will be our input lists! // i.matchPredicate(externalAtom->getAuxPredicate(), arglist); // // for each auxiliary fact we create a new input list for the // external atom, i.e., we evaluate our external atom n = // |arglist| times. // for (AtomSet::const_iterator argi = arglist.begin(); argi != arglist.end(); ++argi) { inputArguments.push_back(argi->getArguments()); } } } /** * @brief Check the answers returned from the external atom, and * remove ill-formed tuples. * * Check whether the answers in the output list are * (1) ground * (2) conform to the output pattern, i.e., * &rdf[uri](S,rdf:subClassOf,O) shall only return tuples of form * <s, rdf:subClassOf, o>, and not for instance <s, * rdf:subPropertyOf, o>, we have to filter them out (do we?) */ struct CheckOutput : public std::binary_function<const Term, const Term, bool> { bool operator() (const Term& t1, const Term& t2) const { // answers must be ground, otw. programming error in the plugin assert(t1.isInt() || t1.isString() || t1.isSymbol()); // pattern tuple values must coincide if (t2.isInt() || t2.isString() || t2.isSymbol()) { return t1 == t2; } else // t2.isVariable() -> t1 is a variable binding for t2 { return true; } } }; void EvaluateExtatom::evaluate(const AtomSet& i, AtomSet& result) const throw (PluginError) { const std::string& fnc = externalAtom->getFunctionName(); boost::shared_ptr<PluginAtom> pluginAtom = container.getAtom(fnc); if (!pluginAtom) { throw PluginError("Could not find plugin for external atom " + fnc); } std::vector<Tuple> inputArguments; groundInputList(i, inputArguments); // // evaluate external atom for each input tuple we have extracted in // groundInputList() // for (std::vector<Tuple>::const_iterator inputi = inputArguments.begin(); inputi != inputArguments.end(); ++inputi) { AtomSet inputSet; const std::vector<PluginAtom::InputType>& inputtypes = pluginAtom->getInputTypes(); Tuple::const_iterator termit = inputi->begin(); // // extract input set from i according to the input parameters // { DLVHEX_BENCHMARK_REGISTER_AND_SCOPE(xatomreplacement,"EvaluateExtatom::extractInp"); for (std::vector<PluginAtom::InputType>::const_iterator typeit = inputtypes.begin(); termit != inputi->end() && typeit != inputtypes.end(); ++termit, ++typeit) { // // at this point, the entire input list must be ground! // assert(!termit->isVariable()); switch(*typeit) { case PluginAtom::CONSTANT: // // nothing to do, the constant will be passed directly to the plugin // break; case PluginAtom::PREDICATE: // // collect all facts from interpretation that we need for the input // of the external atom // /// @todo: since matchpredicate doesn't neet the output list, do we /// need that factlist here? i.matchPredicate(termit->getString(), inputSet); break; default: // // not a specified type - worst case, now we have to pass the // entire interpretation. we simply overwrite a previously // created inputSet, because there can't be specified input // types after this one anyway - TUPLE must always be after // CONSTANT and PREDICATE, see PluginAtom! // //inputSet = i; break; } } } // // build a query object: // - interpretation // - input list // - actual arguments of the external atom (maybe it is partly ground, // then the plugin can be more efficient) // PluginAtom::Query query(inputSet, *inputi, externalAtom->getArguments()); PluginAtom::Answer answer; try { if( 1 == Globals::Instance()->getOption("UseExtAtomCache") ) { DLVHEX_BENCHMARK_REGISTER_AND_SCOPE(xatomrc,"pluginAtom->retrieveCached"); pluginAtom->retrieveCached(query, answer); } else { DLVHEX_BENCHMARK_REGISTER_AND_SCOPE(xatomr,"pluginAtom->retrieve"); pluginAtom->retrieve(query, answer); } } catch (PluginError& e) { std::ostringstream atomstr; atomstr << externalAtom->getFunctionName() << "[" << externalAtom->getInputTerms() << "](" << externalAtom->getArguments() << ")" << " in line " << externalAtom->getLine(); e.setContext(atomstr.str()); throw e; } // // build result with the replacement name for each answer tuple // boost::shared_ptr<std::vector<Tuple> > answers = answer.getTuples(); { DLVHEX_BENCHMARK_REGISTER_AND_SCOPE(xatomreplacement,"EvaluateExtatom::buildReplAtoms"); for (std::vector<Tuple>::const_iterator s = answers->begin(); s != answers->end(); ++s) { if (s->size() != externalAtom->getArguments().size()) { throw PluginError("External atom " + externalAtom->getFunctionName() + " returned tuple of incompatible size."); } // check if this answer from pluginatom conforms to the external atom's arguments std::pair<Tuple::const_iterator,Tuple::const_iterator> mismatched = std::mismatch(s->begin(), s->end(), externalAtom->getArguments().begin(), CheckOutput() ); if (mismatched.first == s->end()) // no mismatch found -> add this tuple to the result { // the replacement atom contains both the input and the output list! // (*inputi must be ground here, since it comes from // groundInputList(i, inputArguments)) Tuple resultTuple(*inputi); // add output list resultTuple.insert(resultTuple.end(), s->begin(), s->end()); // setup new atom with appropriate replacement name AtomPtr ap(new Atom(externalAtom->getReplacementName(), resultTuple)); result.insert(ap); } else { // found a mismatch, ignore this answer tuple } } } } } DLVHEX_NAMESPACE_END // vim:ts=8: // Local Variables: // mode: C++ // End: <|endoftext|>
<commit_before>/* * TestLARObj.cpp * * Created on: 08 apr 2016 * Author: Salvati Danilo * License: MIT License https://opensource.org/licenses/MIT * */ #include "catch.hpp" #include "IOInterfaces/LARObj.h" #include <sys/stat.h> TEST_CASE( "Read and write Obj files", "[LARObj]" ) { LAR::IO::LARObj larObj; SECTION( "Read obj file" ){ const std::string filePath1 = "test/resources/obj/test1obj.obj"; // For Eclipse testing const std::string filePath2 = "../test/resources/obj/test1obj.obj"; // For Travis testing std::pair<std::deque<Eigen::Vector3f>, std::deque<Eigen::SparseMatrix<int, Eigen::RowMajor, int> > > model; struct stat buffer; if (stat (filePath1.c_str(), &buffer) == 0) { model = larObj.readModel(filePath1); } else { model = larObj.readModel(filePath2); } std::deque<Eigen::Vector3f> vectorList = model.first; Eigen::SparseMatrix<int, Eigen::RowMajor, int> facesMatrix = model.second[0]; REQUIRE(vectorList.size() == 8); REQUIRE(vectorList[0] == Eigen::Vector3f(0,0,0)); REQUIRE(vectorList[1] == Eigen::Vector3f(1,0,0)); REQUIRE(vectorList[2] == Eigen::Vector3f(0,1,0)); REQUIRE(vectorList[3] == Eigen::Vector3f(1,1,0)); REQUIRE(vectorList[4] == Eigen::Vector3f(0,0,1)); REQUIRE(vectorList[5] == Eigen::Vector3f(1,0,1)); REQUIRE(vectorList[6] == Eigen::Vector3f(0,1,1)); REQUIRE(vectorList[7] == Eigen::Vector3f(1,1,1)); REQUIRE(facesMatrix.nonZeros() == 12); REQUIRE(facesMatrix.rows() == 3); REQUIRE(facesMatrix.cols() == 8); REQUIRE(facesMatrix.coeff(0,0) == 1); REQUIRE(facesMatrix.coeff(0,1) == 1); REQUIRE(facesMatrix.coeff(0,2) == 1); REQUIRE(facesMatrix.coeff(0,3) == 1); REQUIRE(facesMatrix.coeff(1,4) == 1); REQUIRE(facesMatrix.coeff(1,5) == 1); REQUIRE(facesMatrix.coeff(1,6) == 1); REQUIRE(facesMatrix.coeff(1,7) == 1); REQUIRE(facesMatrix.coeff(2,0) == 1); REQUIRE(facesMatrix.coeff(2,1) == 1); REQUIRE(facesMatrix.coeff(2,4) == 1); REQUIRE(facesMatrix.coeff(2,5) == 1); } SECTION( "Write obj file" ){ Eigen::Vector3f vector1 = Eigen::Vector3f(0,0,0); Eigen::Vector3f vector2 = Eigen::Vector3f(0,1,0); Eigen::Vector3f vector3 = Eigen::Vector3f(1,1,0); Eigen::Vector3f vector4 = Eigen::Vector3f(1,0,0); Eigen::Vector3f vector5 = Eigen::Vector3f(2,0,0); Eigen::Vector3f vector6 = Eigen::Vector3f(2,1,0); Eigen::Vector3f vectors[] = {vector1, vector2, vector3, vector4, vector5, vector6}; std::deque<Eigen::Vector3f> verticesList(vectors, vectors + sizeof(vectors) / sizeof(Eigen::Vector3f)); Eigen::SparseMatrix<int, Eigen::RowMajor, int> matrix(2,6); matrix.coeffRef(0,0) = 1; matrix.coeffRef(0,1) = 1; matrix.coeffRef(0,2) = 1; matrix.coeffRef(0,3) = 1; matrix.coeffRef(1,2) == 1; matrix.coeffRef(1,3) == 1; matrix.coeffRef(1,4) == 1; matrix.coeffRef(1,5) == 1; std::deque<Eigen::SparseMatrix<int, Eigen::RowMajor, int> > topologicalRelationships; topologicalRelationships.push_back(matrix); larObj.writeModel(verticesList, topologicalRelationships, "prova.obj"); } } <commit_msg>Added test for obj writing<commit_after>/* * TestLARObj.cpp * * Created on: 08 apr 2016 * Author: Salvati Danilo * License: MIT License https://opensource.org/licenses/MIT * */ #include "catch.hpp" #include "IOInterfaces/LARObj.h" #include <sys/stat.h> TEST_CASE( "Read and write Obj files", "[LARObj]" ) { LAR::IO::LARObj larObj; SECTION( "Read obj file" ){ const std::string filePath1 = "test/resources/obj/test1obj.obj"; // For Eclipse testing const std::string filePath2 = "../test/resources/obj/test1obj.obj"; // For Travis testing std::pair<std::deque<Eigen::Vector3f>, std::deque<Eigen::SparseMatrix<int, Eigen::RowMajor, int> > > model; struct stat buffer; if (stat (filePath1.c_str(), &buffer) == 0) { model = larObj.readModel(filePath1); } else { model = larObj.readModel(filePath2); } std::deque<Eigen::Vector3f> vectorList = model.first; Eigen::SparseMatrix<int, Eigen::RowMajor, int> facesMatrix = model.second[0]; REQUIRE(vectorList.size() == 8); REQUIRE(vectorList[0] == Eigen::Vector3f(0,0,0)); REQUIRE(vectorList[1] == Eigen::Vector3f(1,0,0)); REQUIRE(vectorList[2] == Eigen::Vector3f(0,1,0)); REQUIRE(vectorList[3] == Eigen::Vector3f(1,1,0)); REQUIRE(vectorList[4] == Eigen::Vector3f(0,0,1)); REQUIRE(vectorList[5] == Eigen::Vector3f(1,0,1)); REQUIRE(vectorList[6] == Eigen::Vector3f(0,1,1)); REQUIRE(vectorList[7] == Eigen::Vector3f(1,1,1)); REQUIRE(facesMatrix.nonZeros() == 12); REQUIRE(facesMatrix.rows() == 3); REQUIRE(facesMatrix.cols() == 8); REQUIRE(facesMatrix.coeff(0,0) == 1); REQUIRE(facesMatrix.coeff(0,1) == 1); REQUIRE(facesMatrix.coeff(0,2) == 1); REQUIRE(facesMatrix.coeff(0,3) == 1); REQUIRE(facesMatrix.coeff(1,4) == 1); REQUIRE(facesMatrix.coeff(1,5) == 1); REQUIRE(facesMatrix.coeff(1,6) == 1); REQUIRE(facesMatrix.coeff(1,7) == 1); REQUIRE(facesMatrix.coeff(2,0) == 1); REQUIRE(facesMatrix.coeff(2,1) == 1); REQUIRE(facesMatrix.coeff(2,4) == 1); REQUIRE(facesMatrix.coeff(2,5) == 1); } SECTION( "Write obj file" ){ Eigen::Vector3f vector1 = Eigen::Vector3f(0,0,0); Eigen::Vector3f vector2 = Eigen::Vector3f(0,1,0); Eigen::Vector3f vector3 = Eigen::Vector3f(1,1,0); Eigen::Vector3f vector4 = Eigen::Vector3f(1,0,0); Eigen::Vector3f vector5 = Eigen::Vector3f(2,0,0); Eigen::Vector3f vector6 = Eigen::Vector3f(2,1,0); Eigen::Vector3f vectors[] = {vector1, vector2, vector3, vector4, vector5, vector6}; std::deque<Eigen::Vector3f> verticesList(vectors, vectors + sizeof(vectors) / sizeof(Eigen::Vector3f)); Eigen::SparseMatrix<int, Eigen::RowMajor, int> matrix(2,6); matrix.coeffRef(0,0) = 1; matrix.coeffRef(0,1) = 1; matrix.coeffRef(0,2) = 1; matrix.coeffRef(0,3) = 1; matrix.coeffRef(1,2) = 1; matrix.coeffRef(1,3) = 1; matrix.coeffRef(1,4) = 1; matrix.coeffRef(1,5) = 1; std::deque<Eigen::SparseMatrix<int, Eigen::RowMajor, int> > topologicalRelationships; topologicalRelationships.push_back(matrix); larObj.writeModel(verticesList, topologicalRelationships, "model.obj"); std::pair<std::deque<Eigen::Vector3f>, std::deque<Eigen::SparseMatrix<int, Eigen::RowMajor, int> > > model = larObj.readModel("model.obj"); REQUIRE(model.first == verticesList); Eigen::SparseMatrix<int, Eigen::RowMajor, int> faces = model.second[0]; REQUIRE(faces.nonZeros() == matrix.nonZeros()); REQUIRE(faces.rows() == matrix.rows()); REQUIRE(faces.cols() == matrix.cols()); REQUIRE(faces.coeff(0,0) == matrix.coeff(0,0)); REQUIRE(faces.coeff(0,1) == matrix.coeff(0,1)); REQUIRE(faces.coeff(0,2) == matrix.coeff(0,2)); REQUIRE(faces.coeff(0,3) == matrix.coeff(0,3)); REQUIRE(faces.coeff(1,4) == matrix.coeff(1,4)); REQUIRE(faces.coeff(1,5) == matrix.coeff(1,5)); REQUIRE(faces.coeff(1,6) == matrix.coeff(1,6)); REQUIRE(faces.coeff(1,7) == matrix.coeff(1,7)); remove("model.obj"); } } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 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" #include "conv_test.hpp" //Note: The results of the tests have been validated with one of (octave/matlab/matlab) // conv_2d_valid_multi TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/1", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 3, 3> I = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0}; etl::fast_matrix<Z, 2, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 2.0, 0.0, 0.5, 0.5}; etl::fast_matrix<Z, 2, 2, 2> c_1; etl::fast_matrix<Z, 2, 2, 2> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/2", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 3, 3> I = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0}; etl::fast_matrix<Z, 2, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1}; etl::fast_matrix<Z, 2, 2, 2> c_1; etl::fast_matrix<Z, 2, 2, 2> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/3", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 3, 3> I = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0}; etl::fast_matrix<Z, 3, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1, 0.0, -1.0, 1.0, 1.0}; etl::fast_matrix<Z, 3, 2, 2> c_1; etl::fast_matrix<Z, 3, 2, 2> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); c_1(2) = conv_2d_valid(I, K(2)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/4", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 5, 5> I(etl::magic<Z>(5)); etl::fast_matrix<Z, 3, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1, 0.0, -1.0, 1.0, 1.0}; etl::fast_matrix<Z, 3, 4, 4> c_1; etl::fast_matrix<Z, 3, 4, 4> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); c_1(2) = conv_2d_valid(I, K(2)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/5", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 5, 5> I(etl::magic<Z>(5)); etl::fast_matrix<Z, 3, 3, 3> K; K(0) = etl::magic<Z>(3); K(1) = etl::magic<Z>(3) * 2.0; K(2) = etl::magic<Z>(3) * etl::magic<Z>(3); etl::fast_matrix<Z, 3, 3, 3> c_1; etl::fast_matrix<Z, 3, 3, 3> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); c_1(2) = conv_2d_valid(I, K(2)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } //TODO Add tests for conv_2d_valid_multi when neithe rthe kernel nor //the image are square. <commit_msg>New tests for conv_2d_valid_multi<commit_after>//======================================================================= // Copyright (c) 2014-2016 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" #include "conv_test.hpp" //Note: The results of the tests have been validated with one of (octave/matlab/matlab) // conv_2d_valid_multi TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/1", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 3, 3> I = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0}; etl::fast_matrix<Z, 2, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 2.0, 0.0, 0.5, 0.5}; etl::fast_matrix<Z, 2, 2, 2> c_1; etl::fast_matrix<Z, 2, 2, 2> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/2", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 3, 3> I = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0}; etl::fast_matrix<Z, 2, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1}; etl::fast_matrix<Z, 2, 2, 2> c_1; etl::fast_matrix<Z, 2, 2, 2> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/3", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 3, 3> I = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0}; etl::fast_matrix<Z, 3, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1, 0.0, -1.0, 1.0, 1.0}; etl::fast_matrix<Z, 3, 2, 2> c_1; etl::fast_matrix<Z, 3, 2, 2> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); c_1(2) = conv_2d_valid(I, K(2)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/4", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 5, 5> I(etl::magic<Z>(5)); etl::fast_matrix<Z, 3, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1, 0.0, -1.0, 1.0, 1.0}; etl::fast_matrix<Z, 3, 4, 4> c_1; etl::fast_matrix<Z, 3, 4, 4> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); c_1(2) = conv_2d_valid(I, K(2)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/5", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 5, 5> I(etl::magic<Z>(5)); etl::fast_matrix<Z, 3, 3, 3> K; K(0) = etl::magic<Z>(3); K(1) = etl::magic<Z>(3) * 2.0; K(2) = etl::magic<Z>(3) * etl::magic<Z>(3); etl::fast_matrix<Z, 3, 3, 3> c_1; etl::fast_matrix<Z, 3, 3, 3> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); c_1(2) = conv_2d_valid(I, K(2)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/6", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 7, 7> I(etl::magic<Z>(7)); etl::fast_matrix<Z, 3, 5, 3> K; K(0) = 1.5 * etl::sequence_generator(10); K(0) = -2.5 * etl::sequence_generator(5); K(0) = 1.3 * etl::sequence_generator(12); etl::fast_matrix<Z, 3, 3, 5> c_1; etl::fast_matrix<Z, 3, 3, 5> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); c_1(2) = conv_2d_valid(I, K(2)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/7", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 9, 7> I(0.5 * etl::sequence_generator(42)); etl::fast_matrix<Z, 3, 5, 5> K; K(0) = 1.5 * etl::sequence_generator(10); K(0) = -2.5 * etl::sequence_generator(5); K(0) = 1.3 * etl::sequence_generator(12); etl::fast_matrix<Z, 3, 5, 3> c_1; etl::fast_matrix<Z, 3, 5, 3> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); c_1(2) = conv_2d_valid(I, K(2)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/8", "[conv] [conv2]", Z, double, float) { etl::fast_matrix<Z, 9, 7> I(0.5 * etl::sequence_generator(42)); etl::fast_matrix<Z, 3, 3, 5> K; K(0) = 1.5 * etl::sequence_generator(10); K(0) = -1.5 * etl::sequence_generator(5); K(0) = 1.3 * etl::sequence_generator(12); etl::fast_matrix<Z, 3, 7, 3> c_1; etl::fast_matrix<Z, 3, 7, 3> c_2; c_1(0) = conv_2d_valid(I, K(0)); c_1(1) = conv_2d_valid(I, K(1)); c_1(2) = conv_2d_valid(I, K(2)); conv_2d_valid_multi(I, K, c_2); for (std::size_t i = 0; i < etl::size(c_1); ++i) { REQUIRE(c_1[i] == Approx(c_2[i])); } } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "kangaru/kangaru.hpp" TEST_CASE("Injected singles are the same returned by the container", "[dependency]") { struct Service1 {}; struct Service2 { Service2() = default; Service2(Service1& s) : s1{&s} {} Service1* s1 = nullptr; }; struct Definition1 : kgr::single_service<Service1> {}; struct Definition2 : kgr::service<Service2, kgr::dependency<Definition1>> {}; kgr::container c; REQUIRE(c.service<Definition2>().s1 == &c.service<Definition1>()); } TEST_CASE("Injected arguments are sent correctly to the constructor", "[dependency]") { struct Service1 {}; struct Service2 { Service2() = default; Service2(Service1& s) : s1{&s} {} Service1* s1 = nullptr; }; struct Definition1 : kgr::single_service<Service1> {}; struct Definition2 { Definition2(kgr::in_place_t) {} Definition2(kgr::in_place_t, Service1& dep) : service{dep} {} Service2 forward() { return std::move(service); } static auto construct(kgr::inject_t<Definition1> d1) -> decltype(kgr::inject(d1.forward())) { return kgr::inject(d1.forward()); } Service2 service; }; kgr::container c; REQUIRE(c.service<Definition2>().s1 == &c.service<Definition1>()); } TEST_CASE("Injected arguments can be single and non single", "[dependency]") { static bool constructor_called = false; struct Service1 {}; struct Service2 {}; struct Service3 { Service3() = default; Service3(Service1& s, Service2) : s1{&s} { constructor_called = true; } Service1* s1 = nullptr; }; struct Definition1 : kgr::single_service<Service1> {}; struct Definition2 : kgr::service<Service2> {}; struct Definition3 { Definition3(kgr::in_place_t, Service1& dep1, Service2 dep2) : service{dep1, std::move(dep2)} {} Service3 forward() { return std::move(service); } static auto construct(kgr::inject_t<Definition1> d1, kgr::inject_t<Definition2> d2) -> decltype(kgr::inject(d1.forward(), d2.forward())) { return kgr::inject(d1.forward(), d2.forward()); } Service3 service; }; (void) kgr::container {}.service<Definition3>(); REQUIRE(constructor_called); } TEST_CASE("Container injects arguments recursively", "[dependency]") { static bool service1_constructed; static bool service2_constructed; static bool service3_one_constructed; static bool service3_two_constructed; static bool service4_constructed; service1_constructed = false; service2_constructed = false; service3_one_constructed = false; service3_two_constructed = false; service4_constructed = false; struct Service1 { Service1() { service1_constructed = true; } }; struct Service2 { Service2() = default; Service2(Service1) { service2_constructed = true; } }; struct Service3 { Service3() = default; Service3(Service1, Service2) { service3_two_constructed = true; } Service3(Service2) { service3_one_constructed = true; } }; struct Service4 { Service4() = default; Service4(Service3) { service4_constructed = true; } }; struct Definition1 : kgr::service<Service1> {}; struct Definition2 : kgr::service<Service2, kgr::dependency<Definition1>> {}; struct Definition3One : kgr::service<Service3, kgr::dependency<Definition2>> {}; struct Definition3Two : kgr::service<Service3, kgr::dependency<Definition1, Definition2>> {}; struct Definition4 : kgr::service<Service4, kgr::dependency<Definition3Two>> {}; SECTION("Injected service can have dependencies") { (void) kgr::container {}.service<Definition3One>(); CHECK(service1_constructed); CHECK(service2_constructed); CHECK(!service3_two_constructed); CHECK(!service4_constructed); REQUIRE(service3_one_constructed); } SECTION("Injected service can have multiple dependencies") { (void) kgr::container {}.service<Definition4>(); CHECK(service1_constructed); CHECK(service2_constructed); CHECK(!service3_one_constructed); CHECK(service3_two_constructed); REQUIRE(service4_constructed); } } <commit_msg>Removed spaces<commit_after>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "kangaru/kangaru.hpp" TEST_CASE("Injected singles are the same returned by the container", "[dependency]") { struct Service1 {}; struct Service2 { Service2() = default; Service2(Service1& s) : s1{&s} {} Service1* s1 = nullptr; }; struct Definition1 : kgr::single_service<Service1> {}; struct Definition2 : kgr::service<Service2, kgr::dependency<Definition1>> {}; kgr::container c; REQUIRE(c.service<Definition2>().s1 == &c.service<Definition1>()); } TEST_CASE("Injected arguments are sent correctly to the constructor", "[dependency]") { struct Service1 {}; struct Service2 { Service2() = default; Service2(Service1& s) : s1{&s} {} Service1* s1 = nullptr; }; struct Definition1 : kgr::single_service<Service1> {}; struct Definition2 { Definition2(kgr::in_place_t) {} Definition2(kgr::in_place_t, Service1& dep) : service{dep} {} Service2 forward() { return std::move(service); } static auto construct(kgr::inject_t<Definition1> d1) -> decltype(kgr::inject(d1.forward())) { return kgr::inject(d1.forward()); } Service2 service; }; kgr::container c; REQUIRE(c.service<Definition2>().s1 == &c.service<Definition1>()); } TEST_CASE("Injected arguments can be single and non single", "[dependency]") { static bool constructor_called = false; struct Service1 {}; struct Service2 {}; struct Service3 { Service3() = default; Service3(Service1& s, Service2) : s1{&s} { constructor_called = true; } Service1* s1 = nullptr; }; struct Definition1 : kgr::single_service<Service1> {}; struct Definition2 : kgr::service<Service2> {}; struct Definition3 { Definition3(kgr::in_place_t, Service1& dep1, Service2 dep2) : service{dep1, std::move(dep2)} {} Service3 forward() { return std::move(service); } static auto construct(kgr::inject_t<Definition1> d1, kgr::inject_t<Definition2> d2) -> decltype(kgr::inject(d1.forward(), d2.forward())) { return kgr::inject(d1.forward(), d2.forward()); } Service3 service; }; (void) kgr::container{}.service<Definition3>(); REQUIRE(constructor_called); } TEST_CASE("Container injects arguments recursively", "[dependency]") { static bool service1_constructed; static bool service2_constructed; static bool service3_one_constructed; static bool service3_two_constructed; static bool service4_constructed; service1_constructed = false; service2_constructed = false; service3_one_constructed = false; service3_two_constructed = false; service4_constructed = false; struct Service1 { Service1() { service1_constructed = true; } }; struct Service2 { Service2() = default; Service2(Service1) { service2_constructed = true; } }; struct Service3 { Service3() = default; Service3(Service1, Service2) { service3_two_constructed = true; } Service3(Service2) { service3_one_constructed = true; } }; struct Service4 { Service4() = default; Service4(Service3) { service4_constructed = true; } }; struct Definition1 : kgr::service<Service1> {}; struct Definition2 : kgr::service<Service2, kgr::dependency<Definition1>> {}; struct Definition3One : kgr::service<Service3, kgr::dependency<Definition2>> {}; struct Definition3Two : kgr::service<Service3, kgr::dependency<Definition1, Definition2>> {}; struct Definition4 : kgr::service<Service4, kgr::dependency<Definition3Two>> {}; SECTION("Injected service can have dependencies") { (void) kgr::container{}.service<Definition3One>(); CHECK(service1_constructed); CHECK(service2_constructed); CHECK(!service3_two_constructed); CHECK(!service4_constructed); REQUIRE(service3_one_constructed); } SECTION("Injected service can have multiple dependencies") { (void) kgr::container{}.service<Definition4>(); CHECK(service1_constructed); CHECK(service2_constructed); CHECK(!service3_one_constructed); CHECK(service3_two_constructed); REQUIRE(service4_constructed); } } <|endoftext|>
<commit_before>#include <iostream> #include <gtest/gtest.h> #include <thread> #include <chrono> #include <msgrpc/thrift_struct/thrift_codec.h> using namespace std; using namespace std::chrono; #include "demo/demo_api_declare.h" #if 0 #define ___methods_of_interface___IBuzzMath(_, ...) \ _(1, ResponseBar, negative_fields, RequestFoo, __VA_ARGS__)\ _(2, ResponseBar, plus1_to_fields, RequestFoo, __VA_ARGS__) ___as_interface(IBuzzMath, __with_interface_id(1)) #endif //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { template <typename T> struct Ret {}; typedef unsigned short msg_id_t; typedef unsigned short service_id_t; //TODO: how to deal with different service id types struct MsgChannel { virtual uint32_t send_msg(const service_id_t& remote_service_id, msg_id_t msg_id, const char* buf, size_t len) const = 0; }; struct Config { void initWith(MsgChannel* msg_channel, msgrpc::msg_id_t request_msg_id, msgrpc::msg_id_t response_msg_id) { instance().msg_channel_ = msg_channel; request_msg_id_ = request_msg_id; response_msg_id_ = response_msg_id; } static inline Config& instance() { static thread_local Config instance; return instance; } MsgChannel* msg_channel_; msg_id_t request_msg_id_; msg_id_t response_msg_id_; }; } namespace msgrpc { /*TODO: using static_assert to assure name length of interface and method*/ const size_t k_max_interface_name_len = 40; const size_t k_max_method_name_len = 40; struct MsgHeader { unsigned char msgrpc_version_; unsigned char method_index_in_interface_; unsigned short interface_index_in_service_; }; struct Request : MsgHeader { }; struct RpcInvokeHandler { void handleInvoke(const MsgHeader& msg_header) { } }; } //////////////////////////////////////////////////////////////////////////////// #include "test_util/UdpChannel.h" namespace demo { const msgrpc::msg_id_t k_msgrpc_request_msg_id = 101; const msgrpc::msg_id_t k_msgrpc_response_msg_id = 102; struct UdpMsgChannel : msgrpc::MsgChannel { virtual uint32_t send_msg(const msgrpc::service_id_t& remote_service_id, msgrpc::msg_id_t msg_id, const char* buf, size_t len) const { size_t msg_len_with_msgid = sizeof(msgrpc::msg_id_t) + len; char* mem = (char*)malloc(msg_len_with_msgid); if (mem) { *(msgrpc::msg_id_t*)(mem) = msg_id; memcpy(mem + sizeof(msgrpc::msg_id_t), buf, len); cout << "send msg len: " << msg_len_with_msgid << endl; g_msg_channel->send_msg_to_remote(string(mem, msg_len_with_msgid), udp::endpoint(udp::v4(), remote_service_id)); free(mem); } else { cout << "send msg failed: allocation failure." << endl; } return 0; } }; } //////////////////////////////////////////////////////////////////////////////// using namespace demo; const msgrpc::service_id_t k_remote_service_id = 2222; const msgrpc::service_id_t k_loacl_service_id = 3333; struct IBuzzMath { virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&) = 0; virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&) = 0; }; //////////////////////////////////////////////////////////////////////////////// struct IBuzzMathStub : IBuzzMath { virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&); virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&); }; msgrpc::Ret<ResponseBar> IBuzzMathStub::negative_fields(const RequestFoo& req) { uint8_t* pbuf; uint32_t len; if (!ThriftEncoder::encode(req, &pbuf, &len)) { /*TODO: how to do with log*/ cout << "encode failed." << endl; return msgrpc::Ret<ResponseBar>(); } //TODO: find k_remote_service_id by interface name "IBuzzMath" size_t msg_len_with_header = sizeof(msgrpc::MsgHeader) + len; char* mem = (char*)malloc(msg_len_with_header); if (!mem) { cout << "alloc mem failed, during sending rpc request." << endl; return msgrpc::Ret<ResponseBar>(); } auto header = (msgrpc::MsgHeader*)mem; header->msgrpc_version_ = 0; header->interface_index_in_service_ = 1; header->method_index_in_interface_ = 1; memcpy(header + 1, (const char*)pbuf, len); cout << "stub sending msg with length: " << msg_len_with_header << endl; msgrpc::Config::instance().msg_channel_->send_msg(k_remote_service_id, k_msgrpc_request_msg_id, mem, msg_len_with_header); free(mem); return msgrpc::Ret<ResponseBar>(); } msgrpc::Ret<ResponseBar> IBuzzMathStub::plus1_to_fields(const RequestFoo& req) { return msgrpc::Ret<ResponseBar>(); } void local_service() { std::this_thread::sleep_for(std::chrono::seconds(1)); msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id); UdpChannel channel(k_loacl_service_id, [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) { if (0 == strcmp(msg, "init")) { IBuzzMathStub buzzMath; RequestFoo foo; foo.fooa = 97; foo.__set_foob(98); buzzMath.negative_fields(foo); } else { cout << "local received msg: " << string(msg, len) << endl; channel.close(); } } ); } //////////////////////////////////////////////////////////////////////////////// struct IBuzzMathImpl { void onRpcInvoke(); //todo:remote_id virtual ResponseBar negative_fields(const RequestFoo&); virtual ResponseBar plus1_to_fields(const RequestFoo&); }; void IBuzzMathImpl::onRpcInvoke() { } ResponseBar IBuzzMathImpl::negative_fields(const RequestFoo& req) { ResponseBar bar; /*TODO:change bar to inout parameter*/ bar.__set_bara(req.get_foob()); if (req.__isset.foob) { bar.__set_barb(req.fooa); } return bar; } ResponseBar IBuzzMathImpl::plus1_to_fields(const RequestFoo& req) { ResponseBar bar; bar.__set_bara(1 + req.fooa); if (req.__isset.foob) { bar.__set_barb(1 + req.get_foob()); } return bar; } void remote_service() { msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id); UdpChannel channel(k_remote_service_id, [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) { if (0 == strcmp(msg, "init")) { return; } cout << "remote received msg with length: " << len << endl; /*TODO: should first check msg_id == msgrpc_msg_request_id */ if (len < sizeof(msgrpc::MsgHeader)) { cout << "invalid msg: without sufficient msg header info." << endl; return; } cout << (int)((msgrpc::MsgHeader*)(msg))->msgrpc_version_ << endl; cout << (int)((msgrpc::MsgHeader*)(msg))->interface_index_in_service_ << endl; cout << (int)((msgrpc::MsgHeader*)(msg))->method_index_in_interface_ << endl; msg += sizeof(msgrpc::MsgHeader); RequestFoo req; if (!ThriftDecoder::decode(req, (uint8_t*)msg, len)) { cout << "decode failed on remote side." << endl; channel.close(); return; } IBuzzMathImpl buzzMath; ResponseBar bar = buzzMath.negative_fields(req); uint8_t* pbuf; uint32_t bar_len; if (!ThriftEncoder::encode(bar, &pbuf, &bar_len)) { cout << "encode failed on remtoe side." << endl; channel.close(); return; } msgrpc::Config::instance().msg_channel_->send_msg(k_loacl_service_id, k_msgrpc_response_msg_id,(const char*)pbuf, bar_len); channel.close(); } ); } //////////////////////////////////////////////////////////////////////////////// TEST(async_rpc, should_able_to__auto__register_rpc_interface__after__application_startup) { demo::RequestFoo req; req.fooa = 1; req.__set_foob(2); std::thread local_thread(local_service); std::thread remote_thread(remote_service); local_thread.join(); remote_thread.join(); }; <commit_msg>move demo code into more generative style<commit_after>#include <iostream> #include <gtest/gtest.h> #include <thread> #include <chrono> #include <msgrpc/thrift_struct/thrift_codec.h> using namespace std; using namespace std::chrono; #include "demo/demo_api_declare.h" #if 0 #define ___methods_of_interface___IBuzzMath(_, ...) \ _(1, ResponseBar, negative_fields, RequestFoo, __VA_ARGS__)\ _(2, ResponseBar, plus1_to_fields, RequestFoo, __VA_ARGS__) ___as_interface(IBuzzMath, __with_interface_id(1)) #endif //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { template <typename T> struct Ret {}; typedef unsigned short msg_id_t; typedef unsigned short service_id_t; //TODO: how to deal with different service id types struct MsgChannel { virtual uint32_t send_msg(const service_id_t& remote_service_id, msg_id_t msg_id, const char* buf, size_t len) const = 0; }; struct Config { void initWith(MsgChannel* msg_channel, msgrpc::msg_id_t request_msg_id, msgrpc::msg_id_t response_msg_id) { instance().msg_channel_ = msg_channel; request_msg_id_ = request_msg_id; response_msg_id_ = response_msg_id; } static inline Config& instance() { static thread_local Config instance; return instance; } MsgChannel* msg_channel_; msg_id_t request_msg_id_; msg_id_t response_msg_id_; }; } namespace msgrpc { /*TODO: using static_assert to assure name length of interface and method*/ const size_t k_max_interface_name_len = 40; const size_t k_max_method_name_len = 40; /*TODO: consider make msgHeader encoded through thrift*/ struct MsgHeader { unsigned char msgrpc_version_; unsigned char method_index_in_interface_; unsigned short interface_index_in_service_; }; struct Request : MsgHeader { }; struct RpcInvokeHandler { void handleInvoke(const MsgHeader& msg_header) { } }; } //////////////////////////////////////////////////////////////////////////////// #include "test_util/UdpChannel.h" namespace demo { const msgrpc::msg_id_t k_msgrpc_request_msg_id = 101; const msgrpc::msg_id_t k_msgrpc_response_msg_id = 102; struct UdpMsgChannel : msgrpc::MsgChannel { virtual uint32_t send_msg(const msgrpc::service_id_t& remote_service_id, msgrpc::msg_id_t msg_id, const char* buf, size_t len) const { size_t msg_len_with_msgid = sizeof(msgrpc::msg_id_t) + len; char* mem = (char*)malloc(msg_len_with_msgid); if (mem) { *(msgrpc::msg_id_t*)(mem) = msg_id; memcpy(mem + sizeof(msgrpc::msg_id_t), buf, len); cout << "send msg len: " << msg_len_with_msgid << endl; g_msg_channel->send_msg_to_remote(string(mem, msg_len_with_msgid), udp::endpoint(udp::v4(), remote_service_id)); free(mem); } else { cout << "send msg failed: allocation failure." << endl; } return 0; } }; } //////////////////////////////////////////////////////////////////////////////// using namespace demo; const msgrpc::service_id_t k_remote_service_id = 2222; const msgrpc::service_id_t k_loacl_service_id = 3333; struct IBuzzMath { virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&) = 0; virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&) = 0; }; //////////////////////////////////////////////////////////////////////////////// struct IBuzzMathStub : IBuzzMath { virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&); virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&); }; msgrpc::Ret<ResponseBar> IBuzzMathStub::negative_fields(const RequestFoo& req) { uint8_t* pbuf; uint32_t len; /*TODO: extract interface for encode/decode for other protocol adoption such as protobuf*/ if (!ThriftEncoder::encode(req, &pbuf, &len)) { /*TODO: how to do with log*/ cout << "encode failed." << endl; return msgrpc::Ret<ResponseBar>(); } //TODO: find k_remote_service_id by interface name "IBuzzMath" size_t msg_len_with_header = sizeof(msgrpc::MsgHeader) + len; char* mem = (char*)malloc(msg_len_with_header); if (!mem) { cout << "alloc mem failed, during sending rpc request." << endl; return msgrpc::Ret<ResponseBar>(); } auto header = (msgrpc::MsgHeader*)mem; header->msgrpc_version_ = 0; header->interface_index_in_service_ = 1; header->method_index_in_interface_ = 1; memcpy(header + 1, (const char*)pbuf, len); cout << "stub sending msg with length: " << msg_len_with_header << endl; msgrpc::Config::instance().msg_channel_->send_msg(k_remote_service_id, k_msgrpc_request_msg_id, mem, msg_len_with_header); free(mem); return msgrpc::Ret<ResponseBar>(); } msgrpc::Ret<ResponseBar> IBuzzMathStub::plus1_to_fields(const RequestFoo& req) { return msgrpc::Ret<ResponseBar>(); } void local_service() { std::this_thread::sleep_for(std::chrono::seconds(1)); msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id); UdpChannel channel(k_loacl_service_id, [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) { if (0 == strcmp(msg, "init")) { IBuzzMathStub buzzMath; RequestFoo foo; foo.fooa = 97; foo.__set_foob(98); buzzMath.negative_fields(foo); } else { cout << "local received msg: " << string(msg, len) << endl; channel.close(); } } ); } //////////////////////////////////////////////////////////////////////////////// struct IBuzzMathImpl { bool onRpcInvoke(const msgrpc::MsgHeader& msg_header, const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len); //todo:remote_id virtual ResponseBar negative_fields(const RequestFoo&); virtual ResponseBar plus1_to_fields(const RequestFoo&); }; bool IBuzzMathImpl::onRpcInvoke(const msgrpc::MsgHeader& msg_header, const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len) { cout << (int)msg_header.msgrpc_version_ << endl; cout << (int)msg_header.interface_index_in_service_ << endl; cout << (int)msg_header.method_index_in_interface_ << endl; RequestFoo req; if (!ThriftDecoder::decode(req, (uint8_t*)msg, len)) { cout << "decode failed on remote side." << endl; return false; } ResponseBar bar = this->negative_fields(req); if (!ThriftEncoder::encode(bar, &pout_buf, &out_buf_len)) { cout << "encode failed on remtoe side." << endl; return false; } return true; } ResponseBar IBuzzMathImpl::negative_fields(const RequestFoo& req) { ResponseBar bar; /*TODO:change bar to inout parameter*/ bar.__set_bara(req.get_foob()); if (req.__isset.foob) { bar.__set_barb(req.fooa); } return bar; } ResponseBar IBuzzMathImpl::plus1_to_fields(const RequestFoo& req) { ResponseBar bar; bar.__set_bara(1 + req.fooa); if (req.__isset.foob) { bar.__set_barb(1 + req.get_foob()); } return bar; } void remote_service() { msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id); UdpChannel channel(k_remote_service_id, [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) { if (0 == strcmp(msg, "init")) { return; } cout << "remote received msg with length: " << len << endl; /*TODO: should first check msg_id == msgrpc_msg_request_id */ if (len < sizeof(msgrpc::MsgHeader)) { cout << "invalid msg: without sufficient msg header info." << endl; return; } auto msg_header = (msgrpc::MsgHeader*)msg; msg += sizeof(msgrpc::MsgHeader); IBuzzMathImpl buzzMath; uint8_t* pout_buf; uint32_t out_buf_len; if (buzzMath.onRpcInvoke(*msg_header, msg, len - sizeof(msgrpc::MsgHeader), pout_buf, out_buf_len)) { msgrpc::Config::instance().msg_channel_->send_msg(k_loacl_service_id, k_msgrpc_response_msg_id,(const char*)pout_buf, out_buf_len); } channel.close(); } ); } //////////////////////////////////////////////////////////////////////////////// TEST(async_rpc, should_able_to__auto__register_rpc_interface__after__application_startup) { demo::RequestFoo req; req.fooa = 1; req.__set_foob(2); std::thread local_thread(local_service); std::thread remote_thread(remote_service); local_thread.join(); remote_thread.join(); }; <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, 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. * */ /** \author Michael Dixon */ #include <gtest/gtest.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/keypoints/sift_keypoint.h> using namespace pcl; using namespace pcl::io; using namespace std; struct KeypointT { float x, y, z, scale; }; PointCloud<PointXYZI>::Ptr cloud_xyzi (new PointCloud<PointXYZI>); ////////////////////////////////////////////////////////////////////////////////////////////// TEST (PCL, SIFTKeypoint) { PointCloud<KeypointT> keypoints; // Compute the SIFT keypoints SIFTKeypoint<PointXYZI, KeypointT> sift_detector; KdTreeFLANN<PointXYZI>::Ptr tree (new KdTreeFLANN<PointXYZI>); sift_detector.setSearchMethod (tree); sift_detector.setScales (0.02, 5, 3); sift_detector.setMinimumContrast (0.03); sift_detector.setInputCloud (cloud_xyzi); sift_detector.compute (keypoints); EXPECT_EQ ((int)keypoints.points.size (), 169); // Change the values and re-compute sift_detector.setScales (0.05, 5, 3); sift_detector.setMinimumContrast (0.06); sift_detector.compute (keypoints); // Compare to previously validated output const int correct_nr_keypoints = 5; const float correct_keypoints[correct_nr_keypoints][4] = { // { x, y, z, scale } {-0.9425, -0.6381, 1.6445, 0.0794}, {-0.5083, -0.5587, 1.8519, 0.0500}, { 1.0265, 0.0500, 1.7154, 0.1000}, { 0.3005, -0.3007, 1.9526, 0.2000}, {-0.1002, -0.1002, 1.9933, 0.3175} }; ASSERT_EQ ((int)keypoints.points.size (), correct_nr_keypoints); for (int i = 0; i < correct_nr_keypoints; ++i) { EXPECT_NEAR (keypoints.points[i].x, correct_keypoints[i][0], 1e-4); EXPECT_NEAR (keypoints.points[i].y, correct_keypoints[i][1], 1e-4); EXPECT_NEAR (keypoints.points[i].z, correct_keypoints[i][2], 1e-4); EXPECT_NEAR (keypoints.points[i].scale, correct_keypoints[i][3], 1e-4); } } /* ---[ */ int main (int argc, char** argv) { if (argc < 2) { std::cerr << "No test file given. Please download `cturtle.pcd` and pass its path to the test." << std::endl; return (-1); } // Load a sample point cloud if (io::loadPCDFile (argv[1], *cloud_xyzi) < 0) { std::cerr << "Failed to read test file. Please download `cturtle.pcd` and pass its path to the test." << std::endl; return (-1); } testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } /* ]--- */ <commit_msg>Added a new test case to help isolate a weird windows bug: duplicate indices returned from a radiusSearch<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, 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. * */ /** \author Michael Dixon */ #include <gtest/gtest.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/keypoints/sift_keypoint.h> #include <set> using namespace pcl; using namespace pcl::io; using namespace std; struct KeypointT { float x, y, z, scale; }; PointCloud<PointXYZI>::Ptr cloud_xyzi (new PointCloud<PointXYZI>); ////////////////////////////////////////////////////////////////////////////////////////////// TEST (PCL, SIFTKeypoint) { PointCloud<KeypointT> keypoints; // Compute the SIFT keypoints SIFTKeypoint<PointXYZI, KeypointT> sift_detector; KdTreeFLANN<PointXYZI>::Ptr tree (new KdTreeFLANN<PointXYZI>); sift_detector.setSearchMethod (tree); sift_detector.setScales (0.02, 5, 3); sift_detector.setMinimumContrast (0.03); sift_detector.setInputCloud (cloud_xyzi); sift_detector.compute (keypoints); EXPECT_EQ ((int)keypoints.points.size (), 169); // Change the values and re-compute sift_detector.setScales (0.05, 5, 3); sift_detector.setMinimumContrast (0.06); sift_detector.compute (keypoints); // Compare to previously validated output const int correct_nr_keypoints = 5; const float correct_keypoints[correct_nr_keypoints][4] = { // { x, y, z, scale } {-0.9425, -0.6381, 1.6445, 0.0794}, {-0.5083, -0.5587, 1.8519, 0.0500}, { 1.0265, 0.0500, 1.7154, 0.1000}, { 0.3005, -0.3007, 1.9526, 0.2000}, {-0.1002, -0.1002, 1.9933, 0.3175} }; ASSERT_EQ ((int)keypoints.points.size (), correct_nr_keypoints); for (int i = 0; i < correct_nr_keypoints; ++i) { EXPECT_NEAR (keypoints.points[i].x, correct_keypoints[i][0], 1e-4); EXPECT_NEAR (keypoints.points[i].y, correct_keypoints[i][1], 1e-4); EXPECT_NEAR (keypoints.points[i].z, correct_keypoints[i][2], 1e-4); EXPECT_NEAR (keypoints.points[i].scale, correct_keypoints[i][3], 1e-4); } } TEST (PCL, SIFTKeypoint_radiusSearch) { int nr_scales_per_octave = 3; float scale = 0.02; KdTreeFLANN<PointXYZI>::Ptr tree_ (new KdTreeFLANN<PointXYZI>); boost::shared_ptr<pcl::PointCloud<PointXYZI> > cloud = cloud_xyzi->makeShared (); VoxelGrid<PointXYZI> voxel_grid; float s = 1.0 * scale; voxel_grid.setLeafSize (s, s, s); voxel_grid.setInputCloud (cloud); voxel_grid.filter (*cloud); tree_->setInputCloud (cloud); const PointCloud<PointXYZI> & input = *cloud; KdTreeFLANN<PointXYZI> & tree = *tree_; float base_scale = scale; std::vector<float> scales (nr_scales_per_octave + 3); for (int i_scale = 0; i_scale <= nr_scales_per_octave + 2; ++i_scale) { scales[i_scale] = base_scale * pow (2.0, (1.0 * i_scale - 1) / nr_scales_per_octave); } Eigen::MatrixXf diff_of_gauss; std::vector<int> nn_indices; std::vector<float> nn_dist; diff_of_gauss.resize (input.size (), scales.size () - 1); const float max_radius = 0.10; size_t i_point = 500; tree.radiusSearch (i_point, max_radius, nn_indices, nn_dist); // Are they all unique? set<int> unique_indices; for (size_t i_neighbor = 0; i_neighbor < nn_indices.size (); ++i_neighbor) { unique_indices.insert (nn_indices[i_neighbor]); } EXPECT_EQ (nn_indices.size (), unique_indices.size ()); } /* ---[ */ int main (int argc, char** argv) { if (argc < 2) { std::cerr << "No test file given. Please download `cturtle.pcd` and pass its path to the test." << std::endl; return (-1); } // Load a sample point cloud if (io::loadPCDFile (argv[1], *cloud_xyzi) < 0) { std::cerr << "Failed to read test file. Please download `cturtle.pcd` and pass its path to the test." << std::endl; return (-1); } testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } /* ]--- */ <|endoftext|>
<commit_before>#include <QtTest/QtTest> #include <QtTest/qtestcase.h> #include <QSignalSpy> #include <QHostInfo> #include <QDebug> #include "websocket.h" #include "unittests.h" class ComplianceTest : public QObject { Q_OBJECT public: ComplianceTest(); private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); /** * @brief Runs the autobahn tests against our implementation */ void autobahnTest(); private: WebSocket *m_pWebSocket; QUrl m_url; }; ComplianceTest::ComplianceTest() : m_pWebSocket(0), m_url("ws://localhost:9001") { } void ComplianceTest::initTestCase() { //m_pWebSocket = new WebSocket(WebSocketProtocol::V_LATEST); // m_pWebSocket->open(m_url, true); // QTRY_VERIFY_WITH_TIMEOUT(m_pWebSocket->state() == QAbstractSocket::ConnectedState, 1000); // QVERIFY(m_pWebSocket->isValid()); } void ComplianceTest::cleanupTestCase() { // if (m_pWebSocket) // { // m_pWebSocket->close(); // //QVERIFY2(m_pWebSocket->waitForDisconnected(1000), "Disconnection failed."); // delete m_pWebSocket; // m_pWebSocket = 0; // } } void ComplianceTest::init() { } void ComplianceTest::cleanup() { } void ComplianceTest::autobahnTest() { //connect to autobahn server at url ws://ipaddress:port/getCaseCount WebSocket *pWebSocket = new WebSocket; int numberOfTestCases = 0; QString m; QObject::connect(pWebSocket, &WebSocket::textFrameReceived, [&](QString message, bool) { //qDebug() << "Received text message from autobahn:" << message; numberOfTestCases = message.toInt(); }); QObject::connect(pWebSocket, &WebSocket::aboutToClose, [=]() { //qDebug() << "About to close"; //pWebSocket->deleteLater(); }); QUrl url = m_url; // url.setPort(9001); url.setPath("/getCaseCount"); pWebSocket->open(url); QTRY_VERIFY_WITH_TIMEOUT(pWebSocket->state() == QAbstractSocket::UnconnectedState, 1000); QVERIFY(numberOfTestCases > 0); QObject::disconnect(pWebSocket, &WebSocket::textFrameReceived, 0, 0); //next for every case, connect to url //ws://ipaddress:port/runCase?case=<number>&agent=<agentname> //where agent name will be QtWebSocket QObject::connect(pWebSocket, &WebSocket::textFrameReceived, [=](QString message, bool) { //qDebug() << "Received text message from autobahn:" << message.length(); pWebSocket->send(message); //pWebSocket->close(); }); QObject::connect(pWebSocket, &WebSocket::binaryFrameReceived, [=](QByteArray message, bool) { //qDebug() << "Received binary message from autobahn:" << message; pWebSocket->send(message); //pWebSocket->close(); }); for (int i = 0; i < numberOfTestCases; ++i) //for (int i = 16; i < 28; ++i) { qDebug() << "Executing test" << (i + 1) << "/" << numberOfTestCases; url.setPath("/runCase?"); QUrlQuery query; query.addQueryItem("case", QString::number(i + 1)); query.addQueryItem("agent", "QtWebSockets"); url.setQuery(query); pWebSocket->open(url); QTRY_VERIFY_WITH_TIMEOUT(pWebSocket->state() == QAbstractSocket::UnconnectedState, 60000); } url.setPath("/updateReports?"); QUrlQuery query; query.addQueryItem("agent", "QtWebSockets"); url.setQuery(query); pWebSocket->open(url); QTRY_VERIFY_WITH_TIMEOUT(pWebSocket->state() == QAbstractSocket::UnconnectedState, 60000); pWebSocket->close(); } DECLARE_TEST(ComplianceTest); #include "tst_compliance.moc" <commit_msg>Cleaned up code<commit_after>#include <QtTest/QtTest> #include <QtTest/qtestcase.h> #include <QSignalSpy> #include <QHostInfo> #include <QDebug> #include "websocket.h" #include "unittests.h" class ComplianceTest : public QObject { Q_OBJECT public: ComplianceTest(); private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); /** * @brief Runs the autobahn tests against our implementation */ void autobahnTest(); private: QUrl m_url; void runTestCases(int startNbr, int stopNbr = -1); void runTestCase(int nbr, int total); }; ComplianceTest::ComplianceTest() : m_url("ws://localhost:9001") { } void ComplianceTest::initTestCase() { } void ComplianceTest::cleanupTestCase() { } void ComplianceTest::init() { } void ComplianceTest::cleanup() { } void ComplianceTest::runTestCase(int nbr, int total) { if (nbr == total) { return; } WebSocket *pWebSocket = new WebSocket; QSignalSpy spy(pWebSocket, SIGNAL(disconnected())); //next for every case, connect to url //ws://ipaddress:port/runCase?case=<number>&agent=<agentname> //where agent name will be QWebSocket QObject::connect(pWebSocket, &WebSocket::textMessageReceived, [=](QString message) { pWebSocket->send(message); }); QObject::connect(pWebSocket, &WebSocket::binaryMessageReceived, [=](QByteArray message) { pWebSocket->send(message); }); qDebug() << "Executing test" << (nbr + 1) << "/" << total; QUrl url = m_url; url.setPath("/runCase?"); QUrlQuery query; query.addQueryItem("case", QString::number(nbr + 1)); query.addQueryItem("agent", "QWebSockets(optimized)"); url.setQuery(query); pWebSocket->open(url); spy.wait(60000); //pWebSocket->close(); delete pWebSocket; runTestCase(nbr + 1, total); } void ComplianceTest::runTestCases(int startNbr, int stopNbr) { runTestCase(startNbr, stopNbr); } void ComplianceTest::autobahnTest() { //connect to autobahn server at url ws://ipaddress:port/getCaseCount WebSocket *pWebSocket = new WebSocket; QUrl url = m_url; int numberOfTestCases = 0; QSignalSpy spy(pWebSocket, SIGNAL(disconnected())); QObject::connect(pWebSocket, &WebSocket::textMessageReceived, [&](QString message) { numberOfTestCases = message.toInt(); }); // QObject::connect(pWebSocket, &WebSocket::disconnected, [=]() { // }); url.setPath("/getCaseCount"); pWebSocket->open(url); spy.wait(60000); QVERIFY(numberOfTestCases > 0); QObject::disconnect(pWebSocket, &WebSocket::textMessageReceived, 0, 0); //runTestCases(64 + 7, 64+141); //141 //runTestCases(64 + 33, 64+33 + 2); //141 //runTestCases(73, 77); //testcase 6.4.1 - 6.4.4 runTestCases(0, numberOfTestCases); //runTestCases(78, 79); //testcase 6.6.1 url.setPath("/updateReports?"); QUrlQuery query; query.addQueryItem("agent", "QWebSockets"); url.setQuery(query); pWebSocket->open(url); spy.wait(60000); delete pWebSocket; } DECLARE_TEST(ComplianceTest) #include "tst_compliance.moc" <|endoftext|>
<commit_before> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <strings.h> #include <string> #include <sstream> #include <signal.h> #include "config/cmd_args.hpp" #include "config/code.hpp" #include "utils.hpp" #include "worker_pool.hpp" #include "buffer_cache/mirrored.hpp" #include "buffer_cache/page_map/array.hpp" #include "buffer_cache/page_repl/page_repl_random.hpp" #include "buffer_cache/writeback/writeback.hpp" #include "buffer_cache/concurrency/rwi_conc.hpp" #include "serializer/in_place.hpp" #include "conn_fsm.hpp" #include "buffer_cache/concurrency/rwi_conc.hpp" #include "btree/get_fsm.hpp" #include "btree/set_fsm.hpp" #include "btree/incr_decr_fsm.hpp" #include "btree/append_prepend_fsm.hpp" #include "btree/delete_fsm.hpp" worker_t::worker_t(int _workerid, int _nqueues, worker_pool_t *parent_pool, cmd_config_t *cmd_config) { ref_count = 0; event_queue = gnew<event_queue_t>(_workerid, _nqueues, parent_pool, this, cmd_config); total_connections = 0; curr_connections = 0; perfmon.monitor(var_monitor_t(var_monitor_t::vt_int, "total_connections", (void*)&total_connections)); perfmon.monitor(var_monitor_t(var_monitor_t::vt_int, "curr_connections", (void*)&curr_connections)); // Init the slices nworkers = _nqueues; workerid = _workerid; nslices = cmd_config->n_slices; mkdir(DATA_DIRECTORY, 0777); for (int i = 0; i < nslices; i++) { typedef std::basic_string<char, std::char_traits<char>, gnew_alloc<char> > rdbstring_t; typedef std::basic_stringstream<char, std::char_traits<char>, gnew_alloc<char> > rdbstringstream_t; rdbstringstream_t out; rdbstring_t str((char*)cmd_config->db_file_name); out << workerid << "_" << i; str += out.str(); slices[i] = gnew<cache_t>( (char*)str.c_str(), BTREE_BLOCK_SIZE, cmd_config->max_cache_size / nworkers, cmd_config->wait_for_flush, cmd_config->flush_timer_ms, cmd_config->flush_threshold_percent); } active_slices = true; } worker_t::~worker_t() { check("Error in ~worker_t, cannot delete a worker_t without first deleting its slices", active_slices == true); delete event_queue; } void worker_t::start_worker() { event_queue->start_queue(this); } void worker_t::start_slices() { for (int i = 0; i < nslices; i++) slices[i]->start(); } void worker_t::shutdown() { shutting_down = true; for (int i = 0; i < nslices; i++) { ref_count++; slices[i]->shutdown(this); } } void worker_t::delete_slices() { for (int i = 0; i < nslices; i++) gdelete(slices[i]); active_slices = false; } void worker_t::new_fsm(int data, int &resource, void **source) { worker_t::conn_fsm_t *fsm = new worker_t::conn_fsm_t(data, event_queue); live_fsms.push_back(fsm); resource = fsm->get_source(); *source = fsm; printf("Opened socket %d\n", resource); curr_connections++; total_connections++; } void worker_t::deregister_fsm(void *fsm, int &resource) { worker_t::conn_fsm_t *cfsm = (worker_t::conn_fsm_t *) fsm; printf("Closing socket %d\n", cfsm->get_source()); resource = cfsm->get_source(); live_fsms.remove(cfsm); shutdown_fsms.push_back(cfsm); curr_connections--; // TODO: there might be outstanding btrees that we're missing (if // we're quitting before the the operation completes). We need to // free the btree structure in this case (more likely the request // and all the btrees associated with it). } bool worker_t::deregister_fsm(int &resource) { if (live_fsms.empty()) { return false; } else { worker_t::conn_fsm_t *cfsm = live_fsms.head(); deregister_fsm(cfsm, resource); return true; } } void worker_t::clean_fsms() { shutdown_fsms.clear(); } void worker_t::initiate_conn_fsm_transition(event_t *event) { code_config_t::conn_fsm_t *fsm = (code_config_t::conn_fsm_t*)event->state; int res = fsm->do_transition(event); void worker_t::process_perfmon_msg(perfmon_msg_t *msg) { worker_t *worker = get_cpu_context()->worker; event_queue_t *queue = worker->event_queue; int this_cpu = get_cpu_context()->worker->workerid; int return_cpu = msg->return_cpu; switch(msg->state) { case perfmon_msg_t::sm_request: // Copy our statistics into the perfmon message and send a response msg->perfmon = new perfmon_t(); msg->perfmon->copy_from(worker->perfmon); msg->state = perfmon_msg_t::sm_response; break; case perfmon_msg_t::sm_response: msg->request->on_request_part_completed(); return; case perfmon_msg_t::sm_copy_cleanup: // Response has been sent to the client, time to delete the // copy delete msg->perfmon; msg->state = perfmon_msg_t::sm_msg_cleanup; break; case perfmon_msg_t::sm_msg_cleanup: // Copy has been deleted, delete the final message and return delete msg; return; } msg->return_cpu = this_cpu; queue->message_hub.store_message(return_cpu, msg); } void worker_t::process_lock_msg(event_t *event, rwi_lock_t::lock_request_t *lr) { lr->callback->on_lock_available(); delete lr; } void worker_t::process_log_msg(log_msg_t *msg) { worker_t *worker = get_cpu_context()->worker; if (msg->del) { delete msg; } else { assert(worker->workerid == LOG_WORKER); worker->log_writer.writef("(%s)Q%d:%s:%d:", msg->level_str(), msg->return_cpu, msg->src_file, msg->src_line); worker->log_writer.write(msg->str); msg->del = true; // No need to change return_cpu because the message will be deleted immediately. worker->event_queue->message_hub.store_message(msg->return_cpu, msg); } } // Handle events coming from the event queue void worker_t::event_handler(event_t *event) { if(event->event_type == et_sock) { // Got some socket action, let the connection fsm know initiate_conn_fsm_transition(event); } else if(event->event_type == et_cpu_event) { cpu_message_t *msg = (cpu_message_t*)event->state; switch(msg->type) { case cpu_message_t::mt_btree: process_btree_msg((code_config_t::btree_fsm_t*)msg); break; case cpu_message_t::mt_lock: process_lock_msg(event, (rwi_lock_t::lock_request_t*)msg); break; case cpu_message_t::mt_perfmon: process_perfmon_msg((perfmon_msg_t*)msg); break; case cpu_message_t::mt_log: process_log_msg((log_msg_t *) msg); break; } } else { check("Unknown event in event_handler", 1); } } void worker_t::on_sync() { decr_ref_count(); } void worker_pool_t::create_worker_pool(pthread_t main_thread, int _nworkers, int _nslices) { this->main_thread = main_thread; // Create the workers if (_nworkers != 0) nworkers = std::min(_nworkers, MAX_CPUS); else nworkers = get_cpu_count(); if (_nslices != 0) nslices = std::min(_nslices, MAX_SLICES); else nslices = DEFAULT_SLICES; cmd_config->n_workers = nworkers; cmd_config->n_slices = nslices; for(int i = 0; i < nworkers; i++) { workers[i] = gnew<worker_t>(i, nworkers, this, cmd_config); } active_worker = 0; for(int i = 0; i < nworkers; i++) { workers[i]->event_queue->message_hub.init(i, nworkers, workers); } // Start the actual queue for(int i = 0; i < nworkers; i++) { workers[i]->start_worker(); } // TODO: can we move the printing out of here? printf("Physical cores: %d\n", get_cpu_count()); printf("Using cores: %d\n", nworkers); printf("Slices per core: %d\n", nslices); printf("Total RAM: %ldMB\n", get_total_ram() / 1024 / 1024); printf("Free RAM: %ldMB (%.2f%%)\n", get_available_ram() / 1024 / 1024, (double)get_available_ram() / (double)get_total_ram() * 100.0f); printf("Max cache size: %ldMB\n", cmd_config->max_cache_size / 1024 / 1024); // TODO: this whole queue creation business is a mess, refactor // the way it works. } worker_pool_t::worker_pool_t(pthread_t main_thread, cmd_config_t *_cmd_config) : cmd_config(_cmd_config) { create_worker_pool(main_thread, cmd_config->n_workers, cmd_config->n_slices); } worker_pool_t::worker_pool_t(pthread_t main_thread, int _nworkers, int _nslices, cmd_config_t *_cmd_config) : cmd_config(_cmd_config) { create_worker_pool(main_thread, _nworkers, _nslices); } worker_pool_t::~worker_pool_t() { // Start stopping each event queue for(int i = 0; i < nworkers; i++) { workers[i]->event_queue->begin_stopping_queue(); } // Wait for all of the event queues to finish stopping before destroying any of them for (int i = 0; i < nworkers; i++) { workers[i]->event_queue->finish_stopping_queue(); } // Free the event queues for(int i = 0; i < nworkers; i++) { gdelete(workers[i]); } nworkers = 0; // Delete all the custom allocators in the system for(size_t i = 0; i < all_allocs.size(); i++) { tls_small_obj_alloc_accessor<alloc_t>::alloc_vector_t *allocs = (tls_small_obj_alloc_accessor<alloc_t>::alloc_vector_t*)(all_allocs[i]); if(allocs) { for(size_t j = 0; j < allocs->size(); j++) { gdelete(allocs->operator[](j)); } } delete allocs; } } worker_t* worker_pool_t::next_active_worker() { int worker = active_worker++; if(active_worker >= nworkers) active_worker = 0; return workers[worker]; // TODO: consider introducing randomness to avoid potential // (intentional and unintentional) attacks on memory allocation // and CPU utilization. } <commit_msg>Adds a ref_count to workers that keeps track of outstanding syncs and outstanding log msgs.<commit_after> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <strings.h> #include <string> #include <sstream> #include <signal.h> #include "config/cmd_args.hpp" #include "config/code.hpp" #include "utils.hpp" #include "worker_pool.hpp" #include "buffer_cache/mirrored.hpp" #include "buffer_cache/page_map/array.hpp" #include "buffer_cache/page_repl/page_repl_random.hpp" #include "buffer_cache/writeback/writeback.hpp" #include "buffer_cache/concurrency/rwi_conc.hpp" #include "serializer/in_place.hpp" #include "conn_fsm.hpp" #include "buffer_cache/concurrency/rwi_conc.hpp" #include "btree/get_fsm.hpp" #include "btree/set_fsm.hpp" #include "btree/incr_decr_fsm.hpp" #include "btree/append_prepend_fsm.hpp" #include "btree/delete_fsm.hpp" worker_t::worker_t(int _workerid, int _nqueues, worker_pool_t *parent_pool, cmd_config_t *cmd_config) { ref_count = 0; event_queue = gnew<event_queue_t>(_workerid, _nqueues, parent_pool, this, cmd_config); total_connections = 0; curr_connections = 0; perfmon.monitor(var_monitor_t(var_monitor_t::vt_int, "total_connections", (void*)&total_connections)); perfmon.monitor(var_monitor_t(var_monitor_t::vt_int, "curr_connections", (void*)&curr_connections)); // Init the slices nworkers = _nqueues; workerid = _workerid; nslices = cmd_config->n_slices; mkdir(DATA_DIRECTORY, 0777); for (int i = 0; i < nslices; i++) { typedef std::basic_string<char, std::char_traits<char>, gnew_alloc<char> > rdbstring_t; typedef std::basic_stringstream<char, std::char_traits<char>, gnew_alloc<char> > rdbstringstream_t; rdbstringstream_t out; rdbstring_t str((char*)cmd_config->db_file_name); out << workerid << "_" << i; str += out.str(); slices[i] = gnew<cache_t>( (char*)str.c_str(), BTREE_BLOCK_SIZE, cmd_config->max_cache_size / nworkers, cmd_config->wait_for_flush, cmd_config->flush_timer_ms, cmd_config->flush_threshold_percent); } active_slices = true; } worker_t::~worker_t() { check("Error in ~worker_t, cannot delete a worker_t without first deleting its slices", active_slices == true); delete event_queue; } void worker_t::start_worker() { event_queue->start_queue(this); } void worker_t::start_slices() { for (int i = 0; i < nslices; i++) slices[i]->start(); } void worker_t::shutdown() { shutting_down = true; for (int i = 0; i < nslices; i++) { ref_count++; slices[i]->shutdown(this); } } void worker_t::delete_slices() { for (int i = 0; i < nslices; i++) gdelete(slices[i]); active_slices = false; } void worker_t::new_fsm(int data, int &resource, void **source) { worker_t::conn_fsm_t *fsm = new worker_t::conn_fsm_t(data, event_queue); live_fsms.push_back(fsm); resource = fsm->get_source(); *source = fsm; printf("Opened socket %d\n", resource); curr_connections++; total_connections++; } void worker_t::deregister_fsm(void *fsm, int &resource) { worker_t::conn_fsm_t *cfsm = (worker_t::conn_fsm_t *) fsm; logf(INF, "Closing socket %d\n", cfsm->get_source()); resource = cfsm->get_source(); live_fsms.remove(cfsm); shutdown_fsms.push_back(cfsm); curr_connections--; // TODO: there might be outstanding btrees that we're missing (if // we're quitting before the the operation completes). We need to // free the btree structure in this case (more likely the request // and all the btrees associated with it). } bool worker_t::deregister_fsm(int &resource) { if (live_fsms.empty()) { return false; } else { worker_t::conn_fsm_t *cfsm = live_fsms.head(); deregister_fsm(cfsm, resource); return true; } } void worker_t::clean_fsms() { shutdown_fsms.clear(); } void worker_t::initiate_conn_fsm_transition(event_t *event) { code_config_t::conn_fsm_t *fsm = (code_config_t::conn_fsm_t*)event->state; int res = fsm->do_transition(event); void worker_t::process_perfmon_msg(perfmon_msg_t *msg) { worker_t *worker = get_cpu_context()->worker; event_queue_t *queue = worker->event_queue; int this_cpu = get_cpu_context()->worker->workerid; int return_cpu = msg->return_cpu; switch(msg->state) { case perfmon_msg_t::sm_request: // Copy our statistics into the perfmon message and send a response msg->perfmon = new perfmon_t(); msg->perfmon->copy_from(worker->perfmon); msg->state = perfmon_msg_t::sm_response; break; case perfmon_msg_t::sm_response: msg->request->on_request_part_completed(); return; case perfmon_msg_t::sm_copy_cleanup: // Response has been sent to the client, time to delete the // copy delete msg->perfmon; msg->state = perfmon_msg_t::sm_msg_cleanup; break; case perfmon_msg_t::sm_msg_cleanup: // Copy has been deleted, delete the final message and return delete msg; return; } msg->return_cpu = this_cpu; queue->message_hub.store_message(return_cpu, msg); } void worker_t::process_lock_msg(event_t *event, rwi_lock_t::lock_request_t *lr) { lr->callback->on_lock_available(); delete lr; } void worker_t::process_log_msg(log_msg_t *msg) { if (msg->del) { ref_count--; delete msg; } else { assert(workerid == LOG_WORKER); log_writer.writef("(%s)Q%d:%s:%d:", msg->level_str(), msg->return_cpu, msg->src_file, msg->src_line); log_writer.write(msg->str); msg->del = true; // No need to change return_cpu because the message will be deleted immediately. event_queue->message_hub.store_message(msg->return_cpu, msg); } } // Handle events coming from the event queue void worker_t::event_handler(event_t *event) { if(event->event_type == et_sock) { // Got some socket action, let the connection fsm know initiate_conn_fsm_transition(event); } else if(event->event_type == et_cpu_event) { cpu_message_t *msg = (cpu_message_t*)event->state; switch(msg->type) { case cpu_message_t::mt_btree: process_btree_msg((code_config_t::btree_fsm_t*)msg); break; case cpu_message_t::mt_lock: process_lock_msg(event, (rwi_lock_t::lock_request_t*)msg); break; case cpu_message_t::mt_perfmon: process_perfmon_msg((perfmon_msg_t*)msg); break; case cpu_message_t::mt_log: process_log_msg((log_msg_t *) msg); break; } } else { check("Unknown event in event_handler", 1); } } void worker_t::incr_ref_count() { ref_count++; } void worker_t::decr_ref_count() { ref_count--; if (ref_count == 0 && shutting_down) { event_queue->send_shutdown(); } } void worker_t::on_sync() { decr_ref_count(); } void worker_pool_t::create_worker_pool(pthread_t main_thread, int _nworkers, int _nslices) { this->main_thread = main_thread; // Create the workers if (_nworkers != 0) nworkers = std::min(_nworkers, MAX_CPUS); else nworkers = get_cpu_count(); if (_nslices != 0) nslices = std::min(_nslices, MAX_SLICES); else nslices = DEFAULT_SLICES; cmd_config->n_workers = nworkers; cmd_config->n_slices = nslices; for(int i = 0; i < nworkers; i++) { workers[i] = gnew<worker_t>(i, nworkers, this, cmd_config); } active_worker = 0; for(int i = 0; i < nworkers; i++) { workers[i]->event_queue->message_hub.init(i, nworkers, workers); } // Start the actual queue for(int i = 0; i < nworkers; i++) { workers[i]->start_worker(); } // TODO: can we move the printing out of here? printf("Physical cores: %d\n", get_cpu_count()); printf("Using cores: %d\n", nworkers); printf("Slices per core: %d\n", nslices); printf("Total RAM: %ldMB\n", get_total_ram() / 1024 / 1024); printf("Free RAM: %ldMB (%.2f%%)\n", get_available_ram() / 1024 / 1024, (double)get_available_ram() / (double)get_total_ram() * 100.0f); printf("Max cache size: %ldMB\n", cmd_config->max_cache_size / 1024 / 1024); // TODO: this whole queue creation business is a mess, refactor // the way it works. } worker_pool_t::worker_pool_t(pthread_t main_thread, cmd_config_t *_cmd_config) : cmd_config(_cmd_config) { create_worker_pool(main_thread, cmd_config->n_workers, cmd_config->n_slices); } worker_pool_t::worker_pool_t(pthread_t main_thread, int _nworkers, int _nslices, cmd_config_t *_cmd_config) : cmd_config(_cmd_config) { create_worker_pool(main_thread, _nworkers, _nslices); } worker_pool_t::~worker_pool_t() { // Start stopping each event queue for(int i = 0; i < nworkers; i++) { workers[i]->event_queue->begin_stopping_queue(); } // Wait for all of the event queues to finish stopping before destroying any of them for (int i = 0; i < nworkers; i++) { workers[i]->event_queue->finish_stopping_queue(); } // Free the event queues for(int i = 0; i < nworkers; i++) { gdelete(workers[i]); } nworkers = 0; // Delete all the custom allocators in the system for(size_t i = 0; i < all_allocs.size(); i++) { tls_small_obj_alloc_accessor<alloc_t>::alloc_vector_t *allocs = (tls_small_obj_alloc_accessor<alloc_t>::alloc_vector_t*)(all_allocs[i]); if(allocs) { for(size_t j = 0; j < allocs->size(); j++) { gdelete(allocs->operator[](j)); } } delete allocs; } } worker_t* worker_pool_t::next_active_worker() { int worker = active_worker++; if(active_worker >= nworkers) active_worker = 0; return workers[worker]; // TODO: consider introducing randomness to avoid potential // (intentional and unintentional) attacks on memory allocation // and CPU utilization. } <|endoftext|>
<commit_before>#include <phypp.hpp> int phypp_main(int argc, char* argv[]) { if (argc < 2) { print("usage: median_sub <directory> [options]"); return 0; } std::string dir = file::directorize(argv[1]); vec1s files = dir+file::list_files(dir+"sci_reconstructed*-sci.fits"); if (files.empty()) { files = dir+file::list_files(dir+"SCI_RECONSTRUCTED*-sci.fits"); } bool mask_center = false; double mask_radius = 0.5; // arcsec std::string masks; read_args(argc-1, argv+1, arg_list(mask_center, masks, mask_radius)); vec1d ra, dec, size; if (!masks.empty()) { ascii::read_table(masks, ascii::find_skip(masks), _, ra, dec, size); } auto ksigma = [](vec1d data) { double v = median(data); double m = 1.48*median(abs(data - v)); vec1u idg = where(abs(data - v) < 7*m); return mean(data[idg]); }; for (auto oname : files) { std::string newfile = file::get_basename(oname); file::copy(oname, newfile); fits::image fimg(newfile); for (uint_t i : range(1, fimg.hdu_count())) { fimg.reach_hdu(i); if (fimg.axis_count() != 3) continue; vec3d cube; fimg.read(cube); uint_t ny = cube.dims[1]; uint_t nx = cube.dims[2]; vec2b mask = replicate(true, ny, nx); // Mask nearby sources from the provided catalog (if any) if (!ra.empty()) { astro::wcs w(fimg.read_header()); vec1d x, y; astro::ad2xy(w, ra, dec, x, y); x -= 1.0; y -= 1.0; double aspix = 1.0; if (!astro::get_pixel_size(w, aspix)) { error("could not read pixel size from cube"); return 1; } vec1d r = size/aspix; vec2d ix = generate_img(mask.dims, [](int_t, int_t tx) { return tx; }); vec2d iy = generate_img(mask.dims, [](int_t ty, int_t) { return ty; }); for (uint_t s : range(ra)) { mask = mask && sqr(x[s] - ix) + sqr(y[s] - iy) > sqr(r[s]); } } else if (mask_center) { astro::wcs w(fimg.read_header()); double aspix = 1.0; if (!astro::get_pixel_size(w, aspix)) { error("could not read pixel size from cube"); return 1; } vec2d ix = generate_img(mask.dims, [](int_t, int_t tx) { return tx; }); vec2d iy = generate_img(mask.dims, [](int_t ty, int_t) { return ty; }); mask = mask && sqr(nx/2 - ix) + sqr(ny/2 - iy) > sqr(mask_radius/aspix); } // Mask borders mask(0,_) = mask(ny-1,_) = mask(_,0) = mask(_,nx-1) = false; // Subtract whole IFU vec1u idg = where(mask); for (uint_t l : range(cube.dims[0])) { cube(l,_,_) -= ksigma(cube(l,_,_)[idg]); } fimg.update(cube); } } return 0; } <commit_msg>Made sure that median_sub does not affect noise extensions<commit_after>#include <phypp.hpp> int phypp_main(int argc, char* argv[]) { if (argc < 2) { print("usage: median_sub <directory> [options]"); return 0; } std::string dir = file::directorize(argv[1]); vec1s files = dir+file::list_files(dir+"sci_reconstructed*-sci.fits"); if (files.empty()) { files = dir+file::list_files(dir+"SCI_RECONSTRUCTED*-sci.fits"); } bool mask_center = false; double mask_radius = 0.5; // arcsec std::string masks; read_args(argc-1, argv+1, arg_list(mask_center, masks, mask_radius)); vec1d ra, dec, size; if (!masks.empty()) { ascii::read_table(masks, ascii::find_skip(masks), _, ra, dec, size); } auto ksigma = [](vec1d data) { double v = median(data); double m = 1.48*median(abs(data - v)); vec1u idg = where(abs(data - v) < 7*m); return mean(data[idg]); }; for (auto oname : files) { std::string newfile = file::get_basename(oname); file::copy(oname, newfile); fits::image fimg(newfile); for (uint_t i : range(1, fimg.hdu_count())) { fimg.reach_hdu(i); if (fimg.axis_count() != 3) continue; std::string extname; if (fimg.read_keyword("EXTNAME", extname) && end_with(extname, ".NOISE")) continue; vec3d cube; fimg.read(cube); uint_t ny = cube.dims[1]; uint_t nx = cube.dims[2]; vec2b mask = replicate(true, ny, nx); // Mask nearby sources from the provided catalog (if any) if (!ra.empty()) { astro::wcs w(fimg.read_header()); vec1d x, y; astro::ad2xy(w, ra, dec, x, y); x -= 1.0; y -= 1.0; double aspix = 1.0; if (!astro::get_pixel_size(w, aspix)) { error("could not read pixel size from cube"); return 1; } vec1d r = size/aspix; vec2d ix = generate_img(mask.dims, [](int_t, int_t tx) { return tx; }); vec2d iy = generate_img(mask.dims, [](int_t ty, int_t) { return ty; }); for (uint_t s : range(ra)) { mask = mask && sqr(x[s] - ix) + sqr(y[s] - iy) > sqr(r[s]); } } else if (mask_center) { astro::wcs w(fimg.read_header()); double aspix = 1.0; if (!astro::get_pixel_size(w, aspix)) { error("could not read pixel size from cube"); return 1; } vec2d ix = generate_img(mask.dims, [](int_t, int_t tx) { return tx; }); vec2d iy = generate_img(mask.dims, [](int_t ty, int_t) { return ty; }); mask = mask && sqr(nx/2 - ix) + sqr(ny/2 - iy) > sqr(mask_radius/aspix); } // Mask borders mask(0,_) = mask(ny-1,_) = mask(_,0) = mask(_,nx-1) = false; // Subtract whole IFU vec1u idg = where(mask); for (uint_t l : range(cube.dims[0])) { cube(l,_,_) -= ksigma(cube(l,_,_)[idg]); } fimg.update(cube); } } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: objectregistry.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:07:42 $ * * 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 CONFIGMGR_API_OBJECTREGISTRY_HXX_ #define CONFIGMGR_API_OBJECTREGISTRY_HXX_ #ifndef CONFIGMGR_CONFIGNODE_HXX_ #include "noderef.hxx" #endif #include <osl/mutex.hxx> #include <vos/refernce.hxx> #include <hash_map> #include "tracer.hxx" namespace configmgr { namespace configapi { class NodeElement; class ObjectRegistry : public vos::OReference { public: typedef configuration::NodeID Key; typedef NodeElement* Element; typedef NodeElement* ElementArg; static Element notFound() { return 0; } struct KeyHash { size_t operator() (const Key& rKey) const {return rKey.hashCode();} }; struct KeyEq { bool operator() (const Key& lhs,const Key& rhs) const {return lhs == rhs;} }; typedef std::hash_map<Key,Element,KeyHash, KeyEq> ObjectMap; public: ObjectRegistry() {} ~ObjectRegistry(); Element findElement(Key const& aNode) const { ObjectMap::const_iterator aFound = m_aMap.find(aNode); return (aFound != m_aMap.end()) ? aFound->second : notFound(); } void registerElement(Key const& aNode, ElementArg aElement) { OSL_ENSURE(m_aMap.find(aNode) == m_aMap.end(), "ERROR: Node is already registered"); m_aMap[aNode] = aElement; } void revokeElement(Key const& aNode, ElementArg aElement) { ObjectMap::iterator aFound = m_aMap.find(aNode); if (aFound != m_aMap.end()) { OSL_ENSURE(aFound->second == aElement,"Found unexpected element in map"); if (aFound->second == aElement) m_aMap.erase(aFound); } } private: ObjectMap m_aMap; }; //----------------------------------------------------------------------------- } } #endif // CONFIGMGR_API_FACTORY_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.8.16); FILE MERGED 2008/04/01 12:27:12 thb 1.8.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:37 rt 1.8.16.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: objectregistry.hxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef CONFIGMGR_API_OBJECTREGISTRY_HXX_ #define CONFIGMGR_API_OBJECTREGISTRY_HXX_ #include "noderef.hxx" #include <osl/mutex.hxx> #include <vos/refernce.hxx> #include <hash_map> #include "tracer.hxx" namespace configmgr { namespace configapi { class NodeElement; class ObjectRegistry : public vos::OReference { public: typedef configuration::NodeID Key; typedef NodeElement* Element; typedef NodeElement* ElementArg; static Element notFound() { return 0; } struct KeyHash { size_t operator() (const Key& rKey) const {return rKey.hashCode();} }; struct KeyEq { bool operator() (const Key& lhs,const Key& rhs) const {return lhs == rhs;} }; typedef std::hash_map<Key,Element,KeyHash, KeyEq> ObjectMap; public: ObjectRegistry() {} ~ObjectRegistry(); Element findElement(Key const& aNode) const { ObjectMap::const_iterator aFound = m_aMap.find(aNode); return (aFound != m_aMap.end()) ? aFound->second : notFound(); } void registerElement(Key const& aNode, ElementArg aElement) { OSL_ENSURE(m_aMap.find(aNode) == m_aMap.end(), "ERROR: Node is already registered"); m_aMap[aNode] = aElement; } void revokeElement(Key const& aNode, ElementArg aElement) { ObjectMap::iterator aFound = m_aMap.find(aNode); if (aFound != m_aMap.end()) { OSL_ENSURE(aFound->second == aElement,"Found unexpected element in map"); if (aFound->second == aElement) m_aMap.erase(aFound); } } private: ObjectMap m_aMap; }; //----------------------------------------------------------------------------- } } #endif // CONFIGMGR_API_FACTORY_HXX_ <|endoftext|>
<commit_before>/* * timing.cpp * * Copyright The Mbed TLS Contributors * Copyright (C) 2021, Arm Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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. * */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/timing.h" #include "drivers/Timeout.h" #include "drivers/Timer.h" #include "drivers/LowPowerTimer.h" #include <chrono> extern "C" { volatile int mbedtls_timing_alarmed = 0; }; static void handle_alarm(void) { mbedtls_timing_alarmed = 1; } extern "C" void mbedtls_set_alarm(int seconds) { static mbed::Timeout t; mbedtls_timing_alarmed = 0; t.attach(handle_alarm, std::chrono::seconds(seconds)); } // The static Mbed timer here is initialized once only. // Mbed TLS can have multiple timers (mbedtls_timing_hr_time) derived // from the Mbed timer. #if DEVICE_LPTICKER static mbed::LowPowerTimer timer; #elif DEVICE_USTICKER static mbed::Timer timer; #else #error "MBEDTLS_TIMING_C requires either LPTICKER or USTICKER" #endif static int timer_init = 0; #if !defined(HAVE_HARDCLOCK) #define HAVE_HARDCLOCK extern "C" unsigned long mbedtls_timing_hardclock(void) { if (timer_init == 0) { timer.reset(); timer.start(); timer_init = 1; } return timer.elapsed_time().count(); } #endif /* !HAVE_HARDCLOCK */ extern "C" unsigned long mbedtls_timing_get_timer(struct mbedtls_timing_hr_time *val, int reset) { if (timer_init == 0) { timer.reset(); timer.start(); timer_init = 1; } if (reset) { val->start = std::chrono::duration_cast<std::chrono::milliseconds>(timer.elapsed_time()).count(); return 0; } else { return std::chrono::duration_cast<std::chrono::milliseconds>(timer.elapsed_time()).count() - val->start; } } /** * Note: The following implementations come from the default timing.c * from Mbed TLS. They are disabled in timing.c when MBEDTLS_TIMING_ALT * is defined, but the implementation is nonetheless applicable to * Mbed OS, so we copy them over. */ extern "C" void mbedtls_timing_set_delay(void *data, uint32_t int_ms, uint32_t fin_ms) { mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data; ctx->int_ms = int_ms; ctx->fin_ms = fin_ms; if (fin_ms != 0) { (void) mbedtls_timing_get_timer(&ctx->timer, 1); } } extern "C" int mbedtls_timing_get_delay(void *data) { mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data; unsigned long elapsed_ms; if (ctx->fin_ms == 0) { return -1; } elapsed_ms = mbedtls_timing_get_timer(&ctx->timer, 0); if (elapsed_ms >= ctx->fin_ms) { return 2; } if (elapsed_ms >= ctx->int_ms) { return 1; } return 0; } <commit_msg>timing_mbed.cpp: Check MBEDTLS_TIMING_ALT<commit_after>/* * timing.cpp * * Copyright The Mbed TLS Contributors * Copyright (C) 2021, Arm Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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. * */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_TIMING_ALT) #include "mbedtls/timing.h" #include "drivers/Timeout.h" #include "drivers/Timer.h" #include "drivers/LowPowerTimer.h" #include <chrono> extern "C" { volatile int mbedtls_timing_alarmed = 0; }; static void handle_alarm(void) { mbedtls_timing_alarmed = 1; } extern "C" void mbedtls_set_alarm(int seconds) { static mbed::Timeout t; mbedtls_timing_alarmed = 0; t.attach(handle_alarm, std::chrono::seconds(seconds)); } // The static Mbed timer here is initialized once only. // Mbed TLS can have multiple timers (mbedtls_timing_hr_time) derived // from the Mbed timer. #if DEVICE_LPTICKER static mbed::LowPowerTimer timer; #elif DEVICE_USTICKER static mbed::Timer timer; #else #error "MBEDTLS_TIMING_C requires either LPTICKER or USTICKER" #endif static int timer_init = 0; #if !defined(HAVE_HARDCLOCK) #define HAVE_HARDCLOCK extern "C" unsigned long mbedtls_timing_hardclock(void) { if (timer_init == 0) { timer.reset(); timer.start(); timer_init = 1; } return timer.elapsed_time().count(); } #endif /* !HAVE_HARDCLOCK */ extern "C" unsigned long mbedtls_timing_get_timer(struct mbedtls_timing_hr_time *val, int reset) { if (timer_init == 0) { timer.reset(); timer.start(); timer_init = 1; } if (reset) { val->start = std::chrono::duration_cast<std::chrono::milliseconds>(timer.elapsed_time()).count(); return 0; } else { return std::chrono::duration_cast<std::chrono::milliseconds>(timer.elapsed_time()).count() - val->start; } } /** * Note: The following implementations come from the default timing.c * from Mbed TLS. They are disabled in timing.c when MBEDTLS_TIMING_ALT * is defined, but the implementation is nonetheless applicable to * Mbed OS, so we copy them over. */ extern "C" void mbedtls_timing_set_delay(void *data, uint32_t int_ms, uint32_t fin_ms) { mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data; ctx->int_ms = int_ms; ctx->fin_ms = fin_ms; if (fin_ms != 0) { (void) mbedtls_timing_get_timer(&ctx->timer, 1); } } extern "C" int mbedtls_timing_get_delay(void *data) { mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data; unsigned long elapsed_ms; if (ctx->fin_ms == 0) { return -1; } elapsed_ms = mbedtls_timing_get_timer(&ctx->timer, 0); if (elapsed_ms >= ctx->fin_ms) { return 2; } if (elapsed_ms >= ctx->int_ms) { return 1; } return 0; } #endif // MBEDTLS_TIMING_ALT <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SQLException.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: oj $ $Date: 2001-10-18 13:17:55 $ * * 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 _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_ #include "java/sql/SQLException.hxx" #endif #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; //************************************************************** //************ Class: java.sql.SQLException //************************************************************** java_sql_SQLException::java_sql_SQLException( const java_sql_SQLException_BASE& _rException,const Reference< XInterface> & _rContext) : starsdbc::SQLException( _rException.getMessage(), _rContext, _rException.getSQLState(), _rException.getErrorCode(), makeAny(_rException.getNextException()) ) { } java_sql_SQLException_BASE::java_sql_SQLException_BASE( JNIEnv * pEnv, jobject myObj ) : java_lang_Exception( pEnv, myObj ) { } jclass java_sql_SQLException_BASE::theClass = 0; java_sql_SQLException_BASE::~java_sql_SQLException_BASE() {} jclass java_sql_SQLException_BASE::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass("java/sql/SQLException"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!"); if(!tempClass) { t.pEnv->ExceptionDescribe(); t.pEnv->ExceptionClear(); } jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_sql_SQLException_BASE::saveClassRef( jclass pClass ) { if( SDBThreadAttach::IsJavaErrorOccured() || pClass==NULL ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } starsdbc::SQLException java_sql_SQLException_BASE::getNextException() const { jobject out = NULL; SDBThreadAttach t; if( t.pEnv ){ // temporaere Variable initialisieren char * cSignature = "()Ljava/sql/Exception;"; char * cMethodName = "getNextException"; // Java-Call absetzen jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = t.pEnv->CallObjectMethod( object, mID); ThrowSQLException(t.pEnv,0); } //mID } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return out ? (starsdbc::SQLException)java_sql_SQLException(java_sql_SQLException_BASE(t.pEnv,out),0) : starsdbc::SQLException(); } ::rtl::OUString java_sql_SQLException_BASE::getSQLState() const { jstring out = (jstring)NULL; SDBThreadAttach t; ::rtl::OUString aStr; if( t.pEnv ){ // temporaere Variable initialisieren char * cSignature = "()Ljava/lang/String;"; char * cMethodName = "getSQLState"; // Java-Call absetzen jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ){ out = (jstring) t.pEnv->CallObjectMethod( object, mID); ThrowSQLException(t.pEnv,0); if(out) aStr = JavaString2String(t.pEnv,out); } //mID } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return aStr; } sal_Int32 java_sql_SQLException_BASE::getErrorCode() const { jint out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!"); if( t.pEnv ){ // temporaere Variable initialisieren char * cSignature = "()I"; char * cMethodName = "getErrorCode"; // Java-Call absetzen jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ){ out = t.pEnv->CallIntMethod( object, mID); ThrowSQLException(t.pEnv,0); } //mID } //t.pEnv return (sal_Int32)out; } <commit_msg>INTEGRATION: CWS mav4 (1.4.76); FILE MERGED 2003/04/15 12:22:14 oj 1.4.76.1: #108943# merge from apps61beta2 and statement fix, concurrency<commit_after>/************************************************************************* * * $RCSfile: SQLException.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2003-04-24 13:22:09 $ * * 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 _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_ #include "java/sql/SQLException.hxx" #endif #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; //************************************************************** //************ Class: java.sql.SQLException //************************************************************** java_sql_SQLException::java_sql_SQLException( const java_sql_SQLException_BASE& _rException,const Reference< XInterface> & _rContext) : starsdbc::SQLException( _rException.getMessage(), _rContext, _rException.getSQLState(), _rException.getErrorCode(), makeAny(_rException.getNextException()) ) { } java_sql_SQLException_BASE::java_sql_SQLException_BASE( JNIEnv * pEnv, jobject myObj ) : java_lang_Exception( pEnv, myObj ) { } jclass java_sql_SQLException_BASE::theClass = 0; java_sql_SQLException_BASE::~java_sql_SQLException_BASE() {} jclass java_sql_SQLException_BASE::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass("java/sql/SQLException"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!"); if(!tempClass) { t.pEnv->ExceptionDescribe(); t.pEnv->ExceptionClear(); } jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_sql_SQLException_BASE::saveClassRef( jclass pClass ) { if( pClass==NULL ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } starsdbc::SQLException java_sql_SQLException_BASE::getNextException() const { jobject out = NULL; SDBThreadAttach t; if( t.pEnv ){ // temporaere Variable initialisieren char * cSignature = "()Ljava/sql/Exception;"; char * cMethodName = "getNextException"; // Java-Call absetzen jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = t.pEnv->CallObjectMethod( object, mID); ThrowSQLException(t.pEnv,0); } //mID } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return out ? (starsdbc::SQLException)java_sql_SQLException(java_sql_SQLException_BASE(t.pEnv,out),0) : starsdbc::SQLException(); } ::rtl::OUString java_sql_SQLException_BASE::getSQLState() const { jstring out = (jstring)NULL; SDBThreadAttach t; ::rtl::OUString aStr; if( t.pEnv ){ // temporaere Variable initialisieren char * cSignature = "()Ljava/lang/String;"; char * cMethodName = "getSQLState"; // Java-Call absetzen jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ){ out = (jstring) t.pEnv->CallObjectMethod( object, mID); ThrowSQLException(t.pEnv,0); if(out) aStr = JavaString2String(t.pEnv,out); } //mID } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return aStr; } sal_Int32 java_sql_SQLException_BASE::getErrorCode() const { jint out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!"); if( t.pEnv ){ // temporaere Variable initialisieren char * cSignature = "()I"; char * cMethodName = "getErrorCode"; // Java-Call absetzen jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ){ out = t.pEnv->CallIntMethod( object, mID); ThrowSQLException(t.pEnv,0); } //mID } //t.pEnv return (sal_Int32)out; } <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // 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. // A binary that crashes, either directly or by copying and re-executing, // to test the stack tracing symbolizer. #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include <string> #include "absl/base/attributes.h" #include "absl/strings/numbers.h" #include "sandboxed_api/util/raw_logging.h" #include "sandboxed_api/util/temp_file.h" ABSL_ATTRIBUTE_NOINLINE void CrashMe() { char* null = reinterpret_cast<char*>(0); *null = 0; } void RunWritable() { int exe_fd = open("/proc/self/exe", O_RDONLY); SAPI_RAW_PCHECK(exe_fd >= 0, "Opening /proc/self/exe"); std::string tmpname; int tmp_fd; std::tie(tmpname, tmp_fd) = sapi::CreateNamedTempFile("tmp").value(); SAPI_RAW_PCHECK(fchmod(tmp_fd, S_IRWXU) == 0, "Fchmod on temporary file"); char buf[4096]; while (true) { ssize_t read_cnt = read(exe_fd, buf, sizeof(buf)); SAPI_RAW_PCHECK(read_cnt >= 0, "Reading /proc/self/exe"); if (read_cnt == 0) { break; } SAPI_RAW_PCHECK(write(tmp_fd, buf, read_cnt) == read_cnt, "Writing temporary file"); } SAPI_RAW_PCHECK(close(tmp_fd) == 0, "Closing temporary file"); tmp_fd = open(tmpname.c_str(), O_RDONLY); SAPI_RAW_PCHECK(tmp_fd >= 0, "Reopening temporary file"); char prog_name[] = "crashme"; char testno[] = "1"; char* argv[] = {prog_name, testno, nullptr}; SAPI_RAW_PCHECK(execv(tmpname.c_str(), argv) == 0, "Executing copied binary"); } int main(int argc, char** argv) { if (argc < 2) { printf("argc < 3\n"); return EXIT_FAILURE; } int testno; SAPI_RAW_CHECK(absl::SimpleAtoi(argv[1], &testno), "testno not a number"); switch (testno) { case 1: CrashMe(); break; case 2: RunWritable(); break; default: printf("Unknown test: %d\n", testno); return EXIT_FAILURE; } printf("OK: All tests went OK\n"); return EXIT_SUCCESS; } <commit_msg>Fix Symbolize* tests.<commit_after>// Copyright 2019 Google LLC // // 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. // A binary that crashes, either directly or by copying and re-executing, // to test the stack tracing symbolizer. #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include <string> #include "absl/base/attributes.h" #include "absl/strings/numbers.h" #include "sandboxed_api/util/raw_logging.h" #include "sandboxed_api/util/temp_file.h" ABSL_ATTRIBUTE_NOINLINE void CrashMe() { volatile char* null = nullptr; *null = 0; } void RunWritable() { int exe_fd = open("/proc/self/exe", O_RDONLY); SAPI_RAW_PCHECK(exe_fd >= 0, "Opening /proc/self/exe"); std::string tmpname; int tmp_fd; std::tie(tmpname, tmp_fd) = sapi::CreateNamedTempFile("tmp").value(); SAPI_RAW_PCHECK(fchmod(tmp_fd, S_IRWXU) == 0, "Fchmod on temporary file"); char buf[4096]; while (true) { ssize_t read_cnt = read(exe_fd, buf, sizeof(buf)); SAPI_RAW_PCHECK(read_cnt >= 0, "Reading /proc/self/exe"); if (read_cnt == 0) { break; } SAPI_RAW_PCHECK(write(tmp_fd, buf, read_cnt) == read_cnt, "Writing temporary file"); } SAPI_RAW_PCHECK(close(tmp_fd) == 0, "Closing temporary file"); tmp_fd = open(tmpname.c_str(), O_RDONLY); SAPI_RAW_PCHECK(tmp_fd >= 0, "Reopening temporary file"); char prog_name[] = "crashme"; char testno[] = "1"; char* argv[] = {prog_name, testno, nullptr}; SAPI_RAW_PCHECK(execv(tmpname.c_str(), argv) == 0, "Executing copied binary"); } int main(int argc, char** argv) { if (argc < 2) { printf("argc < 3\n"); return EXIT_FAILURE; } int testno; SAPI_RAW_CHECK(absl::SimpleAtoi(argv[1], &testno), "testno not a number"); switch (testno) { case 1: CrashMe(); break; case 2: RunWritable(); break; default: printf("Unknown test: %d\n", testno); return EXIT_FAILURE; } printf("OK: All tests went OK\n"); return EXIT_SUCCESS; } <|endoftext|>