<commit_before>#ifndef ITERBASE_HPP_
#define ITERBASE_HPP_

// This file consists of utilities used for the generic nature of the
// iterable wrapper classes.  As such, the contents of this file should be
// considered UNDOCUMENTED and is subject to change without warning.  This
// also applies to the name of the file.  No user code should include
// this file directly.

#include <utility>
#include <iterator>
#include <functional>
#include <memory>
#include <type_traits>
#include <cstddef>

namespace iter {
  namespace impl {
    template <typename T>
    struct type_is {
      using type = T;
    };

    // gcc CWG 1558
    template <typename...>
    struct void_t_help {
      using type = void;
    };
    template <typename... Ts>
    using void_t = typename void_t_help<Ts...>::type;

    // iterator_type<C> is the type of C's iterator
    template <typename Container>
    using iterator_type = decltype(std::begin(std::declval<Container&>()));

    // iterator_deref<C> is the type obtained by dereferencing an iterator
    // to an object of type C
    template <typename Container>
    using iterator_deref = decltype(*std::declval<iterator_type<Container>&>());

    // const_iteator_deref is the type obtained through dereferencing
    // a const iterator& (note: not a const_iterator).  ie: the result
    // of Container::iterator::operator*() const
    template <typename Container>
    using const_iterator_deref =
        decltype(*std::declval<const iterator_type<Container>&>());

    template <typename Container>
    using iterator_traits_deref =
        typename std::remove_reference<iterator_deref<Container>>::type;

    // iterator_type<C> is the type of C's iterator
    template <typename Container>
    using reverse_iterator_type = decltype(std::declval<Container&>().rbegin());

    // iterator_deref<C> is the type obtained by dereferencing an iterator
    // to an object of type C
    template <typename Container>
    using reverse_iterator_deref =
        decltype(*std::declval<reverse_iterator_type<Container>&>());

    namespace detail {
      template <typename T, typename = void>
      struct ArrowHelper {
        using type = void;
      };

      template <typename T>
      struct ArrowHelper<T*, void> {
        using type = T*;
        constexpr type operator()(T* t) const noexcept {
          return t;
        }
      };

      template <typename T>
      struct ArrowHelper<T, void_t<decltype(std::declval<T&>().operator->())>> {
        using type = decltype(std::declval<T&>().operator->());
        type operator()(T& t) const {
          return t.operator->();
        }
      };

      template <typename T>
      using arrow = typename detail::ArrowHelper<T>::type;
    }

    // type of C::iterator::operator->, also works with pointers
    // void if the iterator has no operator->
    template <typename C>
    using iterator_arrow = detail::arrow<iterator_type<C>>;

    template <typename C>
    using reverse_iterator_arrow = detail::arrow<reverse_iterator_type<C>>;

    // applys the -> operator to an object, if the object is a pointer,
    // it returns the pointer
    template <typename T>
    detail::arrow<T> apply_arrow(T& t) {
      return detail::ArrowHelper<T>{}(t);
    }

    // For iterators that have an operator* which returns a value
    // they can return this type from their operator-> instead, which will
    // wrap an object and allow it to be used with arrow
    template <typename T>
    class ArrowProxy {
     private:
      using TPlain = typename std::remove_reference<T>::type;
      T obj;

     public:
      constexpr ArrowProxy(T&& in_obj) : obj(std::forward<T>(in_obj)) {}

      TPlain* operator->() {
        return &obj;
      }
    };

    template <typename, typename = void>
    struct is_random_access_iter : std::false_type {};

    template <typename T>
    struct is_random_access_iter<T,
        typename std::enable_if<std::is_same<typename std::iterator_traits<T>::
                                                 iterator_category,
                                    std::random_access_iterator_tag>::value,
                                     void>::type> : std::true_type {};

    template <typename T>
    using has_random_access_iter = is_random_access_iter<iterator_type<T>>;
    // because std::advance assumes a lot and is actually smart, I need a dumb

    // version that will work with most things
    template <typename InputIt, typename Distance = std::size_t>
    void dumb_advance(InputIt& iter, Distance distance = 1) {
      for (Distance i(0); i < distance; ++i) {
        ++iter;
      }
    }

    template <typename Iter, typename Distance>
    void dumb_advance_impl(
        Iter& iter, const Iter& end, Distance distance, std::false_type) {
      for (Distance i(0); i < distance && iter != end; ++i) {
        ++iter;
      }
    }

    template <typename Iter, typename Distance>
    void dumb_advance_impl(
        Iter& iter, const Iter& end, Distance distance, std::true_type) {
      if (static_cast<Distance>(end - iter) < distance) {
        iter = end;
      } else {
        iter += distance;
      }
    }

    // iter will not be incremented past end
    template <typename Iter, typename Distance = std::size_t>
    void dumb_advance(Iter& iter, const Iter& end, Distance distance = 1) {
      dumb_advance_impl(iter, end, distance, is_random_access_iter<Iter>{});
    }

    template <typename ForwardIt, typename Distance = std::size_t>
    ForwardIt dumb_next(ForwardIt it, Distance distance = 1) {
      dumb_advance(it, distance);
      return it;
    }

    template <typename ForwardIt, typename Distance = std::size_t>
    ForwardIt dumb_next(
        ForwardIt it, const ForwardIt& end, Distance distance = 1) {
      dumb_advance(it, end, distance);
      return it;
    }

    template <typename Container, typename Distance = std::size_t>
    Distance dumb_size(Container&& container) {
      Distance d{0};
      for (auto it = std::begin(container), end = std::end(container);
           it != end; ++it) {
        ++d;
      }
      return d;
    }

    template <typename... Ts>
    struct are_same : std::true_type {};

    template <typename T, typename U, typename... Ts>
    struct are_same<T, U, Ts...>
        : std::integral_constant<bool,
              std::is_same<T, U>::value && are_same<T, Ts...>::value> {};

    // DerefHolder holds the value gotten from an iterator dereference
    // if the iterate dereferences to an lvalue references, a pointer to the
    //     element is stored
    // if it does not, a value is stored instead
    // get() returns a reference to the held item
    // get_ptr() returns a pointer to the held item
    // reset() replaces the currently held item

    template <typename T, typename = void>
    class DerefHolder {
     private:
      static_assert(!std::is_lvalue_reference<T>::value,
          "Non-lvalue-ref specialization used for lvalue ref type");
      // it could still be an rvalue reference
      using TPlain = typename std::remove_reference<T>::type;

      std::unique_ptr<TPlain> item_p;

     public:
      using reference = TPlain&;
      using pointer = TPlain*;

      DerefHolder() = default;

      DerefHolder(const DerefHolder& other)
          : item_p{other.item_p ? new TPlain(*other.item_p) : nullptr} {}

      DerefHolder& operator=(const DerefHolder& other) {
        this->item_p.reset(other.item_p ? new TPlain(*other.item_p) : nullptr);
        return *this;
      }

      DerefHolder(DerefHolder&&) = default;
      DerefHolder& operator=(DerefHolder&&) = default;
      ~DerefHolder() = default;

      reference get() {
        return *this->item_p;
      }

      pointer get_ptr() {
        return this->item_p.get();
      }

      void reset(T&& item) {
        item_p.reset(new TPlain(std::move(item)));
      }

      explicit operator bool() const {
        return this->item_p;
      }
    };

    // Specialization for when T is an lvalue ref.  Keep this in mind
    // wherever a T appears.
    template <typename T>
    class DerefHolder<T,
        typename std::enable_if<std::is_lvalue_reference<T>::value>::type> {
     public:
      using reference = T;
      using pointer = typename std::remove_reference<T>::type*;

     private:
      pointer item_p{};

     public:
      DerefHolder() = default;

      reference get() {
        return *this->item_p;
      }

      pointer get_ptr() {
        return this->item_p;
      }

      void reset(T item) {
        this->item_p = &item;
      }

      explicit operator bool() const {
        return this->item_p != nullptr;
      }
    };
  }
}

#endif
<commit_msg>adds dummy operator()() to ArrowHelper<commit_after>#ifndef ITERBASE_HPP_
#define ITERBASE_HPP_

// This file consists of utilities used for the generic nature of the
// iterable wrapper classes.  As such, the contents of this file should be
// considered UNDOCUMENTED and is subject to change without warning.  This
// also applies to the name of the file.  No user code should include
// this file directly.

#include <utility>
#include <iterator>
#include <functional>
#include <memory>
#include <type_traits>
#include <cstddef>

namespace iter {
  namespace impl {
    template <typename T>
    struct type_is {
      using type = T;
    };

    // gcc CWG 1558
    template <typename...>
    struct void_t_help {
      using type = void;
    };
    template <typename... Ts>
    using void_t = typename void_t_help<Ts...>::type;

    // iterator_type<C> is the type of C's iterator
    template <typename Container>
    using iterator_type = decltype(std::begin(std::declval<Container&>()));

    // iterator_deref<C> is the type obtained by dereferencing an iterator
    // to an object of type C
    template <typename Container>
    using iterator_deref = decltype(*std::declval<iterator_type<Container>&>());

    // const_iteator_deref is the type obtained through dereferencing
    // a const iterator& (note: not a const_iterator).  ie: the result
    // of Container::iterator::operator*() const
    template <typename Container>
    using const_iterator_deref =
        decltype(*std::declval<const iterator_type<Container>&>());

    template <typename Container>
    using iterator_traits_deref =
        typename std::remove_reference<iterator_deref<Container>>::type;

    // iterator_type<C> is the type of C's iterator
    template <typename Container>
    using reverse_iterator_type = decltype(std::declval<Container&>().rbegin());

    // iterator_deref<C> is the type obtained by dereferencing an iterator
    // to an object of type C
    template <typename Container>
    using reverse_iterator_deref =
        decltype(*std::declval<reverse_iterator_type<Container>&>());

    namespace detail {
      template <typename T, typename = void>
      struct ArrowHelper {
        using type = void;
        void operator()(T&) const noexcept { }
      };

      template <typename T>
      struct ArrowHelper<T*, void> {
        using type = T*;
        constexpr type operator()(T* t) const noexcept {
          return t;
        }
      };

      template <typename T>
      struct ArrowHelper<T, void_t<decltype(std::declval<T&>().operator->())>> {
        using type = decltype(std::declval<T&>().operator->());
        type operator()(T& t) const {
          return t.operator->();
        }
      };

      template <typename T>
      using arrow = typename detail::ArrowHelper<T>::type;
    }

    // type of C::iterator::operator->, also works with pointers
    // void if the iterator has no operator->
    template <typename C>
    using iterator_arrow = detail::arrow<iterator_type<C>>;

    template <typename C>
    using reverse_iterator_arrow = detail::arrow<reverse_iterator_type<C>>;

    // applys the -> operator to an object, if the object is a pointer,
    // it returns the pointer
    template <typename T>
    detail::arrow<T> apply_arrow(T& t) {
      return detail::ArrowHelper<T>{}(t);
    }

