<commit_before>#ifndef CAFFE_UTIL_IO_H_
#define CAFFE_UTIL_IO_H_

#include <boost/filesystem.hpp>
#include <string>

#include "google/protobuf/message.h"

#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"

namespace caffe {

using ::google::protobuf::Message;
using ::boost::filesystem::path;

inline void MakeTempFilename(string* temp_filename) {
  temp_filename->clear();
  const path& model = boost::filesystem::temp_directory_path()
    /"caffe_test.%%%%%%";
  *temp_filename = boost::filesystem::unique_path(model).string();
}

inline void MakeTempDir(string* temp_dirname) {
  temp_dirname->clear();
  const path& model = boost::filesystem::temp_directory_path()
    /"caffe_test.%%%%%%";
  const path& dir = boost::filesystem::unique_path(model).string();
  bool directoryCreated = boost::filesystem::create_directory(dir);
  CHECK(directoryCreated);
  *temp_dirname = dir.string();
}

bool ReadProtoFromTextFile(const char* filename, Message* proto);

inline bool ReadProtoFromTextFile(const string& filename, Message* proto) {
  return ReadProtoFromTextFile(filename.c_str(), proto);
}

inline void ReadProtoFromTextFileOrDie(const char* filename, Message* proto) {
  CHECK(ReadProtoFromTextFile(filename, proto));
}

inline void ReadProtoFromTextFileOrDie(const string& filename, Message* proto) {
  ReadProtoFromTextFileOrDie(filename.c_str(), proto);
}

void WriteProtoToTextFile(const Message& proto, const char* filename);
inline void WriteProtoToTextFile(const Message& proto, const string& filename) {
  WriteProtoToTextFile(proto, filename.c_str());
}

bool ReadProtoFromBinaryFile(const char* filename, Message* proto);

inline bool ReadProtoFromBinaryFile(const string& filename, Message* proto) {
  return ReadProtoFromBinaryFile(filename.c_str(), proto);
}

inline void ReadProtoFromBinaryFileOrDie(const char* filename, Message* proto) {
  CHECK(ReadProtoFromBinaryFile(filename, proto));
}

inline void ReadProtoFromBinaryFileOrDie(const string& filename,
                                         Message* proto) {
  ReadProtoFromBinaryFileOrDie(filename.c_str(), proto);
}

void WriteProtoToBinaryFile(const Message& proto, const char* filename);
inline void WriteProtoToBinaryFile(
    const Message& proto, const string& filename) {
  WriteProtoToBinaryFile(proto, filename.c_str());
}

bool ReadFileToDatum(const string& filename, const int label, Datum* datum);

inline bool ReadFileToDatum(const string& filename, Datum* datum) {
  return ReadFileToDatum(filename, -1, datum);
}

bool ReadImageToDatum(const string& filename, const int label,
    const int height, const int width, const bool is_color,
    const std::string & encoding, Datum* datum);

inline bool ReadImageToDatum(const string& filename, const int label,
    const int height, const int width, const bool is_color, Datum* datum) {
  return ReadImageToDatum(filename, label, height, width, is_color,
                          "", datum);
}

inline bool ReadImageToDatum(const string& filename, const int label,
    const int height, const int width, Datum* datum) {
  return ReadImageToDatum(filename, label, height, width, true, datum);
}

inline bool ReadImageToDatum(const string& filename, const int label,
    const bool is_color, Datum* datum) {
  return ReadImageToDatum(filename, label, 0, 0, is_color, datum);
}

inline bool ReadImageToDatum(const string& filename, const int label,
    Datum* datum) {
  return ReadImageToDatum(filename, label, 0, 0, true, datum);
}

inline bool ReadImageToDatum(const string& filename, const int label,
    const std::string & encoding, Datum* datum) {
  return ReadImageToDatum(filename, label, 0, 0, true, encoding, datum);
}

bool DecodeDatumNative(Datum* datum);
bool DecodeDatum(Datum* datum, bool is_color);

#ifdef USE_OPENCV
cv::Mat ReadImageToCVMat(const string& filename,
    const int height, const int width, const bool is_color);

cv::Mat ReadImageToCVMat(const string& filename,
    const int height, const int width);

cv::Mat ReadImageToCVMat(const string& filename,
    const bool is_color);

cv::Mat ReadImageToCVMat(const string& filename);

cv::Mat DecodeDatumToCVMatNative(const Datum& datum);
cv::Mat DecodeDatumToCVMat(const Datum& datum, bool is_color);

void CVMatToDatum(const cv::Mat& cv_img, Datum* datum);
#endif  // USE_OPENCV

}  // namespace caffe

#endif   // CAFFE_UTIL_IO_H_
<commit_msg>Secure implementation of MakeTempDir<commit_after>#ifndef CAFFE_UTIL_IO_H_
#define CAFFE_UTIL_IO_H_

#include <boost/filesystem.hpp>
#include <string>

#include "google/protobuf/message.h"

#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"

#ifndef CAFFE_TMP_DIR_RETRIES
#define CAFFE_TMP_DIR_RETRIES 100
#endif

namespace caffe {

using ::google::protobuf::Message;
using ::boost::filesystem::path;

inline void MakeTempFilename(string* temp_filename) {
  temp_filename->clear();
  const path& model = boost::filesystem::temp_directory_path()
    /"caffe_test.%%%%%%";
  *temp_filename = boost::filesystem::unique_path(model).string();
}

inline void MakeTempDir(string* temp_dirname) {
  temp_dirname->clear();
  const path& model =
    boost::filesystem::temp_directory_path()/"caffe_test.%%%%-%%%%";
  for ( int i = 0; i < CAFFE_TMP_DIR_RETRIES; i++ ) {
    const path& dir = boost::filesystem::unique_path(model).string();
    bool done = boost::filesystem::create_directory(dir);
    if ( done ) {
      *temp_dirname = dir.string();
      return;
    }
  }
  LOG(FATAL) << "Failed to create a temporary directory.";
}

bool ReadProtoFromTextFile(const char* filename, Message* proto);

inline bool ReadProtoFromTextFile(const string& filename, Message* proto) {
  return ReadProtoFromTextFile(filename.c_str(), proto);
}

inline void ReadProtoFromTextFileOrDie(const char* filename, Message* proto) {
  CHECK(ReadProtoFromTextFile(filename, proto));
}

inline void ReadProtoFromTextFileOrDie(const string& filename, Message* proto) {
  ReadProtoFromTextFileOrDie(filename.c_str(), proto);
}

void WriteProtoToTextFile(const Message& proto, const char* filename);
inline void WriteProtoToTextFile(const Message& proto, const string& filename) {
  WriteProtoToTextFile(proto, filename.c_str());
}

bool ReadProtoFromBinaryFile(const char* filename, Message* proto);

inline bool ReadProtoFromBinaryFile(const string& filename, Message* proto) {
  return ReadProtoFromBinaryFile(filename.c_str(), proto);
}

inline void ReadProtoFromBinaryFileOrDie(const char* filename, Message* proto) {
  CHECK(ReadProtoFromBinaryFile(filename, proto));
}

inline void ReadProtoFromBinaryFileOrDie(const string& filename,
                                         Message* proto) {
  ReadProtoFromBinaryFileOrDie(filename.c_str(), proto);
}

void WriteProtoToBinaryFile(const Message& proto, const char* filename);
inline void WriteProtoToBinaryFile(
    const Message& proto, const string& filename) {
  WriteProtoToBinaryFile(proto, filename.c_str());
}

bool ReadFileToDatum(const string& filename, const int label, Datum* datum);

inline bool ReadFileToDatum(const string& filename, Datum* datum) {
  return ReadFileToDatum(filename, -1, datum);
}

bool ReadImageToDatum(const string& filename, const int label,
    const int height, const int width, const bool is_color,
    const std::string & encoding, Datum* datum);

inline bool ReadImageToDatum(const string& filename, const int label,
    const int height, const int width, const bool is_color, Datum* datum) {
  return ReadImageToDatum(filename, label, height, width, is_color,
                          "", datum);
}

inline bool ReadImageToDatum(const string& filename, const int label,
    const int height, const int width, Datum* datum) {
  return ReadImageToDatum(filename, label, height, width, true, datum);
}

inline bool ReadImageToDatum(const string& filename, const int label,
    const bool is_color, Datum* datum) {
  return ReadImageToDatum(filename, label, 0, 0, is_color, datum);
}

inline bool ReadImageToDatum(const string& filename, const int label,
    Datum* datum) {
  return ReadImageToDatum(filename, label, 0, 0, true, datum);
}

inline bool ReadImageToDatum(const string& filename, const int label,
    const std::string & encoding, Datum* datum) {
  return ReadImageToDatum(filename, label, 0, 0, true, encoding, datum);
}

bool DecodeDatumNative(Datum* datum);
bool DecodeDatum(Datum* datum, bool is_color);

#ifdef USE_OPENCV
cv::Mat ReadImageToCVMat(const string& filename,
    const int height, const int width, const bool is_color);

cv::Mat ReadImageToCVMat(const string& filename,
    const int height, const int width);

cv::Mat ReadImageToCVMat(const string& filename,
    const bool is_color);

cv::Mat ReadImageToCVMat(const string& filename);

cv::Mat DecodeDatumToCVMatNative(const Datum& datum);
cv::Mat DecodeDatumToCVMat(const Datum& datum, bool is_color);

void CVMatToDatum(const cv::Mat& cv_img, Datum* datum);
#endif  // USE_OPENCV

}  // namespace caffe

#endif   // CAFFE_UTIL_IO_H_
<|endoftext|>


<commit_before>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. 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 <chartsql/CSTableScan.h>
#include <chartsql/qtree/ColumnReferenceNode.h>
#include <chartsql/runtime/defaultruntime.h>
#include <chartsql/runtime/compile.h>
#include <fnord/inspect.h>

using namespace fnord;

