<commit_before>
/* ========================================

   * File Name : A.cpp

   * Creation Date : 12-06-2015

   * Last Modified : Sat 13 Jun 2015 04:29:09 PM CEST

   * Created By : Karel Ha <mathemage@gmail.com>

   * URL : http://codeforces.com/contest/551/problem/A

   * Points Gained (in case of online contest) : 0/500 (WA)

   ==========================================*/

#include <bits/stdc++.h>

using namespace std;

#define REP(I,N)   FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A)     (A).begin(), (A).end()
template <typename T>
string NumberToString ( T Number ) {
  ostringstream ss;
  ss << Number;
  return ss.str();
}

#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
  vector<string> v;
  stringstream ss(s);
  string x;
  while (getline(ss, x, c))
    v.emplace_back(x);
  return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
  cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
  err(++it, args...);
}

int main() {
  int n;
  cin >> n;

  vector<int> k(2015, 0);
  vector<int> a(n);
  REP(i,n) {
    cin >> a[i];
    k[a[i]]++;
  }

  int ac = 0;
  FOR(i, 2000, 0) {
    int l = k[i];
    k[i] = 1 + ac;
    ac += l;
  }

  for (auto & x : a) {
    cout << k[x] << " ";
  }
  return 0;
}
<commit_msg>Correct Codeforces #307, Div 2, Problem A<commit_after>
/* ========================================

   * File Name : A.cpp

   * Creation Date : 12-06-2015

   * Last Modified : Sun 14 Jun 2015 12:36:16 PM CEST

   * Created By : Karel Ha <mathemage@gmail.com>

   * URL : http://codeforces.com/contest/551/problem/A

   * Points Gained (in case of online contest) : 0/500 (WA)

   ==========================================*/

#include <bits/stdc++.h>

using namespace std;

#define REP(I,N)   FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A)     (A).begin(), (A).end()
template <typename T>
string NumberToString ( T Number ) {
  ostringstream ss;
  ss << Number;
  return ss.str();
}

#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
  vector<string> v;
  stringstream ss(s);
  string x;
  while (getline(ss, x, c))
    v.emplace_back(x);
  return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
  cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
  err(++it, args...);
}

