<commit_before>/* vim: set ts=4 sw=4 tw=79 et :*/
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "TestHarness.h"

#include "base/io/Path.h"

int main(int argc, char* argv[]) {
    int rv = 0;

    /// Path::isAbsolute Tests

    rv +=
    runTest("Test empty string !isAbsolute", []() {
        return !Path::isAbsolute("");
    });

    rv +=
    runPosixOnlyTest("Test isAbsolute('/a/b/c')", []() {
        return Path::isAbsolute("/a/b/c");
    });

    rv +=
    runPosixOnlyTest("Test !isAbsolute('a/b/c')", []() {
        return !Path::isAbsolute("a/b/c");
    });

    rv +=
    runPosixOnlyTest("Test !isAbsolute('../a/b')", []() {
        return !Path::isAbsolute("../a/b");
    });

    rv +=
    runPosixOnlyTest("Test !isAbsolute('./a/b'", []() {
        return !Path::isAbsolute("./a/b");
    });

    rv +=
    runWindowsOnlyTest("Test short/invalid path", []() {
        return
            !Path::isAbsolute("C:") &&
            !Path::isAbsolute("C")  &&
            !Path::isAbsolute("F:F");
    });

    rv +=
    runWindowsOnlyTest("Test isAbsolute('<driveletter>:\\Hello')", []() {
        return
            Path::isAbsolute("a:\\Hello") &&
            Path::isAbsolute("A:\\Hello") &&
            Path::isAbsolute("z:\\Hello") &&
            Path::isAbsolute("Z:\\Hello");
    });

    // Windows supports forward slashes with this form of path
    rv +=
    runWindowsOnlyTest("Test isAbsolute('<driveletter>:/Hello')", []() {
        return
            Path::isAbsolute("a:/Hello") &&
            Path::isAbsolute("A:/Hello") &&
            Path::isAbsolute("z:/Hello") &&
            Path::isAbsolute("Z:/Hello");
    });

    rv +=
    runWindowsOnlyTest("Test isAbsolute('\\\\Path')", []() {
        return Path::isAbsolute("\\\\Path");
    });

    rv +=
    runWindowsOnlyTest("Test isAbsolute('//Path/')", []() {
        return Path::isAbsolute("//Path/");
    });

    rv +=
    runWindowsOnlyTest("Test isAbsolute('\\Single\\Slash')", []() {
        return Path::isAbsolute("\\Single\\Slash");
    });

    /*
     * This '\\?\' prefix is not used as part of the path itself. They indicate
     * that the path should be passed to the system with minimal modification,
     * which means that you cannot use forward slashes to represent path
     * separators, or a period to represent the current directory, or double
     * dots to represent the parent directory. Basically, anything using this
     * prefix kind of has to be an absolute path for it to work.
     */
    rv +=
    runWindowsOnlyTest("Test isAbsolute('\\\\?\\a:\\Long\\Path')", []() {
        return
            Path::isAbsolute("\\\\?\\a:\\Long\\Path") &&
            Path::isAbsolute("\\\\?\\UNC\\Long\\Path");
    });

    rv +=
    runWindowsOnlyTest("Test !isAbsolute('..\\File.ext')", []() {
        return !Path::isAbsolute("..\\File.ext");
    });

    rv +=
    runWindowsOnlyTest("Test !isAbsolute('.\\File.ext')", []() {
        return !Path::isAbsolute(".\\File.ext");
    });

    rv +=
    runWindowsOnlyTest("Test !isAbsolute('<driveletter>:RelativePath')", []() {
        return
            !Path::isAbsolute("A:RelativePath") &&
            !Path::isAbsolute("a:RelativePath") &&
            !Path::isAbsolute("z:RelativePath") &&
            !Path::isAbsolute("Z:RelativePath");
    });

    rv +=
    runWindowsOnlyTest("Test !isAbsolute('A\\F\\ile.ext')", []() {
        return !Path::isAbsolute("A\\F\\ile.ext");
    });

	return rv;
}
<commit_msg>Whitespace (VS is configured to use tabs apparently)<commit_after>/* vim: set ts=4 sw=4 tw=79 et :*/
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "TestHarness.h"

#include "base/io/Path.h"

int main(int argc, char* argv[]) {
    int rv = 0;

    /// Path::isAbsolute Tests

    rv +=
    runTest("Test empty string !isAbsolute", []() {
        return !Path::isAbsolute("");
    });

    rv +=
    runPosixOnlyTest("Test isAbsolute('/a/b/c')", []() {
        return Path::isAbsolute("/a/b/c");
    });

    rv +=
    runPosixOnlyTest("Test !isAbsolute('a/b/c')", []() {
        return !Path::isAbsolute("a/b/c");
    });

    rv +=
    runPosixOnlyTest("Test !isAbsolute('../a/b')", []() {
        return !Path::isAbsolute("../a/b");
    });

    rv +=
    runPosixOnlyTest("Test !isAbsolute('./a/b'", []() {
        return !Path::isAbsolute("./a/b");
    });

    rv +=
    runWindowsOnlyTest("Test short/invalid path", []() {
        return
            !Path::isAbsolute("C:") &&
            !Path::isAbsolute("C")  &&
            !Path::isAbsolute("F:F");
    });

    rv +=
    runWindowsOnlyTest("Test isAbsolute('<driveletter>:\\Hello')", []() {
        return
            Path::isAbsolute("a:\\Hello") &&
            Path::isAbsolute("A:\\Hello") &&
            Path::isAbsolute("z:\\Hello") &&
            Path::isAbsolute("Z:\\Hello");
    });

    // Windows supports forward slashes with this form of path
    rv +=
    runWindowsOnlyTest("Test isAbsolute('<driveletter>:/Hello')", []() {
        return
            Path::isAbsolute("a:/Hello") &&
            Path::isAbsolute("A:/Hello") &&
            Path::isAbsolute("z:/Hello") &&
            Path::isAbsolute("Z:/Hello");
    });

    rv +=
    runWindowsOnlyTest("Test isAbsolute('\\\\Path')", []() {
        return Path::isAbsolute("\\\\Path");
    });

    rv +=
    runWindowsOnlyTest("Test isAbsolute('//Path/')", []() {
        return Path::isAbsolute("//Path/");
    });

    rv +=
    runWindowsOnlyTest("Test isAbsolute('\\Single\\Slash')", []() {
        return Path::isAbsolute("\\Single\\Slash");
    });

    /*
     * This '\\?\' prefix is not used as part of the path itself. They indicate
     * that the path should be passed to the system with minimal modification,
     * which means that you cannot use forward slashes to represent path
     * separators, or a period to represent the current directory, or double
     * dots to represent the parent directory. Basically, anything using this
     * prefix kind of has to be an absolute path for it to work.
     */
    rv +=
    runWindowsOnlyTest("Test isAbsolute('\\\\?\\a:\\Long\\Path')", []() {
        return
            Path::isAbsolute("\\\\?\\a:\\Long\\Path") &&
            Path::isAbsolute("\\\\?\\UNC\\Long\\Path");
    });

    rv +=
    runWindowsOnlyTest("Test !isAbsolute('..\\File.ext')", []() {
        return !Path::isAbsolute("..\\File.ext");
    });

    rv +=
    runWindowsOnlyTest("Test !isAbsolute('.\\File.ext')", []() {
        return !Path::isAbsolute(".\\File.ext");
    });

    rv +=
    runWindowsOnlyTest("Test !isAbsolute('<driveletter>:RelativePath')", []() {
        return
            !Path::isAbsolute("A:RelativePath") &&
            !Path::isAbsolute("a:RelativePath") &&
            !Path::isAbsolute("z:RelativePath") &&
            !Path::isAbsolute("Z:RelativePath");
    });

    rv +=
    runWindowsOnlyTest("Test !isAbsolute('A\\F\\ile.ext')", []() {
        return !Path::isAbsolute("A\\F\\ile.ext");
    });

    return rv;
}
<|endoftext|>


<commit_before>#include <numeric>

#include <pqxx/transaction>

#include "../test_helpers.hxx"