namespace csql {

CSTableScan::CSTableScan(
    RefPtr<SequentialScanNode> stmt,
    cstable::CSTableReader&& cstable,
    DefaultRuntime* runtime) :
    cstable_(std::move(cstable)),
    colindex_(0),
    aggr_strategy_(stmt->aggregationStrategy()) {

  Set<String> column_names;
  for (const auto& slnode : stmt->selectList()) {
    findColumns(slnode->expression(), &column_names);
  }

  for (const auto& col : column_names) {
    columns_.emplace(col, ColumnRef(cstable_.getColumnReader(col), colindex_++));
  }

  for (auto& slnode : stmt->selectList()) {
    resolveColumns(slnode->expression());
  }

  for (const auto& slnode : stmt->selectList()) {
    select_list_.emplace_back(
        findMaxRepetitionLevel(slnode->expression()),
        runtime->buildScalarExpression(slnode->expression()),
        &scratch_);
  }
}

void CSTableScan::execute(
    ExecutionContext* context,
    Function<bool (int argc, const SValue* argv)> fn) {
  uint64_t select_level = 0;
  uint64_t fetch_level = 0;

  Vector<SValue> in_row(colindex_, SValue{});
  Vector<SValue> out_row(select_list_.size(), SValue{});

  size_t num_records = 0;
  size_t total_records = cstable_.numRecords();
  while (num_records < total_records) {
    uint64_t next_level = 0;

    if (fetch_level == 0) {
      ++num_records;
    }

    for (auto& col : columns_) {
      auto nextr = col.second.reader->nextRepetitionLevel();

      if (nextr >= fetch_level) {
        auto& reader = col.second.reader;

        uint64_t r;
        uint64_t d;
        void* data;
        size_t size;
        reader->next(&r, &d, &data, &size);

        switch (col.second.reader->type()) {

          case msg::FieldType::STRING:
            in_row[col.second.index] =
                SValue(SValue::StringType((char*) data, size));
            break;

          case msg::FieldType::UINT32:
          case msg::FieldType::UINT64:
            switch (size) {
              case sizeof(uint32_t):
                in_row[col.second.index] =
                    SValue(SValue::IntegerType(*((uint32_t*) data)));
                break;
              case sizeof(uint64_t):
                in_row[col.second.index] =
                    SValue(SValue::IntegerType(*((uint64_t*) data)));
                break;
              case 0:
                in_row[col.second.index] = SValue();
                break;
            }
            break;

          case msg::FieldType::BOOLEAN:
            switch (size) {
              case sizeof(uint32_t):
                in_row[col.second.index] =
                    SValue(SValue::BoolType(*((uint32_t*) data) > 0));
                break;
              case sizeof(uint64_t):
                in_row[col.second.index] =
                    SValue(SValue::BoolType(*((uint64_t*) data) > 0));
                break;
              case 0:
                in_row[col.second.index] = SValue(SValue::BoolType(false));
                break;
            }
            break;

          case msg::FieldType::OBJECT:
            RAISE(kIllegalStateError);

        }
      }

      next_level = std::max(next_level, col.second.reader->nextRepetitionLevel());
    }

    fetch_level = next_level;

    if (true) { // where clause
      for (int i = 0; i < select_list_.size(); ++i) {
        if (select_list_[i].rep_level >= select_level) {
          select_list_[i].compiled->accumulate(
              &select_list_[i].instance,
              in_row.size(),
              in_row.data());
        }
      }

      switch (aggr_strategy_) {

        case AggregationStrategy::AGGREGATE_ALL:
          break;

        case AggregationStrategy::AGGREGATE_WITHIN_RECORD:
          if (next_level != 0) {
            break;
          }
          /* fallthrough */

        case AggregationStrategy::NO_AGGREGATION:
          for (int i = 0; i < select_list_.size(); ++i) {
            select_list_[i].compiled->result(
                &select_list_[i].instance,
                &out_row[i]);

            select_list_[i].compiled->reset(&select_list_[i].instance);
          }

          if (!fn(out_row.size(), out_row.data())) {
            return;
          }

          break;

      }

      select_level = fetch_level;
    } else {
      select_level = std::min(select_level, fetch_level);
    }

    for (const auto& col : columns_) {
      if (col.second.reader->maxRepetitionLevel() >= select_level) {
        in_row[col.second.index] = SValue();
      }
    }
  }

  switch (aggr_strategy_) {
    case AggregationStrategy::AGGREGATE_ALL:
      for (int i = 0; i < select_list_.size(); ++i) {
        select_list_[i].compiled->result(
            &select_list_[i].instance,
            &out_row[i]);

        select_list_[i].compiled->reset(&select_list_[i].instance);
      }

      fn(out_row.size(), out_row.data());
      break;

    default:
      break;

  }
}

void CSTableScan::findColumns(
    RefPtr<ScalarExpressionNode> expr,
    Set<String>* column_names) const {
  auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    column_names->emplace(fieldref->fieldName());
  }

  for (const auto& e : expr->arguments()) {
    findColumns(e, column_names);
  }
}

void CSTableScan::resolveColumns(RefPtr<ScalarExpressionNode> expr) const {
  auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    auto col = columns_.find(fieldref->fieldName());
    if (col == columns_.end()) {
      RAISE(kIllegalStateError);
    }

    fieldref->setColumnIndex(col->second.index);
  }

  for (const auto& e : expr->arguments()) {
    resolveColumns(e);
  }
}

uint64_t CSTableScan::findMaxRepetitionLevel(
    RefPtr<ScalarExpressionNode> expr) const {
  uint64_t max_level = 0;

  auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    auto col = columns_.find(fieldref->fieldName());
    if (col == columns_.end()) {
      RAISE(kIllegalStateError);
    }

    auto col_level = col->second.reader->maxRepetitionLevel();
    if (col_level > max_level) {
      max_level = col_level;
    }
  }

  for (const auto& e : expr->arguments()) {
    auto e_level = findMaxRepetitionLevel(e);
    if (e_level > max_level) {
      max_level = e_level;
    }
  }

  return max_level;
}

CSTableScan::ColumnRef::ColumnRef(
    RefPtr<cstable::ColumnReader> r,
    size_t i) :
    reader(r),
    index(i) {}

CSTableScan::ExpressionRef::ExpressionRef(
    size_t _rep_level,
    ScopedPtr<ScalarExpression> _compiled,
    ScratchMemory* smem) :
    rep_level(_rep_level),
    compiled(std::move(_compiled)),
    instance(compiled->allocInstance(smem)) {}

CSTableScan::ExpressionRef::ExpressionRef(
    ExpressionRef&& other) :
    rep_level(other.rep_level),
    compiled(std::move(other.compiled)),
    instance(other.instance) {
  other.instance.scratch = nullptr;
}

CSTableScan::ExpressionRef::~ExpressionRef() {
  if (instance.scratch) {
    compiled->freeInstance(&instance);
  }
}

} // namespace csql
<commit_msg>CSTableScan...<commit_after>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. 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 <chartsql/CSTableScan.h>
#include <chartsql/qtree/ColumnReferenceNode.h>
#include <chartsql/runtime/defaultruntime.h>
#include <chartsql/runtime/compile.h>
#include <fnord/inspect.h>

using namespace fnord;

namespace csql {

CSTableScan::CSTableScan(
    RefPtr<SequentialScanNode> stmt,
    cstable::CSTableReader&& cstable,
    DefaultRuntime* runtime) :
    cstable_(std::move(cstable)),
    colindex_(0),
    aggr_strategy_(stmt->aggregationStrategy()) {

  Set<String> column_names;
  for (const auto& slnode : stmt->selectList()) {
    findColumns(slnode->expression(), &column_names);
  }

  for (const auto& col : column_names) {
    columns_.emplace(col, ColumnRef(cstable_.getColumnReader(col), colindex_++));
  }

  for (auto& slnode : stmt->selectList()) {
    resolveColumns(slnode->expression());
  }

  for (const auto& slnode : stmt->selectList()) {
    select_list_.emplace_back(
        findMaxRepetitionLevel(slnode->expression()),
        runtime->buildScalarExpression(slnode->expression()),
        &scratch_);
  }
}

void CSTableScan::execute(
    ExecutionContext* context,
    Function<bool (int argc, const SValue* argv)> fn) {
  uint64_t select_level = 0;
  uint64_t fetch_level = 0;

  Vector<SValue> in_row(colindex_, SValue{});
  Vector<SValue> out_row(select_list_.size(), SValue{});

  size_t num_records = 0;
  size_t total_records = cstable_.numRecords();
  while (num_records < total_records) {
    uint64_t next_level = 0;

    if (fetch_level == 0) {
      ++num_records;
    }

    for (auto& col : columns_) {
      auto nextr = col.second.reader->nextRepetitionLevel();

      if (nextr >= fetch_level) {
        auto& reader = col.second.reader;

        uint64_t r;
        uint64_t d;
        void* data;
        size_t size;
        reader->next(&r, &d, &data, &size);

        switch (col.second.reader->type()) {

          case msg::FieldType::STRING:
            in_row[col.second.index] =
                SValue(SValue::StringType((char*) data, size));
            break;

          case msg::FieldType::UINT32:
          case msg::FieldType::UINT64:
            switch (size) {
              case sizeof(uint32_t):
                in_row[col.second.index] =
                    SValue(SValue::IntegerType(*((uint32_t*) data)));
                break;
              case sizeof(uint64_t):
                in_row[col.second.index] =
                    SValue(SValue::IntegerType(*((uint64_t*) data)));
                break;
              case 0:
                in_row[col.second.index] = SValue();
                break;
            }
            break;

          case msg::FieldType::BOOLEAN:
            switch (size) {
              case sizeof(uint32_t):
                in_row[col.second.index] =
                    SValue(SValue::BoolType(*((uint32_t*) data) > 0));
                break;
              case sizeof(uint64_t):
                in_row[col.second.index] =
                    SValue(SValue::BoolType(*((uint64_t*) data) > 0));
                break;
              case 0:
                in_row[col.second.index] = SValue(SValue::BoolType(false));
                break;
            }
            break;

          case msg::FieldType::OBJECT:
            RAISE(kIllegalStateError);

        }
      }

      next_level = std::max(
          next_level,
          col.second.reader->nextRepetitionLevel());
    }

    fetch_level = next_level;

    if (true) { // where clause
      for (int i = 0; i < select_list_.size(); ++i) {
        if (select_list_[i].rep_level >= select_level) {
          select_list_[i].compiled->accumulate(
              &select_list_[i].instance,
              in_row.size(),
              in_row.data());
        }
      }

      switch (aggr_strategy_) {

        case AggregationStrategy::AGGREGATE_ALL:
          break;

        case AggregationStrategy::AGGREGATE_WITHIN_RECORD:
          if (next_level != 0) {
            break;
          }
          /* fallthrough */

        case AggregationStrategy::NO_AGGREGATION:
          for (int i = 0; i < select_list_.size(); ++i) {
            select_list_[i].compiled->evaluate(
                in_row.size(),
                in_row.data(),
                &out_row[i]);
          }

          if (!fn(out_row.size(), out_row.data())) {
            return;
          }

          break;

      }

      select_level = fetch_level;
    } else {
      select_level = std::min(select_level, fetch_level);
    }
  }

  switch (aggr_strategy_) {
    case AggregationStrategy::AGGREGATE_ALL:
      for (int i = 0; i < select_list_.size(); ++i) {
        select_list_[i].compiled->result(
            &select_list_[i].instance,
            &out_row[i]);

        select_list_[i].compiled->reset(&select_list_[i].instance);
      }

      fn(out_row.size(), out_row.data());
      break;

    default:
      break;

  }
}

void CSTableScan::findColumns(
    RefPtr<ScalarExpressionNode> expr,
    Set<String>* column_names) const {
  auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    column_names->emplace(fieldref->fieldName());
  }