int main() {
  int n;
  cin >> n;

  vector<int> k(2015, 0);
  vector<int> a(n);
  REP(i,n) {
    cin >> a[i];
    k[a[i]]++;
  }

  int ac = 0;
  FOR(i, 2001, 0) {
    int l = k[i];
    k[i] = 1 + ac;
    ac += l;
  }

  for (auto & x : a) {
    cout << k[x] << " ";
  }
  return 0;
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The Descent map loader
//
// NAME         : Hog
// PURPOSE      : Providing a decoder and wrapper for the Descent .HOG format.
// COPYRIGHT    : (c) 2011 Sean Donnellan. All Rights Reserved.
// AUTHORS      : Sean Donnellan (darkdonno@gmail.com)
// DESCRIPTION  : A decoder for the HOG file format that is used by Parallax
//                Software in the computer game, Descent.
//
//                The file format is as follows:
//
//                - Magic number which is 3 bytes and corresponding to the
//                  string "DHF"

//                - A series of files which are preceded by a short header,
//                  which describes the name of the file and the numer of bytes.
//
//                 | "DHF" - 3 bytes
//                 |---------------- Start of the first file
//                 | filename - 13 bytes
//                 | size - 4 bytes
//                 | data - the size of this part is by the size before it.
//                 |---------------- The next header/file comes straight after.
//                 | filename - 13 bytes
//                 | size - 4 bytes
//                 | data - the size of this part is by the size before it.
//
//===----------------------------------------------------------------------===//

/////
// Developer notes
// Different file formats: http://www.descent2.com/ddn/kb/files/
//
/////

#include "cube.hpp"
#include "hogreader.hpp"
#include "hogiterator.hpp"
#include "rdl.hpp"

#include <fstream>
#include <memory>
#include <iterator>
#include <utility>
#include <vector>

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef _MSC_VER
static_assert(sizeof(uint8_t) == 1,
              "The size of uint8_t is incorrect it must be 1-byte");
static_assert(sizeof(uint32_t) == 4,
              "The size of uint32_t is incorrect it must be 4-bytes");
static_assert(sizeof(uint8_t) == sizeof(char),
              "The size of a char must be 1-byte");
#endif

// The 3-byte MAGIC number at the start of the file format used to identifiy the
// file as being a Descent HOG file.
static uint8_t magic[3] = { 'D', 'H', 'F' };

HogReader::iterator HogReader::begin()
{
  // Sync back up to the start just after the magic number.
  if (IsValid())
  {
    fseek(myFile, sizeof(magic), SEEK_SET);
    if (fread(&myChildFile.name, 13, 1, myFile) != 1) HogReaderIterator();
    if (fread(&myChildFile.size, 4, 1, myFile) != 1) HogReaderIterator();
  }

  return HogReaderIterator(*this);
}

HogReader::iterator HogReader::end()
{
  return HogReaderIterator();
}

HogReader::HogReader(const char* filename) : myFile(nullptr), hasReadFile(false)
{
  myFile = fopen(filename, "rb");
  myChildFile.name[0] = '\0';
  myChildFile.size = 0;
  if (!myFile) return;

  const size_t count = 1;
  if (fread(myHeader, sizeof(myHeader), count, myFile) != count)
  {
    myHeader[0] = '\0'; // Failed to load.
    return;
  }

  // Read in the header for the first file.
  if (IsValid())
  {
    if (fread(&myChildFile.name, 13, 1, myFile) != 1) return;
    if (fread(&myChildFile.size, 4, 1, myFile) != 1) return;
  }
}

HogReader::~HogReader()
{
  if (myFile) fclose(myFile);
}

bool HogReader::IsValid() const
{
  if (!myFile) return false;
  return memcmp(myHeader, magic, 3) == 0;
}

bool HogReader::NextFile()
{
  // Skip the current file.
  if (feof(myFile)) return false;

  if (!hasReadFile)
  {
    // The data for the current file has not been read so skip over the data
    // section
    // for the file.

    if (fseek(myFile, myChildFile.size, SEEK_CUR) != 0) return false;
  }

  // Read in the header for the next file.
  if (fread(&myChildFile.name, 13, 1, myFile) != 1) return false;
  if (fread(&myChildFile.size, 4, 1, myFile) != 1) return false;

  hasReadFile = false; // We haven't read the next file yet.
  return true;
}

const char* HogReader::CurrentFileName() const
{
  return myChildFile.name;
}

unsigned int HogReader::CurrentFileSize() const
{
  return myChildFile.size;
}

std::vector<uint8_t> HogReader::CurrentFile()
{
  std::vector<uint8_t> fileData;

  // TODO: Allow this to seek-back and read it again.
  //
  // For now ensure the current file hasn't been read yet.
  assert(!hasReadFile);

  // Skip the current file.
  if (feof(myFile)) return fileData;

  const unsigned int size = CurrentFileSize(); // Size in bytes
  fileData.resize(size);

  if (fread(fileData.data(), size, 1, myFile) != 1)
  {
    fileData.clear();
  }
  else
  {
    hasReadFile = true;
  }

  return fileData;
}

#include <algorithm>
#include <iostream>
#include <string>

struct Quad
{
  size_t a;
  size_t b;
  size_t c;
  size_t d;
};

void Quads(const Cube& cube, std::vector<Quad>* quads)
{
  const uint16_t* const vertices = cube.vertices;

  // Vertices:
  // 0 - left, front, top
  // 1 - left, front, bottom
  // 2 - right, front, bottom
  // 3 - right, front, top
  // 4 - left, back, top
  // 5 - left, back, bottom
  // 6 - right, back, bottom
  // 7 - right, back, top

  // Neighbours:
  enum Neighbour
  {
    Left,
    Top,
    Right,
    Bottom,
    Back,
    Front
  };

  if (cube.neighbors[Left] == -1)
  {
    const Quad quad = { vertices[0], vertices[1], vertices[5], vertices[4] };
    quads->push_back(quad);
  }

  if (cube.neighbors[Top] == -1)
  {
    const Quad quad = { vertices[0], vertices[3], vertices[7], vertices[4] };
    quads->push_back(quad);
  }

  if (cube.neighbors[Right] == -1)
  {
    const Quad quad = { vertices[2], vertices[3], vertices[7], vertices[6] };
    quads->push_back(quad);
  }

  if (cube.neighbors[Bottom] == -1)
  {
    const Quad quad = { vertices[1], vertices[2], vertices[6], vertices[5] };
    quads->push_back(quad);
  }

  if (cube.neighbors[Front] == -1)
  {
    const Quad quad = { vertices[0], vertices[1], vertices[2], vertices[3] };
    quads->push_back(quad);
  }

  if (cube.neighbors[Back] == -1)
  {
    const Quad quad = { vertices[4], vertices[5], vertices[6], vertices[7] };
    quads->push_back(quad);
  }
}

std::vector<Quad> Quads(const std::vector<Cube>& Cubes)
{
  // Generate quads from the sides of the cubes.
  std::vector<Quad> quads;
  for (auto cube = Cubes.cbegin(), cubeEnd = Cubes.cend(); cube != cubeEnd;
       ++cube)
  {
    Quads(*cube, &quads);
  }
  return quads;
}

void ExportToPly(const RdlReader& Reader, const std::string& Name,
                 std::ostream& Output)
{
  const auto vertices = Reader.Vertices();
  const auto cubes = Reader.Cubes();
  const auto quads = Quads(cubes);

  const bool verticesOnly = false;

  Output << "ply" << std::endl;
  Output << "format ascii 1.0" << std::endl;
  Output << "comment An exported Descent 1 level (" << Name << ")" << std::endl;

  Output << "element vertex " << vertices.size() << std::endl;
  Output << "property float x" << std::endl;
  Output << "property float y" << std::endl;
  Output << "property float z" << std::endl;
  if (!verticesOnly)
  {
    Output << "element face " << quads.size() << std::endl;
    Output << "property list uchar int vertex_index" << std::endl;
  }
  Output << "end_header" << std::endl;

  std::for_each(vertices.begin(), vertices.end(), [&Output](Vertex v)
  { Output << v.x << " " << v.y << " " << v.z << std::endl; });

  if (!verticesOnly)
  {
    std::for_each(quads.begin(), quads.end(), [&Output](const Quad& quad)
    {
      Output << "4 " << quad.a << " " << quad.b << " " << quad.c << " "
             << quad.d << std::endl;
    });
  }
}

int main(int argc, char* argv[])
{
  if (argc != 2 && argc != 3)
  {
    printf("usage: %s [-d -l -p -a] filename\n", argv[0]);
    return 1;
  }

  enum Mode
  {
    ListAllFiles,
    ExportToPly,
    ExportAllToPly,
    Debug // Performs some other task during development.
  };

  Mode mode = ExportToPly;
  bool filenameIsFirst = true;

  // Command line option parsing
  if ((argv[1] && argv[1][0] == '-') ||
      (argc == 3 && argv[2] && argv[2][0] == '-'))
  {
    filenameIsFirst = (argv[1][0] != '-');
    const char option = filenameIsFirst ? argv[2][1] : argv[1][1];
    switch (option)
    {
    default:
      fprintf(stderr, "error unsupported option provided (%c)", option);
      return 1;
    case '\0':
      fprintf(stderr, "error option specifier - provided but no option");
      return 1;
    case 'd':
      mode = Debug;
      break;
    case 'l':
      mode = ListAllFiles;
      break;
    case 'p':
      mode = ExportToPly;
      break;
    case 'a':
      mode = ExportAllToPly;
      break;
    }

    if (argc == 2)
    {
      fprintf(stderr, "option provided but no filename");
      return 1;
    }
  }

  HogReader reader(filenameIsFirst ? argv[1] : argv[2]);
  if (!reader.IsValid())
  {
    fprintf(stderr, "error to open the hog file");
    return 1;
  }

  if (mode == ListAllFiles)
  {
    printf("%-13s Size\n", "Name");
    printf("=====================\n");
    std::for_each(reader.begin(), reader.end(),
                  [](HogReader::iterator::value_type item)
    { printf("%-13s %d\n", item.name, item.size); });
  }
  else if (mode == ExportToPly)
  {
    auto file = std::find_if(reader.begin(), reader.end(),
                             [](const HogReader::iterator::value_type & v)->bool
    { return strcmp(v.name, "level02.rdl") == 0; });

    const auto data = file.FileContents();
    RdlReader rdlReader(data);
    ::ExportToPly(rdlReader, std::string(file->name), std::cout);
  }
  else if (mode == ExportAllToPly)
  {
    for (auto file = reader.begin(), end = reader.end(); file != end; ++file)
    {
      const std::string name(file->name);
      if (name.length() < 4) continue;
      if (name.substr(name.length() - 4) != ".rdl") continue;

      const auto data = file.FileContents();
      RdlReader rdlReader(data);

      const std::string ply = name.substr(0, name.length() - 4) + ".ply";
      std::cout << "Writing out " << ply << std::endl;
      std::ofstream output(ply.c_str());
      ::ExportToPly(rdlReader, name, output);
    }
  }
  else
  {
    // Iterate over the file list and list all the files which do not
    // end in the 'rdl' file extension.
    const std::string extentionRdl(".rdl");
    std::for_each(reader.begin(), reader.end(),
                  [&reader, &extentionRdl](HogReader::iterator::value_type n)
    {
      const std::string filename(n.name);
      if (!std::equal(extentionRdl.rbegin(), extentionRdl.rend(),
                      filename.rbegin()))
        return;

      printf("File: %s Size: %d\n", n.name, reader.CurrentFileSize());
      const auto data = reader.CurrentFile();
      RdlReader rdlReader(data);

      if (!rdlReader.IsValid()) return;

      // Print out the vertices.
      const auto vertices = rdlReader.Vertices();
      printf("Vertex count: %d\n", vertices.size());
      std::for_each(vertices.begin(), vertices.end(),
                    [](Vertex v)
                    { printf("%16f %16f %16f\n", v.x, v.y, v.z); });
    });
  }
  return 0;
}
<commit_msg>Added static cast from file size to long.<commit_after>//===----------------------------------------------------------------------===//
//
//                     The Descent map loader
//
// NAME         : Hog
// PURPOSE      : Providing a decoder and wrapper for the Descent .HOG format.
// COPYRIGHT    : (c) 2011 Sean Donnellan. All Rights Reserved.
// AUTHORS      : Sean Donnellan (darkdonno@gmail.com)
// DESCRIPTION  : A decoder for the HOG file format that is used by Parallax
//                Software in the computer game, Descent.
//
//                The file format is as follows:
//
//                - Magic number which is 3 bytes and corresponding to the
//                  string "DHF"

//                - A series of files which are preceded by a short header,
//                  which describes the name of the file and the numer of bytes.
//
//                 | "DHF" - 3 bytes
//                 |---------------- Start of the first file
//                 | filename - 13 bytes
//                 | size - 4 bytes
//                 | data - the size of this part is by the size before it.
//                 |---------------- The next header/file comes straight after.
//                 | filename - 13 bytes
//                 | size - 4 bytes
//                 | data - the size of this part is by the size before it.
//
//===----------------------------------------------------------------------===//

/////
// Developer notes
// Different file formats: http://www.descent2.com/ddn/kb/files/
//
/////

#include "cube.hpp"
#include "hogreader.hpp"
#include "hogiterator.hpp"
#include "rdl.hpp"

#include <fstream>
#include <memory>
#include <iterator>
#include <utility>
#include <vector>

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef _MSC_VER
static_assert(sizeof(uint8_t) == 1,
              "The size of uint8_t is incorrect it must be 1-byte");
static_assert(sizeof(uint32_t) == 4,
              "The size of uint32_t is incorrect it must be 4-bytes");
static_assert(sizeof(uint8_t) == sizeof(char),
              "The size of a char must be 1-byte");
#endif

// The 3-byte MAGIC number at the start of the file format used to identifiy the
// file as being a Descent HOG file.
static uint8_t magic[3] = { 'D', 'H', 'F' };

HogReader::iterator HogReader::begin()
{
  // Sync back up to the start just after the magic number.
  if (IsValid())
  {
    fseek(myFile, sizeof(magic), SEEK_SET);
    if (fread(&myChildFile.name, 13, 1, myFile) != 1) HogReaderIterator();
    if (fread(&myChildFile.size, 4, 1, myFile) != 1) HogReaderIterator();
  }

  return HogReaderIterator(*this);
}

HogReader::iterator HogReader::end()
{
  return HogReaderIterator();
}

HogReader::HogReader(const char* filename) : myFile(nullptr), hasReadFile(false)
{
  myFile = fopen(filename, "rb");
  myChildFile.name[0] = '\0';
  myChildFile.size = 0;
  if (!myFile) return;

  const size_t count = 1;
  if (fread(myHeader, sizeof(myHeader), count, myFile) != count)
  {
    myHeader[0] = '\0'; // Failed to load.
    return;
  }

  // Read in the header for the first file.
  if (IsValid())
  {
    if (fread(&myChildFile.name, 13, 1, myFile) != 1) return;
    if (fread(&myChildFile.size, 4, 1, myFile) != 1) return;
  }
}

HogReader::~HogReader()
{
  if (myFile) fclose(myFile);
}

bool HogReader::IsValid() const
{
  if (!myFile) return false;
  return memcmp(myHeader, magic, 3) == 0;
}

bool HogReader::NextFile()
{
  // Skip the current file.
  if (feof(myFile)) return false;

  if (!hasReadFile)
  {
    // The data for the current file has not been read so skip over the data
    // section
    // for the file.

    if (fseek(myFile, static_cast<long>(myChildFile.size), SEEK_CUR) != 0)
    {
      return false;
    }
  }

  // Read in the header for the next file.
  if (fread(&myChildFile.name, 13, 1, myFile) != 1) return false;
  if (fread(&myChildFile.size, 4, 1, myFile) != 1) return false;

  hasReadFile = false; // We haven't read the next file yet.
  return true;
}

const char* HogReader::CurrentFileName() const
{
  return myChildFile.name;
}

unsigned int HogReader::CurrentFileSize() const
{
  return myChildFile.size;
}

std::vector<uint8_t> HogReader::CurrentFile()
{
  std::vector<uint8_t> fileData;

  // TODO: Allow this to seek-back and read it again.
  //
  // For now ensure the current file hasn't been read yet.
  assert(!hasReadFile);

  // Skip the current file.
  if (feof(myFile)) return fileData;

  const unsigned int size = CurrentFileSize(); // Size in bytes
  fileData.resize(size);

  if (fread(fileData.data(), size, 1, myFile) != 1)
  {
    fileData.clear();
  }
  else
  {
    hasReadFile = true;
  }

  return fileData;
}

#include <algorithm>
#include <iostream>
#include <string>

struct Quad
{
  size_t a;
  size_t b;
  size_t c;
  size_t d;
};

void Quads(const Cube& cube, std::vector<Quad>* quads)
{
  const uint16_t* const vertices = cube.vertices;

  // Vertices:
  // 0 - left, front, top
  // 1 - left, front, bottom
  // 2 - right, front, bottom
  // 3 - right, front, top
  // 4 - left, back, top
  // 5 - left, back, bottom
  // 6 - right, back, bottom
  // 7 - right, back, top

  // Neighbours:
  enum Neighbour
  {
    Left,
    Top,
    Right,
    Bottom,
    Back,
    Front
  };

  if (cube.neighbors[Left] == -1)
  {
    const Quad quad = { vertices[0], vertices[1], vertices[5], vertices[4] };
    quads->push_back(quad);
  }

  if (cube.neighbors[Top] == -1)
  {
    const Quad quad = { vertices[0], vertices[3], vertices[7], vertices[4] };
    quads->push_back(quad);
  }

  if (cube.neighbors[Right] == -1)
  {
    const Quad quad = { vertices[2], vertices[3], vertices[7], vertices[6] };
    quads->push_back(quad);
  }

  if (cube.neighbors[Bottom] == -1)
  {
    const Quad quad = { vertices[1], vertices[2], vertices[6], vertices[5] };
    quads->push_back(quad);
  }

  if (cube.neighbors[Front] == -1)
  {
    const Quad quad = { vertices[0], vertices[1], vertices[2], vertices[3] };
    quads->push_back(quad);
  }

  if (cube.neighbors[Back] == -1)
  {
    const Quad quad = { vertices[4], vertices[5], vertices[6], vertices[7] };
    quads->push_back(quad);
  }
}

std::vector<Quad> Quads(const std::vector<Cube>& Cubes)
{
  // Generate quads from the sides of the cubes.
  std::vector<Quad> quads;
  for (auto cube = Cubes.cbegin(), cubeEnd = Cubes.cend(); cube != cubeEnd;
       ++cube)
  {
    Quads(*cube, &quads);
  }
  return quads;
}

void ExportToPly(const RdlReader& Reader, const std::string& Name,
                 std::ostream& Output)
{
  const auto vertices = Reader.Vertices();
  const auto cubes = Reader.Cubes();
  const auto quads = Quads(cubes);

  const bool verticesOnly = false;

  Output << "ply" << std::endl;
  Output << "format ascii 1.0" << std::endl;
  Output << "comment An exported Descent 1 level (" << Name << ")" << std::endl;

  Output << "element vertex " << vertices.size() << std::endl;
  Output << "property float x" << std::endl;
  Output << "property float y" << std::endl;
  Output << "property float z" << std::endl;
  if (!verticesOnly)
  {
    Output << "element face " << quads.size() << std::endl;
    Output << "property list uchar int vertex_index" << std::endl;
  }
  Output << "end_header" << std::endl;

  std::for_each(vertices.begin(), vertices.end(), [&Output](Vertex v)
  { Output << v.x << " " << v.y << " " << v.z << std::endl; });

  if (!verticesOnly)
  {
    std::for_each(quads.begin(), quads.end(), [&Output](const Quad& quad)
    {
      Output << "4 " << quad.a << " " << quad.b << " " << quad.c << " "
             << quad.d << std::endl;
    });
  }
}

int main(int argc, char* argv[])
{
  if (argc != 2 && argc != 3)
  {
    printf("usage: %s [-d -l -p -a] filename\n", argv[0]);
    return 1;
  }

  enum Mode
  {
    ListAllFiles,
    ExportToPly,
    ExportAllToPly,
    Debug // Performs some other task during development.
  };

  Mode mode = ExportToPly;
  bool filenameIsFirst = true;

  // Command line option parsing
  if ((argv[1] && argv[1][0] == '-') ||
      (argc == 3 && argv[2] && argv[2][0] == '-'))
  {
    filenameIsFirst = (argv[1][0] != '-');
    const char option = filenameIsFirst ? argv[2][1] : argv[1][1];
    switch (option)
    {
    default:
      fprintf(stderr, "error unsupported option provided (%c)", option);
      return 1;
    case '\0':
      fprintf(stderr, "error option specifier - provided but no option");
      return 1;
    case 'd':
      mode = Debug;
      break;
    case 'l':
      mode = ListAllFiles;
      break;
    case 'p':
      mode = ExportToPly;
      break;
    case 'a':
      mode = ExportAllToPly;
      break;
    }

    if (argc == 2)
    {
      fprintf(stderr, "option provided but no filename");
      return 1;
    }
  }

  HogReader reader(filenameIsFirst ? argv[1] : argv[2]);
  if (!reader.IsValid())
  {
    fprintf(stderr, "error to open the hog file");
    return 1;
  }

  if (mode == ListAllFiles)
  {
    printf("%-13s Size\n", "Name");
    printf("=====================\n");
    std::for_each(reader.begin(), reader.end(),
                  [](HogReader::iterator::value_type item)
    { printf("%-13s %d\n", item.name, item.size); });
  }
  else if (mode == ExportToPly)
  {
    auto file = std::find_if(reader.begin(), reader.end(),
                             [](const HogReader::iterator::value_type & v)->bool
    { return strcmp(v.name, "level02.rdl") == 0; });

    const auto data = file.FileContents();
    RdlReader rdlReader(data);
    ::ExportToPly(rdlReader, std::string(file->name), std::cout);
  }
  else if (mode == ExportAllToPly)
  {
    for (auto file = reader.begin(), end = reader.end(); file != end; ++file)
    {
      const std::string name(file->name);
      if (name.length() < 4) continue;
      if (name.substr(name.length() - 4) != ".rdl") continue;

      const auto data = file.FileContents();
      RdlReader rdlReader(data);

      const std::string ply = name.substr(0, name.length() - 4) + ".ply";
      std::cout << "Writing out " << ply << std::endl;
      std::ofstream output(ply.c_str());
      ::ExportToPly(rdlReader, name, output);
    }
  }
  else
  {
    // Iterate over the file list and list all the files which do not
    // end in the 'rdl' file extension.
    const std::string extentionRdl(".rdl");
    std::for_each(reader.begin(), reader.end(),
                  [&reader, &extentionRdl](HogReader::iterator::value_type n)
    {
      const std::string filename(n.name);
      if (!std::equal(extentionRdl.rbegin(), extentionRdl.rend(),
                      filename.rbegin()))
        return;

      printf("File: %s Size: %d\n", n.name, reader.CurrentFileSize());
      const auto data = reader.CurrentFile();
      RdlReader rdlReader(data);

      if (!rdlReader.IsValid()) return;

      // Print out the vertices.
      const auto vertices = rdlReader.Vertices();
      printf("Vertex count: %d\n", vertices.size());
      std::for_each(vertices.begin(), vertices.end(),
                    [](Vertex v)
                    { printf("%16f %16f %16f\n", v.x, v.y, v.z); });
    });
  }
  return 0;
}
<|endoftext|>


<commit_before>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file		g_fileinputstream.cpp
* @version
* @brief
* @author   ylh
* @date     2014-07-11
* @note
*
*  1. 2014-07-11 ylh Created this file
*
*/

#include <g_sync.h>
#include <g_fileinputstream.h>

using namespace std;
using namespace GCommon;

FileInputStream::FileInputStream(std::shared_ptr<GFile> file)
	: m_file(file)
	, m_mtx(PTHREAD_MUTEX_NORMAL)
{
	if (m_file == NULL)
	{
		throw invalid_argument(EXCEPTION_DESCRIPTION("invalid_argument"));
	}
}

FileInputStream::FileInputStream(const std::string& filePath)
	: m_file((shared_ptr<GFile>(new GFile(filePath.c_str()))))
{
	if (m_file->open(G_OPEN_READ) == G_NO)
	{
		throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure"));
	}
}

FileInputStream::~FileInputStream()
{
}

GInt32 FileInputStream::available() throw(std::ios_base::failure)
{
	synchronized(m_mtx)
	{
		GInt64 current = m_file->tell();
		GInt64 end = m_file->seek(0, G_SEEK_END);
		GInt64 available = end - current;

		m_file->seek(current, G_SEEK_BEG);
	}

	return available;
}

void FileInputStream::close() throw(std::ios_base::failure)
{
	// m_file->close();
	// do nothing
}

GInt32 FileInputStream::read() throw(std::ios_base::failure, std::logic_error)
{
	GInt8 buffer[1] = {0};
	return  this->read(buffer, 1);
}

GInt32 FileInputStream::read(GInt8* buffer, GInt32 bufferLen, GInt32 offset, GInt32 len) throw(std::ios_base::failure, std::logic_error)
{
	GInt32 ret = -1;
	synchronized(m_mtx)
	{
		if (!buffer)
		{
			throw invalid_argument(EXCEPTION_DESCRIPTION("invalid_argument"));
		}
		else if (offset < 0 || len < 0 ||bufferLen < offset + len)
		{
			throw out_of_range(EXCEPTION_DESCRIPTION("out_of_range"));
		}
		else if (len == 0)
		{
			return 0;
		}

		ret = m_file->read(buffer + offset, len);
		if (ret < 0)
		{
			throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure"));
		}
		if (ret == 0)
		{
			ret = -1;
		}
	}
	return ret;
}

GInt64 FileInputStream::skip(GInt64 num) throw(std::ios_base::failure)
{
	synchronized(m_mtx)
	{
		if (num == 0)
		{
			return 0;
		}
		if (num  < 0)
		{
			throw out_of_range("");
		}

		// TODO: not complete
		if (m_file->seek(num, G_SEEK_CUR))
		{
			throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure"));
		}
	}
	return 0;
}

std::shared_ptr<GFile> FileInputStream::GetFile()
{
	return m_file;
}

<commit_msg>Update g_fileinputstream.cpp<commit_after>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file		g_fileinputstream.cpp
* @version
* @brief
* @author   ylh
* @date     2014-07-11
* @note
*
*  1. 2014-07-11 ylh Created this file
*
*/

#include <g_sync.h>
#include <g_fileinputstream.h>

using namespace std;
using namespace GCommon;

FileInputStream::FileInputStream(std::shared_ptr<GFile> file)
	: m_file(file)
	, m_mtx(PTHREAD_MUTEX_NORMAL)
{
	if (m_file == NULL)
	{
		throw invalid_argument(EXCEPTION_DESCRIPTION("invalid_argument"));
	}
}

FileInputStream::FileInputStream(const std::string& filePath)
	: m_file((shared_ptr<GFile>(new GFile(filePath.c_str()))))
{
	if (m_file->open(G_OPEN_READ) == G_NO)
	{
		throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure"));
	}
}

FileInputStream::~FileInputStream()
{
}

GInt32 FileInputStream::available() throw(std::ios_base::failure)
{
	synchronized(m_mtx)
	{
		GInt64 current = m_file->tell();
		GInt64 end = m_file->seek(0, G_SEEK_END);
		GInt64 available = end - current;

		m_file->seek(current, G_SEEK_BEG);
		return available;
	}
	return 0;
}

void FileInputStream::close() throw(std::ios_base::failure)
{
	// m_file->close();
	// do nothing
}

GInt32 FileInputStream::read() throw(std::ios_base::failure, std::logic_error)
{
	GInt8 buffer[1] = {0};
	return  this->read(buffer, 1);
}

GInt32 FileInputStream::read(GInt8* buffer, GInt32 bufferLen, GInt32 offset, GInt32 len) throw(std::ios_base::failure, std::logic_error)
{
	GInt32 ret = -1;
	synchronized(m_mtx)
	{
		if (!buffer)
		{
			throw invalid_argument(EXCEPTION_DESCRIPTION("invalid_argument"));
		}
		else if (offset < 0 || len < 0 ||bufferLen < offset + len)
		{
			throw out_of_range(EXCEPTION_DESCRIPTION("out_of_range"));
		}
		else if (len == 0)
		{
			return 0;
		}

		ret = m_file->read(buffer + offset, len);
		if (ret < 0)
		{
			throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure"));
		}
		if (ret == 0)
		{
			ret = -1;
		}
	}
	return ret;
}

GInt64 FileInputStream::skip(GInt64 num) throw(std::ios_base::failure)
{
	synchronized(m_mtx)
	{
		if (num == 0)
		{
			return 0;
		}
		if (num  < 0)
		{
			throw out_of_range("");
		}

		// TODO: not complete
		if (m_file->seek(num, G_SEEK_CUR))
		{
			throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure"));
		}
	}
	return 0;
}

std::shared_ptr<GFile> FileInputStream::GetFile()
{
	return m_file;
}

<|endoftext|>


<commit_before>#include "perf_event_prof.h"

static void *sample_handler_fn(void *args)
{
    perf_event_prof *pep = (perf_event_prof*)args;

    for(;;) {
        pep->read_all_samples();
    }
}

perf_event_prof::perf_event_prof()
{
    // Defaults
    ret = 0;
    mmap_pages = 8;
    sample_period = 10;
    pgsz = sysconf(_SC_PAGESIZE);
    mmap_size = (mmap_pages+1)*pgsz;
    pgmsk = mmap_pages*pgsz-1;

    // Setup
    memset(&pe, 0, sizeof(struct perf_event_attr));
    pe.type = PERF_TYPE_HARDWARE;
    pe.size = sizeof(struct perf_event_attr);
    pe.config = PERF_COUNT_HW_INSTRUCTIONS;
    pe.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TIME;
    pe.mmap = 1;
    pe.mmap_data = 1;
    pe.sample_period = sample_period;
    pe.disabled = 1;
    pe.exclude_kernel = 1;
    pe.exclude_hv = 1;

    // Calling pid, all cpus, single event group, no flags
    fd = syscall(__NR_perf_event_open, &pe,0,-1,-1,0);

    if (fd == -1) {
       fprintf(stderr, "Error opening leader %llx\n", pe.config);
       ready=0;
       return;
    }

    // Create mmap buffer for samples
    mmap_buf = (struct perf_event_mmap_page*)
        mmap(NULL, mmap_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

    if(mmap_buf == MAP_FAILED) {
       fprintf(stderr, "Error mmapping buffer\n");
       ready=0;
       return;
    }

    ready=1;
}

perf_event_prof::~perf_event_prof()
{
    munmap(mmap_buf,mmap_size);
    close(fd);
}

int perf_event_prof::init_sample_handler()
{
    return pthread_create(&sample_handler_thr,NULL,sample_handler_fn,(void*)this);
}

int perf_event_prof::begin_prof()
{
    ret = init_sample_handler();

    if(ret)
    {
        std::cerr << "Couldn't initialize sample handler thread, aborting!\n";
        std::cerr << std::endl;
        return ret;
    }

    ioctl(fd, PERF_EVENT_IOC_RESET, 0);
    ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);

    return ret;
}

void perf_event_prof::end_prof()
{
    pthread_cancel(sample_handler_thr);
    pthread_join(sample_handler_thr,NULL);

    read_all_samples(); // flush it out

    ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
    read(fd, &counter_value, sizeof(uint64_t));
}

int perf_event_prof::read_single_sample()
{
    int ret;
    uint64_t val;

    // READ IP
    ret = read_mmap_buffer((char*)&val,sizeof(uint64_t));
    if(ret)
        *os_err << "Can't read mmap buffer!\n" << std::endl;
    else
        *os_out << "IP : " << std::hex << val << std::endl;

    // READ TIMESTAMP
    ret |= read_mmap_buffer((char*)&val,sizeof(uint64_t));
    if(ret)
        *os_err << "Can't read mmap buffer!\n" << std::endl;
    else
        *os_out << "TS : " << std::hex << val << std::endl;

    return ret;
}

int perf_event_prof::read_all_samples()
{
    struct perf_event_header ehdr;
    int ret;

    for(;;) {
        ret = read_mmap_buffer((char*)&ehdr,sizeof(ehdr));
        if(ret)
            return 0; // no more samples

        switch(ehdr.type) {
            case PERF_RECORD_SAMPLE:
                read_single_sample();
                break;
            case PERF_RECORD_EXIT:
                process_exit_sample();
                break;
            case PERF_RECORD_LOST:
                process_lost_sample();
                break;
            case PERF_RECORD_THROTTLE:
                process_freq_sample();
                break;
            case PERF_RECORD_UNTHROTTLE:
                process_freq_sample();
                break;
            default:
                //printf("unknown sample type %d\n", ehdr.type);
                skip_mmap_buffer(sizeof(ehdr));
        }
    }
}

int perf_event_prof::read_mmap_buffer(char *out, size_t sz)
{
	char *data;
	unsigned long tail;
	size_t avail_sz, m, c;

	data = ((char *)mmap_buf)+sysconf(_SC_PAGESIZE);
	tail = mmap_buf->data_tail & pgmsk;
	avail_sz = mmap_buf->data_head - mmap_buf->data_tail;
	if (sz > avail_sz)
		return -1;
	c = pgmsk + 1 -  tail;
	m = c < sz ? c : sz;
	memcpy(out, data+tail, m);
	if ((sz - m) > 0)
		memcpy(out+m, data, sz - m);
	mmap_buf->data_tail += sz;

	return 0;
}

void perf_event_prof::skip_mmap_buffer(size_t sz)
{
    if ((mmap_buf->data_tail + sz) > mmap_buf->data_head)
        sz = mmap_buf->data_head - mmap_buf->data_tail;

    mmap_buf->data_tail += sz;
}

void perf_event_prof::process_lost_sample()
{
	struct { uint64_t id, lost; } lost;
	const char *str;

	ret = read_mmap_buffer((char*)&lost,sizeof(lost));

    /*
	if (ret)
		errx(1, "cannot read lost info");

	e = perf_id2event(fds, num_fds, lost.id);
	if (e == -1)
		str = "unknown lost event";
	else
		str = fds[e].name;

	fprintf(options.output_file,
		"<<<LOST %"PRIu64" SAMPLES FOR EVENT %s>>>\n", lost.lost, str);
    */
	lost_samples += lost.lost;
}

void perf_event_prof::process_exit_sample()
{
	struct { pid_t pid, ppid, tid, ptid; } grp;
	int ret;

	ret = read_mmap_buffer((char*)&grp, sizeof(grp));
    /*
	if (ret)
		errx(1, "cannot read exit info");

	fprintf(options.output_file,"[%d] exited\n", grp.pid);
    */
}

void perf_event_prof::process_freq_sample()
{
	struct { uint64_t time, id, stream_id; } thr;
	int ret;

	ret = read_mmap_buffer((char*)&thr, sizeof(thr));
    /*
	if (ret)
		errx(1, "cannot read throttling info");

	fprintf(options.output_file,"%s value=%"PRIu64" event ID=%"PRIu64"\n", mode ? "Throttled" : "Unthrottled", thr.id, thr.stream_id);
    */
}
void
do_werk()
{
    double v = 241209092.548394035;
    for(int i=0; i<512; i++)
        for(int j=0; j<512; j++)
            for(int k=0; k<512; k++)
                v = v*v;
    printf("v : %f\n",v);
}

int
main(int argc, char **argv)
{
    perf_event_prof mprof;
    mprof.set_outputstream(&std::cout);
    mprof.begin_prof();
    do_werk();
    mprof.end_prof();
}
<commit_msg>exit nicely<commit_after>#include "perf_event_prof.h"

static void *sample_handler_fn(void *args)
{
    perf_event_prof *pep = (perf_event_prof*)args;

    for(;;) {
        pep->read_all_samples();
    }
}

perf_event_prof::perf_event_prof()
{
    // Defaults
    ret = 0;
    mmap_pages = 8;
    sample_period = 10;
    pgsz = sysconf(_SC_PAGESIZE);
    mmap_size = (mmap_pages+1)*pgsz;
    pgmsk = mmap_pages*pgsz-1;

    // Setup
    memset(&pe, 0, sizeof(struct perf_event_attr));
    pe.type = PERF_TYPE_HARDWARE;
    pe.size = sizeof(struct perf_event_attr);
    pe.config = PERF_COUNT_HW_INSTRUCTIONS;
    pe.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TIME;
    pe.mmap = 1;
    pe.mmap_data = 1;
    pe.sample_period = sample_period;
    pe.disabled = 1;
    pe.exclude_kernel = 1;
    pe.exclude_hv = 1;

    // Calling pid, all cpus, single event group, no flags
    fd = syscall(__NR_perf_event_open, &pe,0,-1,-1,0);

    if (fd == -1) {
       fprintf(stderr, "Error opening leader %llx\n", pe.config);
       ready=0;
       return;
    }

    // Create mmap buffer for samples
    mmap_buf = (struct perf_event_mmap_page*)
        mmap(NULL, mmap_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

    if(mmap_buf == MAP_FAILED) {
       fprintf(stderr, "Error mmapping buffer\n");
       ready=0;
       return;
    }

    ready=1;
}

perf_event_prof::~perf_event_prof()
{
    munmap(mmap_buf,mmap_size);
    close(fd);
}

int perf_event_prof::init_sample_handler()
{
    return pthread_create(&sample_handler_thr,NULL,sample_handler_fn,(void*)this);
}

int perf_event_prof::begin_prof()
{
    ret = init_sample_handler();

    if(ret)
    {
        std::cerr << "Couldn't initialize sample handler thread, aborting!\n";
        std::cerr << std::endl;
        return ret;
    }

    ioctl(fd, PERF_EVENT_IOC_RESET, 0);
    ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);

    return ret;
}

void perf_event_prof::end_prof()
{
    pthread_cancel(sample_handler_thr);
    pthread_join(sample_handler_thr,NULL);

    read_all_samples(); // flush out remaining samples

    ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
    read(fd, &counter_value, sizeof(uint64_t));
}

int perf_event_prof::read_single_sample()
{
    int ret;
    uint64_t val;

    // READ IP
    ret = read_mmap_buffer((char*)&val,sizeof(uint64_t));
    if(ret)
        *os_err << "Can't read mmap buffer!\n" << std::endl;
    else
        *os_out << "IP : " << std::hex << val << std::endl;

    // READ TIMESTAMP
    ret |= read_mmap_buffer((char*)&val,sizeof(uint64_t));
    if(ret)
        *os_err << "Can't read mmap buffer!\n" << std::endl;
    else
        *os_out << "TS : " << std::hex << val << std::endl;

    return ret;
}

int perf_event_prof::read_all_samples()
{
    struct perf_event_header ehdr;
    int ret;

    for(;;) {
        ret = read_mmap_buffer((char*)&ehdr,sizeof(ehdr));
        if(ret)
            return 0; // no more samples

        switch(ehdr.type) {
            case PERF_RECORD_SAMPLE:
                read_single_sample();
                break;
            case PERF_RECORD_EXIT:
                process_exit_sample();
                break;
            case PERF_RECORD_LOST:
                process_lost_sample();
                break;
            case PERF_RECORD_THROTTLE:
                process_freq_sample();
                break;
            case PERF_RECORD_UNTHROTTLE:
                process_freq_sample();
                break;
            default:
                //printf("unknown sample type %d\n", ehdr.type);
                skip_mmap_buffer(sizeof(ehdr));
        }
    }
}

int perf_event_prof::read_mmap_buffer(char *out, size_t sz)
{
	char *data;
	unsigned long tail;
	size_t avail_sz, m, c;

	data = ((char *)mmap_buf)+sysconf(_SC_PAGESIZE);
	tail = mmap_buf->data_tail & pgmsk;
	avail_sz = mmap_buf->data_head - mmap_buf->data_tail;
	if (sz > avail_sz)
		return -1;
	c = pgmsk + 1 -  tail;
	m = c < sz ? c : sz;
	memcpy(out, data+tail, m);
	if ((sz - m) > 0)
		memcpy(out+m, data, sz - m);
	mmap_buf->data_tail += sz;

	return 0;
}

void perf_event_prof::skip_mmap_buffer(size_t sz)
{
    if ((mmap_buf->data_tail + sz) > mmap_buf->data_head)
        sz = mmap_buf->data_head - mmap_buf->data_tail;

    mmap_buf->data_tail += sz;
}

void perf_event_prof::process_lost_sample()
{
	struct { uint64_t id, lost; } lost;
	const char *str;

	ret = read_mmap_buffer((char*)&lost,sizeof(lost));

    /*
	if (ret)
		errx(1, "cannot read lost info");

	e = perf_id2event(fds, num_fds, lost.id);
	if (e == -1)
		str = "unknown lost event";
	else
		str = fds[e].name;

	fprintf(options.output_file,
		"<<<LOST %"PRIu64" SAMPLES FOR EVENT %s>>>\n", lost.lost, str);
    */
	lost_samples += lost.lost;
}

void perf_event_prof::process_exit_sample()
{
	struct { pid_t pid, ppid, tid, ptid; } grp;
	int ret;

	ret = read_mmap_buffer((char*)&grp, sizeof(grp));
    /*
	if (ret)
		errx(1, "cannot read exit info");

	fprintf(options.output_file,"[%d] exited\n", grp.pid);
    */
}

void perf_event_prof::process_freq_sample()
{
	struct { uint64_t time, id, stream_id; } thr;
	int ret;

	ret = read_mmap_buffer((char*)&thr, sizeof(thr));
    /*
	if (ret)
		errx(1, "cannot read throttling info");

	fprintf(options.output_file,"%s value=%"PRIu64" event ID=%"PRIu64"\n", mode ? "Throttled" : "Unthrottled", thr.id, thr.stream_id);
    */
}
void
do_werk()
{
    double v = 241209092.548394035;
    for(int i=0; i<512; i++)
        for(int j=0; j<512; j++)
            for(int k=0; k<512; k++)
                v = v*v;
    printf("v : %f\n",v);
}

int
main(int argc, char **argv)
{
    perf_event_prof mprof;
    mprof.set_outputstream(&std::cout);
    mprof.begin_prof();
    do_werk();
    mprof.end_prof();
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>

int letter_value(char letter) {
  switch (letter) {
    case 'I': return 1;
    case 'V': return 5;
    case 'X': return 10;
    case 'L': return 50;
    case 'C': return 100;
    case 'D': return 500;
    case 'M': return 1000;
    default:  std::string msg("letter not recognised: ");
              throw std::invalid_argument(msg + letter);
  }
}

bool try_group(int* dec, int threshold, std::string group, std::string* roman) {
  if (*dec < threshold) return false;
  *dec -= threshold;
  *roman += group;
  return true;
}

int roman_to_dec(const std::string& roman) {
  int dec = 0;
  size_t cch = roman.length();
  for (int i = 0; i < cch; ) {
    int this_value = letter_value(roman[i]);
    int next_value = (++i < cch) ? letter_value(roman[i]) : 0;
    if (this_value >= next_value) {
      dec += this_value;
    } else {
      dec -= this_value;
      dec += next_value;
      ++i;
    }
  }
  return dec;
}

std::string dec_to_roman(int dec) {
  std::string roman;
  while (dec > 0) {
    if (try_group(&dec, 1000, "M", &roman)) {}
    else if (try_group(&dec, 900, "CM", &roman)) {}
    else if (try_group(&dec, 500, "D", &roman)) {}
    else if (try_group(&dec, 400, "CD", &roman)) {}
    else if (try_group(&dec, 100, "C", &roman)) {}
    else if (try_group(&dec, 90, "XC", &roman)) {}
    else if (try_group(&dec, 50, "L", &roman)) {}
    else if (try_group(&dec, 40, "XL", &roman)) {}
    else if (try_group(&dec, 10, "X", &roman)) {}
    else if (try_group(&dec, 9, "IX", &roman)) {}
    else if (try_group(&dec, 5, "V", &roman)) {}
    else if (try_group(&dec, 4, "IV", &roman)) {}
    else if (try_group(&dec, 1, "I", &roman)) {}
    else throw std::logic_error("Huh?");
  }
  return roman;
}

void test(std::string roman, int dec) {
  std::cout << roman << "->" << roman_to_dec(roman) << std::endl;
  std::cout << dec << "->" << dec_to_roman(dec) << std::endl;
}

int main(int argc, char** argv) {
  std::cout << "X->" << letter_value('X') << std::endl;
  try {
    letter_value('Y');
    std::cout << "SHOULDN'T GET HERE!!!" << std::endl;
  } catch (std::invalid_argument& e) {
    std::cout << "Y rightly throws exception '" << e.what() << "'" << std::endl;
  }
  test("III", 3);
  test("IV", 4);
  test("XV", 15);
  test("MCMXCIX", 1999);

  // Problem itself.
  std::ifstream infile("/Users/pdbartlett/src/cpp/euler/p089_roman.txt");
  int cch = 0;
  std::string roman;
  while (std::getline(infile, roman))
  {
    int dec = roman_to_dec(roman);
    std::string minimal(dec_to_roman(dec));
    std::cout << roman << ", " << dec << ", " << minimal << std::endl;
    cch += roman.size();
    cch -= minimal.size();
  }
  std::cout << "Characters saved = " << cch << std::endl;

  return 0;
}
<commit_msg>Update p089.cc<commit_after>#include <algorithm>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>

int letter_value(char letter) {
  switch (letter) {
    case 'I': return 1;
    case 'V': return 5;
    case 'X': return 10;
    case 'L': return 50;
    case 'C': return 100;
    case 'D': return 500;
    case 'M': return 1000;
    default:  std::string msg("letter not recognised: ");
              throw std::invalid_argument(msg + letter);
  }
}

bool try_group(int* dec, int threshold, std::string group, std::string* roman) {
  if (*dec < threshold) return false;
  *dec -= threshold;
  *roman += group;
  return true;
}

int roman_to_dec(const std::string& roman) {
  int dec = 0;
  size_t cch = roman.length();
  for (int i = 0; i < cch; ) {
    int this_value = letter_value(roman[i]);
    int next_value = (++i < cch) ? letter_value(roman[i]) : 0;
    if (this_value >= next_value) {
      dec += this_value;
    } else {
      dec -= this_value;
      dec += next_value;
      ++i;
    }
  }
  return dec;
}

std::string dec_to_roman(int dec) {
  std::string roman;
  while (dec > 0) {
    if (try_group(&dec, 1000, "M", &roman)) {}
    else if (try_group(&dec, 900, "CM", &roman)) {}
    else if (try_group(&dec, 500, "D", &roman)) {}
    else if (try_group(&dec, 400, "CD", &roman)) {}
    else if (try_group(&dec, 100, "C", &roman)) {}
    else if (try_group(&dec, 90, "XC", &roman)) {}
    else if (try_group(&dec, 50, "L", &roman)) {}
    else if (try_group(&dec, 40, "XL", &roman)) {}
    else if (try_group(&dec, 10, "X", &roman)) {}
    else if (try_group(&dec, 9, "IX", &roman)) {}
    else if (try_group(&dec, 5, "V", &roman)) {}
    else if (try_group(&dec, 4, "IV", &roman)) {}
    else if (try_group(&dec, 1, "I", &roman)) {}
    else throw std::logic_error("Huh?");
  }
  return roman;
}

void test(std::string roman, int dec) {
  std::cout << roman << "->" << roman_to_dec(roman) << std::endl;
  std::cout << dec << "->" << dec_to_roman(dec) << std::endl;
}

int main(int argc, char** argv) {
  std::cout << "X->" << letter_value('X') << std::endl;
  try {
    letter_value('Y');
    std::cout << "SHOULDN'T GET HERE!!!" << std::endl;
  } catch (std::invalid_argument& e) {
    std::cout << "Y rightly throws exception '" << e.what() << "'" << std::endl;
  }
  test("III", 3);
  test("IV", 4);
  test("XV", 15);
  test("MCMXCIX", 1999);

  // Problem itself.
  std::ifstream infile("/Users/pdbartlett/src/cpp/euler/p089_roman.txt");
  int cch = 0;
  std::string roman;
  while (std::getline(infile, roman)) {
    int dec = roman_to_dec(roman);
    std::string minimal(dec_to_roman(dec));
    std::cout << roman << ", " << dec << ", " << minimal << std::endl;
    cch += roman.size();
    cch -= minimal.size();
  }
  std::cout << "Characters saved = " << cch << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifndef __OPENCV_CUDASTEREO_HPP__
#define __OPENCV_CUDASTEREO_HPP__

#ifndef __cplusplus
#  error cudastereo.hpp header must be compiled as C++
#endif

#include "opencv2/core/cuda.hpp"
#include "opencv2/calib3d.hpp"

/**
  @addtogroup cuda
  @{
    @defgroup cudastereo Stereo Correspondence
  @}
 */

namespace cv { namespace cuda {

//! @addtogroup cudastereo
//! @{

/////////////////////////////////////////
// StereoBM

/** @brief Class computing stereo correspondence (disparity map) using the block matching algorithm. :

@sa StereoBM
 */
class CV_EXPORTS StereoBM : public cv::StereoBM
{
public:
    using cv::StereoBM::compute;

    virtual void compute(InputArray left, InputArray right, OutputArray disparity, Stream& stream) = 0;
};

/** @brief Creates StereoBM object.

@param numDisparities the disparity search range. For each pixel algorithm will find the best
disparity from 0 (default minimum disparity) to numDisparities. The search range can then be
shifted by changing the minimum disparity.
@param blockSize the linear size of the blocks compared by the algorithm. The size should be odd
(as the block is centered at the current pixel). Larger block size implies smoother, though less
accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher
chance for algorithm to find a wrong correspondence.
 */
CV_EXPORTS Ptr<cuda::StereoBM> createStereoBM(int numDisparities = 64, int blockSize = 19);

/////////////////////////////////////////
// StereoBeliefPropagation

/** @brief Class computing stereo correspondence using the belief propagation algorithm. :

The class implements algorithm described in @cite Felzenszwalb2006 . It can compute own data cost
(using a truncated linear model) or use a user-provided data cost.

@note
   StereoBeliefPropagation requires a lot of memory for message storage:

    \f[width \_ step  \cdot height  \cdot ndisp  \cdot 4  \cdot (1 + 0.25)\f]

    and for data cost storage:

    \f[width\_step \cdot height \cdot ndisp \cdot (1 + 0.25 + 0.0625 +  \dotsm + \frac{1}{4^{levels}})\f]

    width_step is the number of bytes in a line including padding.

StereoBeliefPropagation uses a truncated linear model for the data cost and discontinuity terms:

\f[DataCost = data \_ weight  \cdot \min ( \lvert Img_Left(x,y)-Img_Right(x-d,y)  \rvert , max \_ data \_ term)\f]

\f[DiscTerm =  \min (disc \_ single \_ jump  \cdot \lvert f_1-f_2  \rvert , max \_ disc \_ term)\f]

For more details, see @cite Felzenszwalb2006 .

By default, StereoBeliefPropagation uses floating-point arithmetics and the CV_32FC1 type for
messages. But it can also use fixed-point arithmetics and the CV_16SC1 message type for better
performance. To avoid an overflow in this case, the parameters must satisfy the following
requirement:

\f[10  \cdot 2^{levels-1}  \cdot max \_ data \_ term < SHRT \_ MAX\f]

@sa StereoMatcher
 */
class CV_EXPORTS StereoBeliefPropagation : public cv::StereoMatcher
{
public:
    using cv::StereoMatcher::compute;

    /** @overload */
    virtual void compute(InputArray left, InputArray right, OutputArray disparity, Stream& stream) = 0;

    /** @brief Enables the stereo correspondence operator that finds the disparity for the specified data cost.

    @param data User-specified data cost, a matrix of msg_type type and
    Size(\<image columns\>\*ndisp, \<image rows\>) size.
    @param disparity Output disparity map. If disparity is empty, the output type is CV_16SC1 .
    Otherwise, the type is retained.
    @param stream Stream for the asynchronous version.
     */
    virtual void compute(InputArray data, OutputArray disparity, Stream& stream = Stream::Null()) = 0;

    //! number of BP iterations on each level
    virtual int getNumIters() const = 0;
    virtual void setNumIters(int iters) = 0;

    //! number of levels
    virtual int getNumLevels() const = 0;
    virtual void setNumLevels(int levels) = 0;

    //! truncation of data cost
    virtual double getMaxDataTerm() const = 0;
    virtual void setMaxDataTerm(double max_data_term) = 0;

    //! data weight
    virtual double getDataWeight() const = 0;
    virtual void setDataWeight(double data_weight) = 0;

    //! truncation of discontinuity cost
    virtual double getMaxDiscTerm() const = 0;
    virtual void setMaxDiscTerm(double max_disc_term) = 0;

    //! discontinuity single jump
    virtual double getDiscSingleJump() const = 0;
    virtual void setDiscSingleJump(double disc_single_jump) = 0;

    //! type for messages (CV_16SC1 or CV_32FC1)
    virtual int getMsgType() const = 0;
    virtual void setMsgType(int msg_type) = 0;

    /** @brief Uses a heuristic method to compute the recommended parameters ( ndisp, iters and levels ) for the
    specified image size ( width and height ).
     */
    static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels);
};

/** @brief Creates StereoBeliefPropagation object.

@param ndisp Number of disparities.
@param iters Number of BP iterations on each level.
@param levels Number of levels.
@param msg_type Type for messages. CV_16SC1 and CV_32FC1 types are supported.
 */
CV_EXPORTS Ptr<cuda::StereoBeliefPropagation>
    createStereoBeliefPropagation(int ndisp = 64, int iters = 5, int levels = 5, int msg_type = CV_32F);

/////////////////////////////////////////
// StereoConstantSpaceBP

/** @brief Class computing stereo correspondence using the constant space belief propagation algorithm. :

The class implements algorithm described in @cite Yang2010 . StereoConstantSpaceBP supports both local
minimum and global minimum data cost initialization algorithms. For more details, see the paper
mentioned above. By default, a local algorithm is used. To enable a global algorithm, set
use_local_init_data_cost to false .

StereoConstantSpaceBP uses a truncated linear model for the data cost and discontinuity terms:

\f[DataCost = data \_ weight  \cdot \min ( \lvert I_2-I_1  \rvert , max \_ data \_ term)\f]

\f[DiscTerm =  \min (disc \_ single \_ jump  \cdot \lvert f_1-f_2  \rvert , max \_ disc \_ term)\f]

For more details, see @cite Yang2010 .

By default, StereoConstantSpaceBP uses floating-point arithmetics and the CV_32FC1 type for
messages. But it can also use fixed-point arithmetics and the CV_16SC1 message type for better
performance. To avoid an overflow in this case, the parameters must satisfy the following
requirement:

\f[10  \cdot 2^{levels-1}  \cdot max \_ data \_ term < SHRT \_ MAX\f]

 */
class CV_EXPORTS StereoConstantSpaceBP : public cuda::StereoBeliefPropagation
{
public:
    //! number of active disparity on the first level
    virtual int getNrPlane() const = 0;
    virtual void setNrPlane(int nr_plane) = 0;

    virtual bool getUseLocalInitDataCost() const = 0;
    virtual void setUseLocalInitDataCost(bool use_local_init_data_cost) = 0;

    /** @brief Uses a heuristic method to compute parameters (ndisp, iters, levelsand nrplane) for the specified
    image size (widthand height).
     */
    static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane);
};

/** @brief Creates StereoConstantSpaceBP object.

@param ndisp Number of disparities.
@param iters Number of BP iterations on each level.
@param levels Number of levels.
@param nr_plane Number of disparity levels on the first level.
@param msg_type Type for messages. CV_16SC1 and CV_32FC1 types are supported.
 */
CV_EXPORTS Ptr<cuda::StereoConstantSpaceBP>
    createStereoConstantSpaceBP(int ndisp = 128, int iters = 8, int levels = 4, int nr_plane = 4, int msg_type = CV_32F);

/////////////////////////////////////////
// DisparityBilateralFilter

/** @brief Class refining a disparity map using joint bilateral filtering. :

The class implements @cite Yang2010 algorithm.
 */
class CV_EXPORTS DisparityBilateralFilter : public cv::Algorithm
{
public:
    /** @brief Refines a disparity map using joint bilateral filtering.

    @param disparity Input disparity map. CV_8UC1 and CV_16SC1 types are supported.
    @param image Input image. CV_8UC1 and CV_8UC3 types are supported.
    @param dst Destination disparity map. It has the same size and type as disparity .
    @param stream Stream for the asynchronous version.
     */
    virtual void apply(InputArray disparity, InputArray image, OutputArray dst, Stream& stream = Stream::Null()) = 0;

    virtual int getNumDisparities() const = 0;
    virtual void setNumDisparities(int numDisparities) = 0;

    virtual int getRadius() const = 0;
    virtual void setRadius(int radius) = 0;

    virtual int getNumIters() const = 0;
    virtual void setNumIters(int iters) = 0;

    //! truncation of data continuity
    virtual double getEdgeThreshold() const = 0;
    virtual void setEdgeThreshold(double edge_threshold) = 0;

    //! truncation of disparity continuity
    virtual double getMaxDiscThreshold() const = 0;
    virtual void setMaxDiscThreshold(double max_disc_threshold) = 0;

    //! filter range sigma
    virtual double getSigmaRange() const = 0;
    virtual void setSigmaRange(double sigma_range) = 0;
};

/** @brief Creates DisparityBilateralFilter object.

@param ndisp Number of disparities.
@param radius Filter radius.
@param iters Number of iterations.
 */
CV_EXPORTS Ptr<cuda::DisparityBilateralFilter>
    createDisparityBilateralFilter(int ndisp = 64, int radius = 3, int iters = 1);

/////////////////////////////////////////
// Utility

/** @brief Reprojects a disparity image to 3D space.

@param disp Input disparity image. CV_8U and CV_16S types are supported.
@param xyzw Output 3- or 4-channel floating-point image of the same size as disp . Each element of
xyzw(x,y) contains 3D coordinates (x,y,z) or (x,y,z,1) of the point (x,y) , computed from the
disparity map.
@param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained via stereoRectify .
@param dst_cn The number of channels for output image. Can be 3 or 4.
@param stream Stream for the asynchronous version.

@sa reprojectImageTo3D
 */
CV_EXPORTS void reprojectImageTo3D(InputArray disp, OutputArray xyzw, InputArray Q, int dst_cn = 4, Stream& stream = Stream::Null());

/** @brief Colors a disparity image.

@param src_disp Source disparity image. CV_8UC1 and CV_16SC1 types are supported.
@param dst_disp Output disparity image. It has the same size as src_disp . The type is CV_8UC4
in BGRA format (alpha = 255).
@param ndisp Number of disparities.
@param stream Stream for the asynchronous version.

This function draws a colored disparity map by converting disparity values from [0..ndisp) interval
first to HSV color space (where different disparity values correspond to different hues) and then
converting the pixels to RGB for visualization.
 */
CV_EXPORTS void drawColorDisp(InputArray src_disp, OutputArray dst_disp, int ndisp, Stream& stream = Stream::Null());

//! @}

}} // namespace cv { namespace cuda {

#endif /* __OPENCV_CUDASTEREO_HPP__ */
<commit_msg>cudastereo: updated documentation for reprojectImage3D and drawColorDisp<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifndef __OPENCV_CUDASTEREO_HPP__
#define __OPENCV_CUDASTEREO_HPP__

#ifndef __cplusplus
#  error cudastereo.hpp header must be compiled as C++
#endif

#include "opencv2/core/cuda.hpp"
#include "opencv2/calib3d.hpp"

/**
  @addtogroup cuda
  @{
    @defgroup cudastereo Stereo Correspondence
  @}
 */

namespace cv { namespace cuda {

//! @addtogroup cudastereo
//! @{

/////////////////////////////////////////
// StereoBM

/** @brief Class computing stereo correspondence (disparity map) using the block matching algorithm. :

@sa StereoBM
 */
class CV_EXPORTS StereoBM : public cv::StereoBM
{
public:
    using cv::StereoBM::compute;

    virtual void compute(InputArray left, InputArray right, OutputArray disparity, Stream& stream) = 0;
};

/** @brief Creates StereoBM object.

@param numDisparities the disparity search range. For each pixel algorithm will find the best
disparity from 0 (default minimum disparity) to numDisparities. The search range can then be
shifted by changing the minimum disparity.
@param blockSize the linear size of the blocks compared by the algorithm. The size should be odd
(as the block is centered at the current pixel). Larger block size implies smoother, though less
accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher
chance for algorithm to find a wrong correspondence.
 */
CV_EXPORTS Ptr<cuda::StereoBM> createStereoBM(int numDisparities = 64, int blockSize = 19);

/////////////////////////////////////////
// StereoBeliefPropagation

/** @brief Class computing stereo correspondence using the belief propagation algorithm. :

The class implements algorithm described in @cite Felzenszwalb2006 . It can compute own data cost
(using a truncated linear model) or use a user-provided data cost.

@note
   StereoBeliefPropagation requires a lot of memory for message storage:

    \f[width \_ step  \cdot height  \cdot ndisp  \cdot 4  \cdot (1 + 0.25)\f]

    and for data cost storage:

    \f[width\_step \cdot height \cdot ndisp \cdot (1 + 0.25 + 0.0625 +  \dotsm + \frac{1}{4^{levels}})\f]

    width_step is the number of bytes in a line including padding.

StereoBeliefPropagation uses a truncated linear model for the data cost and discontinuity terms:

\f[DataCost = data \_ weight  \cdot \min ( \lvert Img_Left(x,y)-Img_Right(x-d,y)  \rvert , max \_ data \_ term)\f]

\f[DiscTerm =  \min (disc \_ single \_ jump  \cdot \lvert f_1-f_2  \rvert , max \_ disc \_ term)\f]

For more details, see @cite Felzenszwalb2006 .

By default, StereoBeliefPropagation uses floating-point arithmetics and the CV_32FC1 type for
messages. But it can also use fixed-point arithmetics and the CV_16SC1 message type for better
performance. To avoid an overflow in this case, the parameters must satisfy the following
requirement:

\f[10  \cdot 2^{levels-1}  \cdot max \_ data \_ term < SHRT \_ MAX\f]

@sa StereoMatcher
 */
class CV_EXPORTS StereoBeliefPropagation : public cv::StereoMatcher
{
public:
    using cv::StereoMatcher::compute;

    /** @overload */
    virtual void compute(InputArray left, InputArray right, OutputArray disparity, Stream& stream) = 0;

    /** @brief Enables the stereo correspondence operator that finds the disparity for the specified data cost.

    @param data User-specified data cost, a matrix of msg_type type and
    Size(\<image columns\>\*ndisp, \<image rows\>) size.
    @param disparity Output disparity map. If disparity is empty, the output type is CV_16SC1 .
    Otherwise, the type is retained.
    @param stream Stream for the asynchronous version.
     */
    virtual void compute(InputArray data, OutputArray disparity, Stream& stream = Stream::Null()) = 0;

    //! number of BP iterations on each level
    virtual int getNumIters() const = 0;
    virtual void setNumIters(int iters) = 0;

    //! number of levels
    virtual int getNumLevels() const = 0;
    virtual void setNumLevels(int levels) = 0;

    //! truncation of data cost
    virtual double getMaxDataTerm() const = 0;
    virtual void setMaxDataTerm(double max_data_term) = 0;

    //! data weight
    virtual double getDataWeight() const = 0;
    virtual void setDataWeight(double data_weight) = 0;

    //! truncation of discontinuity cost
    virtual double getMaxDiscTerm() const = 0;
    virtual void setMaxDiscTerm(double max_disc_term) = 0;

    //! discontinuity single jump
    virtual double getDiscSingleJump() const = 0;
    virtual void setDiscSingleJump(double disc_single_jump) = 0;

    //! type for messages (CV_16SC1 or CV_32FC1)
    virtual int getMsgType() const = 0;
    virtual void setMsgType(int msg_type) = 0;

    /** @brief Uses a heuristic method to compute the recommended parameters ( ndisp, iters and levels ) for the
    specified image size ( width and height ).
     */
    static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels);
};

/** @brief Creates StereoBeliefPropagation object.

@param ndisp Number of disparities.
@param iters Number of BP iterations on each level.
@param levels Number of levels.
@param msg_type Type for messages. CV_16SC1 and CV_32FC1 types are supported.
 */
CV_EXPORTS Ptr<cuda::StereoBeliefPropagation>
    createStereoBeliefPropagation(int ndisp = 64, int iters = 5, int levels = 5, int msg_type = CV_32F);

/////////////////////////////////////////
// StereoConstantSpaceBP

/** @brief Class computing stereo correspondence using the constant space belief propagation algorithm. :

The class implements algorithm described in @cite Yang2010 . StereoConstantSpaceBP supports both local
minimum and global minimum data cost initialization algorithms. For more details, see the paper
mentioned above. By default, a local algorithm is used. To enable a global algorithm, set
use_local_init_data_cost to false .

StereoConstantSpaceBP uses a truncated linear model for the data cost and discontinuity terms:

\f[DataCost = data \_ weight  \cdot \min ( \lvert I_2-I_1  \rvert , max \_ data \_ term)\f]

\f[DiscTerm =  \min (disc \_ single \_ jump  \cdot \lvert f_1-f_2  \rvert , max \_ disc \_ term)\f]

For more details, see @cite Yang2010 .

By default, StereoConstantSpaceBP uses floating-point arithmetics and the CV_32FC1 type for
messages. But it can also use fixed-point arithmetics and the CV_16SC1 message type for better
performance. To avoid an overflow in this case, the parameters must satisfy the following
requirement:

\f[10  \cdot 2^{levels-1}  \cdot max \_ data \_ term < SHRT \_ MAX\f]

 */
class CV_EXPORTS StereoConstantSpaceBP : public cuda::StereoBeliefPropagation
{
public:
    //! number of active disparity on the first level
    virtual int getNrPlane() const = 0;
    virtual void setNrPlane(int nr_plane) = 0;

    virtual bool getUseLocalInitDataCost() const = 0;
    virtual void setUseLocalInitDataCost(bool use_local_init_data_cost) = 0;

    /** @brief Uses a heuristic method to compute parameters (ndisp, iters, levelsand nrplane) for the specified
    image size (widthand height).
     */
    static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane);
};

/** @brief Creates StereoConstantSpaceBP object.

@param ndisp Number of disparities.
@param iters Number of BP iterations on each level.
@param levels Number of levels.
@param nr_plane Number of disparity levels on the first level.
@param msg_type Type for messages. CV_16SC1 and CV_32FC1 types are supported.
 */
CV_EXPORTS Ptr<cuda::StereoConstantSpaceBP>
    createStereoConstantSpaceBP(int ndisp = 128, int iters = 8, int levels = 4, int nr_plane = 4, int msg_type = CV_32F);

/////////////////////////////////////////
// DisparityBilateralFilter

/** @brief Class refining a disparity map using joint bilateral filtering. :

The class implements @cite Yang2010 algorithm.
 */
class CV_EXPORTS DisparityBilateralFilter : public cv::Algorithm
{
public:
    /** @brief Refines a disparity map using joint bilateral filtering.

    @param disparity Input disparity map. CV_8UC1 and CV_16SC1 types are supported.
    @param image Input image. CV_8UC1 and CV_8UC3 types are supported.
    @param dst Destination disparity map. It has the same size and type as disparity .
    @param stream Stream for the asynchronous version.
     */
    virtual void apply(InputArray disparity, InputArray image, OutputArray dst, Stream& stream = Stream::Null()) = 0;

    virtual int getNumDisparities() const = 0;
    virtual void setNumDisparities(int numDisparities) = 0;

    virtual int getRadius() const = 0;
    virtual void setRadius(int radius) = 0;

    virtual int getNumIters() const = 0;
    virtual void setNumIters(int iters) = 0;

    //! truncation of data continuity
    virtual double getEdgeThreshold() const = 0;
    virtual void setEdgeThreshold(double edge_threshold) = 0;

    //! truncation of disparity continuity
    virtual double getMaxDiscThreshold() const = 0;
    virtual void setMaxDiscThreshold(double max_disc_threshold) = 0;

    //! filter range sigma
    virtual double getSigmaRange() const = 0;
    virtual void setSigmaRange(double sigma_range) = 0;
};

/** @brief Creates DisparityBilateralFilter object.

@param ndisp Number of disparities.
@param radius Filter radius.
@param iters Number of iterations.
 */
CV_EXPORTS Ptr<cuda::DisparityBilateralFilter>
    createDisparityBilateralFilter(int ndisp = 64, int radius = 3, int iters = 1);

/////////////////////////////////////////
// Utility

/** @brief Reprojects a disparity image to 3D space.

@param disp Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit
floating-point disparity image. If 16-bit signed format is used, the values are assumed to have no
fractional bits.
@param xyzw Output 3- or 4-channel floating-point image of the same size as disp . Each element of
xyzw(x,y) contains 3D coordinates (x,y,z) or (x,y,z,1) of the point (x,y) , computed from the
disparity map.
@param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained via stereoRectify .
@param dst_cn The number of channels for output image. Can be 3 or 4.
@param stream Stream for the asynchronous version.

@sa reprojectImageTo3D
 */
CV_EXPORTS void reprojectImageTo3D(InputArray disp, OutputArray xyzw, InputArray Q, int dst_cn = 4, Stream& stream = Stream::Null());

/** @brief Colors a disparity image.

@param src_disp Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit
floating-point disparity image. If 16-bit signed format is used, the values are assumed to have no
fractional bits.
@param dst_disp Output disparity image. It has the same size as src_disp. The type is CV_8UC4
in BGRA format (alpha = 255).
@param ndisp Number of disparities.
@param stream Stream for the asynchronous version.

This function draws a colored disparity map by converting disparity values from [0..ndisp) interval
first to HSV color space (where different disparity values correspond to different hues) and then
converting the pixels to RGB for visualization.
 */
CV_EXPORTS void drawColorDisp(InputArray src_disp, OutputArray dst_disp, int ndisp, Stream& stream = Stream::Null());

//! @}

}} // namespace cv { namespace cuda {

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


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/container/container_manager.h"

