text:
// MIT License
//
// Copyright (c) 2019 Oleksandr Tkachenko, Lennart Braun
// Cryptography and Privacy Engineering Group (ENCRYPTO)
// TU Darmstadt, Germany
//
// 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 "algorithm_description.h"

#include <fstream>
#include <regex>
#include <sstream>

#include <fmt/format.h>
#include <boost/algorithm/string/trim.hpp>
#include <boost/lexical_cast.hpp>

namespace encrypto::motion {

AlgorithmDescription AlgorithmDescription::FromBristol(const std::string& path) {
  std::ifstream file_stream(path);
  return FromBristol(file_stream);
}

AlgorithmDescription AlgorithmDescription::FromBristol(std::string&& path) {
  std::ifstream file_stream(std::move(path));
  return FromBristol(file_stream);
}

//
// Bristol format
// 49 65            *** total # of gates, total # of wires
// 8 8 8            *** # input wires parent a, # input wires parent b, # of output wires
//                  *** empty line
// *** below, only gate-related infos:
// *** # of input shares (bundled wires, i.e., XOR has 2 inputs, INV 1, and MUX 3),
// *** # of outputs,
// *** input wire ids (1--many)
// *** output wire ids (usually 1)
// *** gate type
// 2 1 0 8 57 XOR
// 2 1 1 9 16 XOR   ***
// 2 1 0 8 17 AND   ***
// ...
//

AlgorithmDescription AlgorithmDescription::FromBristol(std::ifstream& stream) {
  AlgorithmDescription algorithm_description;
  assert(stream.is_open());
  assert(stream.good());
  stream >> algorithm_description.number_of_gates >> algorithm_description.number_of_wires;

  std::vector<std::string> line_vector;
  std::string line;
  std::getline(stream, line);  // skip \n at the end of the first line
  // second line
  {
    std::string second_line;
    std::getline(stream, second_line);
    std::stringstream ss(second_line);
    while (std::getline(ss, line, ' ')) {
      line_vector.emplace_back(std::move(line));
      line.clear();
    }
    algorithm_description.number_of_input_wires_parent_a = std::stoull(line_vector.at(0));
    if (line_vector.size() == 2) {
      algorithm_description.number_of_output_wires = std::stoull(line_vector.at(1));
    } else if (line_vector.size() == 3) {
      algorithm_description.number_of_input_wires_parent_b = std::stoull(line_vector.at(1));
      algorithm_description.number_of_output_wires = std::stoull(line_vector.at(2));
    } else {
      throw std::runtime_error(
          std::string("Unexpected number of values: " + std::to_string(line_vector.size()) + "\n"));
    }
    line.clear();
    line_vector.clear();
  }

  std::getline(stream, line);
  assert(line.empty());

  // read line
  while (std::getline(stream, line)) {
    std::stringstream ss(line);
    // split line
    while (std::getline(ss, line, ' ')) {
      line_vector.emplace_back(std::move(line));
    }

    if (line_vector.empty()) continue;
    const auto& type = line_vector.at(line_vector.size() - 1);
    PrimitiveOperation primitive_operation;
    if (type == std::string("XOR") || type == std::string("AND") || type == std::string("ADD") ||
        type == std::string("MUL") || type == std::string("OR")) {
      assert(line_vector.size() == 6);
      if (type == std::string("XOR"))
        primitive_operation.type = PrimitiveOperationType::kXor;
      else if (type == std::string("AND"))
        primitive_operation.type = PrimitiveOperationType::kAnd;
      else if (type == std::string("ADD"))
        primitive_operation.type = PrimitiveOperationType::kAdd;
      else if (type == std::string("MUL"))
        primitive_operation.type = PrimitiveOperationType::kMul;
      else if (type == std::string("OR"))
        primitive_operation.type = PrimitiveOperationType::kOr;
      primitive_operation.parent_a = std::stoull(line_vector.at(2));
      primitive_operation.parent_b = std::stoull(line_vector.at(3));
      primitive_operation.output_wire = std::stoull(line_vector.at(4));
    } else if (type == std::string("MUX")) {
      assert(line_vector.size() == 7);
      primitive_operation.type = PrimitiveOperationType::kMux;
      primitive_operation.parent_a = std::stoull(line_vector.at(2));
      primitive_operation.parent_b = std::stoull(line_vector.at(3));
      primitive_operation.selection_bit = std::stoull(line_vector.at(4));
      primitive_operation.output_wire = std::stoull(line_vector.at(5));
    } else if (type == std::string("INV")) {
      assert(line_vector.size() == 5);
      primitive_operation.type = PrimitiveOperationType::kInv;
      primitive_operation.parent_a = std::stoull(line_vector.at(2));
      primitive_operation.output_wire = std::stoull(line_vector.at(3));
    } else {
      throw std::runtime_error("Unknown operation type: " + line_vector.at(line_vector.size() - 1) +
                               "\n");
    }
    algorithm_description.gates.emplace_back(primitive_operation);
    line.clear();
    line_vector.clear();
  }
  return algorithm_description;
}

AlgorithmDescription AlgorithmDescription::FromBristolFashion(const std::string& path) {
  std::ifstream file_stream(path);
  return FromBristolFashion(file_stream);
}

AlgorithmDescription AlgorithmDescription::FromBristolFashion(std::string&& path) {
  std::ifstream file_stream(std::move(path));
  return FromBristolFashion(file_stream);
}

AlgorithmDescription AlgorithmDescription::FromBristolFashion(std::ifstream& stream) {
  AlgorithmDescription algorithm_description;
  assert(stream.is_open());
  assert(stream.good());

  constexpr std::size_t kGateEncodingLineNumber = 4;
  const static std::regex kLineTwoNumbersRegex("^\\s*(\\d+)\\s+(\\d+)\\s*$");
  const static std::regex kLineThreeNumbersRegex("^\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s*$");
  const static std::regex kLineGateRegex(
      "^\\s*(1|2)\\s+(1)\\s+(\\d+)\\s+(\\d+\\s+)?(\\d+)\\s+(XOR|AND|INV)\\s*$");
  const static std::regex kLineWhitespaceRegex("^\\s*$");

  std::string line;
  std::smatch match;

  // first line
  std::getline(stream, line);
  if (!std::regex_match(line, match, kLineTwoNumbersRegex)) {
    throw std::runtime_error("Cannot parse Bristol Fashion file at line 1");
  }
  algorithm_description.number_of_gates = boost::lexical_cast<std::size_t>(match[1]);
  algorithm_description.number_of_wires = boost::lexical_cast<std::size_t>(match[2]);

  // second line
  std::getline(stream, line);
  if (std::regex_match(line, match, kLineTwoNumbersRegex)) {
    auto n = boost::lexical_cast<std::size_t>(match[1]);
    if (n != 1) {
      throw std::runtime_error("Malformed Bristol Fashion format at line 2");
    }
    algorithm_description.number_of_input_wires_parent_a =
        boost::lexical_cast<std::size_t>(match[2]);
  } else if (std::regex_match(line, match, kLineThreeNumbersRegex)) {
    auto n = boost::lexical_cast<std::size_t>(match[1]);
    if (n != 2) {
      throw std::runtime_error("Malformed Bristol Fashion format at line 2");
    }
    algorithm_description.number_of_input_wires_parent_a =
        boost::lexical_cast<std::size_t>(match[2]);
    algorithm_description.number_of_input_wires_parent_b =
        boost::lexical_cast<std::size_t>(match[3]);
  } else {
    throw std::runtime_error(
        "Cannot parse Bristol Fashion file at line 2 (maybe unsupported number of input values)");
  }

  // third line
  std::getline(stream, line);
  if (std::regex_match(line, match, kLineTwoNumbersRegex)) {
    auto n = boost::lexical_cast<std::size_t>(match[1]);
    if (n != 1) {
      throw std::runtime_error("Malformed Bristol Fashion format at line 3");
    }
    algorithm_description.number_of_output_wires = boost::lexical_cast<std::size_t>(match[2]);
  } else {
    throw std::runtime_error(
        "Cannot parse Bristol Fashion file at line 3 (maybe unsupported number of output values)");
  }

  // consume empty line
  std::getline(stream, line);
  assert(line.empty());

  std::size_t line_number = kGateEncodingLineNumber;

  // read gates
  while (std::getline(stream, line)) {
    ++line_number;
    if (line.empty() || std::regex_match(line, kLineWhitespaceRegex)) {
      continue;
    }

    if (!std::regex_match(line, match, kLineGateRegex)) {
      throw std::runtime_error(
          fmt::format("Cannot parse Bristol Fashion file at line {}", line_number));
    }

    using namespace std::string_literals;

    auto number_of_inputs = boost::lexical_cast<std::size_t>(match[1]);
    const auto& operation = match[6];
    PrimitiveOperation primitive_operation;

    if (operation == "XOR"s) {
      if (number_of_inputs != 2) {
        throw std::runtime_error(fmt::format(
            "Cannot parse Bristol Fashion file at line {}: invalid number of inputs", line_number));
      }
      primitive_operation.type = PrimitiveOperationType::kXor;
    } else if (operation == "AND"s) {
      if (number_of_inputs != 2) {
        throw std::runtime_error(fmt::format(
            "Cannot parse Bristol Fashion file at line {}: invalid number of inputs", line_number));
      }
      primitive_operation.type = PrimitiveOperationType::kAnd;
    } else if (operation == "INV"s) {
      if (number_of_inputs != 1) {
        throw std::runtime_error(fmt::format(
            "Cannot parse Bristol Fashion file at line {}: invalid number of inputs", line_number));
      }
      primitive_operation.type = PrimitiveOperationType::kInv;
    }
    primitive_operation.output_wire = boost::lexical_cast<std::size_t>(match[5]);
    primitive_operation.parent_a = boost::lexical_cast<std::size_t>(match[3]);
    if (number_of_inputs == 2) {
      std::string input_b = match[4];
      boost::trim(input_b);
      primitive_operation.parent_b = boost::lexical_cast<std::size_t>(input_b);
    }
    algorithm_description.gates.emplace_back(std::move(primitive_operation));
  }

  return algorithm_description;
}

AlgorithmDescription AlgorithmDescription::FromAby(const std::string& path) {
  std::ifstream file_stream(path);
  return FromBristol(file_stream);
}

AlgorithmDescription AlgorithmDescription::FromAby(std::string&& path) {
  std::ifstream file_stream(std::move(path));
  return FromBristol(file_stream);
}

AlgorithmDescription AlgorithmDescription::FromAby(std::ifstream& stream) {
  AlgorithmDescription algorithm_description;
  assert(stream.is_open());
  assert(stream.good());
  std::string line;
  constexpr int kInvalidValue = 999999999;
  int constant_input_0 [[maybe_unused]] = kInvalidValue;
  int constant_input_1 [[maybe_unused]] = kInvalidValue;
  do {
    std::getline(stream, line);
    switch (line[0]) {
      case '#':  // comment
        break;
      case '\n':  // empty line
        break;
      case '0':  // constant 0
        constant_input_0 = std::stoi(line.substr(1, line.size() - 1));
        break;
      case '1':  // constant 1
        constant_input_1 = std::stoi(line.substr(1, line.size() - 1));
        break;
      case 'C': {  // client's inputs
        std::stringstream ss(line);
        std::string value;
        std::getline(ss, value, ' ');
        assert(value == "C");
        while (std::getline(ss, value, ' ')) ++algorithm_description.number_of_input_wires_parent_a;
        break;
      }
      case 'S': {  // server's inputs
        std::stringstream ss(line);
        std::string value;
        std::getline(ss, value, ' ');
        assert(value == "S");
        while (std::getline(ss, value, ' ')) ++algorithm_description.number_of_input_wires_parent_a;
        break;
      }
      default:
        throw std::logic_error(std::string("Invalid first symbol ") + line[0]);
    }
  } while (line != "#Gates");
  std::vector<std::string> line_vector;

  assert(constant_input_0 != kInvalidValue);
  assert(constant_input_1 != kInvalidValue);

  // read gates
  do {
    std::getline(stream, line);
    if (line.size() <= 1) continue;
    switch (line[0]) {
      case 'A':  // AND gate, `A 101 102 103` denotes 103 = 101 AND 102
        // AND with constant_input_1 is the same gate
        // AND with constant_input_0 is illegal for now
        break;
      case 'I':  // INV gate, `I 101 102` denotes that 102 = NOT 101
        break;
      case 'M':  // MUX gate, `M 101 102 103 104` denotes 104 = 103 ? 102 : 101
        break;
      case 'X':  // XOR gate, `X 101 102 103` denotes 103 = 101 XOR 102
        // XOR with constant_input_1 is an INV gate
        // XOR with constant_input_0 is the same gate
        break;
      default:
        throw std::logic_error(std::string("Invalid first symbol ") + line[0]);
    }
    std::stringstream ss(line);
    while (std::getline(ss, line, ' ')) {
      line_vector.emplace_back(std::move(line));
      line.clear();
    }
    algorithm_description.number_of_input_wires_parent_a = std::stoull(line_vector.at(0));
    if (line_vector.size() == 2) {
      algorithm_description.number_of_output_wires = std::stoull(line_vector.at(1));
    } else if (line_vector.size() == 3) {
      algorithm_description.number_of_input_wires_parent_b = std::stoull(line_vector.at(1));
      algorithm_description.number_of_output_wires = std::stoull(line_vector.at(2));
    } else {
      throw std::runtime_error(
          std::string("Unexpected number of values: " + std::to_string(line_vector.size()) + "\n"));
    }
    line.clear();
    line_vector.clear();
  } while (line != "\n");

  assert(line.empty());

  // read output IDs
  while (std::getline(stream, line)) {
    std::stringstream ss(line);
    // split line
    while (std::getline(ss, line, ' ')) {
      line_vector.emplace_back(std::move(line));
    }

    if (line_vector.empty()) continue;
    const auto& type = line_vector.at(line_vector.size() - 1);
    PrimitiveOperation primitive_operation;
    if (type == std::string("XOR") || type == std::string("AND") || type == std::string("ADD") ||
        type == std::string("MUL") || type == std::string("OR")) {
      assert(line_vector.size() == 6);
      if (type == std::string("XOR"))
        primitive_operation.type = PrimitiveOperationType::kXor;
      else if (type == std::string("AND"))
        primitive_operation.type = PrimitiveOperationType::kAnd;
      else if (type == std::string("ADD"))
        primitive_operation.type = PrimitiveOperationType::kAdd;
      else if (type == std::string("MUL"))
        primitive_operation.type = PrimitiveOperationType::kMul;
      else if (type == std::string("OR"))
        primitive_operation.type = PrimitiveOperationType::kOr;
      primitive_operation.parent_a = std::stoull(line_vector.at(2));
      primitive_operation.parent_b = std::stoull(line_vector.at(3));
      primitive_operation.output_wire = std::stoull(line_vector.at(4));
    } else if (type == std::string("MUX")) {
      assert(line_vector.size() == 7);
      primitive_operation.type = PrimitiveOperationType::kMux;
      primitive_operation.parent_a = std::stoull(line_vector.at(2));
      primitive_operation.parent_b = std::stoull(line_vector.at(3));
      primitive_operation.selection_bit = std::stoull(line_vector.at(4));
      primitive_operation.output_wire = std::stoull(line_vector.at(5));
    } else if (type == std::string("INV")) {
      assert(line_vector.size() == 5);
      primitive_operation.type = PrimitiveOperationType::kInv;
      primitive_operation.parent_a = std::stoull(line_vector.at(2));
      primitive_operation.output_wire = std::stoull(line_vector.at(3));
    } else {
      throw std::runtime_error("Unknown operation type: " + line_vector.at(line_vector.size() - 1) +
                               "\n");
    }
    algorithm_description.gates.emplace_back(primitive_operation);
    line.clear();
    line_vector.clear();
  }
  return algorithm_description;
}

}  // namespace encrypto::motion