namespace
{
void test_move_constructor()
{
  pqxx::connection c1;
  PQXX_CHECK(c1.is_open(), "New connection is not open.");

  pqxx::connection c2{std::move(c1)};

  PQXX_CHECK(not c1.is_open(), "Moving did not close original connection.");
  PQXX_CHECK(c2.is_open(), "Moved constructor is not open.");

  pqxx::work tx{c2};
  PQXX_CHECK_EQUAL(tx.query_value<int>("SELECT 5"), 5, "Weird result!");

  PQXX_CHECK_THROWS(
    pqxx::connection c3{std::move(c2)}, pqxx::usage_error,
    "Moving a connection with a transaction open should be an error.");
}

void test_move_assign()
{
  pqxx::connection c1;
  pqxx::connection c2;

  c2.close();

  c2 = std::move(c1);

  PQXX_CHECK(not c1.is_open(), "Connection still open after being moved out.");
  PQXX_CHECK(c2.is_open(), "Moved constructor is not open.");

  {
    pqxx::work tx1{c2};
    PQXX_CHECK_EQUAL(tx1.query_value<int>("SELECT 8"), 8, "What!?");

    pqxx::connection c3;
    PQXX_CHECK_THROWS(
      c3 = std::move(c2), pqxx::usage_error,
      "Moving a connection with a transaction open should be an error.");

    PQXX_CHECK_THROWS(
      c2 = std::move(c3), pqxx::usage_error,
      "Moving a connection onto one with a transaction open should be "
      "an error.");
  }

  // After failed move attempts, the connection is still usable.
  pqxx::work tx2{c2};
  PQXX_CHECK_EQUAL(tx2.query_value<int>("SELECT 6"), 6, "Huh!?");
}

void test_encrypt_password()
{
  pqxx::connection c;
  auto pw{c.encrypt_password("user", "password")};
  PQXX_CHECK(not std::empty(pw), "Encrypted password was empty.");
  PQXX_CHECK_EQUAL(
    std::strlen(pw.c_str()), std::size(pw),
    "Encrypted password contains a null byte.");
}

void test_connection_string()
{
  pqxx::connection c;
  std::string const connstr{c.connection_string()};

  if (std::getenv("PGUSER") == nullptr)
  {
    PQXX_CHECK(
      connstr.find("user=" + std::string{c.username()}) != std::string::npos,
      "Connection string did not specify user name: " + connstr);
  }
  else
  {
    PQXX_CHECK(
      connstr.find("user=" + std::string{c.username()}) == std::string::npos,
      "Connection string specified user name, even when using default: " +
        connstr);
  }
}

#if defined(PQXX_HAVE_CONCEPTS)
template<typename STR> std::size_t length(STR const &str)
{
  return std::size(str);
}

std::size_t length(char const str[])
{
  return std::strlen(str);
}
#endif // PQXX_HAVE_CONCEPTS

template<typename MAP> void test_params_type()
{
#if defined(PQXX_HAVE_CONCEPTS)
  using item_t = std::remove_reference_t<
    decltype(*std::declval<std::ranges::iterator_t<MAP>>())>;
  using key_t = decltype(std::get<0>(std::declval<item_t>()));
  using value_t = decltype(std::get<1>(std::declval<item_t>()));

  // Set some parameters that are relatively safe to change arbitrarily.
  MAP const params{{
    {key_t{"application_name"}, value_t{"pqxx-test"}},
    {key_t{"connect_timeout"}, value_t{"96"}},
    {key_t{"keepalives_idle"}, value_t{"771"}},
  }};

  // Can we create a connection from these parameters?
  pqxx::connection c{params};

  // Check that the parameters came through in the connection string.
  // We don't know the exact format, but the parameters have to be in there.
  auto const min_size{std::accumulate(
    std::cbegin(params), std::cend(params), std::size(params) - 1,
    [](auto count, auto item) {
      return count + length(std::get<0>(item)) + 1 + length(std::get<1>(item));
    })};

  auto const connstr{c.connection_string()};
  PQXX_CHECK_GREATER_EQUAL(
    std::size(connstr), min_size,
    "Connection string can't possibly contain the options we gave.");
  for (auto const &[key, value] : params)
  {
    PQXX_CHECK_NOT_EQUAL(
      connstr.find(key), std::string::npos,
      "Could not find param name '" + std::string{key} +
        "' in connection string: " + connstr);
    PQXX_CHECK_NOT_EQUAL(
      connstr.find(value), std::string::npos,
      "Could not find value for '" + std::string{value} +
        "' in connection string: " + connstr);
  }
#endif // PQXX_HAVE_CONCEPTS
}

void test_connection_params()
{
  // Connecting in this way supports a wide variety of formats for the
  // parameters.
  test_params_type<std::map<char const *, char const *>>();
  test_params_type<std::map<pqxx::zview, pqxx::zview>>();
  test_params_type<std::map<std::string, std::string>>();
  test_params_type<std::map<std::string, pqxx::zview>>();
  test_params_type<std::map<pqxx::zview, char const *>>();
  test_params_type<std::vector<std::tuple<char const *, char const *>>>();
  test_params_type<std::vector<std::tuple<pqxx::zview, std::string>>>();
  test_params_type<std::vector<std::pair<std::string, char const *>>>();
  test_params_type<std::vector<std::array<std::string, 2>>>();
}

PQXX_REGISTER_TEST(test_move_constructor);
PQXX_REGISTER_TEST(test_move_assign);
PQXX_REGISTER_TEST(test_encrypt_password);
PQXX_REGISTER_TEST(test_connection_string);
PQXX_REGISTER_TEST(test_connection_params);
} // namespace
<commit_msg>Unit-test connection string types.<commit_after>#include <numeric>

#include <pqxx/transaction>

#include "../test_helpers.hxx"

namespace
{
void test_connection_string_constructor()
{
  pqxx::connection c1{""};
  pqxx::connection c2{std::string{}};
}

void test_move_constructor()
{
  pqxx::connection c1;
  PQXX_CHECK(c1.is_open(), "New connection is not open.");

  pqxx::connection c2{std::move(c1)};

  PQXX_CHECK(not c1.is_open(), "Moving did not close original connection.");
  PQXX_CHECK(c2.is_open(), "Moved constructor is not open.");

  pqxx::work tx{c2};
  PQXX_CHECK_EQUAL(tx.query_value<int>("SELECT 5"), 5, "Weird result!");

  PQXX_CHECK_THROWS(
    pqxx::connection c3{std::move(c2)}, pqxx::usage_error,
    "Moving a connection with a transaction open should be an error.");
}

void test_move_assign()
{
  pqxx::connection c1;
  pqxx::connection c2;

  c2.close();

  c2 = std::move(c1);

  PQXX_CHECK(not c1.is_open(), "Connection still open after being moved out.");
  PQXX_CHECK(c2.is_open(), "Moved constructor is not open.");

  {
    pqxx::work tx1{c2};
    PQXX_CHECK_EQUAL(tx1.query_value<int>("SELECT 8"), 8, "What!?");

    pqxx::connection c3;
    PQXX_CHECK_THROWS(
      c3 = std::move(c2), pqxx::usage_error,
      "Moving a connection with a transaction open should be an error.");

    PQXX_CHECK_THROWS(
      c2 = std::move(c3), pqxx::usage_error,
      "Moving a connection onto one with a transaction open should be "
      "an error.");
  }

  // After failed move attempts, the connection is still usable.
  pqxx::work tx2{c2};
  PQXX_CHECK_EQUAL(tx2.query_value<int>("SELECT 6"), 6, "Huh!?");
}

void test_encrypt_password()
{
  pqxx::connection c;
  auto pw{c.encrypt_password("user", "password")};
  PQXX_CHECK(not std::empty(pw), "Encrypted password was empty.");
  PQXX_CHECK_EQUAL(
    std::strlen(pw.c_str()), std::size(pw),
    "Encrypted password contains a null byte.");
}

void test_connection_string()
{
  pqxx::connection c;
  std::string const connstr{c.connection_string()};

  if (std::getenv("PGUSER") == nullptr)
  {
    PQXX_CHECK(
      connstr.find("user=" + std::string{c.username()}) != std::string::npos,
      "Connection string did not specify user name: " + connstr);
  }
  else
  {
    PQXX_CHECK(
      connstr.find("user=" + std::string{c.username()}) == std::string::npos,
      "Connection string specified user name, even when using default: " +
        connstr);
  }
}

#if defined(PQXX_HAVE_CONCEPTS)
template<typename STR> std::size_t length(STR const &str)
{
  return std::size(str);
}

std::size_t length(char const str[])
{
  return std::strlen(str);
}
#endif // PQXX_HAVE_CONCEPTS

template<typename MAP> void test_params_type()
{
#if defined(PQXX_HAVE_CONCEPTS)
  using item_t = std::remove_reference_t<
    decltype(*std::declval<std::ranges::iterator_t<MAP>>())>;
  using key_t = decltype(std::get<0>(std::declval<item_t>()));
  using value_t = decltype(std::get<1>(std::declval<item_t>()));

  // Set some parameters that are relatively safe to change arbitrarily.
  MAP const params{{
    {key_t{"application_name"}, value_t{"pqxx-test"}},
    {key_t{"connect_timeout"}, value_t{"96"}},
    {key_t{"keepalives_idle"}, value_t{"771"}},
  }};

  // Can we create a connection from these parameters?
  pqxx::connection c{params};

  // Check that the parameters came through in the connection string.
  // We don't know the exact format, but the parameters have to be in there.
  auto const min_size{std::accumulate(
    std::cbegin(params), std::cend(params), std::size(params) - 1,
    [](auto count, auto item) {
      return count + length(std::get<0>(item)) + 1 + length(std::get<1>(item));
    })};

  auto const connstr{c.connection_string()};
  PQXX_CHECK_GREATER_EQUAL(
    std::size(connstr), min_size,
    "Connection string can't possibly contain the options we gave.");
  for (auto const &[key, value] : params)
  {
    PQXX_CHECK_NOT_EQUAL(
      connstr.find(key), std::string::npos,
      "Could not find param name '" + std::string{key} +
        "' in connection string: " + connstr);
    PQXX_CHECK_NOT_EQUAL(
      connstr.find(value), std::string::npos,
      "Could not find value for '" + std::string{value} +
        "' in connection string: " + connstr);
  }
#endif // PQXX_HAVE_CONCEPTS
}

void test_connection_params()
{
  // Connecting in this way supports a wide variety of formats for the
  // parameters.
  test_params_type<std::map<char const *, char const *>>();
  test_params_type<std::map<pqxx::zview, pqxx::zview>>();
  test_params_type<std::map<std::string, std::string>>();
  test_params_type<std::map<std::string, pqxx::zview>>();
  test_params_type<std::map<pqxx::zview, char const *>>();
  test_params_type<std::vector<std::tuple<char const *, char const *>>>();
  test_params_type<std::vector<std::tuple<pqxx::zview, std::string>>>();
  test_params_type<std::vector<std::pair<std::string, char const *>>>();
  test_params_type<std::vector<std::array<std::string, 2>>>();
}

PQXX_REGISTER_TEST(test_connection_string_constructor);
PQXX_REGISTER_TEST(test_move_constructor);
PQXX_REGISTER_TEST(test_move_assign);
PQXX_REGISTER_TEST(test_encrypt_password);
PQXX_REGISTER_TEST(test_connection_string);
PQXX_REGISTER_TEST(test_connection_params);
} // namespace
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkCubeSource.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <math.h>
#include "vtkCubeSource.h"
#include "vtkPoints.h"
#include "vtkNormals.h"

vtkCubeSource::vtkCubeSource(float xL, float yL, float zL)
{
  this->XLength = fabs(xL);
  this->YLength = fabs(yL);
  this->ZLength = fabs(zL);

  this->Center[0] = 0.0;
  this->Center[1] = 0.0;
  this->Center[2] = 0.0;
}