namespace apollo {
namespace prediction {

ContainerManager::ContainerManager() {}

ContainerManager::~ContainerManager() {
  containers_.clear();
}

void ContainerManager::RegisterContainer() {}

Container* ContainerManager::mutable_container(const std::string& name) {
  if (containers_.find(name) != containers_.end()) {
    return containers_[name].get();
  } else {
    return nullptr;
  }
}
}
}
<commit_msg>Added container framework.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/container/container_manager.h"

namespace apollo {
namespace prediction {

ContainerManager::ContainerManager() {}

ContainerManager::~ContainerManager() {
  containers_.clear();
}

void ContainerManager::RegisterContainer() {}

Container* ContainerManager::mutable_container(const std::string& name) {
  if (containers_.find(name) != containers_.end()) {
    return containers_[name].get();
  } else {
    return nullptr;
  }
}

}
}
<|endoftext|>


<commit_before>#pragma once
/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _QI_BUFFERREADER_HPP_
#define _QI_BUFFERREADER_HPP_

#include <qi/buffer.hpp>

namespace qi {

  /// Class to read const buffer.
  class QI_API BufferReader
  {
  public:
    /// Copy constructor.
    BufferReader(const Buffer& buf);
    /// Default destructor.
    ~BufferReader();
    /// read and store data from the buffer.
    size_t read(void *data, size_t length);