    // For iterators that have an operator* which returns a value
    // they can return this type from their operator-> instead, which will
    // wrap an object and allow it to be used with arrow
    template <typename T>
    class ArrowProxy {
     private:
      using TPlain = typename std::remove_reference<T>::type;
      T obj;

     public:
      constexpr ArrowProxy(T&& in_obj) : obj(std::forward<T>(in_obj)) {}

      TPlain* operator->() {
        return &obj;
      }
    };

    template <typename, typename = void>
    struct is_random_access_iter : std::false_type {};

    template <typename T>
    struct is_random_access_iter<T,
        typename std::enable_if<std::is_same<typename std::iterator_traits<T>::
                                                 iterator_category,
                                    std::random_access_iterator_tag>::value,
                                     void>::type> : std::true_type {};

    template <typename T>
    using has_random_access_iter = is_random_access_iter<iterator_type<T>>;
    // because std::advance assumes a lot and is actually smart, I need a dumb

    // version that will work with most things
    template <typename InputIt, typename Distance = std::size_t>
    void dumb_advance(InputIt& iter, Distance distance = 1) {
      for (Distance i(0); i < distance; ++i) {
        ++iter;
      }
    }

    template <typename Iter, typename Distance>
    void dumb_advance_impl(
        Iter& iter, const Iter& end, Distance distance, std::false_type) {
      for (Distance i(0); i < distance && iter != end; ++i) {
        ++iter;
      }
    }

    template <typename Iter, typename Distance>
    void dumb_advance_impl(
        Iter& iter, const Iter& end, Distance distance, std::true_type) {
      if (static_cast<Distance>(end - iter) < distance) {
        iter = end;
      } else {
        iter += distance;
      }
    }

    // iter will not be incremented past end
    template <typename Iter, typename Distance = std::size_t>
    void dumb_advance(Iter& iter, const Iter& end, Distance distance = 1) {
      dumb_advance_impl(iter, end, distance, is_random_access_iter<Iter>{});
    }

    template <typename ForwardIt, typename Distance = std::size_t>
    ForwardIt dumb_next(ForwardIt it, Distance distance = 1) {
      dumb_advance(it, distance);
      return it;
    }

    template <typename ForwardIt, typename Distance = std::size_t>
    ForwardIt dumb_next(
        ForwardIt it, const ForwardIt& end, Distance distance = 1) {
      dumb_advance(it, end, distance);
      return it;
    }

    template <typename Container, typename Distance = std::size_t>
    Distance dumb_size(Container&& container) {
      Distance d{0};
      for (auto it = std::begin(container), end = std::end(container);
           it != end; ++it) {
        ++d;
      }
      return d;
    }

    template <typename... Ts>
    struct are_same : std::true_type {};

    template <typename T, typename U, typename... Ts>
    struct are_same<T, U, Ts...>
        : std::integral_constant<bool,
              std::is_same<T, U>::value && are_same<T, Ts...>::value> {};

    // DerefHolder holds the value gotten from an iterator dereference
    // if the iterate dereferences to an lvalue references, a pointer to the
    //     element is stored
    // if it does not, a value is stored instead
    // get() returns a reference to the held item
    // get_ptr() returns a pointer to the held item
    // reset() replaces the currently held item

    template <typename T, typename = void>
    class DerefHolder {
     private:
      static_assert(!std::is_lvalue_reference<T>::value,
          "Non-lvalue-ref specialization used for lvalue ref type");
      // it could still be an rvalue reference
      using TPlain = typename std::remove_reference<T>::type;

      std::unique_ptr<TPlain> item_p;

     public:
      using reference = TPlain&;
      using pointer = TPlain*;

      DerefHolder() = default;

      DerefHolder(const DerefHolder& other)
          : item_p{other.item_p ? new TPlain(*other.item_p) : nullptr} {}

      DerefHolder& operator=(const DerefHolder& other) {
        this->item_p.reset(other.item_p ? new TPlain(*other.item_p) : nullptr);
        return *this;
      }

      DerefHolder(DerefHolder&&) = default;
      DerefHolder& operator=(DerefHolder&&) = default;
      ~DerefHolder() = default;

      reference get() {
        return *this->item_p;
      }

      pointer get_ptr() {
        return this->item_p.get();
      }

      void reset(T&& item) {
        item_p.reset(new TPlain(std::move(item)));
      }

      explicit operator bool() const {
        return this->item_p;
      }
    };

    // Specialization for when T is an lvalue ref.  Keep this in mind
    // wherever a T appears.
    template <typename T>
    class DerefHolder<T,
        typename std::enable_if<std::is_lvalue_reference<T>::value>::type> {
     public:
      using reference = T;
      using pointer = typename std::remove_reference<T>::type*;

     private:
      pointer item_p{};

     public:
      DerefHolder() = default;

      reference get() {
        return *this->item_p;
      }

      pointer get_ptr() {
        return this->item_p;
      }

      void reset(T item) {
        this->item_p = &item;
      }

      explicit operator bool() const {
        return this->item_p != nullptr;
      }
    };
  }
}

#endif
<|endoftext|>


<commit_before>/*
 * HttpSocket.cpp
 *
 *  Created on: Oct 4, 2013
 *      Author: user
 */

#include "HttpSocket.hpp"

#include <fstream>
#include <sstream>
#include <iostream>

#include "common.hpp"

HttpGetter::HttpGetter(unsigned int timeout) :_timeout(timeout), curl((curl_easy_init())) {

}

HttpGetter::~HttpGetter()
{
	curl_easy_cleanup(curl);
}

bool HttpGetter::readContent(const std::string& url, unsigned int port, std::ostream& ostream) const {

	CURLcode code(CURLE_FAILED_INIT);

	if(curl && readDocumentSetup(url, port, curl, ostream))
	{
		code = curl_easy_perform(curl);
	}

	return code == CURLE_OK;
}

bool HttpGetter::readPostContent(const std::string& url, const std::string postParams, unsigned int port, std::ostream& ostream) const {

	CURLcode code(CURLE_FAILED_INIT);

	if(curl && CURLE_OK == curl_easy_setopt(curl, CURLOPT_POST, 1L) &&
			CURLE_OK == curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postParams.c_str()) &&
			readDocumentSetup(url, port, curl, ostream))
	{
		code = curl_easy_perform(curl);
	}

	return code == CURLE_OK;
}

bool HttpGetter::readDocumentSetup(const std::string& url, unsigned int port,  CURL* const curl, std::ostream& ostream) const {

		return CURLE_OK == curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &data_write)
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L)
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L)
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_FILE, &ostream)
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_TIMEOUT, _timeout)
		//&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_PORT, port)
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_URL, url.c_str())
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_ENCODING, "");
}

size_t HttpGetter::data_write(void* buf, size_t size, size_t nmemb, void* userp) {

	if (userp) {

		const std::streamsize len = size * nmemb;
		if (static_cast<std::ostream*>(userp)->write(static_cast<const char*>(buf), len)) {

			return len;
		}
	}
	return 0;
}

<commit_msg>https for curl<commit_after>/*
 * HttpSocket.cpp
 *
 *  Created on: Oct 4, 2013
 *      Author: user
 */

#include "HttpSocket.hpp"

#include <fstream>
#include <sstream>
#include <iostream>

#include "common.hpp"

HttpGetter::HttpGetter(unsigned int timeout) :_timeout(timeout), curl((curl_easy_init())) {

}

HttpGetter::~HttpGetter()
{
	curl_easy_cleanup(curl);
}

bool HttpGetter::readContent(const std::string& url, unsigned int port, std::ostream& ostream) const {

	CURLcode code(CURLE_FAILED_INIT);

	if(curl && readDocumentSetup(url, port, curl, ostream))
	{
		code = curl_easy_perform(curl);
	}

	return code == CURLE_OK;
}

bool HttpGetter::readPostContent(const std::string& url, const std::string postParams, unsigned int port, std::ostream& ostream) const {

	CURLcode code(CURLE_FAILED_INIT);

	if(curl && CURLE_OK == curl_easy_setopt(curl, CURLOPT_POST, 1L) &&
			CURLE_OK == curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postParams.c_str()) &&
			readDocumentSetup(url, port, curl, ostream))
	{
		code = curl_easy_perform(curl);
	}

	return code == CURLE_OK;
}

bool HttpGetter::readDocumentSetup(const std::string& url, unsigned int port,  CURL* const curl, std::ostream& ostream) const {

	 const bool isSSLconnection = url.substr(0, 5) == "https";

		return CURLE_OK == curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &data_write)
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L)
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L)
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_FILE, &ostream)
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_TIMEOUT, _timeout)
		//&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_PORT, port)
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_URL, url.c_str())
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_ENCODING, "")
		&& (!isSSLconnection || (CURLE_OK == curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L)
		&& CURLE_OK == curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L)));
}

size_t HttpGetter::data_write(void* buf, size_t size, size_t nmemb, void* userp) {

	if (userp) {

		const std::streamsize len = size * nmemb;
		if (static_cast<std::ostream*>(userp)->write(static_cast<const char*>(buf), len)) {

			return len;
		}
	}
	return 0;
}

<|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.                  *
 **************************************************************************/

/* $Id$ */

// Macro extracted from MUON test script
// By Laurent Aphecetche

#if !defined(__CINT__) || defined(__MAKECINT__)
#include "AliMUONReconstructor.h"
#include "AliMUONRecoParam.h"
#include "AliCDBManager.h"
#include "AliMagFMaps.h"
#include "AliTracker.h"
#include "AliReconstruction.h"
#include <TRandom.h>
//#include <TObjectTable.h>
#endif

void runReconstruction(int seed, const char* input, const char* recoptions)
{
  AliCDBManager* man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://$ALICE_ROOT");

  gRandom->SetSeed(seed);

  AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k5kG);
  AliTracker::SetFieldMap(field, kFALSE);

  AliReconstruction* MuonRec = new AliReconstruction("galice.root");
  MuonRec->SetInput(input);
  MuonRec->SetRunVertexFinder(kFALSE);
  MuonRec->SetRunLocalReconstruction("MUON");
  MuonRec->SetRunTracking("MUON");
  MuonRec->SetFillESD("");
  MuonRec->SetLoadAlignData("MUON");
  MuonRec->SetNumberOfEventsPerFile(1000);
  MuonRec->SetOption("MUON",recoptions);
  //  MuonRec->SetEventRange(319,319);
  MuonRec->SetWriteAOD();

  AliMUONRecoParam *muonRecoParam = AliMUONRecoParam::GetLowFluxParam();
  AliMUONReconstructor::SetRecoParam(muonRecoParam);
  muonRecoParam->Print("FULL");

  MuonRec->Run();

  delete MuonRec;

  //gObjectTable->Print();
}

<commit_msg>Now uses combined tracking (Laurent)<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.                  *
 **************************************************************************/

/* $Id$ */

// Macro extracted from MUON test script
// By Laurent Aphecetche

#if !defined(__CINT__) || defined(__MAKECINT__)
#include "AliMUONReconstructor.h"
#include "AliMUONRecoParam.h"
#include "AliCDBManager.h"
#include "AliMagFMaps.h"
#include "AliTracker.h"
#include "AliReconstruction.h"
#include <TRandom.h>
//#include <TObjectTable.h>
#endif

