text:
#include <fstream>
#include <fcntl.h>
#include <string>
#include <map>
#include <stdlib.h>
#include <pcl/point_types.h>
#include <pcl/common/io.h>
#include <pcl/io/ply_io.h>
#include <pcl/io/boost.h>
#include <sstream>

boost::tuple<boost::function<void ()>, boost::function<void ()> >
pcl::PLYReader::elementDefinitionCallback (const std::string& element_name, std::size_t count)
{
  if (element_name == "vertex")
  {
    cloud_->data.clear ();
    cloud_->fields.clear ();
    // Cloud dimensions may have already been set from obj_info fields
    if (cloud_->width == 0 || cloud_->height == 0)
    {
      cloud_->width = static_cast<uint32_t> (count);
      cloud_->height = 1;
    }
    cloud_->is_dense = false;
    cloud_->point_step = 0;
    cloud_->row_step = 0;
    vertex_count_ = 0;
    return (boost::tuple<boost::function<void ()>, boost::function<void ()> > (
              boost::bind (&pcl::PLYReader::vertexBeginCallback, this),
              boost::bind (&pcl::PLYReader::vertexEndCallback, this)));
  }
  else if ((element_name == "face") && polygons_)
  {
    polygons_->reserve (count);
    return (boost::tuple<boost::function<void ()>, boost::function<void ()> > (
            boost::bind (&pcl::PLYReader::faceBeginCallback, this),
            boost::bind (&pcl::PLYReader::faceEndCallback, this)));
  }
  else if (element_name == "camera")
  {
    cloud_->is_dense = true;
    return (boost::tuple<boost::function<void ()>, boost::function<void ()> > (0, 0));
  }
  else if (element_name == "range_grid")
  {
    range_grid_->reserve (count);
    return (boost::tuple<boost::function<void ()>, boost::function<void ()> > (
              boost::bind (&pcl::PLYReader::rangeGridBeginCallback, this),
              boost::bind (&pcl::PLYReader::rangeGridEndCallback, this)));
  }
  else
  {
    return (boost::tuple<boost::function<void ()>, boost::function<void ()> > (0, 0));
  }
}

bool
pcl::PLYReader::endHeaderCallback ()
{
  cloud_->data.resize (cloud_->point_step * cloud_->width * cloud_->height);
  return (cloud_->data.size () == cloud_->point_step * cloud_->width * cloud_->height);
}

template<typename Scalar> void
pcl::PLYReader::appendScalarProperty (const std::string& name, const size_t& size)
{
  cloud_->fields.push_back (::pcl::PCLPointField ());
  ::pcl::PCLPointField &current_field = cloud_->fields.back ();
  current_field.name = name;
  current_field.offset = cloud_->point_step;
  current_field.datatype = pcl::traits::asEnum<Scalar>::value;
  current_field.count = static_cast<uint32_t> (size);
  cloud_->point_step += static_cast<uint32_t> (pcl::getFieldSize (pcl::traits::asEnum<Scalar>::value) * size);
}

void
pcl::PLYReader::amendProperty (const std::string& old_name, const std::string& new_name, uint8_t new_datatype)
{
  std::vector< ::pcl::PCLPointField>::reverse_iterator finder = cloud_->fields.rbegin ();
  for (; finder != cloud_->fields.rend (); ++finder)
    if (finder->name == old_name)
      break;
  assert (finder != cloud_->fields.rend ());
  finder->name = new_name;
  if (new_datatype > 0 && new_datatype != finder->datatype)
    finder->datatype = new_datatype;
}

namespace pcl
{
  template <>
  boost::function<void (pcl::io::ply::float32)>
  PLYReader::scalarPropertyDefinitionCallback (const std::string& element_name, const std::string& property_name)
  {
    if (element_name == "vertex")
    {
      appendScalarProperty<pcl::io::ply::float32> (property_name, 1);
      return (boost::bind (&pcl::PLYReader::vertexScalarPropertyCallback<pcl::io::ply::float32>, this, _1));
    }
    else if (element_name == "camera")
    {
      if (property_name == "view_px")
      {
        return boost::bind (&pcl::PLYReader::originXCallback, this, _1);
      }
      else if (property_name == "view_py")
      {
        return boost::bind (&pcl::PLYReader::originYCallback, this, _1);
      }
      else if (property_name == "view_pz")
      {
        return boost::bind (&pcl::PLYReader::originZCallback, this, _1);
      }
      else if (property_name == "x_axisx")
      {
        return boost::bind (&pcl::PLYReader::orientationXaxisXCallback, this, _1);
      }
      else if (property_name == "x_axisy")
      {
        return boost::bind (&pcl::PLYReader::orientationXaxisYCallback, this, _1);
      }
      else if (property_name == "x_axisz")
      {
        return boost::bind (&pcl::PLYReader::orientationXaxisZCallback, this, _1);
      }
      else if (property_name == "y_axisx")
      {
        return boost::bind (&pcl::PLYReader::orientationYaxisXCallback, this, _1);
      }
      else if (property_name == "y_axisy")
      {
        return boost::bind (&pcl::PLYReader::orientationYaxisYCallback, this, _1);
      }
      else if (property_name == "y_axisz")
      {
        return boost::bind (&pcl::PLYReader::orientationYaxisZCallback, this, _1);
      }
      else if (property_name == "z_axisx")
      {
        return boost::bind (&pcl::PLYReader::orientationZaxisXCallback, this, _1);
      }
      else if (property_name == "z_axisy")
      {
        return boost::bind (&pcl::PLYReader::orientationZaxisYCallback, this, _1);
      }
      else if (property_name == "z_axisz")
      {
        return boost::bind (&pcl::PLYReader::orientationZaxisZCallback, this, _1);
      }
      else
      {
        return (0);
      }
    }
    else
    {
      return (0);
    }
  }

  template <> boost::function<void (pcl::io::ply::uint8)>
  PLYReader::scalarPropertyDefinitionCallback (const std::string& element_name, const std::string& property_name)
  {
    if (element_name == "vertex")
    {
      if ((property_name == "red") || (property_name == "green") || (property_name == "blue") ||
          (property_name == "diffuse_red") || (property_name == "diffuse_green") || (property_name == "diffuse_blue"))
      {
        if ((property_name == "red") || (property_name == "diffuse_red"))
          appendScalarProperty<pcl::io::ply::float32> ("rgb");
        return boost::bind (&pcl::PLYReader::vertexColorCallback, this, property_name, _1);
      }
      else if (property_name == "alpha")
      {
        amendProperty ("rgb", "rgba", pcl::PCLPointField::UINT32);
        return boost::bind (&pcl::PLYReader::vertexAlphaCallback, this, _1);
      }
      else if (property_name == "intensity")
      {
        appendScalarProperty<pcl::io::ply::float32> (property_name);
        return boost::bind (&pcl::PLYReader::vertexIntensityCallback, this, _1);
      }
      else
      {
        appendScalarProperty<pcl::io::ply::uint8> (property_name);
        return boost::bind (&pcl::PLYReader::vertexScalarPropertyCallback<pcl::io::ply::uint8>, this, _1);
      }
    }
    else
      return (0);
  }

  template <> boost::function<void (pcl::io::ply::int32)>
  PLYReader::scalarPropertyDefinitionCallback (const std::string& element_name, const std::string& property_name)
  {
    if (element_name == "vertex")
    {
      appendScalarProperty<pcl::io::ply::int32> (property_name, 1);
      return (boost::bind (&pcl::PLYReader::vertexScalarPropertyCallback<pcl::io::ply::int32>, this, _1));
    }
    if (element_name == "camera")
    {
      if (property_name == "viewportx")
      {
        return boost::bind (&pcl::PLYReader::cloudWidthCallback, this, _1);
      }
      else if (property_name == "viewporty")
      {
        return boost::bind (&pcl::PLYReader::cloudHeightCallback, this, _1);
      }
      else
        return (0);
    }
    else
      return (0);
  }

  template <typename Scalar> boost::function<void (Scalar)>
  PLYReader::scalarPropertyDefinitionCallback (const std::string& element_name, const std::string& property_name)
  {
    if (element_name == "vertex")
    {
      appendScalarProperty<Scalar> (property_name, 1);
      return (boost::bind (&pcl::PLYReader::vertexScalarPropertyCallback<Scalar>, this, _1));
    }
    return (0);
  }

  template<typename Scalar> void
  PLYReader::vertexScalarPropertyCallback (Scalar value)
  {
    memcpy (&cloud_->data[vertex_count_ * cloud_->point_step + vertex_offset_before_],
            &value,
            sizeof (Scalar));
    vertex_offset_before_ += static_cast<int> (sizeof (Scalar));
  }

  template <typename SizeType> void
  PLYReader::vertexListPropertyBeginCallback (const std::string& name, SizeType size)
  {
    // Adjust size only once
    if (vertex_count_ == 0)
    {
      std::vector< pcl::PCLPointField>::reverse_iterator finder = cloud_->fields.rbegin ();
      for (; finder != cloud_->fields.rend (); ++finder)
        if (finder->name == name)
          break;
      assert (finder != cloud_->fields.rend ());
      finder->count = size;
    }
  }

  template<typename ContentType> void
  PLYReader::vertexListPropertyContentCallback (ContentType value)
  {
    memcpy (&cloud_->data[vertex_count_ * cloud_->point_step + vertex_offset_before_],
            &value,
            sizeof (ContentType));
    vertex_offset_before_ += static_cast<int> (sizeof (ContentType));
  }

  template <>
  boost::tuple<boost::function<void (pcl::io::ply::uint8)>, boost::function<void (pcl::io::ply::int32)>, boost::function<void ()> >
  pcl::PLYReader::listPropertyDefinitionCallback (const std::string& element_name, const std::string& property_name)
  {
    if ((element_name == "range_grid") && (property_name == "vertex_indices" || property_name == "vertex_index"))
    {
      return boost::tuple<boost::function<void (pcl::io::ply::uint8)>, boost::function<void (pcl::io::ply::int32)>, boost::function<void ()> > (
        boost::bind (&pcl::PLYReader::rangeGridVertexIndicesBeginCallback, this, _1),
        boost::bind (&pcl::PLYReader::rangeGridVertexIndicesElementCallback, this, _1),
        boost::bind (&pcl::PLYReader::rangeGridVertexIndicesEndCallback, this)
      );
    }
    else if ((element_name == "face") && (property_name == "vertex_indices" || property_name == "vertex_index") && polygons_)
    {
      return boost::tuple<boost::function<void (pcl::io::ply::uint8)>, boost::function<void (pcl::io::ply::int32)>, boost::function<void ()> > (
        boost::bind (&pcl::PLYReader::faceVertexIndicesBeginCallback, this, _1),
        boost::bind (&pcl::PLYReader::faceVertexIndicesElementCallback, this, _1),
        boost::bind (&pcl::PLYReader::faceVertexIndicesEndCallback, this)
      );
    }
    else if (element_name == "vertex")
    {
      cloud_->fields.push_back (pcl::PCLPointField ());
      pcl::PCLPointField &current_field = cloud_->fields.back ();
      current_field.name = property_name;
      current_field.offset = cloud_->point_step;
      current_field.datatype = pcl::traits::asEnum<pcl::io::ply::int32>::value;
      current_field.count = std::numeric_limits<pcl::io::ply::uint8>::max ();
      if (current_field.count * sizeof (pcl::io::ply::int32) + cloud_->point_step < std::numeric_limits<uint32_t>::max ())
          cloud_->point_step += static_cast<uint32_t> (current_field.count * sizeof (pcl::io::ply::int32));
      else
        cloud_->point_step = static_cast<uint32_t> (std::numeric_limits<uint32_t>::max ());
      do_resize_ = true;
      return boost::tuple<boost::function<void (pcl::io::ply::uint8)>, boost::function<void (pcl::io::ply::int32)>, boost::function<void ()> > (
                                                                                boost::bind (&pcl::PLYReader::vertexListPropertyBeginCallback<pcl::io::ply::uint8>, this, property_name, _1),
        boost::bind (&pcl::PLYReader::vertexListPropertyContentCallback<pcl::io::ply::int32>, this, _1),
        boost::bind (&pcl::PLYReader::vertexListPropertyEndCallback, this)
      );
    }
    else
    {
      return boost::tuple<boost::function<void (pcl::io::ply::uint8)>, boost::function<void (pcl::io::ply::int32)>, boost::function<void ()> > (0, 0, 0);
    }
  }

