<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

//! @file

#ifndef DO_CORE_IMAGE_HPP
#define DO_CORE_IMAGE_HPP

#include "Color.hpp"
#include "MultiArray.hpp"

namespace DO {

  // ======================================================================== //
  /*!
    \ingroup Core
    \defgroup Image Image
    @{
   */

  //! \brief The specialized element traits class when the entry is a color.
  template <typename T, typename Layout>
  struct ElementTraits<Pixel<T, Layout> >
  {
    typedef Array<T, Layout::size, 1> value_type; //!< STL-like typedef.
    typedef size_t size_type; //!< STL-like typedef.
    typedef value_type * pointer; //!< STL-like typedef.
    typedef const value_type * const_pointer; //!< STL-like typedef.
    typedef value_type& reference; //!< STL-like typedef.
    typedef const value_type& const_reference; //!< STL-like typedef.
    typedef value_type * iterator; //!< STL-like typedef.
    typedef const value_type * const_iterator; //!< STL-like typedef.
    static const bool is_scalar = false; //!< STL-like typedef.
  };

  //! The forward declaration of the image class.
  template <typename Color, int N = 2> class Image;

  //! \brief Helper function for color conversion.
  template <typename T, typename U, int N>
  void convert(Image<T, N>& dst, const Image<U, N>& src);

  //! \brief The image class.
  template <typename Color, int N>
  class Image : public MultiArray<Color, N, ColMajor>
  {
    typedef MultiArray<Color, N, ColMajor> base_type;

  public: /* interface */
    //! N-dimensional integral vector type.
    typedef typename base_type::vector_type vector_type, Vector;

    //! Default constructor.
    inline Image()
      : base_type() {}

    //! Constructor with specified sizes.
    inline explicit Image(const vector_type& sizes)
      : base_type(sizes) {}

    //! Constructor which wraps raw data.
    inline Image(Color *data, const vector_type& sizes,
                 bool getOwnership = false)
      : base_type(data, sizes, getOwnership) {}

    //! Constructor with specified sizes.
    inline Image(int width, int height)
      : base_type(width, height) {}

    //! Constructor with specified sizes.
    inline Image(int width, int height, int depth)
      : base_type(width, height, depth) {}

    //! Copy constructor.
    inline Image(const base_type& x)
      : base_type(x) {}

    //! Assignment operators.
    inline const Image& operator=(const Image& I)
    { base_type::operator=(I); return *this;}

    //! Constant width accessor.
    inline int width() const { return this->base_type::rows(); }

    //! Constant height accessor.
    inline int height() const {  return this->base_type::cols(); }

    //! Constant depth accessor (only for volumetric image.)
    inline int depth() const {  return this->base_type::depth(); }

    //! Color conversion method.
    template <typename Color2>
    Image<Color2, N> convert() const
    {
      Image<Color2, N> dst(base_type::sizes());
      DO::convert(dst, *this);
      return dst;
    }

    //! Convenient helper for chaining filters.
    template <template<typename, int> class Filter>
    inline typename Filter<Color, N>::ReturnType
    compute() const
    { return Filter<Color, N>(*this)(); }

    template <template<typename, int> class Filter>
    inline typename Filter<Color, N>::ReturnType
    compute(const typename Filter<Color, N>::ParamType& param) const
    { return Filter<Color, N>(*this)(param); }
  };

  // ====================================================================== //
  // Construct image views from row major multi-array.
  //! \todo Check this functionality...
#define DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY(Colorspace)          \
  /*! \brief Reinterpret column-major matrix as an image. */            \
  template <typename T>                                                 \
  inline Image<Color<T, Colorspace>, Colorspace::size>                  \
  as##Colorspace##Image(const MultiArray<Matrix<T,3,1>,                 \
                                         Colorspace::size,              \
                                         ColMajor>& M)                  \
  {                                                                     \
    return Image<Color<T, Colorspace> >(                                \
      reinterpret_cast<Color<T, Colorspace> *>(M.data()),               \
      M.sizes() );                                                      \
  }

  DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY(Rgb)
  DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY(Rgba)
  DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY(Cmyk)
  DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY(Yuv)
#undef DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY

  // ====================================================================== //
  // Generic image conversion function.
  //! \brief Generic image converter class.
  template <typename T, typename U, int N>
  struct ConvertImage {
    //! Implementation of the image conversion.
    static void apply(Image<T, N>& dst, const Image<U, N>& src)
    {
      if (dst.sizes() != src.sizes())
        dst.resize(src.sizes());

      const U *src_first = src.data();
      const U *src_last = src_first + src.size();

      T *dst_first  = dst.data();

      for ( ; src_first != src_last; ++src_first, ++dst_first)
        convertColor(*dst_first, *src_first);
    }
  };

  //! \brief Specialized image converter class when the source and color types
  //! are the same.
  template <typename T, int N>
  struct ConvertImage<T,T,N> {
    //! Implementation of the image conversion.
    static void apply(Image<T, N>& dst, const Image<T, N>& src)
    {
      dst = src;
    }
  };

  template <typename T, typename U, int N>
  inline void convert(Image<T, N>& dst, const Image<U, N>& src)
  {
    ConvertImage<T,U,N>::apply(dst, src);
  }

  // ====================================================================== //
  // Find min and max values in images according to point-wise comparison.
  //! \brief Find min and max pixel values of the image.
  template <typename T, int N, typename Layout>
  void findMinMax(Pixel<T, Layout>& min, Pixel<T, Layout>& max,
                  const Image<Pixel<T, Layout>, N>& src)
  {
    const Pixel<T,Layout> *src_first = src.data();
    const Pixel<T,Layout> *src_last = src_first + src.size();

    min = *src_first;
    max = *src_first;

    for ( ; src_first != src_last; ++src_first)
    {
      min = min.cwiseMin(*src_first);
      max = max.cwiseMax(*src_first);
    }
  }

  //! Macro that defines min-max value functions for a specific grayscale
  //! color types.
#define DEFINE_FINDMINMAX_GRAY(T)                               \
  /*! \brief Find min and max grayscale values of the image. */ \
  template <int N>                                              \
  inline void findMinMax(T& min, T& max, const Image<T, N>& src)\
  {                                                             \
    const T *src_first = src.data();                            \
    const T *src_last = src_first + src.size();                 \
                                                                \
    min = *std::min_element(src_first, src_last);               \
    max = *std::max_element(src_first, src_last);               \
  }

  DEFINE_FINDMINMAX_GRAY(unsigned char)
  DEFINE_FINDMINMAX_GRAY(char)
  DEFINE_FINDMINMAX_GRAY(unsigned short)
  DEFINE_FINDMINMAX_GRAY(short)
  DEFINE_FINDMINMAX_GRAY(unsigned int)
  DEFINE_FINDMINMAX_GRAY(int)
  DEFINE_FINDMINMAX_GRAY(float)
  DEFINE_FINDMINMAX_GRAY(double)
#undef DEFINE_FINDMINMAX_GRAY

  // ====================================================================== //
  // Image rescaling functions
  //! \brief color rescaling function.
  template <typename T, typename Layout, int N>
  inline Image<Pixel<T,Layout>, N> colorRescale(
    const Image<Pixel<T,Layout>, N>& src,
    const Pixel<T, Layout>& a = black<T>(),
    const Pixel<T, Layout>& b = white<T>())
  {
    Image<Pixel<T,Layout>, N> dst(src.sizes());

    const Pixel<T,Layout> *src_first = src.data();
    const Pixel<T,Layout> *src_last = src_first + src.size();
    Pixel<T,Layout> *dst_first  = dst.data();

    Pixel<T,Layout> min(*src_first);
    Pixel<T,Layout> max(*src_first);
    for ( ; src_first != src_last; ++src_first)
    {
      min = min.cwiseMin(*src_first);
      max = max.cwiseMax(*src_first);
    }

    if (min == max)
    {
      std::cerr << "Warning: min == max!" << std::endl;
      return dst;
    }

    for (src_first = src.data(); src_first != src_last;
       ++src_first, ++dst_first)
      *dst_first = a + (*src_first-min).cwiseProduct(b-a).
                                        cwiseQuotient(max-min);

    return dst;
  }

  //! Macro that defines a color rescaling function for a specific grayscale
  //! color type.