void runReconstruction(int seed, const char* input, const char* recoptions)
{
  AliCDBManager* man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://$ALICE_ROOT");

  gRandom->SetSeed(seed);

  AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k5kG);
  AliTracker::SetFieldMap(field, kFALSE);

  AliReconstruction* MuonRec = new AliReconstruction("galice.root");
  MuonRec->SetInput(input);
  MuonRec->SetRunVertexFinder(kFALSE);
  MuonRec->SetRunLocalReconstruction("MUON");
  MuonRec->SetRunTracking("MUON");
  MuonRec->SetFillESD("");
  MuonRec->SetLoadAlignData("MUON");
  MuonRec->SetNumberOfEventsPerFile(1000);
  MuonRec->SetOption("MUON",recoptions);
  //  MuonRec->SetEventRange(319,319);
  MuonRec->SetWriteAOD();

  AliMUONRecoParam *muonRecoParam = AliMUONRecoParam::GetLowFluxParam();
  muonRecoParam->CombineClusterTrackReco(kTRUE);

  AliMUONReconstructor::SetRecoParam(muonRecoParam);
  muonRecoParam->Print("FULL");

  MuonRec->Run();

  delete MuonRec;

  //gObjectTable->Print();
}

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2013 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include "boost_std_shared_shim.hpp" // FIXME - do we need it?
// The functions in this file produce deprecation warnings.
// But as shield symbolizer doesn't fully support more than one
// placement from python yet these functions are actually the
// correct ones.

#define NO_DEPRECATION_WARNINGS

// boost
#include <boost/python.hpp>
#include <boost/variant.hpp>
#include <boost/python/suite/indexing/map_indexing_suite.hpp>
// mapnik
#include <mapnik/symbolizer.hpp>
#include <mapnik/symbolizer_hash.hpp>
#include <mapnik/symbolizer_utils.hpp>
#include <mapnik/symbolizer_keys.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/path_expression.hpp>
#include "mapnik_enumeration.hpp"
#include "mapnik_svg.hpp"
#include <mapnik/graphics.hpp>
#include <mapnik/expression_node.hpp>
#include <mapnik/value_error.hpp>
#include <mapnik/marker_cache.hpp> // for known_svg_prefix_

// stl
#include <sstream>

using mapnik::symbolizer;
using mapnik::point_symbolizer;
using mapnik::line_symbolizer;
using mapnik::line_pattern_symbolizer;
using mapnik::polygon_symbolizer;
using mapnik::polygon_pattern_symbolizer;
using mapnik::raster_symbolizer;
using mapnik::shield_symbolizer;
using mapnik::text_symbolizer;
using mapnik::building_symbolizer;
using mapnik::markers_symbolizer;
using mapnik::debug_symbolizer;
using mapnik::symbolizer_base;
using mapnik::color;
using mapnik::path_processor_type;
using mapnik::path_expression_ptr;
using mapnik::guess_type;
using mapnik::expression_ptr;
using mapnik::parse_path;

namespace {
using namespace boost::python;
void __setitem__(mapnik::symbolizer_base & sym, std::string const& name, mapnik::symbolizer_base::value_type const& val)
{
    put(sym, mapnik::get_key(name), val);
}

std::shared_ptr<mapnik::symbolizer_base::value_type> numeric_wrapper(const object& arg)
{
    std::shared_ptr<mapnik::symbolizer_base::value_type> result;
    if (PyBool_Check(arg.ptr()))
    {
        mapnik::value_bool val = extract<mapnik::value_bool>(arg);
        result.reset(new mapnik::symbolizer_base::value_type(val));
    }
    else if (PyFloat_Check(arg.ptr()))
    {
        mapnik::value_double val = extract<mapnik::value_double>(arg);
        result.reset(new mapnik::symbolizer_base::value_type(val));
    }
    else
    {
        mapnik::value_integer val = extract<mapnik::value_integer>(arg);
        result.reset(new mapnik::symbolizer_base::value_type(val));
    }
    return result;
}

struct extract_python_object : public boost::static_visitor<boost::python::object>
{
    typedef boost::python::object result_type;

    template <typename T>
    auto operator() (T const& val) const -> result_type
    {
        return result_type(val); // wrap into python object
    }
};

boost::python::object __getitem__(mapnik::symbolizer_base const& sym, std::string const& name)
{
    typedef symbolizer_base::cont_type::const_iterator const_iterator;
    mapnik::keys key = mapnik::get_key(name);
    const_iterator itr = sym.properties.find(key);
    if (itr != sym.properties.end())
    {
        return boost::apply_visitor(extract_python_object(), itr->second);
    }
    //mapnik::property_meta_type const& meta = mapnik::get_meta(key);
    //return boost::apply_visitor(extract_python_object(), std::get<1>(meta));
    return boost::python::object();
}

struct symbolizer_to_json : public boost::static_visitor<std::string>
{
    typedef std::string result_type;

    template <typename T>
    auto operator() (T const& sym) const -> result_type
    {
        std::stringstream ss;
        ss << "{\"type\":\"" << mapnik::symbolizer_traits<T>::name() << "\",";
        ss << "\"properties\":{";
        bool first = true;
        for (auto const& prop : sym.properties)
        {
            auto const& meta = mapnik::get_meta(prop.first);
            if (first) first = false;
            else ss << ",";
            ss << "\"" <<  std::get<0>(meta) << "\":";
            ss << boost::apply_visitor(mapnik::symbolizer_property_value_string<mapnik::property_meta_type>(meta),prop.second);
        }
        ss << "}}";
        return ss.str();
    }
};

std::string __str__(mapnik::symbolizer const& sym)
{
    return boost::apply_visitor(symbolizer_to_json(), sym);
}

std::string get_symbolizer_type(symbolizer const& sym)
{
    return mapnik::symbolizer_name(sym); // FIXME - do we need this ?
}

struct symbolizer_hash_visitor : public boost::static_visitor<std::size_t>
{
    template <typename T>
    std::size_t operator() (T const& sym) const
    {
        return mapnik::symbolizer_hash::value(sym);
    }
};

std::size_t hash_impl(symbolizer const& sym)
{
    return boost::apply_visitor(symbolizer_hash_visitor(), sym);
}

template <typename T>
std::size_t hash_impl_2(T const& sym)
{
    return mapnik::symbolizer_hash::value<T>(sym);
}

struct extract_underlying_type_visitor : boost::static_visitor<boost::python::object>
{
    template <typename T>
    boost::python::object operator() (T const& sym) const
    {
        return boost::python::object(sym);
    }
};

boost::python::object extract_underlying_type(symbolizer const& sym)
{
    return boost::apply_visitor(extract_underlying_type_visitor(), sym);
}

}

void export_symbolizer()
{
    using namespace boost::python;

    //implicitly_convertible<mapnik::value_bool, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<mapnik::value_integer, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<mapnik::value_double, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<std::string, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<mapnik::color, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<mapnik::expression_ptr, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<mapnik::enumeration_wrapper, mapnik::symbolizer_base::value_type>();

    enum_<mapnik::keys>("keys")
        .value("gamma", mapnik::keys::gamma)
        .value("gamma_method",mapnik::keys::gamma_method)
        ;

    class_<symbolizer>("Symbolizer",no_init)
        .def("type",get_symbolizer_type)
        .def("__hash__",hash_impl)
        .def("extract", extract_underlying_type)
        ;

    class_<symbolizer_base::value_type>("NumericWrapper")
        .def("__init__", make_constructor(numeric_wrapper))
        ;

    class_<symbolizer_base>("SymbolizerBase",no_init)
        .def("__setitem__",&__setitem__)
        .def("__setattr__",&__setitem__)
        .def("__getitem__",&__getitem__)
        .def("__getattr__",&__getitem__)
        .def("__str__", &__str__)
        ;
}

void export_shield_symbolizer()
{
    using namespace boost::python;
    class_< shield_symbolizer, bases<text_symbolizer> >("ShieldSymbolizer",
                                                        init<>("Default ctor"))
        .def("__hash__",hash_impl_2<shield_symbolizer>)
        ;

}

void export_polygon_symbolizer()
{
    using namespace boost::python;

    class_<polygon_symbolizer, bases<symbolizer_base> >("PolygonSymbolizer",
                                                        init<>("Default ctor"))
        .def("__hash__",hash_impl_2<polygon_symbolizer>)
        ;

}

void export_polygon_pattern_symbolizer()
{
    using namespace boost::python;

    mapnik::enumeration_<mapnik::pattern_alignment_e>("pattern_alignment")
        .value("LOCAL",mapnik::LOCAL_ALIGNMENT)
        .value("GLOBAL",mapnik::GLOBAL_ALIGNMENT)
        ;

    class_<polygon_pattern_symbolizer>("PolygonPatternSymbolizer",
                                       init<>("Default ctor"))
        .def("__hash__",hash_impl_2<polygon_pattern_symbolizer>)
        ;
}

void export_raster_symbolizer()
{
    using namespace boost::python;

    class_<raster_symbolizer, bases<symbolizer_base> >("RasterSymbolizer",
                              init<>("Default ctor"))
        ;
}

void export_point_symbolizer()
{
    using namespace boost::python;

    mapnik::enumeration_<mapnik::point_placement_e>("point_placement")
        .value("CENTROID",mapnik::CENTROID_POINT_PLACEMENT)
        .value("INTERIOR",mapnik::INTERIOR_POINT_PLACEMENT)
        ;

    class_<point_symbolizer, bases<symbolizer_base> >("PointSymbolizer",
                             init<>("Default Point Symbolizer - 4x4 black square"))
        .def("__hash__",hash_impl_2<point_symbolizer>)
        ;
}

void export_markers_symbolizer()
{
    using namespace boost::python;

    mapnik::enumeration_<mapnik::marker_placement_e>("marker_placement")
        .value("POINT_PLACEMENT",mapnik::MARKER_POINT_PLACEMENT)
        .value("INTERIOR_PLACEMENT",mapnik::MARKER_INTERIOR_PLACEMENT)
        .value("LINE_PLACEMENT",mapnik::MARKER_LINE_PLACEMENT)
        ;

    mapnik::enumeration_<mapnik::marker_multi_policy_e>("marker_multi_policy")
        .value("EACH",mapnik::MARKER_EACH_MULTI)
        .value("WHOLE",mapnik::MARKER_WHOLE_MULTI)
        .value("LARGEST",mapnik::MARKER_LARGEST_MULTI)
        ;

    class_<markers_symbolizer, bases<symbolizer_base> >("MarkersSymbolizer",
                               init<>("Default Markers Symbolizer - circle"))
        .def("__hash__",hash_impl_2<markers_symbolizer>)
        ;
}