    /// read data from buffer.
    void  *read(size_t offset);
    /// Move forward the buffer cursor by the given offset.
    bool   seek(size_t offset);
    /// Check if we can read from the actual position toward \a offset bytes.
    void  *peek(size_t offset) const;

    /// Check if there is sub-buffer at the actual position.
    bool hasSubBuffer() const;
    /// return the sub-buffer at the actual position.
    const Buffer& subBuffer();
    /// return the actual position in the buffer.
    size_t position() const;

  private:
    Buffer _buffer;
    size_t _cursor;
    size_t _subCursor; // position in sub-buffers
  };
}

#endif  // _QI_BUFFERREADER_HPP_
<commit_msg>BufferReader: change ctor to explicit<commit_after>#pragma once
/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _QI_BUFFERREADER_HPP_
#define _QI_BUFFERREADER_HPP_

#include <qi/buffer.hpp>

namespace qi {

  /// Class to read const buffer.
  class QI_API BufferReader
  {
  public:
    /// Constructor.
    explicit BufferReader(const Buffer& buf);
    /// Default destructor.
    ~BufferReader();
    /// read and store data from the buffer.
    size_t read(void *data, size_t length);

    /// read data from buffer.
    void  *read(size_t offset);
    /// Move forward the buffer cursor by the given offset.
    bool   seek(size_t offset);
    /// Check if we can read from the actual position toward \a offset bytes.
    void  *peek(size_t offset) const;