#define DEFINE_RESCALE_GRAY(T)                                  \
  /*! \brief Rescales color values properly for viewing. */     \
  template <int N>                                              \
  inline Image<T, N> colorRescale(const Image<T, N>& src,       \
                                  T a = ColorTraits<T>::min(),  \
                                  T b = ColorTraits<T>::max())  \
  {                                                             \
    Image<T, N> dst(src.sizes());                               \
                                                                \
    const T *src_first = src.data();                            \
    const T *src_last = src_first + src.size();                 \
    T *dst_first  = dst.data();                                 \
                                                                \
    T min = *std::min_element(src_first, src_last);             \
    T max = *std::max_element(src_first, src_last);             \
                                                                \
    if (min == max)                                             \
    {                                                           \
      std::cerr << "Warning: min == max!" << std::endl;         \
      return dst;                                               \
    }                                                           \
                                                                \
    for ( ; src_first != src_last; ++src_first, ++dst_first)    \
      *dst_first = a + (b-a)*(*src_first-min)/(max-min);        \
                                                                \
    return dst;                                                 \
  }

  DEFINE_RESCALE_GRAY(unsigned char)
  DEFINE_RESCALE_GRAY(char)
  DEFINE_RESCALE_GRAY(unsigned short)
  DEFINE_RESCALE_GRAY(short)
  DEFINE_RESCALE_GRAY(unsigned int)
  DEFINE_RESCALE_GRAY(int)
  DEFINE_RESCALE_GRAY(float)
  DEFINE_RESCALE_GRAY(double)
#undef DEFINE_RESCALE_GRAY

  //! \brief color rescaling functor helper.
  template <typename T, int N>
  struct ColorRescale
  {
    typedef Image<T, N> ReturnType;
    ColorRescale(const Image<T, N>& src) : src_(src) {}
    ReturnType operator()() const { return colorRescale(src_); }
    const Image<T, N>& src_;
  };

  //! @}

} /* namespace DO */

#endif /* DO_CORE_IMAGE_HPP */<commit_msg>Remove unused and untested function.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

//! @file

#ifndef DO_CORE_IMAGE_HPP
#define DO_CORE_IMAGE_HPP

#include "Color.hpp"
#include "MultiArray.hpp"

namespace DO {

  // ======================================================================== //
  /*!
    \ingroup Core
    \defgroup Image Image
    @{
   */

  //! \brief The specialized element traits class when the entry is a color.
  template <typename T, typename Layout>
  struct ElementTraits<Pixel<T, Layout> >
  {
    typedef Array<T, Layout::size, 1> value_type; //!< STL-like typedef.
    typedef size_t size_type; //!< STL-like typedef.
    typedef value_type * pointer; //!< STL-like typedef.
    typedef const value_type * const_pointer; //!< STL-like typedef.
    typedef value_type& reference; //!< STL-like typedef.
    typedef const value_type& const_reference; //!< STL-like typedef.
    typedef value_type * iterator; //!< STL-like typedef.
    typedef const value_type * const_iterator; //!< STL-like typedef.
    static const bool is_scalar = false; //!< STL-like typedef.
  };

  //! The forward declaration of the image class.
  template <typename Color, int N = 2> class Image;

  //! \brief Helper function for color conversion.
  template <typename T, typename U, int N>
  void convert(Image<T, N>& dst, const Image<U, N>& src);

  //! \brief The image class.
  template <typename Color, int N>
  class Image : public MultiArray<Color, N, ColMajor>
  {
    typedef MultiArray<Color, N, ColMajor> base_type;

  public: /* interface */
    //! N-dimensional integral vector type.
    typedef typename base_type::vector_type vector_type, Vector;

    //! Default constructor.
    inline Image()
      : base_type() {}

    //! Constructor with specified sizes.
    inline explicit Image(const vector_type& sizes)
      : base_type(sizes) {}

    //! Constructor which wraps raw data.
    inline Image(Color *data, const vector_type& sizes,
                 bool getOwnership = false)
      : base_type(data, sizes, getOwnership) {}

    //! Constructor with specified sizes.
    inline Image(int width, int height)
      : base_type(width, height) {}

    //! Constructor with specified sizes.
    inline Image(int width, int height, int depth)
      : base_type(width, height, depth) {}

    //! Copy constructor.
    inline Image(const base_type& x)
      : base_type(x) {}

    //! Assignment operators.
    inline const Image& operator=(const Image& I)
    { base_type::operator=(I); return *this;}

    //! Constant width accessor.
    inline int width() const { return this->base_type::rows(); }

    //! Constant height accessor.
    inline int height() const {  return this->base_type::cols(); }

    //! Constant depth accessor (only for volumetric image.)
    inline int depth() const {  return this->base_type::depth(); }

    //! Color conversion method.
    template <typename Color2>
    Image<Color2, N> convert() const
    {
      Image<Color2, N> dst(base_type::sizes());
      DO::convert(dst, *this);
      return dst;
    }

    //! Convenient helper for chaining filters.
    template <template<typename, int> class Filter>
    inline typename Filter<Color, N>::ReturnType
    compute() const
    { return Filter<Color, N>(*this)(); }

    template <template<typename, int> class Filter>
    inline typename Filter<Color, N>::ReturnType
    compute(const typename Filter<Color, N>::ParamType& param) const
    { return Filter<Color, N>(*this)(param); }
  };

  // ====================================================================== //
  // Generic image conversion function.
  //! \brief Generic image converter class.
  template <typename T, typename U, int N>
  struct ConvertImage {
    //! Implementation of the image conversion.
    static void apply(Image<T, N>& dst, const Image<U, N>& src)
    {
      if (dst.sizes() != src.sizes())
        dst.resize(src.sizes());

      const U *src_first = src.data();
      const U *src_last = src_first + src.size();

      T *dst_first  = dst.data();

      for ( ; src_first != src_last; ++src_first, ++dst_first)
        convertColor(*dst_first, *src_first);
    }
  };

  //! \brief Specialized image converter class when the source and color types
  //! are the same.
  template <typename T, int N>
  struct ConvertImage<T,T,N> {
    //! Implementation of the image conversion.
    static void apply(Image<T, N>& dst, const Image<T, N>& src)
    {
      dst = src;
    }
  };

  template <typename T, typename U, int N>
  inline void convert(Image<T, N>& dst, const Image<U, N>& src)
  {
    ConvertImage<T,U,N>::apply(dst, src);
  }

  // ====================================================================== //
  // Find min and max values in images according to point-wise comparison.
  //! \brief Find min and max pixel values of the image.
  template <typename T, int N, typename Layout>
  void findMinMax(Pixel<T, Layout>& min, Pixel<T, Layout>& max,
                  const Image<Pixel<T, Layout>, N>& src)
  {
    const Pixel<T,Layout> *src_first = src.data();
    const Pixel<T,Layout> *src_last = src_first + src.size();

    min = *src_first;
    max = *src_first;

    for ( ; src_first != src_last; ++src_first)
    {
      min = min.cwiseMin(*src_first);
      max = max.cwiseMax(*src_first);
    }
  }

  //! Macro that defines min-max value functions for a specific grayscale
  //! color types.
#define DEFINE_FINDMINMAX_GRAY(T)                               \
  /*! \brief Find min and max grayscale values of the image. */ \
  template <int N>                                              \
  inline void findMinMax(T& min, T& max, const Image<T, N>& src)\
  {                                                             \
    const T *src_first = src.data();                            \
    const T *src_last = src_first + src.size();                 \
                                                                \
    min = *std::min_element(src_first, src_last);               \
    max = *std::max_element(src_first, src_last);               \
  }

  DEFINE_FINDMINMAX_GRAY(unsigned char)
  DEFINE_FINDMINMAX_GRAY(char)
  DEFINE_FINDMINMAX_GRAY(unsigned short)
  DEFINE_FINDMINMAX_GRAY(short)
  DEFINE_FINDMINMAX_GRAY(unsigned int)
  DEFINE_FINDMINMAX_GRAY(int)
  DEFINE_FINDMINMAX_GRAY(float)
  DEFINE_FINDMINMAX_GRAY(double)
#undef DEFINE_FINDMINMAX_GRAY