void export_line_symbolizer()
{
    using namespace boost::python;
    mapnik::enumeration_<mapnik::line_rasterizer_e>("line_rasterizer")
        .value("FULL",mapnik::RASTERIZER_FULL)
        .value("FAST",mapnik::RASTERIZER_FAST)
        ;

    class_<line_symbolizer, bases<symbolizer_base> >("LineSymbolizer",
                            init<>("Default LineSymbolizer - 1px solid black"))
        .def("__hash__",hash_impl_2<line_symbolizer>)
        ;
}

void export_line_pattern_symbolizer()
{
    using namespace boost::python;

    class_<line_pattern_symbolizer, bases<symbolizer_base> >("LinePatternSymbolizer",
                                    init<> ("Default LinePatternSymbolizer"))
        .def("__hash__",hash_impl_2<line_pattern_symbolizer>)
        ;
}

void export_debug_symbolizer()
{
    using namespace boost::python;

    mapnik::enumeration_<mapnik::debug_symbolizer_mode_e>("debug_symbolizer_mode")
        .value("COLLISION",mapnik::DEBUG_SYM_MODE_COLLISION)
        .value("VERTEX",mapnik::DEBUG_SYM_MODE_VERTEX)
        ;

    class_<debug_symbolizer, bases<symbolizer_base> >("DebugSymbolizer",
                             init<>("Default debug Symbolizer"))
        .def("__hash__",hash_impl_2<debug_symbolizer>)
        ;
}

void export_building_symbolizer()
{
    using namespace boost::python;

    class_<building_symbolizer, bases<symbolizer_base> >("BuildingSymbolizer",
                               init<>("Default BuildingSymbolizer"))
        .def("__hash__",hash_impl_2<building_symbolizer>)
        ;

}
<commit_msg>add equality comparator ``` .def(self == self) // __eq__```<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2013 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include "boost_std_shared_shim.hpp" // FIXME - do we need it?
// The functions in this file produce deprecation warnings.
// But as shield symbolizer doesn't fully support more than one
// placement from python yet these functions are actually the
// correct ones.

#define NO_DEPRECATION_WARNINGS

// boost
#include <boost/python.hpp>
#include <boost/variant.hpp>
#include <boost/python/suite/indexing/map_indexing_suite.hpp>
// mapnik
#include <mapnik/symbolizer.hpp>
#include <mapnik/symbolizer_hash.hpp>
#include <mapnik/symbolizer_utils.hpp>
#include <mapnik/symbolizer_keys.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/path_expression.hpp>
#include "mapnik_enumeration.hpp"
#include "mapnik_svg.hpp"
#include <mapnik/graphics.hpp>
#include <mapnik/expression_node.hpp>
#include <mapnik/value_error.hpp>
#include <mapnik/marker_cache.hpp> // for known_svg_prefix_

// stl
#include <sstream>

using mapnik::symbolizer;
using mapnik::point_symbolizer;
using mapnik::line_symbolizer;
using mapnik::line_pattern_symbolizer;
using mapnik::polygon_symbolizer;
using mapnik::polygon_pattern_symbolizer;
using mapnik::raster_symbolizer;
using mapnik::shield_symbolizer;
using mapnik::text_symbolizer;
using mapnik::building_symbolizer;
using mapnik::markers_symbolizer;
using mapnik::debug_symbolizer;
using mapnik::symbolizer_base;
using mapnik::color;
using mapnik::path_processor_type;
using mapnik::path_expression_ptr;
using mapnik::guess_type;
using mapnik::expression_ptr;
using mapnik::parse_path;

namespace {
using namespace boost::python;
void __setitem__(mapnik::symbolizer_base & sym, std::string const& name, mapnik::symbolizer_base::value_type const& val)
{
    put(sym, mapnik::get_key(name), val);
}

std::shared_ptr<mapnik::symbolizer_base::value_type> numeric_wrapper(const object& arg)
{
    std::shared_ptr<mapnik::symbolizer_base::value_type> result;
    if (PyBool_Check(arg.ptr()))
    {
        mapnik::value_bool val = extract<mapnik::value_bool>(arg);
        result.reset(new mapnik::symbolizer_base::value_type(val));
    }
    else if (PyFloat_Check(arg.ptr()))
    {
        mapnik::value_double val = extract<mapnik::value_double>(arg);
        result.reset(new mapnik::symbolizer_base::value_type(val));
    }
    else
    {
        mapnik::value_integer val = extract<mapnik::value_integer>(arg);
        result.reset(new mapnik::symbolizer_base::value_type(val));
    }
    return result;
}

struct extract_python_object : public boost::static_visitor<boost::python::object>
{
    typedef boost::python::object result_type;

    template <typename T>
    auto operator() (T const& val) const -> result_type
    {
        return result_type(val); // wrap into python object
    }
};

boost::python::object __getitem__(mapnik::symbolizer_base const& sym, std::string const& name)
{
    typedef symbolizer_base::cont_type::const_iterator const_iterator;
    mapnik::keys key = mapnik::get_key(name);
    const_iterator itr = sym.properties.find(key);
    if (itr != sym.properties.end())
    {
        return boost::apply_visitor(extract_python_object(), itr->second);
    }
    //mapnik::property_meta_type const& meta = mapnik::get_meta(key);
    //return boost::apply_visitor(extract_python_object(), std::get<1>(meta));
    return boost::python::object();
}

struct symbolizer_to_json : public boost::static_visitor<std::string>
{
    typedef std::string result_type;

    template <typename T>
    auto operator() (T const& sym) const -> result_type
    {
        std::stringstream ss;
        ss << "{\"type\":\"" << mapnik::symbolizer_traits<T>::name() << "\",";
        ss << "\"properties\":{";
        bool first = true;
        for (auto const& prop : sym.properties)
        {
            auto const& meta = mapnik::get_meta(prop.first);
            if (first) first = false;
            else ss << ",";
            ss << "\"" <<  std::get<0>(meta) << "\":";
            ss << boost::apply_visitor(mapnik::symbolizer_property_value_string<mapnik::property_meta_type>(meta),prop.second);
        }
        ss << "}}";
        return ss.str();
    }
};

std::string __str__(mapnik::symbolizer const& sym)
{
    return boost::apply_visitor(symbolizer_to_json(), sym);
}

std::string get_symbolizer_type(symbolizer const& sym)
{
    return mapnik::symbolizer_name(sym); // FIXME - do we need this ?
}

struct symbolizer_hash_visitor : public boost::static_visitor<std::size_t>
{
    template <typename T>
    std::size_t operator() (T const& sym) const
    {
        return mapnik::symbolizer_hash::value(sym);
    }
};

std::size_t hash_impl(symbolizer const& sym)
{
    return boost::apply_visitor(symbolizer_hash_visitor(), sym);
}

template <typename T>
std::size_t hash_impl_2(T const& sym)
{
    return mapnik::symbolizer_hash::value<T>(sym);
}

struct extract_underlying_type_visitor : boost::static_visitor<boost::python::object>
{
    template <typename T>
    boost::python::object operator() (T const& sym) const
    {
        return boost::python::object(sym);
    }
};

boost::python::object extract_underlying_type(symbolizer const& sym)
{
    return boost::apply_visitor(extract_underlying_type_visitor(), sym);
}

}

void export_symbolizer()
{
    using namespace boost::python;

    //implicitly_convertible<mapnik::value_bool, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<mapnik::value_integer, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<mapnik::value_double, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<std::string, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<mapnik::color, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<mapnik::expression_ptr, mapnik::symbolizer_base::value_type>();
    implicitly_convertible<mapnik::enumeration_wrapper, mapnik::symbolizer_base::value_type>();

    enum_<mapnik::keys>("keys")
        .value("gamma", mapnik::keys::gamma)
        .value("gamma_method",mapnik::keys::gamma_method)
        ;

    class_<symbolizer>("Symbolizer",no_init)
        .def("type",get_symbolizer_type)
        .def("__hash__",hash_impl)
        .def("extract", extract_underlying_type)
        ;

    class_<symbolizer_base::value_type>("NumericWrapper")
        .def("__init__", make_constructor(numeric_wrapper))
        ;

    class_<symbolizer_base>("SymbolizerBase",no_init)
        .def("__setitem__",&__setitem__)
        .def("__setattr__",&__setitem__)
        .def("__getitem__",&__getitem__)
        .def("__getattr__",&__getitem__)
        .def("__str__", &__str__)
        .def(self == self) // __eq__
        ;
}

void export_shield_symbolizer()
{
    using namespace boost::python;
    class_< shield_symbolizer, bases<text_symbolizer> >("ShieldSymbolizer",
                                                        init<>("Default ctor"))
        .def("__hash__",hash_impl_2<shield_symbolizer>)
        ;

}

void export_polygon_symbolizer()
{
    using namespace boost::python;

    class_<polygon_symbolizer, bases<symbolizer_base> >("PolygonSymbolizer",
                                                        init<>("Default ctor"))
        .def("__hash__",hash_impl_2<polygon_symbolizer>)
        ;

}

void export_polygon_pattern_symbolizer()
{
    using namespace boost::python;

    mapnik::enumeration_<mapnik::pattern_alignment_e>("pattern_alignment")
        .value("LOCAL",mapnik::LOCAL_ALIGNMENT)
        .value("GLOBAL",mapnik::GLOBAL_ALIGNMENT)
        ;

    class_<polygon_pattern_symbolizer>("PolygonPatternSymbolizer",
                                       init<>("Default ctor"))
        .def("__hash__",hash_impl_2<polygon_pattern_symbolizer>)
        ;
}

void export_raster_symbolizer()
{
    using namespace boost::python;

    class_<raster_symbolizer, bases<symbolizer_base> >("RasterSymbolizer",
                              init<>("Default ctor"))
        ;
}

void export_point_symbolizer()
{
    using namespace boost::python;

    mapnik::enumeration_<mapnik::point_placement_e>("point_placement")
        .value("CENTROID",mapnik::CENTROID_POINT_PLACEMENT)
        .value("INTERIOR",mapnik::INTERIOR_POINT_PLACEMENT)
        ;

    class_<point_symbolizer, bases<symbolizer_base> >("PointSymbolizer",
                             init<>("Default Point Symbolizer - 4x4 black square"))
        .def("__hash__",hash_impl_2<point_symbolizer>)
        ;
}

void export_markers_symbolizer()
{
    using namespace boost::python;

    mapnik::enumeration_<mapnik::marker_placement_e>("marker_placement")
        .value("POINT_PLACEMENT",mapnik::MARKER_POINT_PLACEMENT)
        .value("INTERIOR_PLACEMENT",mapnik::MARKER_INTERIOR_PLACEMENT)
        .value("LINE_PLACEMENT",mapnik::MARKER_LINE_PLACEMENT)
        ;

    mapnik::enumeration_<mapnik::marker_multi_policy_e>("marker_multi_policy")
        .value("EACH",mapnik::MARKER_EACH_MULTI)
        .value("WHOLE",mapnik::MARKER_WHOLE_MULTI)
        .value("LARGEST",mapnik::MARKER_LARGEST_MULTI)
        ;

    class_<markers_symbolizer, bases<symbolizer_base> >("MarkersSymbolizer",
                               init<>("Default Markers Symbolizer - circle"))
        .def("__hash__",hash_impl_2<markers_symbolizer>)
        ;
}

