<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "fnord-cstable/BitPackedIntColumnReader.h"
#include "fnord-cstable/BitPackedIntColumnWriter.h"
#include "fnord-cstable/UInt32ColumnReader.h"
#include "fnord-cstable/UInt32ColumnWriter.h"
#include "fnord-cstable/BooleanColumnReader.h"
#include "fnord-cstable/BooleanColumnWriter.h"
#include "fnord-cstable/CSTableWriter.h"
#include "fnord-cstable/CSTableReader.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include "analytics/AnalyticsTableScan.h"
#include "analytics/CTRByPositionQuery.h"

using namespace cm;
using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "input_file",
      fnord::cli::FlagParser::T_STRING,
      true,
      "i",
      NULL,
      "file",
      "<filename>");

  flags.defineFlag(
      "output_file",
      fnord::cli::FlagParser::T_STRING,
      true,
      "o",
      NULL,
      "file",
      "<filename>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  size_t debug_n = 0;
  size_t debug_z = 0;

  /* query level */
  cstable::UInt32ColumnWriter jq_time_col(1, 1);
  cstable::BitPackedIntColumnWriter jq_page_col(1, 1, 100);
  cstable::BitPackedIntColumnWriter jq_lang_col(1, 1, kMaxLanguage);
  cstable::BitPackedIntColumnWriter jq_numitems_col(1, 1, 250);
  cstable::BitPackedIntColumnWriter jq_numitemclicks_col(1, 1, 250);
  cstable::BitPackedIntColumnWriter jq_abtestgroup_col(1, 1, 100);
  cstable::BitPackedIntColumnWriter jq_devicetype_col(1, 1, kMaxDeviceType);
  cstable::BitPackedIntColumnWriter jq_pagetype_col(1, 1, kMaxPageType);

  /* query item level */
  cstable::BitPackedIntColumnWriter jqi_position_col(2, 2, 64);
  cstable::BooleanColumnWriter jqi_clicked_col(2, 2);

  uint64_t r = 0;
  uint64_t n = 0;

  auto add_session = [&] (const cm::JoinedSession& sess) {
    ++n;

    for (const auto& q : sess.queries) {
      /* queries.time */
      jq_time_col.addDatum(r, 1, q.time.unixMicros() / kMicrosPerSecond);

      /* queries.num_item_clicks, queries.num_items */
      size_t nitems = 0;
      size_t nclicks = 0;
      for (const auto& i : q.items) {
          ++nitems;
          nclicks += i.clicked;
      }
      jq_numitems_col.addDatum(r, 1, nitems);
      jq_numitemclicks_col.addDatum(r, 1, nclicks);

      /* queries.page */
      auto pg_str = cm::extractAttr(q.attrs, "pg");
      if (pg_str.isEmpty()) {
        jq_page_col.addNull(r, 1);
      } else {
        jq_page_col.addDatum(r, 1, std::stoul(pg_str.get()));
      }

      /* queries.ab_test_group */
      auto abgrp = cm::extractABTestGroup(q.attrs);
      if (abgrp.isEmpty()) {
        jq_abtestgroup_col.addNull(r, 1);
      } else {
        jq_abtestgroup_col.addDatum(r, 1, abgrp.get());
      }

      /* queries.device_type */
      jq_devicetype_col.addDatum(r, 1, (uint32_t) extractDeviceType(q.attrs));

      /* queries.page_type */
      jq_pagetype_col.addDatum(r, 1, (uint32_t) extractPageType(q.attrs));

      /* queries.language */
      auto lang = cm::extractLanguage(q.attrs);
      uint32_t l = (uint16_t) lang;
      jq_lang_col.addDatum(r, 1, l);

      if (q.items.size() == 0) {
        jqi_position_col.addNull(r, 1);
        jqi_clicked_col.addNull(r, 1);
      }

      for (const auto& i : q.items) {
        jqi_position_col.addDatum(r, 2, i.position);
        jqi_clicked_col.addDatum(r, 2, i.clicked);
        r = 2;
      }

      r = 1;
    }

    r = 0;
  };

  /* read input tables */
  int row_idx = 0;

  const auto& sstable = flags.getString("input_file");
  fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable);

  /* read sstable header */
  sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));

  if (reader.bodySize() == 0) {
    fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable);
    exit(1);
  }

  /* get sstable cursor */
  auto cursor = reader.getCursor();
  auto body_size = reader.bodySize();

  /* status line */
  util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
    fnord::logInfo(
        "cm.jqcolumnize",
        "[$0%] Reading sstable... rows=$1",
        (size_t) ((cursor->position() / (double) body_size) * 100),
        row_idx);
  });

  /* read sstable rows */
  for (; cursor->valid(); ++row_idx) {
    status_line.runMaybe();

    auto key = cursor->getKeyString();
    auto val = cursor->getDataBuffer();
    Option<cm::JoinedQuery> q;

    try {
      q = Some(json::fromJSON<cm::JoinedQuery>(val));
    } catch (const Exception& e) {
      fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString());
    }

    if (!q.isEmpty()) {
      cm::JoinedSession s;
      s.queries.emplace_back(q.get());
      add_session(s);
    }

    if (!cursor->next()) {
      break;
    }
  }

  status_line.runForce();

  {
    cstable::CSTableWriter writer(flags.getString("output_file") + "~", n);
    writer.addColumn("queries.time", &jq_time_col);
    writer.addColumn("queries.page", &jq_page_col);
    writer.addColumn("queries.language", &jq_lang_col);
    writer.addColumn("queries.num_items", &jq_numitems_col);
    writer.addColumn("queries.num_items_clicked", &jq_numitemclicks_col);
    writer.addColumn("queries.ab_test_group", &jq_abtestgroup_col);
    writer.addColumn("queries.device_type", &jq_devicetype_col);
    writer.addColumn("queries.page_type", &jq_pagetype_col);
    writer.addColumn("queries.items.position", &jqi_position_col);
    writer.addColumn("queries.items.clicked", &jqi_clicked_col);
    writer.commit();
  }

  FileUtil::mv(
      flags.getString("output_file") + "~",
      flags.getString("output_file"));

  //{
  //  cstable::CSTableReader reader(flags.getString("output_file"));
  //  auto t0 = WallClock::unixMicros();

  //  cm::AnalyticsTableScan aq;
  //  cm::CTRByGroupResult<uint16_t> res;
  //  cm::CTRByPositionQuery q(&aq, &res);
  //  aq.scanTable(&reader);
  //  auto t1 = WallClock::unixMicros();
  //  fnord::iputs("scanned $0 rows in $1 ms", res.rows_scanned, (t1 - t0) / 1000.0f);
  //  for (const auto& p : res.counters) {
  //    fnord::iputs(
  //       "pos: $0, views: $1, clicks: $2, ctr: $3",
  //        p.first, p.second.num_views,
  //        p.second.num_clicks,
  //        p.second.num_clicks / (double) p.second.num_views);
  //  }
  //}

  return 0;
}

<commit_msg>index qcat{1,2,3}<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "fnord-cstable/BitPackedIntColumnReader.h"
#include "fnord-cstable/BitPackedIntColumnWriter.h"
#include "fnord-cstable/UInt32ColumnReader.h"
#include "fnord-cstable/UInt32ColumnWriter.h"
#include "fnord-cstable/BooleanColumnReader.h"
#include "fnord-cstable/BooleanColumnWriter.h"
#include "fnord-cstable/CSTableWriter.h"
#include "fnord-cstable/CSTableReader.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include "analytics/AnalyticsTableScan.h"
#include "analytics/CTRByPositionQuery.h"