    /// Check if there is sub-buffer at the actual position.
    bool hasSubBuffer() const;
    /// return the sub-buffer at the actual position.
    const Buffer& subBuffer();
    /// return the actual position in the buffer.
    size_t position() const;

  private:
    Buffer _buffer;
    size_t _cursor;
    size_t _subCursor; // position in sub-buffers
  };
}

#endif  // _QI_BUFFERREADER_HPP_
<|endoftext|>


<commit_before>#ifndef MS_RTC_RATE_CALCULATOR_HPP
#define MS_RTC_RATE_CALCULATOR_HPP

#include "common.hpp"
#include "DepLibUV.hpp"
#include "RTC/RtpPacket.hpp"

namespace RTC
{
	// It is considered that the time source increases monotonically.
	// ie: the current timestamp can never be minor than a timestamp in the past.
	class RateCalculator
	{
	public:
		static constexpr float BpsScale{ 8000.0f };
		static constexpr size_t DefaultWindowSize{ 1000 };

	public:
		explicit RateCalculator(size_t windowSize = DefaultWindowSize, float scale = BpsScale);
		void Update(size_t size, uint64_t now);
		uint32_t GetRate(uint64_t now);
		size_t GetBytes() const;
		void Reset();

	private:
		void RemoveOldData(uint64_t now);
		void Reset(uint64_t now);