void vtkCubeSource::Execute()
{
  float x[3], n[3];
  int numPolys=6, numPts=24;
  int i, j, k;
  int pts[4];
  vtkPoints *newPoints;
  vtkNormals *newNormals;
  vtkCellArray *newPolys;
  vtkPolyData *output = this->GetOutput();

  vtkDebugMacro(<<"Creating polygonal cube");
//
// Set things up; allocate memory
//
  newPoints = vtkPoints::New();
  newPoints->Allocate(numPts);
  newNormals = vtkNormals::New();
  newNormals->Allocate(numPts);

  newPolys = vtkCellArray::New();
  newPolys->Allocate(newPolys->EstimateSize(numPolys,4));
//
// Generate points and normals
//
  numPts = 0;

  for (x[0]=Center[0]-this->XLength/2.0, n[0]=(-1.0), n[1]=n[2]=0.0, i=0;
  i<2; i++, x[0]+=this->XLength, n[0]+=2.0)
    {
    for (x[1]=Center[1]-this->YLength/2.0, j=0; j<2;
    j++, x[1]+=this->YLength)
      {
      for (x[2]=Center[2]-this->ZLength/2.0, k=0; k<2;
      k++, x[2]+=this->ZLength)
        {
        newPoints->InsertNextPoint(x);
        newNormals->InsertNextNormal(n);
        }
      }
    }
  pts[0] = 0; pts[1] = 1; pts[2] = 3; pts[3] = 2;
  newPolys->InsertNextCell(4,pts);
  pts[0] = 4; pts[1] = 6; pts[2] = 7; pts[3] = 5;
  newPolys->InsertNextCell(4,pts);

  for (x[1]=Center[1]-this->YLength/2.0, n[1]=(-1.0), n[0]=n[2]=0.0, i=0;
  i<2; i++, x[1]+=this->YLength, n[1]+=2.0)
    {
    for (x[0]=Center[0]-this->XLength/2.0, j=0; j<2;
    j++, x[0]+=this->XLength)
      {
      for (x[2]=Center[2]-this->ZLength/2.0, k=0; k<2;
      k++, x[2]+=this->ZLength)
        {
        newPoints->InsertNextPoint(x);
        newNormals->InsertNextNormal(n);
        }
      }
    }
  pts[0] = 8; pts[1] = 10; pts[2] = 11; pts[3] = 9;
  newPolys->InsertNextCell(4,pts);
  pts[0] = 12; pts[1] = 13; pts[2] = 15; pts[3] = 14;
  newPolys->InsertNextCell(4,pts);

  for (x[2]=Center[2]-this->ZLength/2.0, n[2]=(-1.0), n[0]=n[1]=0.0, i=0;
  i<2; i++, x[2]+=this->ZLength, n[2]+=2.0)
    {
    for (x[1]=Center[1]-this->YLength/2.0, j=0; j<2;
    j++, x[1]+=this->YLength)
      {
      for (x[0]=Center[0]-this->XLength/2.0, k=0; k<2;
      k++, x[0]+=this->XLength)
        {
        newPoints->InsertNextPoint(x);
        newNormals->InsertNextNormal(n);
        }
      }
    }
  pts[0] = 16; pts[1] = 18; pts[2] = 19; pts[3] = 17;
  newPolys->InsertNextCell(4,pts);
  pts[0] = 20; pts[1] = 21; pts[2] = 23; pts[3] = 22;
  newPolys->InsertNextCell(4,pts);
//
// Update ourselves and release memory
//
  output->SetPoints(newPoints);
  newPoints->Delete();

  output->GetPointData()->SetNormals(newNormals);
  newNormals->Delete();

  newPolys->Squeeze(); // since we've estimated size; reclaim some space
  output->SetPolys(newPolys);
  newPolys->Delete();
}

// Description:
// Convenience method allows creation of cube by specifying bounding box.
void vtkCubeSource::SetBounds(float bounds[6])
{
  this->SetXLength(bounds[1]-bounds[0]);
  this->SetYLength(bounds[3]-bounds[2]);
  this->SetZLength(bounds[5]-bounds[4]);

  this->SetCenter((bounds[1]+bounds[0])/2.0, (bounds[3]+bounds[2])/2.0,
                  (bounds[5]+bounds[4])/2.0);
}

void vtkCubeSource::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPolyDataSource::PrintSelf(os,indent);

  os << indent << "X Length: " << this->XLength << "\n";
  os << indent << "Y Length: " << this->YLength << "\n";
  os << indent << "Z Length: " << this->ZLength << "\n";
  os << indent << "Center: (" << this->Center[0] << ", "
               << this->Center[1] << ", " << this->Center[2] << ")\n";
}

<commit_msg>ENH: Added texture mapping to vtkCubeSource<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkCubeSource.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <math.h>
#include "vtkCubeSource.h"
#include "vtkPoints.h"
#include "vtkNormals.h"

vtkCubeSource::vtkCubeSource(float xL, float yL, float zL)
{
  this->XLength = fabs(xL);
  this->YLength = fabs(yL);
  this->ZLength = fabs(zL);

  this->Center[0] = 0.0;
  this->Center[1] = 0.0;
  this->Center[2] = 0.0;
}

void vtkCubeSource::Execute()
{
  float x[3], n[3], tc[3];
  int numPolys=6, numPts=24;
  int i, j, k;
  int pts[4];
  vtkPoints *newPoints;
  vtkNormals *newNormals;
  vtkTCoords *newTCoords; // CCS 7/27/98 Added for Texture Mapping
  vtkCellArray *newPolys;
  vtkPolyData *output = this->GetOutput();

  vtkDebugMacro(<<"Creating polygonal cube");
//
// Set things up; allocate memory
//
  newPoints = vtkPoints::New();
  newPoints->Allocate(numPts);
  newNormals = vtkNormals::New();
  newNormals->Allocate(numPts);
  newTCoords = vtkTCoords::New();
  newTCoords->Allocate(numPts);

  newPolys = vtkCellArray::New();
  newPolys->Allocate(newPolys->EstimateSize(numPolys,4));
//
// Generate points and normals
//
  numPts = 0;

  for (x[0]=Center[0]-this->XLength/2.0, n[0]=(-1.0), n[1]=n[2]=0.0, i=0;
  i<2; i++, x[0]+=this->XLength, n[0]+=2.0)
    {
    for (x[1]=Center[1]-this->YLength/2.0, j=0; j<2;
    j++, x[1]+=this->YLength)
      {
      tc[1] =  x[1] + 0.5;
      for (x[2]=Center[2]-this->ZLength/2.0, k=0; k<2;
      k++, x[2]+=this->ZLength)
        {
	tc[0] = (x[2] + 0.5) * ( 1 - 2*i );
        newPoints->InsertNextPoint(x);
        newTCoords->InsertNextTCoord(tc);
        newNormals->InsertNextNormal(n);
        }
      }
    }
  pts[0] = 0; pts[1] = 1; pts[2] = 3; pts[3] = 2;
  newPolys->InsertNextCell(4,pts);
  pts[0] = 4; pts[1] = 6; pts[2] = 7; pts[3] = 5;
  newPolys->InsertNextCell(4,pts);

  for (x[1]=Center[1]-this->YLength/2.0, n[1]=(-1.0), n[0]=n[2]=0.0, i=0;
  i<2; i++, x[1]+=this->YLength, n[1]+=2.0)
    {
    for (x[0]=Center[0]-this->XLength/2.0, j=0; j<2;
    j++, x[0]+=this->XLength)
      {
      tc[0] = ( x[0] + 0.5 ) * ( 2*i - 1 );
      for (x[2]=Center[2]-this->ZLength/2.0, k=0; k<2;
      k++, x[2]+=this->ZLength)
        {
	tc[1] = ( x[2] + 0.5 ) * -1;
        newPoints->InsertNextPoint(x);
        newTCoords->InsertNextTCoord(tc);
        newNormals->InsertNextNormal(n);
        }
      }
    }
  pts[0] = 8; pts[1] = 10; pts[2] = 11; pts[3] = 9;
  newPolys->InsertNextCell(4,pts);
  pts[0] = 12; pts[1] = 13; pts[2] = 15; pts[3] = 14;
  newPolys->InsertNextCell(4,pts);

  for (x[2]=Center[2]-this->ZLength/2.0, n[2]=(-1.0), n[0]=n[1]=0.0, i=0;
  i<2; i++, x[2]+=this->ZLength, n[2]+=2.0)
    {
    for (x[1]=Center[1]-this->YLength/2.0, j=0; j<2;
    j++, x[1]+=this->YLength)
      {
      tc[1] = x[1] + 0.5;
      for (x[0]=Center[0]-this->XLength/2.0, k=0; k<2;
      k++, x[0]+=this->XLength)
        {
	tc[0] = ( x[0] + 0.5 ) * ( 2*i - 1 );
        newPoints->InsertNextPoint(x);
	newTCoords->InsertNextTCoord(tc);
        newNormals->InsertNextNormal(n);
        }
      }
    }
  pts[0] = 16; pts[1] = 18; pts[2] = 19; pts[3] = 17;
  newPolys->InsertNextCell(4,pts);
  pts[0] = 20; pts[1] = 21; pts[2] = 23; pts[3] = 22;
  newPolys->InsertNextCell(4,pts);
//
// Update ourselves and release memory
//
  output->SetPoints(newPoints);
  newPoints->Delete();

  output->GetPointData()->SetNormals(newNormals);
  newNormals->Delete();

  output->GetPointData()->SetTCoords(newTCoords);
  newTCoords->Delete();

  newPolys->Squeeze(); // since we've estimated size; reclaim some space
  output->SetPolys(newPolys);
  newPolys->Delete();
}

// Description:
// Convenience method allows creation of cube by specifying bounding box.
void vtkCubeSource::SetBounds(float bounds[6])
{
  this->SetXLength(bounds[1]-bounds[0]);
  this->SetYLength(bounds[3]-bounds[2]);
  this->SetZLength(bounds[5]-bounds[4]);

  this->SetCenter((bounds[1]+bounds[0])/2.0, (bounds[3]+bounds[2])/2.0,
                  (bounds[5]+bounds[4])/2.0);
}

void vtkCubeSource::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPolyDataSource::PrintSelf(os,indent);

  os << indent << "X Length: " << this->XLength << "\n";
  os << indent << "Y Length: " << this->YLength << "\n";
  os << indent << "Z Length: " << this->ZLength << "\n";
  os << indent << "Center: (" << this->Center[0] << ", "
               << this->Center[1] << ", " << this->Center[2] << ")\n";
}

<|endoftext|>