  for (const auto& e : expr->arguments()) {
    findColumns(e, column_names);
  }
}

void CSTableScan::resolveColumns(RefPtr<ScalarExpressionNode> expr) const {
  auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    auto col = columns_.find(fieldref->fieldName());
    if (col == columns_.end()) {
      RAISE(kIllegalStateError);
    }

    fieldref->setColumnIndex(col->second.index);
  }

  for (const auto& e : expr->arguments()) {
    resolveColumns(e);
  }
}

uint64_t CSTableScan::findMaxRepetitionLevel(
    RefPtr<ScalarExpressionNode> expr) const {
  uint64_t max_level = 0;

  auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    auto col = columns_.find(fieldref->fieldName());
    if (col == columns_.end()) {
      RAISE(kIllegalStateError);
    }

    auto col_level = col->second.reader->maxRepetitionLevel();
    if (col_level > max_level) {
      max_level = col_level;
    }
  }

  for (const auto& e : expr->arguments()) {
    auto e_level = findMaxRepetitionLevel(e);
    if (e_level > max_level) {
      max_level = e_level;
    }
  }

  return max_level;
}

CSTableScan::ColumnRef::ColumnRef(
    RefPtr<cstable::ColumnReader> r,
    size_t i) :
    reader(r),
    index(i) {}

CSTableScan::ExpressionRef::ExpressionRef(
    size_t _rep_level,
    ScopedPtr<ScalarExpression> _compiled,
    ScratchMemory* smem) :
    rep_level(_rep_level),
    compiled(std::move(_compiled)),
    instance(compiled->allocInstance(smem)) {}

CSTableScan::ExpressionRef::ExpressionRef(
    ExpressionRef&& other) :
    rep_level(other.rep_level),
    compiled(std::move(other.compiled)),
    instance(other.instance) {
  other.instance.scratch = nullptr;
}

CSTableScan::ExpressionRef::~ExpressionRef() {
  if (instance.scratch) {
    compiled->freeInstance(&instance);
  }
}

} // namespace csql
<|endoftext|>


<commit_before>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. 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 <chartsql/CSTableScan.h>
#include <chartsql/qtree/FieldReferenceNode.h>
#include <chartsql/runtime/defaultruntime.h>
#include <chartsql/runtime/compile.h>
#include <fnord/inspect.h>

using namespace fnord;

namespace csql {

CSTableScan::CSTableScan(
    RefPtr<SelectProjectAggregateNode> stmt,
    cstable::CSTableReader&& cstable) :
    cstable_(std::move(cstable)),
    colindex_(0) {

  Set<String> column_names;
  for (const auto& expr : stmt->selectList()) {
    findColumns(expr, &column_names);
  }

  for (const auto& col : column_names) {
    columns_.emplace(col, ColumnRef(cstable_.getColumnReader(col), colindex_++));
  }

  for (auto& expr : stmt->selectList()) {
    resolveColumns(expr);
  }

  //fnord::iputs("all cols: $0", column_names);

  DefaultRuntime runtime;

  for (const auto& expr : stmt->selectList()) {
    select_list_.emplace_back(
        findMaxRepetitionLevel(expr),
        runtime.compiler()->compile(expr),
        &scratch_);
  }
}

void CSTableScan::execute(Function<bool (int argc, const SValue* argv)> fn) {
  uint64_t select_level = 0;
  uint64_t fetch_level = 0;

  Vector<SValue> in_row(colindex_, SValue{});
  Vector<SValue> out_row(select_list_.size(), SValue{});

  size_t num_records = 0;
  size_t total_records = cstable_.numRecords();
  while (num_records < total_records) {
    uint64_t next_level = 0;

    if (fetch_level == 0) {
      ++num_records;
    }

    for (auto& col : columns_) {
      if (col.second.reader->nextRepetitionLevel() >= fetch_level) {
        uint64_t r;
        uint64_t d;
        void* data;
        size_t size;
        col.second.reader->next(&r, &d, &data, &size);
        in_row[col.second.index] = SValue("fnord");
      }

      next_level = std::max(next_level, col.second.reader->nextRepetitionLevel());
    }

    fetch_level = next_level;

    if (true) { // where clause
      for (int i = 0; i < select_list_.size(); ++i) {
        if (select_list_[i].rep_level >= select_level) {
          //select_level_[i].compiled.accumulate();
        }
      }

      for (int i = 0; i < select_list_.size(); ++i) {
        select_list_[i].compiled->evaluate(
            &select_list_[i].instance,
            in_row.size(),
            in_row.data(),
            &out_row[i]);
      }

      if (!fn(out_row.size(), out_row.data())) {
        return;
      }

      select_level = fetch_level;
    } else {
      select_level = std::min(select_level, fetch_level);
    }
  }
}

void CSTableScan::findColumns(
    RefPtr<ScalarExpressionNode> expr,
    Set<String>* column_names) const {
  auto fieldref = dynamic_cast<FieldReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    column_names->emplace(fieldref->fieldName());
  }

  for (const auto& e : expr->arguments()) {
    findColumns(e, column_names);
  }
}

void CSTableScan::resolveColumns(RefPtr<ScalarExpressionNode> expr) const {
  auto fieldref = dynamic_cast<FieldReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    auto col = columns_.find(fieldref->fieldName());
    if (col == columns_.end()) {
      RAISE(kIllegalStateError);
    }

    fieldref->setColumnIndex(col->second.index);
  }

  for (const auto& e : expr->arguments()) {
    resolveColumns(e);
  }
}

uint64_t CSTableScan::findMaxRepetitionLevel(
    RefPtr<ScalarExpressionNode> expr) const {
  uint64_t max_level = 0;

  auto fieldref = dynamic_cast<FieldReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    auto col = columns_.find(fieldref->fieldName());
    if (col == columns_.end()) {
      RAISE(kIllegalStateError);
    }

    auto col_level = col->second.reader->maxRepetitionLevel();
    if (col_level > max_level) {
      max_level = col_level;
    }
  }

  for (const auto& e : expr->arguments()) {
    auto e_level = findMaxRepetitionLevel(e);
    if (e_level > max_level) {
      max_level = e_level;
    }
  }

  return max_level;
}

CSTableScan::ColumnRef::ColumnRef(
    RefPtr<cstable::ColumnReader> r,
    size_t i) :
    reader(r),
    index(i) {}

CSTableScan::ExpressionRef::ExpressionRef(
    size_t _rep_level,
    ScopedPtr<CompiledProgram> _compiled,
    ScratchMemory* smem) :
    rep_level(_rep_level),
    compiled(std::move(_compiled)),
    instance(compiled->allocInstance(smem)) {}

CSTableScan::ExpressionRef::ExpressionRef(
    ExpressionRef&& other) :
    rep_level(other.rep_level),
    compiled(std::move(other.compiled)),
    instance(other.instance) {
  other.instance.scratch = nullptr;
}

CSTableScan::ExpressionRef::~ExpressionRef() {
  if (instance.scratch) {
    compiled->freeInstance(&instance);
  }
}

} // namespace csql
<commit_msg>encode SValues in CSTableScan<commit_after>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. 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 <chartsql/CSTableScan.h>
#include <chartsql/qtree/FieldReferenceNode.h>
#include <chartsql/runtime/defaultruntime.h>
#include <chartsql/runtime/compile.h>
#include <fnord/inspect.h>

using namespace fnord;

namespace csql {

CSTableScan::CSTableScan(
    RefPtr<SelectProjectAggregateNode> stmt,
    cstable::CSTableReader&& cstable) :
    cstable_(std::move(cstable)),
    colindex_(0) {

  Set<String> column_names;
  for (const auto& expr : stmt->selectList()) {
    findColumns(expr, &column_names);
  }

  for (const auto& col : column_names) {
    columns_.emplace(col, ColumnRef(cstable_.getColumnReader(col), colindex_++));
  }

  for (auto& expr : stmt->selectList()) {
    resolveColumns(expr);
  }

  //fnord::iputs("all cols: $0", column_names);

  DefaultRuntime runtime;

  for (const auto& expr : stmt->selectList()) {
    select_list_.emplace_back(
        findMaxRepetitionLevel(expr),
        runtime.compiler()->compile(expr),
        &scratch_);
  }
}

void CSTableScan::execute(Function<bool (int argc, const SValue* argv)> fn) {
  uint64_t select_level = 0;
  uint64_t fetch_level = 0;

  Vector<SValue> in_row(colindex_, SValue{});
  Vector<SValue> out_row(select_list_.size(), SValue{});

  size_t num_records = 0;
  size_t total_records = cstable_.numRecords();
  while (num_records < total_records) {
    uint64_t next_level = 0;

    if (fetch_level == 0) {
      ++num_records;
    }

    for (auto& col : columns_) {
      if (col.second.reader->nextRepetitionLevel() >= fetch_level) {
        auto& reader = col.second.reader;

        uint64_t r;
        uint64_t d;
        void* data;
        size_t size;
        reader->next(&r, &d, &data, &size);

        switch (col.second.reader->type()) {

          case msg::FieldType::STRING:
            in_row[col.second.index] =
                SValue(SValue::StringType((char*) data, size));
            break;

          case msg::FieldType::UINT32:
          case msg::FieldType::UINT64:
            switch (size) {
              case sizeof(uint32_t):
                in_row[col.second.index] =
                    SValue(SValue::IntegerType(*((uint32_t*) data)));
                break;
              case sizeof(uint64_t):
                in_row[col.second.index] =
                    SValue(SValue::IntegerType(*((uint64_t*) data)));
                break;
              case 0:
                in_row[col.second.index] = SValue(SValue::IntegerType(0));
                break;
            }
            break;

          case msg::FieldType::BOOLEAN:
            switch (size) {
              case sizeof(uint32_t):
                in_row[col.second.index] =
                    SValue(SValue::BoolType(*((uint32_t*) data) > 0));
                break;
              case sizeof(uint64_t):
                in_row[col.second.index] =
                    SValue(SValue::BoolType(*((uint64_t*) data) > 0));
                break;
              case 0:
                in_row[col.second.index] = SValue(SValue::BoolType(false));
                break;
            }
            break;

          case msg::FieldType::OBJECT:
            RAISE(kIllegalStateError);

        }

      }

      next_level = std::max(next_level, col.second.reader->nextRepetitionLevel());
    }

    fetch_level = next_level;

    if (true) { // where clause
      for (int i = 0; i < select_list_.size(); ++i) {
        if (select_list_[i].rep_level >= select_level) {
          //select_level_[i].compiled.accumulate();
        }
      }

      for (int i = 0; i < select_list_.size(); ++i) {
        select_list_[i].compiled->evaluate(
            &select_list_[i].instance,
            in_row.size(),
            in_row.data(),
            &out_row[i]);
      }

      if (!fn(out_row.size(), out_row.data())) {
        return;
      }

      select_level = fetch_level;
    } else {
      select_level = std::min(select_level, fetch_level);
    }
  }
}

void CSTableScan::findColumns(
    RefPtr<ScalarExpressionNode> expr,
    Set<String>* column_names) const {
  auto fieldref = dynamic_cast<FieldReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    column_names->emplace(fieldref->fieldName());
  }