  // ====================================================================== //
  // Image rescaling functions
  //! \brief color rescaling function.
  template <typename T, typename Layout, int N>
  inline Image<Pixel<T,Layout>, N> colorRescale(
    const Image<Pixel<T,Layout>, N>& src,
    const Pixel<T, Layout>& a = black<T>(),
    const Pixel<T, Layout>& b = white<T>())
  {
    Image<Pixel<T,Layout>, N> dst(src.sizes());

    const Pixel<T,Layout> *src_first = src.data();
    const Pixel<T,Layout> *src_last = src_first + src.size();
    Pixel<T,Layout> *dst_first  = dst.data();

    Pixel<T,Layout> min(*src_first);
    Pixel<T,Layout> max(*src_first);
    for ( ; src_first != src_last; ++src_first)
    {
      min = min.cwiseMin(*src_first);
      max = max.cwiseMax(*src_first);
    }

    if (min == max)
    {
      std::cerr << "Warning: min == max!" << std::endl;
      return dst;
    }

    for (src_first = src.data(); src_first != src_last;
       ++src_first, ++dst_first)
      *dst_first = a + (*src_first-min).cwiseProduct(b-a).
                                        cwiseQuotient(max-min);

    return dst;
  }

  //! Macro that defines a color rescaling function for a specific grayscale
  //! color type.
#define DEFINE_RESCALE_GRAY(T)                                  \
  /*! \brief Rescales color values properly for viewing. */     \
  template <int N>                                              \
  inline Image<T, N> colorRescale(const Image<T, N>& src,       \
                                  T a = ColorTraits<T>::min(),  \
                                  T b = ColorTraits<T>::max())  \
  {                                                             \
    Image<T, N> dst(src.sizes());                               \
                                                                \
    const T *src_first = src.data();                            \
    const T *src_last = src_first + src.size();                 \
    T *dst_first  = dst.data();                                 \
                                                                \
    T min = *std::min_element(src_first, src_last);             \
    T max = *std::max_element(src_first, src_last);             \
                                                                \
    if (min == max)                                             \
    {                                                           \
      std::cerr << "Warning: min == max!" << std::endl;         \
      return dst;                                               \
    }                                                           \
                                                                \
    for ( ; src_first != src_last; ++src_first, ++dst_first)    \
      *dst_first = a + (b-a)*(*src_first-min)/(max-min);        \
                                                                \
    return dst;                                                 \
  }

  DEFINE_RESCALE_GRAY(unsigned char)
  DEFINE_RESCALE_GRAY(char)
  DEFINE_RESCALE_GRAY(unsigned short)
  DEFINE_RESCALE_GRAY(short)
  DEFINE_RESCALE_GRAY(unsigned int)
  DEFINE_RESCALE_GRAY(int)
  DEFINE_RESCALE_GRAY(float)
  DEFINE_RESCALE_GRAY(double)
#undef DEFINE_RESCALE_GRAY

  //! \brief color rescaling functor helper.
  template <typename T, int N>
  struct ColorRescale
  {
    typedef Image<T, N> ReturnType;
    ColorRescale(const Image<T, N>& src) : src_(src) {}
    ReturnType operator()() const { return colorRescale(src_); }
    const Image<T, N>& src_;
  };

  //! @}

} /* namespace DO */

#endif /* DO_CORE_IMAGE_HPP */<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;

int main()
{
    int n = 0;
    cin >> n;
    vector<long long> v(n, 0);
    for (int i = 0; i < n; ++i)
    {
        cin >> v[i];
    }

    // Alice opration
    bool Alicefound = false;
    long long diff = 0;
    while (true)
    {
AliceOperation:for (int i = 0; i < v.size(); ++i)
        {
            for (int j = i + 1; j < v.size(); ++j)
            {
                diff = abs(v[i] - v[j]);
                if (count(v.begin(), v.end(), diff) == 0)
                {
                    v.push_back(diff);
                    Alicefound = true;
                    goto BobOperation;
                }
            }
        }

        if (!Alicefound)
        {
            cout << "Bob" << endl;
            break;
        }

        // Bob operation
BobOperation: for (int i = 0; i < v.size(); ++i)
        {
            for (int j = i + 1; j < v.size(); ++j)
            {
                diff = abs(v[i] - v[j]);
                if (count(v.begin(), v.end(), diff) == 0)
                {
                    v.push_back(diff);
                    Alicefound = false;
                    goto AliceOperation;
                }
            }
        }

        if (Alicefound)
        {
            cout << "Alice" << endl;
            break;
        }
    }
    return 0;
}
<commit_msg>use GCD of array to solve it elegant, refer to other's algorithm, good<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

// Greatest Common Divisor between a and b
long long gcd(long long a, long long b)
{
	while (b != 0)
	{
		long long r = a % b;
		a = b;
		b = r;
	}
	return a;
}

// return the greatest common divisor among all values in v
// Time complexity:
long long arrayGcd(vector<long long> v)
{
	long long result = v[0];
	for (int i = 1; i < v.size(); ++i)
	{
		result = gcd(result, v[i]);
	}

    return result;
}

int main()
{
	// read input
	int n = 0;
	cin >> n;
	vector<long long> v(n, 0);
	for (int i = 0; i < n; ++i)
	{
		cin >> v[i];
	}

	long long max_elem = *max_element(v.begin(), v.end());
	long long d = arrayGcd(v);

	long long remain_round = max_elem / d - v.size();
	if (remain_round % 2 == 1)
	{
		cout << "Alice" << endl;
	}
	else
	{
		cout << "Bob" << endl;
	}
	return 0;
}

// Summary:
// 1. calculate GCD use Euler Algorithm
// 2. calculate other GCD always depends on Euler's GCD Algorithm
// 3. figure out why we can achieve all the differece |x-y| in such
//    way, what's behind ? Number Theory ?
<|endoftext|>


<commit_before>#pragma once
#include <fc/reflect/variant.hpp>
#include <functional>
#include <string>
#include <fc/optional.hpp>
#include <fc/variant.hpp>

//#include <fc/network/ip.hpp>
//#include <fc/variant.hpp>

namespace bts { namespace api {

  enum method_prerequisites
  {
    no_prerequisites     = 0,
    json_authenticated   = 1,
    wallet_open          = 2,
    wallet_unlocked      = 4,
    connected_to_network = 8,
  };

  enum parameter_classification
  {
    required_positional,
    required_positional_hidden, /* Hide in help e.g. interactive password entry */
    optional_positional,
    optional_named
  };

  struct parameter_data
  {
    std::string name;
    std::string type;
    parameter_classification classification;
    fc::ovariant default_value;
    parameter_data(const parameter_data& rhs) :
      name(rhs.name),
      type(rhs.type),
      classification(rhs.classification),
      default_value(rhs.default_value)
    {}
    parameter_data(const parameter_data&& rhs) :
      name(std::move(rhs.name)),
      type(std::move(rhs.type)),
      classification(std::move(rhs.classification)),
      default_value(std::move(rhs.default_value))
    {}
    parameter_data(std::string name,
                    std::string type,
                    parameter_classification classification,
                    fc::ovariant default_value) :
      name(name),
      type(type),
      classification(classification),
      default_value(default_value)
    {}
  };

  typedef std::function<fc::variant(const fc::variants& params)> json_api_method_type;

  struct method_data
  {
    std::string                 name;
    json_api_method_type        method;
    std::string                 description;
    std::string                 return_type;
    std::vector<parameter_data> parameters;
    uint32_t                    prerequisites;
    std::string                 detailed_description;
    std::vector<std::string>    aliases;
  };

} } // end namespace bts::api

FC_REFLECT_ENUM(bts::api::method_prerequisites, (no_prerequisites)(json_authenticated)(wallet_open)(wallet_unlocked)(connected_to_network))
<commit_msg>Add operator= that gcc wants to use<commit_after>#pragma once
#include <fc/reflect/variant.hpp>
#include <functional>
#include <string>
#include <fc/optional.hpp>
#include <fc/variant.hpp>

//#include <fc/network/ip.hpp>
//#include <fc/variant.hpp>

namespace bts { namespace api {