  template <typename SizeType, typename ContentType>
  boost::tuple<boost::function<void (SizeType)>, boost::function<void (ContentType)>, boost::function<void ()> >
  pcl::PLYReader::listPropertyDefinitionCallback (const std::string& element_name, const std::string& property_name)
  {
    if (element_name == "vertex")
    {
      cloud_->fields.push_back (pcl::PCLPointField ());
      pcl::PCLPointField &current_field = cloud_->fields.back ();
      current_field.name = property_name;
      current_field.offset = cloud_->point_step;
      current_field.datatype = pcl::traits::asEnum<ContentType>::value;
      current_field.count = std::numeric_limits<SizeType>::max ();
      if (current_field.count * sizeof (ContentType) + cloud_->point_step < std::numeric_limits<uint32_t>::max ())
        cloud_->point_step += static_cast<uint32_t> (current_field.count * sizeof (ContentType));
      else
        cloud_->point_step = static_cast<uint32_t> (std::numeric_limits<uint32_t>::max ());
      do_resize_ = true;
      return boost::tuple<boost::function<void (SizeType)>, boost::function<void (ContentType)>, boost::function<void ()> > (
        boost::bind (&pcl::PLYReader::vertexListPropertyBeginCallback<SizeType>, this, property_name, _1),
        boost::bind (&pcl::PLYReader::vertexListPropertyContentCallback<ContentType>, this, _1),
        boost::bind (&pcl::PLYReader::vertexListPropertyEndCallback, this)
      );
    }
    else
    {
      return boost::tuple<boost::function<void (SizeType)>, boost::function<void (ContentType)>, boost::function<void ()> > (0, 0, 0);
    }
  }
}

void
pcl::PLYReader::vertexColorCallback (const std::string& color_name, pcl::io::ply::uint8 color)
{
  if ((color_name == "red") || (color_name == "diffuse_red"))
  {
    r_ = int32_t (color);
    rgb_offset_before_ = vertex_offset_before_;
  }
  if ((color_name == "green") || (color_name == "diffuse_green"))
  {
    g_ = int32_t (color);
  }
  if ((color_name == "blue") || (color_name == "diffuse_blue"))
  {
    b_ = int32_t (color);
    int32_t rgb = r_ << 16 | g_ << 8 | b_;
    memcpy (&cloud_->data[vertex_count_ * cloud_->point_step + rgb_offset_before_],
            &rgb,
            sizeof (pcl::io::ply::float32));
    vertex_offset_before_ += static_cast<int> (sizeof (pcl::io::ply::float32));
  }
}

void
pcl::PLYReader::vertexAlphaCallback (pcl::io::ply::uint8 alpha)
{
  a_ = uint32_t (alpha);
  // get anscient rgb value and store it in rgba
  memcpy (&rgba_,
          &cloud_->data[vertex_count_ * cloud_->point_step + rgb_offset_before_],
          sizeof (pcl::io::ply::float32));
  // append alpha
  rgba_ = rgba_ | a_ << 24;
  // put rgba back
  memcpy (&cloud_->data[vertex_count_ * cloud_->point_step + rgb_offset_before_],
          &rgba_,
          sizeof (uint32_t));
}

void
pcl::PLYReader::vertexIntensityCallback (pcl::io::ply::uint8 intensity)
{
  pcl::io::ply::float32 intensity_ (intensity);
  memcpy (&cloud_->data[vertex_count_ * cloud_->point_step + vertex_offset_before_],
          &intensity_,
          sizeof (pcl::io::ply::float32));
  vertex_offset_before_ += static_cast<int> (sizeof (pcl::io::ply::float32));
}

void
pcl::PLYReader::vertexBeginCallback ()
{
  vertex_offset_before_ = 0;
}

void
pcl::PLYReader::vertexEndCallback ()
{
  // Resize data if needed
  if (vertex_count_ == 0 && do_resize_)
  {
    cloud_->point_step = vertex_offset_before_;
    cloud_->row_step = cloud_->point_step * cloud_->width;
    cloud_->data.resize (cloud_->point_step * cloud_->width * cloud_->height);
  }
  ++vertex_count_;
}

void
pcl::PLYReader::rangeGridBeginCallback ()
{
  range_grid_->push_back (std::vector <int> ());
}

void
pcl::PLYReader::rangeGridVertexIndicesBeginCallback (pcl::io::ply::uint8 size)
{
  range_grid_->back ().reserve (size);
}

void
pcl::PLYReader::rangeGridVertexIndicesElementCallback (pcl::io::ply::int32 vertex_index)
{
  range_grid_->back ().push_back (vertex_index);
}

void
pcl::PLYReader::rangeGridVertexIndicesEndCallback () {}

void
pcl::PLYReader::rangeGridEndCallback () {}

void
pcl::PLYReader::faceBeginCallback ()
{
  polygons_->push_back (pcl::Vertices ());
}

void
pcl::PLYReader::faceVertexIndicesBeginCallback (pcl::io::ply::uint8 size)
{
  polygons_->back ().vertices.reserve (size);
}

void
pcl::PLYReader::faceVertexIndicesElementCallback (pcl::io::ply::int32 vertex_index)
{
  polygons_->back ().vertices.push_back (vertex_index);
}

void
pcl::PLYReader::faceVertexIndicesEndCallback () { }

void
pcl::PLYReader::faceEndCallback () {}

void
pcl::PLYReader::objInfoCallback (const std::string& line)
{
  std::vector<std::string> st;
  boost::split (st, line, boost::is_any_of (std::string ( "\t ")), boost::token_compress_on);
  assert (st[0].substr (0, 8) == "obj_info");
  {
    if (st.size() >= 3)
    {
      if (st[1] == "num_cols")
        cloudWidthCallback (atoi (st[2].c_str ()));
      else if (st[1] == "num_rows")
        cloudHeightCallback (atoi (st[2].c_str ()));
      else if (st[1] == "echo_rgb_offset_x")
        originXCallback (static_cast<float> (atof (st[2].c_str ())));
      else if (st[1] == "echo_rgb_offset_y")
        originYCallback (static_cast<float> (atof (st[2].c_str ())));
      else if (st[1] == "echo_rgb_offset_z")
        originZCallback (static_cast<float> (atof (st[2].c_str ())));
    }
  }
}

void
pcl::PLYReader::vertexListPropertyEndCallback () {}