<commit_before>/*
    AddressBookSelectorWidget

    Copyright (c) 2005 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Based on LinkAddressBookUI whose code was shamelessly stolen from
    kopete's add new contact wizard, used in Konversation, and then
    reappropriated by Kopete.

    LinkAddressBookUI:
    Copyright (c) 2004 by John Tapsell           <john@geola.co.uk>
    Copyright (c) 2003-2005 by Will Stephenson   <will@stevello.free-online.co.uk>
    Copyright (c) 2002 by Nick Betcher           <nbetcher@kde.org>
    Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Kopete    (c) 2002-2004 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qcheckbox.h>
#include <kapplication.h>
#include <kconfig.h>
#include <klocale.h>
#include <kiconloader.h>

#include <kdeversion.h>
#include <kinputdialog.h>

#include <kpushbutton.h>
#include <kactivelabel.h>
#include <kdebug.h>
#include <klistview.h>
#include <klistviewsearchline.h>
#include <qlabel.h>
#include <qtooltip.h>
#include <q3whatsthis.h>

#include "addressbookselectorwidget.h"
#include <addresseeitem.h>
#include "kabcpersistence.h"

using namespace Kopete::UI;

namespace Kopete
{
namespace UI
{

AddressBookSelectorWidget::AddressBookSelectorWidget( QWidget *parent, const char *name )
		: AddressBookSelectorWidget_Base( parent, name )
{
	m_addressBook = Kopete::KABCPersistence::self()->addressBook();

	// Addressee validation connections
	connect( addAddresseeButton, SIGNAL( clicked() ), SLOT( slotAddAddresseeClicked() ) );
	connect( addAddresseeButton, SIGNAL( clicked() ), SIGNAL( addAddresseeClicked() ) );

	connect( addresseeListView, SIGNAL( clicked(Q3ListViewItem * ) ),
			SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );
	connect( addresseeListView, SIGNAL( selectionChanged( Q3ListViewItem * ) ),
			SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );
	connect( addresseeListView, SIGNAL( spacePressed( Q3ListViewItem * ) ),
			SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );

	connect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) );

	//We should add a clear KAction here.  But we can't really do that with a designer file :\  this sucks

	addresseeListView->setColumnText(2, SmallIconSet(QString::fromLatin1("email")), i18n("Email"));

	kListViewSearchLine->setListView(addresseeListView);
	slotLoadAddressees();

	addresseeListView->setColumnWidthMode(0, Q3ListView::Manual);
	addresseeListView->setColumnWidth(0, 63); //Photo is 60, and it's nice to have a small gap, imho
}

AddressBookSelectorWidget::~AddressBookSelectorWidget()
{
	disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) );
}

KABC::Addressee AddressBookSelectorWidget::addressee()
{
	AddresseeItem *item = 0L;
	item = static_cast<AddresseeItem *>( addresseeListView->selectedItem() );

	if ( item )
		m_addressee = item->addressee();

	return m_addressee;
}

void AddressBookSelectorWidget::selectAddressee( const QString &uid )
{
	// iterate trough list view
	Q3ListViewItemIterator it( addresseeListView );
	while( it.current() )
	{
		AddresseeItem *addrItem = (AddresseeItem *) it.current();
		if ( addrItem->addressee().uid() == uid )
		{
			// select the contact item
			addresseeListView->setSelected( addrItem, true );
			addresseeListView->ensureItemVisible( addrItem );
		}
		++it;
	}
}

bool AddressBookSelectorWidget::addresseeSelected()
{
	return addresseeListView->selectedItem() ? true : false;
}

/**  Read in contacts from addressbook, and select the contact that is for our nick. */
void AddressBookSelectorWidget::slotLoadAddressees()
{
	addresseeListView->clear();
	KABC::AddressBook::Iterator it;
	AddresseeItem *addr;
	for( it = m_addressBook->begin(); it != m_addressBook->end(); ++it )
	{
		 addr = new AddresseeItem( addresseeListView, (*it));
	}

}

void AddressBookSelectorWidget::setLabelMessage( const QString &msg )
{
	lblHeader->setText(msg);
}

void AddressBookSelectorWidget::slotAddAddresseeClicked()
{
	// Pop up add addressee dialog
	QString addresseeName = KInputDialog::getText( i18n( "New Address Book Entry" ), i18n( "Name the new entry:" ), QString::null, 0, this );

	if ( !addresseeName.isEmpty() )
	{
		KABC::Addressee addr;
		addr.setNameFromString( addresseeName );
		m_addressBook->insertAddressee(addr);
		Kopete::KABCPersistence::self()->writeAddressBook( 0 );
		slotLoadAddressees();
		// select the addressee we just added
		Q3ListViewItem * added = addresseeListView->findItem( addresseeName, 1 );
		addresseeListView->setSelected( added, true );
		addresseeListView->ensureItemVisible( added );
	}
}

} // namespace UI
} // namespace Kopete

#include "addressbookselectorwidget.moc"

// vim: set noet ts=4 sts=4 sw=4:

<commit_msg>backport  BUG: 110896<commit_after>/*
    AddressBookSelectorWidget

    Copyright (c) 2005 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Based on LinkAddressBookUI whose code was shamelessly stolen from
    kopete's add new contact wizard, used in Konversation, and then
    reappropriated by Kopete.

    LinkAddressBookUI:
    Copyright (c) 2004 by John Tapsell           <john@geola.co.uk>
    Copyright (c) 2003-2005 by Will Stephenson   <will@stevello.free-online.co.uk>
    Copyright (c) 2002 by Nick Betcher           <nbetcher@kde.org>
    Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Kopete    (c) 2002-2004 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qcheckbox.h>
#include <kapplication.h>
#include <kconfig.h>
#include <klocale.h>
#include <kiconloader.h>

#include <kdeversion.h>
#include <kinputdialog.h>

#include <kpushbutton.h>
#include <kactivelabel.h>
#include <kdebug.h>
#include <klistview.h>
#include <klistviewsearchline.h>
#include <qlabel.h>
#include <qtooltip.h>
#include <q3whatsthis.h>

#include "addressbookselectorwidget.h"
#include <addresseeitem.h>
#include "kabcpersistence.h"

using namespace Kopete::UI;

namespace Kopete
{
namespace UI
{

AddressBookSelectorWidget::AddressBookSelectorWidget( QWidget *parent, const char *name )
		: AddressBookSelectorWidget_Base( parent, name )
{
	m_addressBook = Kopete::KABCPersistence::self()->addressBook();

	// Addressee validation connections
	connect( addAddresseeButton, SIGNAL( clicked() ), SLOT( slotAddAddresseeClicked() ) );
	connect( addAddresseeButton, SIGNAL( clicked() ), SIGNAL( addAddresseeClicked() ) );

	connect( addresseeListView, SIGNAL( clicked(Q3ListViewItem * ) ),
			SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );
	connect( addresseeListView, SIGNAL( selectionChanged( Q3ListViewItem * ) ),
			SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );
	connect( addresseeListView, SIGNAL( spacePressed( Q3ListViewItem * ) ),
			SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );

	connect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) );

	//We should add a clear KAction here.  But we can't really do that with a designer file :\  this sucks

	addresseeListView->setColumnText(2, SmallIconSet(QString::fromLatin1("email")), i18n("Email"));

	kListViewSearchLine->setListView(addresseeListView);
	slotLoadAddressees();

	addresseeListView->setColumnWidthMode(0, Q3ListView::Manual);
	addresseeListView->setColumnWidth(0, 63); //Photo is 60, and it's nice to have a small gap, imho
}

AddressBookSelectorWidget::~AddressBookSelectorWidget()
{
	disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) );
}

KABC::Addressee AddressBookSelectorWidget::addressee()
{
	AddresseeItem *item = 0L;
	item = static_cast<AddresseeItem *>( addresseeListView->selectedItem() );

	if ( item )
		m_addressee = item->addressee();

	return m_addressee;
}

void AddressBookSelectorWidget::selectAddressee( const QString &uid )
{
	// iterate trough list view
	Q3ListViewItemIterator it( addresseeListView );
	while( it.current() )
	{
		AddresseeItem *addrItem = (AddresseeItem *) it.current();
		if ( addrItem->addressee().uid() == uid )
		{
			// select the contact item
			addresseeListView->setSelected( addrItem, true );
			addresseeListView->ensureItemVisible( addrItem );
		}
		++it;
	}
}

bool AddressBookSelectorWidget::addresseeSelected()
{
	return addresseeListView->selectedItem() ? true : false;
}

/**  Read in contacts from addressbook, and select the contact that is for our nick. */
void AddressBookSelectorWidget::slotLoadAddressees()
{
	addresseeListView->clear();
	KABC::AddressBook::Iterator it;
	AddresseeItem *addr;
	for( it = m_addressBook->begin(); it != m_addressBook->end(); ++it )
	{
		 addr = new AddresseeItem( addresseeListView, (*it));
	}

}

void AddressBookSelectorWidget::setLabelMessage( const QString &msg )
{
	lblHeader->setText(msg);
}

void AddressBookSelectorWidget::slotAddAddresseeClicked()
{
	// Pop up add addressee dialog
	QString addresseeName = KInputDialog::getText( i18n( "New Address Book Entry" ), i18n( "Name the new entry:" ), QString::null, 0, this );

	if ( !addresseeName.isEmpty() )
	{
		KABC::Addressee addr;
		addr.setNameFromString( addresseeName );
		m_addressBook->insertAddressee(addr);
		Kopete::KABCPersistence::self()->writeAddressBook( 0 );
		slotLoadAddressees();
		// select the addressee we just added
		Q3ListViewItem * added = addresseeListView->findItem( addresseeName, 1 );
		kListViewSearchLine->clear();
		kListViewSearchLine->updateSearch();
		addresseeListView->setSelected( added, true );
		addresseeListView->ensureItemVisible( added );
	}
}

} // namespace UI
} // namespace Kopete

#include "addressbookselectorwidget.moc"

// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>//===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains code used to execute the program utilizing one of the
// various ways of running LLVM bytecode.
//
//===----------------------------------------------------------------------===//

#include "BugDriver.h"
#include "llvm/Support/ToolRunner.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/SystemUtils.h"
#include <fstream>
using namespace llvm;