  for (const auto& e : expr->arguments()) {
    findColumns(e, column_names);
  }
}

void CSTableScan::resolveColumns(RefPtr<ScalarExpressionNode> expr) const {
  auto fieldref = dynamic_cast<FieldReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    auto col = columns_.find(fieldref->fieldName());
    if (col == columns_.end()) {
      RAISE(kIllegalStateError);
    }

    fieldref->setColumnIndex(col->second.index);
  }

  for (const auto& e : expr->arguments()) {
    resolveColumns(e);
  }
}

uint64_t CSTableScan::findMaxRepetitionLevel(
    RefPtr<ScalarExpressionNode> expr) const {
  uint64_t max_level = 0;

  auto fieldref = dynamic_cast<FieldReferenceNode*>(expr.get());
  if (fieldref != nullptr) {
    auto col = columns_.find(fieldref->fieldName());
    if (col == columns_.end()) {
      RAISE(kIllegalStateError);
    }

    auto col_level = col->second.reader->maxRepetitionLevel();
    if (col_level > max_level) {
      max_level = col_level;
    }
  }

  for (const auto& e : expr->arguments()) {
    auto e_level = findMaxRepetitionLevel(e);
    if (e_level > max_level) {
      max_level = e_level;
    }
  }

  return max_level;
}

CSTableScan::ColumnRef::ColumnRef(
    RefPtr<cstable::ColumnReader> r,
    size_t i) :
    reader(r),
    index(i) {}

CSTableScan::ExpressionRef::ExpressionRef(
    size_t _rep_level,
    ScopedPtr<CompiledProgram> _compiled,
    ScratchMemory* smem) :
    rep_level(_rep_level),
    compiled(std::move(_compiled)),
    instance(compiled->allocInstance(smem)) {}

CSTableScan::ExpressionRef::ExpressionRef(
    ExpressionRef&& other) :
    rep_level(other.rep_level),
    compiled(std::move(other.compiled)),
    instance(other.instance) {
  other.instance.scratch = nullptr;
}

CSTableScan::ExpressionRef::~ExpressionRef() {
  if (instance.scratch) {
    compiled->freeInstance(&instance);
  }
}

} // namespace csql
<|endoftext|>


<commit_before>/********** tell emacs we use -*- c++ -*- style comments *******************
 $Revision: 1.2 $  $Author: trey $  $Date: 2006-04-27 23:19:14 $

 @file    zmdpSolve.cc
 @brief   No brief

 Copyright (c) 2002-2006, Trey Smith.  All rights reserved.

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

 * The software may not be sold or incorporated into a commercial
   product without specific prior written permission.
 * 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 <assert.h>
#include <sys/time.h>
#include <getopt.h>

#include <iostream>
#include <fstream>

#include "zmdpCommonTime.h"
#include "solverUtils.h"

using namespace std;
using namespace MatrixUtils;
using namespace zmdp;

struct OutputParams {
  const char* outFileName;
  double timeoutSeconds;

  OutputParams(void);
};

OutputParams::OutputParams(void) {
  outFileName = "out.policy";
  timeoutSeconds = -1;
}

bool userTerminatedG = false;

void doSolve(const SolverParams& p, const OutputParams& op)
{
  StopWatch run;
  init_matrix_utils();

  printf("%05d reading model file and allocating data structures\n",
	 (int) run.elapsedTime());
  SolverObjects so;
  constructSolverObjects(so, p);

  if (!so.bounds->getSupportsPolicyOutput()) {
    cerr << "ERROR: with selected options, policy output is not supported:" << endl;
    cerr << "  try adding '-v convex' and '--lower-bound' options" << endl;
    exit(EXIT_FAILURE);
  }

  // initialize the solver
  printf("%05d calculating initial heuristics\n",
	 (int) run.elapsedTime());
  so.solver->planInit(so.sim->getModel(), p.targetPrecision);
  printf("%05d finished initialization, beginning to improve policy\n",
	 (int) run.elapsedTime());

  double lastPrintTime = -1000;
  bool reachedTargetPrecision = false;
  bool reachedTimeout = false;
  int numSolverCalls = 0;
  while (!(reachedTargetPrecision || reachedTimeout || userTerminatedG)) {
    // make a call to the solver
    reachedTargetPrecision =
      so.solver->planFixedTime(so.sim->getModel()->getInitialState(),
			       /* maxTime = */ -1, p.targetPrecision);
    numSolverCalls++;

    // check timeout
    double elapsed = run.elapsedTime();
    if (op.timeoutSeconds > 0 && elapsed >= op.timeoutSeconds) {
      reachedTimeout = true;
    }

    // print a progress update every 10 seconds
    if ((elapsed - lastPrintTime > 10)
	|| reachedTargetPrecision || reachedTimeout || userTerminatedG) {
      ValueInterval intv = so.solver->getValueAt(so.sim->getModel()->getInitialState());
      printf("%05d %6d calls to solver, bounds [%8.4f .. %8.4f], precision %g\n",
	     (int) elapsed, numSolverCalls, intv.l, intv.u, (intv.u - intv.l));
      lastPrintTime = elapsed;
    }
  }

  // say why the run ended
  if (reachedTargetPrecision) {
    printf("%05d terminating run; reached target precision of %g\n",
	   (int) run.elapsedTime(), p.targetPrecision);
  } else if (reachedTimeout) {
    printf("%05d terminating run; passed specified timeout of %g seconds\n",
	   (int) run.elapsedTime(), op.timeoutSeconds);
  } else {
    printf("%05d terminating run; caught SIGINT from user\n",
	   (int) run.elapsedTime());
  }

  // write out a policy
  printf("%05d writing policy to '%s'\n", (int) run.elapsedTime(), op.outFileName);
  so.bounds->writePolicy(op.outFileName);

  printf("%05d done\n", (int) run.elapsedTime());
}

void usage(const char* cmdName) {
  cerr <<
    "usage: " << cmdName << " OPTIONS <model>\n"
    "  -h or --help           Print this help\n"
    "  --version              Print version information (CFLAGS used at compilation)\n"
    "\n"
    "Solver options:\n"
    "  -s or --search         Specifies search strategy. Valid choices:\n"
    "                           rtdp, lrtdp, hdp, hsvi, frtdp [default: frtdp]\n"
    "  -t or --type           Specifies problem type. Valid choices:\n"
    "                           racetrack, pomdp [default: infer from model filename]\n"
    "  -v or --value          Specifies value function representation. Valid choices\n"
    "                         depend on problem type. With -t pomdp, choices are:\n"
    "                           point, convex [default: convex]\n"
    "                         For other problem types, choices are:\n"
    "                           point [default: point]\n"
    "  -f or --fast           Use fast (but very picky) alternate POMDP parser\n"
    "  -p or --precision      Set target precision in solution quality; run ends when\n"
    "                           target is reached [default: 1e-3]\n"
    "  --weak-heuristic       Avoid spending time generating a good upper bound heuristic\n"
    "                           (only valid for some problems, interpretation depends on\n"
    "                            the problem; e.g. sets h_U = 0 for racetrack)\n"
    "  --lower-bound          Forces zmdpSolve to maintain a lower bound and use it for\n"
    "                           action selection, even if it is not used during search.\n"
    "  --upper-bound          Forces zmdpSolve to use the upper bound for action selection\n"
    "                           (normally the lower bound is used if it is available).\n"
    "\n"
    "Policy output options:\n"
    "  -o or --output         Specifies name of policy output file [default: 'out.policy']\n"
    "  --timeout              Specifies a timeout in seconds.  If running time exceeds\n"
    "                           the specified value, zmdpSolve writes out a policy\n"
    "                           and terminates [default: no maximum]\n"
    "\n"
    "Examples:\n"
    "  " << cmdName << " RockSample_4_4.pomdp\n"
    "  " << cmdName << " large-b.racetrack\n"
    "  " << cmdName << " --timeout 60 --output my.policy RockSample_4_4.pomdp\n"
    "  " << cmdName << " --search lrtdp --value point RockSample_4_4.pomdp\n"
    "  " << cmdName << " -f RockSample_5_7.pomdp\n"
    "\n"
;
  exit(-1);
}

int main(int argc, char **argv) {
  static char shortOptions[] = "hs:t:v:fo:";
  static struct option longOptions[]={
    {"help",          0,NULL,'h'},
    {"version",       0,NULL,'V'},
    {"search",        1,NULL,'s'},
    {"type",          1,NULL,'t'},
    {"value",         1,NULL,'v'},
    {"fast",          0,NULL,'f'},
    {"precision",     1,NULL,'p'},
    {"weak-heuristic",0,NULL,'W'},
    {"lower-bound",   0,NULL,'L'},
    {"upper-bound",   0,NULL,'U'},
    {"output",        1,NULL,'o'},
    {"timeout",       1,NULL,'T'},
    {NULL,0,0,0}
  };

  SolverParams p;
  OutputParams op;

#if USE_DEBUG_PRINT
  // save arguments for debug printout later
  ostringstream outs;
  for (int i=1; i < argc; i++) {
    outs << argv[i] << " ";
  }
#endif

  p.cmdName = argv[0];
  while (1) {
    char optchar = getopt_long(argc,argv,shortOptions,longOptions,NULL);
    if (optchar == -1) break;

    switch (optchar) {
    case 'h': // help
      usage(argv[0]);
      break;
    case 'V': // version
      cout << "CFLAGS = " << CFLAGS << endl;
      exit(EXIT_SUCCESS);
      break;
    case 's': // search
      p.setStrategy(optarg);
      break;
    case 't': // type
      p.setProbType(optarg);
      break;
    case 'v': // value
      p.setValueRepr(optarg);
      break;
    case 'f': // fast
      p.useFastParser = true;
      break;
    case 'p': // precision
      p.targetPrecision = atof(optarg);
      break;
    case 'W': // weak-heuristic
      p.useHeuristic = false;
      break;
    case 'L': // lower-bound
      p.forceLowerBound = true;
      break;
    case 'U': // upper-bound
      p.forceUpperBoundActionSelection = true;
      break;
    case 'o': // output
      op.outFileName = optarg;
      break;
    case 'T': // timeout
      op.timeoutSeconds = atof(optarg);
      break;

    case '?': // unknown option
    case ':': // option with missing parameter
      // getopt() prints an informative error message
      cerr << endl;
      usage(argv[0]);
      break;
    default:
      abort(); // never reach this point
    }
  }
  if (argc-optind != 1) {
    cerr << "ERROR: wrong number of arguments (should be 1)" << endl << endl;
    usage(argv[0]);
  }

  p.probName = argv[optind++];
  p.inferMissingValues();

#if USE_DEBUG_PRINT
  printf("CFLAGS = %s\n", CFLAGS);
  printf("ARGS = %s\n", outs.str().c_str());
  fflush(stdout);
#endif

  doSolve(p, op);

  return 0;
}

