<commit_before>//===-- LogTest.cpp ---------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"

#include "lldb/Core/Log.h"
#include "lldb/Host/Host.h"
#include "lldb/Utility/StreamString.h"
#include "llvm/Support/ManagedStatic.h"
#include <thread>

using namespace lldb;
using namespace lldb_private;

enum { FOO = 1, BAR = 2 };
static constexpr Log::Category test_categories[] = {
    {"foo", "log foo", FOO}, {"bar", "log bar", BAR},
};
static constexpr uint32_t default_flags = FOO;

static Log::Channel test_channel(test_categories, default_flags);

struct LogChannelTest : public ::testing::Test {
  void TearDown() override { Log::DisableAllLogChannels(nullptr); }

  static void SetUpTestCase() {
    Log::Register("chan", test_channel);
  }

  static void TearDownTestCase() {
    Log::Unregister("chan");
    llvm::llvm_shutdown();
  }
};

static std::string GetLogString(uint32_t log_options, const char *format,
                                int arg) {
  std::string stream_string;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(stream_string));
  Log log_(stream_sp);
  log_.GetOptions().Reset(log_options);
  Log *log = &log_;
  LLDB_LOG(log, format, arg);
  return stream_sp->str();
}

TEST(LogTest, LLDB_LOG_nullptr) {
  Log *log = nullptr;
  LLDB_LOG(log, "{0}", 0); // Shouldn't crash
}

TEST(LogTest, log_options) {
  EXPECT_EQ("Hello World 47\n", GetLogString(0, "Hello World {0}", 47));
  EXPECT_EQ("Hello World 47\n",
            GetLogString(LLDB_LOG_OPTION_THREADSAFE, "Hello World {0}", 47));

  {
    std::string msg =
        GetLogString(LLDB_LOG_OPTION_PREPEND_SEQUENCE, "Hello World {0}", 47);
    int seq_no;
    EXPECT_EQ(1, sscanf(msg.c_str(), "%d Hello World 47", &seq_no));
  }

  EXPECT_EQ(
      "LogTest.cpp:GetLogString                                     Hello "
      "World 47\n",
      GetLogString(LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION, "Hello World {0}", 47));

  EXPECT_EQ(llvm::formatv("[{0,0+4}/{1,0+4}] Hello World 47\n",
                          Host::GetCurrentProcessID(),
                          Host::GetCurrentThreadID())
                .str(),
            GetLogString(LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD,
                         "Hello World {0}", 47));
}

TEST(LogTest, Register) {
  llvm::llvm_shutdown_obj obj;
  Log::Register("chan", test_channel);
  Log::Unregister("chan");
  Log::Register("chan", test_channel);
  Log::Unregister("chan");
}

TEST(LogTest, Unregister) {
  llvm::llvm_shutdown_obj obj;
  Log::Register("chan", test_channel);
  EXPECT_EQ(nullptr, test_channel.GetLogIfAny(FOO));
  const char *cat1[] = {"foo"};
  std::string message;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(message));
  StreamString err;
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", cat1, err));
  EXPECT_NE(nullptr, test_channel.GetLogIfAny(FOO));
  Log::Unregister("chan");
  EXPECT_EQ(nullptr, test_channel.GetLogIfAny(FOO));
}

TEST_F(LogChannelTest, Enable) {
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(FOO));
  std::string message;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(message));
  StreamString err;
  EXPECT_FALSE(Log::EnableLogChannel(stream_sp, 0, "chanchan", {}, err));
  EXPECT_EQ("Invalid log channel 'chanchan'.\n", err.GetString());
  err.Clear();

  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", {}, err));
  EXPECT_EQ("", err.GetString()) << "err: " << err.GetString().str();
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO));
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(BAR));

  const char *cat2[] = {"bar"};
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", cat2, err));
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO | BAR));

  const char *cat3[] = {"baz"};
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", cat3, err));
  EXPECT_TRUE(err.GetString().contains("unrecognized log category 'baz'"))
      << "err: " << err.GetString().str();
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO | BAR));
}

TEST_F(LogChannelTest, EnableOptions) {
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(FOO));
  std::string message;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(message));
  StreamString err;
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, LLDB_LOG_OPTION_VERBOSE, "chan",
                                    {}, err));

  Log *log = test_channel.GetLogIfAll(FOO);
  ASSERT_NE(nullptr, log);
  EXPECT_TRUE(log->GetVerbose());
}

TEST_F(LogChannelTest, Disable) {
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(FOO));
  const char *cat12[] = {"foo", "bar"};
  std::string message;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(message));
  StreamString err;
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", cat12, err));
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO | BAR));

  const char *cat2[] = {"bar"};
  EXPECT_TRUE(Log::DisableLogChannel("chan", cat2, err));
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO));
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(BAR));

  const char *cat3[] = {"baz"};
  EXPECT_TRUE(Log::DisableLogChannel("chan", cat3, err));
  EXPECT_TRUE(err.GetString().contains("unrecognized log category 'baz'"))
      << "err: " << err.GetString().str();
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO));
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(BAR));
  err.Clear();

  EXPECT_TRUE(Log::DisableLogChannel("chan", {}, err));
  EXPECT_EQ(nullptr, test_channel.GetLogIfAny(FOO | BAR));
}

TEST_F(LogChannelTest, List) {
  StreamString str;
  EXPECT_TRUE(Log::ListChannelCategories("chan", str));
  std::string expected =
      R"(Logging categories for 'chan':
  all - all available logging categories
  default - default set of logging categories
  foo - log foo
  bar - log bar
)";
  EXPECT_EQ(expected, str.GetString().str());
  str.Clear();

  EXPECT_FALSE(Log::ListChannelCategories("chanchan", str));
  EXPECT_EQ("Invalid log channel 'chanchan'.\n", str.GetString().str());
}

TEST_F(LogChannelTest, LogThread) {
  // Test that we are able to concurrently write to a log channel and disable
  // it.
  std::string message;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(message));
  StreamString err;
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", {}, err));

  Log *log = test_channel.GetLogIfAll(FOO);

  // Start logging on one thread. Concurrently, try disabling the log channel.
  std::thread log_thread([log] { LLDB_LOG(log, "Hello World"); });
  EXPECT_TRUE(Log::DisableLogChannel("chan", {}, err));
  log_thread.join();

  // The log thread either managed to write to the log in time, or it didn't. In
  // either case, we should not trip any undefined behavior (run the test under
  // TSAN to verify this).
  EXPECT_TRUE(stream_sp->str() == "" || stream_sp->str() == "Hello World\n")
      << "str(): " << stream_sp->str();
}
<commit_msg>Fix gcc compilation of LogTest.cpp<commit_after>//===-- LogTest.cpp ---------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"

#include "lldb/Core/Log.h"
#include "lldb/Host/Host.h"
#include "lldb/Utility/StreamString.h"
#include "llvm/Support/ManagedStatic.h"
#include <thread>

using namespace lldb;
using namespace lldb_private;

enum { FOO = 1, BAR = 2 };
static constexpr Log::Category test_categories[] = {
    {{"foo"}, {"log foo"}, FOO}, {{"bar"}, {"log bar"}, BAR},
};
static constexpr uint32_t default_flags = FOO;

static Log::Channel test_channel(test_categories, default_flags);

struct LogChannelTest : public ::testing::Test {
  void TearDown() override { Log::DisableAllLogChannels(nullptr); }

  static void SetUpTestCase() {
    Log::Register("chan", test_channel);
  }

  static void TearDownTestCase() {
    Log::Unregister("chan");
    llvm::llvm_shutdown();
  }
};

static std::string GetLogString(uint32_t log_options, const char *format,
                                int arg) {
  std::string stream_string;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(stream_string));
  Log log_(stream_sp);
  log_.GetOptions().Reset(log_options);
  Log *log = &log_;
  LLDB_LOG(log, format, arg);
  return stream_sp->str();
}

TEST(LogTest, LLDB_LOG_nullptr) {
  Log *log = nullptr;
  LLDB_LOG(log, "{0}", 0); // Shouldn't crash
}

TEST(LogTest, log_options) {
  EXPECT_EQ("Hello World 47\n", GetLogString(0, "Hello World {0}", 47));
  EXPECT_EQ("Hello World 47\n",
            GetLogString(LLDB_LOG_OPTION_THREADSAFE, "Hello World {0}", 47));

  {
    std::string msg =
        GetLogString(LLDB_LOG_OPTION_PREPEND_SEQUENCE, "Hello World {0}", 47);
    int seq_no;
    EXPECT_EQ(1, sscanf(msg.c_str(), "%d Hello World 47", &seq_no));
  }

  EXPECT_EQ(
      "LogTest.cpp:GetLogString                                     Hello "
      "World 47\n",
      GetLogString(LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION, "Hello World {0}", 47));

  EXPECT_EQ(llvm::formatv("[{0,0+4}/{1,0+4}] Hello World 47\n",
                          Host::GetCurrentProcessID(),
                          Host::GetCurrentThreadID())
                .str(),
            GetLogString(LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD,
                         "Hello World {0}", 47));
}

TEST(LogTest, Register) {
  llvm::llvm_shutdown_obj obj;
  Log::Register("chan", test_channel);
  Log::Unregister("chan");
  Log::Register("chan", test_channel);
  Log::Unregister("chan");
}

TEST(LogTest, Unregister) {
  llvm::llvm_shutdown_obj obj;
  Log::Register("chan", test_channel);
  EXPECT_EQ(nullptr, test_channel.GetLogIfAny(FOO));
  const char *cat1[] = {"foo"};
  std::string message;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(message));
  StreamString err;
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", cat1, err));
  EXPECT_NE(nullptr, test_channel.GetLogIfAny(FOO));
  Log::Unregister("chan");
  EXPECT_EQ(nullptr, test_channel.GetLogIfAny(FOO));
}