	private:
		struct BufferItem
		{
			size_t count{ 0 };
		};

	private:
		std::unique_ptr<BufferItem[]> buffer;

		// Time (in milliseconds) for oldest item in the time window.
		uint64_t oldestTime{ 0 };
		// Index for the oldest item in the time window.
		uint32_t oldestIndex{ 0 };
		// Total count in the time window.
		size_t totalCount{ 0 };
		// Window Size (in milliseconds).
		size_t windowSize{ DefaultWindowSize };
		// Scale in which the rate is represented.
		const float scale{ BpsScale };
		// Total bytes transmitted.
		size_t bytes{ 0 };
	};

	/* Inline instance methods. */

	inline RateCalculator::RateCalculator(size_t windowSize, float scale)
	  : windowSize(windowSize), scale(scale)
	{
		Reset();
	}

	inline size_t RateCalculator::GetBytes() const
	{
		return this->bytes;
	}

	inline void RateCalculator::Reset()
	{
		uint64_t now = DepLibUV::GetTime();

		Reset(now);
	}

	inline void RateCalculator::Reset(uint64_t now)
	{
		this->buffer.reset(new BufferItem[this->windowSize]);
		this->totalCount  = 0;
		this->oldestIndex = 0;
		this->oldestTime  = now - this->windowSize;
	}