bool
pcl::PLYReader::parse (const std::string& istream_filename)
{
  pcl::io::ply::ply_parser::flags_type ply_parser_flags = 0;
  pcl::io::ply::ply_parser ply_parser (ply_parser_flags);

  ply_parser.info_callback (boost::bind (&pcl::PLYReader::infoCallback, this, boost::ref (istream_filename), _1, _2));
  ply_parser.warning_callback (boost::bind (&pcl::PLYReader::warningCallback, this, boost::ref (istream_filename), _1, _2));
  ply_parser.error_callback (boost::bind (&pcl::PLYReader::errorCallback, this, boost::ref (istream_filename), _1, _2));

  ply_parser.obj_info_callback (boost::bind (&pcl::PLYReader::objInfoCallback, this, _1));
  ply_parser.element_definition_callback (boost::bind (&pcl::PLYReader::elementDefinitionCallback, this, _1, _2));
  ply_parser.end_header_callback (boost::bind (&pcl::PLYReader::endHeaderCallback, this));

  pcl::io::ply::ply_parser::scalar_property_definition_callbacks_type scalar_property_definition_callbacks;
  pcl::io::ply::ply_parser::at<pcl::io::ply::float64> (scalar_property_definition_callbacks) = boost::bind (&pcl::PLYReader::scalarPropertyDefinitionCallback<pcl::io::ply::float64>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::float32> (scalar_property_definition_callbacks) = boost::bind (&pcl::PLYReader::scalarPropertyDefinitionCallback<pcl::io::ply::float32>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::int8> (scalar_property_definition_callbacks) = boost::bind (&pcl::PLYReader::scalarPropertyDefinitionCallback<pcl::io::ply::int8>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint8> (scalar_property_definition_callbacks) = boost::bind (&pcl::PLYReader::scalarPropertyDefinitionCallback<pcl::io::ply::uint8>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::int32> (scalar_property_definition_callbacks) = boost::bind (&pcl::PLYReader::scalarPropertyDefinitionCallback<pcl::io::ply::int32>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint32> (scalar_property_definition_callbacks) = boost::bind (&pcl::PLYReader::scalarPropertyDefinitionCallback<pcl::io::ply::uint32>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::int16> (scalar_property_definition_callbacks) = boost::bind (&pcl::PLYReader::scalarPropertyDefinitionCallback<pcl::io::ply::int16>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint16> (scalar_property_definition_callbacks) = boost::bind (&pcl::PLYReader::scalarPropertyDefinitionCallback<pcl::io::ply::uint16>, this, _1, _2);
  ply_parser.scalar_property_definition_callbacks (scalar_property_definition_callbacks);

  pcl::io::ply::ply_parser::list_property_definition_callbacks_type list_property_definition_callbacks;
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint8, pcl::io::ply::int32> (list_property_definition_callbacks) = boost::bind (&pcl::PLYReader::listPropertyDefinitionCallback<pcl::io::ply::uint8, pcl::io::ply::int32>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint32, pcl::io::ply::float64> (list_property_definition_callbacks) = boost::bind (&pcl::PLYReader::listPropertyDefinitionCallback<pcl::io::ply::uint32, pcl::io::ply::float64>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint32, pcl::io::ply::float32> (list_property_definition_callbacks) = boost::bind (&pcl::PLYReader::listPropertyDefinitionCallback<pcl::io::ply::uint32, pcl::io::ply::float32>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint32, pcl::io::ply::uint32> (list_property_definition_callbacks) = boost::bind (&pcl::PLYReader::listPropertyDefinitionCallback<pcl::io::ply::uint32, pcl::io::ply::uint32>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint32, pcl::io::ply::int32> (list_property_definition_callbacks) = boost::bind (&pcl::PLYReader::listPropertyDefinitionCallback<pcl::io::ply::uint32, pcl::io::ply::int32>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint32, pcl::io::ply::uint16> (list_property_definition_callbacks) = boost::bind (&pcl::PLYReader::listPropertyDefinitionCallback<pcl::io::ply::uint32, pcl::io::ply::uint16>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint32, pcl::io::ply::int16> (list_property_definition_callbacks) = boost::bind (&pcl::PLYReader::listPropertyDefinitionCallback<pcl::io::ply::uint32, pcl::io::ply::int16>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint32, pcl::io::ply::uint8> (list_property_definition_callbacks) = boost::bind (&pcl::PLYReader::listPropertyDefinitionCallback<pcl::io::ply::uint32, pcl::io::ply::uint8>, this, _1, _2);
  pcl::io::ply::ply_parser::at<pcl::io::ply::uint32, pcl::io::ply::int8> (list_property_definition_callbacks) = boost::bind (&pcl::PLYReader::listPropertyDefinitionCallback<pcl::io::ply::uint32, pcl::io::ply::int8>, this, _1, _2);
  ply_parser.list_property_definition_callbacks (list_property_definition_callbacks);

  return ply_parser.parse (istream_filename);
}

////////////////////////////////////////////////////////////////////////////////////////
int
pcl::PLYReader::readHeader (const std::string &file_name, pcl::PCLPointCloud2 &cloud,
                            Eigen::Vector4f &origin, Eigen::Quaternionf &orientation,
                            int &, int &, unsigned int &, const int)
{
  // Silence compiler warnings
  cloud_ = &cloud;
  range_grid_ = new std::vector<std::vector<int> >;
  cloud_->width = cloud_->height = 0;
  origin = Eigen::Vector4f::Zero ();
  orientation = Eigen::Quaternionf::Identity ();
  if (!parse (file_name))
  {
    PCL_ERROR ("[pcl::PLYReader::read] problem parsing header!\n");
    return (-1);
  }
  cloud_->row_step = cloud_->point_step * cloud_->width;
  return 0;
}

////////////////////////////////////////////////////////////////////////////////////////
int
pcl::PLYReader::read (const std::string &file_name, pcl::PCLPointCloud2 &cloud,
                      Eigen::Vector4f &origin, Eigen::Quaternionf &orientation, int &ply_version, const int)
{
  // kept only for backward compatibility
  int data_type;
  unsigned int data_idx;

  if (this->readHeader (file_name, cloud, origin, orientation, ply_version, data_type, data_idx))
  {
    PCL_ERROR ("[pcl::PLYReader::read] problem parsing header!\n");
    return (-1);
  }

  // a range_grid element was found ?
  size_t r_size;
  if ((r_size  = (*range_grid_).size ()) > 0 && r_size != vertex_count_)
  {
    //cloud.header = cloud_->header;
    std::vector<pcl::uint8_t> data ((*range_grid_).size () * cloud.point_step);
    const static float f_nan = std::numeric_limits <float>::quiet_NaN ();
    const static double d_nan = std::numeric_limits <double>::quiet_NaN ();
    for (size_t r = 0; r < r_size; ++r)
    {
      if ((*range_grid_)[r].size () == 0)
      {
        for (size_t f = 0; f < cloud_->fields.size (); ++f)
          if (cloud_->fields[f].datatype == ::pcl::PCLPointField::FLOAT32)
            memcpy (&data[r * cloud_->point_step + cloud_->fields[f].offset],
                    reinterpret_cast<const char*> (&f_nan), sizeof (float));
          else if (cloud_->fields[f].datatype == ::pcl::PCLPointField::FLOAT64)
            memcpy (&data[r * cloud_->point_step + cloud_->fields[f].offset],
                    reinterpret_cast<const char*> (&d_nan), sizeof (double));
          else
            memset (&data[r * cloud_->point_step + cloud_->fields[f].offset], 0,
                    pcl::getFieldSize (cloud_->fields[f].datatype) * cloud_->fields[f].count);
      }
      else
        memcpy (&data[r* cloud_->point_step], &cloud_->data[(*range_grid_)[r][0] * cloud_->point_step], cloud_->point_step);
    }
    cloud_->data.swap (data);
  }

  orientation_ = Eigen::Quaternionf (orientation);
  origin_ = origin;

  for (size_t i = 0; i < cloud_->fields.size (); ++i)
  {
    if (cloud_->fields[i].name == "nx")
      cloud_->fields[i].name = "normal_x";
    if (cloud_->fields[i].name == "ny")
      cloud_->fields[i].name = "normal_y";
    if (cloud_->fields[i].name == "nz")
      cloud_->fields[i].name = "normal_z";
  }
  return (0);
}

////////////////////////////////////////////////////////////////////////////////////////
int
pcl::PLYReader::read (const std::string &file_name, pcl::PolygonMesh &mesh,
                      Eigen::Vector4f &origin, Eigen::Quaternionf &orientation,
                      int &ply_version, const int offset)
{
  // kept only for backward compatibility
  int data_type;
  unsigned int data_idx;
  polygons_ = &(mesh.polygons);
  if (this->readHeader (file_name, mesh.cloud, origin, orientation, ply_version, data_type, data_idx, offset))
  {
    PCL_ERROR ("[pcl::PLYReader::read] problem parsing header!\n");
    return (-1);
  }

  // a range_grid element was found ?
  size_t r_size;
  if ((r_size  = (*range_grid_).size ()) > 0 && r_size != vertex_count_)
  {
    //cloud.header = cloud_->header;
    std::vector<pcl::uint8_t> data ((*range_grid_).size () * mesh.cloud.point_step);
    const static float f_nan = std::numeric_limits <float>::quiet_NaN ();
    const static double d_nan = std::numeric_limits <double>::quiet_NaN ();
    for (size_t r = 0; r < r_size; ++r)
    {
      if ((*range_grid_)[r].size () == 0)
      {
        for (size_t f = 0; f < cloud_->fields.size (); ++f)
          if (cloud_->fields[f].datatype == ::pcl::PCLPointField::FLOAT32)
            memcpy (&data[r * cloud_->point_step + cloud_->fields[f].offset],
                    reinterpret_cast<const char*> (&f_nan), sizeof (float));
          else if (cloud_->fields[f].datatype == ::pcl::PCLPointField::FLOAT64)
            memcpy (&data[r * cloud_->point_step + cloud_->fields[f].offset],
                    reinterpret_cast<const char*> (&d_nan), sizeof (double));
          else
            memset (&data[r * cloud_->point_step + cloud_->fields[f].offset], 0,
                    pcl::getFieldSize (cloud_->fields[f].datatype) * cloud_->fields[f].count);
      }
      else
        memcpy (&data[r* cloud_->point_step], &cloud_->data[(*range_grid_)[r][0] * cloud_->point_step], cloud_->point_step);
    }
    cloud_->data.swap (data);
  }

  orientation_ = Eigen::Quaternionf (orientation);
  origin_ = origin;

  for (size_t i = 0; i < cloud_->fields.size (); ++i)
  {
    if (cloud_->fields[i].name == "nx")
      cloud_->fields[i].name = "normal_x";
    if (cloud_->fields[i].name == "ny")
      cloud_->fields[i].name = "normal_y";
    if (cloud_->fields[i].name == "nz")
      cloud_->fields[i].name = "normal_z";
  }
  return (0);
}

////////////////////////////////////////////////////////////////////////////////////////
int
pcl::PLYReader::read (const std::string &file_name, pcl::PolygonMesh &mesh, const int offset)
{
  Eigen::Vector4f origin;
  Eigen::Quaternionf orientation;
  int ply_version;
  return read (file_name, mesh, origin, orientation, ply_version, offset);
}

////////////////////////////////////////////////////////////////////////////////////////
std::string
pcl::PLYWriter::generateHeader (const pcl::PCLPointCloud2 &cloud,
                                const Eigen::Vector4f &origin,
                                const Eigen::Quaternionf &,
                                bool binary,
                                bool use_camera,
                                int valid_points)
{
  std::ostringstream oss;
  // Begin header
  oss << "ply";
  if (!binary)
    oss << "\nformat ascii 1.0";
  else
  {
    if (cloud.is_bigendian)
      oss << "\nformat binary_big_endian 1.0";
    else
      oss << "\nformat binary_little_endian 1.0";
  }
  oss << "\ncomment PCL generated";

  if (!use_camera)
  {
    oss << "\nobj_info is_cyberware_data 0"
      "\nobj_info is_mesh 0"
      "\nobj_info is_warped 0"
      "\nobj_info is_interlaced 0";
    oss << "\nobj_info num_cols " << cloud.width;
    oss << "\nobj_info num_rows " << cloud.height;
    oss << "\nobj_info echo_rgb_offset_x " << origin[0];
    oss << "\nobj_info echo_rgb_offset_y " << origin[1];
    oss << "\nobj_info echo_rgb_offset_z " << origin[2];
    oss << "\nobj_info echo_rgb_frontfocus 0.0"
      "\nobj_info echo_rgb_backfocus 0.0"
      "\nobj_info echo_rgb_pixelsize 0.0"
      "\nobj_info echo_rgb_centerpixel 0"
      "\nobj_info echo_frames 1"
      "\nobj_info echo_lgincr 0.0";
  }

  oss << "\nelement vertex "<< valid_points;

  for (std::size_t i = 0; i < cloud.fields.size (); ++i)
  {
    if (cloud.fields[i].name == "normal_x")
    {
      oss << "\nproperty float nx";
    }
    else if (cloud.fields[i].name == "normal_y")
    {
      oss << "\nproperty float ny";
    }
    else if (cloud.fields[i].name == "normal_z")
    {
      oss << "\nproperty float nz";
    }
    else if (cloud.fields[i].name == "rgb")
    {
      oss << "\nproperty uchar red"
        "\nproperty uchar green"
        "\nproperty uchar blue";
    }
    else if (cloud.fields[i].name == "rgba")
    {
      oss << "\nproperty uchar red"
        "\nproperty uchar green"
        "\nproperty uchar blue"
        "\nproperty uchar alpha";
    }
    else
    {
      oss << "\nproperty";
      if (cloud.fields[i].count != 1)
        oss << " list uint";
      switch (cloud.fields[i].datatype)
      {
        case pcl::PCLPointField::INT8 : oss << " char "; break;
        case pcl::PCLPointField::UINT8 : oss << " uchar "; break;
        case pcl::PCLPointField::INT16 : oss << " short "; break;
        case pcl::PCLPointField::UINT16 : oss << " ushort "; break;
        case pcl::PCLPointField::INT32 : oss << " int "; break;
        case pcl::PCLPointField::UINT32 : oss << " uint "; break;
        case pcl::PCLPointField::FLOAT32 : oss << " float "; break;
        case pcl::PCLPointField::FLOAT64 : oss << " double "; break;
        default :
        {
          PCL_ERROR ("[pcl::PLYWriter::generateHeader] unknown data field type!");
          return ("");
        }
      }
      oss << cloud.fields[i].name;
    }
  }

  if (use_camera)
  {
    oss << "\nelement camera 1"
      "\nproperty float view_px"
      "\nproperty float view_py"
      "\nproperty float view_pz"
      "\nproperty float x_axisx"
      "\nproperty float x_axisy"
      "\nproperty float x_axisz"
      "\nproperty float y_axisx"
      "\nproperty float y_axisy"
      "\nproperty float y_axisz"
      "\nproperty float z_axisx"
      "\nproperty float z_axisy"
      "\nproperty float z_axisz"
      "\nproperty float focal"
      "\nproperty float scalex"
      "\nproperty float scaley"
      "\nproperty float centerx"
      "\nproperty float centery"
      "\nproperty int viewportx"
      "\nproperty int viewporty"
      "\nproperty float k1"
      "\nproperty float k2";
  }
  else if (cloud.height > 1)
  {
    oss << "\nelement range_grid " << cloud.width * cloud.height;
    oss << "\nproperty list uchar int vertex_indices";
  }

  // End header
  oss << "\nend_header\n";
  return (oss.str ());
}

////////////////////////////////////////////////////////////////////////////////////////

int
pcl::PLYWriter::writeASCII (const std::string &file_name,
                            const pcl::PCLPointCloud2 &cloud,
                            const Eigen::Vector4f &origin,
                            const Eigen::Quaternionf &orientation,
                            int precision,
                            bool use_camera)
{
  if (cloud.data.empty ())
  {
    PCL_ERROR ("[pcl::PLYWriter::writeASCII] Input point cloud has no data!\n");
    return (-1);
  }

  std::ofstream fs;
  fs.precision (precision);
  // Open file
  fs.open (file_name.c_str ());
  if (!fs)
  {
    PCL_ERROR ("[pcl::PLYWriter::writeASCII] Error during opening (%s)!\n", file_name.c_str ());
    return (-1);
  }

  unsigned int nr_points  = cloud.width * cloud.height;
  unsigned int point_size = static_cast<unsigned int> (cloud.data.size () / nr_points);

  // Write the header information if available
  if (use_camera)
  {
    fs << generateHeader (cloud, origin, orientation, false, use_camera, nr_points);
    writeContentWithCameraASCII (nr_points, point_size, cloud, origin, orientation, fs);
  }
  else
  {
    std::ostringstream os;
    int nr_valid_points;
    writeContentWithRangeGridASCII (nr_points, point_size, cloud, os, nr_valid_points);
    fs << generateHeader (cloud, origin, orientation, false, use_camera, nr_valid_points);
    fs << os.str ();
  }

  // Close file
  fs.close ();
  return (0);
}

void
pcl::PLYWriter::writeContentWithCameraASCII (int nr_points,
                                             int point_size,
                                             const pcl::PCLPointCloud2 &cloud,
                                             const Eigen::Vector4f &origin,
                                             const Eigen::Quaternionf &orientation,
                                             std::ofstream& fs)
{
  // Iterate through the points
  for (int i = 0; i < nr_points; ++i)
  {
    for (size_t d = 0; d < cloud.fields.size (); ++d)
    {
      int count = cloud.fields[d].count;
      if (count == 0)
        count = 1; //workaround

      if (count > 1)
        fs << count << " ";
      for (int c = 0; c < count; ++c)
      {
        switch (cloud.fields[d].datatype)
        {
          case pcl::PCLPointField::INT8:
          {
            char value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (char)], sizeof (char));
            fs << boost::numeric_cast<int> (value);
            break;
          }
          case pcl::PCLPointField::UINT8:
          {
            unsigned char value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (unsigned char)], sizeof (unsigned char));
            fs << boost::numeric_cast<int> (value);
            break;
          }
          case pcl::PCLPointField::INT16:
          {
            short value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (short)], sizeof (short));
            fs << boost::numeric_cast<int> (value);
            break;
          }
          case pcl::PCLPointField::UINT16:
          {
            unsigned short value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (unsigned short)], sizeof (unsigned short));
            fs << boost::numeric_cast<int> (value);
            break;
          }
          case pcl::PCLPointField::INT32:
          {
            int value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (int)], sizeof (int));
            fs << value;
            break;
          }
          case pcl::PCLPointField::UINT32:
          {
            if (cloud.fields[d].name.find ("rgba") == std::string::npos)
            {
              unsigned int value;
              memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (unsigned int)], sizeof (unsigned int));
              fs << value;
            }
            else
            {
              pcl::RGB color;
              memcpy (&color, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (unsigned int)], sizeof (pcl::RGB));
              int r = color.r;
              int g = color.g;
              int b = color.b;
              int a = color.a;
              fs << r << " " << g << " " << b << " " << a;
            }
            break;
          }
          case pcl::PCLPointField::FLOAT32:
          {
            if (cloud.fields[d].name.find ("rgb") == std::string::npos)
            {
              float value;
              memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (float)], sizeof (float));
              fs << value;
            }
            else
            {
              pcl::RGB color;
              memcpy (&color, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (float)], sizeof (pcl::RGB));
              int r = color.r;
              int g = color.g;
              int b = color.b;
              fs << r << " " << g << " " << b;
            }
            break;
          }
          case pcl::PCLPointField::FLOAT64:
          {
            double value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (double)], sizeof (double));
            fs << value;
            break;
          }
          default:
            PCL_WARN ("[pcl::PLYWriter::writeASCII] Incorrect field data type specified (%d)!\n", cloud.fields[d].datatype);
            break;
        }

        if (d < cloud.fields.size () - 1 || c < static_cast<int> (cloud.fields[d].count) - 1)
          fs << " ";
      }
    }
    fs << '\n';
  }
  // Append sensor information
  if (origin[3] != 0)
    fs << origin[0]/origin[3] << " " << origin[1]/origin[3] << " " << origin[2]/origin[3] << " ";
  else
    fs << origin[0] << " " << origin[1] << " " << origin[2] << " ";

  Eigen::Matrix3f R = orientation.toRotationMatrix ();
  fs << R (0,0) << " " << R (0,1) << " " << R (0,2) << " ";
  fs << R (1,0) << " " << R (1,1) << " " << R (1,2) << " ";
  fs << R (2,0) << " " << R (2,1) << " " << R (2,2) << " ";
  // No focal
  fs << 0 << " ";
  // No scale
  fs << 0 << " " << 0 << " ";
  // No center
  fs << 0 << " " << 0 << " ";
  // Viewport set to width x height
  fs << cloud.width << " " << cloud.height << " ";
  // No corrections
  fs << 0 << " " << 0;
  fs << std::endl;
  fs.flush ();
}