using namespace cm;
using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "input_file",
      fnord::cli::FlagParser::T_STRING,
      true,
      "i",
      NULL,
      "file",
      "<filename>");

  flags.defineFlag(
      "output_file",
      fnord::cli::FlagParser::T_STRING,
      true,
      "o",
      NULL,
      "file",
      "<filename>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  size_t debug_n = 0;
  size_t debug_z = 0;

  /* query level */
  cstable::UInt32ColumnWriter jq_time_col(1, 1);
  cstable::BitPackedIntColumnWriter jq_page_col(1, 1, 100);
  cstable::BitPackedIntColumnWriter jq_lang_col(1, 1, kMaxLanguage);
  cstable::BitPackedIntColumnWriter jq_numitems_col(1, 1, 250);
  cstable::BitPackedIntColumnWriter jq_numitemclicks_col(1, 1, 250);
  cstable::BitPackedIntColumnWriter jq_abtestgroup_col(1, 1, 100);
  cstable::BitPackedIntColumnWriter jq_devicetype_col(1, 1, kMaxDeviceType);
  cstable::BitPackedIntColumnWriter jq_pagetype_col(1, 1, kMaxPageType);
  cstable::BitPackedIntColumnWriter jq_cat1_col(1, 1, 0xffff);
  cstable::BitPackedIntColumnWriter jq_cat2_col(1, 1, 0xffff);
  cstable::BitPackedIntColumnWriter jq_cat3_col(1, 1, 0xffff);

  /* query item level */
  cstable::BitPackedIntColumnWriter jqi_position_col(2, 2, 64);
  cstable::BooleanColumnWriter jqi_clicked_col(2, 2);

  uint64_t r = 0;
  uint64_t n = 0;

  auto add_session = [&] (const cm::JoinedSession& sess) {
    ++n;

    for (const auto& q : sess.queries) {
      /* queries.time */
      jq_time_col.addDatum(r, 1, q.time.unixMicros() / kMicrosPerSecond);

      /* queries.num_item_clicks, queries.num_items */
      size_t nitems = 0;
      size_t nclicks = 0;
      for (const auto& i : q.items) {
          ++nitems;
          nclicks += i.clicked;
      }
      jq_numitems_col.addDatum(r, 1, nitems);
      jq_numitemclicks_col.addDatum(r, 1, nclicks);

      /* queries.page */
      auto pg_str = cm::extractAttr(q.attrs, "pg");
      if (pg_str.isEmpty()) {
        jq_page_col.addNull(r, 1);
      } else {
        jq_page_col.addDatum(r, 1, std::stoul(pg_str.get()));
      }

      /* queries.ab_test_group */
      auto abgrp = cm::extractABTestGroup(q.attrs);
      if (abgrp.isEmpty()) {
        jq_abtestgroup_col.addNull(r, 1);
      } else {
        jq_abtestgroup_col.addDatum(r, 1, abgrp.get());
      }

      /* queries.category1 */
      auto qcat1 = cm::extractAttr(q.attrs, "q_cat1");
      if (qcat1.isEmpty()) {
        jq_cat1_col.addNull(r, 1);
      } else {
        jq_cat1_col.addDatum(r, 1, std::stoul(qcat1.get()));
      }

      /* queries.category2 */
      auto qcat2 = cm::extractAttr(q.attrs, "q_cat2");
      if (qcat2.isEmpty()) {
        jq_cat2_col.addNull(r, 1);
      } else {
        jq_cat2_col.addDatum(r, 1, std::stoul(qcat2.get()));
      }

      /* queries.category3 */
      auto qcat3 = cm::extractAttr(q.attrs, "q_cat3");
      if (qcat3.isEmpty()) {
        jq_cat3_col.addNull(r, 1);
      } else {
        jq_cat3_col.addDatum(r, 1, std::stoul(qcat3.get()));
      }

      /* queries.device_type */
      jq_devicetype_col.addDatum(r, 1, (uint32_t) extractDeviceType(q.attrs));

      /* queries.page_type */
      jq_pagetype_col.addDatum(r, 1, (uint32_t) extractPageType(q.attrs));

      /* queries.language */
      auto lang = cm::extractLanguage(q.attrs);
      uint32_t l = (uint16_t) lang;
      jq_lang_col.addDatum(r, 1, l);

      if (q.items.size() == 0) {
        jqi_position_col.addNull(r, 1);
        jqi_clicked_col.addNull(r, 1);
      }

      for (const auto& i : q.items) {
        jqi_position_col.addDatum(r, 2, i.position);
        jqi_clicked_col.addDatum(r, 2, i.clicked);
        r = 2;
      }

      r = 1;
    }

    r = 0;
  };

  /* read input tables */
  int row_idx = 0;

  const auto& sstable = flags.getString("input_file");
  fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable);

  /* read sstable header */
  sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));

  if (reader.bodySize() == 0) {
    fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable);
    exit(1);
  }

  /* get sstable cursor */
  auto cursor = reader.getCursor();
  auto body_size = reader.bodySize();

  /* status line */
  util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
    fnord::logInfo(
        "cm.jqcolumnize",
        "[$0%] Reading sstable... rows=$1",
        (size_t) ((cursor->position() / (double) body_size) * 100),
        row_idx);
  });

  /* read sstable rows */
  for (; cursor->valid(); ++row_idx) {
    status_line.runMaybe();

    auto key = cursor->getKeyString();
    auto val = cursor->getDataBuffer();
    Option<cm::JoinedQuery> q;

    try {
      q = Some(json::fromJSON<cm::JoinedQuery>(val));
    } catch (const Exception& e) {
      fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString());
    }

    if (!q.isEmpty()) {
      cm::JoinedSession s;
      s.queries.emplace_back(q.get());
      add_session(s);
    }

    if (!cursor->next()) {
      break;
    }
  }

  status_line.runForce();

  {
    cstable::CSTableWriter writer(flags.getString("output_file") + "~", n);
    writer.addColumn("queries.time", &jq_time_col);
    writer.addColumn("queries.page", &jq_page_col);
    writer.addColumn("queries.language", &jq_lang_col);
    writer.addColumn("queries.num_items", &jq_numitems_col);
    writer.addColumn("queries.num_items_clicked", &jq_numitemclicks_col);
    writer.addColumn("queries.ab_test_group", &jq_abtestgroup_col);
    writer.addColumn("queries.device_type", &jq_devicetype_col);
    writer.addColumn("queries.page_type", &jq_pagetype_col);
    writer.addColumn("queries.category1", &jq_cat1_col);
    writer.addColumn("queries.category2", &jq_cat2_col);
    writer.addColumn("queries.category3", &jq_cat3_col);
    writer.addColumn("queries.items.position", &jqi_position_col);
    writer.addColumn("queries.items.clicked", &jqi_clicked_col);
    writer.commit();
  }

  FileUtil::mv(
      flags.getString("output_file") + "~",
      flags.getString("output_file"));

  //{
  //  cstable::CSTableReader reader(flags.getString("output_file"));
  //  auto t0 = WallClock::unixMicros();

  //  cm::AnalyticsTableScan aq;
  //  cm::CTRByGroupResult<uint16_t> res;
  //  cm::CTRByPositionQuery q(&aq, &res);
  //  aq.scanTable(&reader);
  //  auto t1 = WallClock::unixMicros();
  //  fnord::iputs("scanned $0 rows in $1 ms", res.rows_scanned, (t1 - t0) / 1000.0f);
  //  for (const auto& p : res.counters) {
  //    fnord::iputs(
  //       "pos: $0, views: $1, clicks: $2, ctr: $3",
  //        p.first, p.second.num_views,
  //        p.second.num_clicks,
  //        p.second.num_clicks / (double) p.second.num_views);
  //  }
  //}

  return 0;
}

<|endoftext|>


<commit_before>#include "utils/logoutput.h"
#include "commandSocket.h"
#include "FffProcessor.h"
#include "Progress.h"

#include <thread>
#include <cinttypes>

#include <Arcus/Socket.h>

#include <string> // stoi

#ifdef _WIN32
#include <windows.h>
#endif

#define DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(x)
// std::cerr << x;

namespace cura {

#define BYTES_PER_FLOAT 4
#define FLOATS_PER_VECTOR 3
#define VECTORS_PER_FACE 3

class CommandSocket::Private
{
public:
    Private()
        : socket(nullptr)
        , object_count(0)
        , current_sliced_object(nullptr)
        , sliced_objects(0)
        , current_layer_count(0)
        , current_layer_offset(0)
    { }

    cura::proto::Layer* getLayerById(int id);

    Arcus::Socket* socket;

    // Number of objects that need to be sliced
    int object_count;

    // Message that holds a list of sliced objects
    std::shared_ptr<cura::proto::SlicedObjectList> sliced_object_list;

    // Message that holds the currently sliced object (to be added to sliced_object_list)
    cura::proto::SlicedObject* current_sliced_object;

    // Number of sliced objects for this sliced object list
    int sliced_objects;

    // Number of layers sent to the front end so far
    // Used for incrementing the current layer in one at a time mode
    int current_layer_count;
    int current_layer_offset;

    // Ids of the sliced objects
    std::vector<int64_t> object_ids;

    std::string temp_gcode_file;
    std::ostringstream gcode_output_stream;