	class RtpDataCounter
	{
	public:
		RtpDataCounter() = default;

	public:
		void Update(RTC::RtpPacket* packet);
		uint32_t GetBitrate(uint64_t now);
		size_t GetPacketCount() const;
		size_t GetBytes() const;

	private:
		RateCalculator rate;
		size_t packets{ 0 };
	};

	/* Inline instance methods. */

	inline uint32_t RtpDataCounter::GetBitrate(uint64_t now)
	{
		return this->rate.GetRate(now);
	}

	inline size_t RtpDataCounter::GetPacketCount() const
	{
		return this->packets;
	}

	inline size_t RtpDataCounter::GetBytes() const
	{
		return this->rate.GetBytes();
	}
} // namespace RTC

#endif
<commit_msg>RtpDataCounter: use window size of 2500 ms instead of 1000 ms<commit_after>#ifndef MS_RTC_RATE_CALCULATOR_HPP
#define MS_RTC_RATE_CALCULATOR_HPP

#include "common.hpp"
#include "DepLibUV.hpp"
#include "RTC/RtpPacket.hpp"

namespace RTC
{
	// It is considered that the time source increases monotonically.
	// ie: the current timestamp can never be minor than a timestamp in the past.
	class RateCalculator
	{
	public:
		static constexpr size_t DefaultWindowSize{ 1000 };
		static constexpr float DefaultBpsScale{ 8000.0f };