void
pcl::PLYWriter::writeContentWithRangeGridASCII (int nr_points,
                                                int point_size,
                                                const pcl::PCLPointCloud2 &cloud,
                                                std::ostringstream& fs,
                                                int& valid_points)
{
  valid_points = 0;
  std::vector<std::vector <int> > grids (nr_points);
  // Iterate through the points
  for (int i = 0; i < nr_points; ++i)
  {
    std::ostringstream line;
    bool is_valid_line = true;
    for (size_t d = 0; d < cloud.fields.size (); ++d)
    {
      int count = cloud.fields[d].count;
      if (count == 0)
        count = 1; //workaround
      if (count > 1)
        fs << count << " ";
      for (int c = 0; c < count; ++c)
      {
        switch (cloud.fields[d].datatype)
        {
          case pcl::PCLPointField::INT8:
          {
            char value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (char)], sizeof (char));
            line << boost::numeric_cast<int> (value);
            break;
          }
          case pcl::PCLPointField::UINT8:
          {
            unsigned char value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (unsigned char)], sizeof (unsigned char));
            line << boost::numeric_cast<int> (value);
            break;
          }
          case pcl::PCLPointField::INT16:
          {
            short value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (short)], sizeof (short));
            line << boost::numeric_cast<int> (value);
            break;
          }
          case pcl::PCLPointField::UINT16:
          {
            unsigned short value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (unsigned short)], sizeof (unsigned short));
            line << boost::numeric_cast<int> (value);
            break;
          }
          case pcl::PCLPointField::INT32:
          {
            int value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (int)], sizeof (int));
            line << value;
            break;
          }
          case pcl::PCLPointField::UINT32:
          {
            if (cloud.fields[d].name.find ("rgba") == std::string::npos)
            {
              unsigned int value;
              memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (unsigned int)], sizeof (unsigned int));
              line << value;
            }
            else
            {
              pcl::RGB color;
              memcpy (&color, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (unsigned int)], sizeof (pcl::RGB));
              int r = color.r;
              int g = color.g;
              int b = color.b;
              int a = color.a;
              line << r << " " << g << " " << b << " " << a;
            }
            break;
          }
          case pcl::PCLPointField::FLOAT32:
          {
            if (cloud.fields[d].name.find ("rgb") == std::string::npos)
            {
              float value;
              memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (float)], sizeof (float));
              // Test if x-coordinate is NaN, thus an invalid point
              if ("x" == cloud.fields[d].name)
              {
                if (!pcl_isfinite(value))
                  is_valid_line = false;
              }
              line << value;
            }
            else
            {
              pcl::RGB color;
              memcpy (&color, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (float)], sizeof (pcl::RGB));
              int r = color.r;
              int g = color.g;
              int b = color.b;
              line << r << " " << g << " " << b;
            }
            break;
          }
          case pcl::PCLPointField::FLOAT64:
          {
            double value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + c * sizeof (double)], sizeof (double));
            line << value;
            break;
          }
          default:
            PCL_WARN ("[pcl::PLYWriter::writeASCII] Incorrect field data type specified (%d)!\n", cloud.fields[d].datatype);
            break;
        }

        if (d < cloud.fields.size () - 1 || c < static_cast<int> (cloud.fields[d].count) - 1)
          line << " ";
      }
    }

    if (is_valid_line)
    {
      grids[i].push_back (valid_points);
      fs << line.str () << '\n';
      ++valid_points;
    }
  }

  // If point cloud is organized, then append range grid
  if (cloud.height > 1)
  {
    for (int i = 0; i < nr_points; ++i)
    {
      fs << grids [i].size ();
      for (std::vector <int>::const_iterator it = grids [i].begin ();
           it != grids [i].end ();
           ++it)
        fs << " " << *it;
      fs << '\n';
    }
  }

  fs.flush ();
}