    // Print object that olds one or more meshes that need to be sliced.
    std::vector< std::shared_ptr<MeshGroup> > objects_to_slice;
};

CommandSocket::CommandSocket()
    : d(new Private)
{
    FffProcessor::getInstance()->setCommandSocket(this);
}

void CommandSocket::connect(const std::string& ip, int port)
{
    d->socket = new Arcus::Socket();
    //d->socket->registerMessageType(1, &Cura::ObjectList::default_instance());
    d->socket->registerMessageType(1, &cura::proto::Slice::default_instance());
    d->socket->registerMessageType(2, &cura::proto::SlicedObjectList::default_instance());
    d->socket->registerMessageType(3, &cura::proto::Progress::default_instance());
    d->socket->registerMessageType(4, &cura::proto::GCodeLayer::default_instance());
    d->socket->registerMessageType(5, &cura::proto::ObjectPrintTime::default_instance());
    d->socket->registerMessageType(6, &cura::proto::SettingList::default_instance());
    d->socket->registerMessageType(7, &cura::proto::GCodePrefix::default_instance());

    d->socket->connect(ip, port);

    // Start & continue listening as long as socket is not closed and there is no error.
    while(d->socket->state() != Arcus::SocketState::Closed && d->socket->state() != Arcus::SocketState::Error)
    {
        //If there is an object to slice, do so.
        if(d->objects_to_slice.size())
        {
            FffProcessor::getInstance()->resetFileNumber();
            for(auto object : d->objects_to_slice)
            {
                if(!FffProcessor::getInstance()->processMeshGroup(object.get()))
                {
                    logError("Slicing mesh group failed!");
                }
            }
            d->objects_to_slice.clear();
            FffProcessor::getInstance()->finalize();
            sendGCodeLayer();
            sendPrintTime();
            //TODO: Support all-at-once/one-at-a-time printing
            //d->processor->processModel(d->object_to_slice.get());
            //d->object_to_slice.reset();
            //d->processor->resetFileNumber();

            //sendPrintTime();
        }

        // Actually start handling messages.
        Arcus::MessagePtr message = d->socket->takeNextMessage();
        cura::proto::SettingList* setting_list = dynamic_cast<cura::proto::SettingList*>(message.get());
        if(setting_list)
        {
            handleSettingList(setting_list);
        }

        /*cura::proto::ObjectList* object_list = dynamic_cast<cura::proto::ObjectList*>(message.get());
        if(object_list)
        {
            handleObjectList(object_list);
        }*/

        cura::proto::Slice* slice = dynamic_cast<cura::proto::Slice*>(message.get());
        if(slice)
        {
            // Reset object counts
            d->object_count = 0;
            d->object_ids.clear();
            for(auto object : slice->object_lists())
            {
                handleObjectList(&object);
            }
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(250));

        if(!d->socket->errorString().empty())
        {
            logError("%s\n", d->socket->errorString().data());
            d->socket->clearError();
        }
    }
}

void CommandSocket::handleObjectList(cura::proto::ObjectList* list)
{
    FMatrix3x3 matrix;
    //d->object_count = 0;
    //d->object_ids.clear();
    d->objects_to_slice.push_back(std::make_shared<MeshGroup>(FffProcessor::getInstance()));
    MeshGroup* meshgroup = d->objects_to_slice.back().get();

    for(auto setting : list->settings())
    {
        meshgroup->setSetting(setting.name(), setting.value());
    }

    for (int extruder_nr = 0; extruder_nr < FffProcessor::getInstance()->getSettingAsCount("machine_extruder_count"); extruder_nr++)
    { // initialize remaining extruder trains and load the defaults
        meshgroup->createExtruderTrain(extruder_nr)->setExtruderTrainDefaults(extruder_nr); // create new extruder train objects or use already existing ones
    }

    for(auto object : list->objects())
    {
        DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("solid Cura_out\n");
        int extruder_train_nr = 0; // TODO: make primary extruder configurable!
        for(auto setting : object.settings())
        {
            if (setting.name() == "extruder_nr")
            {
                extruder_train_nr = std::stoi(setting.value());
                break;
            }
        }
        SettingsBase* extruder_train = meshgroup->getExtruderTrain(extruder_train_nr);

        meshgroup->meshes.push_back(extruder_train); //Construct a new mesh (with the corresponding extruder train as settings parent object) and put it into MeshGroup's mesh list.
        Mesh& mesh = meshgroup->meshes.back();

        int bytes_per_face = BYTES_PER_FLOAT * FLOATS_PER_VECTOR * VECTORS_PER_FACE;
        int face_count = object.vertices().size() / bytes_per_face;
        for(int i = 0; i < face_count; ++i)
        {
            //TODO: Apply matrix
            std::string data = object.vertices().substr(i * bytes_per_face, bytes_per_face);
            const FPoint3* float_vertices = reinterpret_cast<const FPoint3*>(data.data());

            Point3 verts[3];
            verts[0] = matrix.apply(float_vertices[0]);
            verts[1] = matrix.apply(float_vertices[1]);
            verts[2] = matrix.apply(float_vertices[2]);
            mesh.addFace(verts[0], verts[1], verts[2]);

            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("  facet normal -1 0 0\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("    outer loop\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("      vertex "<<INT2MM(verts[0].x) <<" " << INT2MM(verts[0].y) <<" " << INT2MM(verts[0].z) << "\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("      vertex "<<INT2MM(verts[1].x) <<" " << INT2MM(verts[1].y) <<" " << INT2MM(verts[1].z) << "\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("      vertex "<<INT2MM(verts[2].x) <<" " << INT2MM(verts[2].y) <<" " << INT2MM(verts[2].z) << "\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("    endloop\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("  endfacet\n");
        }
        DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("endsolid Cura_out\n");
        for(auto setting : object.settings())
        {
            mesh.setSetting(setting.name(), setting.value());
        }

        d->object_ids.push_back(object.id());
        mesh.finish();
    }

    d->object_count++;
    meshgroup->finalize();
}

void CommandSocket::handleSettingList(cura::proto::SettingList* list)
{
    for(auto setting : list->settings())
    {
        FffProcessor::getInstance()->setSetting(setting.name(), setting.value());
    }
}

void CommandSocket::sendLayerInfo(int layer_nr, int32_t z, int32_t height)
{
    if(!d->current_sliced_object)
    {
        return;
    }

    cura::proto::Layer* layer = d->getLayerById(layer_nr);
    layer->set_height(z);
    layer->set_thickness(height);
}

void CommandSocket::sendPolygons(PolygonType type, int layer_nr, Polygons& polygons, int line_width)
{
    if(!d->current_sliced_object)
        return;

    if (polygons.size() == 0)
        return;

    cura::proto::Layer* layer = d->getLayerById(layer_nr);

    for(unsigned int i = 0; i < polygons.size(); ++i)
    {
        cura::proto::Polygon* p = layer->add_polygons();
        p->set_type(static_cast<cura::proto::Polygon_Type>(type));
        std::string polydata;
        polydata.append(reinterpret_cast<const char*>(polygons[i].data()), polygons[i].size() * sizeof(Point));
        p->set_points(polydata);
        p->set_line_width(line_width);
    }
}

void CommandSocket::sendProgress(float amount)
{
    auto message = std::make_shared<cura::proto::Progress>();
    amount /= d->object_count;
    amount += d->sliced_objects * (1. / d->object_count);
    message->set_amount(amount);
    d->socket->sendMessage(message);
}

void CommandSocket::sendProgressStage(Progress::Stage stage)
{
    // TODO
}

void CommandSocket::sendPrintTime()
{
    auto message = std::make_shared<cura::proto::ObjectPrintTime>();
    message->set_time(FffProcessor::getInstance()->getTotalPrintTime());
    message->set_material_amount(FffProcessor::getInstance()->getTotalFilamentUsed(0));
    d->socket->sendMessage(message);
}

void CommandSocket::sendPrintMaterialForObject(int index, int extruder_nr, float print_time)
{
//     socket.sendInt32(CMD_OBJECT_PRINT_MATERIAL);
//     socket.sendInt32(12);
//     socket.sendInt32(index);
//     socket.sendInt32(extruder_nr);
//     socket.sendFloat32(print_time);
}

void CommandSocket::beginSendSlicedObject()
{
    if(!d->sliced_object_list)
    {
        d->sliced_object_list = std::make_shared<cura::proto::SlicedObjectList>();
    }

    d->current_sliced_object = d->sliced_object_list->add_objects();
    d->current_sliced_object->set_id(d->object_ids[d->sliced_objects]);
}

void CommandSocket::endSendSlicedObject()
{
    d->sliced_objects++;
    d->current_layer_offset = d->current_layer_count;
    std::cout << "End sliced object called. sliced objects " << d->sliced_objects << " object count: " << d->object_count << std::endl;

    std::cout << "current layer count" << d->current_layer_count << std::endl;
    std::cout << "current layer offset" << d->current_layer_offset << std::endl;

    if(d->sliced_objects >= d->object_count)
    {
        d->socket->sendMessage(d->sliced_object_list);
        d->sliced_objects = 0;
        d->current_layer_count = 0;
        d->current_layer_offset = 0;
        d->sliced_object_list.reset();
        d->current_sliced_object = nullptr;
    }
}

void CommandSocket::beginGCode()
{
    FffProcessor::getInstance()->setTargetStream(&d->gcode_output_stream);
}

void CommandSocket::sendGCodeLayer()
{
    auto message = std::make_shared<cura::proto::GCodeLayer>();
    message->set_id(d->object_ids[0]);
    message->set_data(d->gcode_output_stream.str());
    d->socket->sendMessage(message);

    d->gcode_output_stream.str("");
}

void CommandSocket::sendGCodePrefix(std::string prefix)
{
    auto message = std::make_shared<cura::proto::GCodePrefix>();
    message->set_data(prefix);
    d->socket->sendMessage(message);
}

cura::proto::Layer* CommandSocket::Private::getLayerById(int id)
{
    id += current_layer_offset;

    auto itr = std::find_if(current_sliced_object->mutable_layers()->begin(), current_sliced_object->mutable_layers()->end(), [id](cura::proto::Layer& l) { return l.id() == id; });

    cura::proto::Layer* layer = nullptr;
    if(itr != current_sliced_object->mutable_layers()->end())
    {
        layer = &(*itr);
    }
    else
    {
        layer = current_sliced_object->add_layers();
        layer->set_id(id);
        current_layer_count++;
    }

    return layer;
}

}//namespace cura
<commit_msg>enforce single slicing by commandSocket.<commit_after>#include "utils/logoutput.h"
#include "commandSocket.h"
#include "FffProcessor.h"
#include "Progress.h"

#include <thread>
#include <cinttypes>

#include <Arcus/Socket.h>

#include <string> // stoi

#ifdef _WIN32
#include <windows.h>
#endif

#define DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(x)
// std::cerr << x;

namespace cura {

#define BYTES_PER_FLOAT 4
#define FLOATS_PER_VECTOR 3
#define VECTORS_PER_FACE 3

class CommandSocket::Private
{
public:
    Private()
        : socket(nullptr)
        , object_count(0)
        , current_sliced_object(nullptr)
        , sliced_objects(0)
        , current_layer_count(0)
        , current_layer_offset(0)
    { }

    cura::proto::Layer* getLayerById(int id);

    Arcus::Socket* socket;

    // Number of objects that need to be sliced
    int object_count;

    // Message that holds a list of sliced objects
    std::shared_ptr<cura::proto::SlicedObjectList> sliced_object_list;

    // Message that holds the currently sliced object (to be added to sliced_object_list)
    cura::proto::SlicedObject* current_sliced_object;

    // Number of sliced objects for this sliced object list
    int sliced_objects;

    // Number of layers sent to the front end so far
    // Used for incrementing the current layer in one at a time mode
    int current_layer_count;
    int current_layer_offset;

    // Ids of the sliced objects
    std::vector<int64_t> object_ids;

    std::string temp_gcode_file;
    std::ostringstream gcode_output_stream;

    // Print object that olds one or more meshes that need to be sliced.
    std::vector< std::shared_ptr<MeshGroup> > objects_to_slice;
};

CommandSocket::CommandSocket()
    : d(new Private)
{
    FffProcessor::getInstance()->setCommandSocket(this);
}

void CommandSocket::connect(const std::string& ip, int port)
{
    d->socket = new Arcus::Socket();
    //d->socket->registerMessageType(1, &Cura::ObjectList::default_instance());
    d->socket->registerMessageType(1, &cura::proto::Slice::default_instance());
    d->socket->registerMessageType(2, &cura::proto::SlicedObjectList::default_instance());
    d->socket->registerMessageType(3, &cura::proto::Progress::default_instance());
    d->socket->registerMessageType(4, &cura::proto::GCodeLayer::default_instance());
    d->socket->registerMessageType(5, &cura::proto::ObjectPrintTime::default_instance());
    d->socket->registerMessageType(6, &cura::proto::SettingList::default_instance());
    d->socket->registerMessageType(7, &cura::proto::GCodePrefix::default_instance());

    d->socket->connect(ip, port);

    bool slice_another_time = true;

    // Start & continue listening as long as socket is not closed and there is no error.
    while(d->socket->state() != Arcus::SocketState::Closed && d->socket->state() != Arcus::SocketState::Error && slice_another_time)
    {
        //If there is an object to slice, do so.
        if(d->objects_to_slice.size())
        {
            FffProcessor::getInstance()->resetFileNumber();
            for(auto object : d->objects_to_slice)
            {
                if(!FffProcessor::getInstance()->processMeshGroup(object.get()))
                {
                    logError("Slicing mesh group failed!");
                }
            }
            d->objects_to_slice.clear();
            FffProcessor::getInstance()->finalize();
            sendGCodeLayer();
            sendPrintTime();
            slice_another_time = false; // TODO: remove this when multiple slicing with CuraEngine is safe
            //TODO: Support all-at-once/one-at-a-time printing
            //d->processor->processModel(d->object_to_slice.get());
            //d->object_to_slice.reset();
            //d->processor->resetFileNumber();

            //sendPrintTime();
        }

        // Actually start handling messages.
        Arcus::MessagePtr message = d->socket->takeNextMessage();
        cura::proto::SettingList* setting_list = dynamic_cast<cura::proto::SettingList*>(message.get());
        if(setting_list)
        {
            handleSettingList(setting_list);
        }

        /*cura::proto::ObjectList* object_list = dynamic_cast<cura::proto::ObjectList*>(message.get());
        if(object_list)
        {
            handleObjectList(object_list);
        }*/

        cura::proto::Slice* slice = dynamic_cast<cura::proto::Slice*>(message.get());
        if(slice)
        {
            // Reset object counts
            d->object_count = 0;
            d->object_ids.clear();
            for(auto object : slice->object_lists())
            {
                handleObjectList(&object);
            }
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(250));

        if(!d->socket->errorString().empty())
        {
            logError("%s\n", d->socket->errorString().data());
            d->socket->clearError();
        }
    }
}

void CommandSocket::handleObjectList(cura::proto::ObjectList* list)
{
    FMatrix3x3 matrix;
    //d->object_count = 0;
    //d->object_ids.clear();
    d->objects_to_slice.push_back(std::make_shared<MeshGroup>(FffProcessor::getInstance()));
    MeshGroup* meshgroup = d->objects_to_slice.back().get();

    for(auto setting : list->settings())
    {
        meshgroup->setSetting(setting.name(), setting.value());
    }

    for (int extruder_nr = 0; extruder_nr < FffProcessor::getInstance()->getSettingAsCount("machine_extruder_count"); extruder_nr++)
    { // initialize remaining extruder trains and load the defaults
        meshgroup->createExtruderTrain(extruder_nr)->setExtruderTrainDefaults(extruder_nr); // create new extruder train objects or use already existing ones
    }

    for(auto object : list->objects())
    {
        DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("solid Cura_out\n");
        int extruder_train_nr = 0; // TODO: make primary extruder configurable!
        for(auto setting : object.settings())
        {
            if (setting.name() == "extruder_nr")
            {
                extruder_train_nr = std::stoi(setting.value());
                break;
            }
        }
        SettingsBase* extruder_train = meshgroup->getExtruderTrain(extruder_train_nr);

        meshgroup->meshes.push_back(extruder_train); //Construct a new mesh (with the corresponding extruder train as settings parent object) and put it into MeshGroup's mesh list.
        Mesh& mesh = meshgroup->meshes.back();

        int bytes_per_face = BYTES_PER_FLOAT * FLOATS_PER_VECTOR * VECTORS_PER_FACE;
        int face_count = object.vertices().size() / bytes_per_face;
        for(int i = 0; i < face_count; ++i)
        {
            //TODO: Apply matrix
            std::string data = object.vertices().substr(i * bytes_per_face, bytes_per_face);
            const FPoint3* float_vertices = reinterpret_cast<const FPoint3*>(data.data());

            Point3 verts[3];
            verts[0] = matrix.apply(float_vertices[0]);
            verts[1] = matrix.apply(float_vertices[1]);
            verts[2] = matrix.apply(float_vertices[2]);
            mesh.addFace(verts[0], verts[1], verts[2]);

            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("  facet normal -1 0 0\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("    outer loop\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("      vertex "<<INT2MM(verts[0].x) <<" " << INT2MM(verts[0].y) <<" " << INT2MM(verts[0].z) << "\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("      vertex "<<INT2MM(verts[1].x) <<" " << INT2MM(verts[1].y) <<" " << INT2MM(verts[1].z) << "\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("      vertex "<<INT2MM(verts[2].x) <<" " << INT2MM(verts[2].y) <<" " << INT2MM(verts[2].z) << "\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("    endloop\n");
            DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("  endfacet\n");
        }
        DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR("endsolid Cura_out\n");
        for(auto setting : object.settings())
        {
            mesh.setSetting(setting.name(), setting.value());
        }

        d->object_ids.push_back(object.id());
        mesh.finish();
    }

    d->object_count++;
    meshgroup->finalize();
}

void CommandSocket::handleSettingList(cura::proto::SettingList* list)
{
    for(auto setting : list->settings())
    {
        FffProcessor::getInstance()->setSetting(setting.name(), setting.value());
    }
}

void CommandSocket::sendLayerInfo(int layer_nr, int32_t z, int32_t height)
{
    if(!d->current_sliced_object)
    {
        return;
    }

    cura::proto::Layer* layer = d->getLayerById(layer_nr);
    layer->set_height(z);
    layer->set_thickness(height);
}

void CommandSocket::sendPolygons(PolygonType type, int layer_nr, Polygons& polygons, int line_width)
{
    if(!d->current_sliced_object)
        return;

    if (polygons.size() == 0)
        return;

    cura::proto::Layer* layer = d->getLayerById(layer_nr);

    for(unsigned int i = 0; i < polygons.size(); ++i)
    {
        cura::proto::Polygon* p = layer->add_polygons();
        p->set_type(static_cast<cura::proto::Polygon_Type>(type));
        std::string polydata;
        polydata.append(reinterpret_cast<const char*>(polygons[i].data()), polygons[i].size() * sizeof(Point));
        p->set_points(polydata);
        p->set_line_width(line_width);
    }
}

void CommandSocket::sendProgress(float amount)
{
    auto message = std::make_shared<cura::proto::Progress>();
    amount /= d->object_count;
    amount += d->sliced_objects * (1. / d->object_count);
    message->set_amount(amount);
    d->socket->sendMessage(message);
}

void CommandSocket::sendProgressStage(Progress::Stage stage)
{
    // TODO
}

void CommandSocket::sendPrintTime()
{
    auto message = std::make_shared<cura::proto::ObjectPrintTime>();
    message->set_time(FffProcessor::getInstance()->getTotalPrintTime());
    message->set_material_amount(FffProcessor::getInstance()->getTotalFilamentUsed(0));
    d->socket->sendMessage(message);
}

void CommandSocket::sendPrintMaterialForObject(int index, int extruder_nr, float print_time)
{
//     socket.sendInt32(CMD_OBJECT_PRINT_MATERIAL);
//     socket.sendInt32(12);
//     socket.sendInt32(index);
//     socket.sendInt32(extruder_nr);
//     socket.sendFloat32(print_time);
}

void CommandSocket::beginSendSlicedObject()
{
    if(!d->sliced_object_list)
    {
        d->sliced_object_list = std::make_shared<cura::proto::SlicedObjectList>();
    }

    d->current_sliced_object = d->sliced_object_list->add_objects();
    d->current_sliced_object->set_id(d->object_ids[d->sliced_objects]);
}

void CommandSocket::endSendSlicedObject()
{
    d->sliced_objects++;
    d->current_layer_offset = d->current_layer_count;
    std::cout << "End sliced object called. sliced objects " << d->sliced_objects << " object count: " << d->object_count << std::endl;

    std::cout << "current layer count" << d->current_layer_count << std::endl;
    std::cout << "current layer offset" << d->current_layer_offset << std::endl;

    if(d->sliced_objects >= d->object_count)
    {
        d->socket->sendMessage(d->sliced_object_list);
        d->sliced_objects = 0;
        d->current_layer_count = 0;
        d->current_layer_offset = 0;
        d->sliced_object_list.reset();
        d->current_sliced_object = nullptr;
    }
}

void CommandSocket::beginGCode()
{
    FffProcessor::getInstance()->setTargetStream(&d->gcode_output_stream);
}

void CommandSocket::sendGCodeLayer()
{
    auto message = std::make_shared<cura::proto::GCodeLayer>();
    message->set_id(d->object_ids[0]);
    message->set_data(d->gcode_output_stream.str());
    d->socket->sendMessage(message);

    d->gcode_output_stream.str("");
}

void CommandSocket::sendGCodePrefix(std::string prefix)
{
    auto message = std::make_shared<cura::proto::GCodePrefix>();
    message->set_data(prefix);
    d->socket->sendMessage(message);
}

cura::proto::Layer* CommandSocket::Private::getLayerById(int id)
{
    id += current_layer_offset;

    auto itr = std::find_if(current_sliced_object->mutable_layers()->begin(), current_sliced_object->mutable_layers()->end(), [id](cura::proto::Layer& l) { return l.id() == id; });

    cura::proto::Layer* layer = nullptr;
    if(itr != current_sliced_object->mutable_layers()->end())
    {
        layer = &(*itr);
    }
    else
    {
        layer = current_sliced_object->add_layers();
        layer->set_id(id);
        current_layer_count++;
    }

    return layer;
}

}//namespace cura
<|endoftext|>


<commit_before>//----------------------------  rt_5.cc  ---------------------------
//    rt_5.cc,v 1.1 2003/06/09 15:59:07 wolf Exp
//    Version:
//
//    Copyright (C) 2003, 2004, 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  rt_5.cc  ---------------------------

// Just output the restriction matrices of the RT element

#include "../tests.h"
#include <base/logstream.h>
#include <fe/fe_raviart_thomas.h>

#include <fstream>
#include <string>

#define PRECISION 2

template<int dim>
void
test(const unsigned int degree)
{
  deallog << "FE_RaviartThomas<" << dim << "> (" << degree << ")"
	  << std::endl;

  FE_RaviartThomas<dim> fe_rt(degree);

  for (unsigned int c=0; c<GeometryInfo<dim>::children_per_cell; ++c)
    {
      const FullMatrix<double> & m = fe_rt.get_restriction_matrix(c);

      for (unsigned int i=0; i<m.m(); ++i)
	{
	  for (unsigned int j=0; j<m.n(); ++j)
	    deallog << m(i,j) << ' ';
	  deallog << std::endl;
	}

      deallog << std::endl;
    }
}

int
main()
{
  std::ofstream logfile ("rt_5/output");
  logfile.precision (PRECISION);
  logfile.setf(std::ios::fixed);
  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  for (unsigned int degree=0; degree<1; ++degree)
    test<2>(degree);
//  test<3>(degree);

  return 0;
}

<commit_msg>output matrices for higher order<commit_after>//----------------------------  rt_5.cc  ---------------------------
//    rt_5.cc,v 1.1 2003/06/09 15:59:07 wolf Exp
//    Version:
//
//    Copyright (C) 2003, 2004, 2005, 2006 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  rt_5.cc  ---------------------------

// Just output the restriction matrices of the RT element

#include "../tests.h"
#include <base/logstream.h>
#include <fe/fe_raviart_thomas.h>

#include <fstream>
#include <string>

#define PRECISION 2

template<int dim>
void
test(const unsigned int degree)
{
  deallog << "FE_RaviartThomas<" << dim << "> (" << degree << ")"
	  << std::endl;

  FE_RaviartThomas<dim> fe_rt(degree);

  if (false)
  for (unsigned int c=0; c<GeometryInfo<dim>::children_per_cell; ++c)
    {
      const FullMatrix<double> & m = fe_rt.get_restriction_matrix(c);

      for (unsigned int i=0; i<m.m(); ++i)
	{
	  for (unsigned int j=0; j<m.n(); ++j)
	    deallog << m(i,j) << ' ';
	  deallog << std::endl;
	}

      deallog << std::endl;
    }
}

int
main()
{
  std::ofstream logfile ("rt_5/output");
  logfile.precision (PRECISION);
  logfile.setf(std::ios::fixed);
  deallog.attach(logfile);
  deallog.depth_console(10);
  deallog.log_execution_time(true);
  deallog.threshold_double(1.e-10);

  for (unsigned int degree=0; degree<3; ++degree)
    {
      test<2>(degree);
//      test<3>(degree);
    }

  return 0;
}
<|endoftext|>


<commit_before>/*
*Component meta data.
*Used to hold global properties for all components.
*Includes OLC, so that OLC entries do not have to be defined on each instance of the component, as well as
*instance data specific to components.
*/
#pragma once
#ifndef COMPONENT_META_H
#define COMPONENT_META_H
#include <tinyxml2.h>
#include <algorithm>
#include <string>
#include <vector>
#include "mud.h"
#include "conf.h"
#include "olcGroup.h"
#include "olc.h"
#include "serializer.h"
#include "serializationHelpers.h"

class IComponentMeta:public ISerializable
{
public:
    virtual ~IComponentMeta() { }
    virtual Component* Create() = 0;
    virtual void Initialize() = 0;
    virtual std::string GetName() const = 0;
    virtual     BOOL AddDependency(const std::string &dependency) = 0;
    virtual     void GetDependencies(std::vector<std::string>* out) const = 0;
    virtual OLCGROUP GetOlcGroup() const = 0;
};

template <class T>
class ComponentMeta:public IComponentMeta
{
    std::string _name;
    std::vector <std::string> _dependencies; //component dependencies.
public:
    ComponentMeta(const std::string &name)
    {
        _name = name;
    }
    ~ComponentMeta()
    {
    }
    void SetName(const std::string &name)
    {
        _name = name;
    }
    std::string GetName() const
    {
        return _name;
    }
    /*
    *Checks to see if the specified dependency is located in the dependencies list.
    *Param: [in] the name of the dependency.
    *Return: True if the dependency exists in the dependencies list, false otherwise.
    */
    BOOL DependencyExists(const std::string &name) const
    {
        std::vector<std::string>::const_iterator it, itEnd;

        itEnd = _dependencies.end();
        for (it = _dependencies.begin(); it != itEnd; ++it)
            {
                if ((*it) == name)
                    {
                        return true;
                    }
            }

        return false;
    }

    /*
    *Will add the specified dependency to the list.
    *Param: [in] The name of the component to add as a dependency.
    */
    BOOL AddDependency(const std::string &dependency)
    {
        if (DependencyExists(dependency))
            {
                return false;
            }

        _dependencies.push_back(dependency);
        return true;
    }

    /*
    *Returns a pointer to a vector of dependency names.
    *Return: a pointer to the vector of strings containing the names of the dependencies associated with the component.
    */
    void GetDependencies(std::vector<std::string>* out) const
    {
        std::copy(_dependencies.begin(), _dependencies.end(), out->end());
    }

    /*
    *Called to create an instance of the component.
    *Param: [in] a pointer to the instance of the ComponentMeta object responsible for the component.
    */
    virtual T* Create()
    {
        T* ret = new T(this);
        ret->Initialize();
        return ret;
    }

    /*
    *Does all the initialization for a component once it's added
    *to the component factory.
    */
    virtual void Initialize()
    {
    }

    virtual OLCGROUP GetOlcGroup() const
    {
        return OLCGROUP::NONE;
    }
    virtual void Serialize(tinyxml2::XMLElement* root)
    {
        tinyxml2::XMLDocument* doc = root->GetDocument();
        tinyxml2::XMLElement* ent = doc->NewElement("cmeta");
        ent->SetAttribute("name", _name.c_str());

        SerializeList<std::string, std::vector<std::string>>("dependencies", "dependency", ent, _dependencies);
        root->InsertEndChild(ent);
    }
    virtual void Deserialize(tinyxml2::XMLElement* root)
    {
        _name = root->Attribute("name");

        DeserializeCollection(root, "dependencies", [this](tinyxml2::XMLElement* visitor)
        {
            AddDependency(visitor->Attribute("name"));
        });
    }
};
#endif
<commit_msg>Updated component meta to fix a serialization issue where the wrong function was called.<commit_after>/*
*Component meta data.
*Used to hold global properties for all components.
*Includes OLC, so that OLC entries do not have to be defined on each instance of the component, as well as
*instance data specific to components.
*/
#pragma once
#ifndef COMPONENT_META_H
#define COMPONENT_META_H
#include <tinyxml2.h>
#include <algorithm>
#include <string>
#include <vector>
#include "mud.h"
#include "conf.h"
#include "olcGroup.h"
#include "olc.h"
#include "serializer.h"
#include "serializationHelpers.h"

class IComponentMeta:public ISerializable
{
public:
    virtual ~IComponentMeta() { }
    virtual Component* Create() = 0;
    virtual void Initialize() = 0;
    virtual std::string GetName() const = 0;
    virtual     BOOL AddDependency(const std::string &dependency) = 0;
    virtual     void GetDependencies(std::vector<std::string>* out) const = 0;
    virtual OLCGROUP GetOlcGroup() const = 0;
};

template <class T>
class ComponentMeta:public IComponentMeta
{
    std::string _name;
    std::vector <std::string> _dependencies; //component dependencies.
public:
    ComponentMeta(const std::string &name)
    {
        _name = name;
    }
    ~ComponentMeta()
    {
    }
    void SetName(const std::string &name)
    {
        _name = name;
    }
    std::string GetName() const
    {
        return _name;
    }
    /*
    *Checks to see if the specified dependency is located in the dependencies list.
    *Param: [in] the name of the dependency.
    *Return: True if the dependency exists in the dependencies list, false otherwise.
    */
    BOOL DependencyExists(const std::string &name) const
    {
        std::vector<std::string>::const_iterator it, itEnd;

        itEnd = _dependencies.end();
        for (it = _dependencies.begin(); it != itEnd; ++it)
            {
                if ((*it) == name)
                    {
                        return true;
                    }
            }

        return false;
    }

    /*
    *Will add the specified dependency to the list.
    *Param: [in] The name of the component to add as a dependency.
    */
    BOOL AddDependency(const std::string &dependency)
    {
        if (DependencyExists(dependency))
            {
                return false;
            }

        _dependencies.push_back(dependency);
        return true;
    }

    /*
    *Returns a pointer to a vector of dependency names.
    *Return: a pointer to the vector of strings containing the names of the dependencies associated with the component.
    */
    void GetDependencies(std::vector<std::string>* out) const
    {
        std::copy(_dependencies.begin(), _dependencies.end(), out->end());
    }

    /*
    *Called to create an instance of the component.
    *Param: [in] a pointer to the instance of the ComponentMeta object responsible for the component.
    */
    virtual T* Create()
    {
        T* ret = new T(this);
        ret->Initialize();
        return ret;
    }

    /*
    *Does all the initialization for a component once it's added
    *to the component factory.
    */
    virtual void Initialize()
    {
    }

    virtual OLCGROUP GetOlcGroup() const
    {
        return OLCGROUP::NONE;
    }
    virtual void Serialize(tinyxml2::XMLElement* root)
    {
        tinyxml2::XMLDocument* doc = root->GetDocument();
        tinyxml2::XMLElement* ent = doc->NewElement("cmeta");
        ent->SetAttribute("name", _name.c_str());

        SerializeCollection<std::vector<std::string>, std::string>("dependencies", "dependency", root, _dependencies, [this](tinyxml2::XMLElement* visitor, const std::string& dep)
        {
            visitor->SetAttribute("name", dep.c_str());
        });
        root->InsertEndChild(ent);
    }
    virtual void Deserialize(tinyxml2::XMLElement* root)
    {
        _name = root->Attribute("name");

        DeserializeCollection(root, "dependencies", [this](tinyxml2::XMLElement* visitor)
        {
            AddDependency(visitor->Attribute("name"));
        });
    }
};
#endif
<|endoftext|>


<commit_before>#pragma once
#define ENABLE_WAWL_BASETYPE

#include <string>
#include <cstdint>

// WinAPI Header
#define NOMINMAX
#include <Windows.h>
#include <tchar.h>
#undef NOMINMAX

namespace wawl {
	namespace base {

		// ascii char type
		using Achar = ::CHAR;
		// wide char type
		using Wchar = ::WCHAR;
		// generic char type
		using Tchar = ::TCHAR;

		// ascii string type
		using Astring = std::basic_string<Achar>;
		// wide string type
		using Wstring = std::basic_string<Wchar>;
		// generic string type
		using Tstring = std::basic_string<Tchar>;

		// signed 64bit int
		using Int64 = std::int64_t;

		// unsigned int
		using Uint = unsigned int;
		// unsigned 8bit int
		using Uint8 = ::BYTE;
		// unsigned 16bit int
		using Uint16 = ::WORD;
		// unsigned 32bit int
		using Uint32 = ::DWORD;
		// unsigned 64bit int
		using Uint64 = std::uint64_t;

		// integer which can contain pointer
		using IntPtr = ::INT_PTR;
		// unsigned integer which cantain pointer
		using UintPtr = ::UINT_PTR;
		// larger than IntPtr
		using LongPtr = ::LONG_PTR;

		// any handle
		using Handle = ::HANDLE;
		constexpr Handle InvalidHandle = INVALID_HANDLE_VALUE;
		inline bool closeHandle(Handle h) {
			return ::CloseHandle(h) != 0;
		}

		// application handle
		using AppHandle = ::HINSTANCE;
		using ModuleHandle = ::HINSTANCE;

		struct Position {
			int x, y;

			Position operator + (const Position& p) {
				return Position{ x + p.x, y + p.y };
			}
			Position& operator += (const Position& p) {
				x += p.x;
				y += p.y;
				return *this;
			}
			Position operator - (const Position& p) {
				return Position{ x - p.x, y - p.y };
			}
			Position& operator -= (const Position& p) {
				x -= p.x;
				y -= p.y;
				return *this;
			}
		};
		using Size = Position;

		struct Rect {
			int x, y;
			int w, h;
		};

	} // ::wawl::base

	using namespace base;

} // ::wawl<commit_msg>add some basetypes<commit_after>#pragma once
#define ENABLE_WAWL_BASETYPE

#include <string>
#include <cstdint>

// WinAPI Header
#define NOMINMAX
#include <Windows.h>
#include <tchar.h>
#undef NOMINMAX

namespace wawl {
	namespace base {

		// ascii char type
		using Achar = ::CHAR;
		// wide char type
		using Wchar = ::WCHAR;
		// generic char type
		using Tchar = ::TCHAR;

		// ascii string type
		using Astring = std::basic_string<Achar>;
		// wide string type
		using Wstring = std::basic_string<Wchar>;
		// generic string type
		using Tstring = std::basic_string<Tchar>;

		// signed 8bit int
		using Int8 = std::int8_t;
		// signed 16bit int
		using Int16 = std::int16_t;
		// signed 32bit int
		using Int32 = std::int32_t;
		// signed 64bit int
		using Int64 = std::int64_t;

		// unsigned int
		using Uint = unsigned int;
		// unsigned 8bit int
		using Uint8 = ::BYTE;
		// unsigned 16bit int
		using Uint16 = ::WORD;
		// unsigned 32bit int
		using Uint32 = ::DWORD;
		// unsigned 64bit int
		using Uint64 = std::uint64_t;

		// integer which can contain pointer
		using IntPtr = ::INT_PTR;
		// unsigned integer which cantain pointer
		using UintPtr = ::UINT_PTR;
		// larger than IntPtr
		using LongPtr = ::LONG_PTR;

		// any handle
		using Handle = ::HANDLE;
		constexpr Handle InvalidHandle = INVALID_HANDLE_VALUE;
		inline bool closeHandle(Handle h) {
			return ::CloseHandle(h) != 0;
		}

		// application handle
		using AppHandle = ::HINSTANCE;
		using ModuleHandle = ::HINSTANCE;

		struct Position {
			int x, y;

			Position operator + (const Position& p) {
				return Position{ x + p.x, y + p.y };
			}
			Position& operator += (const Position& p) {
				x += p.x;
				y += p.y;
				return *this;
			}
			Position operator - (const Position& p) {
				return Position{ x - p.x, y - p.y };
			}
			Position& operator -= (const Position& p) {
				x -= p.x;
				y -= p.y;
				return *this;
			}
		};
		using Size = Position;

		struct Rect {
			int x, y;
			int w, h;
		};

	} // ::wawl::base

	using namespace base;

} // ::wawl<|endoftext|>


<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __RAPICORN_STRINGS_HH__
#define __RAPICORN_STRINGS_HH__

#include <rcore/utilities.hh>
#include <string>
#include <cstring>

namespace Rapicorn {

// == i18n ==
const char*                     rapicorn_gettext        (const char *text) RAPICORN_FORMAT (1);
#ifdef __RAPICORN_BUILD__
#define _(str)  Rapicorn::rapicorn_gettext (str)
#define N_(str) (str)
#endif

// == Macros ==
#ifdef RAPICORN_CONVENIENCE
/// Produce a const char* string, wrapping @a str into C-style double quotes.
#define CQUOTE(str)                                     RAPICORN_CQUOTE(str)
/// Create a Rapicorn::StringVector, from a const char* C-style array.
#define STRING_VECTOR_FROM_ARRAY(ConstCharArray)        RAPICORN_STRING_VECTOR_FROM_ARRAY(ConstCharArray)
#endif // RAPICORN_CONVENIENCE

// == C-String ==
bool    			cstring_to_bool          (const char *string, bool fallback = false);

// == String ==
String                          string_multiply          (const String &s, uint64 count);
String                          string_canonify          (const String &s, const String &valid_chars, const String &substitute);
String                          string_set_a2z           ();
String                          string_set_A2Z           ();
String                          string_set_ascii_alnum   ();
String  			string_tolower           (const String &str);
String  			string_toupper           (const String &str);
String  			string_totitle           (const String &str);
String  			string_printf            (const char *format, ...) RAPICORN_PRINTF (1, 2);
String  			string_vprintf           (const char *format, va_list vargs);
String  			string_locale_printf     (const char *format, ...) RAPICORN_PRINTF (1, 2);
String  			string_locale_vprintf    (const char *format, va_list vargs);
StringVector 			string_split             (const String &string, const String &splitter = "");
String  			string_join              (const String &junctor, const StringVector &strvec);
bool    			string_to_bool           (const String &string, bool fallback = false);
String  			string_from_bool         (bool value);
uint64  			string_to_uint           (const String &string, uint base = 10);
String  			string_from_uint         (uint64 value);
bool    			string_has_int           (const String &string);
int64   			string_to_int            (const String &string, uint base = 10);
String  			string_from_int          (int64 value);
String  			string_from_float        (float value);
double  			string_to_double         (const String &string);
double  			string_to_double         (const char *dblstring, const char **endptr);
String                          string_from_double       (double value);
inline String                   string_from_float        (double value)         { return string_from_double (value); }
inline double                   string_to_float          (const String &string) { return string_to_double (string); }
template<typename Type> Type    string_to_type           (const String &string);
template<typename Type> String  string_from_type         (Type          value);
template<> inline double        string_to_type<double>   (const String &string) { return string_to_double (string); }
template<> inline String        string_from_type<double> (double         value) { return string_from_double (value); }
template<> inline float         string_to_type<float>    (const String &string) { return string_to_float (string); }
template<> inline String        string_from_type<float>  (float         value)  { return string_from_float (value); }
template<> inline bool          string_to_type<bool>     (const String &string) { return string_to_bool (string); }
template<> inline String        string_from_type<bool>   (bool         value)   { return string_from_bool (value); }
template<> inline int16         string_to_type<int16>    (const String &string) { return string_to_int (string); }
template<> inline String        string_from_type<int16>  (int16         value)  { return string_from_int (value); }
template<> inline uint16        string_to_type<uint16>   (const String &string) { return string_to_uint (string); }
template<> inline String        string_from_type<uint16> (uint16        value)  { return string_from_uint (value); }
template<> inline int           string_to_type<int>      (const String &string) { return string_to_int (string); }
template<> inline String        string_from_type<int>    (int         value)    { return string_from_int (value); }
template<> inline uint          string_to_type<uint>     (const String &string) { return string_to_uint (string); }
template<> inline String        string_from_type<uint>   (uint           value) { return string_from_uint (value); }
template<> inline int64         string_to_type<int64>    (const String &string) { return string_to_int (string); }
template<> inline String        string_from_type<int64>  (int64         value)  { return string_from_int (value); }
template<> inline uint64        string_to_type<uint64>   (const String &string) { return string_to_uint (string); }
template<> inline String        string_from_type<uint64> (uint64         value) { return string_from_uint (value); }
template<> inline String        string_to_type<String>   (const String &string) { return string; }
template<> inline String        string_from_type<String> (String         value) { return value; }
vector<double>                  string_to_double_vector  (const String         &string);
String                          string_from_double_vector(const vector<double> &dvec,
                                                          const String         &delim = " ");
String  			string_from_errno        (int         errno_val);
bool                            string_is_uuid           (const String &uuid_string); /* check uuid formatting */
int                             string_cmp_uuid          (const String &uuid_string1,
                                                          const String &uuid_string2); /* -1=smaller, 0=equal, +1=greater (assuming valid uuid strings) */
bool                            string_startswith        (const String &string, const String &fragment);
bool                            string_endswith          (const String &string, const String &fragment);
bool    string_match_identifier                          (const String &ident1, const String &ident2);
bool    string_match_identifier_tail                     (const String &ident, const String &tail);
String  string_from_pretty_function_name                 (const char *gnuc_pretty_function);
String  string_to_cescape                                (const String &str);
String  string_to_cquote                                 (const String &str);
String  string_from_cquote                               (const String &input);
String  string_hexdump                                   (const void *addr, size_t length, size_t initial_offset = 0);
String  string_lstrip                                    (const String &input);
String  string_rstrip                                    (const String &input);
String  string_strip                                     (const String &input);
String  string_substitute_char                           (const String &input, const char match, const char subst);
String  string_vector_find (const StringVector &svector, const String &key, const String &fallback);
StringVector cstrings_to_vector (const char*, ...) RAPICORN_SENTINEL;
void         memset4		(uint32 *mem, uint32 filler, uint length);
long double posix_locale_strtold   (const char *nptr, char **endptr);
long double current_locale_strtold (const char *nptr, char **endptr);

// == String Options ==
bool    string_option_check     (const String   &option_string,
                                 const String   &option);
String  string_option_get       (const String   &option_string,
                                 const String   &option);
void    string_options_split    (const String   &option_string,
                                 vector<String> &option_names,
                                 vector<String> &option_values,
                                 const String   &empty_default = "");

// == Strings ==
/// Convenience Constructor for StringSeq or std::vector<std::string>
class Strings : public std::vector<std::string>
{
  typedef const std::string CS;
public:
  explicit Strings (CS &s1);
  explicit Strings (CS &s1, CS &s2);
  explicit Strings (CS &s1, CS &s2, CS &s3);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA, CS &sB);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA, CS &sB, CS &sC);
};

// == Charset Conversions ==
bool    text_convert    (const String &to_charset,
                         String       &output_string,
                         const String &from_charset,
                         const String &input_string,
                         const String &fallback_charset = "ISO-8859-15",
                         const String &output_mark = "");

// == C strings ==
using         ::strerror;       // introduce (const char* strerror (int))
const char*     strerror ();    // simple wrapper for strerror (errno)

// == Implementations ==
#define RAPICORN_STRING_VECTOR_FROM_ARRAY(ConstCharArray)               ({ \
  Rapicorn::StringVector __a;                                           \
  const Rapicorn::uint64 __l = RAPICORN_ARRAY_SIZE (ConstCharArray);    \
  for (Rapicorn::uint64 __ai = 0; __ai < __l; __ai++)                   \
    __a.push_back (ConstCharArray[__ai]);                               \
  __a; })
#define RAPICORN_CQUOTE(str)    (Rapicorn::string_to_cquote (str).c_str())

} // Rapicorn

#endif /* __RAPICORN_STRINGS_HH__ */
<commit_msg>RCORE: add string_format() for type safe printf-like formatting<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __RAPICORN_STRINGS_HH__
#define __RAPICORN_STRINGS_HH__

#include <rcore/utilities.hh>
#include <rcore/formatter.hh>
#include <string>
#include <cstring>

namespace Rapicorn {

// == i18n ==
const char*                     rapicorn_gettext        (const char *text) RAPICORN_FORMAT (1);
#ifdef __RAPICORN_BUILD__
#define _(str)  Rapicorn::rapicorn_gettext (str)
#define N_(str) (str)
#endif

// == Macros ==
#ifdef RAPICORN_CONVENIENCE
/// Produce a const char* string, wrapping @a str into C-style double quotes.
#define CQUOTE(str)                                     RAPICORN_CQUOTE(str)
/// Create a Rapicorn::StringVector, from a const char* C-style array.
#define STRING_VECTOR_FROM_ARRAY(ConstCharArray)        RAPICORN_STRING_VECTOR_FROM_ARRAY(ConstCharArray)
#endif // RAPICORN_CONVENIENCE

// == C-String ==
bool    			cstring_to_bool          (const char *string, bool fallback = false);

// == String Formatting ==
template<class... Args> RAPICORN_PRINTF (1, 0) String string_format (const char *format, Args... args);

// == String ==
String                          string_multiply          (const String &s, uint64 count);
String                          string_canonify          (const String &s, const String &valid_chars, const String &substitute);
String                          string_set_a2z           ();
String                          string_set_A2Z           ();
String                          string_set_ascii_alnum   ();
String  			string_tolower           (const String &str);
String  			string_toupper           (const String &str);
String  			string_totitle           (const String &str);
String  			string_printf            (const char *format, ...) RAPICORN_PRINTF (1, 2);
String  			string_vprintf           (const char *format, va_list vargs);
String  			string_locale_printf     (const char *format, ...) RAPICORN_PRINTF (1, 2);
String  			string_locale_vprintf    (const char *format, va_list vargs);
StringVector 			string_split             (const String &string, const String &splitter = "");
String  			string_join              (const String &junctor, const StringVector &strvec);
bool    			string_to_bool           (const String &string, bool fallback = false);
String  			string_from_bool         (bool value);
uint64  			string_to_uint           (const String &string, uint base = 10);
String  			string_from_uint         (uint64 value);
bool    			string_has_int           (const String &string);
int64   			string_to_int            (const String &string, uint base = 10);
String  			string_from_int          (int64 value);
String  			string_from_float        (float value);
double  			string_to_double         (const String &string);
double  			string_to_double         (const char *dblstring, const char **endptr);
String                          string_from_double       (double value);
inline String                   string_from_float        (double value)         { return string_from_double (value); }
inline double                   string_to_float          (const String &string) { return string_to_double (string); }
template<typename Type> Type    string_to_type           (const String &string);
template<typename Type> String  string_from_type         (Type          value);
template<> inline double        string_to_type<double>   (const String &string) { return string_to_double (string); }
template<> inline String        string_from_type<double> (double         value) { return string_from_double (value); }
template<> inline float         string_to_type<float>    (const String &string) { return string_to_float (string); }
template<> inline String        string_from_type<float>  (float         value)  { return string_from_float (value); }
template<> inline bool          string_to_type<bool>     (const String &string) { return string_to_bool (string); }
template<> inline String        string_from_type<bool>   (bool         value)   { return string_from_bool (value); }
template<> inline int16         string_to_type<int16>    (const String &string) { return string_to_int (string); }
template<> inline String        string_from_type<int16>  (int16         value)  { return string_from_int (value); }
template<> inline uint16        string_to_type<uint16>   (const String &string) { return string_to_uint (string); }
template<> inline String        string_from_type<uint16> (uint16        value)  { return string_from_uint (value); }
template<> inline int           string_to_type<int>      (const String &string) { return string_to_int (string); }
template<> inline String        string_from_type<int>    (int         value)    { return string_from_int (value); }
template<> inline uint          string_to_type<uint>     (const String &string) { return string_to_uint (string); }
template<> inline String        string_from_type<uint>   (uint           value) { return string_from_uint (value); }
template<> inline int64         string_to_type<int64>    (const String &string) { return string_to_int (string); }
template<> inline String        string_from_type<int64>  (int64         value)  { return string_from_int (value); }
template<> inline uint64        string_to_type<uint64>   (const String &string) { return string_to_uint (string); }
template<> inline String        string_from_type<uint64> (uint64         value) { return string_from_uint (value); }
template<> inline String        string_to_type<String>   (const String &string) { return string; }
template<> inline String        string_from_type<String> (String         value) { return value; }
vector<double>                  string_to_double_vector  (const String         &string);
String                          string_from_double_vector(const vector<double> &dvec,
                                                          const String         &delim = " ");
String  			string_from_errno        (int         errno_val);
bool                            string_is_uuid           (const String &uuid_string); /* check uuid formatting */
int                             string_cmp_uuid          (const String &uuid_string1,
                                                          const String &uuid_string2); /* -1=smaller, 0=equal, +1=greater (assuming valid uuid strings) */
bool                            string_startswith        (const String &string, const String &fragment);
bool                            string_endswith          (const String &string, const String &fragment);
bool    string_match_identifier                          (const String &ident1, const String &ident2);
bool    string_match_identifier_tail                     (const String &ident, const String &tail);
String  string_from_pretty_function_name                 (const char *gnuc_pretty_function);
String  string_to_cescape                                (const String &str);
String  string_to_cquote                                 (const String &str);
String  string_from_cquote                               (const String &input);
String  string_hexdump                                   (const void *addr, size_t length, size_t initial_offset = 0);
String  string_lstrip                                    (const String &input);
String  string_rstrip                                    (const String &input);
String  string_strip                                     (const String &input);
String  string_substitute_char                           (const String &input, const char match, const char subst);
String  string_vector_find (const StringVector &svector, const String &key, const String &fallback);
StringVector cstrings_to_vector (const char*, ...) RAPICORN_SENTINEL;
void         memset4		(uint32 *mem, uint32 filler, uint length);
long double posix_locale_strtold   (const char *nptr, char **endptr);
long double current_locale_strtold (const char *nptr, char **endptr);

// == String Options ==
bool    string_option_check     (const String   &option_string,
                                 const String   &option);
String  string_option_get       (const String   &option_string,
                                 const String   &option);
void    string_options_split    (const String   &option_string,
                                 vector<String> &option_names,
                                 vector<String> &option_values,
                                 const String   &empty_default = "");

// == Strings ==
/// Convenience Constructor for StringSeq or std::vector<std::string>
class Strings : public std::vector<std::string>
{
  typedef const std::string CS;
public:
  explicit Strings (CS &s1);
  explicit Strings (CS &s1, CS &s2);
  explicit Strings (CS &s1, CS &s2, CS &s3);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA, CS &sB);
  explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA, CS &sB, CS &sC);
};

// == Charset Conversions ==
bool    text_convert    (const String &to_charset,
                         String       &output_string,
                         const String &from_charset,
                         const String &input_string,
                         const String &fallback_charset = "ISO-8859-15",
                         const String &output_mark = "");

// == C strings ==
using         ::strerror;       // introduce (const char* strerror (int))
const char*     strerror ();    // simple wrapper for strerror (errno)

// == Implementations ==
#define RAPICORN_STRING_VECTOR_FROM_ARRAY(ConstCharArray)               ({ \
  Rapicorn::StringVector __a;                                           \
  const Rapicorn::uint64 __l = RAPICORN_ARRAY_SIZE (ConstCharArray);    \
  for (Rapicorn::uint64 __ai = 0; __ai < __l; __ai++)                   \
    __a.push_back (ConstCharArray[__ai]);                               \
  __a; })