	public:
		explicit RateCalculator(size_t windowSize = DefaultWindowSize, float scale = DefaultBpsScale);
		void Update(size_t size, uint64_t now);
		uint32_t GetRate(uint64_t now);
		size_t GetBytes() const;
		void Reset();

	private:
		void RemoveOldData(uint64_t now);
		void Reset(uint64_t now);

	private:
		struct BufferItem
		{
			size_t count{ 0 };
		};

	private:
		std::unique_ptr<BufferItem[]> buffer;

		// Time (in milliseconds) for oldest item in the time window.
		uint64_t oldestTime{ 0 };
		// Index for the oldest item in the time window.
		uint32_t oldestIndex{ 0 };
		// Total count in the time window.
		size_t totalCount{ 0 };
		// Window Size (in milliseconds).
		size_t windowSize{ DefaultWindowSize };
		// Scale in which the rate is represented.
		const float scale{ DefaultBpsScale };
		// Total bytes transmitted.
		size_t bytes{ 0 };
	};

	/* Inline instance methods. */

	inline RateCalculator::RateCalculator(size_t windowSize, float scale)
	  : windowSize(windowSize), scale(scale)
	{
		Reset();
	}

	inline size_t RateCalculator::GetBytes() const
	{
		return this->bytes;
	}

	inline void RateCalculator::Reset()
	{
		uint64_t now = DepLibUV::GetTime();

		Reset(now);
	}

	inline void RateCalculator::Reset(uint64_t now)
	{
		this->buffer.reset(new BufferItem[this->windowSize]);
		this->totalCount  = 0;
		this->oldestIndex = 0;
		this->oldestTime  = now - this->windowSize;
	}

	class RtpDataCounter
	{
	public:
		RtpDataCounter() = default;

	public:
		void Update(RTC::RtpPacket* packet);
		uint32_t GetBitrate(uint64_t now);
		size_t GetPacketCount() const;
		size_t GetBytes() const;

	private:
		RateCalculator rate{ /*windowSize*/ 2500 };
		size_t packets{ 0 };
	};

	/* Inline instance methods. */

	inline uint32_t RtpDataCounter::GetBitrate(uint64_t now)
	{
		return this->rate.GetRate(now);
	}

	inline size_t RtpDataCounter::GetPacketCount() const
	{
		return this->packets;
	}

	inline size_t RtpDataCounter::GetBytes() const
	{
		return this->rate.GetBytes();
	}
} // namespace RTC

#endif
<|endoftext|>