max_stars_repo_name: tompetersen/MOTION

max_issues_repo_name: tompetersen/MOTION

max_forks_repo_name: tompetersen/MOTION


text:
#include "storage/serialization.hpp"

#include "../common/range_tools.hpp"
#include "../common/temporary_file.hpp"

#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(serialization)

using namespace osrm;
using namespace osrm::storage;

BOOST_AUTO_TEST_CASE(pack_test)
{
    std::vector<bool> v = {0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1};

    BOOST_CHECK_EQUAL(storage::serialization::detail::packBits(v, 0, 8), 0x2e);
    BOOST_CHECK_EQUAL(storage::serialization::detail::packBits(v, 5, 7), 0x65);
    BOOST_CHECK_EQUAL(storage::serialization::detail::packBits(v, 6, 8), 0x95);
    BOOST_CHECK_EQUAL(storage::serialization::detail::packBits(v, 11, 1), 0x01);
}

BOOST_AUTO_TEST_CASE(unpack_test)
{
    std::vector<bool> v(14), expected = {0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1};

    storage::serialization::detail::unpackBits(v, 0, 8, 0x2e);
    storage::serialization::detail::unpackBits(v, 5, 7, 0x65);
    storage::serialization::detail::unpackBits(v, 6, 8, 0x95);
    storage::serialization::detail::unpackBits(v, 11, 1, 0x01);
    BOOST_CHECK_EQUAL_COLLECTIONS(v.begin(), v.end(), expected.begin(), expected.end());
}

BOOST_AUTO_TEST_CASE(tar_serialize_bool_vector)
{
    TemporaryFile tmp;
    {
        std::vector<std::vector<bool>> data = {
            {}, {0}, {1, 1, 1}, {1, 1, 0, 0, 1, 1, 0, 0}, {1, 1, 0, 0, 1, 1, 0, 0, 1}};
        for (const auto &v : data)
        {
            {
                tar::FileWriter writer(tmp.path, tar::FileWriter::GenerateFingerprint);
                storage::serialization::write(writer, "my_boolean_vector", v);
            }
            std::vector<bool> result;
            tar::FileReader reader(tmp.path, tar::FileReader::VerifyFingerprint);
            storage::serialization::read(reader, "my_boolean_vector", result);
            BOOST_CHECK_EQUAL_COLLECTIONS(v.begin(), v.end(), result.begin(), result.end());
        }
    }
}

BOOST_AUTO_TEST_CASE(tar_serialize_int_vector)
{
    TemporaryFile tmp;
    {
        std::vector<std::vector<int>> data = {{},
                                              {0},
                                              {1, -2, 3},
                                              {4, -5, 6, -7, 8, -9, 10, -11},
                                              {-12, 13, -14, 15, -16, 17, -18, 19, -20}};
        for (const auto &v : data)
        {
            {
                tar::FileWriter writer(tmp.path, tar::FileWriter::GenerateFingerprint);
                storage::serialization::write(writer, "my_int_vector", v);
            }
            std::vector<int> result;
            tar::FileReader reader(tmp.path, tar::FileReader::VerifyFingerprint);
            storage::serialization::read(reader, "my_int_vector", result);
            BOOST_CHECK_EQUAL_COLLECTIONS(v.begin(), v.end(), result.begin(), result.end());
        }
    }
}

BOOST_AUTO_TEST_CASE(tar_serialize_unsigned_vector)
{
    TemporaryFile tmp;
    {
        std::vector<std::vector<unsigned>> data = {
            {}, {0}, {1, 2, 3}, {4, 5, 6, 7, 8, 9, 10, 11}, {12, 13, 14, 15, 16, 17, 18, 19, 20}};
        for (const auto &v : data)
        {
            {
                tar::FileWriter writer(tmp.path, tar::FileWriter::GenerateFingerprint);
                storage::serialization::write(writer, "my_unsigned_vector", v);
            }
            std::vector<unsigned> result;
            tar::FileReader reader(tmp.path, tar::FileReader::VerifyFingerprint);
            storage::serialization::read(reader, "my_unsigned_vector", result);
            BOOST_CHECK_EQUAL_COLLECTIONS(v.begin(), v.end(), result.begin(), result.end());
        }
    }
}

BOOST_AUTO_TEST_CASE(tar_serialize_deallocting_vector)
{
    TemporaryFile tmp;
    {
        std::vector<util::DeallocatingVector<unsigned>> data = {
            {}, {0}, {1, 2, 3}, {4, 5, 6, 7, 8, 9, 10, 11}, {12, 13, 14, 15, 16, 17, 18, 19, 20}};
        for (const auto &v : data)
        {
            {
                tar::FileWriter writer(tmp.path, tar::FileWriter::GenerateFingerprint);
                storage::serialization::write(writer, "my_unsigned_vector", v);
            }
            std::vector<unsigned> result;
            tar::FileReader reader(tmp.path, tar::FileReader::VerifyFingerprint);
            storage::serialization::read(reader, "my_unsigned_vector", result);
            BOOST_CHECK_EQUAL_COLLECTIONS(v.begin(), v.end(), result.begin(), result.end());
        }
    }
}