#define RAPICORN_CQUOTE(str)    (Rapicorn::string_to_cquote (str).c_str())

template<class... Args> String
string_format (const char *format, Args... args)
{
  return Lib::StringFormatter::format (format, args...);
}

} // Rapicorn

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


<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
extern "C" {
  #include "config.h"
  #include "debug.h"
  #include "util.h"
  #include "loop.h"
  #include "process.h"
  #include "profile.h"
  #include "socket.h"
  #include "msg.h"
  #include "iface.h"
  #include "id.h"
}
#include "gtest/gtest.h"

extern co_socket_t unix_socket_proto;

/*
 * POA
 * * List socket functions that need testing @
 * * Come up with general order of testing @
 * * Determine set up variables and functions
 * * Determine tear down process
 *
 *
 * Functions to test:
 * co_obj_t *co_socket_create(size_t size, co_socket_t proto);
 * int co_socket_send(co_obj_t *self, char *outgoing, size_t length);
 * int co_socket_receive(co_obj_t * self, co_obj_t *fd, char *incoming, size_t length);
 * int co_socket_hangup(co_obj_t *self, co_obj_t *context);
 * int co_socket_destroy(co_obj_t *self);
 *
 *
 */

class SocketTest : public ::testing::Test
{
protected:
  int ret;