/***************************************************************************
 * REVISION HISTORY:
 * $Log: not supported by cvs2svn $
 * Revision 1.1  2006/04/27 23:07:24  trey
 * initial check-in
 *
 *
 ***************************************************************************/
<commit_msg>improved error diagnostic for policy output<commit_after>/********** tell emacs we use -*- c++ -*- style comments *******************
 $Revision: 1.3 $  $Author: trey $  $Date: 2006-04-27 23:42:54 $

 @file    zmdpSolve.cc
 @brief   No brief

 Copyright (c) 2002-2006, Trey Smith.  All rights reserved.

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

 * The software may not be sold or incorporated into a commercial
   product without specific prior written permission.
 * 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 <assert.h>
#include <sys/time.h>
#include <getopt.h>

#include <iostream>
#include <fstream>

#include "zmdpCommonTime.h"
#include "solverUtils.h"

using namespace std;
using namespace MatrixUtils;
using namespace zmdp;

struct OutputParams {
  const char* outFileName;
  double timeoutSeconds;

  OutputParams(void);
};

OutputParams::OutputParams(void) {
  outFileName = "out.policy";
  timeoutSeconds = -1;
}

bool userTerminatedG = false;

void doSolve(const SolverParams& p, const OutputParams& op)
{
  StopWatch run;
  init_matrix_utils();

  printf("%05d reading model file and allocating data structures\n",
	 (int) run.elapsedTime());
  SolverObjects so;
  constructSolverObjects(so, p);

  if (!so.bounds->getSupportsPolicyOutput()) {
    cerr << "ERROR: with selected options, policy output is not supported:" << endl;
    cerr << "  in order to enable policy output, problem must be a POMDP; if" << endl;
    cout << "  it is, try adding the '-v convex' and '--lower-bound' options" << endl;
    exit(EXIT_FAILURE);
  }

  // initialize the solver
  printf("%05d calculating initial heuristics\n",
	 (int) run.elapsedTime());
  so.solver->planInit(so.sim->getModel(), p.targetPrecision);
  printf("%05d finished initialization, beginning to improve policy\n",
	 (int) run.elapsedTime());

  double lastPrintTime = -1000;
  bool reachedTargetPrecision = false;
  bool reachedTimeout = false;
  int numSolverCalls = 0;
  while (!(reachedTargetPrecision || reachedTimeout || userTerminatedG)) {
    // make a call to the solver
    reachedTargetPrecision =
      so.solver->planFixedTime(so.sim->getModel()->getInitialState(),
			       /* maxTime = */ -1, p.targetPrecision);
    numSolverCalls++;

    // check timeout
    double elapsed = run.elapsedTime();
    if (op.timeoutSeconds > 0 && elapsed >= op.timeoutSeconds) {
      reachedTimeout = true;
    }

    // print a progress update every 10 seconds
    if ((elapsed - lastPrintTime > 10)
	|| reachedTargetPrecision || reachedTimeout || userTerminatedG) {
      ValueInterval intv = so.solver->getValueAt(so.sim->getModel()->getInitialState());
      printf("%05d %6d calls to solver, bounds [%8.4f .. %8.4f], precision %g\n",
	     (int) elapsed, numSolverCalls, intv.l, intv.u, (intv.u - intv.l));
      lastPrintTime = elapsed;
    }
  }

  // say why the run ended
  if (reachedTargetPrecision) {
    printf("%05d terminating run; reached target precision of %g\n",
	   (int) run.elapsedTime(), p.targetPrecision);
  } else if (reachedTimeout) {
    printf("%05d terminating run; passed specified timeout of %g seconds\n",
	   (int) run.elapsedTime(), op.timeoutSeconds);
  } else {
    printf("%05d terminating run; caught SIGINT from user\n",
	   (int) run.elapsedTime());
  }

  // write out a policy
  printf("%05d writing policy to '%s'\n", (int) run.elapsedTime(), op.outFileName);
  so.bounds->writePolicy(op.outFileName);

  printf("%05d done\n", (int) run.elapsedTime());
}

void usage(const char* cmdName) {
  cerr <<
    "usage: " << cmdName << " OPTIONS <model>\n"
    "  -h or --help           Print this help\n"
    "  --version              Print version information (CFLAGS used at compilation)\n"
    "\n"
    "Solver options:\n"
    "  -s or --search         Specifies search strategy. Valid choices:\n"
    "                           rtdp, lrtdp, hdp, hsvi, frtdp [default: frtdp]\n"
    "  -t or --type           Specifies problem type. Valid choices:\n"
    "                           racetrack, pomdp [default: infer from model filename]\n"
    "  -v or --value          Specifies value function representation. Valid choices\n"
    "                         depend on problem type. With -t pomdp, choices are:\n"
    "                           point, convex [default: convex]\n"
    "                         For other problem types, choices are:\n"
    "                           point [default: point]\n"
    "  -f or --fast           Use fast (but very picky) alternate POMDP parser\n"
    "  -p or --precision      Set target precision in solution quality; run ends when\n"
    "                           target is reached [default: 1e-3]\n"
    "  --weak-heuristic       Avoid spending time generating a good upper bound heuristic\n"
    "                           (only valid for some problems, interpretation depends on\n"
    "                            the problem; e.g. sets h_U = 0 for racetrack)\n"
    "  --lower-bound          Forces zmdpSolve to maintain a lower bound and use it for\n"
    "                           action selection, even if it is not used during search.\n"
    "  --upper-bound          Forces zmdpSolve to use the upper bound for action selection\n"
    "                           (normally the lower bound is used if it is available).\n"
    "\n"
    "Policy output options:\n"
    "  -o or --output         Specifies name of policy output file [default: 'out.policy']\n"
    "  --timeout              Specifies a timeout in seconds.  If running time exceeds\n"
    "                           the specified value, zmdpSolve writes out a policy\n"
    "                           and terminates [default: no maximum]\n"
    "\n"
    "Examples:\n"
    "  " << cmdName << " RockSample_4_4.pomdp\n"
    "  " << cmdName << " large-b.racetrack\n"
    "  " << cmdName << " --timeout 60 --output my.policy RockSample_4_4.pomdp\n"
    "  " << cmdName << " --search lrtdp --value point RockSample_4_4.pomdp\n"
    "  " << cmdName << " -f RockSample_5_7.pomdp\n"
    "\n"
;
  exit(-1);
}

int main(int argc, char **argv) {
  static char shortOptions[] = "hs:t:v:fo:";
  static struct option longOptions[]={
    {"help",          0,NULL,'h'},
    {"version",       0,NULL,'V'},
    {"search",        1,NULL,'s'},
    {"type",          1,NULL,'t'},
    {"value",         1,NULL,'v'},
    {"fast",          0,NULL,'f'},
    {"precision",     1,NULL,'p'},
    {"weak-heuristic",0,NULL,'W'},
    {"lower-bound",   0,NULL,'L'},
    {"upper-bound",   0,NULL,'U'},
    {"output",        1,NULL,'o'},
    {"timeout",       1,NULL,'T'},
    {NULL,0,0,0}
  };

  SolverParams p;
  OutputParams op;

#if USE_DEBUG_PRINT
  // save arguments for debug printout later
  ostringstream outs;
  for (int i=1; i < argc; i++) {
    outs << argv[i] << " ";
  }
#endif

  p.cmdName = argv[0];
  while (1) {
    char optchar = getopt_long(argc,argv,shortOptions,longOptions,NULL);
    if (optchar == -1) break;

    switch (optchar) {
    case 'h': // help
      usage(argv[0]);
      break;
    case 'V': // version
      cout << "CFLAGS = " << CFLAGS << endl;
      exit(EXIT_SUCCESS);
      break;
    case 's': // search
      p.setStrategy(optarg);
      break;
    case 't': // type
      p.setProbType(optarg);
      break;
    case 'v': // value
      p.setValueRepr(optarg);
      break;
    case 'f': // fast
      p.useFastParser = true;
      break;
    case 'p': // precision
      p.targetPrecision = atof(optarg);
      break;
    case 'W': // weak-heuristic
      p.useHeuristic = false;
      break;
    case 'L': // lower-bound
      p.forceLowerBound = true;
      break;
    case 'U': // upper-bound
      p.forceUpperBoundActionSelection = true;
      break;
    case 'o': // output
      op.outFileName = optarg;
      break;
    case 'T': // timeout
      op.timeoutSeconds = atof(optarg);
      break;

    case '?': // unknown option
    case ':': // option with missing parameter
      // getopt() prints an informative error message
      cerr << endl;
      usage(argv[0]);
      break;
    default:
      abort(); // never reach this point
    }
  }
  if (argc-optind != 1) {
    cerr << "ERROR: wrong number of arguments (should be 1)" << endl << endl;
    usage(argv[0]);
  }

  p.probName = argv[optind++];
  p.inferMissingValues();

#if USE_DEBUG_PRINT
  printf("CFLAGS = %s\n", CFLAGS);
  printf("ARGS = %s\n", outs.str().c_str());
  fflush(stdout);
#endif

  doSolve(p, op);

  return 0;
}

/***************************************************************************
 * REVISION HISTORY:
 * $Log: not supported by cvs2svn $
 * Revision 1.2  2006/04/27 23:19:14  trey
 * removed unnecessary #include of Interleave.h
 *
 * Revision 1.1  2006/04/27 23:07:24  trey
 * initial check-in
 *
 *
 ***************************************************************************/
<|endoftext|>


<commit_before>
#include "../Flare.h"
#include "FlareGame.h"
#include "FlareDebrisField.h"
#include "FlareSimulatedSector.h"

#include "StaticMeshResources.h"

#define LOCTEXT_NAMESPACE "FlareDebrisField"

/*----------------------------------------------------
	Constructor
----------------------------------------------------*/

UFlareDebrisField::UFlareDebrisField(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	CurrentGenerationIndex = 0;
}