////////////////////////////////////////////////////////////////////////////////////////
int
pcl::PLYWriter::writeBinary (const std::string &file_name,
                             const pcl::PCLPointCloud2 &cloud,
                             const Eigen::Vector4f &origin,
                             const Eigen::Quaternionf &orientation,
                             bool use_camera)
{
  if (cloud.data.empty ())
  {
    PCL_ERROR ("[pcl::PLYWriter::writeBinary] Input point cloud has no data!\n");
    return (-1);
  }

  std::ofstream fs;
  fs.open (file_name.c_str ());      // Open file
  if (!fs)
  {
    PCL_ERROR ("[pcl::PLYWriter::writeBinary] Error during opening (%s)!\n", file_name.c_str ());
    return (-1);
  }

  unsigned int nr_points  = cloud.width * cloud.height;
  unsigned int point_size = static_cast<unsigned int> (cloud.data.size () / nr_points);

  // Compute the range_grid, if necessary, and then write out the PLY header
  bool doRangeGrid = !use_camera && cloud.height > 1;
  std::vector<pcl::io::ply::int32> rangegrid (nr_points);
  if (doRangeGrid)
  {
    unsigned int valid_points = 0;

    // Determine the field containing the x-coordinate
    int xfield = pcl::getFieldIndex (cloud, "x");
    if (xfield >= 0 && cloud.fields[xfield].datatype != pcl::PCLPointField::FLOAT32)
      xfield = -1;

    // If no x-coordinate field exists, then assume all points are valid
    if (xfield < 0)
    {
      for (unsigned int i=0; i < nr_points; ++i)
        rangegrid[i] = i;
      valid_points = nr_points;
    }
    // Otherwise, look at their x-coordinates to determine if points are valid
    else
    {
      for (size_t i=0; i < nr_points; ++i)
      {
        float value;
        memcpy(&value, &cloud.data[i * point_size + cloud.fields[xfield].offset], sizeof(float));
        if (pcl_isfinite(value))
        {
          rangegrid[i] = valid_points;
          ++valid_points;
        }
        else
          rangegrid[i] = -1;
      }
    }
    fs << generateHeader (cloud, origin, orientation, true, use_camera, valid_points);
  }
  else
  {
    fs << generateHeader (cloud, origin, orientation, true, use_camera, nr_points);
  }

  // Close the file
  fs.close ();
  // Open file in binary appendable
  std::ofstream fpout (file_name.c_str (), std::ios::app | std::ios::binary);
  if (!fpout)
  {
    PCL_ERROR ("[pcl::PLYWriter::writeBinary] Error during reopening (%s)!\n", file_name.c_str ());
    return (-1);
  }

  // Iterate through the points
  for (unsigned int i = 0; i < nr_points; ++i)
  {
    // Skip writing any invalid points from range_grid
    if (doRangeGrid && rangegrid[i] < 0)
      continue;

    size_t total = 0;
    for (size_t d = 0; d < cloud.fields.size (); ++d)
    {
      int count = cloud.fields[d].count;
      if (count == 0)
        count = 1; //workaround
      if (count > 1)
      {
        static unsigned int ucount (count);
        fpout.write (reinterpret_cast<const char*> (&ucount), sizeof (unsigned int));
      }
      // Ignore invalid padded dimensions that are inherited from binary data
      if (cloud.fields[d].name == "_")
      {
        total += cloud.fields[d].count; // jump over this many elements in the string token
        continue;
      }

      for (int c = 0; c < count; ++c)
      {
        switch (cloud.fields[d].datatype)
        {
          case pcl::PCLPointField::INT8:
          {
            char value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + (total + c) * sizeof (char)], sizeof (char));
            fpout.write (reinterpret_cast<const char*> (&value), sizeof (char));
            break;
          }
          case pcl::PCLPointField::UINT8:
          {
            unsigned char value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + (total + c) * sizeof (unsigned char)], sizeof (unsigned char));
            fpout.write (reinterpret_cast<const char*> (&value), sizeof (unsigned char));
            break;
          }
          case pcl::PCLPointField::INT16:
          {
            short value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + (total + c) * sizeof (short)], sizeof (short));
            fpout.write (reinterpret_cast<const char*> (&value), sizeof (short));
            break;
          }
          case pcl::PCLPointField::UINT16:
          {
            unsigned short value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + (total + c) * sizeof (unsigned short)], sizeof (unsigned short));
            fpout.write (reinterpret_cast<const char*> (&value), sizeof (unsigned short));
            break;
          }
          case pcl::PCLPointField::INT32:
          {
            int value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + (total + c) * sizeof (int)], sizeof (int));
            fpout.write (reinterpret_cast<const char*> (&value), sizeof (int));
            break;
          }
          case pcl::PCLPointField::UINT32:
          {
            if (cloud.fields[d].name.find ("rgba") == std::string::npos)
            {
              unsigned int value;
              memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + (total + c) * sizeof (unsigned int)], sizeof (unsigned int));
              fpout.write (reinterpret_cast<const char*> (&value), sizeof (unsigned int));
            }
            else
            {
              pcl::RGB color;
              memcpy (&color, &cloud.data[i * point_size + cloud.fields[d].offset + (total + c) * sizeof (unsigned int)], sizeof (pcl::RGB));
              unsigned char r = color.r;
              unsigned char g = color.g;
              unsigned char b = color.b;
              unsigned char a = color.a;
              fpout.write (reinterpret_cast<const char*> (&r), sizeof (unsigned char));
              fpout.write (reinterpret_cast<const char*> (&g), sizeof (unsigned char));
              fpout.write (reinterpret_cast<const char*> (&b), sizeof (unsigned char));
              fpout.write (reinterpret_cast<const char*> (&a), sizeof (unsigned char));
            }
            break;
          }
          case pcl::PCLPointField::FLOAT32:
          {
            if (cloud.fields[d].name.find ("rgb") == std::string::npos)
            {
              float value;
              memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + (total + c) * sizeof (float)], sizeof (float));
              fpout.write (reinterpret_cast<const char*> (&value), sizeof (float));
            }
            else
            {
              pcl::RGB color;
              memcpy (&color, &cloud.data[i * point_size + cloud.fields[d].offset + (total + c) * sizeof (float)], sizeof (pcl::RGB));
              unsigned char r = color.r;
              unsigned char g = color.g;
              unsigned char b = color.b;
              fpout.write (reinterpret_cast<const char*> (&r), sizeof (unsigned char));
              fpout.write (reinterpret_cast<const char*> (&g), sizeof (unsigned char));
              fpout.write (reinterpret_cast<const char*> (&b), sizeof (unsigned char));
            }
            break;
          }
          case pcl::PCLPointField::FLOAT64:
          {
            double value;
            memcpy (&value, &cloud.data[i * point_size + cloud.fields[d].offset + (total + c) * sizeof (double)], sizeof (double));
            fpout.write (reinterpret_cast<const char*> (&value), sizeof (double));
            break;
          }
          default:
            PCL_WARN ("[pcl::PLYWriter::writeBinary] Incorrect field data type specified (%d)!\n", cloud.fields[d].datatype);
            break;
        }
      }
    }
  }

  if (use_camera)
  {
    // Append sensor information
    float t;
    for (int i = 0; i < 3; ++i)
    {
      if (origin[3] != 0)
        t = origin[i]/origin[3];
      else
        t = origin[i];
      fpout.write (reinterpret_cast<const char*> (&t), sizeof (float));
    }
    Eigen::Matrix3f R = orientation.toRotationMatrix ();
    for (int i = 0; i < 3; ++i)
      for (int j = 0; j < 3; ++j)
    {
      fpout.write (reinterpret_cast<const char*> (&R (i, j)),sizeof (float));
    }

    /////////////////////////////////////////////////////
    // Append those properties directly.               //
    // They are for perspective cameras so just put 0  //
    //                                                 //
    // property float focal                            //
    // property float scalex                           //
    // property float scaley                           //
    // property float centerx                          //
    // property float centery                          //
    // and later on                                    //
    // property float k1                               //
    // property float k2                               //
    /////////////////////////////////////////////////////

    const float zerof = 0;
    for (int i = 0; i < 5; ++i)
      fpout.write (reinterpret_cast<const char*> (&zerof), sizeof (float));

    // width and height
    int width = cloud.width;
    fpout.write (reinterpret_cast<const char*> (&width), sizeof (int));

    int height = cloud.height;
    fpout.write (reinterpret_cast<const char*> (&height), sizeof (int));

    for (int i = 0; i < 2; ++i)
      fpout.write (reinterpret_cast<const char*> (&zerof), sizeof (float));
  }
  else if (doRangeGrid)
  {
    // Write out range_grid
    for (size_t i=0; i < nr_points; ++i)
    {
      pcl::io::ply::uint8 listlen;

      if (rangegrid[i] >= 0)
      {
        listlen = 1;
        fpout.write (reinterpret_cast<const char*> (&listlen), sizeof (pcl::io::ply::uint8));
        fpout.write (reinterpret_cast<const char*> (&rangegrid[i]), sizeof (pcl::io::ply::int32));
      }
      else
      {
        listlen = 0;
        fpout.write (reinterpret_cast<const char*> (&listlen), sizeof (pcl::io::ply::uint8));
      }
    }
  }

  // Close file
  fpout.close ();
  return (0);
}

////////////////////////////////////////////////////////////////////////////////////////
int
pcl::io::savePLYFile (const std::string &file_name, const pcl::PolygonMesh &mesh, unsigned precision)
{
  if (mesh.cloud.data.empty ())
  {
    PCL_ERROR ("[pcl::io::savePLYFile] Input point cloud has no data!\n");
    return (-1);
  }
  // Open file
  std::ofstream fs;
  fs.precision (precision);
  fs.open (file_name.c_str ());
  if (!fs)
  {
    PCL_ERROR ("[pcl::io::savePLYFile] Error during opening (%s)!\n", file_name.c_str ());
    return (-1);
  }

  // number of points
  size_t nr_points  = mesh.cloud.width * mesh.cloud.height;
  size_t point_size = mesh.cloud.data.size () / nr_points;

  // number of faces
  size_t nr_faces = mesh.polygons.size ();

  // Write header
  fs << "ply";
  fs << "\nformat ascii 1.0";
  fs << "\ncomment PCL generated";
  // Vertices
  fs << "\nelement vertex "<< mesh.cloud.width * mesh.cloud.height;
  fs << "\nproperty float x"
        "\nproperty float y"
        "\nproperty float z";
  // Check if we have color on vertices
  int rgba_index = getFieldIndex (mesh.cloud, "rgba"),
  rgb_index = getFieldIndex (mesh.cloud, "rgb");
  if (rgba_index != -1)
  {
    fs << "\nproperty uchar red"
          "\nproperty uchar green"
          "\nproperty uchar blue"
          "\nproperty uchar alpha";
  }
  else if (rgb_index != -1)
  {
    fs << "\nproperty uchar red"
          "\nproperty uchar green"
          "\nproperty uchar blue";
  }
  // Check if we have normal on vertices
  int normal_x_index = getFieldIndex(mesh.cloud, "normal_x");
  int normal_y_index = getFieldIndex(mesh.cloud, "normal_y");
  int normal_z_index = getFieldIndex(mesh.cloud, "normal_z");
  if (normal_x_index != -1 && normal_y_index != -1 && normal_z_index != -1)
  {
      fs << "\nproperty float nx"
            "\nproperty float ny"
            "\nproperty float nz";
  }
  // Check if we have curvature on vertices
  int curvature_index = getFieldIndex(mesh.cloud, "curvature");
  if ( curvature_index != -1)
  {
      fs << "\nproperty float curvature";
  }
  // Faces
  fs << "\nelement face "<< nr_faces;
  fs << "\nproperty list uchar int vertex_indices";
  fs << "\nend_header\n";

  // Write down vertices
  for (size_t i = 0; i < nr_points; ++i)
  {
    int xyz = 0;
    for (size_t d = 0; d < mesh.cloud.fields.size (); ++d)
    {
      int count = mesh.cloud.fields[d].count;
      if (count == 0)
        count = 1;          // we simply cannot tolerate 0 counts (coming from older converter code)
      int c = 0;

      // adding vertex
      if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && (
          mesh.cloud.fields[d].name == "x" ||
          mesh.cloud.fields[d].name == "y" ||
          mesh.cloud.fields[d].name == "z"))
      {
        float value;
        memcpy (&value, &mesh.cloud.data[i * point_size + mesh.cloud.fields[d].offset + c * sizeof (float)], sizeof (float));
        fs << value;
        // if (++xyz == 3)
        //   break;
        ++xyz;
      }
      else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) &&
                (mesh.cloud.fields[d].name == "rgb"))

      {
        pcl::RGB color;
        memcpy (&color, &mesh.cloud.data[i * point_size + mesh.cloud.fields[rgb_index].offset + c * sizeof (float)], sizeof (RGB));
        fs << int (color.r) << " " << int (color.g) << " " << int (color.b);
      }
      else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::UINT32) &&
               (mesh.cloud.fields[d].name == "rgba"))
      {
        pcl::RGB color;
        memcpy (&color, &mesh.cloud.data[i * point_size + mesh.cloud.fields[rgba_index].offset + c * sizeof (uint32_t)], sizeof (RGB));
        fs << int (color.r) << " " << int (color.g) << " " << int (color.b) << " " << int (color.a);
      }
      else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && (
                mesh.cloud.fields[d].name == "normal_x" ||
                mesh.cloud.fields[d].name == "normal_y" ||
                mesh.cloud.fields[d].name == "normal_z"))
      {
        float value;
        memcpy (&value, &mesh.cloud.data[i * point_size + mesh.cloud.fields[d].offset + c * sizeof(float)], sizeof(float));
        fs << value;
      }
      else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && (
                mesh.cloud.fields[d].name == "curvature"))
      {
        float value;
        memcpy(&value, &mesh.cloud.data[i * point_size + mesh.cloud.fields[d].offset + c * sizeof(float)], sizeof(float));
        fs << value;
      }
      fs << " ";
    }
    if (xyz != 3)
    {
      PCL_ERROR ("[pcl::io::savePLYFile] Input point cloud has no XYZ data!\n");
      return (-2);
    }
    fs << '\n';
  }

  // Write down faces
  for (size_t i = 0; i < nr_faces; i++)
  {
    fs << mesh.polygons[i].vertices.size () << " ";
    size_t j = 0;
    for (j = 0; j < mesh.polygons[i].vertices.size () - 1; ++j)
      fs << mesh.polygons[i].vertices[j] << " ";
    fs << mesh.polygons[i].vertices[j] << '\n';
  }

  // Close file
  fs.close ();
  return (0);
}