void export_line_symbolizer()
{
    using namespace boost::python;
    mapnik::enumeration_<mapnik::line_rasterizer_e>("line_rasterizer")
        .value("FULL",mapnik::RASTERIZER_FULL)
        .value("FAST",mapnik::RASTERIZER_FAST)
        ;

    class_<line_symbolizer, bases<symbolizer_base> >("LineSymbolizer",
                            init<>("Default LineSymbolizer - 1px solid black"))
        .def("__hash__",hash_impl_2<line_symbolizer>)
        ;
}

void export_line_pattern_symbolizer()
{
    using namespace boost::python;

    class_<line_pattern_symbolizer, bases<symbolizer_base> >("LinePatternSymbolizer",
                                    init<> ("Default LinePatternSymbolizer"))
        .def("__hash__",hash_impl_2<line_pattern_symbolizer>)
        ;
}

void export_debug_symbolizer()
{
    using namespace boost::python;

    mapnik::enumeration_<mapnik::debug_symbolizer_mode_e>("debug_symbolizer_mode")
        .value("COLLISION",mapnik::DEBUG_SYM_MODE_COLLISION)
        .value("VERTEX",mapnik::DEBUG_SYM_MODE_VERTEX)
        ;

    class_<debug_symbolizer, bases<symbolizer_base> >("DebugSymbolizer",
                             init<>("Default debug Symbolizer"))
        .def("__hash__",hash_impl_2<debug_symbolizer>)
        ;
}

void export_building_symbolizer()
{
    using namespace boost::python;

    class_<building_symbolizer, bases<symbolizer_base> >("BuildingSymbolizer",
                               init<>("Default BuildingSymbolizer"))
        .def("__hash__",hash_impl_2<building_symbolizer>)
        ;

}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  $Id$
 *
 */

#ifndef PCL_FEATURES_IMPL_USC_HPP_
#define PCL_FEATURES_IMPL_USC_HPP_

#include <pcl/features/usc.h>
#include <pcl/features/shot_common.h>
#include <pcl/common/geometry.h>
#include <pcl/common/angles.h>
#include <pcl/common/utils.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> bool
pcl::UniqueShapeContext<PointInT, PointOutT>::initCompute ()
{
  if (!Feature<PointInT, PointOutT>::initCompute ())
  {
    PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ());
    return (false);
  }

  if (search_radius_< min_radius_)
  {
    PCL_ERROR ("[pcl::%s::initCompute] search_radius_ must be GREATER than min_radius_.\n", getClassName ().c_str ());
    return (false);
  }

  // Update descriptor length
  descriptor_length_ = elevation_bins_ * azimuth_bins_ * radius_bins_;

  // Compute radial, elevation and azimuth divisions
  float azimuth_interval = (float) 360 / azimuth_bins_;
  float elevation_interval = (float) 180 / elevation_bins_;

  // Reallocate divisions and volume lut
  radii_interval_.clear ();
  phi_divisions_.clear ();
  theta_divisions_.clear ();
  volume_lut_.clear ();

  // Fills radii interval based on formula (1) in section 2.1 of Frome's paper
  radii_interval_.resize (radius_bins_ + 1);
  for (size_t j = 0; j < radius_bins_ + 1; j++)
    radii_interval_[j] = exp (log (min_radius_) + (((float) j / (radius_bins_)) * log (search_radius_/min_radius_)));

  // Fill theta didvisions of elevation
  theta_divisions_.resize (elevation_bins_+1);
  for (size_t k = 0; k < elevation_bins_+1; k++)
    theta_divisions_[k] = k*elevation_interval;

  // Fill phi didvisions of elevation
  phi_divisions_.resize (azimuth_bins_+1);
  for (size_t l = 0; l < azimuth_bins_+1; l++)
    phi_divisions_[l] = l*azimuth_interval;

  // LookUp Table that contains the volume of all the bins
  // "phi" term of the volume integral
  // "integr_phi" has always the same value so we compute it only one time
  float integr_phi  = pcl::deg2rad (phi_divisions_[1]) - pcl::deg2rad (phi_divisions_[0]);
  // exponential to compute the cube root using pow
  float e = 1.0 / 3.0;
  // Resize volume look up table
  volume_lut_.resize (radius_bins_ * elevation_bins_ * azimuth_bins_);
  // Fill volumes look up table
  for (size_t j = 0; j < radius_bins_; j++)
  {
    // "r" term of the volume integral
    float integr_r = (radii_interval_[j+1]*radii_interval_[j+1]*radii_interval_[j+1] / 3) - (radii_interval_[j]*radii_interval_[j]*radii_interval_[j]/ 3);

    for (size_t k = 0; k < elevation_bins_; k++)
    {
      // "theta" term of the volume integral
      float integr_theta = cos (deg2rad (theta_divisions_[k])) - cos (deg2rad (theta_divisions_[k+1]));
      // Volume
      float V = integr_phi * integr_theta * integr_r;
      // Compute cube root of the computed volume commented for performance but left
      // here for clarity
      // float cbrt = pow(V, e);
      // cbrt = 1 / cbrt;

      for (size_t l = 0; l < azimuth_bins_; l++)
        // Store in lut 1/cbrt
        //volume_lut_[ (l*elevation_bins_*radius_bins_) + k*radius_bins_ + j ] = cbrt;
        volume_lut_[(l*elevation_bins_*radius_bins_) + k*radius_bins_ + j] = 1.0 / pow (V, e);
    }
  }
  return (true);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> bool