  void Send();

  co_socket_t *socket1;

  SocketTest()
  {
    socket1 = (co_socket_t*)co_socket_create(sizeof(co_socket_t), unix_socket_proto);
    // socket1->register_cb = co_loop_add_socket;
    socket1->bind((co_obj_t*)socket1, "commotiontest2.sock");
  }

  virtual void SetUp()
  {
  }

  ~SocketTest()
  {
    co_socket_destroy((co_obj_t *)socket1);
  }

};

void SocketTest::Send()
{

  ASSERT_EQ(1, 1);
}

TEST_F(SocketTest, Send)
{
  Send();
}<commit_msg>completed first draft of socket testing<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
extern "C" {
  #include "config.h"
  #include "debug.h"
  #include "util.h"
  #include "loop.h"
  #include "process.h"
  #include "profile.h"
  #include "socket.h"
  #include "msg.h"
  #include "iface.h"
  #include "id.h"
  #include "list.h"
}
#include "gtest/gtest.h"

extern co_socket_t unix_socket_proto;

/*
 * POA
 * * List socket functions that need testing @
 * * Come up with general order of testing @
 * * Determine set up variables and functions
 * * Determine tear down process
 *
 *
 * Functions to test:
 * co_obj_t *co_socket_create(size_t size, co_socket_t proto);
 * int co_socket_send(co_obj_t *self, char *outgoing, size_t length);
 * int co_socket_receive(co_obj_t * self, co_obj_t *fd, char *incoming, size_t length);
 * int co_socket_hangup(co_obj_t *self, co_obj_t *context);
 * int co_socket_destroy(co_obj_t *self);
 *
 *
 */