////////////////////////////////////////////////////////////////////////////////////////
int
pcl::io::savePLYFileBinary (const std::string &file_name, const pcl::PolygonMesh &mesh)
{
  if (mesh.cloud.data.empty ())
  {
    PCL_ERROR ("[pcl::io::savePLYFile] Input point cloud has no data!\n");
    return (-1);
  }
  // Open file
  std::ofstream fs;
  fs.open (file_name.c_str ());
  if (!fs)
  {
    PCL_ERROR ("[pcl::io::savePLYFile] Error during opening (%s)!\n", file_name.c_str ());
    return (-1);
  }

  // number of points
  size_t nr_points  = mesh.cloud.width * mesh.cloud.height;
  size_t point_size = mesh.cloud.data.size () / nr_points;

  // number of faces
  size_t nr_faces = mesh.polygons.size ();

  // Write header
  fs << "ply";
  fs << "\nformat " << (mesh.cloud.is_bigendian ? "binary_big_endian" : "binary_little_endian") << " 1.0";
  fs << "\ncomment PCL generated";
  // Vertices
  fs << "\nelement vertex "<< mesh.cloud.width * mesh.cloud.height;
  fs << "\nproperty float x"
        "\nproperty float y"
        "\nproperty float z";
  // Check if we have color on vertices
  int rgba_index = getFieldIndex (mesh.cloud, "rgba"),
  rgb_index = getFieldIndex (mesh.cloud, "rgb");
  if (rgba_index != -1)
  {
    fs << "\nproperty uchar red"
          "\nproperty uchar green"
          "\nproperty uchar blue"
          "\nproperty uchar alpha";
  }
  else if (rgb_index != -1)
  {
    fs << "\nproperty uchar red"
          "\nproperty uchar green"
          "\nproperty uchar blue";
  }
  // Check if we have normal on vertices
  int normal_x_index = getFieldIndex(mesh.cloud, "normal_x");
  int normal_y_index = getFieldIndex(mesh.cloud, "normal_y");
  int normal_z_index = getFieldIndex(mesh.cloud, "normal_z");
  if (normal_x_index != -1 && normal_y_index != -1 && normal_z_index != -1)
  {
	  fs << "\nproperty float nx"
		  "\nproperty float ny"
		  "\nproperty float nz";
  }
  // Check if we have curvature on vertices
  int curvature_index = getFieldIndex(mesh.cloud, "curvature");
  if ( curvature_index != -1)
  {
	  fs << "\nproperty float curvature";
  }
  // Faces
  fs << "\nelement face "<< nr_faces;
  fs << "\nproperty list uchar int vertex_indices";
  fs << "\nend_header\n";

  // Close the file
  fs.close ();
  // Open file in binary appendable
  std::ofstream fpout (file_name.c_str (), std::ios::app | std::ios::binary);
  if (!fpout)
  {
    PCL_ERROR ("[pcl::io::writePLYFileBinary] Error during reopening (%s)!\n", file_name.c_str ());
    return (-1);
  }

  // Write down vertices
  for (size_t i = 0; i < nr_points; ++i)
  {
    int xyz = 0;
    for (size_t d = 0; d < mesh.cloud.fields.size (); ++d)
    {
      int count = mesh.cloud.fields[d].count;
      if (count == 0)
        count = 1;          // we simply cannot tolerate 0 counts (coming from older converter code)
      int c = 0;

      // adding vertex
      if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && (
          mesh.cloud.fields[d].name == "x" ||
          mesh.cloud.fields[d].name == "y" ||
          mesh.cloud.fields[d].name == "z"))
      {
        float value;
        memcpy (&value, &mesh.cloud.data[i * point_size + mesh.cloud.fields[d].offset + c * sizeof (float)], sizeof (float));
        fpout.write (reinterpret_cast<const char*> (&value), sizeof (float));
        // if (++xyz == 3)
        //   break;
        ++xyz;
      }
      else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) &&
                (mesh.cloud.fields[d].name == "rgb"))

      {
        pcl::RGB color;
        memcpy (&color, &mesh.cloud.data[i * point_size + mesh.cloud.fields[rgb_index].offset + c * sizeof (float)], sizeof (RGB));
        fpout.write (reinterpret_cast<const char*> (&color.r), sizeof (unsigned char));
        fpout.write (reinterpret_cast<const char*> (&color.g), sizeof (unsigned char));
        fpout.write (reinterpret_cast<const char*> (&color.b), sizeof (unsigned char));
      }
      else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::UINT32) &&
               (mesh.cloud.fields[d].name == "rgba"))
      {
        pcl::RGB color;
        memcpy (&color, &mesh.cloud.data[i * point_size + mesh.cloud.fields[rgba_index].offset + c * sizeof (uint32_t)], sizeof (RGB));
        fpout.write (reinterpret_cast<const char*> (&color.r), sizeof (unsigned char));
        fpout.write (reinterpret_cast<const char*> (&color.g), sizeof (unsigned char));
        fpout.write (reinterpret_cast<const char*> (&color.b), sizeof (unsigned char));
        fpout.write (reinterpret_cast<const char*> (&color.a), sizeof (unsigned char));
      }
      else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && (
               mesh.cloud.fields[d].name == "normal_x" ||
               mesh.cloud.fields[d].name == "normal_y" ||
               mesh.cloud.fields[d].name == "normal_z"))
      {
        float value;
        memcpy (&value, &mesh.cloud.data[i * point_size + mesh.cloud.fields[d].offset + c * sizeof (float)], sizeof (float));
        fpout.write (reinterpret_cast<const char*> (&value), sizeof (float));
      }
      else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) &&
               (mesh.cloud.fields[d].name == "curvature"))
      {
        float value;
        memcpy (&value, &mesh.cloud.data[i * point_size + mesh.cloud.fields[d].offset + c * sizeof (float)], sizeof (float));
        fpout.write (reinterpret_cast<const char*> (&value), sizeof (float));
      }
    }
    if (xyz != 3)
    {
      PCL_ERROR ("[pcl::io::savePLYFile] Input point cloud has no XYZ data!\n");
      return (-2);
    }
  }

  // Write down faces
  for (size_t i = 0; i < nr_faces; i++)
  {
    unsigned char value = static_cast<unsigned char> (mesh.polygons[i].vertices.size ());
    fpout.write (reinterpret_cast<const char*> (&value), sizeof (unsigned char));
    size_t j = 0;
    for (j = 0; j < mesh.polygons[i].vertices.size (); ++j)
    {
      //fs << mesh.polygons[i].vertices[j] << " ";
      int value = mesh.polygons[i].vertices[j];
      fpout.write (reinterpret_cast<const char*> (&value), sizeof (int));
    }
  }

  // Close file
  fs.close ();
  return (0);
}


text:
khal v0.9.0 released
====================

.. feed-entry::
        :date: 2017-01-24

This is probably the biggest release of khal to date, that is, the one with the
most changes since the last release. This changes are made up of a bunch of bug
fixes and enhancements.  Unfortunately, some of these break backwards
compatibility, many of which will make themselves noticeable, because your config
file will no longer be valid, consult the changelog_ or the documentation_.
Noticable is also, that command `agenda` has been renamed to `list`

Some of the larger changes include, among others, new configuration options on
how events are printed (thanks to first time contributor Taylor Money) and a new
look for ikhal's event-list column.

Have a look at the changelog_ for more complete list of new features (of which
there are many).

Get `khal v0.9.0`__ from this site, or from pypi_.

__ https://lostpackets.de/khal/downloads/khal-0.9.0.tar.gz

.. _pypi: https://pypi.python.org/pypi/khal/
.. _changelog: changelog.html#id2
.. _documentation: https://lostpackets.de/khal/

redpajama_set_name: RedPajamaGithub


text:
module Zencoder
  class Response

    attr_accessor :request, :code, :body, :raw_body, :raw_response

    def initialize(options={})
      options.each do |k, v|
        send("#{k}=", v) if respond_to?("#{k}=")
      end
    end

    def success?
      code.to_i > 199 && code.to_i < 300
    end

    def errors
      if body.is_a?(Hash)
        Array(body['errors']).compact
      else
        []
      end
    end

    def body_without_wrapper
      if body.is_a?(Hash) && body['api_response']
        body['api_response']
      else
        body
      end
    end

  end
end


text:
<?php
/**
 * Fichier application/helpers/outils_helper.php
 *
 * Contient divers fonctions utilitaires utilisables dans toute l'application code igniter,
 * à condition de charger l'helper avec la ligne :
 * $this->load->helper('outils');
 */

/**
 * Charge le gabarit standard de l'interface + la vue demandée
 *
 * @param type $obj
 * @param type $data
 * @param type $vue
 */