  enum method_prerequisites
  {
    no_prerequisites     = 0,
    json_authenticated   = 1,
    wallet_open          = 2,
    wallet_unlocked      = 4,
    connected_to_network = 8,
  };

  enum parameter_classification
  {
    required_positional,
    required_positional_hidden, /* Hide in help e.g. interactive password entry */
    optional_positional,
    optional_named
  };

  struct parameter_data
  {
    std::string name;
    std::string type;
    parameter_classification classification;
    fc::ovariant default_value;
    parameter_data(const parameter_data& rhs) :
      name(rhs.name),
      type(rhs.type),
      classification(rhs.classification),
      default_value(rhs.default_value)
    {}
    parameter_data(const parameter_data&& rhs) :
      name(std::move(rhs.name)),
      type(std::move(rhs.type)),
      classification(std::move(rhs.classification)),
      default_value(std::move(rhs.default_value))
    {}
    parameter_data(std::string name,
                    std::string type,
                    parameter_classification classification,
                    fc::ovariant default_value) :
      name(name),
      type(type),
      classification(classification),
      default_value(default_value)
    {}
    parameter_data& operator=(const parameter_data& rhs)
    {
      name = rhs.name;
      type = rhs.type;
      classification = rhs.classification;
      default_value = rhs.default_value;
      return *this;
    }
  };

  typedef std::function<fc::variant(const fc::variants& params)> json_api_method_type;

  struct method_data
  {
    std::string                 name;
    json_api_method_type        method;
    std::string                 description;
    std::string                 return_type;
    std::vector<parameter_data> parameters;
    uint32_t                    prerequisites;
    std::string                 detailed_description;
    std::vector<std::string>    aliases;
  };

} } // end namespace bts::api

FC_REFLECT_ENUM(bts::api::method_prerequisites, (no_prerequisites)(json_authenticated)(wallet_open)(wallet_unlocked)(connected_to_network))
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, Intel Corporation
 *
 * 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 Intel Corporation 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 LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef CIRCULARBUFFER_HPP_INCLUDE
#define CIRCULARBUFFER_HPP_INCLUDE

#include <stdlib.h>
#include <vector>

namespace geopm
{
    /// @brief Templated container for a circular buffer implementation.
    ///
    /// The CircularBuffer container implements a fixed size buffer. Once
    /// at capacity, any new insertions cause the oldest entry to be dropped.
    template <class type>
    class CircularBuffer
    {
        public:
            /// @brief Constructor ofr the CircularBuffer template.
            ///
            /// Creates an empty circular buffer with a set capacity.
            ///
            /// @param [in] size Requested capacity for the buffer.
            CircularBuffer(const unsigned int size);
            /// @brief CircularBuffer destructor, virtual
            virtual ~CircularBuffer();
            /// @brief Resize the circular buffer.
            ///
            /// Resets the capacity of the circular buffer without
            /// modifying it's current contents.
            ///
            /// @param [in] size Requested capacity for the buffer.
            void set_capacity(const unsigned int size);
            /// @brief Clears all entries fron the buffer.
            void clear(void);
            /// @brief Size of the buffer contents.
            ///
            /// Returns the number of items in the buffer. This
            /// value will be less than or equal to the current
            /// capacity of the buffer.
            //
            /// @retrun Size of the buffer contents.
            int size(void) const;
            /// @brief Capacity of the buffer.
            ///
            /// Returns the current size of the circular buffer at
            /// the time of the call.
            ///
            /// @return Capacity of the buffer.
            int capacity(void) const;
            /// @brief Insert a value into the buffer.
            ///
            /// If the buffer is not full, the nae value is simply
            /// added to the buffer. It the buffer is at capacity,
            /// The head of the buffer is dropped and moved to the
            /// next oldest entry and the new value is then inserted
            /// at the end of the buffer.
            ///
            /// @param [in] value The value to be inserted.
            void insert(const type value);
            /// @brief Returns a value from the buffer.
            ///
            /// Accesses the contents of the circular buffer
            /// at a particular index. Valid indicies range
            /// from 0 to [size-1]. Where size is the number
            /// of valid entries in the buffer. An attemp to
            /// retrieve a value for an out of bound index a
            /// geopm::Exception will be thrown with an
            /// error_value() of GEOPM_ERROR_INVALID.
            ///
            /// @param [in] index Buffer index to retrieve.
            ///
            /// @return Value from the specified buffer index.
            type value(const unsigned int index) const;
        protected:
            /// @brief Vector holding the buffer data.
            std::vector<type> m_buffer;
            /// @brief Index of the current head of the buffer.
            unsigned long m_head;
            /// @brief The number of valid enrties in the buffer.
            unsigned long m_count;
            /// @brief Current capacity of the buffer.
            size_t m_max_size;
    };

    template <class type>
    CircularBuffer<type>::CircularBuffer(const unsigned int size)
    {
        m_max_size = size;
        m_head = 0;
        m_count = 0;
    }

    template <class type>
    CircularBuffer<type>::~CircularBuffer()
    {

    }

    template <class type>
    int CircularBuffer<type>::size() const
    {
        return m_count;
    }

    template <class type>
    int CircularBuffer<type>::capacity() const
    {
        return m_max_size;
    }

    template <class type>
    void CircularBuffer<type>::clear()
    {
        m_buffer.clear();
        m_head = 0;
        m_count = 0;
    }

    template <class type>
    void CircularBuffer<type>::set_capacity(const unsigned int size)
    {
        if (size < m_count) {
            int size_diff = m_count - size;
            std::vector<type> temp;
            //Copy newest data into temporary vector
            for (unsigned int i = m_head + size_diff; i < ((m_head + m_count) % m_max_size); i = ((i + 1) % m_max_size)) {
                temp.push_back(m_buffer[i]);
            }
            //now resize and swap out with tmp vector data
            m_buffer.resize(size);
            m_buffer.swap(temp);
            m_count = size;
        }
        else {
            m_buffer.resize(size);
        }
        m_head = 0;
        m_max_size = size;
    }

    template <class type>
    void CircularBuffer<type>::insert(const type value)
    {
        if (m_count < m_max_size) {
            m_buffer.push_back(value);
            m_count++;
        }
        else {
            m_buffer[m_head] = value;
            m_head = ((m_head + 1) % m_max_size);
        }
    }

    template <class type>
    type CircularBuffer<type>::value(const unsigned int index) const
    {
        return m_buffer[(m_head+index) % m_max_size];
    }
}