TEST_F(LogChannelTest, Enable) {
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(FOO));
  std::string message;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(message));
  StreamString err;
  EXPECT_FALSE(Log::EnableLogChannel(stream_sp, 0, "chanchan", {}, err));
  EXPECT_EQ("Invalid log channel 'chanchan'.\n", err.GetString());
  err.Clear();

  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", {}, err));
  EXPECT_EQ("", err.GetString()) << "err: " << err.GetString().str();
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO));
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(BAR));

  const char *cat2[] = {"bar"};
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", cat2, err));
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO | BAR));

  const char *cat3[] = {"baz"};
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", cat3, err));
  EXPECT_TRUE(err.GetString().contains("unrecognized log category 'baz'"))
      << "err: " << err.GetString().str();
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO | BAR));
}

TEST_F(LogChannelTest, EnableOptions) {
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(FOO));
  std::string message;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(message));
  StreamString err;
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, LLDB_LOG_OPTION_VERBOSE, "chan",
                                    {}, err));

  Log *log = test_channel.GetLogIfAll(FOO);
  ASSERT_NE(nullptr, log);
  EXPECT_TRUE(log->GetVerbose());
}

TEST_F(LogChannelTest, Disable) {
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(FOO));
  const char *cat12[] = {"foo", "bar"};
  std::string message;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(message));
  StreamString err;
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", cat12, err));
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO | BAR));

  const char *cat2[] = {"bar"};
  EXPECT_TRUE(Log::DisableLogChannel("chan", cat2, err));
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO));
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(BAR));

  const char *cat3[] = {"baz"};
  EXPECT_TRUE(Log::DisableLogChannel("chan", cat3, err));
  EXPECT_TRUE(err.GetString().contains("unrecognized log category 'baz'"))
      << "err: " << err.GetString().str();
  EXPECT_NE(nullptr, test_channel.GetLogIfAll(FOO));
  EXPECT_EQ(nullptr, test_channel.GetLogIfAll(BAR));
  err.Clear();

  EXPECT_TRUE(Log::DisableLogChannel("chan", {}, err));
  EXPECT_EQ(nullptr, test_channel.GetLogIfAny(FOO | BAR));
}

TEST_F(LogChannelTest, List) {
  StreamString str;
  EXPECT_TRUE(Log::ListChannelCategories("chan", str));
  std::string expected =
      R"(Logging categories for 'chan':
  all - all available logging categories
  default - default set of logging categories
  foo - log foo
  bar - log bar
)";
  EXPECT_EQ(expected, str.GetString().str());
  str.Clear();

  EXPECT_FALSE(Log::ListChannelCategories("chanchan", str));
  EXPECT_EQ("Invalid log channel 'chanchan'.\n", str.GetString().str());
}

TEST_F(LogChannelTest, LogThread) {
  // Test that we are able to concurrently write to a log channel and disable
  // it.
  std::string message;
  std::shared_ptr<llvm::raw_string_ostream> stream_sp(
      new llvm::raw_string_ostream(message));
  StreamString err;
  EXPECT_TRUE(Log::EnableLogChannel(stream_sp, 0, "chan", {}, err));

  Log *log = test_channel.GetLogIfAll(FOO);

  // Start logging on one thread. Concurrently, try disabling the log channel.
  std::thread log_thread([log] { LLDB_LOG(log, "Hello World"); });
  EXPECT_TRUE(Log::DisableLogChannel("chan", {}, err));
  log_thread.join();

  // The log thread either managed to write to the log in time, or it didn't. In
  // either case, we should not trip any undefined behavior (run the test under
  // TSAN to verify this).
  EXPECT_TRUE(stream_sp->str() == "" || stream_sp->str() == "Hello World\n")
      << "str(): " << stream_sp->str();
}
<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(n)

class Solution {
public:
    /**
     * @param s input string
     * @return the longest palindromic substring
     */
    string longestPalindrome(string& s) {
        string T = preProcess(s);
        int n = T.length();
        vector<int> P(n);
        int C = 0, R = 0;
        for (int i = 1; i < n - 1; ++i) {
            int i_mirror = 2 * C - i; // equals to i' = C - (i-C)

            P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0;

            // Attempt to expand palindrome centered at i
            while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) {
                ++P[i];
            }

            // If palindrome centered at i expand past R,
            // adjust center based on expanded palindrome.
            if (i + P[i] > R) {
                C = i;
                R = i + P[i];
            }
        }

        // Find the maximum element in P.
        int max_len = 0, center_index = 0;
        for (int i = 1; i < n - 1; ++i) {
            if (P[i] > max_len) {
                max_len = P[i];
                center_index = i;
            }
        }

        return s.substr((center_index - 1 - max_len) / 2, max_len);
    }
    private:
    string preProcess(const string& s) {
        if (s.empty()) {
            return "^$";
        }
        string ret = "^";
        for (int i = 0; i < s.length(); ++i) {
            ret += "#" + s.substr(i, 1);
        }

        ret += "#$";
        return ret;
    }
};
<commit_msg>Update longest-palindromic-substring.cpp<commit_after>// Time:  O(n)
// Space: O(n)

class Solution {
public:
    /**
     * @param s input string
     * @return the longest palindromic substring
     */
    string longestPalindrome(string& s) {
        string T = preProcess(s);
        const int n = T.length();
        vector<int> P(n);
        int C = 0, R = 0;
        for (int i = 1; i < n - 1; ++i) {
            int i_mirror = 2 * C - i; // equals to i' = C - (i-C)

            P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0;

            // Attempt to expand palindrome centered at i
            while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) {
                ++P[i];
            }

            // If palindrome centered at i expand past R,
            // adjust center based on expanded palindrome.
            if (i + P[i] > R) {
                C = i;
                R = i + P[i];
            }
        }

        // Find the maximum element in P.
        int max_len = 0, center_index = 0;
        for (int i = 1; i < n - 1; ++i) {
            if (P[i] > max_len) {
                max_len = P[i];
                center_index = i;
            }
        }

        return s.substr((center_index - 1 - max_len) / 2, max_len);
    }

private:
    string preProcess(const string& s) {
        if (s.empty()) {
            return "^$";
        }
        string ret = "^";
        for (int i = 0; i < s.length(); ++i) {
            ret += "#" + s.substr(i, 1);
        }
        ret += "#$";
        return ret;
    }
};
<|endoftext|>


<commit_before>#include "commodconverter_facility.h"