namespace {
  // OutputType - Allow the user to specify the way code should be run, to test
  // for miscompilation.
  //
  enum OutputType {
    AutoPick, RunLLI, RunJIT, RunLLC, RunCBE
  };

  cl::opt<OutputType>
  InterpreterSel(cl::desc("Specify how LLVM code should be executed:"),
                 cl::values(clEnumValN(AutoPick, "auto", "Use best guess"),
                            clEnumValN(RunLLI, "run-int",
                                       "Execute with the interpreter"),
                            clEnumValN(RunJIT, "run-jit", "Execute with JIT"),
                            clEnumValN(RunLLC, "run-llc", "Compile with LLC"),
                            clEnumValN(RunCBE, "run-cbe", "Compile with CBE"),
                            clEnumValEnd),
                 cl::init(AutoPick));

  cl::opt<bool>
  CheckProgramExitCode("check-exit-code",
                   cl::desc("Assume nonzero exit code is failure (default on)"),
                       cl::init(true));

  cl::opt<std::string>
  InputFile("input", cl::init("/dev/null"),
            cl::desc("Filename to pipe in as stdin (default: /dev/null)"));

  cl::list<std::string>
  AdditionalSOs("additional-so",
                cl::desc("Additional shared objects to load "
                         "into executing programs"));

  cl::opt<unsigned>
  TimeoutValue("timeout", cl::init(300), cl::value_desc("seconds"),
               cl::desc("Number of seconds program is allowed to run before it "
                        "is killed (default is 300s), 0 disables timeout"));
}

namespace llvm {
  // Anything specified after the --args option are taken as arguments to the
  // program being debugged.
  cl::list<std::string>
  InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
            cl::ZeroOrMore, cl::PositionalEatsArgs);

  cl::list<std::string>
  ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
           cl::ZeroOrMore, cl::PositionalEatsArgs);
}

//===----------------------------------------------------------------------===//
// BugDriver method implementation
//

/// initializeExecutionEnvironment - This method is used to set up the
/// environment for executing LLVM programs.
///
bool BugDriver::initializeExecutionEnvironment() {
  std::cout << "Initializing execution environment: ";

  // Create an instance of the AbstractInterpreter interface as specified on
  // the command line
  cbe = 0;
  std::string Message;

  switch (InterpreterSel) {
  case AutoPick:
    InterpreterSel = RunCBE;
    Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
                                                       &ToolArgv);
    if (!Interpreter) {
      InterpreterSel = RunJIT;
      Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
                                                   &ToolArgv);
    }
    if (!Interpreter) {
      InterpreterSel = RunLLC;
      Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
                                                   &ToolArgv);
    }
    if (!Interpreter) {
      InterpreterSel = RunLLI;
      Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
                                                   &ToolArgv);
    }
    if (!Interpreter) {
      InterpreterSel = AutoPick;
      Message = "Sorry, I can't automatically select an interpreter!\n";
    }
    break;
  case RunLLI:
    Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
                                                 &ToolArgv);
    break;
  case RunLLC:
    Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
                                                 &ToolArgv);
    break;
  case RunJIT:
    Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
                                                 &ToolArgv);
    break;
  case RunCBE:
    Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
                                                       &ToolArgv);
    break;
  default:
    Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
    break;
  }
  std::cerr << Message;

  // Initialize auxiliary tools for debugging
  if (!cbe) {
    cbe = AbstractInterpreter::createCBE(getToolName(), Message, &ToolArgv);
    if (!cbe) { std::cout << Message << "\nExiting.\n"; exit(1); }
  }
  gcc = GCC::create(getToolName(), Message);
  if (!gcc) { std::cout << Message << "\nExiting.\n"; exit(1); }

  // If there was an error creating the selected interpreter, quit with error.
  return Interpreter == 0;
}

/// compileProgram - Try to compile the specified module, throwing an exception
/// if an error occurs, or returning normally if not.  This is used for code
/// generation crash testing.
///
void BugDriver::compileProgram(Module *M) {
  // Emit the program to a bytecode file...
  sys::Path BytecodeFile ("bugpoint-test-program.bc");
  BytecodeFile.makeUnique();
  if (writeProgramToFile(BytecodeFile.toString(), M)) {
    std::cerr << ToolName << ": Error emitting bytecode to file '"
              << BytecodeFile << "'!\n";
    exit(1);
  }

    // Remove the temporary bytecode file when we are done.
  FileRemover BytecodeFileRemover(BytecodeFile);

  // Actually compile the program!
  Interpreter->compileProgram(BytecodeFile.toString());
}

/// executeProgram - This method runs "Program", capturing the output of the
/// program to a file, returning the filename of the file.  A recommended
/// filename may be optionally specified.
///
std::string BugDriver::executeProgram(std::string OutputFile,
                                      std::string BytecodeFile,
                                      const std::string &SharedObj,
                                      AbstractInterpreter *AI,
                                      bool *ProgramExitedNonzero) {
  if (AI == 0) AI = Interpreter;
  assert(AI && "Interpreter should have been created already!");
  bool CreatedBytecode = false;
  if (BytecodeFile.empty()) {
    // Emit the program to a bytecode file...
    sys::Path uniqueFilename("bugpoint-test-program.bc");
    uniqueFilename.makeUnique();
    BytecodeFile = uniqueFilename.toString();

    if (writeProgramToFile(BytecodeFile, Program)) {
      std::cerr << ToolName << ": Error emitting bytecode to file '"
                << BytecodeFile << "'!\n";
      exit(1);
    }
    CreatedBytecode = true;
  }

  // Remove the temporary bytecode file when we are done.
  FileRemover BytecodeFileRemover(sys::Path(BytecodeFile), CreatedBytecode);

  if (OutputFile.empty()) OutputFile = "bugpoint-execution-output";

  // Check to see if this is a valid output filename...
  sys::Path uniqueFile(OutputFile);
  uniqueFile.makeUnique();
  OutputFile = uniqueFile.toString();

  // Figure out which shared objects to run, if any.
  std::vector<std::string> SharedObjs(AdditionalSOs);
  if (!SharedObj.empty())
    SharedObjs.push_back(SharedObj);

  // Actually execute the program!
  int RetVal = AI->ExecuteProgram(BytecodeFile, InputArgv, InputFile,
                                  OutputFile, SharedObjs, TimeoutValue);

  if (RetVal == -1) {
    std::cerr << "<timeout>";
    static bool FirstTimeout = true;
    if (FirstTimeout) {
      std::cout << "\n"
 "*** Program execution timed out!  This mechanism is designed to handle\n"
 "    programs stuck in infinite loops gracefully.  The -timeout option\n"
 "    can be used to change the timeout threshold or disable it completely\n"
 "    (with -timeout=0).  This message is only displayed once.\n";
      FirstTimeout = false;
    }
  }

  if (ProgramExitedNonzero != 0)
    *ProgramExitedNonzero = (RetVal != 0);

  // Return the filename we captured the output to.
  return OutputFile;
}

/// executeProgramWithCBE - Used to create reference output with the C
/// backend, if reference output is not provided.
///
std::string BugDriver::executeProgramWithCBE(std::string OutputFile) {
  bool ProgramExitedNonzero;
  std::string outFN = executeProgram(OutputFile, "", "",
                                     (AbstractInterpreter*)cbe,
                                     &ProgramExitedNonzero);
  if (ProgramExitedNonzero) {
    std::cerr
      << "Warning: While generating reference output, program exited with\n"
      << "non-zero exit code. This will NOT be treated as a failure.\n";
    CheckProgramExitCode = false;
  }
  return outFN;
}

std::string BugDriver::compileSharedObject(const std::string &BytecodeFile) {
  assert(Interpreter && "Interpreter should have been created already!");
  sys::Path OutputCFile;

  // Using CBE
  cbe->OutputC(BytecodeFile, OutputCFile);

#if 0 /* This is an alternative, as yet unimplemented */
  // Using LLC
  std::string Message;
  LLC *llc = createLLCtool(Message);
  if (llc->OutputAsm(BytecodeFile, OutputFile)) {
    std::cerr << "Could not generate asm code with `llc', exiting.\n";
    exit(1);
  }
#endif

  std::string SharedObjectFile;
  if (gcc->MakeSharedObject(OutputCFile.toString(), GCC::CFile,
                            SharedObjectFile))
    exit(1);

  // Remove the intermediate C file
  OutputCFile.destroyFile();

  return "./" + SharedObjectFile;
}

/// diffProgram - This method executes the specified module and diffs the output
/// against the file specified by ReferenceOutputFile.  If the output is
/// different, true is returned.
///
bool BugDriver::diffProgram(const std::string &BytecodeFile,
                            const std::string &SharedObject,
                            bool RemoveBytecode) {
  bool ProgramExitedNonzero;

  // Execute the program, generating an output file...
  sys::Path Output (executeProgram("", BytecodeFile, SharedObject, 0,
                                      &ProgramExitedNonzero));

  // If we're checking the program exit code, assume anything nonzero is bad.
  if (CheckProgramExitCode && ProgramExitedNonzero) {
    Output.destroyFile();
    if (RemoveBytecode)
      sys::Path(BytecodeFile).destroyFile();
    return true;
  }

  std::string Error;
  bool FilesDifferent = false;
  if (DiffFiles(ReferenceOutputFile, Output.toString(), &Error)) {
    if (!Error.empty()) {
      std::cerr << "While diffing output: " << Error << '\n';
      exit(1);
    }
    FilesDifferent = true;
  }

  // Remove the generated output.
  Output.destroyFile();

  // Remove the bytecode file if we are supposed to.
  if (RemoveBytecode) sys::Path(BytecodeFile).destroyFile();
  return FilesDifferent;
}

bool BugDriver::isExecutingJIT() {
  return InterpreterSel == RunJIT;
}

<commit_msg>Fix the build on PowerPC/Darwin - it thought we were declaring a new function or something. Since FileRemover takes a const reference to sys::Path, we need to pass an actual sys::Path variable.<commit_after>//===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains code used to execute the program utilizing one of the
// various ways of running LLVM bytecode.
//
//===----------------------------------------------------------------------===//

#include "BugDriver.h"
#include "llvm/Support/ToolRunner.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/SystemUtils.h"
#include <fstream>
using namespace llvm;