#endif
<commit_msg>Added throws on error conditions on inserting and retrieving values from a CircularBuffer.<commit_after>/*
 * Copyright (c) 2015, Intel Corporation
 *
 * 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 Intel Corporation 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 LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef CIRCULARBUFFER_HPP_INCLUDE
#define CIRCULARBUFFER_HPP_INCLUDE

#include <stdlib.h>
#include <vector>

#include "Exception.hpp"

namespace geopm
{
    /// @brief Templated container for a circular buffer implementation.
    ///
    /// The CircularBuffer container implements a fixed size buffer. Once
    /// at capacity, any new insertions cause the oldest entry to be dropped.
    template <class type>
    class CircularBuffer
    {
        public:
            /// @brief Constructor ofr the CircularBuffer template.
            ///
            /// Creates an empty circular buffer with a set capacity.
            ///
            /// @param [in] size Requested capacity for the buffer.
            CircularBuffer(const unsigned int size);
            /// @brief CircularBuffer destructor, virtual
            virtual ~CircularBuffer();
            /// @brief Resize the circular buffer.
            ///
            /// Resets the capacity of the circular buffer without
            /// modifying it's current contents.
            ///
            /// @param [in] size Requested capacity for the buffer.
            void set_capacity(const unsigned int size);
            /// @brief Clears all entries fron the buffer.
            void clear(void);
            /// @brief Size of the buffer contents.
            ///
            /// Returns the number of items in the buffer. This
            /// value will be less than or equal to the current
            /// capacity of the buffer.
            //
            /// @retrun Size of the buffer contents.
            int size(void) const;
            /// @brief Capacity of the buffer.
            ///
            /// Returns the current size of the circular buffer at
            /// the time of the call.
            ///
            /// @return Capacity of the buffer.
            int capacity(void) const;
            /// @brief Insert a value into the buffer.
            ///
            /// If the buffer is not full, the nae value is simply
            /// added to the buffer. It the buffer is at capacity,
            /// The head of the buffer is dropped and moved to the
            /// next oldest entry and the new value is then inserted
            /// at the end of the buffer.
            ///
            /// @param [in] value The value to be inserted.
            void insert(const type value);
            /// @brief Returns a value from the buffer.
            ///
            /// Accesses the contents of the circular buffer
            /// at a particular index. Valid indicies range
            /// from 0 to [size-1]. Where size is the number
            /// of valid entries in the buffer. An attemp to
            /// retrieve a value for an out of bound index a
            /// geopm::Exception will be thrown with an
            /// error_value() of GEOPM_ERROR_INVALID.
            ///
            /// @param [in] index Buffer index to retrieve.
            ///
            /// @return Value from the specified buffer index.
            type value(const unsigned int index) const;
        protected:
            /// @brief Vector holding the buffer data.
            std::vector<type> m_buffer;
            /// @brief Index of the current head of the buffer.
            unsigned long m_head;
            /// @brief The number of valid enrties in the buffer.
            unsigned long m_count;
            /// @brief Current capacity of the buffer.
            size_t m_max_size;
    };

    template <class type>
    CircularBuffer<type>::CircularBuffer(const unsigned int size)
    {
        m_max_size = size;
        m_head = 0;
        m_count = 0;
    }

    template <class type>
    CircularBuffer<type>::~CircularBuffer()
    {

    }

    template <class type>
    int CircularBuffer<type>::size() const
    {
        return m_count;
    }

    template <class type>
    int CircularBuffer<type>::capacity() const
    {
        return m_max_size;
    }

    template <class type>
    void CircularBuffer<type>::clear()
    {
        m_buffer.clear();
        m_head = 0;
        m_count = 0;
    }

    template <class type>
    void CircularBuffer<type>::set_capacity(const unsigned int size)
    {
        if (size < m_count) {
            int size_diff = m_count - size;
            std::vector<type> temp;
            //Copy newest data into temporary vector
            for (unsigned int i = m_head + size_diff; i < ((m_head + m_count) % m_max_size); i = ((i + 1) % m_max_size)) {
                temp.push_back(m_buffer[i]);
            }
            //now resize and swap out with tmp vector data
            m_buffer.resize(size);
            m_buffer.swap(temp);
            m_count = size;
        }
        else {
            m_buffer.resize(size);
        }
        m_head = 0;
        m_max_size = size;
    }

    template <class type>
    void CircularBuffer<type>::insert(const type value)
    {
        if (m_max_size < 1) {
            throw Exception("CircularBuffer::insert(): Cannot insert into a bufffer of 0 size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        if (m_count < m_max_size) {
            m_buffer.push_back(value);
            m_count++;
        }
        else {
            m_buffer[m_head] = value;
            m_head = ((m_head + 1) % m_max_size);
        }
    }

    template <class type>
    type CircularBuffer<type>::value(const unsigned int index) const
    {
        if (index >= m_count) {
            throw Exception("CircularBuffer::value(): index is out of bounds", GEOPM_ERROR_INVALID, __FILE__, __LINE__);
        }
        return m_buffer[(m_head+index) % m_max_size];
    }
}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders 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.
 *
 * Authors: Nathan Binkert
 *          Dave Greene
 */

#ifndef __MISC_HH__
#define __MISC_HH__

#include <assert.h>
#include "base/cprintf.hh"

//
// This implements a cprintf based panic() function.  panic() should
// be called when something happens that should never ever happen
// regardless of what the user does (i.e., an acutal m5 bug).  panic()
// calls abort which can dump core or enter the debugger.
//
//
void __panic(const std::string&, cp::ArgList &, const char*, const char*, int)
    __attribute__((noreturn));
#define __panic__(format, args...) \
    __panic(format, (*(new cp::ArgList), args), \
        __FUNCTION__, __FILE__, __LINE__)
#define panic(args...) \
    __panic__(args, cp::ArgListNull())

//
// This implements a cprintf based fatal() function.  fatal() should
// be called when the simulation cannot continue due to some condition
// that is the user's fault (bad configuration, invalid arguments,
// etc.) and not a simulator bug.  fatal() calls exit(1), i.e., a
// "normal" exit with an error code, as opposed to abort() like
// panic() does.
//
void __fatal(const std::string&, cp::ArgList &, const char*, const char*, int)
    __attribute__((noreturn));
#define __fatal__(format, args...) \
    __fatal(format, (*(new cp::ArgList), args), \
        __FUNCTION__, __FILE__, __LINE__)
#define fatal(args...) \
    __fatal__(args, cp::ArgListNull())

//
// This implements a cprintf based warn
//
void __warn(const std::string&, cp::ArgList &, const char*, const char*, int);
#define __warn__(format, args...) \
    __warn(format, (*(new cp::ArgList), args), \
           __FUNCTION__, __FILE__, __LINE__)
#define warn(args...) \
    __warn__(args, cp::ArgListNull())

//
// assert() that prints out the current cycle
//
#define m5_assert(TEST) \
   if (!(TEST)) { \
     std::cerr << "Assertion failure, curTick = " << curTick << std::endl; \
   } \
   assert(TEST);

#endif // __MISC_HH__
<commit_msg>add warn_once which will print any given warning message only once.<commit_after>/*
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders 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.
 *
 * Authors: Nathan Binkert
 *          Dave Greene
 */

#ifndef __MISC_HH__
#define __MISC_HH__

#include <assert.h>
#include "base/cprintf.hh"

//
// This implements a cprintf based panic() function.  panic() should
// be called when something happens that should never ever happen
// regardless of what the user does (i.e., an acutal m5 bug).  panic()
// calls abort which can dump core or enter the debugger.
//
//
void __panic(const std::string&, cp::ArgList &, const char*, const char*, int)
    __attribute__((noreturn));
#define __panic__(format, args...) \
    __panic(format, (*(new cp::ArgList), args), \
        __FUNCTION__, __FILE__, __LINE__)
#define panic(args...) \
    __panic__(args, cp::ArgListNull())

//
// This implements a cprintf based fatal() function.  fatal() should
// be called when the simulation cannot continue due to some condition
// that is the user's fault (bad configuration, invalid arguments,
// etc.) and not a simulator bug.  fatal() calls exit(1), i.e., a
// "normal" exit with an error code, as opposed to abort() like
// panic() does.
//
void __fatal(const std::string&, cp::ArgList &, const char*, const char*, int)
    __attribute__((noreturn));
#define __fatal__(format, args...) \
    __fatal(format, (*(new cp::ArgList), args), \
        __FUNCTION__, __FILE__, __LINE__)
#define fatal(args...) \
    __fatal__(args, cp::ArgListNull())

//
// This implements a cprintf based warn
//
void __warn(const std::string&, cp::ArgList &, const char*, const char*, int);
#define __warn__(format, args...) \
    __warn(format, (*(new cp::ArgList), args), \
           __FUNCTION__, __FILE__, __LINE__)
#define warn(args...) \
    __warn__(args, cp::ArgListNull())

// Only print the warning message the first time it is seen.  This
// doesn't check the warning string itself, it just only lets one
// warning come from the statement. So, even if the arguments change
// and that would have resulted in a different warning message,
// subsequent messages would still be supressed.
#define warn_once(args...) do {                     \
        static bool once = false;                   \
        if (!once) {                                \
            __warn__(args, cp::ArgListNull());      \
            once = true;                            \
        }                                           \
    } while (0)

//
// assert() that prints out the current cycle
//
#define m5_assert(TEST) \
   if (!(TEST)) { \
     std::cerr << "Assertion failure, curTick = " << curTick << std::endl; \
   } \
   assert(TEST);

#endif // __MISC_HH__
<|endoftext|>