namespace commodconverter {

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodconverterFacility::CommodconverterFacility(cyclus::Context* ctx)
    : cyclus::Facility(ctx) {};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// pragmas

#pragma cyclus def schema commodconverter::CommodconverterFacility

#pragma cyclus def annotations commodconverter::CommodconverterFacility

#pragma cyclus def initinv commodconverter::CommodconverterFacility

#pragma cyclus def snapshotinv commodconverter::CommodconverterFacility

#pragma cyclus def initfromdb commodconverter::CommodconverterFacility

#pragma cyclus def initfromcopy commodconverter::CommodconverterFacility

#pragma cyclus def infiletodb commodconverter::CommodconverterFacility

#pragma cyclus def snapshot commodconverter::CommodconverterFacility

#pragma cyclus def clone commodconverter::CommodconverterFacility

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string CommodconverterFacility::str() {
  std::stringstream ss;
  ss << cyclus::Facility::str();
  ss << " has facility parameters {" << "\n"
     << "     Input Commodity = " << in_commod() << ",\n"
     << "     Output Commodity = " << out_commod() << ",\n"
     << "     Process Time = " << process_time() << ",\n"
     << "     Capacity = " << capacity() << ",\n"
     << "'}";
  return ss.str();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Build(cyclus::Agent* parent) {
  using cyclus::Material;

  Facility::Build(parent);
  if (initial_reserves > 0) {
    inventory.Push(
      Material::Create(
        this, initial_reserves, context()->GetRecipe(in_recipe)));
  }

  LOG(cyclus::LEV_DEBUG2, "ComCnv") << "CommodconverterFacility "
                                 << " entering the simuluation: ";
  LOG(cyclus::LEV_DEBUG2, "ComCnv") << str();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Tick() {
  LOG(cyclus::LEV_INFO3, "ComCnv") << prototype() << " is ticking {";
  LOG(cyclus::LEV_INFO3, "ComCnv") << "}";
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Tock() {
  LOG(cyclus::LEV_INFO3, "ComCnv") << prototype() << " is tocking {";
  LOG(cyclus::LEV_INFO3, "ComCnv") << "}";
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr>
CommodconverterFacility::GetMatlRequests() {
  using cyclus::CapacityConstraint;
  using cyclus::Material;
  using cyclus::RequestPortfolio;
  using cyclus::Request;

  std::set<RequestPortfolio<Material>::Ptr> ports;
  RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>());
  Material::Ptr mat = Request_();
  double amt = mat->quantity();

  if (amt > cyclus::eps()) {
    CapacityConstraint<Material> cc(amt);
    port->AddConstraint(cc);

    port->AddRequest(mat, this, in_commod);

    ports.insert(port);
  }

  return ports;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::AcceptMatlTrades(
  const std::vector< std::pair<cyclus::Trade<cyclus::Material>,
  cyclus::Material::Ptr> >& responses) {
  std::vector< std::pair<cyclus::Trade<cyclus::Material>,
      cyclus::Material::Ptr> >::const_iterator it;
  for (it = responses.begin(); it != responses.end(); ++it) {
    AddMat_(it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<cyclus::BidPortfolio<cyclus::Material>::Ptr>
CommodconverterFacility::GetMatlBids(
  cyclus::CommodMap<cyclus::Material>::type& commod_requests) {
  using cyclus::Bid;
  using cyclus::BidPortfolio;
  using cyclus::CapacityConstraint;
  using cyclus::Converter;
  using cyclus::Material;
  using cyclus::Request;

  std::set<BidPortfolio<Material>::Ptr> ports;

  if (commod_requests.count(out_commod) > 0 && inventory.quantity() > 0) {
    BidPortfolio<Material>::Ptr port(new BidPortfolio<Material>());

    std::vector<Request<Material>*>& requests =
        commod_requests[out_commod];

    std::vector<Request<Material>*>::iterator it;
    for (it = requests.begin(); it != requests.end(); ++it) {
      Request<Material>* req = *it;
      if (ValidReq(req->target())) {
        Material::Ptr offer = Offer_(req->target());
        port->AddBid(req, offer, this);
      }
    }

    // want to add constraints based on the incoming commodity
    // TODO, determine whether it's possible to request material
    // without adding a recipe constraint. Ask matt?
    Converter<Material>::Ptr sc(new SWUConverter(feed_assay, tails_assay));
    Converter<Material>::Ptr nc(new NatUConverter(feed_assay, tails_assay));
    CapacityConstraint<Material> swu(swu_capacity, sc);
    CapacityConstraint<Material> natu(inventory.quantity(), nc);
    port->AddConstraint(swu);
    port->AddConstraint(natu);

    LOG(cyclus::LEV_INFO5, "ComCnv") << prototype()
                                  << " adding a swu constraint of "
                                  << swu.capacity();
    LOG(cyclus::LEV_INFO5, "ComCnv") << prototype()
                                  << " adding a natu constraint of "
                                  << natu.capacity();

    ports.insert(port);
  }
  return ports;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CommodconverterFacility::ValidReq(const cyclus::Material::Ptr mat) {
  // TODO make this just check the commod.
  return 1; // where is this used?
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::GetMatlTrades(
  const std::vector< cyclus::Trade<cyclus::Material> >& trades,
  std::vector<std::pair<cyclus::Trade<cyclus::Material>,
  cyclus::Material::Ptr> >& responses) {
  using cyclus::Material;
  using cyclus::Trade;

  std::vector< Trade<Material> >::const_iterator it;
  for (it = trades.begin(); it != trades.end(); ++it) {
    Material::Ptr mat = it->bid->offer();
    double qty = it->amt;
    Material::Ptr response = Enrich_(mat, qty);
    responses.push_back(std::make_pair(*it, response));
    LOG(cyclus::LEV_INFO5, "ComCnv") << prototype()
                                  << " just received an order"
                                  << " for " << it->amt
                                  << " of " << out_commod;
  }

  if (cyclus::IsNegative(current_swu_capacity)) {
    throw cyclus::ValueError(
      "ComCnv " + prototype()
      + " is being asked to provide more than its SWU capacity.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::AddMat_(cyclus::Material::Ptr mat) {
  // Here we do not check that the recipe matches the input recipe.

  LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " is initially holding "
                                << inventory.quantity() << " total.";

  try {
    inventory.Push(mat);
  } catch (cyclus::Error& e) {
    e.msg(Agent::InformErrorMsg(e.msg()));
    throw e;
  }

  LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " added " << mat->quantity()
                                << " of " << in_commod
                                << " to its inventory, which is holding "
                                << inventory.quantity() << " total.";

}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" cyclus::Agent* ConstructCommodconverterFacility(cyclus::Context* ctx) {
  return new CommodconverterFacility(ctx);
}

} // namespace commodconverter
<commit_msg>implements Build function based on batch reactor<commit_after>// commodconverter_facility.cc
// Implements the CommodconverterFacility class
#include "commodconverter_facility.h"

namespace commodconverter {

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodconverterFacility::CommodconverterFacility(cyclus::Context* ctx)
    : cyclus::Facility(ctx) {};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// pragmas

#pragma cyclus def schema commodconverter::CommodconverterFacility

#pragma cyclus def annotations commodconverter::CommodconverterFacility

#pragma cyclus def initinv commodconverter::CommodconverterFacility

#pragma cyclus def snapshotinv commodconverter::CommodconverterFacility

#pragma cyclus def initfromdb commodconverter::CommodconverterFacility

#pragma cyclus def initfromcopy commodconverter::CommodconverterFacility

#pragma cyclus def infiletodb commodconverter::CommodconverterFacility

#pragma cyclus def snapshot commodconverter::CommodconverterFacility

#pragma cyclus def clone commodconverter::CommodconverterFacility

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string CommodconverterFacility::str() {
  std::stringstream ss;
  ss << cyclus::Facility::str();
  ss << " has facility parameters {" << "\n"
     << "     Input Commodity = " << in_commod() << ",\n"
     << "     Output Commodity = " << out_commod() << ",\n"
     << "     Process Time = " << process_time() << ",\n"
     << "     Capacity = " << capacity() << ",\n"
     << "'}";
  return ss.str();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Build(cyclus::Agent* parent) {
  using cyclus::Material;

  Facility::Build(parent);
  std::string rec = crctx_.in_recipe(*crctx_.in_commods().begin());
  spillover_ = Material::Create(this, 0.0, context()->GetRecipe(rec));

  Material::Ptr mat;
  for (int i = 0; i < ics_.n_reserves; ++i) {
    mat = Material::Create(this,
                           batch_size(),
                           context()->GetRecipe(ics_.reserves_rec));
    assert(ics_.reserves_commod != "");
    crctx_.AddRsrc(ics_.reserves_commod, mat);
    reserves_.Push(mat);
  }
  for (int i = 0; i < ics_.n_core; ++i) {
    mat = Material::Create(this,
                           batch_size(),
                           context()->GetRecipe(ics_.core_rec));
    assert(ics_.core_commod != "");
    crctx_.AddRsrc(ics_.core_commod, mat);
    core_.Push(mat);
  }
  for (int i = 0; i < ics_.n_storage; ++i) {
    mat = Material::Create(this,
                           batch_size(),
                           context()->GetRecipe(ics_.storage_rec));
    assert(ics_.storage_commod != "");
    crctx_.AddRsrc(ics_.storage_commod, mat);
    storage_[ics_.storage_commod].Push(mat);
  }

  LOG(cyclus::LEV_DEBUG2, "ComCnv") << "CommodconverterFacility "
                                    << "entering the simuluation: ";
  LOG(cyclus::LEV_DEBUG2, "ComCnv") << str();

}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Tick() {
  LOG(cyclus::LEV_INFO3, "ComCnv") << prototype() << " is ticking {";
  LOG(cyclus::LEV_INFO3, "ComCnv") << "}";
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Tock() {
  LOG(cyclus::LEV_INFO3, "ComCnv") << prototype() << " is tocking {";
  LOG(cyclus::LEV_INFO3, "ComCnv") << "}";
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr>
CommodconverterFacility::GetMatlRequests() {
  using cyclus::CapacityConstraint;
  using cyclus::Material;
  using cyclus::RequestPortfolio;
  using cyclus::Request;

  std::set<RequestPortfolio<Material>::Ptr> ports;
  RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>());
  Material::Ptr mat = Request_();
  double amt = mat->quantity();

  if (amt > cyclus::eps()) {
    CapacityConstraint<Material> cc(amt);
    port->AddConstraint(cc);

    port->AddRequest(mat, this, in_commod);

    ports.insert(port);
  }

  return ports;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::AcceptMatlTrades(
  const std::vector< std::pair<cyclus::Trade<cyclus::Material>,
  cyclus::Material::Ptr> >& responses) {
  std::vector< std::pair<cyclus::Trade<cyclus::Material>,
      cyclus::Material::Ptr> >::const_iterator it;
  for (it = responses.begin(); it != responses.end(); ++it) {
    AddMat_(it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<cyclus::BidPortfolio<cyclus::Material>::Ptr>
CommodconverterFacility::GetMatlBids(
  cyclus::CommodMap<cyclus::Material>::type& commod_requests) {
  using cyclus::Bid;
  using cyclus::BidPortfolio;
  using cyclus::CapacityConstraint;
  using cyclus::Converter;
  using cyclus::Material;
  using cyclus::Request;

  std::set<BidPortfolio<Material>::Ptr> ports;

  if (commod_requests.count(out_commod) > 0 && inventory.quantity() > 0) {
    BidPortfolio<Material>::Ptr port(new BidPortfolio<Material>());

    std::vector<Request<Material>*>& requests =
        commod_requests[out_commod];

    std::vector<Request<Material>*>::iterator it;
    for (it = requests.begin(); it != requests.end(); ++it) {
      Request<Material>* req = *it;
      if (ValidReq(req->target())) {
        Material::Ptr offer = Offer_(req->target());
        port->AddBid(req, offer, this);
      }
    }

    // want to add constraints based on the incoming commodity
    // TODO, determine whether it's possible to request material
    // without adding a recipe constraint. Ask matt?
    Converter<Material>::Ptr sc(new SWUConverter(feed_assay, tails_assay));
    Converter<Material>::Ptr nc(new NatUConverter(feed_assay, tails_assay));
    CapacityConstraint<Material> swu(swu_capacity, sc);
    CapacityConstraint<Material> natu(inventory.quantity(), nc);
    port->AddConstraint(swu);
    port->AddConstraint(natu);

    LOG(cyclus::LEV_INFO5, "ComCnv") << prototype()
                                  << " adding a swu constraint of "
                                  << swu.capacity();
    LOG(cyclus::LEV_INFO5, "ComCnv") << prototype()
                                  << " adding a natu constraint of "
                                  << natu.capacity();

    ports.insert(port);
  }
  return ports;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CommodconverterFacility::ValidReq(const cyclus::Material::Ptr mat) {
  // TODO make this just check the commod.
  return 1; // where is this used?
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::GetMatlTrades(
  const std::vector< cyclus::Trade<cyclus::Material> >& trades,
  std::vector<std::pair<cyclus::Trade<cyclus::Material>,
  cyclus::Material::Ptr> >& responses) {
  using cyclus::Material;
  using cyclus::Trade;

  std::vector< Trade<Material> >::const_iterator it;
  for (it = trades.begin(); it != trades.end(); ++it) {
    Material::Ptr mat = it->bid->offer();
    double qty = it->amt;
    Material::Ptr response = Enrich_(mat, qty);
    responses.push_back(std::make_pair(*it, response));
    LOG(cyclus::LEV_INFO5, "ComCnv") << prototype()
                                  << " just received an order"
                                  << " for " << it->amt
                                  << " of " << out_commod;
  }

  if (cyclus::IsNegative(current_swu_capacity)) {
    throw cyclus::ValueError(
      "ComCnv " + prototype()
      + " is being asked to provide more than its SWU capacity.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::AddMat_(cyclus::Material::Ptr mat) {
  // Here we do not check that the recipe matches the input recipe.

  LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " is initially holding "
                                << inventory.quantity() << " total.";

  try {
    inventory.Push(mat);
  } catch (cyclus::Error& e) {
    e.msg(Agent::InformErrorMsg(e.msg()));
    throw e;
  }

  LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " added " << mat->quantity()
                                << " of " << in_commod
                                << " to its inventory, which is holding "
                                << inventory.quantity() << " total.";

}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" cyclus::Agent* ConstructCommodconverterFacility(cyclus::Context* ctx) {
  return new CommodconverterFacility(ctx);
}

} // namespace commodconverter
<|endoftext|>


<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <iostream>
#include <fstream>

#include <minizinc/model.hh>
#include <minizinc/parser.hh>
#include <minizinc/prettyprinter.hh>
#include <minizinc/typecheck.hh>
#include <minizinc/astexception.hh>
#include <minizinc/hash.hh>
#include <minizinc/eval_par.hh>
#include <minizinc/builtins.hh>
#include <minizinc/file_utils.hh>

using namespace MiniZinc;
using namespace std;

int main(int argc, char** argv) {
  string filename;

  string flag_output_file;

  bool flag_output_comments = true;
  bool flag_output_flush = true;
  string solfile;
  int flag_ignore_lines = 0;
  istream& solstream = cin;

  string solution_separator = "----------";
  string unsatisfiable_msg  = "=====UNSATISFIABLE=====";
  string unbounded_msg      = "=====UNBOUNDED=====";
  string unknown_msg        = "=====UNKNOWN=====";
  string search_complete_msg= "==========";

  vector<string> includePaths;
  string std_lib_dir;
  if (char* MZNSTDLIBDIR = getenv("MZN_STDLIB_DIR")) {
    std_lib_dir = string(MZNSTDLIBDIR);
  }

  if (argc < 2)
    goto error;

  GC::init();

  for (int i=1; i<argc; i++) {
    if (string(argv[i])==string("--version")) {
      std::cout << "NICTA MiniZinc solution printing tool, version "
      << MZN_VERSION_MAJOR << "." << MZN_VERSION_MINOR << "." << MZN_VERSION_PATCH << std::endl;
      std::cout << "Copyright (C) 2014 Monash University and NICTA" << std::endl;
      std::exit(EXIT_SUCCESS);
    }
    if (string(argv[i])==string("-h") || string(argv[i])==string("--help")) {
        goto error;
    } else if (string(argv[i])=="-o" || string(argv[i])=="--output-to-file") {
      i++;
      if (i==argc)
        goto error;
      flag_output_file = argv[i];
    } else if (string(argv[i])=="--stdlib-dir") {
      i++;
      if (i==argc)
        goto error;
      std_lib_dir = argv[i];
    } else if (string(argv[i])=="--no-flush-output") {
      flag_output_flush = false;
    } else if (string(argv[i])=="--no-output-comments") {
      flag_output_comments = false;
    } else if (string(argv[i])=="-i" ||
               string(argv[i])=="--ignore-lines" ||
               string(argv[i])=="--ignore-leading-lines") {
      ++i;
      if (i==argc)
        goto error;
      flag_ignore_lines = atoi(argv[i]);
    } else if (string(argv[i])=="--soln-sep" ||
               string(argv[i])=="--soln-separator" ||
               string(argv[i])=="--solution-separator") {
      ++i;
      if (i==argc)
        goto error;
      solution_separator = string(argv[i]);
    } else if (string(argv[i])=="--unsat-msg" ||
               string(argv[i])=="--unsatisfiable-msg") {
      ++i;
      if (i==argc)
        goto error;
      unsatisfiable_msg = string(argv[i]);
    } else if (string(argv[i])=="--unbounded-msg") {
      ++i;
      if (i==argc)
        goto error;
      unbounded_msg = string(argv[i]);
    } else if (string(argv[i])=="--unknown-msg") {
      ++i;
      if (i==argc)
        goto error;
      unknown_msg = string(argv[i]);
    } else if (string(argv[i])=="--search-complete-msg") {
      ++i;
      if (i==argc)
        goto error;
      search_complete_msg = string(argv[i]);
    } else {
      filename = argv[i++];
      if (filename.length()<=4 ||
          filename.substr(filename.length()-4,string::npos) != ".ozn") {
        std::cerr << "Invalid .ozn file " << filename << "." << std::endl;
        goto error;
      }
    }
  }

  if (std_lib_dir=="") {
    std::string mypath = FileUtils::progpath();
    if (!mypath.empty()) {
      if (FileUtils::file_exists(mypath+"/share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/share/minizinc";
      } else if (FileUtils::file_exists(mypath+"/../share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/../share/minizinc";
      } else if (FileUtils::file_exists(mypath+"/../../share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/../../share/minizinc";
      }
    }
  }

  if (std_lib_dir=="") {
    std::cerr << "Error: unknown minizinc standard library directory.\n"
    << "Specify --stdlib-dir on the command line or set the\n"
    << "MZN_STDLIB_DIR environment variable.\n";
    std::exit(EXIT_FAILURE);
  }

  includePaths.push_back(std_lib_dir+"/std/");

  {
    if (Model* outputm = parse(filename, std::vector<std::string>(), includePaths, false,
                               std::cerr)) {
      try {
        std::vector<TypeError> typeErrors;
        MiniZinc::typecheck(outputm,typeErrors);
        MiniZinc::registerBuiltins(outputm);

        typedef pair<VarDecl*,Expression*> DE;
        ASTStringMap<DE>::t declmap;
        Expression* outputExpr = NULL;
        for (unsigned int i=0; i<outputm->size(); i++) {
          if (VarDeclI* vdi = (*outputm)[i]->dyn_cast<VarDeclI>()) {
            declmap.insert(pair<ASTString,DE>(vdi->e()->id()->v(),DE(vdi->e(),vdi->e()->e())));
          } else if (OutputI* oi = (*outputm)[i]->dyn_cast<OutputI>()) {
            outputExpr = oi->e();
          }
        }

        //ostream& fout(flag_output_file.empty() ? std::cout : new fstream(flag_output_file));
        fstream file_ostream;
        if (!flag_output_file.empty())
            file_ostream.open(flag_output_file, std::fstream::out);
        ostream& fout = flag_output_file.empty() ? std::cout : file_ostream;

        string solution;
        string comments;
        for (;;) {
          if (solstream.good()) {
            string line;
            getline(solstream, line);
            if (flag_ignore_lines > 0) {
              flag_ignore_lines--;
              continue;
            }
            if (line=="----------") {
              if (outputExpr != NULL) {
                for (unsigned int i=0; i<outputm->size(); i++) {
                  if (VarDeclI* vdi = (*outputm)[i]->dyn_cast<VarDeclI>()) {
                    ASTStringMap<DE>::t::iterator it = declmap.find(vdi->e()->id()->v());
                    vdi->e()->e(it->second.second);
                    vdi->e()->evaluated(false);
                  }
                }
                Model* sm = parseFromString(solution, "solution.szn", includePaths, true, cerr);
                for (unsigned int i=0; i<sm->size(); i++) {
                  if (AssignI* ai = (*sm)[i]->dyn_cast<AssignI>()) {
                    ASTStringMap<DE>::t::iterator it = declmap.find(ai->id());
                    if (it==declmap.end()) {
                      cerr << "Error: unexpected identifier " << ai->id() << " in output\n";
                      exit(EXIT_FAILURE);
                    }
                    ai->e()->type(it->second.first->type());
                    ai->decl(it->second.first);
                    typecheck(outputm, ai);
                    if (Call* c = ai->e()->dyn_cast<Call>()) {
                      // This is an arrayXd call, make sure we get the right builtin
                      assert(c->args()[c->args().size()-1]->isa<ArrayLit>());
                      for (unsigned int i=0; i<c->args().size(); i++)
                        c->args()[i]->type(Type::parsetint());
                      c->args()[c->args().size()-1]->type(it->second.first->type());
                      c->decl(outputm->matchFn(c));
                    }
                    it->second.first->e(ai->e());
                  }
                }

                GCLock lock;
                ArrayLit* al = eval_array_lit(outputExpr);
                std::string os;
                for (unsigned int i=0; i<al->v().size(); i++) {
                  std::string s = eval_string(al->v()[i]);
                  if (!s.empty()) {
                    os = s;
                    fout << os;
                    if (flag_output_flush)
                      fout.flush();
                  }
                }
                if (!os.empty() && os[os.size()-1] != '\n')
                  fout << std::endl;
                  if (flag_output_flush)
                    fout.flush();
              }
              fout << comments;
              fout << solution_separator << std::endl;
              if (flag_output_flush)
                fout.flush();
              solution = "";
              comments = "";
            } else if (line=="==========") {
              fout << search_complete_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNSATISFIABLE=====") {
              fout << unsatisfiable_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNBOUNDED=====") {
              fout << unbounded_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNKNOWN=====") {
              fout << unknown_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else {
              solution += line+"\n";
              size_t comment_pos = line.find('%');
              if (comment_pos != string::npos) {
                comments += line.substr(comment_pos);
                comments += "\n";
              }
            }
          } else {
            break;
          }
        }
        fout << comments;
        if (flag_output_flush)
          fout.flush();
      } catch (LocationException& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        std::cerr << e.loc() << std::endl;
        exit(EXIT_FAILURE);
      } catch (Exception& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        exit(EXIT_FAILURE);
      }
      delete outputm;
    }
  }

  return 0;

error:
  std::cerr << "Usage: "<< argv[0]
            << " [<options>] <model>.ozn" << std::endl
            << std::endl
            << "Options:" << std::endl
            << "  --help, -h\n    Print this help message." << std::endl
            << "  --version\n    Print version information." << std::endl
            << "  -o <file>, --output-to-file <file>\n    Filename for generated output." << std::endl
            << "  --stdlib-dir <dir>\n    Path to MiniZinc standard library directory." << std::endl
            << "  --no-output-comments\n    Do not print comments in the FlatZinc solution stream." << std::endl
            << "  --no-flush-output\n    Don't flush output stream after every line." << std::endl
            << "  -i <n>, --ignore-lines <n>, --ignore-leading-lines <n>\n    Ignore the first <n> lines in the FlatZinc solution stream." << std::endl
            << "  --soln-sep <s>, --soln-separator <s>, --solution-separator <s>\n    Specify the string used to separate solutions.\n    The default is to use the FlatZinc solution separator,\n    \"----------\"." << std::endl
            << "  --unsat-msg <msg>, --unsatisfiable-msg <msg>\n    Specify the message to print if the model instance is\n    unsatisfiable.\n    The default is to print \"=====UNSATISFIABLE=====\"." << std::endl
            << "  --unbounded-msg <msg>\n    Specify the message to print if the objective of the\n    model instance is unbounded.\n    The default is to print \"=====UNBOUNDED=====\"." << std::endl
            << "  --unknown-msg <msg>\n    Specify the message to print if search terminates without\n    the entire search space having been explored and no\n    solution has been found.\n    The default is to print \"=====UNKNOWN=====\"." << std::endl
            << "  --search-complete-msg <msg>\n    Specify the message to print if search terminates having\n    explored the entire search space.\n    The default is to print \"==========\"." << std::endl
  ;

  exit(EXIT_FAILURE);
}
<commit_msg>Need to use c_str for older c++ stdlibs<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <iostream>
#include <fstream>

#include <minizinc/model.hh>
#include <minizinc/parser.hh>
#include <minizinc/prettyprinter.hh>
#include <minizinc/typecheck.hh>
#include <minizinc/astexception.hh>
#include <minizinc/hash.hh>
#include <minizinc/eval_par.hh>
#include <minizinc/builtins.hh>
#include <minizinc/file_utils.hh>

using namespace MiniZinc;
using namespace std;

int main(int argc, char** argv) {
  string filename;

  string flag_output_file;

  bool flag_output_comments = true;
  bool flag_output_flush = true;
  string solfile;
  int flag_ignore_lines = 0;
  istream& solstream = cin;

  string solution_separator = "----------";
  string unsatisfiable_msg  = "=====UNSATISFIABLE=====";
  string unbounded_msg      = "=====UNBOUNDED=====";
  string unknown_msg        = "=====UNKNOWN=====";
  string search_complete_msg= "==========";

  vector<string> includePaths;
  string std_lib_dir;
  if (char* MZNSTDLIBDIR = getenv("MZN_STDLIB_DIR")) {
    std_lib_dir = string(MZNSTDLIBDIR);
  }

  if (argc < 2)
    goto error;

  GC::init();

  for (int i=1; i<argc; i++) {
    if (string(argv[i])==string("--version")) {
      std::cout << "NICTA MiniZinc solution printing tool, version "
      << MZN_VERSION_MAJOR << "." << MZN_VERSION_MINOR << "." << MZN_VERSION_PATCH << std::endl;
      std::cout << "Copyright (C) 2014 Monash University and NICTA" << std::endl;
      std::exit(EXIT_SUCCESS);
    }
    if (string(argv[i])==string("-h") || string(argv[i])==string("--help")) {
        goto error;
    } else if (string(argv[i])=="-o" || string(argv[i])=="--output-to-file") {
      i++;
      if (i==argc)
        goto error;
      flag_output_file = argv[i];
    } else if (string(argv[i])=="--stdlib-dir") {
      i++;
      if (i==argc)
        goto error;
      std_lib_dir = argv[i];
    } else if (string(argv[i])=="--no-flush-output") {
      flag_output_flush = false;
    } else if (string(argv[i])=="--no-output-comments") {
      flag_output_comments = false;
    } else if (string(argv[i])=="-i" ||
               string(argv[i])=="--ignore-lines" ||
               string(argv[i])=="--ignore-leading-lines") {
      ++i;
      if (i==argc)
        goto error;
      flag_ignore_lines = atoi(argv[i]);
    } else if (string(argv[i])=="--soln-sep" ||
               string(argv[i])=="--soln-separator" ||
               string(argv[i])=="--solution-separator") {
      ++i;
      if (i==argc)
        goto error;
      solution_separator = string(argv[i]);
    } else if (string(argv[i])=="--unsat-msg" ||
               string(argv[i])=="--unsatisfiable-msg") {
      ++i;
      if (i==argc)
        goto error;
      unsatisfiable_msg = string(argv[i]);
    } else if (string(argv[i])=="--unbounded-msg") {
      ++i;
      if (i==argc)
        goto error;
      unbounded_msg = string(argv[i]);
    } else if (string(argv[i])=="--unknown-msg") {
      ++i;
      if (i==argc)
        goto error;
      unknown_msg = string(argv[i]);
    } else if (string(argv[i])=="--search-complete-msg") {
      ++i;
      if (i==argc)
        goto error;
      search_complete_msg = string(argv[i]);
    } else {
      filename = argv[i++];
      if (filename.length()<=4 ||
          filename.substr(filename.length()-4,string::npos) != ".ozn") {
        std::cerr << "Invalid .ozn file " << filename << "." << std::endl;
        goto error;
      }
    }
  }

  if (std_lib_dir=="") {
    std::string mypath = FileUtils::progpath();
    if (!mypath.empty()) {
      if (FileUtils::file_exists(mypath+"/share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/share/minizinc";
      } else if (FileUtils::file_exists(mypath+"/../share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/../share/minizinc";
      } else if (FileUtils::file_exists(mypath+"/../../share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/../../share/minizinc";
      }
    }
  }

  if (std_lib_dir=="") {
    std::cerr << "Error: unknown minizinc standard library directory.\n"
    << "Specify --stdlib-dir on the command line or set the\n"
    << "MZN_STDLIB_DIR environment variable.\n";
    std::exit(EXIT_FAILURE);
  }

  includePaths.push_back(std_lib_dir+"/std/");

  {
    if (Model* outputm = parse(filename, std::vector<std::string>(), includePaths, false,
                               std::cerr)) {
      try {
        std::vector<TypeError> typeErrors;
        MiniZinc::typecheck(outputm,typeErrors);
        MiniZinc::registerBuiltins(outputm);

        typedef pair<VarDecl*,Expression*> DE;
        ASTStringMap<DE>::t declmap;
        Expression* outputExpr = NULL;
        for (unsigned int i=0; i<outputm->size(); i++) {
          if (VarDeclI* vdi = (*outputm)[i]->dyn_cast<VarDeclI>()) {
            declmap.insert(pair<ASTString,DE>(vdi->e()->id()->v(),DE(vdi->e(),vdi->e()->e())));
          } else if (OutputI* oi = (*outputm)[i]->dyn_cast<OutputI>()) {
            outputExpr = oi->e();
          }
        }

        //ostream& fout(flag_output_file.empty() ? std::cout : new fstream(flag_output_file));
        fstream file_ostream;
        if (!flag_output_file.empty())
            file_ostream.open(flag_output_file.c_str(), std::fstream::out);
        ostream& fout = flag_output_file.empty() ? std::cout : file_ostream;

        string solution;
        string comments;
        for (;;) {
          if (solstream.good()) {
            string line;
            getline(solstream, line);
            if (flag_ignore_lines > 0) {
              flag_ignore_lines--;
              continue;
            }
            if (line=="----------") {
              if (outputExpr != NULL) {
                for (unsigned int i=0; i<outputm->size(); i++) {
                  if (VarDeclI* vdi = (*outputm)[i]->dyn_cast<VarDeclI>()) {
                    ASTStringMap<DE>::t::iterator it = declmap.find(vdi->e()->id()->v());
                    vdi->e()->e(it->second.second);
                    vdi->e()->evaluated(false);
                  }
                }
                Model* sm = parseFromString(solution, "solution.szn", includePaths, true, cerr);
                for (unsigned int i=0; i<sm->size(); i++) {
                  if (AssignI* ai = (*sm)[i]->dyn_cast<AssignI>()) {
                    ASTStringMap<DE>::t::iterator it = declmap.find(ai->id());
                    if (it==declmap.end()) {
                      cerr << "Error: unexpected identifier " << ai->id() << " in output\n";
                      exit(EXIT_FAILURE);
                    }
                    ai->e()->type(it->second.first->type());
                    ai->decl(it->second.first);
                    typecheck(outputm, ai);
                    if (Call* c = ai->e()->dyn_cast<Call>()) {
                      // This is an arrayXd call, make sure we get the right builtin
                      assert(c->args()[c->args().size()-1]->isa<ArrayLit>());
                      for (unsigned int i=0; i<c->args().size(); i++)
                        c->args()[i]->type(Type::parsetint());
                      c->args()[c->args().size()-1]->type(it->second.first->type());
                      c->decl(outputm->matchFn(c));
                    }
                    it->second.first->e(ai->e());
                  }
                }

                GCLock lock;
                ArrayLit* al = eval_array_lit(outputExpr);
                std::string os;
                for (unsigned int i=0; i<al->v().size(); i++) {
                  std::string s = eval_string(al->v()[i]);
                  if (!s.empty()) {
                    os = s;
                    fout << os;
                    if (flag_output_flush)
                      fout.flush();
                  }
                }
                if (!os.empty() && os[os.size()-1] != '\n')
                  fout << std::endl;
                  if (flag_output_flush)
                    fout.flush();
              }
              fout << comments;
              fout << solution_separator << std::endl;
              if (flag_output_flush)
                fout.flush();
              solution = "";
              comments = "";
            } else if (line=="==========") {
              fout << search_complete_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNSATISFIABLE=====") {
              fout << unsatisfiable_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNBOUNDED=====") {
              fout << unbounded_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNKNOWN=====") {
              fout << unknown_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else {
              solution += line+"\n";
              size_t comment_pos = line.find('%');
              if (comment_pos != string::npos) {
                comments += line.substr(comment_pos);
                comments += "\n";
              }
            }
          } else {
            break;
          }
        }
        fout << comments;
        if (flag_output_flush)
          fout.flush();
      } catch (LocationException& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        std::cerr << e.loc() << std::endl;
        exit(EXIT_FAILURE);
      } catch (Exception& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        exit(EXIT_FAILURE);
      }
      delete outputm;
    }
  }

  return 0;

error:
  std::cerr << "Usage: "<< argv[0]
            << " [<options>] <model>.ozn" << std::endl
            << std::endl
            << "Options:" << std::endl
            << "  --help, -h\n    Print this help message." << std::endl
            << "  --version\n    Print version information." << std::endl
            << "  -o <file>, --output-to-file <file>\n    Filename for generated output." << std::endl
            << "  --stdlib-dir <dir>\n    Path to MiniZinc standard library directory." << std::endl
            << "  --no-output-comments\n    Do not print comments in the FlatZinc solution stream." << std::endl
            << "  --no-flush-output\n    Don't flush output stream after every line." << std::endl
            << "  -i <n>, --ignore-lines <n>, --ignore-leading-lines <n>\n    Ignore the first <n> lines in the FlatZinc solution stream." << std::endl
            << "  --soln-sep <s>, --soln-separator <s>, --solution-separator <s>\n    Specify the string used to separate solutions.\n    The default is to use the FlatZinc solution separator,\n    \"----------\"." << std::endl
            << "  --unsat-msg <msg>, --unsatisfiable-msg <msg>\n    Specify the message to print if the model instance is\n    unsatisfiable.\n    The default is to print \"=====UNSATISFIABLE=====\"." << std::endl
            << "  --unbounded-msg <msg>\n    Specify the message to print if the objective of the\n    model instance is unbounded.\n    The default is to print \"=====UNBOUNDED=====\"." << std::endl
            << "  --unknown-msg <msg>\n    Specify the message to print if search terminates without\n    the entire search space having been explored and no\n    solution has been found.\n    The default is to print \"=====UNKNOWN=====\"." << std::endl
            << "  --search-complete-msg <msg>\n    Specify the message to print if search terminates having\n    explored the entire search space.\n    The default is to print \"==========\"." << std::endl
  ;

  exit(EXIT_FAILURE);
}
<|endoftext|>


<commit_before>
// MainFrm.cpp : CMainFrame ʵ
//

#include "stdafx.h"
#include "02Menu.h"

#include "MainFrm.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CMainFrame

IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	ON_WM_CREATE()
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // ״ָ̬ʾ
	ID_INDICATOR_CAPS,
	ID_INDICATOR_NUM,
	ID_INDICATOR_SCRL,
};

// CMainFrame /

CMainFrame::CMainFrame()
{
	// TODO: ڴӳԱʼ
}

CMainFrame::~CMainFrame()
{
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	if (!m_wndStatusBar.Create(this))
	{
		TRACE0("δܴ״̬\n");
		return -1;      // δܴ
	}
	m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));

	CMenu menu;
	menu.CreateMenu();
	//GetMenu()->AppendMenu(MF_POPUP, (UINT_PTR)menu.m_hMenu, _T("Test"));
	GetMenu()->InsertMenu(2, MF_POPUP | MF_BYPOSITION, (UINT_PTR)menu.m_hMenu, _T("Test"));
	menu.AppendMenu(MF_STRING, 111, _T("Hello"));
	menu.AppendMenu(MF_STRING, 112, _T("Bye"));
	menu.AppendMenu(MF_STRING, 113, _T("MyBole"));

	menu.Detach();

	return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	// TODO: ڴ˴ͨ޸
	//  CREATESTRUCT cs ޸Ĵʽ

	return TRUE;
}

// CMainFrame

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWnd::Dump(dc);
}
#endif //_DEBUG

// CMainFrame Ϣ
<commit_msg><需求实现>删除菜单项 需求： 删除菜单项 实现： DeleteMenu()<commit_after>
// MainFrm.cpp : CMainFrame ʵ
//

#include "stdafx.h"
#include "02Menu.h"

#include "MainFrm.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CMainFrame

IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	ON_WM_CREATE()
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // ״ָ̬ʾ
	ID_INDICATOR_CAPS,
	ID_INDICATOR_NUM,
	ID_INDICATOR_SCRL,
};

// CMainFrame /

CMainFrame::CMainFrame()
{
	// TODO: ڴӳԱʼ
}

CMainFrame::~CMainFrame()
{
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	if (!m_wndStatusBar.Create(this))
	{
		TRACE0("δܴ״̬\n");
		return -1;      // δܴ
	}
	m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));

	CMenu menu;
	menu.CreateMenu();
	//GetMenu()->AppendMenu(MF_POPUP, (UINT_PTR)menu.m_hMenu, _T("Test"));
	GetMenu()->InsertMenu(2, MF_POPUP | MF_BYPOSITION, (UINT_PTR)menu.m_hMenu, _T("Test"));
	menu.AppendMenu(MF_STRING, 111, _T("Hello"));
	menu.AppendMenu(MF_STRING, 112, _T("Bye"));
	menu.AppendMenu(MF_STRING, 113, _T("MyBole"));

	menu.Detach();

	GetMenu()->DeleteMenu(2, MF_BYPOSITION);

	return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	// TODO: ڴ˴ͨ޸
	//  CREATESTRUCT cs ޸Ĵʽ

	return TRUE;
}

// CMainFrame

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWnd::Dump(dc);
}
#endif //_DEBUG

// CMainFrame Ϣ
<|endoftext|>


<commit_before>/*******************************************************************************
 *  Code contributed to the webinos project
 *
 * 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.
 *
 * Copyright 2012 Torsec -Computer and network security group-
 * Politecnico di Torino
 *
 ******************************************************************************/

#include "AuthorizationsSet.h"
#include "../../debug.h"

AuthorizationsSet::AuthorizationsSet(TiXmlElement* authorizationsset){

	// AuthzUseForPurpose Tag
	if (authorizationsset->FirstChild(authzTag)) {
		LOGD("AuthorizationsSet constructor, AuthzUseForPurpose found");
		TiXmlElement * child = static_cast<TiXmlElement*>(authorizationsset->FirstChild(authzTag));
		for(child = static_cast<TiXmlElement*>(child->FirstChild(purposeTag)); child;
				child = static_cast<TiXmlElement*>(child->NextSibling(purposeTag))) {
			LOGD("Purpose %s found", child->GetText());
			authzuseforpurpose.push_back(child->GetText());
		}
	}
	else{
		LOGD("AuthorizationsSet constructor, AuthzUseForPurpose not found");
	}
}

AuthorizationsSet::~AuthorizationsSet(){
}

bool AuthorizationsSet::evaluate(Request * req){
	LOGD("Evaluating AuthorizationsSet");

	vector<bool> purpose_satisfied(arraysize(ontology_vector), false);
	vector<bool> purpose = req->getPurposeAttrs();
	unsigned int i = 0;

	// invalid purposes vector
	if (purpose.size() != arraysize(ontology_vector)) {
		LOGD("AuthorizationsSet: invalid purposes vector");
		return false;
	}

	for(vector<bool>::const_iterator it = purpose.begin(); it!= purpose.end(); it++){
		// Purpose requested
		if (*it == true){
			purpose_satisfied[i] = false;
			LOGD("AuthorizationsSet: purpose %d is true", i);
			for(unsigned int j=0; j<authzuseforpurpose.size(); j++){
				LOGD("AuthorizationsSet: checking authzuseforpurpose %d, %s", j, authzuseforpurpose[j].c_str());
				if (ontology_vector[i].compare(authzuseforpurpose[j]) == 0){
					// Purpose requested and satisfied
					purpose_satisfied[i] = true;
					break;
				}
			}
		}
		// Purpose not requested
		else {
			LOGD("AuthorizationsSet: purpose %d is false", i);
			purpose_satisfied[i] = true;
		}
		i++;
	}

	for (i=0; i < arraysize(ontology_vector); i++){
		if (purpose_satisfied[i] == false)
			// A purpose is not satisfied
			return false;
	}
	// All purposes are satisfied
	return true;
}
<commit_msg>Added empty purpose tag management<commit_after>/*******************************************************************************
 *  Code contributed to the webinos project
 *
 * 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.
 *
 * Copyright 2012 Torsec -Computer and network security group-
 * Politecnico di Torino
 *
 ******************************************************************************/

#include "AuthorizationsSet.h"
#include "../../debug.h"

AuthorizationsSet::AuthorizationsSet(TiXmlElement* authorizationsset){

	// AuthzUseForPurpose Tag
	if (authorizationsset->FirstChild(authzTag)) {
		LOGD("AuthorizationsSet constructor, AuthzUseForPurpose found");
		TiXmlElement * child = static_cast<TiXmlElement*>(authorizationsset->FirstChild(authzTag));
		for(child = static_cast<TiXmlElement*>(child->FirstChild(purposeTag)); child;
				child = static_cast<TiXmlElement*>(child->NextSibling(purposeTag))) {
			if (child->GetText()) {
				LOGD("Purpose %s found", child->GetText());
				authzuseforpurpose.push_back(child->GetText());
			}
			else {
				LOGD("Empty purpose tag, all purposes allowed");
				authzuseforpurpose.clear();
				for (unsigned int i = 0; i < arraysize(ontology_vector); i++) {
					authzuseforpurpose.push_back(ontology_vector[i]);
				}
				break;
			}
		}
	}
	else{
		LOGD("AuthorizationsSet constructor, AuthzUseForPurpose not found");
	}
}

AuthorizationsSet::~AuthorizationsSet(){
}

bool AuthorizationsSet::evaluate(Request * req){
	LOGD("Evaluating AuthorizationsSet");

	vector<bool> purpose_satisfied(arraysize(ontology_vector), false);
	vector<bool> purpose = req->getPurposeAttrs();
	unsigned int i = 0;

	// invalid purposes vector
	if (purpose.size() != arraysize(ontology_vector)) {
		LOGD("AuthorizationsSet: invalid purposes vector");
		return false;
	}

	for(vector<bool>::const_iterator it = purpose.begin(); it!= purpose.end(); it++){
		// Purpose requested
		if (*it == true){
			purpose_satisfied[i] = false;
			LOGD("AuthorizationsSet: purpose %d is true", i);
			for(unsigned int j=0; j<authzuseforpurpose.size(); j++){
				LOGD("AuthorizationsSet: checking authzuseforpurpose %d, %s", j, authzuseforpurpose[j].c_str());
				if (ontology_vector[i].compare(authzuseforpurpose[j]) == 0){
					// Purpose requested and satisfied
					purpose_satisfied[i] = true;
					break;
				}
			}
		}
		// Purpose not requested
		else {
			LOGD("AuthorizationsSet: purpose %d is false", i);
			purpose_satisfied[i] = true;
		}
		i++;
	}

	for (i=0; i < arraysize(ontology_vector); i++){
		if (purpose_satisfied[i] == false)
			// A purpose is not satisfied
			return false;
	}
	// All purposes are satisfied
	return true;
}
<|endoftext|>


<commit_before>#ifndef GNR_ANYFUNCTION_HPP
# define GNR_ANYFUNCTION_HPP
# pragma once

#include <cassert>

#include <cstdint>

#include <functional>

#include "many.hpp"

#include "some.hpp"

namespace gnr
{

namespace
{

template <typename>
struct signature
{
};

//
template <typename>
struct class_ref;

//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...)>
{
  using type = C&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const>
{
  using type = C const&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile>
{
  using type = C const volatile&;
};

//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) &>
{
  using type = C&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const &>
{
  using type = C const&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile &>
{
  using type = C const volatile&;
};

//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) &&>
{
  using type = C&&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const &&>
{
  using type = C const&&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile &&>
{
  using type = C const volatile&&;
};

template <typename F>
using class_ref_t = typename class_ref<F>::type;

//
template <typename>
struct remove_cv_seq;

//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...)>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile>
{
  using type = R(A...);
};

//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) &>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const &>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile &>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile &>
{
  using type = R(A...);
};

//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) &&>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const &&>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile &&>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile &&>
{
  using type = R(A...);
};

template <typename F>
constexpr inline auto extract_signature(F* const) noexcept
{
  return signature<typename remove_cv_seq<F>::type>();
}

template <typename C, typename F>
constexpr inline auto extract_signature(F C::* const) noexcept
{
  return signature<typename remove_cv_seq<F>::type>();
}

template <typename F>
constexpr inline auto extract_signature(F const&) noexcept ->
  decltype(&F::operator(), extract_signature(&F::operator()))
{
  return extract_signature(&F::operator());
}

}

template <typename Any = gnr::some<4 * sizeof(void*)>>
class any_function
{
  using typeid_t = std::uintptr_t;

  #if defined(__GNUC__)
  template <typename T>
  static typeid_t type_id() noexcept
  {
    return typeid_t(type_id<T>);
  }
  #else
  template <typename T>
  static typeid_t type_id() noexcept
  {
    static char const type_id{};

    return typeid_t(&type_id);
  }
  #endif // __GNUC__

  void (*f_)(Any const&, void const*, Any&);

  Any any_;

#ifndef NDEBUG
  typeid_t type_id_;
#endif // NDEBUG

  template <typename R, typename ...A, typename F, std::size_t ...I>
  static std::enable_if_t<!std::is_void<R>{}>
  do_invoke(F&& f,
    gnr::many<A...> const& t,
    Any& r,
    std::index_sequence<I...> const) noexcept(
#if __cplusplus <= 201402L
      noexcept(f(std::get<I>(t)...))
#else
      noexcept(std::invoke(f, std::get<I>(t)...))
#endif
    )
  {
#if __cplusplus <= 201402L
    r = f(std::get<I>(t)...);
#else
    r = std::invoke(f, std::get<I>(t)...);
#endif
  }

  template <typename R, typename ...A, typename F, std::size_t ...I>
  static std::enable_if_t<std::is_void<R>{}>
  do_invoke(F&& f,
    gnr::many<A...> const& t,
    Any&,
    std::index_sequence<I...> const) noexcept(
#if __cplusplus <= 201402L
      noexcept(f(std::get<I>(t)...))
#else
      noexcept(std::invoke(f, std::get<I>(t)...))
#endif
    )
  {
#if __cplusplus <= 201402L
    f(std::get<I>(t)...);
#else
    std::invoke(f, std::get<I>(t)...);
#endif
  }

  template <typename F, typename R, typename ...A>
  static std::enable_if_t<!std::is_member_function_pointer<F>{}>
  invoker(Any const& any,
    void const* const v,
    Any& r) noexcept(
    noexcept(do_invoke<R, A...>(std::get<F>(any),
      *static_cast<gnr::many<A...> const*>(v),
      r,
      std::make_index_sequence<sizeof...(A)>())
    )
  )
  {
    do_invoke<R, A...>(std::get<F>(any),
      *static_cast<gnr::many<A...> const*>(v),
      r,
      std::make_index_sequence<sizeof...(A)>()
    );
  }

  template <typename F, typename R, typename ...A>
  static std::enable_if_t<std::is_member_function_pointer<F>{}>
  invoker(Any const& any,
    void const* const v,
    Any& r) noexcept(
    noexcept(do_invoke<R, A...>(std::get<F>(any),
      *static_cast<gnr::many<class_ref_t<F>, A...> const*>(v),
      r,
      std::make_index_sequence<sizeof...(A) + 1>())
    )
  )
  {
    do_invoke<R, A...>(std::get<F>(any),
      *static_cast<gnr::many<class_ref_t<F>, A...> const*>(v),
      r,
      std::make_index_sequence<sizeof...(A) + 1>()
    );
  }

  template <typename F, typename R, typename ...A>
  std::enable_if_t<!std::is_member_function_pointer<F>{}>
  assign(signature<R(A...)>) noexcept
  {
    f_ = invoker<F, R, A...>;

#ifndef NDEBUG
    type_id_ = type_id<gnr::many<A...>>();
#endif // NDEBUG
  }

  template <typename F, typename R, typename ...A>
  std::enable_if_t<std::is_member_function_pointer<F>{}>
  assign(signature<R(A...)>) noexcept
  {
    f_ = invoker<F, R, A...>;

#ifndef NDEBUG
    type_id_ = type_id<gnr::many<class_ref_t<F>, A...>>();
#endif // NDEBUG
  }

public:
  template <typename T>
  struct arg_type
  {
    using type = std::decay_t<T>;
  };

  template <typename T>
  struct arg_type<std::reference_wrapper<T> >
  {
    using type = T&;
  };

  template <typename T>
  using arg_type_t = typename arg_type<T>::type;

  any_function() = default;

  template <typename F,
    typename = std::enable_if_t<
      !std::is_same<std::decay_t<F>, any_function>{}
    >
  >
  any_function(F&& f) :
    any_(std::forward<F>(f))
  {
    assign<F>(extract_signature(std::forward<F>(f)));
  }

  any_function(any_function const&) = default;

  any_function(any_function&&) = default;

  any_function& operator=(any_function const&) = default;

  any_function& operator=(any_function&&) = default;

  template <typename F,
    typename = std::enable_if_t<
      !std::is_same<std::decay_t<F>, any_function>{}
    >
  >
  any_function& operator=(F&& f)
  {
    assign(std::forward<F>(f));

    return *this;
  }

  explicit operator bool() const noexcept
  {
    return bool(any_);
  }

  bool empty() const noexcept
  {
    return !*this;
  }

  template <typename F>
  void assign(F&& f)
  {
    any_ = std::forward<F>(f);

    assign<F>(extract_signature(std::forward<F>(f)));
  }

  template <typename ...A>
  auto operator()(A&& ...args) const
  {
    return invoke(std::forward<A>(args)...);
  }

  template <typename ...A>
  Any apply(gnr::many<A...> const& m) const
  {
#ifndef NDEBUG
    assert(type_id<gnr::many<A...> >() == type_id_);
#endif // NDEBUG

    Any result;

    f_(any_, &m, result);

    return result;
  }

  template <typename ...A>
  auto invoke(A&& ...args) const
  {
    return apply(gnr::many<arg_type_t<A>...>{std::forward<A>(args)...});
  }
};

}

#endif // GNR_ANYFUNCTION_HPP
<commit_msg>some fixes<commit_after>#ifndef GNR_ANYFUNCTION_HPP
# define GNR_ANYFUNCTION_HPP
# pragma once

#include <cassert>

#include <cstdint>

#include <functional>

#include "many.hpp"

#include "some.hpp"

namespace gnr
{

namespace
{

template <typename>
struct signature
{
};

//
template <typename>
struct class_ref;

//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...)>
{
  using type = C&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const>
{
  using type = C const&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile>
{
  using type = C const volatile&;
};

//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) &>
{
  using type = C&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const &>
{
  using type = C const&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile &>
{
  using type = C const volatile&;
};

//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) &&>
{
  using type = C&&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const &&>
{
  using type = C const&&;
};

template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile &&>
{
  using type = C const volatile&&;
};

template <typename F>
using class_ref_t = typename class_ref<F>::type;

//
template <typename>
struct remove_cv_seq;

//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...)>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile>
{
  using type = R(A...);
};

//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) &>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const &>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile &>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile &>
{
  using type = R(A...);
};

//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) &&>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const &&>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile &&>
{
  using type = R(A...);
};

template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile &&>
{
  using type = R(A...);
};

template <typename F>
constexpr inline auto extract_signature(F* const) noexcept
{
  return signature<typename remove_cv_seq<F>::type>();
}

template <typename C, typename F>
constexpr inline auto extract_signature(F C::* const) noexcept
{
  return signature<typename remove_cv_seq<F>::type>();
}

template <typename F>
constexpr inline auto extract_signature(F const&) noexcept ->
  decltype(&F::operator(), extract_signature(&F::operator()))
{
  return extract_signature(&F::operator());
}

}

template <typename Any = gnr::some<4 * sizeof(void*)>>
class any_function
{
  using typeid_t = void(*)();

  template <typename T>
  static typeid_t type_id() noexcept
  {
    return typeid_t(type_id<T>);
  }

  void (*f_)(Any const&, void const*, Any&);

  Any any_;

#ifndef NDEBUG
  typeid_t type_id_;
#endif // NDEBUG

  template <typename R, typename ...A, typename F, std::size_t ...I>
  static std::enable_if_t<!std::is_void<R>{}>
  do_invoke(F&& f,
    gnr::many<A...> const& t,
    Any& r,
    std::index_sequence<I...> const) noexcept(
#if __cplusplus <= 201402L
      noexcept(f(std::get<I>(t)...))
#else
      noexcept(std::invoke(f, std::get<I>(t)...))
#endif
    )
  {
#if __cplusplus <= 201402L
    r = f(std::get<I>(t)...);
#else
    r = std::invoke(f, std::get<I>(t)...);
#endif
  }

  template <typename R, typename ...A, typename F, std::size_t ...I>
  static std::enable_if_t<std::is_void<R>{}>
  do_invoke(F&& f,
    gnr::many<A...> const& t,
    Any&,
    std::index_sequence<I...> const) noexcept(
#if __cplusplus <= 201402L
      noexcept(f(std::get<I>(t)...))
#else
      noexcept(std::invoke(f, std::get<I>(t)...))
#endif
    )
  {
#if __cplusplus <= 201402L
    f(std::get<I>(t)...);
#else
    std::invoke(f, std::get<I>(t)...);
#endif
  }

  template <typename F, typename R, typename ...A>
  static std::enable_if_t<!std::is_member_function_pointer<F>{}>
  invoker(Any const& any,
    void const* const v,
    Any& r) noexcept(
    noexcept(do_invoke<R, A...>(std::get<F>(any),
      *static_cast<gnr::many<A...> const*>(v),
      r,
      std::make_index_sequence<sizeof...(A)>())
    )
  )
  {
    do_invoke<R, A...>(std::get<F>(any),
      *static_cast<gnr::many<A...> const*>(v),
      r,
      std::make_index_sequence<sizeof...(A)>()
    );
  }

  template <typename F, typename R, typename ...A>
  static std::enable_if_t<std::is_member_function_pointer<F>{}>
  invoker(Any const& any,
    void const* const v,
    Any& r) noexcept(
    noexcept(do_invoke<R, A...>(std::get<F>(any),
      *static_cast<gnr::many<class_ref_t<F>, A...> const*>(v),
      r,
      std::make_index_sequence<sizeof...(A) + 1>())
    )
  )
  {
    do_invoke<R, A...>(std::get<F>(any),
      *static_cast<gnr::many<class_ref_t<F>, A...> const*>(v),
      r,
      std::make_index_sequence<sizeof...(A) + 1>()
    );
  }

  template <typename F, typename R, typename ...A>
  std::enable_if_t<!std::is_member_function_pointer<F>{}>
  assign(signature<R(A...)>) noexcept
  {
    f_ = invoker<F, R, A...>;

#ifndef NDEBUG
    type_id_ = type_id<gnr::many<A...>>();
#endif // NDEBUG
  }

  template <typename F, typename R, typename ...A>
  std::enable_if_t<std::is_member_function_pointer<F>{}>
  assign(signature<R(A...)>) noexcept
  {
    f_ = invoker<F, R, A...>;

#ifndef NDEBUG
    type_id_ = type_id<gnr::many<class_ref_t<F>, A...>>();
#endif // NDEBUG
  }

public:
  template <typename T>
  struct arg_type
  {
    using type = std::decay_t<T>;
  };

  template <typename T>
  struct arg_type<std::reference_wrapper<T> >
  {
    using type = T&;
  };

  template <typename T>
  using arg_type_t = typename arg_type<T>::type;

  any_function() = default;

  template <typename F,
    typename = std::enable_if_t<
      !std::is_same<std::decay_t<F>, any_function>{}
    >
  >
  any_function(F&& f) :
    any_(std::forward<F>(f))
  {
    assign<F>(extract_signature(std::forward<F>(f)));
  }

  any_function(any_function const&) = default;

  any_function(any_function&&) = default;

  any_function& operator=(any_function const&) = default;

  any_function& operator=(any_function&&) = default;

  template <typename F,
    typename = std::enable_if_t<
      !std::is_same<std::decay_t<F>, any_function>{}
    >
  >
  any_function& operator=(F&& f)
  {
    assign(std::forward<F>(f));

    return *this;
  }

  explicit operator bool() const noexcept
  {
    return bool(any_);
  }

  bool empty() const noexcept
  {
    return !*this;
  }

  template <typename F>
  void assign(F&& f)
  {
    any_ = std::forward<F>(f);

    assign<F>(extract_signature(std::forward<F>(f)));
  }

  template <typename ...A>
  auto operator()(A&& ...args) const
  {
    return invoke(std::forward<A>(args)...);
  }

  template <typename ...A>
  Any apply(gnr::many<A...> const& m) const
  {
#ifndef NDEBUG
    assert(type_id<gnr::many<A...> >() == type_id_);
#endif // NDEBUG

    Any result;

    f_(any_, &m, result);

    return result;
  }

  template <typename ...A>
  auto invoke(A&& ...args) const
  {
    return apply(gnr::many<arg_type_t<A>...>{std::forward<A>(args)...});
  }
};

}

#endif // GNR_ANYFUNCTION_HPP
<|endoftext|>


<commit_before>#include <string>
#include <fstream>
#include "io/BmpIO.hpp"
#include "matrix/Matrix.hpp"

using namespace sipl;

MatrixX<uint8_t> BmpIO::read(const char* filename)
{
    return read(std::string(filename));
}

MatrixX<uint8_t> BmpIO::read(const std::string& filename)
{
    std::ifstream stream{filename, std::ios::binary};
    if (!stream) {
        throw IOException("Could not open file '" + filename + "'for reading");
    }

    // Get total file length
    stream.seekg(0, std::ios::end);
    std::streampos file_length = stream.tellg();
    stream.seekg(0, std::ios::beg);
    std::cout << "file length: " << file_length << std::endl;

    // Read into buffer
    std::unique_ptr<char[]> buf(new char[file_length]);
    stream.read(reinterpret_cast<char*>(buf.get()), file_length);

    // Fill BMPFILEHEADER and BMPINFOHEADER structs
    BITMAPFILEHEADER* file_header =
        reinterpret_cast<BITMAPFILEHEADER*>(buf.get());
    BITMAPINFOHEADER* info_header = reinterpret_cast<BITMAPINFOHEADER*>(
        buf.get() + sizeof(BITMAPFILEHEADER));

    std::cout << "bfSize:        " << file_header->bfSize << std::endl;
    std::cout << "bfOffBits:     " << file_header->bfOffBits << std::endl;
    std::cout << "biSize:        " << info_header->biSize << std::endl;
    std::cout << "biWidth:       " << info_header->biWidth << std::endl;
    std::cout << "biHeight:      " << info_header->biHeight << std::endl;
    std::cout << "biBitCount:    " << info_header->biBitCount << std::endl;
    std::cout << "biCompression: " << info_header->biCompression << std::endl;
    std::cout << "biSizeImage:   " << info_header->biSizeImage << std::endl;

    // Fill the new matrix
    const auto data_offset = file_header->bfOffBits;
    MatrixX<uint8_t> img(info_header->biHeight, info_header->biWidth);
    const auto data_start = buf.get() + data_offset;
    const auto data_end = data_start + info_header->biSizeImage;
    std::cout << "data start: " << std::to_string(data_start - buf.get())
              << std::endl;
    std::cout << "data end:   " << std::to_string(data_end - buf.get())
              << std::endl;
    std::copy(data_start, data_end, img.bytes());
    std::cout << buf.get()[10000] << std::endl;
    return img;
}

/*
void write(const MatrixX<uint8_t>& mat, const char* filename)
{
    write(mat, std::string(filename));
}
*/

// void write(const MatrixX<uint8_t>& mat, const std::string& filename) {}
<commit_msg>Implement backward reading since BPM is dumb and stores the rows in the reverse order you'd expect<commit_after>#include <string>
#include <fstream>
#include "io/BmpIO.hpp"
#include "matrix/Matrix.hpp"

using namespace sipl;

MatrixX<uint8_t> BmpIO::read(const char* filename)
{
    return read(std::string(filename));
}

MatrixX<uint8_t> BmpIO::read(const std::string& filename)
{
    std::ifstream stream{filename, std::ios::binary};
    if (!stream) {
        throw IOException("Could not open file '" + filename + "'for reading");
    }

    // Get total file length
    stream.seekg(0, std::ios::end);
    std::streampos file_length = stream.tellg();
    stream.seekg(0, std::ios::beg);
    // std::cout << "file length: " << file_length << std::endl;

    // Read into buffer
    std::unique_ptr<char[]> buf(new char[file_length]);
    stream.read(reinterpret_cast<char*>(buf.get()), file_length);

    // Fill BMPFILEHEADER and BMPINFOHEADER structs
    BITMAPFILEHEADER* file_header =
        reinterpret_cast<BITMAPFILEHEADER*>(buf.get());
    BITMAPINFOHEADER* info_header = reinterpret_cast<BITMAPINFOHEADER*>(
        buf.get() + sizeof(BITMAPFILEHEADER));

    /*
    std::cout << "bfSize:        " << file_header->bfSize << std::endl;
    std::cout << "bfOffBits:     " << file_header->bfOffBits << std::endl;
    std::cout << "biSize:        " << info_header->biSize << std::endl;
    std::cout << "biWidth:       " << info_header->biWidth << std::endl;
    std::cout << "biHeight:      " << info_header->biHeight << std::endl;
    std::cout << "biBitCount:    " << info_header->biBitCount << std::endl;
    std::cout << "biCompression: " << info_header->biCompression << std::endl;
    std::cout << "biSizeImage:   " << info_header->biSizeImage << std::endl;
    */

    // Fill the new matrix
    // XXX There's a segfault on OSX somewhere in here, not sure where...
    // ASan nor Valgrind report anything useful on OSX
    const auto data_offset = file_header->bfOffBits;
    MatrixX<uint8_t> img(info_header->biHeight, info_header->biWidth);
    const auto data_start = buf.get() + data_offset;

    // Need to read in rows in reverse order because they put the origin in the
    // "normal" position, not in the "image" position
    for (int32_t i = img.dims[0] - 1; i >= 0; --i) {
        const auto row_start = data_start + i * img.dims[1];
        const auto row_end = row_start + info_header->biWidth;
        const auto mat_start =
            img.bytes() + (img.dims[0] - 1 - i) * img.dims[1];
        std::copy(row_start, row_end, mat_start);
    }

    return img;
}

/*
void write(const MatrixX<uint8_t>& mat, const char* filename)
{
    write(mat, std::string(filename));
}
*/

// void write(const MatrixX<uint8_t>& mat, const std::string& filename) {}
<|endoftext|>