namespace {
  // OutputType - Allow the user to specify the way code should be run, to test
  // for miscompilation.
  //
  enum OutputType {
    AutoPick, RunLLI, RunJIT, RunLLC, RunCBE
  };

  cl::opt<OutputType>
  InterpreterSel(cl::desc("Specify how LLVM code should be executed:"),
                 cl::values(clEnumValN(AutoPick, "auto", "Use best guess"),
                            clEnumValN(RunLLI, "run-int",
                                       "Execute with the interpreter"),
                            clEnumValN(RunJIT, "run-jit", "Execute with JIT"),
                            clEnumValN(RunLLC, "run-llc", "Compile with LLC"),
                            clEnumValN(RunCBE, "run-cbe", "Compile with CBE"),
                            clEnumValEnd),
                 cl::init(AutoPick));

  cl::opt<bool>
  CheckProgramExitCode("check-exit-code",
                   cl::desc("Assume nonzero exit code is failure (default on)"),
                       cl::init(true));

  cl::opt<std::string>
  InputFile("input", cl::init("/dev/null"),
            cl::desc("Filename to pipe in as stdin (default: /dev/null)"));

  cl::list<std::string>
  AdditionalSOs("additional-so",
                cl::desc("Additional shared objects to load "
                         "into executing programs"));

  cl::opt<unsigned>
  TimeoutValue("timeout", cl::init(300), cl::value_desc("seconds"),
               cl::desc("Number of seconds program is allowed to run before it "
                        "is killed (default is 300s), 0 disables timeout"));
}

namespace llvm {
  // Anything specified after the --args option are taken as arguments to the
  // program being debugged.
  cl::list<std::string>
  InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
            cl::ZeroOrMore, cl::PositionalEatsArgs);

  cl::list<std::string>
  ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
           cl::ZeroOrMore, cl::PositionalEatsArgs);
}

//===----------------------------------------------------------------------===//
// BugDriver method implementation
//

/// initializeExecutionEnvironment - This method is used to set up the
/// environment for executing LLVM programs.
///
bool BugDriver::initializeExecutionEnvironment() {
  std::cout << "Initializing execution environment: ";

  // Create an instance of the AbstractInterpreter interface as specified on
  // the command line
  cbe = 0;
  std::string Message;

  switch (InterpreterSel) {
  case AutoPick:
    InterpreterSel = RunCBE;
    Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
                                                       &ToolArgv);
    if (!Interpreter) {
      InterpreterSel = RunJIT;
      Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
                                                   &ToolArgv);
    }
    if (!Interpreter) {
      InterpreterSel = RunLLC;
      Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
                                                   &ToolArgv);
    }
    if (!Interpreter) {
      InterpreterSel = RunLLI;
      Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
                                                   &ToolArgv);
    }
    if (!Interpreter) {
      InterpreterSel = AutoPick;
      Message = "Sorry, I can't automatically select an interpreter!\n";
    }
    break;
  case RunLLI:
    Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
                                                 &ToolArgv);
    break;
  case RunLLC:
    Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
                                                 &ToolArgv);
    break;
  case RunJIT:
    Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
                                                 &ToolArgv);
    break;
  case RunCBE:
    Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
                                                       &ToolArgv);
    break;
  default:
    Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
    break;
  }
  std::cerr << Message;

  // Initialize auxiliary tools for debugging
  if (!cbe) {
    cbe = AbstractInterpreter::createCBE(getToolName(), Message, &ToolArgv);
    if (!cbe) { std::cout << Message << "\nExiting.\n"; exit(1); }
  }
  gcc = GCC::create(getToolName(), Message);
  if (!gcc) { std::cout << Message << "\nExiting.\n"; exit(1); }

  // If there was an error creating the selected interpreter, quit with error.
  return Interpreter == 0;
}

/// compileProgram - Try to compile the specified module, throwing an exception
/// if an error occurs, or returning normally if not.  This is used for code
/// generation crash testing.
///
void BugDriver::compileProgram(Module *M) {
  // Emit the program to a bytecode file...
  sys::Path BytecodeFile ("bugpoint-test-program.bc");
  BytecodeFile.makeUnique();
  if (writeProgramToFile(BytecodeFile.toString(), M)) {
    std::cerr << ToolName << ": Error emitting bytecode to file '"
              << BytecodeFile << "'!\n";
    exit(1);
  }

    // Remove the temporary bytecode file when we are done.
  FileRemover BytecodeFileRemover(BytecodeFile);

  // Actually compile the program!
  Interpreter->compileProgram(BytecodeFile.toString());
}

/// executeProgram - This method runs "Program", capturing the output of the
/// program to a file, returning the filename of the file.  A recommended
/// filename may be optionally specified.
///
std::string BugDriver::executeProgram(std::string OutputFile,
                                      std::string BytecodeFile,
                                      const std::string &SharedObj,
                                      AbstractInterpreter *AI,
                                      bool *ProgramExitedNonzero) {
  if (AI == 0) AI = Interpreter;
  assert(AI && "Interpreter should have been created already!");
  bool CreatedBytecode = false;
  if (BytecodeFile.empty()) {
    // Emit the program to a bytecode file...
    sys::Path uniqueFilename("bugpoint-test-program.bc");
    uniqueFilename.makeUnique();
    BytecodeFile = uniqueFilename.toString();

    if (writeProgramToFile(BytecodeFile, Program)) {
      std::cerr << ToolName << ": Error emitting bytecode to file '"
                << BytecodeFile << "'!\n";
      exit(1);
    }
    CreatedBytecode = true;
  }

  // Remove the temporary bytecode file when we are done.
  sys::Path BytecodePath (BytecodeFile);
  FileRemover BytecodeFileRemover(BytecodePath, CreatedBytecode);

  if (OutputFile.empty()) OutputFile = "bugpoint-execution-output";

  // Check to see if this is a valid output filename...
  sys::Path uniqueFile(OutputFile);
  uniqueFile.makeUnique();
  OutputFile = uniqueFile.toString();

  // Figure out which shared objects to run, if any.
  std::vector<std::string> SharedObjs(AdditionalSOs);
  if (!SharedObj.empty())
    SharedObjs.push_back(SharedObj);

  // Actually execute the program!
  int RetVal = AI->ExecuteProgram(BytecodeFile, InputArgv, InputFile,
                                  OutputFile, SharedObjs, TimeoutValue);

  if (RetVal == -1) {
    std::cerr << "<timeout>";
    static bool FirstTimeout = true;
    if (FirstTimeout) {
      std::cout << "\n"
 "*** Program execution timed out!  This mechanism is designed to handle\n"
 "    programs stuck in infinite loops gracefully.  The -timeout option\n"
 "    can be used to change the timeout threshold or disable it completely\n"
 "    (with -timeout=0).  This message is only displayed once.\n";
      FirstTimeout = false;
    }
  }

  if (ProgramExitedNonzero != 0)
    *ProgramExitedNonzero = (RetVal != 0);

  // Return the filename we captured the output to.
  return OutputFile;
}

/// executeProgramWithCBE - Used to create reference output with the C
/// backend, if reference output is not provided.
///
std::string BugDriver::executeProgramWithCBE(std::string OutputFile) {
  bool ProgramExitedNonzero;
  std::string outFN = executeProgram(OutputFile, "", "",
                                     (AbstractInterpreter*)cbe,
                                     &ProgramExitedNonzero);
  if (ProgramExitedNonzero) {
    std::cerr
      << "Warning: While generating reference output, program exited with\n"
      << "non-zero exit code. This will NOT be treated as a failure.\n";
    CheckProgramExitCode = false;
  }
  return outFN;
}

std::string BugDriver::compileSharedObject(const std::string &BytecodeFile) {
  assert(Interpreter && "Interpreter should have been created already!");
  sys::Path OutputCFile;

  // Using CBE
  cbe->OutputC(BytecodeFile, OutputCFile);

#if 0 /* This is an alternative, as yet unimplemented */
  // Using LLC
  std::string Message;
  LLC *llc = createLLCtool(Message);
  if (llc->OutputAsm(BytecodeFile, OutputFile)) {
    std::cerr << "Could not generate asm code with `llc', exiting.\n";
    exit(1);
  }
#endif

  std::string SharedObjectFile;
  if (gcc->MakeSharedObject(OutputCFile.toString(), GCC::CFile,
                            SharedObjectFile))
    exit(1);

  // Remove the intermediate C file
  OutputCFile.destroyFile();

  return "./" + SharedObjectFile;
}

/// diffProgram - This method executes the specified module and diffs the output
/// against the file specified by ReferenceOutputFile.  If the output is
/// different, true is returned.
///
bool BugDriver::diffProgram(const std::string &BytecodeFile,
                            const std::string &SharedObject,
                            bool RemoveBytecode) {
  bool ProgramExitedNonzero;

  // Execute the program, generating an output file...
  sys::Path Output (executeProgram("", BytecodeFile, SharedObject, 0,
                                      &ProgramExitedNonzero));

  // If we're checking the program exit code, assume anything nonzero is bad.
  if (CheckProgramExitCode && ProgramExitedNonzero) {
    Output.destroyFile();
    if (RemoveBytecode)
      sys::Path(BytecodeFile).destroyFile();
    return true;
  }

  std::string Error;
  bool FilesDifferent = false;
  if (DiffFiles(ReferenceOutputFile, Output.toString(), &Error)) {
    if (!Error.empty()) {
      std::cerr << "While diffing output: " << Error << '\n';
      exit(1);
    }
    FilesDifferent = true;
  }

  // Remove the generated output.
  Output.destroyFile();

  // Remove the bytecode file if we are supposed to.
  if (RemoveBytecode) sys::Path(BytecodeFile).destroyFile();
  return FilesDifferent;
}

bool BugDriver::isExecutingJIT() {
  return InterpreterSel == RunJIT;
}

<|endoftext|>


<commit_before>//===-- ClangFuzzer.cpp - Fuzz Clang --------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a function that runs Clang on a single
///  input. This function is then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//

#include "clang/Tooling/Tooling.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Option/Option.h"

using namespace clang;

extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
  std::string s((const char *)data, size);
  llvm::opt::ArgStringList CC1Args;
  CC1Args.push_back("-cc1");
  CC1Args.push_back("./test.cc");
  llvm::IntrusiveRefCntPtr<FileManager> Files(
      new FileManager(FileSystemOptions()));
  IgnoringDiagConsumer Diags;
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
      &Diags, false);
  std::unique_ptr<clang::CompilerInvocation> Invocation(
      tooling::newInvocation(&Diagnostics, CC1Args));
  std::unique_ptr<llvm::MemoryBuffer> Input =
      llvm::MemoryBuffer::getMemBuffer(s);
  Invocation->getPreprocessorOpts().addRemappedFile("./test.cc", Input.release());
  std::unique_ptr<tooling::ToolAction> action(
      tooling::newFrontendActionFactory<clang::SyntaxOnlyAction>());
  std::shared_ptr<PCHContainerOperations> PCHContainerOps =
      std::make_shared<PCHContainerOperations>();
  action->runInvocation(Invocation.release(), Files.get(), PCHContainerOps,
                        &Diags);
  return 0;
}
<commit_msg>Add missing header in ClangFuzzer (after r275882 cleanup)<commit_after>//===-- ClangFuzzer.cpp - Fuzz Clang --------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a function that runs Clang on a single
///  input. This function is then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//

#include "clang/Tooling/Tooling.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "llvm/Option/Option.h"

using namespace clang;

extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
  std::string s((const char *)data, size);
  llvm::opt::ArgStringList CC1Args;
  CC1Args.push_back("-cc1");
  CC1Args.push_back("./test.cc");
  llvm::IntrusiveRefCntPtr<FileManager> Files(
      new FileManager(FileSystemOptions()));
  IgnoringDiagConsumer Diags;
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
      &Diags, false);
  std::unique_ptr<clang::CompilerInvocation> Invocation(
      tooling::newInvocation(&Diagnostics, CC1Args));
  std::unique_ptr<llvm::MemoryBuffer> Input =
      llvm::MemoryBuffer::getMemBuffer(s);
  Invocation->getPreprocessorOpts().addRemappedFile("./test.cc", Input.release());
  std::unique_ptr<tooling::ToolAction> action(
      tooling::newFrontendActionFactory<clang::SyntaxOnlyAction>());
  std::shared_ptr<PCHContainerOperations> PCHContainerOps =
      std::make_shared<PCHContainerOperations>();
  action->runInvocation(Invocation.release(), Files.get(), PCHContainerOps,
                        &Diags);
  return 0;
}
<|endoftext|>


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

#include "hungarian/hungarian.hpp"
#include <map>
#include <vector>
#include <sstream>
#include <cstdlib>
#include <algorithm>

typedef unsigned int uint;
typedef std::string Id;
typedef std::vector<int> Preferences;
typedef std::pair<Id,Preferences> Entity;

std::vector<std::string> split(const std::string& data, char delimiter) {
  std::vector<std::string> result;
  std::stringstream stream(data);
  std::string element;
  while(std::getline(stream, element, delimiter)){
      result.push_back(element);
  }
  return result;
}

template<typename T>
T parse(const std::string& data){
  std::istringstream istream(data);
  T result;
  istream >> result;
  return result;
}

template<typename T>
std::vector<T> parse_vector(const std::vector<std::string>& data, uint start_at=0){
  std::vector<T> result;
  for(uint i = start_at; i < data.size(); ++i){
    result.push_back(parse<T>(data[i]));
  }
  return result;
}

Entity parseEntity(const std::string& csv){
  std::vector<std::string> vector = split(csv,',');
  Entity result;
  result.first = parse<std::string>(vector.front());
  result.second = parse_vector<int>(vector,1);
  return result;
}

int main(int arg_num, char** args) {

  // process command line arguments
  for(int i = 1; i < arg_num; ++i){
    std::string arg = args[i];
    if(arg == "--help" || arg == "-h"){
      std::cout << "This application uses preferences to sort entities into groups. Input data is read from stdin.\n"\
                << "Usage: assign < preferences.csv\n\n"
                << "Parameters:\n"
                << "\t -h | --help \t\t print this message and leave.\n"
                << "\t -e | --example \t print an example preferences document in the correct format and leave."
                << std::endl;
      std::exit(0);
    } else if (arg == "--example" || arg == "-e"){
      std::cout << "jack,1,5,6,2,3" << std::endl;
      std::cout << "jill,6,2,4,6,2" << std::endl;
      std::cout << "paul,3,3,5,2,1" << std::endl;
      std::cout << "will,2,9,7,4,3" << std::endl;
      std::cout << "jenn,5,6,3,7,1" << std::endl;
      std::exit(0);
    }
  }

  // process data from sidin into vectors
  std::vector<Id> entity_ids;
  std::vector<Preferences> entity_preferences;

  uint group_count = 0;
  uint line = 1;
  while(std::cin) {
    std::string entity_csv;
    std::getline(std::cin, entity_csv);
    if(std::cin.eof()) break;
    Entity entity = parseEntity(entity_csv);
    entity_ids.push_back(entity.first);
    entity_preferences.push_back(entity.second);
    if(line == 1){
      group_count = entity.second.size();
    } else  {
      if(entity.second.size() != group_count){
        std::cerr << "Error: Group count in line #" << line << " is defferent from previous. "
                  << entity.second.size() << " != " << group_count << "(previous)." << std::endl;
        std::exit(-1);
      }
    }
    ++line;
  }

  for(uint i = 0;  i < entity_ids.size(); ++i){
    std::cout << entity_ids[i] << ":\t";
    for (int j = 0; j < entity_preferences[i].size(); ++j){
      std::cout << entity_preferences[i][j] << " ";
    }
    std::cout << std::endl;
  }

  // create cost matrix
  uint group_size = (entity_ids.size() / group_count);
  if(entity_ids.size() % group_count) ++group_size;
  std::vector<std::vector<int> > matrix;
  matrix.resize(entity_ids.size(),std::vector<int>(group_count*group_size,0));
  for(uint i = 0; i < entity_ids.size(); ++i){
    std::vector<int>& row = matrix[i];
    for(uint j = 0; j < group_size; ++j){
      std::copy(entity_preferences[i].begin(), entity_preferences[i].end(), row.begin()+(j*group_count));
    }
  }

  /* initialize the hungarian_problem using the cost matrix*/
  Hungarian hungarian(matrix, matrix.size(),matrix.front().size(), HUNGARIAN_MODE_MINIMIZE_COST) ;

  /* some output */
  fprintf(stderr, "cost-matrix:");
  hungarian.print_cost();

  /* solve the assignement problem */
  hungarian.solve();

  /* some output */
  fprintf(stderr, "assignment:");
  hungarian.print_assignment();

  return 0;
}

<commit_msg>Refactor assign, Fix matrix transposed<commit_after>/*********************************************************************
* The MIT License (MIT)                                              *
*                                                                    *
* Copyright (c) 2015 Viktor Richter                                  *
*                                                                    *
* Permission is hereby granted, free of charge, to any person        *
* obtaining a copy of this software and associated documentation     *
* files (the "Software"), to deal in the Software without            *
* restriction, including without limitation the rights               *
* to use, copy, modify, merge, publish, distribute, sublicense,      *
* and/or sell copies of the Software, and to permit persons to whom  *
* the Software is furnished to do so, subject to the following       *
* conditions:                                                        *
*                                                                    *
* The above copyright notice and this permission notice shall be     *
* included in all copies or substantial portions of the Software.    *
*                                                                    *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,    *
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND              *
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT        *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,       *
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER      *
* DEALINGS IN THE SOFTWARE.                                          *
*********************************************************************/

#include "hungarian/hungarian.hpp"
#include <map>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cstdlib>
#include <cassert>

typedef unsigned int uint;
typedef int Cost;
typedef std::vector<std::vector<Cost> > CostMatrix;
typedef std::string Id;
typedef std::vector<int> Preferences;
typedef std::pair<Id,Preferences> Entity;

std::vector<std::string> split(const std::string& data, char delimiter) {
  std::vector<std::string> result;
  std::stringstream stream(data);
  std::string element;
  while(std::getline(stream, element, delimiter)){
      result.push_back(element);
  }
  return result;
}

template<typename T>
T parse(const std::string& data){
  std::istringstream istream(data);
  T result;
  istream >> result;
  return result;
}

template<typename T>
std::vector<T> parse_vector(const std::vector<std::string>& data, uint start_at=0){
  std::vector<T> result;
  for(uint i = start_at; i < data.size(); ++i){
    result.push_back(parse<T>(data[i]));
  }
  return result;
}

Entity parseEntity(const std::string& csv){
  std::vector<std::string> vector = split(csv,',');
  Entity result;
  result.first = parse<std::string>(vector.front());
  result.second = parse_vector<int>(vector,1);
  return result;
}

void process_args(int arg_num, char** args){
  for(int i = 1; i < arg_num; ++i){
    std::string arg = args[i];
    if(arg == "--help" || arg == "-h"){
      std::cout << "This application uses preferences to sort entities into groups. Input data is read from stdin.\n"\
                << "Usage: assign < preferences.csv\n\n"
                << "Parameters:\n"
                << "\t -h | --help \t\t print this message and leave.\n"
                << "\t -e | --example \t print an example preferences document in the correct format and leave."
                << std::endl;
      std::exit(0);
    } else if (arg == "--example" || arg == "-e"){
      std::cout << "jack,1,5,6,2,3" << std::endl;
      std::cout << "jill,6,2,4,6,2" << std::endl;
      std::cout << "paul,3,3,5,2,1" << std::endl;
      std::cout << "will,2,9,7,4,3" << std::endl;
      std::cout << "jenn,5,6,3,7,1" << std::endl;
      std::exit(0);
    }
  }
}

void parse_csv_data(std::vector<Id>& entity_ids, std::vector<Preferences>& entity_preferences){
  uint group_count = 0;
  uint line = 1;
  while(std::cin) {
    std::string entity_csv;
    std::getline(std::cin, entity_csv);
    if(std::cin.eof()) break;
    Entity entity = parseEntity(entity_csv);
    entity_ids.push_back(entity.first);
    entity_preferences.push_back(entity.second);
    if(line == 1){
      group_count = entity.second.size();
    } else  {
      if(entity.second.size() != group_count){
        std::cerr << "Error: Group count in line #" << line << " is defferent from previous. "
                  << entity.second.size() << " != " << group_count << "(previous)." << std::endl;
        std::exit(-1);
      }
    }
    ++line;
  }
}