function modLoad($obj, $data, $vue)
{
    // Le paramètre objet doit être une instance d'une classe
    if(!is_object($obj))
    {
        die("Objet corrompu !");
    }

    $obj->load->view('v_entete', $data);

    // Charge le sommaire selon s'il s'agit d'un comptable ou d'un visiteur
    if(get_class($obj)=="Comptable")
    {
        $obj->load->view('v_sommaire_c', $data);
    }
    else if(get_class($obj)=="Visiteur")
    {
        $obj->load->view("v_sommaire", $data);
    }

    // On peut charger une ou plusieurs vues
    if(!is_array($vue))
    {
        $obj->load->view($vue, $data);
    }
    else
    {
        foreach($vue as $uneVue)
        {
            $obj->load->view($uneVue, $data);
        }
    }

    $obj->load->view('v_pied');
}

/**
 * Formate une clef année mois de type AAAAMM, pour enregistrement dans la BDD, à partir de la date du jour
 *
 * @param string : $date date("d/m/Y")
 * @return string : la clef au format AAAAMM
 */
function getMois($date)
{
    // Crée une liste pour contenir les 3 parties de la date
    @list($jour,$mois,$annee) = explode('/',$date);
    // Traite les mois à un seul caractère en leur rajoutant un zéro
    if(strlen($mois) == 1)
    {
        $mois = "0".$mois;
    }
    return $annee.$mois;
}

/**
 * Transforme un mois au format chiffre MM en sa version en lettre
 *
 * @param string : $mois
 * @return string : la version en lettre du $mois
 */
function moisChiffresVersLettres($mois)
{
    $ret = "";
    if(estEntierPositif($mois) && $mois < 13 && $mois > 0)
    {
        switch($mois)
        {
            case 1 : $ret = "Janvier" ; break ;
            case 2 : $ret = "Février" ; break ;
            case 3 : $ret = "Mars" ; break ;
            case 4 : $ret = "Avril" ; break ;
            case 5 : $ret = "Mai" ; break ;
            case 6 : $ret = "Juin" ; break ;
            case 7 : $ret = "Juillet" ; break ;
            case 8 : $ret = "Août" ; break ;
            case 9 : $ret = "Septembre" ; break ;
            case 10 : $ret = "Octobre" ; break ;
            case 11 : $ret = "Novembre" ; break ;
            case 12 : $ret = "Décembre" ; break ;
        }
    }
    return $ret ;
}

/**
 * Transforme une date au format français jj/mm/aaaa vers le format anglais aaaa-mm-jj
 *
 * @param string : $madate au format  jj/mm/aaaa
 * @return string : la date au format anglais aaaa-mm-jj
*/
function dateFrancaisVersAnglais($maDate)
{
    // Crée une liste pour contenir les 3 parties de la date
    @list($jour,$mois,$annee) = explode('/',$maDate);
    // Retourne la date au format anglais (compatible mysql) AAAA-MM-JJ
    return date('Y-m-d',mktime(0,0,0,$mois,$jour,$annee));
}

/**
 * Transforme une date au format format anglais aaaa-mm-jj vers le format français jj/mm/aaaa
 *
 * @param string : $madate au format  aaaa-mm-jj
 * @return string : la date au format format français jj/mm/aaaa
*/
function dateAnglaisVersFrancais($maDate)
{
    // Crée une liste pour contenir les 3 parties de la date
    @list($annee,$mois,$jour)=explode('-',$maDate);
    // Reforme la date format JJ/MM/AAAA
    $date="$jour"."/".$mois."/".$annee;
    return $date;
}

/**
 * Vérifie qu'une variable est bien un entier positif
 *
 * @param integer : $valeur la valeur à vérifier
 * @return boolean : vrai ou faux selon si la valeur est un entier positif ou non
 */
function estEntierPositif($valeur)
{
    // Utilisation des expressions régulière pour vérifier que la variable,
    // traitée comme une chaîne, ne contienne que des caractère numériques
    return preg_match("/[^0-9]/", $valeur) == 0;
}

/**
 * Indique si un tableau de valeurs est constitué d'entiers positifs ou nuls
 *
 * @param array[string] : $tabEntiers : le tableau
 * @return boolean : vrai ou faux
*/
function estTableauEntiers($tabEntiers)
{
    $ok = true;
    foreach($tabEntiers as $unEntier)
    {
        // Parcours le tableau et vérifie que chaque élément est bien un entier positif
    	if(!estEntierPositif($unEntier))
        {
            $ok=false;
	}
    }
    return $ok;
}

/**
 * Vérifie si une date est inférieure d'un an à la date actuelle
 *
 * @param string : $dateTestee
 * @return boolean : vrai ou faux
*/
function estDateDepassee($dateTestee)
{
    // Récupére la date du jour
    $dateActuelle=date("d/m/Y");
    @list($jour,$mois,$annee) = explode('/',$dateActuelle);
    // Enlève un an et reforme la date
    $annee--;
    $AnPasse = $annee.$mois.$jour;
    // Compare les deux dates
    @list($jourTeste,$moisTeste,$anneeTeste) = explode('/',$dateTestee);
    return ($anneeTeste.$moisTeste.$jourTeste < $AnPasse);
}

/**
 * Vérifie la validité du format d'une date française jj/mm/aaaa d'une chaine de caractère
 *
 * @param string : $date
 * @return boolean : vrai ou faux
*/
function estDateValide($date)
{
    // Sépare la date avec le séparateur '/' parties
    $tabDate = explode('/',$date);
    $dateOK = true;
    // S'il n'y a pas 3 parties => non valide
    if (count($tabDate) != 3)
    {
        $dateOK = false;
    }
    else
    {
        // Si les trois parties de la date ne sont pas tous des entiers => non valide
        if (!estTableauEntiers($tabDate))
        {
            $dateOK = false;
        }
        else
        {
            if (!checkdate($tabDate[1], $tabDate[0], $tabDate[2]))
            {
                $dateOK = false;
            }
        }
    }
    return $dateOK;
}

/**
 * Vérifie que le tableau de frais ne contient que des valeurs numériques
 *
 * @param array[?] : $lesFrais
 * @return boolean : vrai ou faux
*/
function lesQteFraisValides($lesFrais)
{
    return estTableauEntiers($lesFrais);
}

/**
 * Vérifie la validité des trois arguments : la date, le libellé du frais et le montant
 * des message d'erreurs sont ajoutés au tableau des erreurs
 * @param string : $dateFrais
 * @param string : $libelle
 * @param float : $montant
 */
function valideInfosFrais($dateFrais,$libelle,$montant)
{
    $noError = true ;
    if($dateFrais=="")
    {
	$noError = false ;
    }
    else
    {
	if(!estDatevalide($dateFrais))
        {
            $noError = false ;
	}
        else
        {
            if(estDateDepassee($dateFrais))
            {
		$noError = false ;
            }
	}
    }
    if($libelle == "")
    {
        $noError = false ;
    }
    if($montant == "")
    {
        $noError = false ;
    }
    else
    {
        if( !is_numeric($montant) )
        {
            $noError = false ;
	}
    }

    return $noError ;
}
?>


text:
//
//  NSFileManager_Extensions.m
//  TouchCode
//
//  Created by Jonathan Wight on 11/13/08.
//  Copyright 2008 toxicsoftware.com. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person
//  obtaining a copy of this software and associated documentation
//  files (the "Software"), to deal in the Software without
//  restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following
//  conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//  OTHER DEALINGS IN THE SOFTWARE.
//

#import "NSFileManager_Extensions.h"

#if TARGET_OS_IPHONE
#import <MobileCoreServices/MobileCoreServices.h>
#endif /* TARGET_OS_IPHONE */

@implementation NSFileManager (NSFileManager_Extensions)

+ (NSFileManager *)fileManager;
    {
    // TODO One per thread!
    return([[[NSFileManager alloc] init] autorelease]);
    }

- (NSString *)mimeTypeForPath:(NSString *)inPath
{

NSString *thePathExtension = [inPath pathExtension];
if ([thePathExtension isEqualToString:@"html"])
	{
	return(@"text/html");
	}
else if ([thePathExtension isEqualToString:@"png"])
	{
	return(@"image/png");
	}
else if ([thePathExtension isEqualToString:@"css"])
	{
	return(@"text/css");
	}
else if ([thePathExtension isEqualToString:@"jpg"])
	{
	return(@"image/jpeg");
	}
else if ([thePathExtension isEqualToString:@"gif"])
	{
	return(@"image/gif");
	}
else if ([thePathExtension isEqualToString:@"js"])
	{
	return(@"text/javascript");
	}
else if ([thePathExtension isEqualToString:@"rtf"])
	{
	return(@"application/rtf");
	}
return(@"application/octet-stream");
}

- (NSString *)applicationSupportFolder
    {
    // TODO rewrite with URLForDirectory.
    NSArray *thePaths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
    NSString *theBasePath = ([thePaths count] > 0) ? [thePaths objectAtIndex:0] : NSTemporaryDirectory();

    NSString *theBundleName = [[[[NSBundle mainBundle] bundlePath] lastPathComponent] stringByDeletingPathExtension];
    NSString *theApplicationSupportFolder = [theBasePath stringByAppendingPathComponent:theBundleName];

    if ([self fileExistsAtPath:theApplicationSupportFolder] == NO)
        {
        NSError *theError = NULL;
        // TODO possible race condition
        if ([self createDirectoryAtPath:theApplicationSupportFolder withIntermediateDirectories:YES attributes:NULL error:&theError] == NO)
            return(NULL);
        }

    return(theApplicationSupportFolder);
    }

@end


text:
import json
import lib.common.web as webutil
import lib.common.slack as slackutil
import lib.rank as rank
import re
import time
from lib.data import games as game_data
from lib.data import players as player_data

def handle(command_text):
    command_text = trim_extra_whitespace(command_text)

    result_components = parse_results(command_text)
    race_count = parse_race_count(result_components[0])

    scores = []

    for i in range(1, len(result_components)):
        player_score = {
            'player_id': re.sub('[<@]', '', result_components[i].split(' ')[1].split('|')[0]),
            'score': int(result_components[i].split(' ')[2]),
            'average': round(float(result_components[i].split(' ')[2]) / race_count, 2)
        }

        scores.append(player_score)

    game = {
        'games': race_count,
        'datetime': int(time.time()) * 1000,
        'scores': scores
    }

    last_game = game_data.get_last_game()
    matrix_curr = last_game['skill_matrix']
    matrix_updated = rank.update_rank_matrix_with_game(matrix_curr, game)
    game['skill_matrix'] = matrix_updated

    game_data.add_game(game)

    scores = sorted(scores, key=lambda k: k['average'], reverse=True)

    response_text = 'A game of *' + str(game.get('games')) + '* races was played! Average scores:'
    for score in scores:
        player_cursor = player_data.get_player(score['player_id']) or {}
        response_text += '\n' + player_cursor.get('name', '<Unknown>')
        response_text += ': ' + str(score['average'])
    response_text += '\n-------------------'
    response_text += '\nCheck out the updated rankings at http://kartskills.com!'

    slack_body = slackutil.in_channel_response(response_text)
    return webutil.respond_success_json(json.dumps(slack_body))

def trim_extra_whitespace(text):
    return ' '.join(text.split())

def parse_results(text):
    return text.split(',')