void UFlareDebrisField::Setup(AFlareGame* GameMode, UFlareSimulatedSector* Sector)
{
	check(Sector);
	check(GameMode);

	// Get debris field parameters
	Game = GameMode;
	const FFlareDebrisFieldInfo* DebrisFieldInfo = &Sector->GetDescription()->DebrisFieldInfo;
	UFlareAsteroidCatalog* DebrisFieldMeshes = DebrisFieldInfo->DebrisCatalog;
	TArray<AStaticMeshActor*> NewDebris;

	// Add debris
	if (DebrisFieldInfo)
	{
		float SectorScale = 5000 * 100;
		int32 DebrisCount = 100 * DebrisFieldInfo->DebrisFieldDensity;
		FLOGV("UFlareDebrisField::Setup : spawning debris field : gen %d, size = %d, icy = %d", CurrentGenerationIndex, DebrisCount, Sector->GetDescription()->IsIcy);

		for (int32 Index = 0; Index < DebrisCount; Index++)
		{
			int32 DebrisIndex = FMath::RandRange(0, DebrisFieldMeshes->Asteroids.Num() - 1);

			float MinSize = DebrisFieldInfo->MinDebrisSize;
			float MaxSize = DebrisFieldInfo->MaxDebrisSize;
			float Size = FMath::FRandRange(MinSize, MaxSize);

			FName Name = FName(*(FString::Printf(TEXT("DebrisGen%dIndex%d"), CurrentGenerationIndex, Index)));

			NewDebris.Add(AddDebris(Sector, DebrisFieldMeshes->Asteroids[DebrisIndex], Size, SectorScale, Name));
		}
	}

	// Remember new debris
	DebrisField.Empty();
	for (int DebrisIndex = 0; DebrisIndex < NewDebris.Num(); DebrisIndex++)
	{
		if (NewDebris[DebrisIndex])
		{
			DebrisField.Add(NewDebris[DebrisIndex]);
		}
	}

	CurrentGenerationIndex++;
	FLOGV("UFlareDebrisField::Setup : done spawning debris field, size = %d", DebrisField.Num());
}

void UFlareDebrisField::Reset()
{
	FLOGV("UFlareDebrisField::Reset : clearing debris field, size = %d", DebrisField.Num());
	for (int i = 0; i < DebrisField.Num(); i++)
	{
		Game->GetWorld()->DestroyActor(DebrisField[i]);
	}
	DebrisField.Empty();
}

void UFlareDebrisField::SetWorldPause(bool Pause)
{
	for (int i = 0; i < DebrisField.Num(); i++)
	{
		DebrisField[i]->SetActorHiddenInGame(Pause);
		DebrisField[i]->CustomTimeDilation = (Pause ? 0.f : 1.0);
		Cast<UPrimitiveComponent>(DebrisField[i]->GetRootComponent())->SetSimulatePhysics(!Pause);
	}
}

/*----------------------------------------------------
	Internals
----------------------------------------------------*/

AStaticMeshActor* UFlareDebrisField::AddDebris(UFlareSimulatedSector* Sector, UStaticMesh* Mesh, float Size, float SectorScale, FName Name)
{
	FActorSpawnParameters Params;
	Params.Name = Name;
	Params.Owner = Game;
	Params.bNoFail = false;
	Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::DontSpawnIfColliding;

	// Compute size, location and rotation
	FVector Location = FMath::VRand() * SectorScale * FMath::FRandRange(0.2, 1.0);
	FRotator Rotation = FRotator(FMath::FRandRange(0, 360), FMath::FRandRange(0, 360), FMath::FRandRange(0, 360));

	// Spawn
	AStaticMeshActor* DebrisMesh = Game->GetWorld()->SpawnActor<AStaticMeshActor>(AStaticMeshActor::StaticClass(), Location, Rotation, Params);
	if (DebrisMesh)
	{
		DebrisMesh->SetMobility(EComponentMobility::Movable);
		DebrisMesh->SetActorScale3D(Size * FVector(1, 1, 1));
		DebrisMesh->SetActorEnableCollision(true);

		// Setup
		UStaticMeshComponent* DebrisComponent = DebrisMesh->GetStaticMeshComponent();
		if (DebrisComponent)
		{
			DebrisComponent->SetStaticMesh(Mesh);
			DebrisComponent->SetSimulatePhysics(true);
			DebrisComponent->SetCollisionProfileName("BlockAllDynamic");

			// Set material
			UMaterialInstanceDynamic* DebrisMaterial = UMaterialInstanceDynamic::Create(DebrisComponent->GetMaterial(0), DebrisComponent->GetWorld());
			if (DebrisMaterial)
			{
				DebrisComponent->SetMaterial(0, DebrisMaterial);
				DebrisMaterial->SetScalarParameterValue("IceMask", Sector->GetDescription()->IsIcy);
				FLOGV("UFlareDebrisField::AddDebris : updated icy set %d", Sector->GetDescription()->IsIcy);
			}
			else
			{
				FLOG("UFlareDebrisField::AddDebris : failed to set material (no material or mesh)")
			}
		}
	}
	else
	{
		FLOG("UFlareDebrisField::AddDebris : failed to spawn debris")
	}

	return DebrisMesh;
}

#undef LOCTEXT_NAMESPACE
<commit_msg>Removed spamming logs<commit_after>
#include "../Flare.h"
#include "FlareGame.h"
#include "FlareDebrisField.h"
#include "FlareSimulatedSector.h"

#include "StaticMeshResources.h"

#define LOCTEXT_NAMESPACE "FlareDebrisField"

/*----------------------------------------------------
	Constructor
----------------------------------------------------*/

UFlareDebrisField::UFlareDebrisField(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	CurrentGenerationIndex = 0;
}

void UFlareDebrisField::Setup(AFlareGame* GameMode, UFlareSimulatedSector* Sector)
{
	check(Sector);
	check(GameMode);

	// Get debris field parameters
	Game = GameMode;
	const FFlareDebrisFieldInfo* DebrisFieldInfo = &Sector->GetDescription()->DebrisFieldInfo;
	UFlareAsteroidCatalog* DebrisFieldMeshes = DebrisFieldInfo->DebrisCatalog;
	TArray<AStaticMeshActor*> NewDebris;

	// Add debris
	if (DebrisFieldInfo)
	{
		float SectorScale = 5000 * 100;
		int32 DebrisCount = 100 * DebrisFieldInfo->DebrisFieldDensity;
		FLOGV("UFlareDebrisField::Setup : spawning debris field : gen %d, size = %d, icy = %d", CurrentGenerationIndex, DebrisCount, Sector->GetDescription()->IsIcy);

		for (int32 Index = 0; Index < DebrisCount; Index++)
		{
			int32 DebrisIndex = FMath::RandRange(0, DebrisFieldMeshes->Asteroids.Num() - 1);

			float MinSize = DebrisFieldInfo->MinDebrisSize;
			float MaxSize = DebrisFieldInfo->MaxDebrisSize;
			float Size = FMath::FRandRange(MinSize, MaxSize);

			FName Name = FName(*(FString::Printf(TEXT("DebrisGen%dIndex%d"), CurrentGenerationIndex, Index)));

			NewDebris.Add(AddDebris(Sector, DebrisFieldMeshes->Asteroids[DebrisIndex], Size, SectorScale, Name));
		}
	}

	// Remember new debris
	DebrisField.Empty();
	for (int DebrisIndex = 0; DebrisIndex < NewDebris.Num(); DebrisIndex++)
	{
		if (NewDebris[DebrisIndex])
		{
			DebrisField.Add(NewDebris[DebrisIndex]);
		}
	}

	CurrentGenerationIndex++;
}

void UFlareDebrisField::Reset()
{
	FLOGV("UFlareDebrisField::Reset : clearing debris field, size = %d", DebrisField.Num());
	for (int i = 0; i < DebrisField.Num(); i++)
	{
		Game->GetWorld()->DestroyActor(DebrisField[i]);
	}
	DebrisField.Empty();
}

void UFlareDebrisField::SetWorldPause(bool Pause)
{
	for (int i = 0; i < DebrisField.Num(); i++)
	{
		DebrisField[i]->SetActorHiddenInGame(Pause);
		DebrisField[i]->CustomTimeDilation = (Pause ? 0.f : 1.0);
		Cast<UPrimitiveComponent>(DebrisField[i]->GetRootComponent())->SetSimulatePhysics(!Pause);
	}
}

/*----------------------------------------------------
	Internals
----------------------------------------------------*/

AStaticMeshActor* UFlareDebrisField::AddDebris(UFlareSimulatedSector* Sector, UStaticMesh* Mesh, float Size, float SectorScale, FName Name)
{
	FActorSpawnParameters Params;
	Params.Name = Name;
	Params.Owner = Game;
	Params.bNoFail = false;
	Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::DontSpawnIfColliding;

	// Compute size, location and rotation
	FVector Location = FMath::VRand() * SectorScale * FMath::FRandRange(0.2, 1.0);
	FRotator Rotation = FRotator(FMath::FRandRange(0, 360), FMath::FRandRange(0, 360), FMath::FRandRange(0, 360));

	// Spawn
	AStaticMeshActor* DebrisMesh = Game->GetWorld()->SpawnActor<AStaticMeshActor>(AStaticMeshActor::StaticClass(), Location, Rotation, Params);
	if (DebrisMesh)
	{
		DebrisMesh->SetMobility(EComponentMobility::Movable);
		DebrisMesh->SetActorScale3D(Size * FVector(1, 1, 1));
		DebrisMesh->SetActorEnableCollision(true);

		// Setup
		UStaticMeshComponent* DebrisComponent = DebrisMesh->GetStaticMeshComponent();
		if (DebrisComponent)
		{
			DebrisComponent->SetStaticMesh(Mesh);
			DebrisComponent->SetSimulatePhysics(true);
			DebrisComponent->SetCollisionProfileName("BlockAllDynamic");

			// Set material
			UMaterialInstanceDynamic* DebrisMaterial = UMaterialInstanceDynamic::Create(DebrisComponent->GetMaterial(0), DebrisComponent->GetWorld());
			if (DebrisMaterial)
			{
				DebrisComponent->SetMaterial(0, DebrisMaterial);
				DebrisMaterial->SetScalarParameterValue("IceMask", Sector->GetDescription()->IsIcy);
			}
			else
			{
				FLOG("UFlareDebrisField::AddDebris : failed to set material (no material or mesh)")
			}
		}
	}
	else
	{
		FLOG("UFlareDebrisField::AddDebris : failed to spawn debris")
	}

	return DebrisMesh;
}

#undef LOCTEXT_NAMESPACE
<|endoftext|>


<commit_before>//
//  Created by Robert Segal on 2014-04-01.
//  Copyright (c) 2016 Get Set Games Inc. All rights reserved.
//