<commit_before>/*****************************************************************************
  bedtools.cpp

  bedtools command line interface.
  Thanks to Heng Li, as this interface is inspired and
  based upon his samtools interface.

  (c) 2009-2011 - Aaron Quinlan
  Quinlan Laboratory
  Department of Public Health Sciences
  Center for Public Health genomics
  University of Virginia
  aaronquinlan@gmail.com

  Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include "version.h"

using namespace std;

// define our program name
#define PROGRAM_NAME "bedtools"

// colors for the term's menu
#define RESET "\033[m"
#define GREEN "\033[1;32m"
#define BLUE "\033[1;34m"
#define RED "\033[1;31m"

// define our parameter checking macro
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)

int annotate_main(int argc, char* argv[]);//
int bamtobed_main(int argc, char* argv[]);//
int bamtofastq_main(int argc, char* argv[]);//
int bed12tobed6_main(int argc, char* argv[]); //
int bedtobam_main(int argc, char* argv[]);//
int bedtoigv_main(int argc, char* argv[]);//
int bedpetobam_main(int argc, char* argv[]);//
int closest_main(int argc, char* argv[]); //
int cluster_main(int argc, char* argv[]); //
int complement_main(int argc, char* argv[]);//
int coverage_main(int argc, char* argv[]); //
int expand_main(int argc, char* argv[]);//
int fastafrombed_main(int argc, char* argv[]);//
int flank_main(int argc, char* argv[]); //
int genomecoverage_main(int argc, char* argv[]);//
int getoverlap_main(int argc, char* argv[]);//
int groupby_main(int argc, char* argv[]);//
int intersect_main(int argc, char* argv[]); //
int links_main(int argc, char* argv[]);//
int maskfastafrombed_main(int argc, char* argv[]);//
int map_main(int argc, char* argv[]); //
int merge_main(int argc, char* argv[]); //
int multibamcov_main(int argc, char* argv[]);//
int multiintersect_main(int argc, char* argv[]);//
int nuc_main(int argc, char* argv[]);//
int pairtobed_main(int argc, char* argv[]);//
int pairtopair_main(int argc, char* argv[]);//
int random_main(int argc, char* argv[]); //
int shuffle_main(int argc, char* argv[]); //
int slop_main(int argc, char* argv[]); //
int sort_main(int argc, char* argv[]); //
int subtract_main(int argc, char* argv[]); //
int tagbam_main(int argc, char* argv[]);//
int unionbedgraphs_main(int argc, char* argv[]);//
int window_main(int argc, char* argv[]); //
int windowmaker_main(int argc, char* argv[]); //
int bedtools_help(void);
int bedtools_faq(void);

int main(int argc, char *argv[])
{
    // make sure the user at least entered a sub_command
    if (argc < 2) return bedtools_help();

    std::string sub_cmd = argv[1];

    // genome arithmetic tools
    if (sub_cmd == "intersect")        return intersect_main(argc-1, argv+1);
    else if (sub_cmd == "window")      return window_main(argc-1, argv+1);
    else if (sub_cmd == "closest")     return closest_main(argc-1, argv+1);
    else if (sub_cmd == "coverage")    return coverage_main(argc-1, argv+1);
    else if (sub_cmd == "map")         return map_main(argc-1, argv+1);
    else if (sub_cmd == "genomecov")   return genomecoverage_main(argc-1, argv+1);
    else if (sub_cmd == "merge")       return merge_main(argc-1, argv+1);
    else if (sub_cmd == "cluster")     return cluster_main(argc-1, argv+1);
    else if (sub_cmd == "complement")  return complement_main(argc-1, argv+1);
    else if (sub_cmd == "subtract")    return subtract_main(argc-1, argv+1);
    else if (sub_cmd == "slop")        return slop_main(argc-1, argv+1);
    else if (sub_cmd == "flank")       return flank_main(argc-1, argv+1);
    else if (sub_cmd == "sort")        return sort_main(argc-1, argv+1);
    else if (sub_cmd == "random")      return random_main(argc-1, argv+1);
    else if (sub_cmd == "shuffle")     return shuffle_main(argc-1, argv+1);
    else if (sub_cmd == "annotate")    return annotate_main(argc-1, argv+1);

    // Multi-way file comparisonstools
    else if (sub_cmd == "multiinter")  return multiintersect_main(argc-1, argv+1);
    else if (sub_cmd == "unionbedg")   return unionbedgraphs_main(argc-1, argv+1);

    // paired-end conversion tools
    else if (sub_cmd == "pairtobed")   return pairtobed_main(argc-1, argv+1);
    else if (sub_cmd == "pairtopair")  return pairtopair_main(argc-1, argv+1);

    // format conversion tools
    else if (sub_cmd == "bamtobed")    return bamtobed_main(argc-1, argv+1);
    else if (sub_cmd == "bedtobam")    return bedtobam_main(argc-1, argv+1);
    else if (sub_cmd == "bamtofastq")  return bamtofastq_main(argc-1, argv+1);
    else if (sub_cmd == "bedpetobam")  return bedpetobam_main(argc-1, argv+1);
    else if (sub_cmd == "bed12tobed6") return bed12tobed6_main(argc-1, argv+1);

    // BAM-specific tools
    else if (sub_cmd == "multicov")    return multibamcov_main(argc-1, argv+1);
    else if (sub_cmd == "tag")         return tagbam_main(argc-1, argv+1);

    // fasta tools
    else if (sub_cmd == "getfasta")    return fastafrombed_main(argc-1, argv+1);
    else if (sub_cmd == "maskfasta")   return maskfastafrombed_main(argc-1, argv+1);
    else if (sub_cmd == "nuc")         return nuc_main(argc-1, argv+1);

    // misc. tools
    else if (sub_cmd == "overlap")     return getoverlap_main(argc-1, argv+1);
    else if (sub_cmd == "igv")         return bedtoigv_main(argc-1, argv+1);
    else if (sub_cmd == "links")       return links_main(argc-1, argv+1);
    else if (sub_cmd == "makewindows") return windowmaker_main(argc-1, argv+1);
    else if (sub_cmd == "groupby")     return groupby_main(argc-1, argv+1);
    else if (sub_cmd == "expand")      return expand_main(argc-1, argv+1);

    // help
    else if (sub_cmd == "-h" || sub_cmd == "--help" ||
             sub_cmd == "-help")
        return bedtools_help();

    // frequently asked questions
    else if (sub_cmd == "--FAQ" || sub_cmd == "--faq" ||
             sub_cmd == "-FAQ"  || sub_cmd == "-faq")
        return bedtools_faq();

    // verison information
    else if (sub_cmd == "-version" || sub_cmd == "--version")
        cout << "bedtools " << VERSION << endl;

    // verison information
    else if (sub_cmd == "-contact" || sub_cmd == "--contact")
    {
        cout << endl;
        cout << "- For further help, or to report a bug, please " << endl;
        cout << "  email the bedtools mailing list: " << endl;
        cout << "     bedtools-discuss@googlegroups.com" << endl << endl;

        cout << "- Stable releases of bedtools can be found at: " << endl;
        cout << "     http://bedtools.googlecode.com" << endl << endl;

        cout << "- The development repository can be found at: " << endl;
        cout << "     https://github.com/arq5x/bedtools" << endl << endl;
    }
    // unknown
    else {
        // TODO: Implement a Levenstein-based "did you mean???"
        cerr << "error: unrecognized command: " << argv[1] << endl << endl;
        return 1;
    }
    return 0;
}

int bedtools_help(void)
{
    cout  << PROGRAM_NAME  << ": flexible tools for genome arithmetic and DNA sequence analysis.\n";
    cout << "usage:    bedtools <subcommand> [options]" << endl << endl;

    cout  << "The bedtools sub-commands include:" << endl;

    cout  << endl;
    cout  << "[ Genome arithmetic ]" << endl;
    cout  << "    intersect     "  << "Find overlapping intervals in various ways.\n";
    cout  << "    window        "  << "Find overlapping intervals within a window around an interval.\n";
    cout  << "    closest       "  << "Find the closest, potentially non-overlapping interval.\n";
    cout  << "    coverage      "  << "Compute the coverage over defined intervals.\n";
    cout  << "    map           "  << "Apply a function to a column for each overlapping interval.\n";
    cout  << "    genomecov     "  << "Compute the coverage over an entire genome.\n";
    cout  << "    merge         "  << "Combine overlapping/nearby intervals into a single interval.\n";
    cout  << "    cluster       "  << "Cluster (but don't merge) overlapping/nearby intervals.\n";
    cout  << "    complement    "  << "Extract intervals _not_ represented by an interval file.\n";
    cout  << "    subtract      "  << "Remove intervals based on overlaps b/w two files.\n";
    cout  << "    slop          "  << "Adjust the size of intervals.\n";
    cout  << "    flank         "  << "Create new intervals from the flanks of existing intervals.\n";
    cout  << "    sort          "  << "Order the intervals in a file.\n";
    cout  << "    random        "  << "Generate random intervals in a genome.\n";
    cout  << "    shuffle       "  << "Randomly redistrubute intervals in a genome.\n";
    cout  << "    annotate      "  << "Annotate coverage of features from multiple files.\n";

    cout  << endl;
    cout  << "[ Multi-way file comparisons ]" << endl;
    cout  << "    multiinter    "  << "Identifies common intervals among multiple interval files.\n";
    cout  << "    unionbedg     "  << "Combines coverage intervals from multiple BEDGRAPH files.\n";

    cout  << endl;
    cout  << "[ Paired-end manipulation ]" << endl;
    cout  << "    pairtobed     "  << "Find pairs that overlap intervals in various ways.\n";
    cout  << "    pairtopair    "  << "Find pairs that overlap other pairs in various ways.\n";

    cout  << endl;
    cout  << "[ Format conversion ]" << endl;
    cout  << "    bamtobed      "  << "Convert BAM alignments to BED (& other) formats.\n";
    cout  << "    bedtobam      "  << "Convert intervals to BAM records.\n";
    cout  << "    bedtofastq    "  << "Convert BAM records to FASTQ records.\n";
    cout  << "    bedpetobam    "  << "Convert BEDPE intervals to BAM records.\n";
    cout  << "    bed12tobed6   "  << "Breaks BED12 intervals into discrete BED6 intervals.\n";

    cout  << endl;
    cout  << "[ Fasta manipulation ]" << endl;
    cout  << "    getfasta      "  << "Use intervals to extract sequences from a FASTA file.\n";
    cout  << "    maskfasta     "  << "Use intervals to mask sequences from a FASTA file.\n";
    cout  << "    nuc           "  << "Profile the nucleotide content of intervals in a FASTA file.\n";

    cout  << endl;
    cout  << "[ BAM focused tools ]" << endl;
    cout  << "    multicov      "  << "Counts coverage from multiple BAMs at specific intervals.\n";
    cout  << "    tag           "  << "Tag BAM alignments based on overlaps with interval files.\n";

    cout  << endl;
    cout  << "[ Miscellaneous tools ]" << endl;
    cout  << "    overlap       "  << "Computes the amount of overlap from two intervals.\n";
    cout  << "    igv           "  << "Create an IGV snapshot batch script.\n";
    cout  << "    links         "  << "Create a HTML page of links to UCSC locations.\n";
    cout  << "    makewindows   "  << "Make interval \"windows\" across a genome.\n";
    cout  << "    groupby       "  << "Group by common cols. & summarize oth. cols. (~ SQL \"groupBy\")\n";
    cout  << "    expand        "  << "Replicate lines based on lists of values in columns.\n";

    cout  << endl;
    cout  << "[ General help ]" << endl;
    cout  << "    --help        "  << "Print this help menu.\n";
    //cout  << "    --faq         "  << "Frequently asked questions.\n";  TODO
    cout  << "    --version     "  << "What version of bedtools are you using?.\n";
    cout  << "    --contact     "  << "Feature requests, bugs, mailing lists, etc.\n";

    cout << "\n";
    return 0;
}

int bedtools_faq(void)
{
    cout << "\n";

    cout << "Q1. How do I see the help for a given command?" << endl;
    cout << "A1. All BEDTools commands have a \"-h\" option. Additionally, some tools " << endl;
    cout << "    will provide the help menu if you just type the command line " << endl;
    cout << "    followed by enter. " << endl;

    cout << "\n";
    return 0;
}
<commit_msg>menu typo<commit_after>/*****************************************************************************
  bedtools.cpp

  bedtools command line interface.
  Thanks to Heng Li, as this interface is inspired and
  based upon his samtools interface.

  (c) 2009-2011 - Aaron Quinlan
  Quinlan Laboratory
  Department of Public Health Sciences
  Center for Public Health genomics
  University of Virginia
  aaronquinlan@gmail.com

  Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include "version.h"

using namespace std;

// define our program name
#define PROGRAM_NAME "bedtools"

// colors for the term's menu
#define RESET "\033[m"
#define GREEN "\033[1;32m"
#define BLUE "\033[1;34m"
#define RED "\033[1;31m"

// define our parameter checking macro
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)

int annotate_main(int argc, char* argv[]);//
int bamtobed_main(int argc, char* argv[]);//
int bamtofastq_main(int argc, char* argv[]);//
int bed12tobed6_main(int argc, char* argv[]); //
int bedtobam_main(int argc, char* argv[]);//
int bedtoigv_main(int argc, char* argv[]);//
int bedpetobam_main(int argc, char* argv[]);//
int closest_main(int argc, char* argv[]); //
int cluster_main(int argc, char* argv[]); //
int complement_main(int argc, char* argv[]);//
int coverage_main(int argc, char* argv[]); //
int expand_main(int argc, char* argv[]);//
int fastafrombed_main(int argc, char* argv[]);//
int flank_main(int argc, char* argv[]); //
int genomecoverage_main(int argc, char* argv[]);//
int getoverlap_main(int argc, char* argv[]);//
int groupby_main(int argc, char* argv[]);//
int intersect_main(int argc, char* argv[]); //
int links_main(int argc, char* argv[]);//
int maskfastafrombed_main(int argc, char* argv[]);//
int map_main(int argc, char* argv[]); //
int merge_main(int argc, char* argv[]); //
int multibamcov_main(int argc, char* argv[]);//
int multiintersect_main(int argc, char* argv[]);//
int nuc_main(int argc, char* argv[]);//
int pairtobed_main(int argc, char* argv[]);//
int pairtopair_main(int argc, char* argv[]);//
int random_main(int argc, char* argv[]); //
int shuffle_main(int argc, char* argv[]); //
int slop_main(int argc, char* argv[]); //
int sort_main(int argc, char* argv[]); //
int subtract_main(int argc, char* argv[]); //
int tagbam_main(int argc, char* argv[]);//
int unionbedgraphs_main(int argc, char* argv[]);//
int window_main(int argc, char* argv[]); //
int windowmaker_main(int argc, char* argv[]); //
int bedtools_help(void);
int bedtools_faq(void);

int main(int argc, char *argv[])
{
    // make sure the user at least entered a sub_command
    if (argc < 2) return bedtools_help();

    std::string sub_cmd = argv[1];

    // genome arithmetic tools
    if (sub_cmd == "intersect")        return intersect_main(argc-1, argv+1);
    else if (sub_cmd == "window")      return window_main(argc-1, argv+1);
    else if (sub_cmd == "closest")     return closest_main(argc-1, argv+1);
    else if (sub_cmd == "coverage")    return coverage_main(argc-1, argv+1);
    else if (sub_cmd == "map")         return map_main(argc-1, argv+1);
    else if (sub_cmd == "genomecov")   return genomecoverage_main(argc-1, argv+1);
    else if (sub_cmd == "merge")       return merge_main(argc-1, argv+1);
    else if (sub_cmd == "cluster")     return cluster_main(argc-1, argv+1);
    else if (sub_cmd == "complement")  return complement_main(argc-1, argv+1);
    else if (sub_cmd == "subtract")    return subtract_main(argc-1, argv+1);
    else if (sub_cmd == "slop")        return slop_main(argc-1, argv+1);
    else if (sub_cmd == "flank")       return flank_main(argc-1, argv+1);
    else if (sub_cmd == "sort")        return sort_main(argc-1, argv+1);
    else if (sub_cmd == "random")      return random_main(argc-1, argv+1);
    else if (sub_cmd == "shuffle")     return shuffle_main(argc-1, argv+1);
    else if (sub_cmd == "annotate")    return annotate_main(argc-1, argv+1);

    // Multi-way file comparisonstools
    else if (sub_cmd == "multiinter")  return multiintersect_main(argc-1, argv+1);
    else if (sub_cmd == "unionbedg")   return unionbedgraphs_main(argc-1, argv+1);

    // paired-end conversion tools
    else if (sub_cmd == "pairtobed")   return pairtobed_main(argc-1, argv+1);
    else if (sub_cmd == "pairtopair")  return pairtopair_main(argc-1, argv+1);

    // format conversion tools
    else if (sub_cmd == "bamtobed")    return bamtobed_main(argc-1, argv+1);
    else if (sub_cmd == "bedtobam")    return bedtobam_main(argc-1, argv+1);
    else if (sub_cmd == "bamtofastq")  return bamtofastq_main(argc-1, argv+1);
    else if (sub_cmd == "bedpetobam")  return bedpetobam_main(argc-1, argv+1);
    else if (sub_cmd == "bed12tobed6") return bed12tobed6_main(argc-1, argv+1);

    // BAM-specific tools
    else if (sub_cmd == "multicov")    return multibamcov_main(argc-1, argv+1);
    else if (sub_cmd == "tag")         return tagbam_main(argc-1, argv+1);

    // fasta tools
    else if (sub_cmd == "getfasta")    return fastafrombed_main(argc-1, argv+1);
    else if (sub_cmd == "maskfasta")   return maskfastafrombed_main(argc-1, argv+1);
    else if (sub_cmd == "nuc")         return nuc_main(argc-1, argv+1);

    // misc. tools
    else if (sub_cmd == "overlap")     return getoverlap_main(argc-1, argv+1);
    else if (sub_cmd == "igv")         return bedtoigv_main(argc-1, argv+1);
    else if (sub_cmd == "links")       return links_main(argc-1, argv+1);
    else if (sub_cmd == "makewindows") return windowmaker_main(argc-1, argv+1);
    else if (sub_cmd == "groupby")     return groupby_main(argc-1, argv+1);
    else if (sub_cmd == "expand")      return expand_main(argc-1, argv+1);

    // help
    else if (sub_cmd == "-h" || sub_cmd == "--help" ||
             sub_cmd == "-help")
        return bedtools_help();

    // frequently asked questions
    else if (sub_cmd == "--FAQ" || sub_cmd == "--faq" ||
             sub_cmd == "-FAQ"  || sub_cmd == "-faq")
        return bedtools_faq();

    // verison information
    else if (sub_cmd == "-version" || sub_cmd == "--version")
        cout << "bedtools " << VERSION << endl;

    // verison information
    else if (sub_cmd == "-contact" || sub_cmd == "--contact")
    {
        cout << endl;
        cout << "- For further help, or to report a bug, please " << endl;
        cout << "  email the bedtools mailing list: " << endl;
        cout << "     bedtools-discuss@googlegroups.com" << endl << endl;

        cout << "- Stable releases of bedtools can be found at: " << endl;
        cout << "     http://bedtools.googlecode.com" << endl << endl;

        cout << "- The development repository can be found at: " << endl;
        cout << "     https://github.com/arq5x/bedtools" << endl << endl;
    }
    // unknown
    else {
        // TODO: Implement a Levenstein-based "did you mean???"
        cerr << "error: unrecognized command: " << argv[1] << endl << endl;
        return 1;
    }
    return 0;
}

int bedtools_help(void)
{
    cout  << PROGRAM_NAME  << ": flexible tools for genome arithmetic and DNA sequence analysis.\n";
    cout << "usage:    bedtools <subcommand> [options]" << endl << endl;

    cout  << "The bedtools sub-commands include:" << endl;

    cout  << endl;
    cout  << "[ Genome arithmetic ]" << endl;
    cout  << "    intersect     "  << "Find overlapping intervals in various ways.\n";
    cout  << "    window        "  << "Find overlapping intervals within a window around an interval.\n";
    cout  << "    closest       "  << "Find the closest, potentially non-overlapping interval.\n";
    cout  << "    coverage      "  << "Compute the coverage over defined intervals.\n";
    cout  << "    map           "  << "Apply a function to a column for each overlapping interval.\n";
    cout  << "    genomecov     "  << "Compute the coverage over an entire genome.\n";
    cout  << "    merge         "  << "Combine overlapping/nearby intervals into a single interval.\n";
    cout  << "    cluster       "  << "Cluster (but don't merge) overlapping/nearby intervals.\n";
    cout  << "    complement    "  << "Extract intervals _not_ represented by an interval file.\n";
    cout  << "    subtract      "  << "Remove intervals based on overlaps b/w two files.\n";
    cout  << "    slop          "  << "Adjust the size of intervals.\n";
    cout  << "    flank         "  << "Create new intervals from the flanks of existing intervals.\n";
    cout  << "    sort          "  << "Order the intervals in a file.\n";
    cout  << "    random        "  << "Generate random intervals in a genome.\n";
    cout  << "    shuffle       "  << "Randomly redistrubute intervals in a genome.\n";
    cout  << "    annotate      "  << "Annotate coverage of features from multiple files.\n";

    cout  << endl;
    cout  << "[ Multi-way file comparisons ]" << endl;
    cout  << "    multiinter    "  << "Identifies common intervals among multiple interval files.\n";
    cout  << "    unionbedg     "  << "Combines coverage intervals from multiple BEDGRAPH files.\n";

    cout  << endl;
    cout  << "[ Paired-end manipulation ]" << endl;
    cout  << "    pairtobed     "  << "Find pairs that overlap intervals in various ways.\n";
    cout  << "    pairtopair    "  << "Find pairs that overlap other pairs in various ways.\n";

    cout  << endl;
    cout  << "[ Format conversion ]" << endl;
    cout  << "    bamtobed      "  << "Convert BAM alignments to BED (& other) formats.\n";
    cout  << "    bedtobam      "  << "Convert intervals to BAM records.\n";
    cout  << "    bamtofastq    "  << "Convert BAM records to FASTQ records.\n";
    cout  << "    bedpetobam    "  << "Convert BEDPE intervals to BAM records.\n";
    cout  << "    bed12tobed6   "  << "Breaks BED12 intervals into discrete BED6 intervals.\n";

    cout  << endl;
    cout  << "[ Fasta manipulation ]" << endl;
    cout  << "    getfasta      "  << "Use intervals to extract sequences from a FASTA file.\n";
    cout  << "    maskfasta     "  << "Use intervals to mask sequences from a FASTA file.\n";
    cout  << "    nuc           "  << "Profile the nucleotide content of intervals in a FASTA file.\n";

    cout  << endl;
    cout  << "[ BAM focused tools ]" << endl;
    cout  << "    multicov      "  << "Counts coverage from multiple BAMs at specific intervals.\n";
    cout  << "    tag           "  << "Tag BAM alignments based on overlaps with interval files.\n";

    cout  << endl;
    cout  << "[ Miscellaneous tools ]" << endl;
    cout  << "    overlap       "  << "Computes the amount of overlap from two intervals.\n";
    cout  << "    igv           "  << "Create an IGV snapshot batch script.\n";
    cout  << "    links         "  << "Create a HTML page of links to UCSC locations.\n";
    cout  << "    makewindows   "  << "Make interval \"windows\" across a genome.\n";
    cout  << "    groupby       "  << "Group by common cols. & summarize oth. cols. (~ SQL \"groupBy\")\n";
    cout  << "    expand        "  << "Replicate lines based on lists of values in columns.\n";

    cout  << endl;
    cout  << "[ General help ]" << endl;
    cout  << "    --help        "  << "Print this help menu.\n";
    //cout  << "    --faq         "  << "Frequently asked questions.\n";  TODO
    cout  << "    --version     "  << "What version of bedtools are you using?.\n";
    cout  << "    --contact     "  << "Feature requests, bugs, mailing lists, etc.\n";

    cout << "\n";
    return 0;
}

int bedtools_faq(void)
{
    cout << "\n";

    cout << "Q1. How do I see the help for a given command?" << endl;
    cout << "A1. All BEDTools commands have a \"-h\" option. Additionally, some tools " << endl;
    cout << "    will provide the help menu if you just type the command line " << endl;
    cout << "    followed by enter. " << endl;

    cout << "\n";
    return 0;
}
<|endoftext|>