class SocketTest : public ::testing::Test
{
protected:
  int ret;

  #define MAX_MESSAGE 100

  char message1[MAX_MESSAGE];

  void SendReceive();

  co_socket_t *socket1;
  co_socket_t *socket2;

  SocketTest()
  {
    socket1 = (co_socket_t*)co_socket_create(sizeof(co_socket_t), unix_socket_proto);
    // socket1->register_cb = co_loop_add_socket;
    socket1->bind((co_obj_t*)socket1, "commotiontest.sock");

    socket2 = (co_socket_t*)co_socket_create(sizeof(co_socket_t), unix_socket_proto);
    socket2->connect((co_obj_t*)socket2, "commotiontest.sock");
    // socket1->register_cb = co_loop_add_socket;
    // socket2->bind((co_obj_t*)socket2, "commotiontest.sock");
  }

  virtual void SetUp()
  {
  }

  ~SocketTest()
  {
    co_socket_destroy((co_obj_t *)socket1);
  }

};

void SocketTest::SendReceive()
{
  char buffer[14];
  int length = 14;
  int received = 0;

  char *test_message = "test message";

  ret = co_socket_send((co_obj_t *)socket2->fd, "test message", sizeof("test message"));
  ASSERT_EQ(sizeof("test message"), ret);

  received = co_socket_receive((co_obj_t *)socket1, (co_obj_t *)socket1->fd, buffer, length);

  received = co_socket_receive((co_obj_t *)socket1, (co_obj_t *)co_list_get_first(socket1->rfd_lst), buffer, length);

  DEBUG("\n\nSent %d bytes.\n", ret);
  DEBUG("\n\nReceived %d bytes.\n", received);

  ASSERT_STREQ(test_message, buffer);

  co_socket_hangup
}

TEST_F(SocketTest, SendReceive)
{
  SendReceive();
}<|endoftext|>