#include "UpsightPrivatePCH.h"
#include "CallbackDevice.h"

#if PLATFORM_IOS
#import <UpsightKit/UpsightKit.h>
#endif

#if PLATFORM_IOS

@interface UUpsightComponentDelegate : NSObject <USBillboardDelegate>
-(UIViewController *)presentingViewControllerForBillboard:(id<USBillboard>)aBillboard;
@end

static UUpsightComponentDelegate* ucd;

@implementation UUpsightComponentDelegate

+(void)load
{
    if (!ucd)
    {
        ucd = [[UUpsightComponentDelegate alloc] init];
    }
}

-(id)init
{
    self = [super init];

    if (self)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(applicationDidFinishLaunching:)
                                                     name:UIApplicationDidFinishLaunchingNotification
                                                   object:nil];
    }

    return self;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

-(void)applicationDidFinishLaunching:(NSNotification *)n
{
    NSDictionary *dLaunchOptionsUrl = n.userInfo[@"UIApplicationLaunchOptionsURLKey"];

    if (!dLaunchOptionsUrl)
    {
        [USPush registerForPushNotifications];
    }
}

-(UIViewController *)presentingViewControllerForBillboard:(id<USBillboard>)aBillboard
{
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

@end

#endif

void UUpsightComponent::OnRegister()
{
	Super::OnRegister();

    FCoreDelegates::ApplicationRegisteredForRemoteNotificationsDelegate.AddUObject(this, &UUpsightComponent::ApplicationRegisteredForRemoteNotifications_Handler);
    FCoreDelegates::ApplicationRegisteredForUserNotificationsDelegate.AddUObject(this, &UUpsightComponent::ApplicationRegisteredForUserNotificationsDelegate_Handler);
    FCoreDelegates::ApplicationFailedToRegisterForRemoteNotificationsDelegate.AddUObject(this, &UUpsightComponent::ApplicationFailedToRegisterForRemoteNotifications_Handler);
    FCoreDelegates::ApplicationReceivedRemoteNotificationDelegate.AddUObject(this, &UUpsightComponent::ApplicationReceivedRemoteNotification_Handler);
}

void UUpsightComponent::OnUnregister()
{
	Super::OnUnregister();
}

void UUpsightComponent::ApplicationRegisteredForUserNotificationsDelegate_Handler(int32 inInt)
{
#if PLATFORM_IOS
    UIUserNotificationSettings *notificationSettings = (UIUserNotificationSettings *)inInt;

    [USPush didRegisterUserNotificationSettings:notificationSettings];
#endif
}

void UUpsightComponent::ApplicationRegisteredForRemoteNotifications_Handler(TArray<uint8> Token)
{
#if PLATFORM_IOS
    NSData* TokenData = [NSData dataWithBytes:Token.GetData() length:Token.Num()];

    [USPush registerPushToken:TokenData];
#endif
}

void UUpsightComponent::ApplicationFailedToRegisterForRemoteNotifications_Handler(FString RegisterError)
{
    UE_LOG(LogUpsight, Error, TEXT("ApplicationFailedToRegisterForRemoteNotifications: %s"), *RegisterError);
}

void UUpsightComponent::ApplicationReceivedRemoteNotification_Handler(FString Json)
{
#if PLATFORM_IOS
    [USPush pushBillboard].delegate = ucd;

    NSDictionary *userInfo = @{ @"message" : @"" };

    [USPush handleRemoteNotificationWithUserInfo:userInfo];
#endif

    UE_LOG(LogUpsight, Log, TEXT("ApplicationReceivedRemoteNotification: %s"), *Json);
}

<commit_msg>Correctly convert and pass int32 argument on to UIUserNotificationSettings structure require by Upsight call<commit_after>//
//  Created by Robert Segal on 2014-04-01.
//  Copyright (c) 2016 Get Set Games Inc. All rights reserved.
//

#include "UpsightPrivatePCH.h"
#include "CallbackDevice.h"

#if PLATFORM_IOS
#import <UpsightKit/UpsightKit.h>
#endif

#if PLATFORM_IOS

@interface UUpsightComponentDelegate : NSObject <USBillboardDelegate>
-(UIViewController *)presentingViewControllerForBillboard:(id<USBillboard>)aBillboard;
@end

static UUpsightComponentDelegate* ucd;

@implementation UUpsightComponentDelegate

+(void)load
{
    if (!ucd)
    {
        ucd = [[UUpsightComponentDelegate alloc] init];
    }
}

-(id)init
{
    self = [super init];

    if (self)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(applicationDidFinishLaunching:)
                                                     name:UIApplicationDidFinishLaunchingNotification
                                                   object:nil];
    }

    return self;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

-(void)applicationDidFinishLaunching:(NSNotification *)n
{
    NSDictionary *dLaunchOptionsUrl = n.userInfo[@"UIApplicationLaunchOptionsURLKey"];

    if (!dLaunchOptionsUrl)
    {
        [USPush registerForPushNotifications];
    }
}