pcl::UniqueShapeContext<PointInT, PointOutT>::computePointRF (size_t index, float rf[9])
{
  std::vector<int> nn_indices;
  std::vector<float> nn_dists;
  size_t nb_neighbours = searchForNeighbors ((*indices_)[index], local_radius_, nn_indices, nn_dists);

  // The RF is formed as the SHOT local RF
  if (nb_neighbours < 5)
  {
    //PCL_WARN ("[pcl::%s::computePointRF] Neighborhood has %d vertices which is less than 5, aborting description of point index %d\n!", getClassName ().c_str (), nb_neighbours, (*indices_)[index]);
    return (false);
  }
  std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > rf_ (3);
  Eigen::Vector4f central_point = input_->points[(*indices_)[index]].getVector4fMap ();
  central_point[3] = 0;
  pcl::getLocalRF (*surface_, local_radius_, central_point /*(*indices_)[index]*/, nn_indices, nn_dists, rf_);
  for (int d = 0; d < 9; ++d)
    rf[d] = rf_[d/3][d%3];

  return (true);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> void
pcl::UniqueShapeContext<PointInT, PointOutT>::computePointDescriptor (size_t index, float rf[9], std::vector<float> &desc)
{
  pcl::Vector3fMapConst origin = input_->points[(*indices_)[index]].getVector3fMap ();
  const Eigen::Map<Eigen::Vector3f> x_axis (rf);
  const Eigen::Map<Eigen::Vector3f> y_axis (rf + 3);
  const Eigen::Map<Eigen::Vector3f> normal (rf + 6);
  // Find every point within specified search_radius_
  std::vector<int> nn_indices;
  std::vector<float> nn_dists;
  const size_t neighb_cnt = searchForNeighbors ((*indices_)[index], search_radius_, nn_indices, nn_dists);
  // For each point within radius
  for (size_t ne = 0; ne < neighb_cnt; ne++)
  {
    if (pcl::utils::equal(nn_dists[ne], 0.0f))
      continue;
    // Get neighbours coordinates
    Eigen::Vector3f neighbour = surface_->points[nn_indices[ne]].getVector3fMap ();

    // ----- Compute current neighbour polar coordinates -----

    // Get distance between the neighbour and the origin
    float r = sqrt (nn_dists[ne]);

    // Project point into the tangent plane
    Eigen::Vector3f proj;
    pcl::geometry::project (neighbour, origin, normal, proj);
    proj -= origin;

    // Normalize to compute the dot product
    proj.normalize ();

    // Compute the angle between the projection and the x axis in the interval [0,360]
    Eigen::Vector3f cross = x_axis.cross (proj);
    float phi = rad2deg (std::atan2 (cross.norm (), x_axis.dot (proj)));
    phi = cross.dot (normal) < 0.f ? (360.0 - phi) : phi;
    /// Compute the angle between the neighbour and the z axis (normal) in the interval [0, 180]
    Eigen::Vector3f no = neighbour - origin;
    no.normalize ();
    float theta = normal.dot (no);
    theta = pcl::rad2deg (acos (std::min (1.0f, std::max (-1.0f, theta))));

    /// Bin (j, k, l)
    size_t j = 0;
    size_t k = 0;
    size_t l = 0;

    /// Compute the Bin(j, k, l) coordinates of current neighbour
    for (size_t rad = 1; rad < radius_bins_ + 1; rad++)
    {
      if (r <= radii_interval_[rad])
      {
        j = rad - 1;
        break;
      }
    }

    for (size_t ang = 1; ang < elevation_bins_ + 1; ang++)
    {
      if (theta <= theta_divisions_[ang])
      {
        k = ang - 1;
        break;
      }
    }

    for (size_t ang = 1; ang < azimuth_bins_ + 1; ang++)
    {
      if (phi <= phi_divisions_[ang])
      {
        l = ang - 1;
        break;
      }
    }

    /// Local point density = number of points in a sphere of radius "point_density_radius_" around the current neighbour
    std::vector<int> neighbour_indices;
    std::vector<float> neighbour_didtances;
    float point_density = (float) searchForNeighbors (*surface_, nn_indices[ne], point_density_radius_, neighbour_indices, neighbour_didtances);
    /// point_density is always bigger than 0 because FindPointsWithinRadius returns at least the point itself
    float w = (1.0 / point_density) * volume_lut_[(l*elevation_bins_*radius_bins_) +
                                                  (k*radius_bins_) +
                                                  j];

    assert (w >= 0.0);
    if (w == std::numeric_limits<float>::infinity ())
      PCL_ERROR ("Shape Context Error INF!\n");
    if (w != w)
      PCL_ERROR ("Shape Context Error IND!\n");
    /// Accumulate w into correspondant Bin(j,k,l)
    desc[(l*elevation_bins_*radius_bins_) + (k*radius_bins_) + j] += w;

    assert (desc[(l*elevation_bins_*radius_bins_) + (k*radius_bins_) + j] >= 0);
  } // end for each neighbour
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> void
pcl::UniqueShapeContext<PointInT, PointOutT>::computeFeature (PointCloudOut &output)
{
  for (size_t point_index = 0; point_index < indices_->size (); point_index++)
  {
    output[point_index].descriptor.resize (descriptor_length_);
    computePointRF (point_index, output[point_index].rf);
    computePointDescriptor (point_index, output[point_index].rf, output[point_index].descriptor);
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::UniqueShapeContext<PointInT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output)
{
  Eigen::VectorXf rf (9);
  output.points.resize (indices_->size (), descriptor_length_ + 9);
  for (size_t point_index = 0; point_index < indices_->size (); point_index++)
  {
    computePointRF (point_index, rf.data ());
    output.points.row (point_index) = rf;
    std::vector<float> descriptor (descriptor_length_);
    computePointDescriptor (point_index, rf.data (), descriptor);
    for (size_t j = 0; j < descriptor_length_; ++j)
      output.points (point_index, 9 + j) = descriptor[j];
  }
}

#define PCL_INSTANTIATE_UniqueShapeContext(T,OutT) template class PCL_EXPORTS pcl::UniqueShapeContext<T,OutT>;

#endif
<commit_msg>bug fix for DEBUG<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  $Id$
 *
 */

#ifndef PCL_FEATURES_IMPL_USC_HPP_
#define PCL_FEATURES_IMPL_USC_HPP_

#include <pcl/features/usc.h>
#include <pcl/features/shot_common.h>
#include <pcl/common/geometry.h>
#include <pcl/common/angles.h>
#include <pcl/common/utils.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> bool
pcl::UniqueShapeContext<PointInT, PointOutT>::initCompute ()
{
  if (!Feature<PointInT, PointOutT>::initCompute ())
  {
    PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ());
    return (false);
  }

  if (search_radius_< min_radius_)
  {
    PCL_ERROR ("[pcl::%s::initCompute] search_radius_ must be GREATER than min_radius_.\n", getClassName ().c_str ());
    return (false);
  }

  // Update descriptor length
  descriptor_length_ = elevation_bins_ * azimuth_bins_ * radius_bins_;

  // Compute radial, elevation and azimuth divisions
  float azimuth_interval = (float) 360 / azimuth_bins_;
  float elevation_interval = (float) 180 / elevation_bins_;

  // Reallocate divisions and volume lut
  radii_interval_.clear ();
  phi_divisions_.clear ();
  theta_divisions_.clear ();
  volume_lut_.clear ();

  // Fills radii interval based on formula (1) in section 2.1 of Frome's paper
  radii_interval_.resize (radius_bins_ + 1);
  for (size_t j = 0; j < radius_bins_ + 1; j++)
    radii_interval_[j] = exp (log (min_radius_) + (((float) j / (radius_bins_)) * log (search_radius_/min_radius_)));

  // Fill theta didvisions of elevation
  theta_divisions_.resize (elevation_bins_+1);
  for (size_t k = 0; k < elevation_bins_+1; k++)
    theta_divisions_[k] = k*elevation_interval;

  // Fill phi didvisions of elevation
  phi_divisions_.resize (azimuth_bins_+1);
  for (size_t l = 0; l < azimuth_bins_+1; l++)
    phi_divisions_[l] = l*azimuth_interval;

  // LookUp Table that contains the volume of all the bins
  // "phi" term of the volume integral
  // "integr_phi" has always the same value so we compute it only one time
  float integr_phi  = pcl::deg2rad (phi_divisions_[1]) - pcl::deg2rad (phi_divisions_[0]);
  // exponential to compute the cube root using pow
  float e = 1.0 / 3.0;
  // Resize volume look up table
  volume_lut_.resize (radius_bins_ * elevation_bins_ * azimuth_bins_);
  // Fill volumes look up table
  for (size_t j = 0; j < radius_bins_; j++)
  {
    // "r" term of the volume integral
    float integr_r = (radii_interval_[j+1]*radii_interval_[j+1]*radii_interval_[j+1] / 3) - (radii_interval_[j]*radii_interval_[j]*radii_interval_[j]/ 3);

    for (size_t k = 0; k < elevation_bins_; k++)
    {
      // "theta" term of the volume integral
      float integr_theta = cos (deg2rad (theta_divisions_[k])) - cos (deg2rad (theta_divisions_[k+1]));
      // Volume
      float V = integr_phi * integr_theta * integr_r;
      // Compute cube root of the computed volume commented for performance but left
      // here for clarity
      // float cbrt = pow(V, e);
      // cbrt = 1 / cbrt;

      for (size_t l = 0; l < azimuth_bins_; l++)
        // Store in lut 1/cbrt
        //volume_lut_[ (l*elevation_bins_*radius_bins_) + k*radius_bins_ + j ] = cbrt;
        volume_lut_[(l*elevation_bins_*radius_bins_) + k*radius_bins_ + j] = 1.0 / pow (V, e);
    }
  }
  return (true);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> bool
pcl::UniqueShapeContext<PointInT, PointOutT>::computePointRF (size_t index, float rf[9])
{
  std::vector<int> nn_indices;
  std::vector<float> nn_dists;
  size_t nb_neighbours = searchForNeighbors ((*indices_)[index], local_radius_, nn_indices, nn_dists);

  // The RF is formed as the SHOT local RF
  if (nb_neighbours < 5)
  {
    //PCL_WARN ("[pcl::%s::computePointRF] Neighborhood has %d vertices which is less than 5, aborting description of point index %d\n!", getClassName ().c_str (), nb_neighbours, (*indices_)[index]);
    return (false);
  }
  std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > rf_ (3);
  Eigen::Vector4f central_point = input_->points[(*indices_)[index]].getVector4fMap ();
  central_point[3] = 0;
  pcl::getLocalRF (*surface_, local_radius_, central_point /*(*indices_)[index]*/, nn_indices, nn_dists, rf_);
  for (int d = 0; d < 9; ++d)
    rf[d] = rf_[d/3][d%3];

  return (true);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> void
pcl::UniqueShapeContext<PointInT, PointOutT>::computePointDescriptor (size_t index, float rf[9], std::vector<float> &desc)
{
  pcl::Vector3fMapConst origin = input_->points[(*indices_)[index]].getVector3fMap ();
  const Eigen::Map<Eigen::Vector3f> x_axis (rf);
  const Eigen::Map<Eigen::Vector3f> y_axis (rf + 3);
  const Eigen::Map<Eigen::Vector3f> normal (rf + 6);
  // Find every point within specified search_radius_
  std::vector<int> nn_indices;
  std::vector<float> nn_dists;
  const size_t neighb_cnt = searchForNeighbors ((*indices_)[index], search_radius_, nn_indices, nn_dists);
  // For each point within radius
  for (size_t ne = 0; ne < neighb_cnt; ne++)
  {
    if (pcl::utils::equal(nn_dists[ne], 0.0f))
      continue;
    // Get neighbours coordinates
    Eigen::Vector3f neighbour = surface_->points[nn_indices[ne]].getVector3fMap ();

    // ----- Compute current neighbour polar coordinates -----

    // Get distance between the neighbour and the origin
    float r = sqrt (nn_dists[ne]);

    // Project point into the tangent plane
    Eigen::Vector3f proj;
    pcl::geometry::project (neighbour, origin, normal, proj);
    proj -= origin;

    // Normalize to compute the dot product
    proj.normalize ();

    // Compute the angle between the projection and the x axis in the interval [0,360]
    Eigen::Vector3f cross = x_axis.cross (proj);
    float phi = rad2deg (std::atan2 (cross.norm (), x_axis.dot (proj)));
    phi = cross.dot (normal) < 0.f ? (360.0 - phi) : phi;
    /// Compute the angle between the neighbour and the z axis (normal) in the interval [0, 180]
    Eigen::Vector3f no = neighbour - origin;
    no.normalize ();
    float theta = normal.dot (no);
    theta = pcl::rad2deg (acos (std::min (1.0f, std::max (-1.0f, theta))));

    /// Bin (j, k, l)
    size_t j = 0;
    size_t k = 0;
    size_t l = 0;

    /// Compute the Bin(j, k, l) coordinates of current neighbour
    for (size_t rad = 1; rad < radius_bins_ + 1; rad++)
    {
      if (r <= radii_interval_[rad])
      {
        j = rad - 1;
        break;
      }
    }

    for (size_t ang = 1; ang < elevation_bins_ + 1; ang++)
    {
      if (theta <= theta_divisions_[ang])
      {
        k = ang - 1;
        break;
      }
    }

    for (size_t ang = 1; ang < azimuth_bins_ + 1; ang++)
    {
      if (phi <= phi_divisions_[ang])
      {
        l = ang - 1;
        break;
      }
    }

    /// Local point density = number of points in a sphere of radius "point_density_radius_" around the current neighbour
    std::vector<int> neighbour_indices;
    std::vector<float> neighbour_didtances;
    float point_density = (float) searchForNeighbors (*surface_, nn_indices[ne], point_density_radius_, neighbour_indices, neighbour_didtances);
    /// point_density is always bigger than 0 because FindPointsWithinRadius returns at least the point itself
    float w = (1.0 / point_density) * volume_lut_[(l*elevation_bins_*radius_bins_) +
                                                  (k*radius_bins_) +
                                                  j];

    assert (w >= 0.0);
    if (w == std::numeric_limits<float>::infinity ())
      PCL_ERROR ("Shape Context Error INF!\n");
    if (w != w)
      PCL_ERROR ("Shape Context Error IND!\n");
    /// Accumulate w into correspondant Bin(j,k,l)
    desc[(l*elevation_bins_*radius_bins_) + (k*radius_bins_) + j] += w;

    assert (desc[(l*elevation_bins_*radius_bins_) + (k*radius_bins_) + j] >= 0);
  } // end for each neighbour
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointOutT> void
pcl::UniqueShapeContext<PointInT, PointOutT>::computeFeature (PointCloudOut &output)
{
  for (size_t point_index = 0; point_index < indices_->size (); point_index++)
  {
    output[point_index].descriptor.resize (descriptor_length_);
    computePointRF (point_index, output[point_index].rf);
    computePointDescriptor (point_index, output[point_index].rf, output[point_index].descriptor);
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::UniqueShapeContext<PointInT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output)
{
  Eigen::VectorXf rf (9);
  output.points.resize (indices_->size (), descriptor_length_ + 9);
  for (size_t point_index = 0; point_index < indices_->size (); point_index++)
  {
    computePointRF (point_index, rf.data ());
    for (int j = 0; j < 9; ++j)
      output.points (point_index, j) = rf[j];
    std::vector<float> descriptor (descriptor_length_);
    computePointDescriptor (point_index, rf.data (), descriptor);
    for (size_t j = 0; j < descriptor_length_; ++j)
      output.points (point_index, 9 + j) = descriptor[j];
  }
}

#define PCL_INSTANTIATE_UniqueShapeContext(T,OutT) template class PCL_EXPORTS pcl::UniqueShapeContext<T,OutT>;

#endif
<|endoftext|>


<commit_before>/*Santiago Zubieta*/
#include <iostream>
#include <numeric>
#include <fstream>
#include <climits>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <deque>
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>

using namespace std;

map<char, double> table;

void initMap() {
// Mapping between chemical symbols and their molar weights
    table['H'] = 1.008;
    table['C'] = 12.01;
    table['N'] = 14.01;
    table['O'] = 16.00;
}

bool isNumeric(char c) {
// Return if the representation of a character is that of a number
    return '0' <= c  && c <= '9';
}

int main() {
    int T;
    // Number of Test Cases
    string s;
    // String containing the read element chain
    initMap();
    cin >> T;
    while(T--) {
        cin >> s;
        // USE DOUBLE PRECISION SERIOUSLY, WITH FLOAT IT LOSES PRECISION WAY
        // TOO FAST, and I can confirm it costed me a submission ;-)
        double total = 0;
        // Total molar weight of a given molecule
        double num = 0;
        // The value of the last read element, to apply multipliers into
        int mult = 0;
        // The multiplier to apply to the chemical element right before it
        for(int k = 0; k < s.length(); k++) {
            if(isNumeric(s[k])) {
            // If we're reading a indice value
                if(mult != 0) {
                // If we had just read one, it means the previous one is a
                // decimal place bigger than the current one, but both are
                // part of the same number. I think this allows to exceed
                // the bound of two decimal places that the problem has.
                    mult *= 10;
                }
                mult += s[k] - '0';
            }
            else {
            // If a chemical symbol is read
                if(mult != 0) {
                // Check if we had a previously computed index, and apply it to
                // the previously found chemical element, if any.
                    num *= mult;
                }
                mult = 0;
                // Reset the chemical element multiplier
                total += num;
                // Add the previously found number to the running count of mass
                num = table[s[k]];
                // Set a new value to possibly apply a multiplying factor later
            }
        }
        // Do the last step again in case we ran out of the string and never
        // got to find a new element that would cause the previously found mult
        // liplier to apply to the previously found element and add it into the
        // running total of mole mass for the given molecule.
        if(mult != 0) {
            num *= mult;
        }
        total += num;
        printf("%.3lf\n", total);
        // Print with 3 decimal places
    }
}<commit_msg>Added second batch of problems from Summer Training, 2014<commit_after>/*Santiago Zubieta*/
#include <iostream>
#include <numeric>
#include <fstream>
#include <climits>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <deque>
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>

using namespace std;

map<char, double> table;
// A cheap 'Periodic Table'! :-)

void initMap() {
// Mapping between chemical symbols and their molar weights
    table['H'] = 1.008;
    table['C'] = 12.01;
    table['N'] = 14.01;
    table['O'] = 16.00;
}

bool isNumeric(char c) {
// Return if the representation of a character is that of a number
    return '0' <= c  && c <= '9';
}

int main() {
    int T;
    // Number of Test Cases
    string s;
    // String containing the read element chain
    initMap();
    cin >> T;
    while(T--) {
        cin >> s;
        // USE DOUBLE PRECISION SERIOUSLY, WITH FLOAT IT LOSES PRECISION WAY
        // TOO FAST, and I can confirm it costed me a submission ;-)
        double total = 0;
        // Total molar weight of a given molecule
        double num = 0;
        // The value of the last read element, to apply multipliers into
        int mult = 0;
        // The multiplier to apply to the chemical element right before it
        for(int k = 0; k < s.length(); k++) {
            if(isNumeric(s[k])) {
            // If we're reading a indice value
                if(mult != 0) {
                // If we had just read one, it means the previous one is a
                // decimal place bigger than the current one, but both are
                // part of the same number. I think this allows to exceed
                // the bound of two decimal places that the problem has.
                    mult *= 10;
                }
                mult += s[k] - '0';
            }
            else {
            // If a chemical symbol is read
                if(mult != 0) {
                // Check if we had a previously computed index, and apply it to
                // the previously found chemical element, if any.
                    num *= mult;
                }
                mult = 0;
                // Reset the chemical element multiplier
                total += num;
                // Add the previously found number to the running count of mass
                num = table[s[k]];
                // Set a new value to possibly apply a multiplying factor later
            }
        }
        // Do the last step again in case we ran out of the string and never
        // got to find a new element that would cause the previously found mult
        // liplier to apply to the previously found element and add it into the
        // running total of mole mass for the given molecule.
        if(mult != 0) {
            num *= mult;
        }
        total += num;
        printf("%.3lf\n", total);
        // Print with 3 decimal places
    }
}<|endoftext|>


<commit_before>
#include "PreCompiled.h"

#include <Base/Unit.h>

// inclusion of the generated files (generated out of UnitPy.xml)
#include <Base/UnitPy.h>
#include <Base/QuantityPy.h>
#include <Base/UnitPy.cpp>

using namespace Base;

// returns a string which represents the object e.g. when printed in python
std::string UnitPy::representation(void) const
{
    const UnitSignature &  Sig = getUnitPtr()->getSignature();
    std::stringstream ret;
    ret << "Unit: ";
    ret << getUnitPtr()->getString().toUtf8().constData() << " (";
    ret << Sig.Length << ",";
    ret << Sig.Mass  << ",";
    ret << Sig.Time  << ",";
    ret << Sig.ElectricCurrent  << ",";
    ret << Sig.ThermodynamicTemperature << ",";
    ret << Sig.AmountOfSubstance  << ",";
    ret << Sig.LuminousIntensity  << ",";
    ret << Sig.Angle  << ")";
    std::string type = getUnitPtr()->getTypeString().toUtf8().constData();
    if (! type.empty())
        ret << " [" << type << "]";

    return ret.str();
}

PyObject *UnitPy::PyMake(struct _typeobject *, PyObject *, PyObject *)  // Python wrapper
{
    // create a new instance of UnitPy and the Twin object
    return new UnitPy(new Unit);
}

// constructor method
int UnitPy::PyInit(PyObject* args, PyObject* /*kwd*/)
{
    Unit *self = getUnitPtr();

    int i1=0;
    int i2=0;
    int i3=0;
    int i4=0;
    int i5=0;
    int i6=0;
    int i7=0;
    int i8=0;
    if (PyArg_ParseTuple(args, "|iiiiiiii", &i1,&i2,&i3,&i4,&i5,&i6,&i7,&i8)) {
        *self = Unit(i1,i2,i3,i4,i5,i6,i7,i8);
        return 0;
    }
    PyErr_Clear(); // set by PyArg_ParseTuple()

    PyObject *object;

    if (PyArg_ParseTuple(args,"O!",&(Base::QuantityPy::Type), &object)) {
        // Note: must be static_cast, not reinterpret_cast
        *self = static_cast<Base::QuantityPy*>(object)->getQuantityPtr()->getUnit();
        return 0;
    }
    PyErr_Clear(); // set by PyArg_ParseTuple()

    if (PyArg_ParseTuple(args,"O!",&(Base::UnitPy::Type), &object)) {
        // Note: must be static_cast, not reinterpret_cast
        *self = *(static_cast<Base::UnitPy*>(object)->getUnitPtr());
        return 0;
    }
    PyErr_Clear(); // set by PyArg_ParseTuple()
    char* string;
    if (PyArg_ParseTuple(args,"et", "utf-8", &string)) {
        QString qstr = QString::fromUtf8(string);
        PyMem_Free(string);
        try {
            *self = Quantity::parse(qstr).getUnit();
            return 0;
        }
        catch (const Base::Exception& e) {
            PyErr_SetString(PyExc_RuntimeError, e.what());
            return -1;
        }
    }

    PyErr_SetString(PyExc_TypeError, "Either string, (float,8 ints), Unit() or Quantity()");
    return -1;
}

PyObject* UnitPy::number_add_handler(PyObject *self, PyObject *other)
{
    if (!PyObject_TypeCheck(self, &(UnitPy::Type))) {
        PyErr_SetString(PyExc_TypeError, "First arg must be Unit");
        return 0;
    }
    if (!PyObject_TypeCheck(other, &(UnitPy::Type))) {
        PyErr_SetString(PyExc_TypeError, "Second arg must be Unit");
        return 0;
    }
    Base::Unit *a = static_cast<UnitPy*>(self)->getUnitPtr();
    Base::Unit *b = static_cast<UnitPy*>(other)->getUnitPtr();

    if (*a != *b) {
        PyErr_SetString(PyExc_TypeError, "Units not matching!");
        return 0;
    }

    return new UnitPy(new Unit(*a));
}

PyObject* UnitPy::number_subtract_handler(PyObject *self, PyObject *other)
{
    if (!PyObject_TypeCheck(self, &(UnitPy::Type))) {
        PyErr_SetString(PyExc_TypeError, "First arg must be Unit");
        return 0;
    }
    if (!PyObject_TypeCheck(other, &(UnitPy::Type))) {
        PyErr_SetString(PyExc_TypeError, "Second arg must be Unit");
        return 0;
    }
    Base::Unit *a = static_cast<UnitPy*>(self)->getUnitPtr();
    Base::Unit *b = static_cast<UnitPy*>(other)->getUnitPtr();

    if (*a != *b) {
        PyErr_SetString(PyExc_TypeError, "Units not matching!");
        return 0;
    }

    return new UnitPy(new Unit(*a));
}

PyObject* UnitPy::number_multiply_handler(PyObject *self, PyObject *other)
{
    if (!PyObject_TypeCheck(self, &(UnitPy::Type))) {
        PyErr_SetString(PyExc_TypeError, "First arg must be Unit");
        return 0;
    }

    if (PyObject_TypeCheck(other, &(UnitPy::Type))) {
        Base::Unit *a = static_cast<UnitPy*>(self) ->getUnitPtr();
        Base::Unit *b = static_cast<UnitPy*>(other)->getUnitPtr();

        return new UnitPy(new Unit( (*a) * (*b) ) );
    }
    else {
        PyErr_SetString(PyExc_TypeError, "A Unit can only be multiplied by a Unit");
        return 0;
    }
}

PyObject* UnitPy::richCompare(PyObject *v, PyObject *w, int op)
{
    if (PyObject_TypeCheck(v, &(UnitPy::Type)) &&
        PyObject_TypeCheck(w, &(UnitPy::Type))) {
        const Unit * u1 = static_cast<UnitPy*>(v)->getUnitPtr();
        const Unit * u2 = static_cast<UnitPy*>(w)->getUnitPtr();

        PyObject *res=0;
        if (op != Py_EQ && op != Py_NE) {
            PyErr_SetString(PyExc_TypeError,
            "no ordering relation is defined for Units");
            return 0;
        }
        else if (op == Py_EQ) {
            res = (*u1 == *u2) ? Py_True : Py_False;
            Py_INCREF(res);
            return res;
        }
        else {
            res = (*u1 != *u2) ? Py_True : Py_False;
            Py_INCREF(res);
            return res;
        }
    }
    else {
        // This always returns False
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }
}

Py::String UnitPy::getType(void) const
{
    return Py::String(getUnitPtr()->getTypeString().toUtf8(),"utf-8");
}

Py::Tuple UnitPy::getSignature(void) const
{
    const UnitSignature &  Sig = getUnitPtr()->getSignature();
    Py::Tuple tuple(8);
    tuple.setItem(0, Py::Long(Sig.Length));
    tuple.setItem(1, Py::Long(Sig.Mass));
    tuple.setItem(2, Py::Long(Sig.Time));
    tuple.setItem(3, Py::Long(Sig.ElectricCurrent));
    tuple.setItem(4, Py::Long(Sig.ThermodynamicTemperature));
    tuple.setItem(5, Py::Long(Sig.AmountOfSubstance));
    tuple.setItem(6, Py::Long(Sig.LuminousIntensity));
    tuple.setItem(7, Py::Long(Sig.Angle));
    return tuple;
}

PyObject *UnitPy::getCustomAttributes(const char* /*attr*/) const
{
    return 0;
}

int UnitPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
    return 0;
}

PyObject * UnitPy::number_divide_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_remainder_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_divmod_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_power_handler (PyObject* /*self*/, PyObject* /*other*/, PyObject* /*modulo*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_negative_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_positive_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_absolute_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

int UnitPy::number_nonzero_handler (PyObject* /*self*/)
{
    return 1;
}

PyObject * UnitPy::number_invert_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_lshift_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_rshift_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_and_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_xor_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_or_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

#if PY_MAJOR_VERSION < 3
int UnitPy::number_coerce_handler (PyObject** /*self*/, PyObject** /*other*/)
{
    return 1;
}
#endif

PyObject * UnitPy::number_int_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

#if PY_MAJOR_VERSION < 3
PyObject * UnitPy::number_long_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}
#endif

PyObject * UnitPy::number_float_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

#if PY_MAJOR_VERSION < 3
PyObject * UnitPy::number_oct_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_hex_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}
#endif
<commit_msg>Python: [skip ci] exception handling in PyInit to avoid to close application<commit_after>
#include "PreCompiled.h"

#include <Base/Unit.h>

// inclusion of the generated files (generated out of UnitPy.xml)
#include <Base/UnitPy.h>
#include <Base/QuantityPy.h>
#include <Base/UnitPy.cpp>

using namespace Base;

// returns a string which represents the object e.g. when printed in python
std::string UnitPy::representation(void) const
{
    const UnitSignature &  Sig = getUnitPtr()->getSignature();
    std::stringstream ret;
    ret << "Unit: ";
    ret << getUnitPtr()->getString().toUtf8().constData() << " (";
    ret << Sig.Length << ",";
    ret << Sig.Mass  << ",";
    ret << Sig.Time  << ",";
    ret << Sig.ElectricCurrent  << ",";
    ret << Sig.ThermodynamicTemperature << ",";
    ret << Sig.AmountOfSubstance  << ",";
    ret << Sig.LuminousIntensity  << ",";
    ret << Sig.Angle  << ")";
    std::string type = getUnitPtr()->getTypeString().toUtf8().constData();
    if (! type.empty())
        ret << " [" << type << "]";

    return ret.str();
}

PyObject *UnitPy::PyMake(struct _typeobject *, PyObject *, PyObject *)  // Python wrapper
{
    // create a new instance of UnitPy and the Twin object
    return new UnitPy(new Unit);
}

// constructor method
int UnitPy::PyInit(PyObject* args, PyObject* /*kwd*/)
{
    Unit *self = getUnitPtr();

    int i1=0;
    int i2=0;
    int i3=0;
    int i4=0;
    int i5=0;
    int i6=0;
    int i7=0;
    int i8=0;
    if (PyArg_ParseTuple(args, "|iiiiiiii", &i1,&i2,&i3,&i4,&i5,&i6,&i7,&i8)) {
        try {
            *self = Unit(i1,i2,i3,i4,i5,i6,i7,i8);
            return 0;
        }
        catch (const Base::OverflowError& e) {
            PyErr_SetString(PyExc_OverflowError, e.what());
            return -1;
        }
    }
    PyErr_Clear(); // set by PyArg_ParseTuple()

    PyObject *object;

    if (PyArg_ParseTuple(args,"O!",&(Base::QuantityPy::Type), &object)) {
        // Note: must be static_cast, not reinterpret_cast
        *self = static_cast<Base::QuantityPy*>(object)->getQuantityPtr()->getUnit();
        return 0;
    }
    PyErr_Clear(); // set by PyArg_ParseTuple()

    if (PyArg_ParseTuple(args,"O!",&(Base::UnitPy::Type), &object)) {
        // Note: must be static_cast, not reinterpret_cast
        *self = *(static_cast<Base::UnitPy*>(object)->getUnitPtr());
        return 0;
    }
    PyErr_Clear(); // set by PyArg_ParseTuple()
    char* string;
    if (PyArg_ParseTuple(args,"et", "utf-8", &string)) {
        QString qstr = QString::fromUtf8(string);
        PyMem_Free(string);
        try {
            *self = Quantity::parse(qstr).getUnit();
            return 0;
        }
        catch (const Base::Exception& e) {
            PyErr_SetString(PyExc_RuntimeError, e.what());
            return -1;
        }
    }

    PyErr_SetString(PyExc_TypeError, "Either string, (float,8 ints), Unit() or Quantity()");
    return -1;
}

PyObject* UnitPy::number_add_handler(PyObject *self, PyObject *other)
{
    if (!PyObject_TypeCheck(self, &(UnitPy::Type))) {
        PyErr_SetString(PyExc_TypeError, "First arg must be Unit");
        return 0;
    }
    if (!PyObject_TypeCheck(other, &(UnitPy::Type))) {
        PyErr_SetString(PyExc_TypeError, "Second arg must be Unit");
        return 0;
    }
    Base::Unit *a = static_cast<UnitPy*>(self)->getUnitPtr();
    Base::Unit *b = static_cast<UnitPy*>(other)->getUnitPtr();

    if (*a != *b) {
        PyErr_SetString(PyExc_TypeError, "Units not matching!");
        return 0;
    }

    return new UnitPy(new Unit(*a));
}

PyObject* UnitPy::number_subtract_handler(PyObject *self, PyObject *other)
{
    if (!PyObject_TypeCheck(self, &(UnitPy::Type))) {
        PyErr_SetString(PyExc_TypeError, "First arg must be Unit");
        return 0;
    }
    if (!PyObject_TypeCheck(other, &(UnitPy::Type))) {
        PyErr_SetString(PyExc_TypeError, "Second arg must be Unit");
        return 0;
    }
    Base::Unit *a = static_cast<UnitPy*>(self)->getUnitPtr();
    Base::Unit *b = static_cast<UnitPy*>(other)->getUnitPtr();

    if (*a != *b) {
        PyErr_SetString(PyExc_TypeError, "Units not matching!");
        return 0;
    }

    return new UnitPy(new Unit(*a));
}

PyObject* UnitPy::number_multiply_handler(PyObject *self, PyObject *other)
{
    if (!PyObject_TypeCheck(self, &(UnitPy::Type))) {
        PyErr_SetString(PyExc_TypeError, "First arg must be Unit");
        return 0;
    }

    if (PyObject_TypeCheck(other, &(UnitPy::Type))) {
        Base::Unit *a = static_cast<UnitPy*>(self) ->getUnitPtr();
        Base::Unit *b = static_cast<UnitPy*>(other)->getUnitPtr();

        return new UnitPy(new Unit( (*a) * (*b) ) );
    }
    else {
        PyErr_SetString(PyExc_TypeError, "A Unit can only be multiplied by a Unit");
        return 0;
    }
}

PyObject* UnitPy::richCompare(PyObject *v, PyObject *w, int op)
{
    if (PyObject_TypeCheck(v, &(UnitPy::Type)) &&
        PyObject_TypeCheck(w, &(UnitPy::Type))) {
        const Unit * u1 = static_cast<UnitPy*>(v)->getUnitPtr();
        const Unit * u2 = static_cast<UnitPy*>(w)->getUnitPtr();

        PyObject *res=0;
        if (op != Py_EQ && op != Py_NE) {
            PyErr_SetString(PyExc_TypeError,
            "no ordering relation is defined for Units");
            return 0;
        }
        else if (op == Py_EQ) {
            res = (*u1 == *u2) ? Py_True : Py_False;
            Py_INCREF(res);
            return res;
        }
        else {
            res = (*u1 != *u2) ? Py_True : Py_False;
            Py_INCREF(res);
            return res;
        }
    }
    else {
        // This always returns False
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }
}

Py::String UnitPy::getType(void) const
{
    return Py::String(getUnitPtr()->getTypeString().toUtf8(),"utf-8");
}

Py::Tuple UnitPy::getSignature(void) const
{
    const UnitSignature &  Sig = getUnitPtr()->getSignature();
    Py::Tuple tuple(8);
    tuple.setItem(0, Py::Long(Sig.Length));
    tuple.setItem(1, Py::Long(Sig.Mass));
    tuple.setItem(2, Py::Long(Sig.Time));
    tuple.setItem(3, Py::Long(Sig.ElectricCurrent));
    tuple.setItem(4, Py::Long(Sig.ThermodynamicTemperature));
    tuple.setItem(5, Py::Long(Sig.AmountOfSubstance));
    tuple.setItem(6, Py::Long(Sig.LuminousIntensity));
    tuple.setItem(7, Py::Long(Sig.Angle));
    return tuple;
}

PyObject *UnitPy::getCustomAttributes(const char* /*attr*/) const
{
    return 0;
}

int UnitPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
    return 0;
}

PyObject * UnitPy::number_divide_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_remainder_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_divmod_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_power_handler (PyObject* /*self*/, PyObject* /*other*/, PyObject* /*modulo*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_negative_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_positive_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_absolute_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

int UnitPy::number_nonzero_handler (PyObject* /*self*/)
{
    return 1;
}

PyObject * UnitPy::number_invert_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_lshift_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_rshift_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_and_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_xor_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_or_handler (PyObject* /*self*/, PyObject* /*other*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

#if PY_MAJOR_VERSION < 3
int UnitPy::number_coerce_handler (PyObject** /*self*/, PyObject** /*other*/)
{
    return 1;
}
#endif

PyObject * UnitPy::number_int_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

#if PY_MAJOR_VERSION < 3
PyObject * UnitPy::number_long_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}
#endif

PyObject * UnitPy::number_float_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

#if PY_MAJOR_VERSION < 3
PyObject * UnitPy::number_oct_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}

PyObject * UnitPy::number_hex_handler (PyObject* /*self*/)
{
    PyErr_SetString(PyExc_NotImplementedError, "Not implemented");
    return 0;
}
#endif
<|endoftext|>


<commit_before>class Solution {
    public:
        bool isMatch(const char *s, const char *p) {
            if(*p == '\0') return *p == *s;
            if(*p == '?') return isMatch(++s, ++p);
            else if(*p == '*'){
                while(*p == '*') ++p;
                for(p; *s != '\0'; ++s){
                    if(isMatch(s, p) == true) return true;
                }
                return *p == '\0';
            }
            else return *p == *s && isMatch(++s, ++p);
        }
};
<commit_msg>add a non-recursive solution<commit_after>// http://yucoding.blogspot.com/2013/02/leetcode-question-123-wildcard-matching.html
class Solution {
    public:
        bool isMatch(const char *s, const char *p) {
            const char *star = NULL;
            const char *ss = s;
            while(*s){
                if(*s == *p || *p == '?'){ ++s; ++p; continue;}
                if(*p == '*'){ star = p++; ss = s; continue;}
                if(star){ p = star + 1; s = ++ss; continue;}
                return false;
            }
            while(*p == '*') ++p;
            return !*p;
        }
};
<|endoftext|>