def parse_race_count(text):
    return int(text.split(' ')[1])


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cart_payment_item_container"
    style="@style/CardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="@dimen/margin_5dp"
    >
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <com.vinsol.spree.views.CustomFontTextView
            android:id="@+id/cart_payment_item_header_txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Payment Info"
            custom:typeface="roboto_medium.ttf"
            android:layout_margin="@dimen/margin_10dp"
            android:layout_centerHorizontal="true"
            android:textSize="@dimen/text_size_18sp"
            >
        </com.vinsol.spree.views.CustomFontTextView>

        <com.vinsol.spree.views.CustomFontTextView
            android:id="@+id/cart_payment_item_card_txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="XXXX-XXXX-XXXX-4567"
            android:layout_below="@id/cart_payment_item_header_txt"
            android:layout_margin="@dimen/margin_10dp"
            custom:typeface="roboto_light.ttf"
            android:layout_gravity="top"
            android:textSize="@dimen/text_size_15sp"
            >
        </com.vinsol.spree.views.CustomFontTextView>

        <com.vinsol.spree.views.CustomFontTextView
            android:id="@+id/cart_payment_item_card_type_txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="VISA"
            android:layout_below="@id/cart_payment_item_card_txt"
            android:layout_margin="@dimen/margin_10dp"
            custom:typeface="roboto_light.ttf"
            android:layout_gravity="top"
            android:textSize="@dimen/text_size_15sp"
            >
        </com.vinsol.spree.views.CustomFontTextView>

        <RelativeLayout
            android:id="@+id/cart_payment_item_edit_img_container"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:visibility="gone"
            >

            <ImageView
                android:id="@+id/cart_payment_item_edit_img"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin_10dp"
                android:src="@drawable/address_edit_icon"
                >
            </ImageView>
        </RelativeLayout>
    </RelativeLayout>
</android.support.v7.widget.CardView>


text:
cask 'musicbrainz-picard' do
  version '2.1.3'
  sha256 '91d0f06b9efdf2d23830068e329115ad5133038ea2586c1091c581d09d7bfec8'

  # musicbrainz.osuosl.org/pub/ was verified as official when first introduced to the cask
  url "https://musicbrainz.osuosl.org/pub/musicbrainz/picard/MusicBrainz.Picard.#{version}.dmg"
  appcast 'https://picard.musicbrainz.org/downloads/'
  name 'MusicBrainz Picard'
  homepage 'https://picard.musicbrainz.org/'

  depends_on macos: '>= :yosemite'

  app 'MusicBrainz Picard.app'

  zap trash: [
               '~/.config/MusicBrainz',
               '~/Library/Caches/MusicBrainz',
               '~/Library/Preferences/org.musicbrainz.picard.plist',
               '~/Library/Saved Application State/org.musicbrainz.picard.savedState',
             ]
end


text:
import time
import RPi.GPIO as GPIO
from subprocess import call

GPIO.setmode(GPIO.BCM)

BUTTON_0_PIN = 20
BUTTON_1_PIN = 12
BUTTON_2_PIN = 13
BUTTON_3_PIN = 19
BUTTON_4_PIN = 26
PS_SWITCH_PIN = 6

GPIO.setup(BUTTON_0_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(BUTTON_1_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(BUTTON_2_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(BUTTON_3_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(BUTTON_4_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(PS_SWITCH_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)

def activateScreen(pin):
	if pin == BUTTON_0_PIN:
		call(["bash", "/home/pi/display/set_view_0.sh"])
	elif pin == BUTTON_1_PIN:
		call(["bash", "/home/pi/display/set_view_1.sh"])
	elif pin == BUTTON_2_PIN:
		call(["bash", "/home/pi/display/set_view_2.sh"])
	elif pin == BUTTON_3_PIN:
		call(["bash", "/home/pi/display/set_view_3.sh"])
	elif pin == BUTTON_4_PIN:
		call(["bash", "/home/pi/display/set_view_4.sh"])

def setPowersave(pin):
	if GPIO.input(pin):
		print("Gonna enter powersave mode")
	else:
		print("Gonna exit powersave mode")

GPIO.add_event_detect(BUTTON_0_PIN, GPIO.FALLING, callback=activateScreen, bouncetime=300)
GPIO.add_event_detect(BUTTON_1_PIN, GPIO.FALLING, callback=activateScreen, bouncetime=300)
GPIO.add_event_detect(BUTTON_2_PIN, GPIO.FALLING, callback=activateScreen, bouncetime=300)
GPIO.add_event_detect(BUTTON_3_PIN, GPIO.FALLING, callback=activateScreen, bouncetime=300)
GPIO.add_event_detect(BUTTON_4_PIN, GPIO.FALLING, callback=activateScreen, bouncetime=300)

GPIO.add_event_detect(PS_SWITCH_PIN, GPIO.BOTH, callback=setPowersave, bouncetime=300)

try:
	while True:
		time.sleep(1)
except:# KeyboardException:
	print ("Got a ctrl-c")
finally:
	print("Cleaning up")
	GPIO.cleanup()


text:
<title>GLGE</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">

<canvas id="canvas" width="900"
height="500"></canvas>

Powered By GLGE


text:
//
//  Copyright 2014 Gustavo J Knuppe (https://github.com/knuppe)
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//
//   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//   - May you do good and not evil.                                         -
//   - May you find forgiveness for yourself and forgive others.             -
//   - May you share freely, never taking more than you give.                -
//   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

using System;
using System.Globalization;
using System.Text;

namespace SharpNL.ML.Model {
    /// <summary>
    /// A maxent event representation which we can use to sort based on the predicates indexes contained in the events.
    /// </summary>
    public class ComparableEvent : IComparable<ComparableEvent> {
        public int outcome;
        public int[] predIndexes;
        public int seen = 1; // the number of times this event has been seen.

        public float[] values;

        public ComparableEvent(int oc, int[] pids) :this(oc, pids, null) { }

        public ComparableEvent(int oc, int[] pids, float[] values) {
            outcome = oc;
            if (values == null) {
                Array.Sort(pids);
            } else {
                Sort(pids, values);
            }
            this.values = values; // needs to be sorted like pids
            predIndexes = pids;
        }

        #region . CompareTo .
        /// <summary>
        /// Compares the current object with another object of the same type.
        /// </summary>
        /// <returns>
        /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public int CompareTo(ComparableEvent other) {
            if (outcome < other.outcome)
                return -1;

            if (outcome > other.outcome)
                return 1;

            var smallerLength = (predIndexes.Length > other.predIndexes.Length ? other.predIndexes.Length
                : predIndexes.Length);

            for (int i = 0; i < smallerLength; i++) {
                if (predIndexes[i] < other.predIndexes[i])
                    return -1;

                if (predIndexes[i] > other.predIndexes[i])
                    return 1;

                if (values != null && other.values != null) {
                    if (values[i] < other.values[i])
                        return -1;
                    if (values[i] > other.values[i])
                        return 1;
                } else if (values != null) {
                    if (values[i] < 1)
                        return -1;
                    if (values[i] > 1)
                        return 1;
                } else if (other.values != null) {
                    if (1 < other.values[i])
                        return -1;
                    if (1 > other.values[i])
                        return 1;
                }
            }

            if (predIndexes.Length < other.predIndexes.Length)
                return -1;

            if (predIndexes.Length > other.predIndexes.Length)
                return 1;

            return 0;
        }
        #endregion

        #region . Sort .
        private static void Sort(int[] pids, float[] values) {
            for (int mi = 0; mi < pids.Length; mi++) {
                int min = mi;
                for (int pi = mi + 1; pi < pids.Length; pi++) {
                    if (pids[min] > pids[pi]) {
                        min = pi;
                    }
                }
                int pid = pids[mi];
                pids[mi] = pids[min];
                pids[min] = pid;
                float val = values[mi];
                values[mi] = values[min];
                values[min] = val;
            }
        }
        #endregion

        #region . ToString .
        /// <summary>
        /// Returns a string that represents the current event.
        /// </summary>
        /// <returns>
        /// A string that represents the current event.
        /// </returns>
        public override string ToString() {
            var sb = new StringBuilder();
            sb.Append(outcome.ToString(CultureInfo.InvariantCulture)).Append(":");

            for (int i = 0; i < predIndexes.Length; i++) {
                sb.Append(" ").Append(predIndexes[i]);
                if (values != null) {
                    sb.Append("=").Append(values[i]);
                }
            }
            return sb.ToString();
        }
        #endregion

    }
}


text:
<?php

namespace MakerLabs\PagerBundle\Test;

use MakerLabs\PagerBundle\Pager;

/**
 *
 * @author Marcin Butlak <contact@maker-labs.com>
 */
class PagerTest extends \PHPUnit_Framework_TestCase
{
    /**
     *
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $adapter;
    /**
     *
     * @var Pager
     */
    private $pager;

    protected function setUp()
    {
        $this->adapter = $this->getMock('MakerLabs\PagerBundle\Adapter\PagerAdapterInterface');

        $this->adapter->expects($this->any())
                ->method('count')
                ->will($this->returnValue(100));

        $this->pager = new Pager($this->adapter);
    }

    public function testConstructor()
    {
        $pager = new Pager($this->adapter, array('page' => 2, 'limit' => 30));

        $this->assertEquals(2, $pager->getPage());

        $this->assertEquals(30, $pager->getLimit());
    }

    public function testNoResults()
    {
        $adapter = $this->getMock('MakerLabs\PagerBundle\Adapter\PagerAdapterInterface');

        $adapter->expects($this->any())
                ->method('count')
                ->will($this->returnValue(0));

        $pager = new Pager($adapter);

        $this->assertEquals(1, $pager->getLastPage());

        $this->assertEquals(false, $pager->hasResults());
    }

    public function testDefaults()
    {
        $this->assertEquals(1, $this->pager->getPage());

        $this->assertEquals(20, $this->pager->getLimit());

        $this->assertEquals(1, $this->pager->getFirstPage());

        $this->assertEquals(true, $this->pager->isFirstPage());

        $this->assertEquals(5, $this->pager->getLastPage());

        $this->assertEquals(false, $this->pager->isLastPage());

        $this->assertEquals(2, $this->pager->getNextPage());

        $this->assertEquals(1, $this->pager->getPreviousPage());

        $this->assertEquals(true, $this->pager->isPaginable());
    }

    public function testIsLastPage()
    {
        $this->pager->setPage(5);

        $this->assertEquals(true, $this->pager->isLastPage());
    }

    public function testNotLastPage()
    {
        $this->pager->setPage(2);

        $this->assertEquals(false, $this->pager->isLastPage());
    }

    public function testNotFirstPage()
    {
        $this->pager->setPage(5);

        $this->assertEquals(false, $this->pager->isFirstPage());
    }

    public function testOutOfRangeLimit()
    {
        $this->pager->setPage(200);

        $this->assertEquals(5, $this->pager->getPage());

        $this->pager->setPage(-100);

        $this->assertEquals(1, $this->pager->getPage());

        $this->pager->setLimit(-100);

        $this->assertEquals(1, $this->pager->getLimit());
    }

    public function testResults()
    {
        $this->assertEquals(true, $this->pager->hasResults());

        $this->adapter->expects($this->any())
                ->method('getResults')
                ->with($this->equalTo(40), $this->equalTo(40));

        $this->pager->setPage(2)->setLimit(40);

        $this->pager->getResults();
    }

    public function testIsNotPaginable()
    {
        $this->pager->setLimit(100);

        $this->assertEquals(false, $this->pager->isPaginable());
    }
}