-(UIViewController *)presentingViewControllerForBillboard:(id<USBillboard>)aBillboard
{
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

@end

#endif

void UUpsightComponent::OnRegister()
{
	Super::OnRegister();

    FCoreDelegates::ApplicationRegisteredForRemoteNotificationsDelegate.AddUObject(this, &UUpsightComponent::ApplicationRegisteredForRemoteNotifications_Handler);
    FCoreDelegates::ApplicationRegisteredForUserNotificationsDelegate.AddUObject(this, &UUpsightComponent::ApplicationRegisteredForUserNotificationsDelegate_Handler);
    FCoreDelegates::ApplicationFailedToRegisterForRemoteNotificationsDelegate.AddUObject(this, &UUpsightComponent::ApplicationFailedToRegisterForRemoteNotifications_Handler);
    FCoreDelegates::ApplicationReceivedRemoteNotificationDelegate.AddUObject(this, &UUpsightComponent::ApplicationReceivedRemoteNotification_Handler);
}

void UUpsightComponent::OnUnregister()
{
	Super::OnUnregister();
}

void UUpsightComponent::ApplicationRegisteredForUserNotificationsDelegate_Handler(int32 inInt)
{
#if PLATFORM_IOS
    NSUInteger t = [[NSNumber numberWithInt:inInt] unsignedIntegerValue];

    UIUserNotificationSettings *s = [UIUserNotificationSettings settingsForTypes:t categories:nil];

    [USPush didRegisterUserNotificationSettings:s];
#endif
}

void UUpsightComponent::ApplicationRegisteredForRemoteNotifications_Handler(TArray<uint8> Token)
{
#if PLATFORM_IOS
    NSData* TokenData = [NSData dataWithBytes:Token.GetData() length:Token.Num()];

    [USPush registerPushToken:TokenData];
#endif
}

void UUpsightComponent::ApplicationFailedToRegisterForRemoteNotifications_Handler(FString RegisterError)
{
    UE_LOG(LogUpsight, Error, TEXT("ApplicationFailedToRegisterForRemoteNotifications: %s"), *RegisterError);
}

void UUpsightComponent::ApplicationReceivedRemoteNotification_Handler(FString Json)
{
#if PLATFORM_IOS
    [USPush pushBillboard].delegate = ucd;

    NSDictionary *userInfo = @{ @"message" : @"" };

    [USPush handleRemoteNotificationWithUserInfo:userInfo];
#endif

    UE_LOG(LogUpsight, Log, TEXT("ApplicationReceivedRemoteNotification: %s"), *Json);
}

<|endoftext|>


<commit_before>/*
 * callbacks.hpp - Framework support of callback functions
 *
 *   Copyright 2010-2012 Jesús Torres <jmtorres@ull.es>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef CALLBACKS_HPP_
#define CALLBACKS_HPP_

#include <string>
#include <vector>

#include <boost/function.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/type_traits.hpp>

#include <cli/exceptions.hpp>

//
// Macro CLI_DECLARE_CALLBACKS & CLI_DECLARE_CALLBACKS_TPL
//
// Helps to add the support for callbacks to a class declaration.
//

#define CLI_DECLARE_CALLBACKS_FILLER_0(X, Y)    \
    ((X, Y)) CLI_DECLARE_CALLBACKS_FILLER_1
#define CLI_DECLARE_CALLBACKS_FILLER_1(X, Y)    \
    ((X, Y)) CLI_DECLARE_CALLBACKS_FILLER_0
#define CLI_DECLARE_CALLBACKS_FILLER_0_END
#define CLI_DECLARE_CALLBACKS_FILLER_1_END

#define CLI_DECLARE_CALLBACK_MEMBER(r, TYPE, DECLARATION_TUPLE)             \
    typedef cli::callback::                                                 \
        BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE)<TYPE>::Type            \
        BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE);                       \
    boost::function<BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE)>           \
        BOOST_PP_TUPLE_ELEM(2, 1, DECLARATION_TUPLE);				        \
    template <int N, int M>													\
    struct SetCallbackImpl<                                                 \
        cli::callback::BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE), N, M>  \
    {                                                                       \
        template <typename T, typename Functor>                             \
        static void setCallback(T& interpreter, Functor function)           \
            { interpreter.BOOST_PP_TUPLE_ELEM(2, 1, DECLARATION_TUPLE) =    \
                function; }                                                 \
    };

#define CLI_DECLARE_CALLBACK_MEMBER_TPL(r, TYPE, DECLARATION_TUPLE)         \
    typedef typename cli::callback::                                        \
        BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE)<TYPE>::Type            \
        BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE);                       \
    boost::function<BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE)>           \
        BOOST_PP_TUPLE_ELEM(2, 1, DECLARATION_TUPLE);                       \
    template <int N, int M>                                                 \
    struct SetCallbackImpl<                                                 \
        cli::callback::BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE), N, M>  \
    {                                                                       \
        template <typename T, typename Functor>                             \
        static void setCallback(T& interpreter, Functor function)           \
            { interpreter.BOOST_PP_TUPLE_ELEM(2, 1, DECLARATION_TUPLE) =    \
                function; }                                                 \
    };

#define CLI_DECLARE_CALLBACKS(TYPE, DECLARATIONS_SEQ)               \
    template <template <typename> class Callback, int N, int M> 	\
    struct SetCallbackImpl											\
    {																\
        template <typename T, typename Functor>						\
        static void setCallback(T& interpreter, Functor function)	\
        {															\
            throw cli::exception::UnknownCallbackException(			\
                Callback<T>::name());								\
        }															\
    };																\
    BOOST_PP_SEQ_FOR_EACH(                                          \
        CLI_DECLARE_CALLBACK_MEMBER,                                \
        TYPE,                                                       \
        BOOST_PP_CAT(                                               \
            CLI_DECLARE_CALLBACKS_FILLER_0 DECLARATIONS_SEQ, _END))

#define CLI_DECLARE_CALLBACKS_TPL(TYPE, DECLARATIONS_SEQ)           \
    template <template <typename> class Callback, int N, int M> 	\
    struct SetCallbackImpl											\
    {																\
        template <typename T, typename Functor>						\
        static void setCallback(T& interpreter, Functor function)	\
        {															\
            throw cli::exception::UnknownCallbackException(			\
                Callback<T>::name());								\
        }															\
    };																\
    BOOST_PP_SEQ_FOR_EACH(                                          \
        CLI_DECLARE_CALLBACK_MEMBER_TPL,                            \
        TYPE,                                                       \
        BOOST_PP_CAT(                                               \
            CLI_DECLARE_CALLBACKS_FILLER_0 DECLARATIONS_SEQ, _END))

//
// Macro CLI_CALLBACK_SIGNATURE_ASSERT & CLI_CALLBACK_SIGNATURE_ASSERT_TPL
//
// Tests if the function signature of FUNCTOR match the expected by CALLBACK.
//

#define CLI_CALLBACK_SIGNATURE_ASSERT(CALLBACK, FUNCTOR)                \
    BOOST_MPL_ASSERT((boost::is_convertible<FUNCTOR,                    \
        boost::function<CALLBACK<Type>::Type> >))

#define CLI_CALLBACK_SIGNATURE_ASSERT_TPL(CALLBACK, FUNCTOR)            \
    BOOST_MPL_ASSERT((boost::is_convertible<FUNCTOR,                    \
        boost::function<typename CALLBACK<Type>::Type> >))

namespace cli { namespace callback
{
    //
    // DoCommandCallback
    //

    template <typename T>
    struct DoCommandCallback
    {
        typedef bool (Type)(const std::string&,
            typename T::ArgumentsType const&);
        static const char* name() { return "DoCommandCallback"; }
    };

    //
    // EmptyLineCallback
    //

    template <typename T>
    struct EmptyLineCallback
    {
        typedef bool (Type)();
        static const char* name() { return "EmptyLineCallback"; }
    };

    //
    // PreDoCommandCallback
    //

    template <typename T>
    struct PreDoCommandCallback
    {
        typedef void (Type)(std::string&);
        static const char* name() { return "PreDoCommandCallback"; }
    };

    //
    // PostDoCommandCallback
    //

    template <typename T>
    struct PostDoCommandCallback
    {
        typedef bool (Type)(bool, const std::string&);
        static const char* name() { return "PostDoCommandCallback"; }
    };

    //
    // ParseErrorCallback
    //

    template <typename T>
    struct ParseErrorCallback
    {
            typedef bool (Type)(typename T::ParseErrorType const&,
                const std::string&);
            static const char* name() { return "ParseErrorCallback"; }
    };

    //
    // PreLoopCallback
    //

    template <typename T>
    struct PreLoopCallback
    {
        typedef void (Type)();
        static const char* name() { return "PreLoopCallback"; }
    };

    //
    // PostLoopCallback
    //

    template <typename T>
    struct PostLoopCallback
    {
        typedef void (Type)();
        static const char* name() { return "PostLoopCallback"; }
    };

    //
    // VariableLookupCallback
    //

    template <typename T>
    struct VariableLookupCallback
    {
        typedef std::string (Type)(const std::string&);
        static const char* name() { return "VariableLookupCallback"; }
    };

    //
    // PathnameExpansionCallback
    //

    template <typename T>
    struct PathnameExpansionCallback
    {
        typedef std::vector<std::string> (Type)(const std::string&);
        static const char* name() { return "PathnameExpansionCallback"; }
    };
}}

#endif /* CALLBACKS_HPP_ */
<commit_msg>fix wrong tabulation<commit_after>/*
 * callbacks.hpp - Framework support of callback functions
 *
 *   Copyright 2010-2012 Jesús Torres <jmtorres@ull.es>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef CALLBACKS_HPP_
#define CALLBACKS_HPP_

#include <string>
#include <vector>

#include <boost/function.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/type_traits.hpp>

#include <cli/exceptions.hpp>

//
// Macro CLI_DECLARE_CALLBACKS & CLI_DECLARE_CALLBACKS_TPL
//
// Helps to add the support for callbacks to a class declaration.
//

#define CLI_DECLARE_CALLBACKS_FILLER_0(X, Y)    \
    ((X, Y)) CLI_DECLARE_CALLBACKS_FILLER_1
#define CLI_DECLARE_CALLBACKS_FILLER_1(X, Y)    \
    ((X, Y)) CLI_DECLARE_CALLBACKS_FILLER_0
#define CLI_DECLARE_CALLBACKS_FILLER_0_END
#define CLI_DECLARE_CALLBACKS_FILLER_1_END

#define CLI_DECLARE_CALLBACK_MEMBER(r, TYPE, DECLARATION_TUPLE)             \
    typedef cli::callback::                                                 \
        BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE)<TYPE>::Type            \
        BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE);                       \
    boost::function<BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE)>           \
        BOOST_PP_TUPLE_ELEM(2, 1, DECLARATION_TUPLE);                       \
    template <int N, int M>                                                 \
    struct SetCallbackImpl<                                                 \
        cli::callback::BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE), N, M>  \
    {                                                                       \
        template <typename T, typename Functor>                             \
        static void setCallback(T& interpreter, Functor function)           \
            { interpreter.BOOST_PP_TUPLE_ELEM(2, 1, DECLARATION_TUPLE) =    \
                function; }                                                 \
    };

#define CLI_DECLARE_CALLBACK_MEMBER_TPL(r, TYPE, DECLARATION_TUPLE)         \
    typedef typename cli::callback::                                        \
        BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE)<TYPE>::Type            \
        BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE);                       \
    boost::function<BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE)>           \
        BOOST_PP_TUPLE_ELEM(2, 1, DECLARATION_TUPLE);                       \
    template <int N, int M>                                                 \
    struct SetCallbackImpl<                                                 \
        cli::callback::BOOST_PP_TUPLE_ELEM(2, 0, DECLARATION_TUPLE), N, M>  \
    {                                                                       \
        template <typename T, typename Functor>                             \
        static void setCallback(T& interpreter, Functor function)           \
            { interpreter.BOOST_PP_TUPLE_ELEM(2, 1, DECLARATION_TUPLE) =    \
                function; }                                                 \
    };

#define CLI_DECLARE_CALLBACKS(TYPE, DECLARATIONS_SEQ)               \
    template <template <typename> class Callback, int N, int M>     \
    struct SetCallbackImpl                                          \
    {                                                               \
        template <typename T, typename Functor>                     \
        static void setCallback(T& interpreter, Functor function)   \
        {                                                           \
            throw cli::exception::UnknownCallbackException(         \
                Callback<T>::name());                               \
        }                                                           \
    };                                                              \
    BOOST_PP_SEQ_FOR_EACH(                                          \
        CLI_DECLARE_CALLBACK_MEMBER,                                \
        TYPE,                                                       \
        BOOST_PP_CAT(                                               \
            CLI_DECLARE_CALLBACKS_FILLER_0 DECLARATIONS_SEQ, _END))

#define CLI_DECLARE_CALLBACKS_TPL(TYPE, DECLARATIONS_SEQ)           \
    template <template <typename> class Callback, int N, int M>     \
    struct SetCallbackImpl                                          \
    {                                                               \
        template <typename T, typename Functor>                     \
        static void setCallback(T& interpreter, Functor function)   \
        {                                                           \
            throw cli::exception::UnknownCallbackException(         \
                Callback<T>::name());                               \
        }                                                           \
    };                                                              \
    BOOST_PP_SEQ_FOR_EACH(                                          \
        CLI_DECLARE_CALLBACK_MEMBER_TPL,                            \
        TYPE,                                                       \
        BOOST_PP_CAT(                                               \
            CLI_DECLARE_CALLBACKS_FILLER_0 DECLARATIONS_SEQ, _END))

//
// Macro CLI_CALLBACK_SIGNATURE_ASSERT & CLI_CALLBACK_SIGNATURE_ASSERT_TPL
//
// Tests if the function signature of FUNCTOR match the expected by CALLBACK.
//

#define CLI_CALLBACK_SIGNATURE_ASSERT(CALLBACK, FUNCTOR)                \
    BOOST_MPL_ASSERT((boost::is_convertible<FUNCTOR,                    \
        boost::function<CALLBACK<Type>::Type> >))

#define CLI_CALLBACK_SIGNATURE_ASSERT_TPL(CALLBACK, FUNCTOR)            \
    BOOST_MPL_ASSERT((boost::is_convertible<FUNCTOR,                    \
        boost::function<typename CALLBACK<Type>::Type> >))

namespace cli { namespace callback
{
    //
    // DoCommandCallback
    //

    template <typename T>
    struct DoCommandCallback
    {
        typedef bool (Type)(const std::string&,
            typename T::ArgumentsType const&);
        static const char* name() { return "DoCommandCallback"; }
    };

    //
    // EmptyLineCallback
    //

    template <typename T>
    struct EmptyLineCallback
    {
        typedef bool (Type)();
        static const char* name() { return "EmptyLineCallback"; }
    };

    //
    // PreDoCommandCallback
    //

    template <typename T>
    struct PreDoCommandCallback
    {
        typedef void (Type)(std::string&);
        static const char* name() { return "PreDoCommandCallback"; }
    };

    //
    // PostDoCommandCallback
    //

    template <typename T>
    struct PostDoCommandCallback
    {
        typedef bool (Type)(bool, const std::string&);
        static const char* name() { return "PostDoCommandCallback"; }
    };

    //
    // ParseErrorCallback
    //

    template <typename T>
    struct ParseErrorCallback
    {
            typedef bool (Type)(typename T::ParseErrorType const&,
                const std::string&);
            static const char* name() { return "ParseErrorCallback"; }
    };

    //
    // PreLoopCallback
    //

    template <typename T>
    struct PreLoopCallback
    {
        typedef void (Type)();
        static const char* name() { return "PreLoopCallback"; }
    };

    //
    // PostLoopCallback
    //

    template <typename T>
    struct PostLoopCallback
    {
        typedef void (Type)();
        static const char* name() { return "PostLoopCallback"; }
    };

    //
    // VariableLookupCallback
    //

    template <typename T>
    struct VariableLookupCallback
    {
        typedef std::string (Type)(const std::string&);
        static const char* name() { return "VariableLookupCallback"; }
    };

    //
    // PathnameExpansionCallback
    //

    template <typename T>
    struct PathnameExpansionCallback
    {
        typedef std::vector<std::string> (Type)(const std::string&);
        static const char* name() { return "PathnameExpansionCallback"; }
    };
}}

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