void print_data(const std::vector<Id>& entity_ids, const std::vector<Preferences>& entity_preferences, std::ostream& dst){
  assert(entity_ids.size() == entity_preferences.size());
  for(uint i = 0;  i < entity_ids.size(); ++i){
    dst << entity_ids[i] << ":\t";
    for (int j = 0; j < entity_preferences[i].size(); ++j){
      dst << entity_preferences[i][j] << " ";
    }
    dst << std::endl;
  }
}

void fill_cost_matrix(const std::vector<Id>& entity_ids, const std::vector<Preferences>& entity_preferences,
                      uint group_count,
                      CostMatrix& cost_matrix)
{
  uint group_size = entity_ids.size() / group_count;
  if(entity_ids.size() % group_count) { ++group_size; } // rounding up
  uint columns = entity_ids.size(); // true count of entities
  uint rows = group_count * group_size;

  cost_matrix.clear();
  cost_matrix.reserve(columns);
  // fill the first rows with preferences
  for(uint row = 0; row < group_count; ++row){
    cost_matrix.push_back(std::vector<Cost>(columns,0));
    for(uint column = 0; column < entity_preferences.size(); ++column){
      cost_matrix[row][column] = entity_preferences[column][row]; // transposing
    }
  }
  // fill the other rows by copying the first ones.
  for(uint row = group_count; row < rows; ++row){
    cost_matrix.push_back(cost_matrix[row % group_count]);
  }
}

int main(int arg_num, char** args) {

  process_args(arg_num,args);

  std::vector<Id> entity_ids;
  std::vector<Preferences> entity_preferences;
  parse_csv_data(entity_ids, entity_preferences);

  print_data(entity_ids,entity_preferences,std::cout);

  // create cost matrix
  CostMatrix cost_matrix;
  uint group_count = entity_preferences.front().size(); // #groups == #group preferences
  fill_cost_matrix(entity_ids,entity_preferences,group_count,cost_matrix);

  /* initialize the hungarian_problem using the cost matrix*/
  Hungarian hungarian(cost_matrix, cost_matrix.size(), cost_matrix.front().size(), HUNGARIAN_MODE_MINIMIZE_COST) ;

  /* some output */
  fprintf(stderr, "cost-matrix:");
  hungarian.print_cost();

  /* solve the assignement problem */
  hungarian.solve();

  /* some output */
  fprintf(stderr, "assignment:");
  hungarian.print_assignment();

  return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"

#include <tools/svlibrary.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/util/XMacroExpander.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/xPropertySet.hpp>
#include <comphelper/processfactory.hxx>
#include <tools/string.hxx>
#include <rtl/uri.hxx>

using namespace com::sun::star;

static uno::Sequence< rtl::OUString > GetMultiPaths_Impl()
{
    uno::Sequence< rtl::OUString >   aRes;
    uno::Sequence< rtl::OUString >   aInternalPaths;
    uno::Sequence< rtl::OUString >   aUserPaths;

    bool bSuccess = true;
    uno::Reference< lang::XMultiServiceFactory >  xMgr( comphelper::getProcessServiceFactory() );
    if (xMgr.is())
    {
        try
        {
            String aInternal;
            aInternal.AppendAscii("Libraries");
            String aUser;
            aUser.AppendAscii("Libraries");
            aInternal .AppendAscii( "_internal" );
            aUser     .AppendAscii( "_user" );

            uno::Reference< beans::XPropertySet > xPathSettings( xMgr->createInstance(
                rtl::OUString::createFromAscii( "com.sun.star.util.PathSettings" ) ), uno::UNO_QUERY_THROW );
            xPathSettings->getPropertyValue( aInternal )  >>= aInternalPaths;
            xPathSettings->getPropertyValue( aUser )      >>= aUserPaths;
        }
        catch (uno::Exception &)
        {
            bSuccess = false;
        }
    }
    if (bSuccess)
    {
        sal_Int32 nMaxEntries = aInternalPaths.getLength() + aUserPaths.getLength();
        aRes.realloc( nMaxEntries );
        rtl::OUString *pRes = aRes.getArray();
        sal_Int32 nCount = 0;   // number of actually added entries
        for (int i = 0;  i < 2;  ++i)
        {
            const uno::Sequence< rtl::OUString > &rPathSeq = i == 0 ? aUserPaths : aInternalPaths;
            const rtl::OUString *pPathSeq = rPathSeq.getConstArray();
            for (sal_Int32 k = 0;  k < rPathSeq.getLength();  ++k)
            {
                const bool bAddUser     = (&rPathSeq == &aUserPaths);
                const bool bAddInternal = (&rPathSeq == &aInternalPaths);
                if ((bAddUser || bAddInternal) && pPathSeq[k].getLength() > 0)
                    pRes[ nCount++ ] = pPathSeq[k];
            }
        }
        aRes.realloc( nCount );
    }

    return aRes;
}

bool SvLibrary::LoadModule( osl::Module& rModule, const rtl::OUString& rLibName, ::oslGenericFunction baseModule, ::sal_Int32 mode )
{
    static uno::Sequence < rtl::OUString > aPaths = GetMultiPaths_Impl();
    bool bLoaded = false;

    for (sal_Int32 n=0; n<aPaths.getLength(); n++)
    {
        rtl::OUString aMod = aPaths[n];
        if ( aPaths[n].indexOfAsciiL("vnd.sun.star.expand",19) == 0)
        {
            uno::Reference< uno::XComponentContext > xComponentContext = comphelper::getProcessComponentContext();
            uno::Reference< util::XMacroExpander > xMacroExpander;
            xComponentContext->getValueByName(
                ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/singletons/com.sun.star.util.theMacroExpander") ) )
                    >>= xMacroExpander;

            aMod = aMod.copy( sizeof("vnd.sun.star.expand:") -1 );
            aMod = ::rtl::Uri::decode( aMod, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
            aMod = xMacroExpander->expandMacros( aMod );
        }

        aMod += ::rtl::OUString( sal_Unicode('/') );
        aMod += rLibName;
        bLoaded = rModule.load( aMod, mode );
        if ( bLoaded )
            break;
    }

    if (!bLoaded )
        bLoaded = rModule.loadRelative( baseModule, rLibName, mode );

    return bLoaded;
}
<commit_msg>CWS mba33issues01: typo<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"

#include <tools/svlibrary.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/util/XMacroExpander.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <comphelper/processfactory.hxx>
#include <tools/string.hxx>
#include <rtl/uri.hxx>

using namespace com::sun::star;

static uno::Sequence< rtl::OUString > GetMultiPaths_Impl()
{
    uno::Sequence< rtl::OUString >   aRes;
    uno::Sequence< rtl::OUString >   aInternalPaths;
    uno::Sequence< rtl::OUString >   aUserPaths;

    bool bSuccess = true;
    uno::Reference< lang::XMultiServiceFactory >  xMgr( comphelper::getProcessServiceFactory() );
    if (xMgr.is())
    {
        try
        {
            String aInternal;
            aInternal.AppendAscii("Libraries");
            String aUser;
            aUser.AppendAscii("Libraries");
            aInternal .AppendAscii( "_internal" );
            aUser     .AppendAscii( "_user" );

            uno::Reference< beans::XPropertySet > xPathSettings( xMgr->createInstance(
                rtl::OUString::createFromAscii( "com.sun.star.util.PathSettings" ) ), uno::UNO_QUERY_THROW );
            xPathSettings->getPropertyValue( aInternal )  >>= aInternalPaths;
            xPathSettings->getPropertyValue( aUser )      >>= aUserPaths;
        }
        catch (uno::Exception &)
        {
            bSuccess = false;
        }
    }
    if (bSuccess)
    {
        sal_Int32 nMaxEntries = aInternalPaths.getLength() + aUserPaths.getLength();
        aRes.realloc( nMaxEntries );
        rtl::OUString *pRes = aRes.getArray();
        sal_Int32 nCount = 0;   // number of actually added entries
        for (int i = 0;  i < 2;  ++i)
        {
            const uno::Sequence< rtl::OUString > &rPathSeq = i == 0 ? aUserPaths : aInternalPaths;
            const rtl::OUString *pPathSeq = rPathSeq.getConstArray();
            for (sal_Int32 k = 0;  k < rPathSeq.getLength();  ++k)
            {
                const bool bAddUser     = (&rPathSeq == &aUserPaths);
                const bool bAddInternal = (&rPathSeq == &aInternalPaths);
                if ((bAddUser || bAddInternal) && pPathSeq[k].getLength() > 0)
                    pRes[ nCount++ ] = pPathSeq[k];
            }
        }
        aRes.realloc( nCount );
    }

    return aRes;
}

bool SvLibrary::LoadModule( osl::Module& rModule, const rtl::OUString& rLibName, ::oslGenericFunction baseModule, ::sal_Int32 mode )
{
    static uno::Sequence < rtl::OUString > aPaths = GetMultiPaths_Impl();
    bool bLoaded = false;

    for (sal_Int32 n=0; n<aPaths.getLength(); n++)
    {
        rtl::OUString aMod = aPaths[n];
        if ( aPaths[n].indexOfAsciiL("vnd.sun.star.expand",19) == 0)
        {
            uno::Reference< uno::XComponentContext > xComponentContext = comphelper::getProcessComponentContext();
            uno::Reference< util::XMacroExpander > xMacroExpander;
            xComponentContext->getValueByName(
                ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/singletons/com.sun.star.util.theMacroExpander") ) )
                    >>= xMacroExpander;

            aMod = aMod.copy( sizeof("vnd.sun.star.expand:") -1 );
            aMod = ::rtl::Uri::decode( aMod, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
            aMod = xMacroExpander->expandMacros( aMod );
        }

        aMod += ::rtl::OUString( sal_Unicode('/') );
        aMod += rLibName;
        bLoaded = rModule.load( aMod, mode );
        if ( bLoaded )
            break;
    }

    if (!bLoaded )
        bLoaded = rModule.loadRelative( baseModule, rLibName, mode );

    return bLoaded;
}
<|endoftext|>