BOOST_AUTO_TEST_CASE(buffer_serialize_map)
{
    std::map<std::string, std::int32_t> map = {
        {"foo", 1}, {"barrrr", 2}, {"bal", 3}, {"bazbar", 4}, {"foofofofo", 5},
    };

    std::string buffer;
    {
        io::BufferWriter writer;
        storage::serialization::write(writer, map);
        buffer = writer.GetBuffer();
    }

    std::map<std::string, std::int32_t> result;
    {
        io::BufferReader reader(buffer);
        storage::serialization::read(reader, result);
    }

    for (auto &pair : map)
    {
        BOOST_CHECK_EQUAL(pair.second, result[pair.first]);
    }
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_issues_repo_name: serarca/osrm-backend

max_forks_repo_name: serarca/osrm-backend


text:
#ifndef SWISSARMYKNIFE_BYTES_UTILS_HPP
#define SWISSARMYKNIFE_BYTES_UTILS_HPP

#include <swissarmyknife/detail/config.hpp>

#include <string>
#include <sstream>
#include <cctype>
#include <math.h>
#include <stdexcept>
#include <fstream>
#include <boost/cstdint.hpp>
#include <boost/container/vector.hpp>
#include <boost/container/map.hpp>
#include <boost/assign.hpp>
#include <boost/foreach.hpp>

namespace swissarmyknife { namespace bytes {

    /**
     * \brief Constant telling how much bits there is in a nibble
     */
    const size_t NIBBLE_BITS = 4;

    /**
     * \brief Constant telling how much Nibbles are in a byte
     */
    const size_t BYTE_NIBBLES = 2;

    /**
     * \brief Convers the given byte array of the given length to a corresponding hexadecimal number in a string.
     * \param bytes Array of bytes
     * \param length Length of the byte array
     */
    inline std::string to_hexstring(const boost::uint8_t *bytes, const size_t length) {
        uint8_t ch = 0x00;
        size_t i = 0;

        if (bytes == NULL || length <= 0)
            return std::string("");

        /**
         * Constant array which can be used to convert hex strings to real nibbles.
         */
        const char nibbleToChar[] = {'0', '1', '2', '3', '4', '5',
                                     '6', '7', '8', '9', 'a', 'b',
                                     'c', 'd', 'e', 'f'};

        std::string out;
        out.reserve(length*2);
        while (i < length) {

            ch = (bytes[i] & 0xF0); // Strip off high nibble
            ch = (ch >> NIBBLE_BITS); // shift the bits down
            ch = (ch & 0x0F); // must do this is high order bit is on!

            out.push_back(nibbleToChar[ch]); // convert the nibble to a String Character

            ch = (bytes[i] & 0x0F); // Strip off low nibble

            out.push_back(nibbleToChar[ch]); // convert the nibble to a String Character

            i++;
        }

        return out;
    }

    /**
     * \brief Convers the given byte array of the given length to a corresponding binary number in a string.
     * \param byteArray Array of bytes
     */
    inline std::string to_binstring(const boost::container::vector<boost::uint8_t> &byteArray) {
        std::stringstream bitsRepresentation;
        const int shift = 8 * sizeof( uint8_t ) - 1;
        const uint8_t mask = 1 << shift;

        BOOST_FOREACH(uint8_t byte, byteArray) {

            for ( size_t i = 1; i <= shift + 1; i++ ) {
                bitsRepresentation << ( byte & mask ? '1' : '0' );
                byte <<= 1;
            }
        }

        return bitsRepresentation.str();
    }

    /**
     * \brief Converts the given hexChars to the byte corresponding
     * \param highNibbleChar
     * \param lowNibbleChar
     */
    inline boost::uint8_t from_hexchar(char highNibbleChar, char lowNibbleChar) {
        const boost::container::map<char, boost::uint8_t> charToNibble = boost::assign::map_list_of('0', 0)('1', 1)('2', 2)
                                                                                ('3', 3)('4', 4)('5', 5)
                                                                                ('6', 6)('7', 7)('8', 8)
                                                                                ('9', 9)('a', 10)('b', 11)
                                                                                ('c', 12)('d', 13)('e', 14)
                                                                                ('f', 15);
        if (!isdigit(highNibbleChar)) {
            highNibbleChar = tolower(highNibbleChar);
        }

        if (!isdigit(lowNibbleChar)) {
            lowNibbleChar = tolower(lowNibbleChar);
        }

        if ( (charToNibble.find(highNibbleChar) != charToNibble.end()) && ( charToNibble.find(lowNibbleChar) != charToNibble.end() ) ) {
            boost::uint8_t highNibble = charToNibble.find(highNibbleChar)->second;
            boost::uint8_t lowNibble = charToNibble.find(lowNibbleChar)->second;

            highNibble <<= NIBBLE_BITS; // make it high
            lowNibble |= highNibble; // merge them together

            return lowNibble;
        }

        return 0; // This is invalid
    }

    /**
     * \brief This function can be used to parse a string of hexadecimal number back into bits representation.
     * Note that it runs from left to right, putting eventually the last nibble empty if the size of the input string isn't a multiple of 2.
     * \param hexString to convert
     */
    inline boost::container::vector<boost::uint8_t> from_hexstring(const std::string &hexString) {
        size_t nibblePaddedSize = ( (hexString.size() / BYTE_NIBBLES) + (hexString.size() % BYTE_NIBBLES) );

        if ((nibblePaddedSize & 1) != 0) {
            ++nibblePaddedSize;
        }

        boost::container::vector<boost::uint8_t> result;
        result.reserve(nibblePaddedSize);

        for (std::string::const_iterator iter = hexString.begin(); iter != hexString.end(); iter += BYTE_NIBBLES) {

            if ( (iter+1) != hexString.end() ) {
                result.push_back(from_hexchar(*iter, *(iter+1)));
            } else {
                result.push_back(from_hexchar(*iter, '0'));
                break;
            }
        }

        return result;
    }

    /**
     * \brief This function transforms any byteArray in the chosen (u)int*_t type.
     * \param byteArray To transform into native uint
     * \return The int requested with the value of the byteArray.
     */
    template<typename intX_t>
    inline intX_t from_byteArray(const boost::container::vector<boost::uint8_t> &byteArray) {
        intX_t result = 0x0;

        for (size_t i = 0; i < sizeof(intX_t); ++i) {
            result |= static_cast<intX_t>(byteArray[i] << (CHAR_BIT * (sizeof(intX_t) - (i+1))));
        }

        return result;
    }

    /**
     * \brief This methods opens up a file and parses it's bytes into a bytearray.
     * \param binaryFilePath Where to find the file to load
     * \return The bytearray corresponding to the file content
     *
     * \throws std::runtime_error In case the file isn't found.
     */
    inline boost::shared_ptr<boost::container::vector<boost::uint8_t> > load_bytearray(const std::string binaryFilePath) {
        boost::shared_ptr<boost::container::vector<boost::uint8_t> > bytearray;
        std::ifstream in(binaryFilePath.data(), std::ios_base::in | std::ios::binary);

        if (in.good()) {
            in.seekg(0, in.end);
            std::streampos lengthToRead = in.tellg();
            in.seekg(0, in.beg);

            bytearray.reset(new boost::container::vector<boost::uint8_t>(lengthToRead, 0x0));
            in.read(reinterpret_cast<char*>(&bytearray->at(0)), lengthToRead);
            in.close();
        } else {
            throw std::runtime_error("File " + binaryFilePath + " not found.");
        }

        return bytearray;
    }
}}

#endif

ext: hpp

max_stars_repo_name: daminetreg/lib-cpp-swissarmyknife

max_issues_repo_name: daminetreg/lib-cpp-swissarmyknife

max_forks_repo_name: daminetreg/lib-cpp-swissarmyknife


text:
#include <string>
#include <iostream>
#include <vector>
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
#include "../src/strutils.h"
#include "../src/Terminal.h"
#include "CommandProcessor.h"
#include "FileTab.h"

using namespace std;
using namespace boost::filesystem;

extern CmdMap cmdMap[];

CmdMap *findCmd(string name_to_find)
{
	for (int i = 0; i < CmdCount; i++)
	{
		if (cmdMap[i].cmdName == name_to_find)
			return &cmdMap[i];
	}
	return nullptr;
}

void loop()
{
	path full_path(current_path());
	FileTab fileTab;
	Terminal term("terminal", full_path.string() + "$", &fileTab);
	CommandProcessor cp(&term, &fileTab);
	while (true)
	{
		term.redraw();
		term.read();
		if (term.argc <= 1) continue;
		CmdMap *cmdMap = findCmd(term.argv[1]);
		if (cmdMap)
			cp.run(cmdMap, term.argc, term.argv);
		else
			cp.call(term.argc, term.argv);
	}
}

int main(int argc, const char** argv)
{
	loop();
	return 0;
}

max_stars_repo_name: borneq/terminal-edit

max_issues_repo_name: borneq/terminal-edit

max_forks_repo_name: borneq/terminal-edit


text:
#include <voxelized_geometry_tools/pointcloud_voxelization_ros_interface.hpp>

#include <cstring>
#include <map>
#include <stdexcept>
#include <vector>

#include <Eigen/Geometry>
#include <sensor_msgs/PointCloud2.h>
#include <voxelized_geometry_tools/pointcloud_voxelization_interface.hpp>

namespace voxelized_geometry_tools
{
namespace pointcloud_voxelization
{
PointCloud2Wrapper::PointCloud2Wrapper(
    const sensor_msgs::PointCloud2* const cloud_ptr,
    const Eigen::Isometry3d& origin_transform, const double max_range)
    : cloud_ptr_(cloud_ptr), origin_transform_(origin_transform),
      max_range_(max_range)
{
  if (cloud_ptr_ == nullptr)
  {
    throw std::invalid_argument("cloud_ptr_ == nullptr");
  }
  if (max_range_ <= 0.0)
  {
    throw std::runtime_error("max_range_ <= 0.0");
  }
  // Figure out what the size and offset for XYZ fields in the pointcloud are.
  std::map<std::string, uint8_t> field_type_map;
  std::map<std::string, size_t> field_offset_map;
  for (const auto& field : cloud_ptr_->fields)
  {
    field_type_map[field.name] = field.datatype;
    field_offset_map[field.name] = static_cast<size_t>(field.offset);
  }
  // Check field types
  if (field_type_map.at("x") != sensor_msgs::PointField::FLOAT32)
  {
    throw std::invalid_argument("PointCloud x field is not FLOAT32");
  }
  if (field_type_map.at("y") != sensor_msgs::PointField::FLOAT32)
  {
    throw std::invalid_argument("PointCloud y field is not FLOAT32");
  }
  if (field_type_map.at("z") != sensor_msgs::PointField::FLOAT32)
  {
    throw std::invalid_argument("PointCloud z field is not FLOAT32");
  }
  // Check that x, y, and z are sequential.
  const size_t x_offset = field_offset_map.at("x");
  const size_t y_offset = field_offset_map.at("y");
  const size_t z_offset = field_offset_map.at("z");
  if ((z_offset - y_offset) == sizeof(float) &&
      (y_offset - x_offset) == sizeof(float))
  {
    xyz_offset_from_point_start_ = x_offset;
  }
  else
  {
    throw std::invalid_argument(
        "PointCloud does not have sequential xyz fields");
  }
}
}  // namespace pointcloud_voxelization
}  // namespace voxelized_geometry_tools


text:
/*
Copyright (c) 2015-2019, Florian Sittel (www.lettis.net) and Daniel Nagel
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER 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.
*/
#pragma once

#include <list>
#include <map>

#include <boost/program_options.hpp>
/*! \file
 * \brief Noise Assignment
 *
 * \sa \link Clustering::Noise
 */
namespace Clustering {
  /*!
   * \brief functions related to noise assignment
   *
   * This module contains all function for identifying and dynamically
   * reassigning noise. The underlaying principal is to assign low populated
   * regions dynamically to the previous state, to improve the meta-stability
   * of the resulting states.
   * In Nagel19 it was shown that this works better than coring in case of low
   * dimensional input. I.e., if the input is not homogeniously distributed in
   * the input coordinates.
   */
  namespace Noise {
    //! map for sorting clusters by population
    typedef std::map<int,unsigned int> CounterClustMap;

    /*!
     * \brief controlling function and user interface for noise assignment
     *
     * \param states single column file with state information.
     * \param basename basename used in 'clustering network' (def.: 'clust.').
     * \param cmin population threshold in percent below which an geometrically
     *            isolated cluster gets assigned as noise.
     * \param concat-nframes no. of frames per trajectory.
     * \param concat-limits length of concated trajectories.
     * \param output file name to store resulting trajectory.
     * \param cores file name to store resulting cores.
     * \return void
     * \note This code needs to be executed from the same directory as clustering
     *       density
     * \warning This function is still in beta.
     */
    void
    main(boost::program_options::variables_map args);
  } // end namespace Noise
} // end namespace Clustering

max_stars_repo_name: gregorweiss/Clustering

max_issues_repo_name: gregorweiss/Clustering

max_forks_repo_name: gregorweiss/Clustering


text:
/**
   @author Shin'ichiro Nakaoka
*/

#include "SceneDragger.h"
#include <cnoid/SceneWidget>
#include <cnoid/SceneRenderer>
#include <cnoid/SceneUtil>
#include <cnoid/MeshGenerator>
#include <cnoid/MeshExtractor>
#include <cnoid/EigenUtil>
#include <boost/bind.hpp>
#include <iostream>

using namespace std;
using namespace cnoid;

namespace {

const char* axisNames[3] = { "x", "y", "z" };

/**
   \note This node is not inserted the node path obtained by SceneWidgetEvent::nodePath()
*/
class ViewpointDependentRenderingSelector : public SgGroup
{
    Vector3 axis;
    double thresh;

public:
    ViewpointDependentRenderingSelector(){
        axis = Vector3::UnitX();
        thresh = cos(radian(45.0));
    }

    ViewpointDependentRenderingSelector(const ViewpointDependentRenderingSelector& org, SgCloneMap& cloneMap)
        : SgGroup(org, cloneMap) {
        axis = org.axis;
        thresh = org.thresh;
    }

    virtual SgObject* clone(SgCloneMap& cloneMap) const {
        return new ViewpointDependentRenderingSelector(*this, cloneMap);
    }

    void setAxis(const Vector3& axis){
        this->axis = axis;
    }

    void setSwitchAngle(double rad){
        thresh = cos(rad);
    }

    virtual void accept(SceneVisitor& visitor) {
        SceneRenderer* renderer = dynamic_cast<SceneRenderer*>(&visitor);
        if(!renderer){
            visitor.visitGroup(this);
        } else {
            const Affine3& C = renderer->currentCameraPosition();
            const Affine3& M = renderer->currentModelTransform();
            bool isPerspetiveCamera = (renderer->projectionMatrix()(3, 3) == 0.0);
            if(isPerspetiveCamera){
                double d = fabs((C.translation() - M.translation()).normalized().dot((M.linear() * axis).normalized()));
                if(d > thresh){
                    if(numChildren() > 0){
                        child(0)->accept(visitor);
                    }
                } else {
                    if(numChildren() > 1){
                        child(1)->accept(visitor);
                    }
                }
            } else {

            }
        }
    }
};

}

TranslationDragger::TranslationDragger()
{
    axisCylinderNormalizedRadius = 0.04;

    MeshGenerator meshGenerator;

    SgShape* cone = new SgShape;
    meshGenerator.setDivisionNumber(20);
    cone->setMesh(meshGenerator.generateCone(0.1, 0.2, true, true));
    SgPosTransform* conePos = new SgPosTransform;
    conePos->setTranslation(Vector3(0.0, 0.9, 0.0));
    conePos->addChild(cone);

    SgShape* cylinder = new SgShape;
    meshGenerator.setDivisionNumber(12);
    cylinder->setMesh(meshGenerator.generateCylinder(axisCylinderNormalizedRadius, 1.8, true, false));
    SgPosTransform* cylinderPos = new SgPosTransform;
    cylinderPos->setTranslation(Vector3(0.0, -0.1, 0.0));
    cylinderPos->addChild(cylinder);

    MeshExtractor meshExtractor;
    SgGroupPtr group = new SgGroup;
    group->addChild(conePos);
    group->addChild(cylinderPos);
    SgMeshPtr mesh = meshExtractor.integrate(group);

    scale = new SgScaleTransform;
    for(int i=0; i < 3; ++i){
        SgShape* shape = new SgShape;
        shape->setMesh(mesh);

        SgMaterial* material = shape->getOrCreateMaterial();
        Vector3f color(0.2f, 0.2f, 0.2f);
        color[i] = 1.0f;
        material->setDiffuseColor(Vector3f::Zero());
        material->setEmissiveColor(color);
        material->setAmbientIntensity(0.0f);
        material->setTransparency(0.6f);

        SgPosTransform* arrow = new SgPosTransform;
        arrow->addChild(shape);
        if(i == 0){
            arrow->setRotation(AngleAxis(-PI / 2.0, Vector3::UnitZ()));
        } else if(i == 2){
            arrow->setRotation(AngleAxis( PI / 2.0, Vector3::UnitX()));
        }
        SgInvariantGroup* invariant = new SgInvariantGroup;
        invariant->setName(axisNames[i]);
        invariant->addChild(arrow);
        scale->addChild(invariant);
    }
    addChild(scale);

    isContainerMode_ = false;
}

TranslationDragger::TranslationDragger(const TranslationDragger& org)
{
    scale = new SgScaleTransform;
    scale->setScale(org.scale->scale());
    org.scale->copyChildren(scale);
    addChild(scale);

    axisCylinderNormalizedRadius = org.axisCylinderNormalizedRadius;
    isContainerMode_ = org.isContainerMode_;
}

TranslationDragger::TranslationDragger(const TranslationDragger& org, SgCloneMap& cloneMap)
    : SgPosTransform(org, cloneMap)
{
    scale = getChild<SgScaleTransform>(0);
    axisCylinderNormalizedRadius = org.axisCylinderNormalizedRadius;
    isContainerMode_ = org.isContainerMode_;
}

SgObject* TranslationDragger::clone(SgCloneMap& cloneMap) const
{
    return new TranslationDragger(*this, cloneMap);
}

double TranslationDragger::radius() const
{
    return scale->scale().x();
}

void TranslationDragger::setRadius(double r)
{
    scale->setScale(r);
}

void TranslationDragger::setContainerMode(bool on)
{
    isContainerMode_ = on;
}

bool TranslationDragger::isContainerMode() const
{
    return isContainerMode_;
}

bool TranslationDragger::isDragging() const
{
    return dragProjector.isDragging();
}

const Vector3& TranslationDragger::draggedTranslation() const
{
    return dragProjector.translation();
}

const Affine3& TranslationDragger::draggedPosition() const
{
    return dragProjector.position();
}

static bool detectAxisFromNodePath(const SgNodePath& path, SgNode* topNode, int& out_axis, int& out_indexOfTopNode)
{
    for(size_t i=0; i < path.size(); ++i){
        const SgNode* node = path[i];
        if(node == topNode){
            out_indexOfTopNode = i;
        }
        if(out_indexOfTopNode >= 0){
            const string& name = node->name();
            if(!name.empty()){
                for(int j=0; j < 3; ++j){
                     if(name == axisNames[j]){
                        out_axis = j;
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

bool TranslationDragger::onButtonPressEvent(const SceneWidgetEvent& event)
{
    int axis;
    int indexOfTopNode;
    const SgNodePath& path = event.nodePath();
    if(detectAxisFromNodePath(path, this, axis, indexOfTopNode)){
        SgNodePath::const_iterator axisIter = path.begin() + indexOfTopNode + 1;
        const Affine3 T_global = calcTotalTransform(path.begin(), axisIter);
        dragProjector.setInitialPosition(T_global);
        const Affine3 T_axis = calcTotalTransform(axisIter, path.end());
        const Vector3 p_local = (T_global * T_axis).inverse() * event.point();
        if(p_local.norm() < 2.0 * axisCylinderNormalizedRadius){
            dragProjector.setTranslationAlongViewPlane();
        } else {
            dragProjector.setTranslationAxis(T_global.linear().col(axis));
        }
        if(dragProjector.startTranslation(event)){
            sigTranslationStarted_();
            return true;
        }
    }
    return false;
}

bool TranslationDragger::onButtonReleaseEvent(const SceneWidgetEvent& event)
{
    if(dragProjector.isDragging()){
        sigTranslationFinished_();
        dragProjector.resetDragMode();
        return true;
    }
    return false;
}

bool TranslationDragger::onPointerMoveEvent(const SceneWidgetEvent& event)
{
    if(dragProjector.dragTranslation(event)){
        if(isContainerMode_){
            setPosition(dragProjector.position());
            notifyUpdate();
        }
        sigTranslationDragged_();
        return true;
    }
    return false;
}

void TranslationDragger::onPointerLeaveEvent(const SceneWidgetEvent& event)
{
    if(dragProjector.isDragging()){
        sigTranslationFinished_();
        dragProjector.resetDragMode();
    }
}

RotationDragger::RotationDragger()
{
    MeshGenerator meshGenerator;
    meshGenerator.setDivisionNumber(36);
    SgMeshPtr beltMesh1 = meshGenerator.generateDisc(1.0, 1.0 - 0.2);
    meshGenerator.setDivisionNumber(24);
    SgMeshPtr beltMesh2 = meshGenerator.generateCylinder(1.0, 0.2, false, false);

    scale = new SgScaleTransform;

    // make dragger belts
    for(int i=0; i < 3; ++i){

        SgMaterial* material = new SgMaterial;
        Vector3f color(0.2f, 0.2f, 0.2f);
        color[i] = 1.0f;
        material->setDiffuseColor(Vector3f::Zero());
        material->setEmissiveColor(color);
        material->setAmbientIntensity(0.0f);
        material->setTransparency(0.6f);

        SgShape* beltShape1 = new SgShape;
        beltShape1->setMesh(beltMesh1);
        beltShape1->setMaterial(material);

        SgShape* beltShape2 = new SgShape;
        beltShape2->setMesh(beltMesh2);
        beltShape2->setMaterial(material);

        ViewpointDependentRenderingSelector* selector = new ViewpointDependentRenderingSelector;

        SgPosTransform* transform1 = new SgPosTransform;
        if(i == 0){ // x-axis
            selector->setAxis(Vector3::UnitX());
            transform1->setRotation(AngleAxis(PI / 2.0, Vector3::UnitY()));
        } else if(i == 1){ // y-axis
            selector->setAxis(Vector3::UnitY());
            transform1->setRotation(AngleAxis(-PI / 2.0, Vector3::UnitX()));
        } else if(i == 2) { // z-axis
            selector->setAxis(Vector3::UnitZ());
        }
        transform1->addChild(beltShape1);
        SgInvariantGroup* belt1 = new SgInvariantGroup;
        belt1->setName(axisNames[i]);
        belt1->addChild(transform1);
        selector->addChild(belt1);

        SgPosTransform* transform2 = new SgPosTransform;
        if(i == 0){ // x-axis
            transform2->setRotation(AngleAxis(-PI / 2.0, Vector3::UnitZ()));
        } else if(i == 2) { // z-axis
            transform2->setRotation(AngleAxis(PI / 2.0, Vector3::UnitX()));
        }
        transform2->addChild(beltShape2);
        SgInvariantGroup* belt2 = new SgInvariantGroup;
        belt2->setName(axisNames[i]);
        belt2->addChild(transform2);
        selector->addChild(belt2);

        scale->addChild(selector);
    }

    addChild(scale);

    isContainerMode_ = false;
}

RotationDragger::RotationDragger(const RotationDragger& org)
{
    scale = new SgScaleTransform;
    scale->setScale(org.scale->scale());
    org.scale->copyChildren(scale);
    addChild(scale);
    isContainerMode_ = org.isContainerMode_;
}

RotationDragger::RotationDragger(const RotationDragger& org, SgCloneMap& cloneMap)
    : SgPosTransform(org, cloneMap)
{
    scale = getChild<SgScaleTransform>(0);
    isContainerMode_ = org.isContainerMode_;
}

SgObject* RotationDragger::clone(SgCloneMap& cloneMap) const
{
    return new RotationDragger(*this, cloneMap);
}

void RotationDragger::setRadius(double r)
{
    scale->setScale(r);
}

void RotationDragger::setContainerMode(bool on)
{
    isContainerMode_ = on;
}

bool RotationDragger::isContainerMode() const
{
    return isContainerMode_;
}

bool RotationDragger::isDragging() const
{
    return dragProjector.isDragging();
}

const AngleAxis& RotationDragger::draggedAngleAxis() const
{
    return dragProjector.rotationAngleAxis();
}

const Affine3& RotationDragger::draggedPosition() const
{
    return dragProjector.position();
}

bool RotationDragger::onButtonPressEvent(const SceneWidgetEvent& event)
{
    int axis;
    int indexOfTopNode;
    if(detectAxisFromNodePath(event.nodePath(), this, axis, indexOfTopNode)){
        Affine3 T = calcTotalTransform(event.nodePath(), this);
        dragProjector.setInitialPosition(T);
        dragProjector.setRotationAxis(T.linear().col(axis));
        if(dragProjector.startRotation(event)){
            sigRotationStarted_();
            return true;
        }
    }
    return false;
}

bool RotationDragger::onButtonReleaseEvent(const SceneWidgetEvent& event)
{
    if(dragProjector.isDragging()){
        sigRotationFinished_();
        dragProjector.resetDragMode();
        return true;
    }
    return false;
}

bool RotationDragger::onPointerMoveEvent(const SceneWidgetEvent& event)
{
    if(dragProjector.dragRotation(event)){
        if(isContainerMode_){
            setPosition(dragProjector.position());
            notifyUpdate();
        }
        sigRotationDragged_(dragProjector.rotationAngleAxis());
        return true;
    }
    return false;
}

void RotationDragger::onPointerLeaveEvent(const SceneWidgetEvent& event)
{
    if(dragProjector.isDragging()){
        sigRotationFinished_();
        dragProjector.resetDragMode();
    }
}

PositionDragger::PositionDragger()
{
    translationDragger_ = new TranslationDragger;
    rotationDragger_ = new RotationDragger;
    initalizeDraggers();
    isDraggerAlwaysShown_ = false;
    isContainerMode_ = false;
}

PositionDragger::PositionDragger(const PositionDragger& org)
{
    translationDragger_ = new TranslationDragger(*org.translationDragger_);
    rotationDragger_ = new RotationDragger(*org.rotationDragger_);
    initalizeDraggers();
    isContainerMode_ = org.isContainerMode_;
    isDraggerAlwaysShown_ = org.isDraggerAlwaysShown_;
}

PositionDragger::PositionDragger(const PositionDragger& org, SgCloneMap& cloneMap)
{
    translationDragger_ = new TranslationDragger(*org.translationDragger_, cloneMap);
    rotationDragger_ = new RotationDragger(*org.rotationDragger_, cloneMap);
    initalizeDraggers();
    isContainerMode_ = org.isContainerMode_;
    isDraggerAlwaysShown_ = org.isDraggerAlwaysShown_;
}

void PositionDragger::initalizeDraggers()
{
    translationDragger_->sigTranslationStarted().connect(boost::ref(sigDragStarted_));
    translationDragger_->sigTranslationDragged().connect(
        boost::bind(&PositionDragger::onSubDraggerDragged, this));
    translationDragger_->sigTranslationFinished().connect(boost::ref(sigDragFinished_));

    rotationDragger_->sigRotationStarted().connect(boost::ref(sigDragStarted_));
    rotationDragger_->sigRotationDragged().connect(
        boost::bind(&PositionDragger::onSubDraggerDragged, this));
    rotationDragger_->sigRotationFinished().connect(boost::ref(sigDragFinished_));
}

SgObject* PositionDragger::clone(SgCloneMap& cloneMap) const
{
    return new PositionDragger(*this, cloneMap);
}

void PositionDragger::setRadius(double r, double translationAxisRatio)
{
    translationDragger_->setRadius(r * translationAxisRatio);
    rotationDragger_->setRadius(r);
}

void PositionDragger::setContainerMode(bool on)
{
    isContainerMode_ = on;
}

bool PositionDragger::isContainerMode() const
{
    return isContainerMode_;
}

void PositionDragger::setDraggerAlwaysShown(bool on)
{
    if(on != isDraggerAlwaysShown_){
        showDragMarkers(on);
    }
    isDraggerAlwaysShown_ = on;
}

bool PositionDragger::isDraggerAlwaysShown() const
{
    return isDraggerAlwaysShown_;
}

void PositionDragger::showDragMarkers(bool on)
{
    if(on){
        addChildOnce(translationDragger_, true);
        addChildOnce(rotationDragger_, true);
    } else {
        removeChild(translationDragger_, true);
        removeChild(rotationDragger_, true);
    }
}

Affine3 PositionDragger::draggedPosition() const
{
    if(rotationDragger_->isDragging()){
        return rotationDragger_->draggedPosition();
    } else if(translationDragger_->isDragging()){
        return translationDragger_->draggedPosition();
    } else if(dragProjector.isDragging()){
        return dragProjector.position();
    } else {
        return T();
    }
}

void PositionDragger::onSubDraggerDragged()
{
    if(isContainerMode_){
        setPosition(draggedPosition());
        notifyUpdate();
    }
    sigPositionDragged_();
}

bool PositionDragger::onButtonPressEvent(const SceneWidgetEvent& event)
{
    if(isContainerMode_){
        if(!isDraggerAlwaysShown_){
            showDragMarkers(true);
        }
        dragProjector.setInitialPosition(T());
        dragProjector.setTranslationAlongViewPlane();
        return dragProjector.startTranslation(event);
    }
    return false;
}

bool PositionDragger::onButtonReleaseEvent(const SceneWidgetEvent& event)
{
    if(isContainerMode_){
        if(dragProjector.isDragging()){
            dragProjector.resetDragMode();
            return true;
        }
    }
    return false;
}

bool PositionDragger::onPointerMoveEvent(const SceneWidgetEvent& event)
{
    if(isContainerMode_){
        if(dragProjector.drag(event)){
            setPosition(dragProjector.position());
            notifyUpdate();
            sigPositionDragged_();
            return true;
        }
    }
    return false;
}

void PositionDragger::onPointerLeaveEvent(const SceneWidgetEvent& event)
{
    if(isContainerMode_){
        dragProjector.resetDragMode();
    }
}

void PositionDragger::onFocusChanged(const SceneWidgetEvent& event, bool on)
{
    if(isContainerMode_){
        showDragMarkers(on || isDraggerAlwaysShown_);
    }
}

void PositionDragger::onSceneModeChanged(const SceneWidgetEvent& event)
{
    if(!event.sceneWidget()->isEditMode()){
        showDragMarkers(false);
    }
}

max_stars_repo_name: snozawa/choreonoid

max_issues_repo_name: snozawa/choreonoid

max_forks_repo_name: snozawa/choreonoid


text:
/*====================================================================

	wolframkit - cellular automata playground

	Copyright (c) 2019 Nicola Pisanti <nicola@npisanti.com>

	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 3 of the License, or
	(at your option) any later version.

	This program 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program. If not, see <http://www.gnu.org/licenses/>.

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

#include "RuleSeq.h"
#include <boost/filesystem.hpp>
#include "ofJson.h"
#include "ofAppRunner.h"

np::RuleSeq::Entry::Entry(){
    rule = 60;
    density = 0.5;
    for( int i=0; i<NUMSYNTHS; ++i ) thresholds[i] = 0;
}

np::RuleSeq::Buffer::Buffer(){
    tempo = 120;
    division = 16;
    num_bars = 8;
    first = 0;
    iEntry = 0;
}

np::RuleSeq::RuleSeq(){
    bChanged = false;
    iBuffer = 1;
}

bool np::RuleSeq::setup( std::string path ){

    this->path = path;
    if( ! ofFilePath::isAbsolute( path )){
        path = ofFilePath::getCurrentWorkingDirectory() + "/" + path;
    }
    this->name = ofFilePath::getFileName( path );

    ofFile file( path );
    if( file.exists() ){
        ofAddListener(ofEvents().update, this, &np::RuleSeq::checkFile);
        writeTimestamp = boost::filesystem::last_write_time( path );
        reload();
        return true;
    }else{
        ofLogError() << "[np::RuleSeq] file does not exists\n";
        return false;
    }
}

void np::RuleSeq::checkFile(ofEventArgs &args){
    timePassed += ofGetLastFrameTime();
    if( timePassed > interval ){
        time_t checkTimestamp = boost::filesystem::last_write_time( path );
        if( checkTimestamp != writeTimestamp){
            writeTimestamp = checkTimestamp;
            reload();
            ofLogNotice() << "["<<name<<"] file reloaded";
        }
    }
}

void np::RuleSeq::reload(){
    ofJson json = ofLoadJson( path );
    int b = (iBuffer==0) ? 1 : 0;

    try {
        ofJson general = json["general"];

        buffers[b].tempo = general["tempo"];
        buffers[b].division = general["division"];
        if( buffers[b].division<= 0 ){
            std::cout<<"[ "<<name<<" ] division must be greater than 0, setting do default (16)\n";
            buffers[b].division = 16;
        }
        buffers[b].num_bars = general["num_bars"];
        if( buffers[b].num_bars<= 0 ){
            std::cout<<"[ "<<name<<" ] num_bars must be greater than 0, setting do default (8)\n";
            buffers[b].num_bars = 8;
        }
        buffers[b].first = general["first_seq"];

//        std::cout<< "settings loaded: tempo="<<buffers[b].tempo<<" | division="<<buffers[b].division<<" | num_bars="<<buffers[b].num_bars<<" | first_seq="<<buffers[b].first<<"\n";

        ofJson seqs = json["sequences"];
        buffers[b].entries.resize( seqs.size() );
        auto & e = buffers[b].entries;

        for( size_t i=0; i<e.size(); ++i ){
            auto & seq = seqs[i];
            e[i].rule = seq["rule"];
            e[i].density = seq["density"];
//            std::cout<<"entry "<<i<<" density = "<< e[i].density<<"\n";
//            std::cout <<"  thresholds = ";
            ofJson t = seq["thresholds"];
            for( size_t k=0; k<NUMSYNTHS; ++k  ){
                if( k<t.size() ){
                    e[i].thresholds[k] = t[k];
//                    std::cout<<" "<<t[k];
                }else{
                    e[i].thresholds[k] = 8;
//                    std::cout<<" d8";
                }
            }
//            std::cout<<"\n";
        }
//        std::cout<<"RULESET LOADED!!!!!!!!!!!! entries="<<buffers[b].entries.size()<<"\n";
        bChanged = true;
    }
    catch ( ofJson::exception& e)
    {
         // output exception information
         std::cout << "[ "<<name<<" ] message: " << e.what() << '\n'
                   << "exception id: " << e.id << std::endl;
     }
}

bool np::RuleSeq::changed(){
    if(bChanged){
        bChanged = false;
        swapBuffers();
        buffers[iBuffer].iEntry = buffers[iBuffer].first;
        return true;
    }
    return false;
}

void np::RuleSeq::swapBuffers(){
    iBuffer = (iBuffer==0) ? 1 : 0;
}

int np::RuleSeq::division() const{
    return buffers[iBuffer].division;
}

int np::RuleSeq::tempo() const{
    return buffers[iBuffer].tempo;
}

int np::RuleSeq::numBars() const{
    return buffers[iBuffer].num_bars;
}

const np::RuleSeq::Entry & np::RuleSeq::entry() const{
    int i = buffers[iBuffer].iEntry;
    return buffers[iBuffer].entries[i];
}

void np::RuleSeq::next(){
    buffers[iBuffer].iEntry++;
    if (buffers[iBuffer].iEntry >= (int) buffers[iBuffer].entries.size()){
        buffers[iBuffer].iEntry = 0;
    }
}

max_stars_repo_name: npisanti/np-instruments

max_issues_repo_name: npisanti/np-instruments

max_forks_repo_name: npisanti/np-instruments


text:
#define CNOID_BACKWARD_COMPATIBILITY

#include <ros/ros.h>
#include <std_msgs/Int32.h>
#include <tms_msg_rc/smartpal_control.h>
#include <tms_msg_rp/action.h>
#include <tms_msg_rp/rps_path_planning.h>

#include <boost/bind.hpp>

#include <cnoid/Plugin>
#include <cnoid/MenuManager>
#include <cnoid/MessageView>
#include <cnoid/LazyCaller>

#include <Grasp/PlanBase.h>
#include <Grasp/PlanInterface.h>
#include <Grasp/VectorMath.h>
#include <PRM/TrajectoryPlanner.h>

#include <Grasp/GraspController.h>

#include <boost/thread.hpp>

#define rad2deg(x) ((x) * (180.0) / M_PI)
#define deg2rad(x) ((x)*M_PI / 180.0)

#define UNIT_ALL 0
#define UNIT_VEHICLE 1
#define UNIT_ARM_R 2
#define UNIT_ARM_L 3
#define UNIT_GRIPPER_R 4
#define UNIT_GRIPPER_L 5
#define UNIT_LUMBA 6
#define UNIT_CC 7

#define CMD_CLEARALARM 0
#define CMD_SETPOWER 1
#define CMD_SETSERVO 2
#define CMD_PAUSE 3
#define CMD_RESUME 4
#define CMD_ABORT 5
#define CMD_STOP 6
#define CMD_GETSTATE 7
#define CMD_GETPOSE 8
#define CMD_MOVE_ABS 15
#define CMD_MOVE_REL 16

using namespace std;
using namespace boost;
using namespace cnoid;
using namespace grasp;

int argc;
char **argv;
ros::ServiceClient sp5_control_client;
ros::ServiceClient path_planning_client;

bool action(tms_msg_rp::action::Request &req, tms_msg_rp::action::Response &res)
{
  tms_msg_rc::smartpal_control sp_control_srv;

  //----------------------------------------------------------------------
  sp_control_srv.request.unit = UNIT_ARM_R;
  sp_control_srv.request.cmd = CMD_MOVE_ABS;
  sp_control_srv.request.arg.resize(8);
  sp_control_srv.request.arg[0] = 0;
  sp_control_srv.request.arg[1] = -10;
  sp_control_srv.request.arg[2] = 0;
  sp_control_srv.request.arg[3] = 0;
  sp_control_srv.request.arg[4] = 0;
  sp_control_srv.request.arg[5] = 0;
  sp_control_srv.request.arg[6] = 0;
  sp_control_srv.request.arg[7] = 10;

  if (sp5_control_client.call(sp_control_srv))
    ROS_INFO("result: %d", sp_control_srv.response.result);
  else
    ROS_ERROR("Failed to call service sp5_control");

  sp_control_srv.request.unit = UNIT_ARM_L;
  sp_control_srv.request.cmd = CMD_MOVE_ABS;
  sp_control_srv.request.arg.resize(8);
  sp_control_srv.request.arg[0] = 0;
  sp_control_srv.request.arg[1] = -10;
  sp_control_srv.request.arg[2] = 0;
  sp_control_srv.request.arg[3] = 0;
  sp_control_srv.request.arg[4] = 0;
  sp_control_srv.request.arg[5] = 0;
  sp_control_srv.request.arg[6] = 0;
  sp_control_srv.request.arg[7] = 10;

  if (sp5_control_client.call(sp_control_srv))
    ROS_INFO("result: %d", sp_control_srv.response.result);
  else
    ROS_ERROR("Failed to call service sp5_control");

  cout << "PRM start" << endl;
  if (!PlanBase::instance()->targetArmFinger)
  {
    MessageView::mainInstance()->putln("error: Set Robot");
  }
  cout << "check setRobot" << endl;

  cnoid::Link *rl = PlanBase::instance()->targetArmFinger->bodyItemRobot->body()->rootLink();
  cout << "make linkt" << endl;

  MessageView::mainInstance()->putln("run SmartpalAction!");

  PlanBase *pb = PlanBase::instance();
  // setrobot
  pb->setTrajectoryPlanDOF();
  // setobject

  for (int i = 0; i < 18; i++)
  {
    pb->bodyItemRobot()->body()->joint(i)->q() = 0;
  }
  pb->bodyItemRobot()->body()->joint(3)->q() = deg2rad(-10.0);
  pb->bodyItemRobot()->body()->joint(11)->q() = deg2rad(10.0);

  pb->initial();
  pb->graspMotionSeq.clear();

  pb->setGraspingState(PlanBase::NOT_GRASPING);
  pb->setObjectContactState(PlanBase::ON_ENVIRONMENT);
  pb->graspMotionSeq.push_back(pb->getMotionState());

  bool success = GraspController::instance()->loadAndSelectGraspPattern();
  if (!success)
  {
    cout << "Error: Cannot find grasping posure" << endl;
  }

  MotionState graspMotionState = pb->getMotionState();

  Vector3 Pp_(pb->palm()->p());
  Matrix3 Rp_(pb->palm()->R());

  //==== Approach Point
  pb->setMotionState(graspMotionState);
  pb->arm()->IK_arm(Rp_ * pb->arm()->approachOffset + Pp_ + Vector3(0, 0, 0.05), Rp_);
  pb->setGraspingState(PlanBase::UNDER_GRASPING);
  for (int i = 0; i < pb->nFing(); i++)
  {
    for (int j = 0; j < pb->fingers(i)->fing_path->numJoints(); j++)
    {
      pb->fingers(i)->fing_path->joint(j)->q() = pb->fingers(i)->fingerOpenPose[j];
    }
  }
  pb->graspMotionSeq.push_back(pb->getMotionState());

  //==== Grasp Point and Hand open
  pb->setMotionState(graspMotionState);
  pb->setGraspingState(PlanBase::UNDER_GRASPING);
  for (int i = 0; i < pb->nFing(); i++)
  {
    for (int j = 0; j < pb->fingers(i)->fing_path->numJoints(); j++)
    {
      pb->fingers(i)->fing_path->joint(j)->q() = pb->fingers(i)->fingerOpenPose[j];
    }
  }
  pb->graspMotionSeq.push_back(pb->getMotionState());

  //==== hand close
  pb->setMotionState(graspMotionState);
  pb->setGraspingState(PlanBase::GRASPING);
  pb->graspMotionSeq.push_back(pb->getMotionState());

  //==== lift up
  pb->arm()->IK_arm(Vector3(Vector3(0, 0, 0.05) + Pp_), Rp_);

  pb->setObjectContactState(PlanBase::OFF_ENVIRONMENT);
  pb->graspMotionSeq.push_back(pb->getMotionState());

  //==== end point
  vector< double > closefinger;
  for (int i = 0; i < pb->nFing(); i++)
  {
    for (int j = 0; j < pb->fingers(i)->fing_path->numJoints(); j++)
    {
      closefinger.push_back(pb->fingers(i)->fing_path->joint(j)->q());
    }
  }

  for (int i = 0; i < 18; i++)
  {
    pb->bodyItemRobot()->body()->joint(i)->q() = 0;
  }
  pb->bodyItemRobot()->body()->joint(3)->q() = deg2rad(-10.0);
  pb->bodyItemRobot()->body()->joint(11)->q() = deg2rad(10.0);

  int cnt = 0;
  for (int i = 0; i < pb->nFing(); i++)
  {
    for (int j = 0; j < pb->fingers(i)->fing_path->numJoints(); j++)
    {
      pb->fingers(i)->fing_path->joint(j)->q() = closefinger[cnt++];
    }
  }
  pb->graspMotionSeq.push_back(pb->getMotionState());

  TrajectoryPlanner tp;
  success = tp.doTrajectoryPlanning();

  if (!success)
  {
    cout << "Error: Cannot find motion path" << endl;
  }

  res.result = (float)success;

  double jonit[18];

  for (int i = 0; i < tp.motionSeq.size(); i++)
  {
    for (int j = 0; j < tp.motionSeq[i].jointSeq.size(); j++)
    {
      jonit[j] = rad2deg(tp.motionSeq[i].jointSeq(j));
      cout << "jonit[" << j << "] : " << jonit[j] << endl;
    }

    sp_control_srv.request.unit = UNIT_ARM_R;
    sp_control_srv.request.cmd = CMD_MOVE_ABS;
    sp_control_srv.request.arg.resize(8);
    sp_control_srv.request.arg[0] = jonit[2];
    sp_control_srv.request.arg[1] = jonit[3];
    sp_control_srv.request.arg[2] = jonit[4];
    sp_control_srv.request.arg[3] = jonit[5];
    sp_control_srv.request.arg[4] = jonit[6];
    sp_control_srv.request.arg[5] = jonit[7];
    sp_control_srv.request.arg[6] = jonit[8];
    sp_control_srv.request.arg[7] = 10;

    if (sp5_control_client.call(sp_control_srv))
      ROS_INFO("result: %d", sp_control_srv.response.result);
    else
      ROS_ERROR("Failed to call service sp5_control");

    //----------------------------------------------------------------------------
    sp_control_srv.request.unit = UNIT_LUMBA;
    sp_control_srv.request.cmd = 16;
    sp_control_srv.request.arg.resize(4);
    sp_control_srv.request.arg[0] = jonit[0];
    sp_control_srv.request.arg[1] = jonit[1];
    sp_control_srv.request.arg[2] = 10;
    sp_control_srv.request.arg[3] = 10;

    if (sp5_control_client.call(sp_control_srv))
      ROS_INFO("result: %d", sp_control_srv.response.result);
    else
      ROS_ERROR("Failed to call service sp5_control");

    //----------------------------------------------------------------------------
    sp_control_srv.request.unit = UNIT_GRIPPER_R;
    sp_control_srv.request.cmd = CMD_MOVE_ABS;
    sp_control_srv.request.arg.resize(3);
    sp_control_srv.request.arg[0] = jonit[9];
    sp_control_srv.request.arg[1] = 10;
    sp_control_srv.request.arg[2] = 10;

    if (sp5_control_client.call(sp_control_srv))
      ROS_INFO("result: %d", sp_control_srv.response.result);
    else
      ROS_ERROR("Failed to call service sp5_control");

    sleep(3);
  }

  return true;
}

class SmartpalActionPlugin : public Plugin
{
public:
  void LoopRosTest(void)
  {
    //----------------------------------------------------------------------
    tms_msg_rp::rps_path_planning rplsrv;

    rplsrv.request.robot_id = 1;
    rplsrv.request.rps_goal_candidate.rps_route.resize(1);
    rplsrv.request.rps_goal_candidate.rps_route[0].x = 3000;
    rplsrv.request.rps_goal_candidate.rps_route[0].y = 1000;
    rplsrv.request.rps_goal_candidate.rps_route[0].th = 0;

    if (path_planning_client.call(rplsrv))
    {
      ROS_INFO("result: %d message: %s", rplsrv.response.success, rplsrv.response.message.c_str());
    }
    else
    {
      ROS_ERROR("Failed to call service rps_path_planning");
    }

    if (rplsrv.response.rps_path.size() != 0)
    {
      for (int i = 0; i < rplsrv.response.rps_path[0].rps_route.size(); i++)
      {
        ROS_INFO("[%d]: x=%f, y=%f, th=%f", i, rplsrv.response.rps_path[0].rps_route[i].x,
                 rplsrv.response.rps_path[0].rps_route[i].y, rplsrv.response.rps_path[0].rps_route[i].th);
      }
    }
    else
    {
      ROS_ERROR("Noting rps_path_planning data");
    }

    static ros::Rate loop_rate(10);  // 0.1sec
    while (ros::ok())
    {
      ros::spinOnce();
      loop_rate.sleep();
    }
  }
  //----------------------------------------------------------------------------
  void OnRosInterfaceActivated()
  {
    cout << "SmartPal action node init for choreonoid" << endl;
    if (!is_ros_init)
    {
      ros::init(argc, argv, "smartpal_action");
      is_ros_init = true;
    }

    //----------------------------------------------------------------------
    cout << "set ros srv" << endl;
    static ros::NodeHandle nh;
    static ros::ServiceServer action_server = nh.advertiseService("rp_action_srv", action);
    sp5_control_client = nh.serviceClient< tms_msg_rc::smartpal_control >("sp5_control");
    path_planning_client = nh.serviceClient< tms_msg_rp::rps_path_planning >("rps_path_planning");

    static boost::thread t(boost::bind(&SmartpalActionPlugin::LoopRosTest, this));

    MessageView::mainInstance()->putln("stop SmartpalAction!");
  }

public:
  SmartpalActionPlugin() : Plugin("SmartpalAction")
  {
  }

  bool is_ros_init;

  virtual bool initialize()
  {
    is_ros_init = false;
    menuManager()
        .setPath("/Tools")
        .addItem("SmartpalAction")
        ->sigTriggered()
        .connect(bind(&SmartpalActionPlugin::OnRosInterfaceActivated, this));

    return true;
  }
};

CNOID_IMPLEMENT_PLUGIN_ENTRY(SmartpalActionPlugin)


text:
//////////////////////////////////////////////////////////////////////////////
// Copyright 2005-2006 Andreas Huber Doenni
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//////////////////////////////////////////////////////////////////////////////

#include "TuTest.hpp"

#include <boost/test/test_tools.hpp>

#include <stdexcept>

int test_main( int, char* [] )
{
  TuTest machine;
  machine.initiate();
  // unconsumed_event sanity check
  BOOST_REQUIRE_THROW( machine.process_event( EvY() ), std::runtime_error );
  machine.process_event( EvX() );
  return 0;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/*
 * Copyright 2012 Steven Gribble
 *
 *  This file is part of the UW CSE 333 course project sequence
 *  (333proj).
 *
 *  333proj 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  333proj 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with 333proj.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdint.h>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <map>
#include <string>
#include <vector>

#include "./HttpRequest.h"
#include "./HttpUtils.h"
#include "./HttpConnection.h"

using std::map;
using std::string;

namespace hw4 {

bool HttpConnection::GetNextRequest(HttpRequest *request) {
  // Use "WrappedRead" to read data into the buffer_
  // instance variable.  Keep reading data until either the
  // connection drops or you see a "\r\n\r\n" that demarcates
  // the end of the request header.
  //
  // Once you've seen the request header, use ParseRequest()
  // to parse the header into the *request argument.
  //
  // Very tricky part:  clients can send back-to-back requests
  // on the same socket.  So, you need to preserve everything
  // after the "\r\n\r\n" in buffer_ for the next time the
  // caller invokes GetNextRequest()!

  // MISSING:
  auto pos = buffer_.find("\r\n\r\n");
  if (pos == std::string::npos)
  {
    char buf[1024];
    while (1)
    {
      int res = WrappedRead(fd_, reinterpret_cast<unsigned char*>(buf), sizeof(buf));
      if (res == -1) return false;
      else if (res == 0) break;
      else
      {
        buffer_ += std::string(buf, res);
      }

      pos = buffer_.find("\r\n\r\n");
      if (pos != std::string::npos) break;
    }
  }

  if (pos == std::string::npos) return false;

  *request = ParseRequest(pos + 4);

  // TODO return false if the request is not well formatted
  buffer_ = buffer_.substr(pos + 4);

  return true;
}

bool HttpConnection::WriteResponse(const HttpResponse &response) {
  std::string str = response.GenerateResponseString();
  int res = WrappedWrite(fd_,
                         (unsigned char *) str.c_str(),
                         str.length());
  if (res != static_cast<int>(str.length()))
    return false;
  return true;
}

HttpRequest HttpConnection::ParseRequest(size_t end) {
  HttpRequest req;
  req.URI = "/";  // by default, get "/".

  // Get the header.
  std::string str = buffer_.substr(0, end);

  // Split the header into lines.  Extract the URI from the first line
  // and store it in req.URI.  For each additional line beyond the
  // first, extract out the header name and value and store them in
  // req.headers (i.e., req.headers[headername] = headervalue).
  // You should look at HttpResponse.h for details about the HTTP header
  // format that you need to parse.
  //
  // You'll probably want to look up boost functions for (a) splitting
  // a string into lines on a "\r\n" delimiter, (b) trimming
  // whitespace from the end of a string, and (c) converting a string
  // to lowercase.

  // MISSING:
  std::vector<std::string> lines;
  boost::algorithm::split(lines, str, boost::is_any_of("\r\n"), boost::token_compress_on);

  std::vector<std::string> firstRow;
  boost::algorithm::split(firstRow, lines[0], boost::is_any_of("\t "), boost::token_compress_on);
  req.URI = firstRow[1];

  for (size_t idx = 1; idx < lines.size(); ++idx)
  {
    boost::algorithm::to_lower(lines[idx]);
    std::vector<std::string> kv;
    boost::algorithm::split(kv, lines[idx], boost::is_any_of(":"));
    if (kv.size() == 2)
    {
      boost::trim(kv[0]);
      boost::trim(kv[1]);
      req.headers[kv[0]] = kv[1];
    }
  }

  return req;
}

}  // namespace hw4

ext: cc

max_stars_repo_name: tavaresdong/courses-notes

max_issues_repo_name: tavaresdong/courses-notes

max_forks_repo_name: tavaresdong/courses-notes


text:
#include <boost/test/unit_test.hpp>

#include <cpp-utils/down_cast.h>

namespace {

struct A { virtual ~A() { } };
struct B : A { };
struct C : A { };

} // namespace

BOOST_AUTO_TEST_SUITE(DownCast_Tests)

BOOST_AUTO_TEST_CASE(pointer)
{
  B b;
  A* ab = &b;
  BOOST_CHECK(&b == cpp::down_cast<B>(ab));

#ifndef NDEBUG
  // failure
  C c;
  A* ac = &c;
  BOOST_CHECK_THROW(cpp::down_cast<B>(ac), cpp::assert_failure);
#endif
}

BOOST_AUTO_TEST_CASE(ref)
{
  B b;
  A& ab = b;
  BOOST_CHECK(&b == &cpp::down_cast<B>(ab));

#ifndef NDEBUG
  // failure
  C c;
  A& ac = c;
  BOOST_CHECK_THROW(cpp::down_cast<B>(ac), cpp::assert_failure);
#endif
}

BOOST_AUTO_TEST_SUITE_END()


text:
#include "stdafx.h"
#include "graphics/SpriteFont.h"

#include <boost/filesystem.hpp>

#if defined(VORB_IMPL_FONT_SDL)
#if defined(VORB_OS_WINDOWS)
#include <TTF/SDL_ttf.h>
#else
#include <SDL2_ttf/SDL_ttf.h>
#endif
#endif

#include "graphics/GraphicsDevice.h"
#include "graphics/ImageIO.h"
#include "graphics/SpriteBatch.h"
#include "utils.h"

// X Offset multipliers for vg::TextAlign
const f32 X_OFF_MULTS[9] = {
    0.0f, // LEFT
    0.0f, // TOP_LEFT
    -0.5f, // TOP
    -1.0f, // TOP_RIGHT
    -1.0f, // RIGHT
    -1.0f, // BOTTOM_RIGHT
    -0.5f, // BOTTOM
    0.0f, // BOTTOM_LEFT
    -0.5f // CENTER
};

// Used for alignment
struct GlyphToRender {
    GlyphToRender(size_t gi, f32 x) : gi(gi), x(x) {}
    size_t gi;
    f32 x;
};

i32 closestPow2(i32 i) {
    i--;
    i32 pi = 1;
    while (i > 0) {
        i >>= 1;
        pi <<= 1;
    }
    return pi;
}

void vg::SpriteFont::init(const cString font, ui32 size, char cs, char ce) {
#if defined(VORB_IMPL_FONT_SDL)
    TTF_Font* f = TTF_OpenFont(font, size);
    if (!f) {
        std::cerr << "Failed to open font " << font << "\n";
        std::cerr << "Error: " << TTF_GetError() << std::endl;
        return;
    }
    m_fontHeight = TTF_FontHeight(f);
    SDL_Color fg = { 255, 255, 255, 255 };
#endif
    m_regStart = cs;
    m_regLength = ce - cs + 1;
    ui32 padding = size / 8;

    // First Measure All The Regions
    i32v4* glyphRects = new i32v4[m_regLength];
    size_t i = 0;
    i32 advance;
    for (char c = cs; c <= ce; c++) {
#if defined(VORB_IMPL_FONT_SDL)
        TTF_GlyphMetrics(f, c, &glyphRects[i].x, &glyphRects[i].z, &glyphRects[i].y, &glyphRects[i].w, &advance);
#endif
        glyphRects[i].z -= glyphRects[i].x;
        glyphRects[i].x = 0;
        glyphRects[i].w -= glyphRects[i].y;
        glyphRects[i].y = 0;
        i++;
    }

    // Find Best Partitioning Of Glyphs
    ui32 rows = 1, w, h, bestWidth = 0, bestHeight = 0, area = 4096 * 4096, bestRows = 0;
    std::vector<ui32>* bestPartition = nullptr;
    while (rows <= m_regLength) {
        h = rows * (padding + m_fontHeight) + padding;
        auto gr = createRows(glyphRects, m_regLength, rows, padding, w);

        // Desire A Power Of 2 Texture
        w = closestPow2(w);
        h = closestPow2(h);

        // A Texture Must Be Feasible
        ui32 maxTextureSize = GraphicsDevice::getCurrent()->getProperties().maxTextureSize;
        if (w > maxTextureSize || h > maxTextureSize) {
            rows++;
            delete[] gr;
            continue;
        }

        // Check For Minimal Area
        if (area >= w * h) {
            if (bestPartition) delete[] bestPartition;
            bestPartition = gr;
            bestWidth = w;
            bestHeight = h;
            bestRows = rows;
            area = bestWidth * bestHeight;
            rows++;
        } else {
            delete[] gr;
            break;
        }
    }

    // Can A Bitmap Font Be Made?
    if (!bestPartition) return;

    // Create The Texture
    glGenTextures(1, &m_texID);
    glBindTexture(GL_TEXTURE_2D, m_texID);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bestWidth, bestHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);

    // Now Draw All The Glyphs
    ui32 ly = padding;
    for (size_t ri = 0; ri < bestRows; ri++) {
        ui32 lx = padding;
        for (size_t ci = 0; ci < bestPartition[ri].size(); ci++) {
            ui32 gi = bestPartition[ri][ci];

#if defined(VORB_IMPL_FONT_SDL)
            SDL_Surface* glyphSurface = TTF_RenderGlyph_Blended(f, (char)(cs + gi), fg);
            // Pre-multiplication Occurs Here
            ubyte* sp = (ubyte*)glyphSurface->pixels;
            ui32 cp = glyphSurface->w * glyphSurface->h * 4;
            for (size_t i = 0; i < cp; i += 4) {
                f32 a = sp[i + 3] / 255.0f;
                sp[i] = (ubyte)((f32)sp[i] * a);
                sp[i + 1] = sp[i];
                sp[i + 2] = sp[i];
            }

            // Save Glyph Image And Update Coordinates
            glTexSubImage2D(GL_TEXTURE_2D, 0, lx, ly, glyphSurface->w, glyphSurface->h, GL_BGRA, GL_UNSIGNED_BYTE, glyphSurface->pixels);
            glyphRects[gi].x = lx;
            glyphRects[gi].y = ly;
            glyphRects[gi].z = glyphSurface->w;
            glyphRects[gi].w = glyphSurface->h;

            SDL_FreeSurface(glyphSurface);
            glyphSurface = nullptr;
#endif

            lx += glyphRects[gi].z + padding;
        }
        ly += m_fontHeight + padding;
    }

    // Draw The Unsupported Glyph
    ui32 rs = padding - 1;
    ui32* pureWhiteSquare = new ui32[rs * rs];
    memset(pureWhiteSquare, 0xffffffffu, rs * rs * sizeof(ui32));
    glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, rs, rs, GL_RGBA, GL_UNSIGNED_BYTE, pureWhiteSquare);
    delete[] pureWhiteSquare;
    pureWhiteSquare = nullptr;

    // Create SpriteBatch Glyphs
    m_glyphs = new CharGlyph[m_regLength + 1];
    for (i = 0; i < m_regLength; i++) {
        m_glyphs[i].character = (char)(cs + i);
        m_glyphs[i].size = f32v2((f32)glyphRects[i].z, (f32)glyphRects[i].w);
        m_glyphs[i].uvRect = f32v4(
            (f32)glyphRects[i].x / (f32)bestWidth,
            (f32)glyphRects[i].y / (f32)bestHeight,
            (f32)glyphRects[i].z / (f32)bestWidth,
            (f32)glyphRects[i].w / (f32)bestHeight
            );
    }
    m_glyphs[m_regLength].character = ' ';
    m_glyphs[m_regLength].size = m_glyphs[0].size;
    m_glyphs[m_regLength].uvRect = f32v4(0.0f, 0.0f, (f32)rs / (f32)bestWidth, (f32)rs / (f32)bestHeight);

#ifdef DEBUG
    // Save An Image
    std::vector<ui8> pixels;
    pixels.resize(bestWidth * bestHeight * 4);
    glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[0]);
    char buffer[512];
    sprintf(buffer, "SFont_%s_%s_%d.png", TTF_FontFaceFamilyName(f), TTF_FontFaceStyleName(f), size);
    vg::ImageIO().save(buffer, pixels.data(), bestWidth, bestHeight, vg::ImageIOFormat::RGBA_UI8);
#endif // DEBUG

    glBindTexture(GL_TEXTURE_2D, 0);
    delete[] glyphRects;
    delete[] bestPartition;

#if defined(VORB_IMPL_FONT_SDL)
    TTF_CloseFont(f);
#endif
}

void vg::SpriteFont::dispose() {
    if (m_texID != 0) {
        glDeleteTextures(1, &m_texID);
        m_texID = 0;
    }
    if (m_glyphs) {
        m_glyphs = nullptr;
        delete[] m_glyphs;
    }
}

void vg::SpriteFont::getInstalledFonts(std::map<nString, nString>& fontFileDictionary) {
#ifdef DEBUG
    ui32 startTime = SDL_GetTicks(), searchCount = 0;
#endif // DEBUG

    boost::filesystem::path fontDirectory(getenv("SystemRoot"));
    fontDirectory /= "Fonts";
    boost::filesystem::directory_iterator dirIter(fontDirectory);
    nString fontExtTTF = ".ttf";
    nString fontExtFON = ".fon";
    while (true) {
        i32* m_impCheck = (i32*)&dirIter;
        if (*m_impCheck == 0) break;

        auto dirFile = dirIter->path();
#ifdef DEBUG
        searchCount++;
#endif // DEBUG
        if (!boost::filesystem::is_directory(dirFile)) {
            nString fExt = dirFile.extension().string();
            if (fExt == fontExtTTF || fExt == fontExtFON) {
                nString fontFile = dirFile.string();
                TTF_Font* font = TTF_OpenFont(fontFile.c_str(), 12);
                if (font) {
                    nString fontName = TTF_FontFaceFamilyName(font);
                    fontName += " - " + nString(TTF_FontFaceStyleName(font));
                    fontFileDictionary[fontName] = fontFile;

                    TTF_CloseFont(font);
                    font = nullptr;
                }
            }
        }
        dirIter++;
    }
#ifdef DEBUG
    printf("Found %d System Fonts Out Of %d Files\nTime Spent: %d ms\n", fontFileDictionary.size(), searchCount, SDL_GetTicks() - startTime);
#endif // DEBUG
    return;
}

std::vector<ui32>* vg::SpriteFont::createRows(i32v4* rects, ui32 rectsLength, ui32 r, ui32 padding, ui32& w) {
    // Blank Initialize
    std::vector<ui32>* l = new std::vector<ui32>[r]();
    ui32* cw = new ui32[r]();
    for (size_t i = 0; i < r; i++) {
        cw[i] = padding;
    }

    // Loop Through All Glyphs
    for (ui32 i = 0; i < rectsLength; i++) {
        // Find Row For Placement
        size_t ri = 0;
        for (size_t rii = 1; rii < r; rii++)
        if (cw[rii] < cw[ri]) ri = rii;

        // Add Width To That Row
        cw[ri] += rects[i].z + padding;

        // Add Glyph To The Row List
        l[ri].push_back(i);
    }

    // Find The Max Width
    w = 0;
    for (size_t i = 0; i < r; i++) {
        if (cw[i] > w) w = cw[i];
    }

    return l;
}

f32v2 vg::SpriteFont::measure(const cString s) const {
    f32v2 size((f32)0, (f32)m_fontHeight);
    float cw = 0;
    for (int si = 0; s[si] != 0; si++) {
        char c = s[si];
        if (s[si] == '\n') {
            size.y += m_fontHeight;
            if (size.x < cw)
                size.x = cw;
            cw = 0;
        } else {
            // Check For Correct Glyph
            size_t gi = c - m_regStart;
            if (gi >= m_regLength)
                gi = m_regLength;
            cw += m_glyphs[gi].size.x;
        }
    }
    if (size.x < cw)
        size.x = cw;
    return size;
}

void vg::SpriteFont::draw(SpriteBatch* batch, const cString s, const f32v2& position, const f32v2& scaling, const color4& tint, TextAlign align, f32 depth, const f32v4& clipRect, bool shouldWrap) const {
    f32v2 pos = position;
    pos.y += getInitialYOffset(align) * scaling.y;
    if (pos.x < clipRect.x) pos.x = clipRect.x;
    f32 gx = 0.0f;
    std::vector <std::vector<GlyphToRender> > rows(1); // Rows of glyphs
    std::vector <f32> rightEdges(1, 0.0f); // Right edge positions for rows
    for (int si = 0; s[si] != 0; si++) {
        char c = s[si];
        if (s[si] == '\n') {
            // Go to new row on newlines
            rightEdges.back() = gx;
            rightEdges.push_back(0.0f);
            rows.emplace_back();
            gx = 0.0f;
        } else {
            bool useGlyph = true;
            // Check For Correct Glyph
            size_t gi = c - m_regStart;
            if (gi >= m_regLength) gi = m_regLength;

            // Get glyph width
            f32 gWidth = m_glyphs[gi].size.x * scaling.x;

            // Check for wrapping
            if (shouldWrap) {
                bool isOut;
                switch (align) {
                    case vg::TextAlign::TOP:
                    case vg::TextAlign::CENTER:
                    case vg::TextAlign::BOTTOM:
                        isOut = ((pos.x + (gx + gWidth) / 2.0f > clipRect.x + clipRect.z)); break;
                    case vg::TextAlign::TOP_RIGHT:
                    case vg::TextAlign::RIGHT:
                    case vg::TextAlign::BOTTOM_RIGHT:
                        isOut = ((pos.x - gx - gWidth < clipRect.x)); break;
                    default:
                        isOut = ((pos.x + gx + gWidth > clipRect.x + clipRect.z)); break;
                }

                // If the glyph is out of the clip rect, may need to go to new row
                if (isOut) {
                    // TODO(Ben): Check input clipping characters
                    if (c == ' ') {
                        useGlyph = false;
                    } else {
                        // Count the word size
                        int numChars = 0;
                        while (s[si - numChars] != ' ' && si - numChars != 0) numChars++;

                        if (si - numChars > 0) {
                            for (int i = 0; i < numChars; i++) {
                                gx -= m_glyphs[si - i].size.x * scaling.x;
                            }
                            si -= (numChars + 1); // -1 to counter ++ later.
                            rightEdges.back() = gx;
                            gx = 0.0f;
                            useGlyph = false; // TODO(Ben): Is this right?
                        } else {
                            rightEdges.back() = gx;
                        }
                    }
                    // Go to new row
                    rightEdges.push_back(0.0f);
                    rows.emplace_back();
                    gx = 0.0f;
                }
            }
            // Add glyph to the row
            if (useGlyph) {
                rows.back().emplace_back(gi, gx);
                gx += gWidth;
            }
        }
    }
    rightEdges.back() = gx;
    // Get y offset
    f32 yOff = getYOffset(rows.size(), align) * scaling.y;
    // Render each row
    for (size_t y = 0; y < rows.size(); y++) {
        f32 rightEdge = rightEdges[y];
        for (auto& g : rows[y]) {
            f32v2 position = pos + f32v2(g.x + rightEdges[y] * X_OFF_MULTS[(int)align], yOff + y * m_fontHeight * scaling.y);
            f32v2 size = m_glyphs[g.gi].size * scaling;
            f32v4 uvRect = m_glyphs[g.gi].uvRect;
            // Clip the glyphs with clipRect
            computeClipping(clipRect, position, size, uvRect);
            // Don't draw the glyph if its too small after clipping
            if (size.x > 0.0f && size.y > 0.0f) {
                batch->draw(m_texID, &uvRect, position, size, tint, depth);
            }
        }
    }
}

f32 vg::SpriteFont::getInitialYOffset(TextAlign textAlign) const {
    // No need to measure top left
    if (textAlign == vg::TextAlign::TOP_LEFT) return 0.0f;
    switch (textAlign) {
        case vg::TextAlign::LEFT:
            return -(f32)m_fontHeight / 2.0f;
        case vg::TextAlign::TOP_LEFT:
            return 0.0f;
        case vg::TextAlign::TOP:
            return 0.0f;
        case vg::TextAlign::TOP_RIGHT:
            return 0.0f;
        case vg::TextAlign::RIGHT:
            return -(f32)m_fontHeight / 2.0f;
        case vg::TextAlign::BOTTOM_RIGHT:
            return -(f32)m_fontHeight;
        case vg::TextAlign::BOTTOM:
            return -(f32)m_fontHeight;
        case vg::TextAlign::BOTTOM_LEFT:
            return -(f32)m_fontHeight;
        case vg::TextAlign::CENTER:
            return -(f32)m_fontHeight / 2.0f;
        default:
            return 0.0f; // Should never happen
    }
    return 0.0f;
}

f32 vg::SpriteFont::getYOffset(size_t numRows, vg::TextAlign align) const {
    switch (align) {
        case vg::TextAlign::TOP_LEFT:
        case vg::TextAlign::TOP:
        case vg::TextAlign::TOP_RIGHT:
            return 0.0f;
        case vg::TextAlign::LEFT:
        case vg::TextAlign::CENTER:
        case vg::TextAlign::RIGHT:
            return -((f32)(numRows - 1) * m_fontHeight / 2.0f);
        default:
            return -((f32)(numRows - 1) * m_fontHeight);
    }
    return 0.0f; // Should never happen
}

max_stars_repo_name: caseymcc/Vorb

max_issues_repo_name: caseymcc/Vorb

max_forks_repo_name: caseymcc/Vorb


text: #include <boost/graph/distributed/one_bit_color_map.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino