text:
#ifndef __NBDPROXY
#define __NBDPROXY

#include <boost/thread/mutex.hpp>
#include <boost/function.hpp>
// #include "request.hpp"
#include "bdproxy.hpp"
namespace ilrd
{
//NDBDiscReq has the same members as Request (m_type)
typedef Request NDBDiscReq;
int read_all(int fd, char* buf, size_t count);
int write_all(int fd, char* buf, size_t count);

class NBDTranslator
{
public:
    u_int16_t ToNetWork(u_int16_t);
    u_int32_t ToNetWork(u_int32_t);
    u_int64_t ToNetWork(u_int64_t);

    u_int16_t ToHost(u_int16_t);
    u_int32_t ToHost(u_int32_t);
    u_int64_t ToHost(u_int64_t);

private:
    static int s_endianess;
};

class NBDProxy:public BDProxyFunction,private boost::noncopyable
{
public:
    NBDProxy(u_int64_t size, const char* dev_file);
    ~NBDProxy();
    bool IsValid();
    void Done(struct Request &req);
    void OnSocketReady();

    int GetFd();

private:
    static void* RunServer(void* ptr);
    boost::mutex m_mutex;
    int m_socket_fd[2];
    int m_nbd_fd;
};

//request also contains int m_type;
struct NBDRWReq:public Request
{
    NBDRWReq(struct nbd_request, char* data = 0);
    ~NBDRWReq();
    int m_size;
    int m_offset;
    char m_handle[8];
    char* m_data;
};

}//namespace ilrd
#endif

ext: hpp

max_stars_repo_name: zrora/DistributedNAS

max_issues_repo_name: zrora/DistributedNAS

max_forks_repo_name: zrora/DistributedNAS


text:
/**
 * @file t_FileMonitor.cpp
 * @brief test FileMonitor
 */

#include "FileMonitorTestFixture.h"
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <iostream>
#include <sstream>
#include <ctime>
#include <cstdlib> // system
#include <unistd.h> // sleep
#include <sys/inotify.h>
#include <glog/logging.h>

using namespace sf1r;
namespace bfs = boost::filesystem;

BOOST_FIXTURE_TEST_SUITE(FileMonitorTest, FileMonitorTestFixture)

BOOST_AUTO_TEST_CASE(testUpdateTimeStamp)
{
    const std::string watchName("a.txt");
    const uint32_t event = IN_ATTRIB;

    // create file
    const std::string path = dirName_ + "/" + watchName;
    std::ofstream ofs(path.c_str());
    ofs.close();

    BOOST_CHECK(monitor_.addWatch(path, event));
    start();

    BOOST_CHECK_EQUAL(actualFileName_, "");
    BOOST_CHECK_EQUAL(actualMask_, 0);

    // update file timestamp
    bfs::last_write_time(path, time(NULL));

    // wait for event is triggered and processed
    sleep(1);

    // for event IN_ATTRIB, it's found that the file name got is empty
    BOOST_CHECK_EQUAL(actualFileName_, "");
    BOOST_CHECK(actualMask_ & event);
}

BOOST_AUTO_TEST_CASE(testModifyFile)
{
    const std::string watchName("a.txt");
    const uint32_t event = IN_MODIFY;

    // create file
    const std::string path = dirName_ + "/" + watchName;
    {
        std::ofstream ofs(path.c_str());
        ofs << "hello" << std::endl;
        ofs.close();
    }

    BOOST_CHECK(monitor_.addWatch(path, event));
    start();

    BOOST_CHECK_EQUAL(actualFileName_, "");
    BOOST_CHECK_EQUAL(actualMask_, 0);

    // modify file content
    {
        std::ofstream ofs(path.c_str());
        ofs << "world" << std::endl;
        ofs.close();
    }

    // wait for event is triggered and processed
    sleep(1);

    // for event IN_MODIFY, it's found that the file name got is empty
    BOOST_CHECK_EQUAL(actualFileName_, "");
    BOOST_CHECK(actualMask_ & event);
}

BOOST_AUTO_TEST_CASE(testCreateFile)
{
    const uint32_t event = IN_CREATE;
    const std::string path = dirName_;

    BOOST_CHECK(monitor_.addWatch(path, event));
    start();

    BOOST_CHECK_EQUAL(actualFileName_, "");
    BOOST_CHECK_EQUAL(actualMask_, 0);

    // create file
    const std::string fileName = "a.txt";
    const std::string filePath = dirName_ + "/" + fileName;
    {
        std::ofstream ofs(filePath.c_str());
        ofs << "hello" << std::endl;
        ofs.close();
    }

    // wait for event is triggered and processed
    sleep(1);

    BOOST_CHECK_EQUAL(actualFileName_, fileName);
    BOOST_CHECK(actualMask_ & event);
}

BOOST_AUTO_TEST_CASE(testNotExistFile)
{
    const std::string watchName("a.txt");
    const uint32_t event = IN_ATTRIB;
    const std::string path = dirName_ + "/" + watchName;

    BOOST_CHECK(monitor_.addWatch(path, event) == false);
    start();

    BOOST_CHECK_EQUAL(actualFileName_, "");
    BOOST_CHECK_EQUAL(actualMask_, 0);

    // create file
    std::ofstream ofs(path.c_str());
    ofs << "hello" << std::endl;
    ofs.close();

    // wait for event is triggered and processed
    sleep(1);

    // as no event is triggered, the result should not be changed
    BOOST_CHECK_EQUAL(actualFileName_, "");
    BOOST_CHECK_EQUAL(actualMask_, 0);
}

BOOST_AUTO_TEST_CASE(testRSyncDir)
{
    const std::string dirA = dirName_ + "/a/";
    const std::string dirB = dirName_ + "/b/";
    bfs::create_directory(dirA);
    bfs::create_directory(dirB);

    const std::string fileName1 = "1.txt";
    const std::string fileName2 = "2.txt";
    const std::string lastFileName = "z.update.time";

    std::ostringstream oss;
    oss << "touch " << dirA << fileName1
        << " && touch " << dirA << fileName2
        << " && touch " << dirA << lastFileName
        << " && rsync -azvP --delete " << dirA << " " << dirB;
    const std::string command = oss.str();

    LOG(INFO) << "create files: " << command;
    BOOST_REQUIRE_EQUAL(std::system(command.c_str()), 0);

    const std::string watchPath = dirB;
    const uint32_t event = IN_MOVED_TO;

    LOG(INFO) << "watch path: " << watchPath;
    BOOST_CHECK(monitor_.addWatch(watchPath, event));
    start();

    // wait for watch is added
    sleep(1);

    checkCommand(command, lastFileName, event);

    resetStatus();

    checkCommand(command, lastFileName, event);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp


text:
#include <boost/random.hpp>

#include "math_functions.hpp"
#include <cmath>

namespace pwalk {

// Define random number generator type
typedef boost::mt19937 rng_t;

template <typename Dtype>
void sample_gaussian(const int n, const Dtype a,
                        const Dtype sigma, Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& r) {
  static rng_t gen(1234567);
  static boost::normal_distribution<Dtype> random_distribution(a, sigma);
  static boost::variate_generator<rng_t&, boost::normal_distribution<Dtype> >
      variate_generator(gen, random_distribution);

  for (int i = 0; i < n; ++i) {
    r[i] = variate_generator();
  }
}

template <typename Dtype>
Dtype rng_uniform(const Dtype a, const Dtype b) {
  static rng_t gen(1234567);
  static boost::uniform_real<Dtype> random_distribution(a, b);
  static boost::variate_generator<rng_t&, boost::uniform_real<Dtype> >
      variate_generator(gen, random_distribution);

  return variate_generator();
}

template <typename Dtype>
Dtype gaussian_density(const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& x, const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& mu, const Eigen::Matrix<Dtype, Eigen::Dynamic, Eigen::Dynamic>& sqrt_cov) {
  Eigen::Matrix<Dtype, Eigen::Dynamic, 1> c = sqrt_cov * (x - mu);
  return std::exp(-0.5*c.dot(c)) * sqrt_cov.determinant();
}

template
void sample_gaussian<float>(const int n, const float mu,
                               const float sigma, Eigen::Matrix<float, Eigen::Dynamic, 1>& r);

template
void sample_gaussian<double>(const int n, const double mu,
                                const double sigma, Eigen::Matrix<double, Eigen::Dynamic, 1>& r);

template
float rng_uniform<float>(const float a, const float b);

template
double rng_uniform<double>(const double a, const double b);

template
float gaussian_density(const Eigen::Matrix<float, Eigen::Dynamic, 1>& x, const Eigen::Matrix<float, Eigen::Dynamic, 1>& mu, const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>& sqrt_inv_cov);

template
double gaussian_density(const Eigen::Matrix<double, Eigen::Dynamic, 1>& x, const Eigen::Matrix<double, Eigen::Dynamic, 1>& mu, const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& sqrt_inv_cov);

} // namespace pwalk

max_stars_repo_name: yuachen/polytopewalk

max_issues_repo_name: yuachen/polytopewalk

max_forks_repo_name: yuachen/polytopewalk


text:
#ifndef STAN_MCMC_HMC_HAMILTONIANS_BASE_HAMILTONIAN_HPP
#define STAN_MCMC_HMC_HAMILTONIANS_BASE_HAMILTONIAN_HPP

#include <stan/callbacks/logger.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/model/gradient.hpp>
#include <stan/model/log_prob_propto.hpp>
#include <Eigen/Dense>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>

namespace stan {
namespace mcmc {

template <class Model, class Point, class BaseRNG>
class base_hamiltonian {
 public:
  explicit base_hamiltonian(const Model& model) : model_(model) {}

  ~base_hamiltonian() {}

  typedef Point PointType;

  virtual double T(Point& z) = 0;

  double V(Point& z) { return z.V; }

  virtual double tau(Point& z) = 0;

  virtual double phi(Point& z) = 0;

  double H(Point& z) { return T(z) + V(z); }

  // The time derivative of the virial, G = \sum_{d = 1}^{D} q^{d} p_{d}.
  virtual double dG_dt(Point& z, callbacks::logger& logger) = 0;

  // tau = 0.5 p_{i} p_{j} Lambda^{ij} (q)
  virtual Eigen::VectorXd dtau_dq(Point& z, callbacks::logger& logger) = 0;

  virtual Eigen::VectorXd dtau_dp(Point& z) = 0;

  // phi = 0.5 * log | Lambda (q) | + V(q)
  virtual Eigen::VectorXd dphi_dq(Point& z, callbacks::logger& logger) = 0;

  virtual void sample_p(Point& z, BaseRNG& rng) = 0;

  void init(Point& z, callbacks::logger& logger) {
    this->update_potential_gradient(z, logger);
  }

  void update_potential(Point& z, callbacks::logger& logger) {
    try {
      z.V = -stan::model::log_prob_propto<true>(model_, z.q);
    } catch (const std::exception& e) {
      this->write_error_msg_(e, logger);
      z.V = std::numeric_limits<double>::infinity();
    }
  }

  void update_potential_gradient(Point& z, callbacks::logger& logger) {
    try {
      stan::model::gradient(model_, z.q, z.V, z.g, logger);
      z.V = -z.V;
    } catch (const std::exception& e) {
      this->write_error_msg_(e, logger);
      z.V = std::numeric_limits<double>::infinity();
    }
    z.g = -z.g;
  }

  void update_metric(Point& z, callbacks::logger& logger) {}

  void update_metric_gradient(Point& z, callbacks::logger& logger) {}

  void update_gradients(Point& z, callbacks::logger& logger) {
    update_potential_gradient(z, logger);
  }

 protected:
  const Model& model_;

  void write_error_msg_(const std::exception& e, callbacks::logger& logger) {
    logger.error(
        "Informational Message: The current Metropolis proposal "
        "is about to be rejected because of the following issue:");
    logger.error(e.what());
    logger.error(
        "If this warning occurs sporadically, such as for highly "
        "constrained variable types like covariance matrices, "
        "then the sampler is fine,");
    logger.error(
        "but if this warning occurs often then your model may be "
        "either severely ill-conditioned or misspecified.");
    logger.error("");
  }
};

}  // namespace mcmc
}  // namespace stan

#endif

max_stars_repo_name: Dr-G/stan

max_issues_repo_name: Dr-G/stan

max_forks_repo_name: Dr-G/stan


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
// QuickBook Example

// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//[length_with_strategy
//`The following example shows the length measured over a sphere, expressed in kilometers. To do that the radius of the sphere must be specified in the constructor of the strategy.

#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/linestring.hpp>

int main()
{
    using namespace boost::geometry;
    typedef model::point<float, 2, cs::spherical_equatorial<degree> > P;
    model::linestring<P> line;
    line.push_back(P(2, 41));
    line.push_back(P(2, 48));
    line.push_back(P(5, 52));
    double const mean_radius = 6371.0; /*< [@http://en.wikipedia.org/wiki/Earth_radius Wiki]  >*/
    std::cout << "length is "
        << length(line, strategy::distance::haversine<P>(mean_radius) )
        << " kilometers " << std::endl;

    return 0;
}

//]

//[length_with_strategy_output
/*`
Output:
[pre
length is 1272.03 kilometers
]
*/
//]

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#include "scoped_temp_folder.hpp"
#include <boost/filesystem/operations.hpp>

scoped_temp_folder::scoped_temp_folder(std::string const& prefix)
{
  auto parent = boost::filesystem::temp_directory_path();
  auto folder = boost::filesystem::unique_path(prefix + "%%%%%-%%%%%-%%%%-%%%%");
  auto path = parent / folder;
  boost::filesystem::create_directory(path);
  m_path = path;
}

scoped_temp_folder::~scoped_temp_folder()
{
  boost::filesystem::remove_all(m_path);
}


text:
// Copyright (C) 2020 T. Zachary Laine
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/text/unencoded_rope.hpp>

#include <gtest/gtest.h>

using boost::text::string_view;
using namespace boost::text::detail;

TEST(rope_detail, test_node_ptr)
{
    {
        node_ptr<char, std::string> p0(new_interior_node<char, std::string>());
        node_ptr<char, std::string> p1 = p0;

        EXPECT_EQ(p0->refs_, 2);
        EXPECT_EQ(p1->refs_, 2);

        EXPECT_EQ(p0.as_interior()->refs_, 2);
        EXPECT_EQ(p0.as_interior()->leaf_, false);
        EXPECT_EQ(p0.as_interior()->keys_.size(), 0u);
        EXPECT_EQ(p0.as_interior()->children_.size(), 0u);

        EXPECT_EQ(size(p0.get()), 0u);

        (void)children(p0);
        (void)keys(p0);

        EXPECT_EQ(num_children(p0), 0u);
        EXPECT_EQ(num_keys(p0), 0u);
    }

    {
        node_ptr<char, std::string> p0(new leaf_node_t<char, std::string>);
        node_ptr<char, std::string> p1 = p0;

        EXPECT_EQ(p0->refs_, 2);
        EXPECT_EQ(p1->refs_, 2);

        EXPECT_EQ(p0.as_leaf()->refs_, 2);
        EXPECT_EQ(p0.as_leaf()->leaf_, true);
        EXPECT_EQ(p0.as_leaf()->size(), 0u);

        EXPECT_EQ(size(p0.get()), 0u);
    }
}

TEST(rope_detail, test_make_node)
{
    {
        std::string t("some text");
        node_ptr<char, std::string> p = make_node(t);

        EXPECT_EQ(size(p.get()), t.size());
        EXPECT_EQ(p.as_leaf()->as_seg(), t);
        EXPECT_NE(&*p.as_leaf()->as_seg().begin(), &*t.begin());
    }

    {
        std::string t("some text");
        node_ptr<char, std::string> p = make_node(std::move(t));

        EXPECT_EQ(size(p.get()), 9u);
        EXPECT_EQ(t.size(), 0u);
        EXPECT_EQ(p.as_leaf()->as_seg(), "some text");
    }

    {
        string_view tv("some text");
        node_ptr<char, string_view> p = make_node(tv);

        EXPECT_EQ(size(p.get()), tv.size());
        EXPECT_EQ(p.as_leaf()->as_seg(), tv);
    }
}

node_ptr<char, std::string> make_tree()
{
    interior_node_t<char, std::string> * int_root = nullptr;
    node_ptr<char, std::string> root(int_root = new_interior_node<char, std::string>());

    interior_node_t<char, std::string> * int_left = nullptr;
    node_ptr<char, std::string> left(int_left = new_interior_node<char, std::string>());
    int_left->children_.push_back(make_node<std::string>("left left"));
    int_left->keys_.push_back(size(int_left->children_[0].get()));
    int_left->children_.push_back(make_node<std::string>("left right"));
    int_left->keys_.push_back(
        int_left->keys_[0] + size(int_left->children_[1].get()));

    int_root->children_.push_back(left);
    int_root->keys_.push_back(size(left.get()));

    interior_node_t<char, std::string> * int_right = nullptr;
    node_ptr<char, std::string> right(int_right = new_interior_node<char, std::string>());
    int_right->children_.push_back(make_node<std::string>("right left"));
    int_right->keys_.push_back(size(int_right->children_[0].get()));
    int_right->children_.push_back(make_node<std::string>("right right"));
    int_right->keys_.push_back(
        int_right->keys_[0] + size(int_right->children_[1].get()));

    int_root->children_.push_back(right);
    int_root->keys_.push_back(int_root->keys_[0] + size(right.get()));

    return root;
}

TEST(rope_detail, test_find)
{
    // find_child

    {
        interior_node_t<char, string_view> parent;
        parent.children_.push_back(make_node(string_view("some")));
        parent.children_.push_back(make_node(string_view(" ")));
        parent.children_.push_back(make_node(string_view("text")));
        parent.keys_.push_back(4);
        parent.keys_.push_back(5);
        parent.keys_.push_back(9);

        EXPECT_EQ(parent.keys_[0], 4u);
        EXPECT_EQ(parent.keys_[1], 5u);

        EXPECT_EQ(find_child(&parent, 0), 0u);
        EXPECT_EQ(find_child(&parent, 1), 0u);
        EXPECT_EQ(find_child(&parent, 2), 0u);
        EXPECT_EQ(find_child(&parent, 3), 0u);
        EXPECT_EQ(find_child(&parent, 4), 1u);
        EXPECT_EQ(find_child(&parent, 5), 2u);
        EXPECT_EQ(find_child(&parent, 6), 2u);
        EXPECT_EQ(find_child(&parent, 7), 2u);
        EXPECT_EQ(find_child(&parent, 8), 2u);
        EXPECT_EQ(find_child(&parent, 9), 2u);
    }

    // find_leaf

    {
        node_ptr<char, std::string> root = make_node<std::string>("test");
        found_leaf<char, std::string> found;

        find_leaf(root, 0, found);
        EXPECT_EQ(found.leaf_, &root);
        EXPECT_EQ(found.offset_, 0u);
        EXPECT_TRUE(found.path_.empty());

        find_leaf(root, 2, found);
        EXPECT_EQ(found.leaf_, &root);
        EXPECT_EQ(found.offset_, 2u);
        EXPECT_TRUE(found.path_.empty());

        find_leaf(root, 4, found);
        EXPECT_EQ(found.leaf_, &root);
        EXPECT_EQ(found.offset_, 4u);
        EXPECT_TRUE(found.path_.empty());
    }

    {
        interior_node_t<char, std::string> * int_root = nullptr;
        node_ptr<char, std::string> root(int_root = new_interior_node<char, std::string>());

        interior_node_t<char, std::string> * int_left = nullptr;
        node_ptr<char, std::string> left(int_left = new_interior_node<char, std::string>());
        int_left->children_.push_back(make_node<std::string>("left left"));
        int_left->keys_.push_back(size(int_left->children_[0].get()));
        int_left->children_.push_back(make_node<std::string>("left right"));
        int_left->keys_.push_back(
            int_left->keys_[0] + size(int_left->children_[1].get()));

        int_root->children_.push_back(left);
        int_root->keys_.push_back(size(left.get()));

        interior_node_t<char, std::string> * int_right = nullptr;
        node_ptr<char, std::string> right(int_right = new_interior_node<char, std::string>());
        int_right->children_.push_back(make_node<std::string>("right left"));
        int_right->keys_.push_back(size(int_right->children_[0].get()));
        int_right->children_.push_back(make_node<std::string>("right right"));
        int_right->keys_.push_back(
            int_right->keys_[0] + size(int_right->children_[1].get()));

        int_root->children_.push_back(right);
        int_root->keys_.push_back(int_root->keys_[0] + size(right.get()));

        {
            found_leaf<char, std::string> found;
            find_leaf(root, 0, found);
            EXPECT_EQ(found.leaf_->as_leaf()->as_seg(), "left left");
            EXPECT_EQ(found.offset_, 0u);
            EXPECT_EQ(found.path_.size(), 2u);
            EXPECT_EQ(found.path_[0], int_root);
            EXPECT_EQ(found.path_[1], int_left);
        }

        {
            found_leaf<char, std::string> found;
            find_leaf(root, 8, found);
            EXPECT_EQ(found.leaf_->as_leaf()->as_seg(), "left left");
            EXPECT_EQ(found.offset_, 8u);
            EXPECT_EQ(found.path_.size(), 2u);
            EXPECT_EQ(found.path_[0], int_root);
            EXPECT_EQ(found.path_[1], int_left);
        }

        {
            found_leaf<char, std::string> found;
            find_leaf(root, 9, found);
            EXPECT_EQ(found.leaf_->as_leaf()->as_seg(), "left right");
            EXPECT_EQ(found.offset_, 0u);
            EXPECT_EQ(found.path_.size(), 2u);
            EXPECT_EQ(found.path_[0], int_root);
            EXPECT_EQ(found.path_[1], int_left);
        }

        {
            found_leaf<char, std::string> found;
            find_leaf(root, 10, found);
            EXPECT_EQ(found.leaf_->as_leaf()->as_seg(), "left right");
            EXPECT_EQ(found.offset_, 1u);
            EXPECT_EQ(found.path_.size(), 2u);
            EXPECT_EQ(found.path_[0], int_root);
            EXPECT_EQ(found.path_[1], int_left);
        }

        {
            found_leaf<char, std::string> found;
            find_leaf(root, 13, found);
            EXPECT_EQ(found.leaf_->as_leaf()->as_seg(), "left right");
            EXPECT_EQ(found.offset_, 4u);
            EXPECT_EQ(found.path_.size(), 2u);
            EXPECT_EQ(found.path_[0], int_root);
            EXPECT_EQ(found.path_[1], int_left);
        }

        {
            found_leaf<char, std::string> found;
            find_leaf(root, 18, found);
            EXPECT_EQ(found.leaf_->as_leaf()->as_seg(), "left right");
            EXPECT_EQ(found.offset_, 9u);
            EXPECT_EQ(found.path_.size(), 2u);
            EXPECT_EQ(found.path_[0], int_root);
            EXPECT_EQ(found.path_[1], int_left);
        }

        {
            found_leaf<char, std::string> found;
            find_leaf(root, 19, found);
            EXPECT_EQ(found.leaf_->as_leaf()->as_seg(), "right left");
            EXPECT_EQ(found.offset_, 0u);
            EXPECT_EQ(found.path_.size(), 2u);
            EXPECT_EQ(found.path_[0], int_root);
            EXPECT_EQ(found.path_[1], int_right);
        }

        {
            found_leaf<char, std::string> found;
            find_leaf(root, 28, found);
            EXPECT_EQ(found.leaf_->as_leaf()->as_seg(), "right left");
            EXPECT_EQ(found.offset_, 9u);
            EXPECT_EQ(found.path_.size(), 2u);
            EXPECT_EQ(found.path_[0], int_root);
            EXPECT_EQ(found.path_[1], int_right);
        }

        {
            found_leaf<char, std::string> found;
            find_leaf(root, 29, found);
            EXPECT_EQ(found.leaf_->as_leaf()->as_seg(), "right right");
            EXPECT_EQ(found.offset_, 0u);
            EXPECT_EQ(found.path_.size(), 2u);
            EXPECT_EQ(found.path_[0], int_root);
            EXPECT_EQ(found.path_[1], int_right);
        }

        {
            found_leaf<char, std::string> found;
            find_leaf(root, 40, found);
            EXPECT_EQ(found.leaf_->as_leaf()->as_seg(), "right right");
            EXPECT_EQ(found.offset_, 11u);
            EXPECT_EQ(found.path_.size(), 2u);
            EXPECT_EQ(found.path_[0], int_root);
            EXPECT_EQ(found.path_[1], int_right);
        }
    }
}

void fill_interior_node(interior_node_t<char, std::string> & parent)
{
    parent.children_.push_back(make_node<std::string>("some"));
    parent.children_.push_back(make_node<std::string>(" "));
    parent.children_.push_back(make_node<std::string>("text"));
    parent.keys_.push_back(4);
    parent.keys_.push_back(5);
    parent.keys_.push_back(9);
}

TEST(rope_detail, test_insert_erase_child)
{
    {
        interior_node_t<char, std::string> parent;
        fill_interior_node(parent);
        insert_child(&parent, 0, make_node<std::string>("X"));
        EXPECT_EQ(parent.children_[0].as_leaf()->as_seg(), "X");
        EXPECT_EQ(parent.keys_[0], 1u);
        EXPECT_EQ(parent.keys_[1], 5u);
        EXPECT_EQ(parent.keys_[2], 6u);
        EXPECT_EQ(parent.keys_[3], 10u);
    }

    {
        interior_node_t<char, std::string> parent;
        fill_interior_node(parent);
        insert_child(&parent, 2, make_node<std::string>("X"));
        EXPECT_EQ(parent.children_[2].as_leaf()->as_seg(), "X");
        EXPECT_EQ(parent.keys_[0], 4u);
        EXPECT_EQ(parent.keys_[1], 5u);
        EXPECT_EQ(parent.keys_[2], 6u);
        EXPECT_EQ(parent.keys_[3], 10u);
    }

    {
        interior_node_t<char, std::string> parent;
        fill_interior_node(parent);
        insert_child(&parent, 3, make_node<std::string>("X"));
        EXPECT_EQ(parent.children_[3].as_leaf()->as_seg(), "X");
        EXPECT_EQ(parent.keys_[0], 4u);
        EXPECT_EQ(parent.keys_[1], 5u);
        EXPECT_EQ(parent.keys_[2], 9u);
        EXPECT_EQ(parent.keys_[3], 10u);
    }

    {
        interior_node_t<char, std::string> parent;
        fill_interior_node(parent);
        erase_child(&parent, 0, dont_adjust_keys);
        EXPECT_EQ(parent.children_[0].as_leaf()->as_seg(), " ");
        EXPECT_EQ(parent.children_[1].as_leaf()->as_seg(), "text");
        EXPECT_EQ(parent.keys_[0], 5u);
        EXPECT_EQ(parent.keys_[1], 9u);
    }

    {
        interior_node_t<char, std::string> parent;
        fill_interior_node(parent);
        erase_child(&parent, 1);
        EXPECT_EQ(parent.children_[0].as_leaf()->as_seg(), "some");
        EXPECT_EQ(parent.children_[1].as_leaf()->as_seg(), "text");
        EXPECT_EQ(parent.keys_[0], 4u);
        EXPECT_EQ(parent.keys_[1], 8u);
    }

    {
        interior_node_t<char, std::string> parent;
        fill_interior_node(parent);
        erase_child(&parent, 2);
        EXPECT_EQ(parent.children_[0].as_leaf()->as_seg(), "some");
        EXPECT_EQ(parent.children_[1].as_leaf()->as_seg(), " ");
        EXPECT_EQ(parent.keys_[0], 4u);
        EXPECT_EQ(parent.keys_[1], 5u);
    }
}

max_stars_repo_name: Ryan-rsm-McKenzie/text

max_issues_repo_name: Ryan-rsm-McKenzie/text

max_forks_repo_name: Ryan-rsm-McKenzie/text


text:
// Copyright (c) 2012 Christopher Lux <christopherlux@gmail.com>
// Distributed under the Modified BSD License, see license.txt.

#include "volume_renderer.h"

#include <exception>
#include <stdexcept>
#include <sstream>
#include <string>

#include <boost/assign/list_of.hpp>

#include <scm/gl_core/math.h>
#include <scm/gl_core/buffer_objects.h>
#include <scm/gl_core/render_device.h>
#include <scm/gl_core/shader_objects.h>
#include <scm/gl_core/state_objects.h>
#include <scm/gl_core/texture_objects.h>

#include <scm/gl_util/primitives/box.h>
#include <scm/gl_util/primitives/box_volume.h>
#include <scm/gl_util/viewer/camera.h>
#include <scm/gl_util/viewer/camera_uniform_block.h>

#include <renderer/volume_data.h>

namespace scm {
namespace data {

volume_renderer::volume_renderer(const gl::render_device_ptr& device, const math::vec2ui& vp_size)
  : _viewport_size(vp_size)
{
    using namespace scm;
    using namespace scm::gl;
    using namespace scm::math;
    using boost::assign::list_of;

    camera_uniform_block::add_block_include_string(device);

    _camera_block.reset(new gl::camera_uniform_block(device));

    // state objects //////////////////////////////////////////////////////////////////////////////
    _bstate = device->create_blend_state(false, FUNC_ONE, FUNC_ZERO, FUNC_ONE, FUNC_ZERO);
    //_bstate = device->create_blend_state(true, FUNC_SRC_ALPHA, FUNC_ONE_MINUS_SRC_ALPHA, FUNC_ONE, FUNC_ZERO);
    _dstate = device->create_depth_stencil_state(true, true, COMPARISON_LESS);

    _rstate = device->create_rasterizer_state(FILL_SOLID, CULL_BACK, ORIENT_CCW, true);
    _rstate_sample_shading = device->create_rasterizer_state(FILL_SOLID, CULL_BACK, ORIENT_CCW, true, true, 1.0f);

    _sstate_lin = device->create_sampler_state(FILTER_MIN_MAG_LINEAR, WRAP_CLAMP_TO_EDGE);
    _sstate_lin_mip = device->create_sampler_state(FILTER_MIN_MAG_MIP_LINEAR, WRAP_CLAMP_TO_EDGE);

    if (   !_bstate
        || !_dstate
        || !_rstate
        || !_sstate_lin
        || !_sstate_lin_mip) {
        throw (std::runtime_error("volume_renderer::volume_renderer(): error creating state objects"));
    }

    if (!reload_shaders(device)) {
        throw std::runtime_error("volume_renderer::volume_renderer(): error loading shader programs.");
    }

    //_vtexture_program->uniform("model_matrix", model_matrix);
    //_vtexture_program->uniform_buffer("camera_matrices", 0);
    //_vtexture_program->uniform_subroutine(STAGE_FRAGMENT_SHADER, "out_color_gen", "draw_vtexture");
    //_vtexture_program->uniform_subroutine(STAGE_FRAGMENT_SHADER, "out_color_gen", "draw_debug_atlas");
    //_vtexture_program->uniform_subroutine(STAGE_FRAGMENT_SHADER, "out_color_gen", "draw_atlas");
    //_vtexture_program->uniform_subroutine(STAGE_FRAGMENT_SHADER, "out_color_gen", "visualize_normal");
    //_vtexture_program->uniform_subroutine(STAGE_FRAGMENT_SHADER, "out_color_gen", "visualize_texcoord");

}

volume_renderer::~volume_renderer()
{
    _program.reset();

    _dstate.reset();
    _bstate.reset();
    _rstate.reset();
    _rstate_sample_shading.reset();
    _sstate_lin.reset();
    _sstate_lin_mip.reset();

    _camera_block.reset();
}

void
volume_renderer::draw(const gl::render_context_ptr& context,
                      const volume_data_ptr&        vdata,
                      const vr_mode                 mode,
                      bool                          use_sample_shading,
                      bool                          use_supersampling) const
{
    using namespace scm;
    using namespace scm::gl;
    using namespace scm::math;

    switch (mode) {
        case volume_raw:
            _program->uniform_subroutine(STAGE_FRAGMENT_SHADER, "volume_color_lookup", "raw_lookup");
            break;
        case volume_color_map:
            _program->uniform_subroutine(STAGE_FRAGMENT_SHADER, "volume_color_lookup", "raw_color_map_lookup");
            break;
    }

    _program->uniform("volume_lod", vdata->selected_lod());
    _program->uniform("use_ss",     use_supersampling);

    context_state_objects_guard     csg(context);
    context_texture_units_guard     tug(context);
    context_uniform_buffer_guard    ubg(context);

    context->reset_state_objects();

    context->set_depth_stencil_state(_dstate);
    context->set_blend_state(_bstate);
    context->set_rasterizer_state(use_sample_shading ? _rstate_sample_shading : _rstate);

    context->bind_uniform_buffer(_camera_block->block().block_buffer(), 0);
    context->bind_uniform_buffer(vdata->volume_block().block_buffer(),  1);

    context->bind_program(_program);

    context->reset_texture_units();
    context->bind_texture(vdata->volume_raw(),      _sstate_lin_mip, 0);
    context->bind_texture(vdata->color_alpha_map(), _sstate_lin,     2);

    vdata->bbox_geometry()->draw(context, geometry::MODE_SOLID);
}

void
volume_renderer::update(const gl::render_context_ptr& context,
                        const gl::camera&             cam)
{
    _camera_block->update(context, cam);
}

bool
volume_renderer::reload_shaders(const gl::render_device_ptr& device)
{
    using namespace scm;
    using namespace scm::gl;
    using namespace scm::math;
    using boost::assign::list_of;

    scm::out() << log::info
               << "volume_renderer::reload_shaders(): "
               << "reloading shader strings." << log::end;

    // ray casting program ////////////////////////////////////////////////////////////////////////
    program_ptr prog_rcraw  = device->create_program(list_of(device->create_shader_from_file(STAGE_VERTEX_SHADER,   "../../../src/renderer/shader/volume_ray_cast.glslv"))
                                                            (device->create_shader_from_file(STAGE_FRAGMENT_SHADER, "../../../src/renderer/shader/volume_ray_cast.glslf")),
                                                     "volume_renderer::program");

    if (!prog_rcraw) {
        scm::err() << log::error
                   << "volume_renderer::reload_shaders(): "
                   << "error loading program" << log::end;
        return false;
    }
    else {
        _program = prog_rcraw;
    }

    _program->uniform_sampler("volume_raw",     0);
    _program->uniform_sampler("color_map",      2);
    _program->uniform("viewport_size",  math::vec2f(_viewport_size));

    _program->uniform_buffer("camera_matrices",     0);
    _program->uniform_buffer("volume_uniform_data", 1);

    return true;
}

} // namespace data
} // namespace scm

max_stars_repo_name: Nyran/schism

max_issues_repo_name: Nyran/schism

max_forks_repo_name: Nyran/schism


text:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "XtekReader.h"
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include "exlibtiff/internal/exlibtiff.h"
#include "exlibtiff/internal/tiffio.h"

//Constructor

XtekReader::XtekReader(std::string filename,CCPiUserApplicationInterface* msg)
{
	test = true;
	this->msg = msg;
	msg->LogMessage("Starting to read the .xtekct file");
	if(readXtekCTFile(filename))
	{
		msg->SetProgressValue(0.1);
		msg->SetStatusMessage("Completed reading .xtekct file");
		msg->LogMessage("Completed reading .xtekct file");
		//Split and get the file path and append the _ctdata.txt to read angles data
		boost::filesystem::path xtekfile(filename);
		boost::filesystem::path ctname("_ctdata.txt");
		boost::filesystem::path full_ctname = xtekfile.parent_path() / ctname;
		if(!readCTDataFile(full_ctname.string()))
		{
			msg->LogMessage("Error reading the _ctdata.txt file");
			//Try ang file
			boost::filesystem::path full_ang = xtekfile.replace_extension("ang");
			msg->LogMessage(std::string("Reading ang file instead ")+full_ang.string());
			if(!readAngFile(full_ang.string()))
				return;
		}
		msg->SetProgressValue(0.2);
		msg->LogMessage("Completed reading the _ctdata.txt file");
		//allocate memory for the images
		unsigned long long width = detectorPixels[0];
		unsigned long long height = detectorPixels[1];
		imageData = new uint16_t[projections * width * height];
		boost::filesystem::path imgname(name); //prefix of the images
		boost::filesystem::path prefix_image = xtekfile.parent_path() / imgname;
		//read the images
		readImageFiles(prefix_image.string(), projections, imageData);
		msg->SetProgressValue(1.0);
		msg->SetStatusMessage("Done");
	}
}

//Destructor

XtekReader::~XtekReader()
{
}

bool XtekReader::readXtekCTFile(std::string filename)
{
	//Open the xxx.xtetct file
	std::ifstream ctfile(filename.c_str());
	if(!ctfile.is_open()) return false;
	//read the header
	std::string line;
	getline(ctfile, line);
	boost::algorithm::trim(line);
	if(line.compare("[XTekCT]")!=0) return false; // return on invalid header
	while( getline(ctfile, line))
	{
		boost::algorithm::trim(line);
		std::vector<std::string> keyvalue;
		boost::algorithm::split(keyvalue, line, boost::is_any_of("="));
		if(keyvalue[0].compare("Name")==0)
		{
			name = keyvalue[1];
		}else if(keyvalue[0].compare("VoxelsX")==0)
		{
			voxels[0] = atoi(keyvalue[1].c_str());
		}else if(keyvalue[0].compare("VoxelsY")==0)
		{
			voxels[1] = atoi(keyvalue[1].c_str());
		}else if(keyvalue[0].compare("VoxelsZ")==0)
		{
			voxels[2] = atoi(keyvalue[1].c_str());
		}else if(keyvalue[0].compare("VoxelSizeX")==0)
		{
			voxelSize[0] = strtod(keyvalue[1].c_str(),NULL);
		}else if(keyvalue[0].compare("VoxelSizeY")==0)
		{
			voxelSize[1] = strtod(keyvalue[1].c_str(),NULL);
		}else if(keyvalue[0].compare("VoxelSizeZ")==0)
		{
			voxelSize[2] = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("OffsetX")==0)
		{
			offset[0] = strtod(keyvalue[1].c_str(),NULL);
		}else if(keyvalue[0].compare("OffsetY")==0)
		{
			offset[1] = strtod(keyvalue[1].c_str(), NULL);
		}else if (keyvalue[0].compare("OffsetZ")==0)
		{
			offset[2] = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("SrcToObject")==0)
		{
			srcToObject = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("SrcToDetector")==0)
		{
			srcToDetector = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("MaskRadius")==0)
		{
			maskRadius = strtod(keyvalue[1].c_str(),NULL);
		}else if(keyvalue[0].compare("DetectorPixelsX")==0)
		{
			detectorPixels[0]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("DetectorPixelsY")==0)
		{
			detectorPixels[1]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("DetectorPixelSizeX")==0)
		{
			detectorPixelSize[0]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("DetectorPixelSizeY")==0)
		{
			detectorPixelSize[1]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("DetectorOffsetX")==0)
		{
			detectorOffset[0]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("DetectorOffsetY")==0)
		{
			detectorOffset[1]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("CentreOfRotation")==0)
		{
			centreOfRotation[0]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("CentreOfRotationTop")==0)
		{
			centreOfRotation[1]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("CentreOfRotationBottom")==0)
		{
			centreOfRotation[2]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("WhiteLevel")==0)
		{
			whiteLevel= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("Scattering")==0)
		{
			scattering= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("CoefX4")==0)
		{
			coefX[4]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("CoefX3")==0)
		{
			coefX[3]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("CoefX2")==0)
		{
			coefX[2]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("CoefX1")==0)
		{
			coefX[1]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("CoefX0")==0)
		{
			coefX[0]= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("Scale")==0)
		{
			scale= strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("RegionStartX")==0)
		{
			regionStart[0] = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("RegionStartY")==0)
		{
			regionStart[1] = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("RegionPixelsX")==0)
		{
			regionPixels[0] = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("RegionPixelsY")==0)
		{
			regionPixels[1] = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("Projections")==0)
		{
			projections = atoi(keyvalue[1].c_str());
		}else if(keyvalue[0].compare("InitialAngle")==0)
		{
			initialAngle = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("AngularStep")==0)
		{
			angularStep = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("FilterType")==0)
		{
			filterType = atoi(keyvalue[1].c_str());
		}else if(keyvalue[0].compare("CutOffFrequency")==0)
		{
			cutOffFrequency = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("Exponent")==0)
		{
			exponent = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("Normalisation")==0)
		{
			normalisation = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("InterpolationType")==0)
		{
			interpolationType = atoi(keyvalue[1].c_str());
		}else if(keyvalue[0].compare("Scaling")==0)
		{
			scaling = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("OutputType")==0)
		{
			outputType = atoi(keyvalue[1].c_str());
		}else if(keyvalue[0].compare("ImportConversion")==0)
		{
			importConversion = atoi(keyvalue[1].c_str());
		}else if(keyvalue[0].compare("TIFFScaling")==0)
		{
			tiffScaling = atoi(keyvalue[1].c_str());
		}else if(keyvalue[0].compare("XraykV")==0)
		{
			xrayKV = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("XrayuA")==0)
		{
			xrayuA = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("Filter_ThicknessMM")==0)
		{
			filterThicknessMM = strtod(keyvalue[1].c_str(), NULL);
		}else if(keyvalue[0].compare("Filter_Material")==0)
		{
			filterMaterial = keyvalue[1];
		}else if(keyvalue[0].compare("Shuttling")==0)
		{
			boost::algorithm::to_lower(keyvalue[1]);
			std::istringstream is(keyvalue[1]);
			is >> std::boolalpha >> shuttling;
		}else if(keyvalue[0].compare("InputSeparator") == 0)
		{
			inputSeperator = keyvalue[1];
		}
	}
	return true;
}

bool XtekReader::readCTDataFile(std::string filename)
{
	//Open the _ctdata.txt file
	std::ifstream ctfile(filename.c_str());
	if(!ctfile.is_open()) return false;
	//read the header
	std::string line;
	getline(ctfile, line);
	boost::algorithm::trim(line);
	if(line.compare("Projs	Frames	Exposure(ms)")!=0) return false; // return on invalid header
	//Read number of projections
	getline(ctfile, line);
	boost::algorithm::trim(line);
	std::vector<std::string> values;
	boost::algorithm::split(values, line, boost::is_any_of("\t "), boost::token_compress_on);
	if (atoi(values[0].c_str())!= projections) return false; // number of projections don't match
	framesPerProjection = atoi(values[1].c_str());
	exposureTime = strtod(values[2].c_str(), NULL);

	//Read the next header
	getline(ctfile, line);
	//Allocate angles memory
	angles = new float[projections];
	angleTime = new double[projections];
	while( getline(ctfile, line))
	{
		boost::algorithm::trim(line);
		std::vector<std::string> values;
		boost::algorithm::split(values, line, boost::is_any_of("\t "), boost::token_compress_on);
		int proj = atoi(values[0].c_str()) - 1;
		if(proj > projections) return false; // projection index cannot be greater than number projections
		angles[proj] = initialAngle + strtod(values[1].c_str(), NULL);
		angleTime[proj] = strtod(values[2].c_str(), NULL);
	}
	ctfile.close();
	return true;
}

bool XtekReader::readAngFile(std::string filename)
{
	//Open the xxx.ang file
	std::ifstream ctfile(filename.c_str());
	if(!ctfile.is_open()) return false;
	//read the header
	std::string line;
	getline(ctfile, line);
	boost::algorithm::trim(line);
	if(line.compare("Proj	Angle(deg)")!=0) return false; // return on invalid header
	angles = new float[projections];
	while( getline(ctfile, line))
	{
		boost::algorithm::trim(line);
		std::vector<std::string> values;
		boost::algorithm::split(values, line, boost::is_any_of("\t "), boost::token_compress_on);
		int proj = atoi(values[0].c_str());
		if(proj > projections) return false; // projection index cannot be greater than number projections
		angles[projections - proj] = initialAngle + strtod(values[1].c_str(), NULL);
	}
	ctfile.close();
	return true;
}

bool XtekReader::readImageFiles(std::string filePrefix, int numberOfAngles, uint16_t *data)
{
	unsigned long long width,height;
	width = detectorPixels[0];
	height = detectorPixels[1];
	for (unsigned long long i=0;i<numberOfAngles;i++) {
		std::stringstream fullpath;
		fullpath << boost::format("%s%s%|04d|.tif")%filePrefix %inputSeperator %(i+1);
		msg->SetStatusMessage(fullpath.str());
		bool ok = readTiffFile(fullpath.str(), width, height, data+i*width*height);
		msg->SetProgressValue(((float)i+1)/numberOfAngles);
		if(msg->isCancel()) return false;
		if(!ok)
		{
			std::cout<<"Error reading file: "<<fullpath.str()<<std::endl;
			msg->LogMessage(std::string("Error reading file: ")+fullpath.str());
			return false;
		}
	}
	return true;
}

bool XtekReader::readTiffFile(std::string filename, int width, int height, uint16_t *data)
{
	TIFF *tif = TIFFOpen(filename.c_str(), "r");
	if (tif == 0) {
		std::cout<<"Error opening the file"<<std::endl;
		return false;
	} else {
		if (TIFFIsTiled(tif)) {
			std::cout<<"Error: Doesn't support tiled tiff"<<std::endl;
			return false; // Doesn't support tiled tiff
		} else {
			uint16 bps;
			if (TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bps) == 0) {
				std::cout<<"Error: reading bits per sample"<<std::endl;
				return false; //TIFF error reading bits per sample
			} else if (bps != 16) {
				std::cout<<"Error: TIFF is not 16bit data"<<std::endl;
				return false; //TIFF is not 16bit data
			} else {
				uint16 photo;
				if (TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photo) == 0) {
					std::cout<<"Error: getting TIFF photometric info"<<std::endl;
					return false; //Error getting TIFF photometric info
				} else if (photo != PHOTOMETRIC_MINISBLACK) {
					std::cout<<"Error: TIFF photometric type not supported by XTek Reader"<<std::endl;
					return false;//TIFF photometric type not supported by XTek reader
				} else {
					if (TIFFIsMSB2LSB(tif) == 0) {
						std::cout<<"Error: TIFF is not MSB to LSB"<<std::endl;
						return false;//TIFF is not MSB to LSB
					} else {
						// I'm assuming orientation would be 1, (0,0) in top left corner
						// but XTek tiffs don't usually work with TIFFTAG_ORIENTATION
						uint32 w;
						if (TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w) == 0) {
							std::cout<<"Error: getting TIFF width"<<std::endl;
							return false;//Error getting TIFF width
						} else if ((int)w != width) {
							std::cout<<"Error: Width don't match"<<std::endl;
							return false; //Image width mismatch
						} else {
							tsize_t strip_size = TIFFStripSize(tif);
							int nstrips = TIFFNumberOfStrips(tif);
							char *buf = (char *)_TIFFmalloc(strip_size * nstrips);
							int offset = 0;
							int result;
							for (int count = 0; (count < nstrips); count++) {
								if ((result = TIFFReadEncodedStrip(tif, count, buf + offset,
									strip_size)) == -1) {
										std::cout<<"Error: read error in file"<<std::endl;
										return false;//Read error in file
								} else
									offset += result;
							}
							int extra = offset % 2;
							offset /= 2;
							if (extra == 1) {
								std::cout<<"Error: Odd number of bytes for 16bit image"<<std::endl;
								return false;//Odd number of bytes for 16 bit image
							} else if (offset != width * height) {
								std::cout<<"Error: Image size mismatch"<<std::endl;
								return false;//Image size mismatch
							} else {
								//std::memcpy(data, buf, sizeof(uint16)*width*height);
								uint16 *b = (uint16 *)buf;
								for(unsigned long i=0;i<width;i++)
									for(unsigned long j=0;j<height;j++)
										data[i*height+j] = uint16_t(b[i*height+j]);
							}
							_TIFFfree(buf);
						}
					}
				}
			}
		}
		TIFFClose(tif);
	}
	return true;
}

max_stars_repo_name: vais-ral/CCPi-Reconstruction

max_issues_repo_name: vais-ral/CCPi-Reconstruction

max_forks_repo_name: vais-ral/CCPi-Reconstruction


text:
#ifndef SCOMP_SEMANTICS_ENTRY_HPP_
#define SCOMP_SEMANTICS_ENTRY_HPP_

#include <string>
#include <vector>

#include <boost/variant.hpp>

#include <scomp/semantics/type.hpp>
#include <scomp/semantics/entry_fwd.hpp>
#include <scomp/semantics/scope.hpp>

namespace scomp {
  namespace semantics {

    namespace entry_node {
      struct var_entry {
        std::string name;
        semantics::type type;

        var_entry() = default;
        var_entry(std::string name, semantics::type const& t)
            : name(std::move(name)), type(t) {}
        var_entry(std::string name, semantics::type&& t)
            : name(std::move(name)), type(std::move(t)) {}
      };

      struct fun_entry {
        std::string name;
        using param_type = std::pair<std::string, semantics::type>;
        std::vector<param_type> params;
        semantics::type return_type;
        scope_ptr fun_scope;

        fun_entry() = default;
        fun_entry(std::string name, std::vector<param_type> const& params,
                  semantics::type const& return_type,
                  enclosing_scope_ptr&& enclosing)
            : name(std::move(name)),
              params(params),
              return_type(return_type),
              fun_scope(std::make_shared<scope>(std::move(enclosing))) {
          for (auto&& param : this->params) {
            fun_scope->define_symbol(
                param.first,
                std::make_shared<var_entry>(param.first, param.second));
          }
        }
        fun_entry(std::string name, std::vector<param_type>&& params,
                  semantics::type&& return_type,
                  enclosing_scope_ptr&& enclosing)
            : name(std::move(name)),
              params(std::move(params)),
              return_type(std::move(return_type)),
              fun_scope(std::make_shared<scope>(std::move(enclosing))) {
          for (auto&& param : this->params) {
            fun_scope->define_symbol(
                param.first,
                std::make_shared<var_entry>(param.first, param.second));
          }
        }
      };
    } // namespace entry_node

  } // namespace semantics
} // namespace scomp

#endif

max_stars_repo_name: agatan/scomp

max_issues_repo_name: agatan/scomp

max_forks_repo_name: agatan/scomp


text:
#pragma once

#include <string>
#include <stdexcept>
#include <map>

#include <boost/filesystem.hpp>
#include <rapidjson/document.h>

#include "PHKVStorage.hpp"

enum class json_rpc_error : int{
    parse_error = -32700,
    invalid_request = -32600,
    method_not_found = -32601,
    invalid_params = -32602,
    internal_error = -32603,
};

class json_rpc_exception:public std::runtime_error{
public:
    json_rpc_exception(json_rpc_error error, std::string message):std::runtime_error(std::move(message)), m_error(error)
    {
    }
    int get_error()const noexcept
    {
        return static_cast<int>(m_error);
    }
protected:
    json_rpc_error m_error;
};

class json_rpc_method_params{
public:

    json_rpc_method_params(const rapidjson::Value& params):m_params(params)
    {
    }

    bool getBool(const char* name)const;
    bool getBoolDefault(const char* name, bool defaultValue)const;
    int getInt(const char* name)const;
    int getIntDefault(const char* name, int defaultValue)const;
    const char* getString(const char* name)const;
    const char* getStringDefault(const char* name, const char* defaultValue)const;

    rapidjson::Value::ConstArray getArray(const char* name, rapidjson::Type expectedType = rapidjson::kNullType)const;
    const rapidjson::Value& getObject(const char* name)const;

protected:
    const rapidjson::Value& m_params;
};

class json_rpc_result_value{
public:
protected:
    rapidjson::Document& m_result;
    rapidjson::Value& m_value;
};

class json_rpc_result{
public:
    rapidjson::Document& get_document()
    {
        return m_result;
    }
    template <class T>
    void push_back(T&& item)
    {
        if ( m_result.GetType() != rapidjson::kArrayType ) {
            m_result.SetArray();
        }
        m_result.PushBack(item, m_result.GetAllocator());
    }
    template <size_t N, class T>
    void addMember(const char (&name)[N], T value)
    {
        if ( m_result.GetType() != rapidjson::kObjectType ) {
            m_result.SetObject();
        }
        m_result.GetObject().AddMember(name, value, m_result.GetAllocator());
    }
    template <size_t N, size_t M>
    void addMember(const char (&name)[N], const char (&value)[M])
    {
        if ( m_result.GetType() != rapidjson::kObjectType ) {
            m_result.SetObject();
        }
        m_result.GetObject().AddMember(name, value, m_result.GetAllocator());
    }
protected:
    rapidjson::Document m_result;
};

class json_rpc_service{
public:
    json_rpc_service()=default;
    struct config{
        boost::filesystem::path default_path;
    };
    void init(phkvs::PHKVStorage::UniquePtr&& storage, const config& config);
    json_rpc_result callMethod(const char* methodName, const json_rpc_method_params& params)const;
protected:

    boost::filesystem::path m_default_path;
    using method_type = std::function<json_rpc_result(const json_rpc_method_params&)>;
    struct method_record{
        method_type method;
    };
    void registerMethod(const char* name, method_type);
    std::map<std::string, method_record> m_methods;

    phkvs::PHKVStorage::UniquePtr m_storage;

    json_rpc_result get_volumes_list_method(const json_rpc_method_params& params);
    json_rpc_result create_and_mount_volume_method(const json_rpc_method_params& params);
    json_rpc_result mount_volume_method(const json_rpc_method_params& params);
    json_rpc_result unmount_volume_method(const json_rpc_method_params& params);

    json_rpc_result store_method(const json_rpc_method_params& params);
    json_rpc_result lookup_method(const json_rpc_method_params& params);
    json_rpc_result get_dir_entries_method(const json_rpc_method_params& params);
    json_rpc_result erase_key_method(const json_rpc_method_params& params);
    json_rpc_result erase_dir_recursive_method(const json_rpc_method_params& params);

};

max_stars_repo_name: Xecutor/phkvstorage

max_issues_repo_name: Xecutor/phkvstorage

max_forks_repo_name: Xecutor/phkvstorage


text:
/*
 * ControllerCLI.cpp
 *
 *  Created on: Jun 5, 2016
 *      Author: james
 */

#include "tcp/RemoteCLI.h"

#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/basic_socket_iostream.hpp>
#include <iostream>

#include "Beetle.h"
#include "BeetleConfig.h"
#include "CLI.h"
#include "controller/ControllerClient.h"

RemoteCLI::RemoteCLI(Beetle &beetle, std::string host, int port, BeetleConfig beetleConfig,
		std::shared_ptr<NetworkDiscoveryClient> discovery, bool useDaemon) {
	auto stream = new boost::asio::ip::tcp::iostream;

	// TODO SSL this
	// http://www.boost.org/doc/libs/1_45_0/doc/html/boost_asio/example/ssl/client.cpp

	stream->connect(host, std::to_string(port));
	if(stream->fail()) {
		throw ControllerException("Could not connect to command server.");
	}

	cli = std::make_unique<CLI>(beetle, beetleConfig, discovery, stream, useDaemon, false);
}

RemoteCLI::~RemoteCLI() {

}

void RemoteCLI::join() {
	cli->join();
}

CLI *RemoteCLI::get() {
	return cli.get();
}

max_stars_repo_name: helena-project/beetle

max_issues_repo_name: helena-project/beetle

max_forks_repo_name: helena-project/beetle


text:
/**
/*   Copyright (c) 2003by  Marco Welti
/*
/*   This document is  bound by the  QT Public License
/*   (http://www.trolltech.com/licenses/qpl.html).
/*   See License.txt for more information.
/*
/*
/*
/*   ALL RIGHTS RESERVED.
/*
/*   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
/*   OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
/*   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
/*   ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
/*   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
/*   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
/*   GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/*   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
/*   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
/*   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
/*   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
/***********************************************************************/

#pragma warning( disable:4800 )

#include "stdafx.h"
#include "resource.h"

#include <Controller/Browsers/OutlineBrowser.h>

#include <Renderer/LabelBroker.h>
#include <Renderer/TooltipBroker.h>
#include <Renderer/MFC/ESBImageList.h>
#include <Renderer/MFC/Properties/OutlinePropertyPanel.h>
#include <Renderer/MFC/Browsers/OutlineBrowserRenderer.h>
#include <Renderer/MFC/TreeCtrlHelper.h>

#include <Utilities/StringTokenizer.h>

#include <string>

//#include <boost/bind.hpp>

using namespace std;
using namespace boost;

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// OutlineBrowserRenderer dialog

BEGIN_MESSAGE_MAP(OutlineBrowserRenderer, super )
  //{{AFX_MSG_MAP(OutlineBrowserRenderer)
  ON_COMMAND(ID_OUTLINEBROWSER_HEADER, onGotoHeader)
  ON_COMMAND(ID_OUTLINEBROWSER_SOURCE, onGotoSource)
  ON_COMMAND(ID_OUTLINEBROWSER_INSPECT, onInspectTag)
  ON_COMMAND(ID_OUTLINEBROWSER_HIERARCHY, onShowHierarchy)
  ON_WM_SIZE()
  ON_WM_CREATE()
  //}}AFX_MSG_MAP

  ON_NOTIFY(NM_CLICK, IDC_OUTLINE, onMouseClicked)
  ON_NOTIFY(NM_DBLCLK, IDC_OUTLINE, onMouseClicked)
  ON_NOTIFY(NM_RCLICK, IDC_OUTLINE, onMouseClicked)
  ON_NOTIFY(NM_RDBLCLK, IDC_OUTLINE, onMouseClicked)
	ON_NOTIFY(TVN_GETINFOTIP, IDC_OUTLINE, onGetToolTip)
  //ON_NOTIFY_EX( TTN_NEEDTEXT, 0, onToolTipNotify )

  ON_BN_CLICKED(IDC_OUTLINE_SORT, onSort)
  ON_BN_CLICKED(IDC_OUTLINE_NO_FIELDS, onNoFields)
  ON_BN_CLICKED(IDC_OUTLINE_NO_STATIC, onNoStatic)
  ON_BN_CLICKED(IDC_OUTLINE_PUBLIC_ONLY, onPublicOnly)
  ON_BN_CLICKED(IDC_CUSTOM_FILTER, onCustomFilter)

END_MESSAGE_MAP()

OutlineBrowserRenderer::OutlineBrowserRenderer(OutlineBrowser *c, CWnd* pParent /*=NULL*/)
	: super(), mController(c), mOld(0,0,0,0)
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserRenderer::OutlineBrowserRenderer()");

  size_t style = WS_CHILD | WS_TABSTOP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  Create("", style, CRect(0,0, 300, 450), pParent ? pParent : GetDesktopWindow(), IDC_OUTLANE_PANEL); //super=CStatic
  //Create(NULL, "", style, CRect(0,0, 300, 450), pParent ? pParent : GetDesktopWindow(), IDC_OUTLANE_PANEL); //super=cwnd

  initialize();
  super::registerMouseListener(this);
}

void OutlineBrowserRenderer::initialize()
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserRenderer::initialize()");

  CSize size(22,23);
  CRect rect;

  GetClientRect(rect);
  size_t treeStyle = WS_VISIBLE | TVS_INFOTIP | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT | WS_CHILD | WS_BORDER | WS_TABSTOP;
  size_t border = 2;
  mOutline.EnableToolTips();
  mOutline.CreateEx(WS_EX_CLIENTEDGE, "SysTreeView32", "", treeStyle, CRect(CPoint(0, size.cy), CPoint(rect.Width(), rect.Height())), this, IDC_OUTLINE);
  mOutline.ModifyStyleEx(TVS_NOTOOLTIPS, TVS_INFOTIP);
  mOutline.ModifyStyle(TVS_NOTOOLTIPS, TVS_INFOTIP);
  mOutline.GetToolTips()->SetWindowPos(&wndTopMost, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
  mOutline.GetToolTips()->AddTool(&mOutline, LPSTR_TEXTCALLBACK, NULL, 0);
  mOutline.GetToolTips()->SetDelayTime(0, 1000);

#if _MSC_VER > 1200  // VC7
  mOutline.CreateEx(WS_EX_CLIENTEDGE, treeStyle, CRect(CPoint(0, size.cy), CPoint(rect.Width(), rect.Height())), this, IDC_OUTLINE);
#else
  getOutlinePanel().SetImageList(&ESBImageList::instance(), TVSIL_NORMAL );
#endif
  mOutline.SetWindowText("ffosfdgoosfg");

  GetWindowRect(rect);
  ScreenToClient(rect);

  rect.SetRect(CPoint(rect.right-size.cx, 0), CPoint(rect.right, size.cy));

  rect.OffsetRect(-border, 0);
  mSorted.Create(_T(""), getStyle(),rect, this, IDC_OUTLINE_SORT);
  mSorted.SetBitmaps(IDB_SORT_A, RGB(0,0,0), IDB_SORT_F);
  mSorted.SetTooltipText("Sort");
  mSorted.SetWindowPos(&wndTopMost,0,0,0,0,SWP_SHOWWINDOW|
                                    SWP_NOSIZE |SWP_NOMOVE);
  rect.OffsetRect(-size.cx, 0);
  mNoFields.Create(_T(""), getStyle(), rect, this, IDC_OUTLINE_NO_FIELDS);
  mNoFields.SetBitmaps(IDB_NO_FIELDS_A, RGB(0,0,0), IDB_NO_FIELDS_F);
  mNoFields.SetTooltipText("Hide Fields");

  rect.OffsetRect(-size.cx, 0);
  mNoStatic.Create(_T(""), getStyle(),rect, this, IDC_OUTLINE_NO_STATIC);
  mNoStatic.SetBitmaps(IDB_NO_STATIC_A, RGB(0,0,0), IDB_NO_STATIC_F);
  mNoStatic.SetTooltipText("Hide Static Members");

  rect.OffsetRect(-size.cx, 0);
  mPublicOnly.Create(_T(""), getStyle(), rect, this, IDC_OUTLINE_PUBLIC_ONLY);
  mPublicOnly.SetBitmaps(IDB_PUBLIC_ONLY_A, RGB(0,0,0), IDB_PUBLIC_ONLY_F, RGB(255,0,0));
  mPublicOnly.SetTooltipText("Hide Non-Public Members");

  size = CSize(29, size.cy);
  rect.OffsetRect(-size.cx, 0);
  rect.SetRect(rect.TopLeft(), CPoint(rect.TopLeft().x + size.cx , size.cy));
  mCustomFilter.Create(_T(""), getStyle(), rect, this, IDC_CUSTOM_FILTER);
  mCustomFilter.SetBitmaps(IDB_FILTER_A, RGB(0,0,0), IDB_FILTER_F, RGB(255,0,0));
  mCustomFilter.SetTooltipText("Custom Filter");

  mCustomFilter.SetMenu(IDR_CUSTOM_OUTLINE_FILTER, *this, true);
  mCustomFilter.GetMenu().RemoveMenu(0, MF_BYPOSITION);
  BCMenu *popup = mCustomFilter.GetMenu().AppendODPopupMenuA("Custom Filter");

  getOutlinePanel().ModifyStyle(0, TVS_SHOWSELALWAYS | LVS_SINGLESEL, 0);

}

size_t OutlineBrowserRenderer::getStyle()
{
  return WS_CHILD | WS_VISIBLE | WS_GROUP | WS_TABSTOP | BS_BITMAP | BS_AUTOCHECKBOX | BS_NOTIFY;
}

/////////////////////////////////////////////////////////////////////////////
// OutlineBrowserRenderer message handlers

void OutlineBrowserRenderer::render()
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserRenderer::render()");

  getOutlinePanel().SetRedraw(false);
  getOutlinePanel().DeleteAllItems();

  render(getController().getChildrenOf(NULL), TVI_ROOT);

  getOutlinePanel().SetRedraw(true);
}

void OutlineBrowserRenderer::render(const TagList &elements, HTREEITEM parent)
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserRenderer::render(const TagList&, HTREEITEM)");

  LabelBroker broker;
  //for_each(outline.begin(), outline.end(), bind(&MetaObject::acceptVisitor, _1, &outliner));
  for(TagList::const_iterator element = elements.begin(); element != elements.end(); element++) {

    HTREEITEM x = getOutlinePanel().InsertItem(broker.getLabel(*(*element)).c_str(), parent);
    int icon = ESBImageList::instance().getIcon(*(*element));
	  getOutlinePanel().SetItemImage(x, icon, icon);
    getOutlinePanel().SetItemData(x, (long)element->get());

    render(getController().getChildrenOf(element->get()), x);
    if(parent == TVI_ROOT) {
      getOutlinePanel().Expand(x, TVE_EXPAND);
    }
	}
}

void OutlineBrowserRenderer::showPopupMenu(MetaObject *tag, short x, short y)
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserRenderer::render(MetaObject*, short, short)");

  if(tag) {
    CMenu menu;
	  menu.LoadMenu(IDR_OUTLINE_BROWSER_POPUPMENU);
	  CMenu* pPopup = menu.GetSubMenu(0);

    if(tag->getDeclaration().getFile().empty()) {
      pPopup->EnableMenuItem(ID_OUTLINEBROWSER_HEADER, MF_GRAYED);
    }
    if(tag->getDefinition().getFile().empty()) {
      pPopup->EnableMenuItem(ID_OUTLINEBROWSER_SOURCE, MF_GRAYED);
    }
    MetaObjectTyper typer;
    tag->acceptVisitor(&typer);
    if(!(typer.getType() & (eClass | eStruct | eUnion))) {
      pPopup->EnableMenuItem(ID_OUTLINEBROWSER_HIERARCHY, MF_GRAYED);
    }
 	  pPopup->TrackPopupMenu(TPM_LEFTALIGN, x, y, this);
  }
}

void OutlineBrowserRenderer::onSort()
{
  const static string function("OutlineBrowserRenderer::onSort()");
  Tracer trc(NO_LABEL, RENDERER, function);

  try {
    getOutlinePanel().SetFocus();
    getController().sortOrderChanged(mSorted.GetCheck() == 1);

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }
}

void OutlineBrowserRenderer::onPublicOnly()
{
  const static string function("OutlineBrowserRenderer::onPublicOnly()");
  Tracer trc(NO_LABEL, RENDERER, function);

  try {
	  getOutlinePanel().SetFocus();
	  getController().publicMemberFilterChanged(mPublicOnly.GetCheck() == 1);

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }
}

void OutlineBrowserRenderer::onNoStatic()
{
  const static string function("OutlineBrowserRenderer::onNoStatic()");
  Tracer trc(NO_LABEL, RENDERER, function);

  try {
	  getOutlinePanel().SetFocus();
	  getController().staticMemberFilterChanged(mNoStatic.GetCheck() == 1);

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }
}

void OutlineBrowserRenderer::onNoFields()
{
  const static string function("OutlineBrowserRenderer::onNoFields()");
  Tracer trc(NO_LABEL, RENDERER, function);

  try {
	  getOutlinePanel().SetFocus();
	  getController().fieldFilterChanged(mNoFields.GetCheck() == 1);

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }
}

void OutlineBrowserRenderer::onCustomFilter()
{
  const static string function("OutlineBrowserRenderer::onCustomFilter()");
  Tracer trc(NO_LABEL, RENDERER, function);

  try {
	  getOutlinePanel().SetFocus();
    bool isChecked = mCustomFilter.GetCheck() == 1;

    CPoint pos = GetMessagePos();
    CRect rect;
    mCustomFilter.GetWindowRect(&rect);

    if(pos.x < rect.left + 10 ) {
      if(!isChecked) {
        mCustomFilter.SetCheck(TRUE);
      }
      if(!getController().customFilterChanged() && isChecked) {
        mCustomFilter.SetCheck(FALSE);
        return;
      }
    }

	  getController().customFilterEnabled(isChecked);

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }
}

void OutlineBrowserRenderer::onGotoHeader()
{
  const static string function("OutlineBrowserRenderer::onGotoHeader()");
  Tracer trc(NO_LABEL, RENDERER, function);

  try {
	  getController().gotoHeader();

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }
}

void OutlineBrowserRenderer::onGotoSource()
{
  const static string function("OutlineBrowserRenderer::onGotoSource()");
  Tracer trc(NO_LABEL, RENDERER, function);

  try {
	  getController().gotoSource();

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }
}

void OutlineBrowserRenderer::onInspectTag()
{
  const static string function("OutlineBrowserRenderer::onInspectTag()");
  Tracer trc(NO_LABEL, RENDERER, function);

  try {
	  getController().inspect();

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }
}

void OutlineBrowserRenderer::onShowHierarchy()
{
  static const string function = "OutlineBrowserRenderer::onShowHierarchy()";
  Tracer trc(NO_LABEL, RENDERER, function);

  try {
    getController().gotoHierarchy();

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }
}

void OutlineBrowserRenderer::onMouseClicked(NMHDR* pNMHDR, LRESULT* pResult)
{
  static const string function = "OutlineBrowserRenderer::onMouseClicked(NMHDR*, LRESULT*) ";
  Tracer trc(NO_LABEL, RENDERER, function);

  *pResult = 0;

  MSG msg;
  if(!PeekMessage(&msg, *this, WM_MOUSEFIRST , WM_MOUSELAST , PM_NOREMOVE)){
    msg.wParam = 0;
  }

  size_t clickCount = 0;
  MouseEvent::MouseButton button;
  CWnd *wnd = &getOutlinePanel();
  switch(pNMHDR->code) {
    case NM_CLICK:   button = MouseEvent::eLeftButton;  clickCount = 1; break;
    case NM_DBLCLK:  button = MouseEvent::eLeftButton;  clickCount = 2; break;
    case NM_RCLICK:  button = MouseEvent::eRightButton; clickCount = 1; break;
    case NM_RDBLCLK: button = MouseEvent::eRightButton; clickCount = 2; break;
  }

  mouseClicked(MouseEvent(MouseEvent::eClicked, button | msg.wParam, wnd, GetMessagePos(), clickCount));
}

void OutlineBrowserRenderer::mouseClicked(const MouseEvent &e)
{
  static const string function = "OutlineBrowserRenderer::mouseClicked(MouseEvent)";
  Tracer trc(NO_LABEL, RENDERER, function);

  TagRetriever retriever(&getOutlinePanel());

  list<MetaObject*> selection;
  HTREEITEM item = getOutlinePanel().GetFirstSelectedItem();
  while(item != NULL) {
    selection.push_back(retriever.getTag(item));
    item = getOutlinePanel().GetNextSelectedItem(item);
  }

  getController().tagSelectionChanged(selection);
  getController().tagSelectionChanged(retriever.getTagAt(e.getPoint(), true), e);
}

void OutlineBrowserRenderer::setCaption(const std::string &text)
{
  //SetWindowText(text.c_str());
}

std::string OutlineBrowserRenderer::getCaption()
{
  CString text;
  GetWindowText(text);
  return text.GetBuffer(0);
}

std::pair<short, short> OutlineBrowserRenderer::getPosition()
{
  CRect rect;
  GetWindowRect(&rect);
  return make_pair(rect.TopLeft().x , rect.TopLeft().y);
}

void OutlineBrowserRenderer::setPosition(short x, short y)
{
  SetWindowPos( NULL, x, y, 0 , 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOOWNERZORDER);
}

void OutlineBrowserRenderer::show()
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserRenderer::show()");
  ShowWindow(SW_SHOW);
}

void OutlineBrowserRenderer::hide()
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserRenderer::hide()");
  ShowWindow(SW_HIDE);
}

void OutlineBrowserRenderer::OnSize(UINT nType, int cx, int cy)
{
  static const string function = "OutlineBrowserRenderer::OnSize()";
  Tracer trc(NO_LABEL, RENDERER, function);

  try{
    super::OnSize(nType, cx, cy);

    if(!m_hWnd || !mOutline.m_hWnd) return;

    // start deferring window pos
    HDWP hdwp=BeginDeferWindowPos(20);

    CRect buttonBar;
    mSorted.GetWindowRect(buttonBar);
    DeferWindowPos(hdwp,mOutline,NULL, 0, 0, cx, cy-buttonBar.Height(), SWP_NOZORDER | SWP_NOMOVE | SWP_NOOWNERZORDER);

    int distance = cx - mOld.Width();
    if(distance) {
      moveChild(mSorted, distance, 0, hdwp);
      moveChild(mNoFields, distance, 0, hdwp);
      moveChild(mNoStatic, distance, 0, hdwp);
      moveChild(mPublicOnly, distance, 0, hdwp);
      moveChild(mCustomFilter, distance, 0, hdwp);
    }

    // do the deferred window position change
    EndDeferWindowPos(hdwp);

    //store current rect
    GetWindowRect(&mOld);

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }
}

void OutlineBrowserRenderer::moveChild(const CWnd &wnd, int x, int y, HDWP hdwp)
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserRenderer::moveChild()");

  CRect rect;
  wnd.GetWindowRect(&rect);
  ScreenToClient(rect);
  rect.OffsetRect(x, y);
  DeferWindowPos(hdwp,wnd,NULL, rect.left, rect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE);
}

int OutlineBrowserRenderer::OnCreate(LPCREATESTRUCT create)
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserRenderer::OnCreate()");

  if(mOld == CRect(0,0,0,0)) {
    mOld.SetRect(create->x, create->y, create->cx, create->cy);
  }

  return super::OnCreate(create);
}

int OutlineBrowserRenderer::onToolTipNotify(UINT, NMHDR *pNMHDR, LRESULT *pResult)
{
  static const string function = "OutlineBrowserRenderer::onToolTipNotify()";
  Tracer trc(NO_LABEL, RENDERER, function);

  try{

    TOOLTIPTEXT *pTTT = (TOOLTIPTEXT*)pNMHDR;
    getOutlinePanel().GetToolTips()->SetWindowPos(&wndTopMost, 0,0,0,0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE);

    if((pTTT->uFlags & TTF_IDISHWND) && ::GetDlgCtrlID((HWND)pNMHDR->idFrom))
    {
      MetaObject *object = TagRetriever(&getOutlinePanel()).getTagAt(GetMessagePos(), false);
      if(object && PropertiesManager::instance().getProperty(Browsers::SHOW_TOOLTIPS, "1") == "1") {
        pTTT->lpszText = "item xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
      }

      pTTT->hinst = NULL;
      return TRUE;
    }

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }

  return FALSE;

}

void OutlineBrowserRenderer::onGetToolTip(NMHDR* pNMHDR, LRESULT* pResult)
{
  static const string function = "OutlineBrowserRenderer::onGetToolTip()";
  Tracer trc(NO_LABEL, RENDERER, function);

  try {

    NMTVGETINFOTIP *pInfoTip = (NMTVGETINFOTIP*)pNMHDR;
    *pResult = 1;

    MetaObject *object = TagRetriever(&getOutlinePanel()).getTag(pInfoTip->hItem);
    if(object && PropertiesManager::instance().getProperty(Browsers::SHOW_TOOLTIPS, "1") == "1") {
      static string hack; //.c_str() is tmp only and the InfoTip doesnt copy it imediatly !
      hack = TooltipBroker().getTooltip(*object);
      pInfoTip->pszText = (char*)hack.c_str();
      getOutlinePanel().GetToolTips()->SetWindowPos(&wndTopMost, 0,0,0,0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE);
      *pResult = 0;
    }

  } catch(std::exception &e) {
    log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog;

  } catch(...) {
    log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog;
  }
}

///////////////////////////////////////////////
//
///////////////////////////////////////////////
OutlineBrowserDialog::OutlineBrowserDialog()
: RaisableDialog(IDD_EMPTY_DIALOG), mOutline(NULL)
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserDialog::OutlineBrowserDialog()");

  setHoverTimeKey(Browsers::Outline::HOVERTIME);
  setRaiseCornerKey(Browsers::Outline::RAISECORNER);
  setPositionKey(Browsers::Outline::POSITION);
  setIcon(IDI_OUTLINE);
}

void OutlineBrowserDialog::show()
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserDialog::show()");

	bool modal = false;

//  getRenderer().renderOutline(getModel(), getFilter());
//  setCaption(mOutlineName);

//  if(modal) {
//    DoModal();

//  } else {
    if(!m_hWnd) {
		  Create(IDD_EMPTY_DIALOG,CWnd::GetDesktopWindow());
    }
    ShowWindow(SW_SHOW);
//  }
}

void OutlineBrowserDialog::hide()
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserDialog::hide()");
  super::hide();
}

void OutlineBrowserDialog::close()
{
}

void OutlineBrowserDialog::moveToForeground()
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserDialog::moveToForeground()");
  super::moveToForeground();
}

BOOL OutlineBrowserDialog::OnInitDialog()
{
  Tracer trc(NO_LABEL, RENDERER, "OutlineBrowserDialog::OnInitDialog()");

  RaisableDialog::OnInitDialog();

  CWnd *outline = &dynamic_cast<CWnd&>(mOutline);
  CRect rect;
  outline->GetWindowRect(&rect);
  SetWindowPos(NULL, 0, 0, rect.Width()+7, rect.Height()+26, SWP_NOZORDER | SWP_NOMOVE);
  outline->SetParent(this);
  outline->ShowWindow(SW_SHOW);

  AddControl(IDC_OUTLANE_PANEL,sizeResize,sizeResize);

  setFocusableWindow(dynamic_cast<CWnd&>(mOutline).GetDlgItem(IDC_OUTLINE));

  return TRUE;
}

max_stars_repo_name: Kochise/BeSweet

max_issues_repo_name: Kochise/BeSweet

max_forks_repo_name: Kochise/BeSweet


text:
// Copyright 2019 Google LLC
//
// 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.

#include "src/dcmtkUtils.h"
#include <dcmtk/dcmdata/dcdeftag.h>
#include <dcmtk/dcmdata/dcdict.h>
#include <dcmtk/dcmdata/dcfilefo.h>
#include <dcmtk/dcmdata/dcostrmf.h>
#include <dcmtk/dcmdata/dcpixseq.h>
#include <dcmtk/dcmdata/dcpxitem.h>
#include <dcmtk/dcmdata/dcuid.h>
#include <dcmtk/dcmdata/dcvrat.h>
#include <dcmtk/dcmdata/dcwcache.h>
#include <dcmtk/dcmdata/libi2d/i2d.h>
#include <dcmtk/dcmdata/libi2d/i2doutpl.h>
#include <dcmtk/dcmdata/libi2d/i2dplsc.h>
#include <boost/chrono.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/log/trivial.hpp>
#include <boost/thread/thread.hpp>
#include <ctime>
#include <iomanip>
#include <string>
#include <utility>
#include <vector>

namespace wsiToDicomConverter {

inline OFCondition generateFramePositionMetadata(DcmDataset* resultObject,
                                                 uint32_t numberOfFrames,
                                                 uint32_t rowSize, uint32_t row,
                                                 uint32_t column, uint32_t x,
                                                 uint32_t y) {
  std::unique_ptr<DcmSequenceOfItems> PerFrameFunctionalGroupsSequence =
      std::make_unique<DcmSequenceOfItems>(
          DCM_PerFrameFunctionalGroupsSequence);
  for (uint32_t frameNumber = 0; frameNumber < numberOfFrames; frameNumber++) {
    if (column > rowSize) {
      column = 1;
      row++;
    }
    std::string index = std::to_string(column) + "\\" + std::to_string(row);
    std::unique_ptr<DcmItem> dimension = std::make_unique<DcmItem>();
    dimension->putAndInsertString(DCM_DimensionIndexValues, index.c_str());

    std::unique_ptr<DcmSequenceOfItems> sequenceDimension =
        std::make_unique<DcmSequenceOfItems>(DCM_FrameContentSequence);
    sequenceDimension->insert(dimension.release());

    std::unique_ptr<DcmItem> pixelPosition = std::make_unique<DcmItem>();
    pixelPosition->putAndInsertSint32(DCM_ColumnPositionInTotalImagePixelMatrix,
                                      (column - 1) * x + 1);
    pixelPosition->putAndInsertSint32(DCM_RowPositionInTotalImagePixelMatrix,
                                      (row - 1) * y + 1);

    std::unique_ptr<DcmSequenceOfItems> sequencePosition =
        std::make_unique<DcmSequenceOfItems>(DCM_PlanePositionSlideSequence);
    sequencePosition->insert(pixelPosition.release());

    std::unique_ptr<DcmItem> positionItem = std::make_unique<DcmItem>();
    positionItem->insert(sequenceDimension.release());
    positionItem->insert(sequencePosition.release());
    PerFrameFunctionalGroupsSequence->insert(positionItem.release());
    column++;
  }
  return resultObject->insert(PerFrameFunctionalGroupsSequence.release());
}

inline OFCondition generateSharedFunctionalGroupsSequence(
    DcmDataset* resultObject, double pixelSizeMm) {
  if (pixelSizeMm <= 0) {
    pixelSizeMm = 0.1;
  }
  std::unique_ptr<DcmItem> sharedFunctionalGroupsSequence =
      std::make_unique<DcmItem>();
  std::unique_ptr<DcmItem> pixelMeasuresSequence = std::make_unique<DcmItem>();
  std::string pixelSizeMmStr = std::to_string(pixelSizeMm);
  pixelSizeMmStr = pixelSizeMmStr + "\\" + pixelSizeMmStr;
  pixelMeasuresSequence->putAndInsertString(DCM_PixelSpacing,
                                            pixelSizeMmStr.c_str());
  sharedFunctionalGroupsSequence->insertSequenceItem(
      DCM_PixelMeasuresSequence, pixelMeasuresSequence.release());
  return resultObject->insertSequenceItem(
      DCM_SharedFunctionalGroupsSequence,
      sharedFunctionalGroupsSequence.release());
}

inline std::unique_ptr<DcmItem> pointerItem(char* dimensionOrganizationUIDstr) {
  std::unique_ptr<DcmItem> pointerItem = std::make_unique<DcmItem>();
  pointerItem->putAndInsertOFStringArray(DCM_DimensionOrganizationUID,
                                         dimensionOrganizationUIDstr);
  std::unique_ptr<DcmAttributeTag> slideSequence =
      std::make_unique<DcmAttributeTag>(DCM_FunctionalGroupPointer);
  slideSequence->putTagVal(DCM_PlanePositionSlideSequence);
  std::unique_ptr<DcmAttributeTag> columnPosition =
      std::make_unique<DcmAttributeTag>(DCM_DimensionIndexPointer);
  columnPosition->putTagVal(DCM_ColumnPositionInTotalImagePixelMatrix);
  pointerItem->insert(slideSequence.release());
  pointerItem->insert(columnPosition.release());
  return pointerItem;
}

inline OFCondition generateDimensionIndexSequence(DcmDataset* resultObject) {
  std::unique_ptr<DcmItem> dimensionOrganizationUID =
      std::make_unique<DcmItem>();
  char dimensionOrganizationUIDstr[100];
  dimensionOrganizationUID->putAndInsertOFStringArray(
      DCM_DimensionOrganizationUID,
      dcmGenerateUniqueIdentifier(dimensionOrganizationUIDstr,
                                  SITE_STUDY_UID_ROOT));
  std::unique_ptr<DcmSequenceOfItems> dimensionOrganizationSequence =
      std::make_unique<DcmSequenceOfItems>(DCM_DimensionOrganizationSequence);
  dimensionOrganizationSequence->insert(dimensionOrganizationUID.release());
  resultObject->insert(dimensionOrganizationSequence.release());

  std::unique_ptr<DcmSequenceOfItems> sequence =
      std::make_unique<DcmSequenceOfItems>(DCM_DimensionIndexSequence);
  sequence->insert(pointerItem(dimensionOrganizationUIDstr).release());
  sequence->insert(pointerItem(dimensionOrganizationUIDstr).release());
  return resultObject->insert(sequence.release());
}

std::string formatTime(std::string format) {
  std::stringstream stringStream;
  struct tm utcTime;
  time_t timeNow = time(nullptr);
  gmtime_r(&timeNow, &utcTime);
  stringStream << std::put_time(&utcTime, format.c_str());
  return stringStream.str();
}

std::string currentDate() { return formatTime("%Y%m%d"); }
std::string currentTime() { return formatTime("%OH%OM%OS"); }

OFCondition insertPixelMetadata(DcmDataset* dataset,
                                const DcmtkImgDataInfo& imgInfo,
                                uint32_t numberOfFrames) {
  OFCondition cond =
      dataset->putAndInsertUint16(DCM_SamplesPerPixel, imgInfo.samplesPerPixel);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertOFStringArray(DCM_PhotometricInterpretation,
                                            imgInfo.photoMetrInt);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_PlanarConfiguration, imgInfo.planConf);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_Rows, imgInfo.rows);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_Columns, imgInfo.cols);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_BitsAllocated, imgInfo.bitsAlloc);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_BitsStored, imgInfo.bitsStored);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_HighBit, imgInfo.highBit);
  if (cond.bad()) return cond;

  if (numberOfFrames >= 1) {
    char buf[10];
    int err = snprintf(buf, sizeof(buf), "%u", numberOfFrames);
    if (err == -1) return EC_IllegalCall;
    cond = dataset->putAndInsertOFStringArray(DCM_NumberOfFrames, buf);
    if (cond.bad()) return cond;

    cond = dataset->putAndInsertString(DCM_FrameIncrementPointer, "");
    if (cond.bad()) return cond;
  }

  return dataset->putAndInsertUint16(DCM_PixelRepresentation,
                                     imgInfo.pixelRepr);
}

OFCondition generateDcmDataset(I2DOutputPlug* outPlug, DcmDataset* resultDset,
                               const DcmtkImgDataInfo& imgInfo,
                               uint32_t numberOfFrames) {
  if (!outPlug) return EC_IllegalParameter;

  OFCondition cond = insertPixelMetadata(resultDset, imgInfo, numberOfFrames);

  if (cond.bad()) {
    return cond;
  }

  std::string lossy = "00";
  if (imgInfo.transSyn == EXS_JPEGProcess1) {
    lossy = "01";
  }
  cond = resultDset->putAndInsertOFStringArray(DCM_LossyImageCompression,
                                               lossy.c_str(), true);

  if (cond.bad()) return cond;

  cond = outPlug->convert(*resultDset);
  if (cond.bad()) {
    return cond;
  }

  if (cond.bad()) {
    return cond;
  }
  return EC_Normal;
}

OFCondition DcmtkUtils::populateDataSet(
    const int64_t imageHeight, const int64_t imageWidth, const uint32_t rowSize,
    const std::string& studyId, const std::string& seriesId,
    const std::string& imageName, std::unique_ptr<DcmPixelData> pixelData,
    const DcmtkImgDataInfo& imgInfo, const uint32_t numberOfFrames,
    const uint32_t row, const uint32_t column, const int level,
    const int batchNumber, const uint32_t offset,
    const uint32_t totalNumberOfFrames, const bool tiled,
    DcmTags* additionalTags, const double firstLevelWidthMm,
    const double firstLevelHeightMm, DcmDataset* dataSet) {
  std::unique_ptr<I2DOutputPlug> outPlug;

  OFString pixDataFile, outputFile;

  outPlug = std::make_unique<I2DOutputPlugSC>();
  if (outPlug.get() == nullptr) return EC_MemoryExhausted;

  OFBool insertType2 = OFTrue;
  OFBool inventType1 = OFTrue;
  OFBool doChecks = OFTrue;

  outPlug->setValidityChecking(doChecks, insertType2, inventType1);

  if (!dcmDataDict.isDictionaryLoaded()) {
    dcmDataDict.wrlock().reloadDictionaries(true, false);
    dcmDataDict.unlock();
  }

  OFCondition cond =
      generateDcmDataset(outPlug.get(), dataSet, imgInfo, numberOfFrames);

  if (cond.bad()) return cond;

  cond = dataSet->insert(pixelData.release());
  if (cond.bad()) return cond;

  cond = generateDateTags(dataSet);

  if (cond.bad()) return cond;

  cond = insertIds(studyId, seriesId, dataSet);

  if (cond.bad()) return cond;

  cond = insertBaseImageTags(imageName, imageHeight, imageWidth,
                             firstLevelWidthMm, firstLevelHeightMm, dataSet);

  if (cond.bad()) return cond;

  insertMultiFrameTags(imgInfo, numberOfFrames, rowSize, row, column, level,
                       batchNumber, offset, totalNumberOfFrames, tiled,
                       seriesId, dataSet);
  if (cond.bad()) return cond;

  cond = insertStaticTags(dataSet);

  if (cond.bad()) return cond;

  cond = generateSharedFunctionalGroupsSequence(
      dataSet, firstLevelHeightMm / imageHeight);
  if (cond.bad()) return cond;

  cond = generateDimensionIndexSequence(dataSet);

  if (cond.bad()) return cond;

  if (additionalTags != nullptr) {
    additionalTags->populateDataset(dataSet);
  }

  return cond;
}

OFCondition DcmtkUtils::generateDateTags(DcmDataset* dataSet) {
  OFCondition cond = dataSet->putAndInsertOFStringArray(DCM_ContentDate,
                                                        currentDate().c_str());
  if (cond.good())
    cond = dataSet->putAndInsertOFStringArray(DCM_ContentTime,
                                              currentTime().c_str());
  return cond;
}

OFCondition DcmtkUtils::insertStaticTags(DcmDataset* dataSet) {
  OFCondition cond = dataSet->putAndInsertOFStringArray(
      DCM_SOPClassUID, UID_VLWholeSlideMicroscopyImageStorage);
  if (cond.bad()) return cond;
  cond = dataSet->putAndInsertOFStringArray(DCM_Modality, "SM");
  if (cond.bad()) return cond;
  cond = dataSet->putAndInsertOFStringArray(DCM_ImageType,
                                            "DERIVED\\PRIMARY\\VOLUME\\NONE");
  if (cond.bad()) return cond;
  cond = dataSet->putAndInsertOFStringArray(DCM_ImageOrientationSlide,
                                            "0\\-1\\0\\-1\\0\\0");
  if (cond.bad()) return cond;
  dataSet->putAndInsertUint16(DCM_RepresentativeFrameNumber, 1);

  return cond;
}

OFCondition DcmtkUtils::insertIds(const std::string& studyId,
                                  const std::string& seriesId,
                                  DcmDataset* dataSet) {
  char instanceUidGenerated[100];
  dcmGenerateUniqueIdentifier(instanceUidGenerated, SITE_INSTANCE_UID_ROOT);
  OFCondition cond = dataSet->putAndInsertOFStringArray(DCM_SOPInstanceUID,
                                                        instanceUidGenerated);
  if (cond.bad()) return cond;
  cond =
      dataSet->putAndInsertOFStringArray(DCM_StudyInstanceUID, studyId.c_str());
  if (cond.bad()) return cond;
  cond = dataSet->putAndInsertOFStringArray(DCM_SeriesInstanceUID,
                                            seriesId.c_str());
  return cond;
}

OFCondition DcmtkUtils::insertBaseImageTags(const std::string& imageName,
                                            const int64_t imageHeight,
                                            const int64_t imageWidth,
                                            const double firstLevelWidthMm,
                                            const double firstLevelHeightMm,
                                            DcmDataset* dataSet) {
  OFCondition cond = dataSet->putAndInsertOFStringArray(DCM_SeriesDescription,
                                                        imageName.c_str());
  if (cond.bad()) return cond;
  cond = dataSet->putAndInsertUint32(DCM_TotalPixelMatrixColumns, imageWidth);
  if (cond.bad()) return cond;
  cond = dataSet->putAndInsertUint32(DCM_TotalPixelMatrixRows, imageHeight);
  if (firstLevelWidthMm > 0 && firstLevelHeightMm > 0 && cond.good()) {
    cond =
        dataSet->putAndInsertFloat32(DCM_ImagedVolumeWidth, firstLevelWidthMm);
    if (cond.bad()) return cond;
    cond = dataSet->putAndInsertFloat32(DCM_ImagedVolumeHeight,
                                        firstLevelHeightMm);
  }
  return cond;
}

OFCondition DcmtkUtils::insertMultiFrameTags(
    const DcmtkImgDataInfo& imgInfo, const uint32_t numberOfFrames,
    const uint32_t rowSize, const uint32_t row, const uint32_t column,
    const int level, const int batchNumber, const uint32_t offset,
    const uint32_t totalNumberOfFrames, const bool tiled,
    const std::string& seriesId, DcmDataset* dataSet) {
  unsigned int concatenationTotalNumber;

  if (totalNumberOfFrames - offset == numberOfFrames) {
    concatenationTotalNumber = batchNumber + 1;
  } else {
    concatenationTotalNumber =
        std::ceil(static_cast<double>(totalNumberOfFrames) /
                  static_cast<double>(numberOfFrames));
  }

  OFCondition cond = dataSet->putAndInsertOFStringArray(
      DCM_InstanceNumber, std::to_string(level + 1).c_str());
  if (concatenationTotalNumber > 1 && cond.good()) {
    cond =
        dataSet->putAndInsertUint32(DCM_ConcatenationFrameOffsetNumber, offset);
    if (cond.bad()) return cond;
    cond =
        dataSet->putAndInsertUint16(DCM_InConcatenationNumber, batchNumber + 1);
    if (cond.bad()) return cond;
    cond = dataSet->putAndInsertUint16(DCM_InConcatenationTotalNumber,
                                       concatenationTotalNumber);
    if (cond.bad()) return cond;
    cond = dataSet->putAndInsertOFStringArray(
        DCM_ConcatenationUID,
        (seriesId + "." + std::to_string(level + 1)).c_str());
  }
  if (cond.bad()) return cond;
  cond = dataSet->putAndInsertOFStringArray(
      DCM_FrameOfReferenceUID,
      (seriesId + "." + std::to_string(level + 1)).c_str());
  if (cond.bad()) return cond;
  if (tiled) {
    cond = dataSet->putAndInsertOFStringArray(DCM_DimensionOrganizationType,
                                              "TILED_FULL");
  } else {
    cond = dataSet->putAndInsertOFStringArray(DCM_DimensionOrganizationType,
                                              "TILED_SPARSE");
    if (cond.bad()) return cond;
    cond = generateFramePositionMetadata(dataSet, numberOfFrames, rowSize, row,
                                         column, imgInfo.rows, imgInfo.cols);
  }
  return cond;
}

OFCondition DcmtkUtils::startConversion(
    int64_t imageHeight, int64_t imageWidth, uint32_t rowSize,
    const std::string& studyId, const std::string& seriesId,
    const std::string& imageName, std::unique_ptr<DcmPixelData> pixelData,
    const DcmtkImgDataInfo& imgInfo, uint32_t numberOfFrames, uint32_t row,
    uint32_t column, int level, int batchNumber, uint32_t offset,
    uint32_t totalNumberOfFrames, bool tiled, DcmOutputStream* outStream) {
  return startConversion(imageHeight, imageWidth, rowSize, studyId, seriesId,
                         imageName, std::move(pixelData), imgInfo,
                         numberOfFrames, row, column, level, batchNumber,
                         offset, totalNumberOfFrames, tiled, nullptr, 0.0, 0.0,
                         outStream);
}

OFCondition DcmtkUtils::startConversion(
    int64_t imageHeight, int64_t imageWidth, uint32_t rowSize,
    const std::string& studyId, const std::string& seriesId,
    const std::string& imageName, std::unique_ptr<DcmPixelData> pixelData,
    const DcmtkImgDataInfo& imgInfo, uint32_t numberOfFrames, uint32_t row,
    uint32_t column, int level, int batchNumber, unsigned int offset,
    uint32_t totalNumberOfFrames, bool tiled, DcmTags* additionalTags,
    double firstLevelWidthMm, double firstLevelHeightMm,
    DcmOutputStream* outStream) {
  E_GrpLenEncoding grpLenEncoding = EGL_recalcGL;
  E_EncodingType encodingType = EET_ExplicitLength;
  E_PaddingEncoding paddingEncoding = EPD_noChange;
  OFCmdUnsignedInt filepad = 0;
  OFCmdUnsignedInt itempad = 0;
  E_FileWriteMode writeMode = EWM_fileformat;

  std::unique_ptr<DcmDataset> resultObject = std::make_unique<DcmDataset>();

  OFCondition cond = populateDataSet(
      imageHeight, imageWidth, rowSize, studyId, seriesId, imageName,
      std::move(pixelData), imgInfo, numberOfFrames, row, column, level,
      batchNumber, offset, totalNumberOfFrames, tiled, additionalTags,
      firstLevelWidthMm, firstLevelHeightMm, resultObject.get());

  DcmFileFormat dcmFileFormat(resultObject.get());

  DcmWriteCache wcache;
  cond = outStream->status();
  if (cond.good()) {
    dcmFileFormat.transferInit();
    cond = dcmFileFormat.write(*outStream, imgInfo.transSyn, encodingType,
                               &wcache, grpLenEncoding, paddingEncoding,
                               OFstatic_cast(Uint32, filepad),
                               OFstatic_cast(Uint32, itempad), 0, writeMode);
    dcmFileFormat.transferEnd();
  }
  if (cond.bad()) {
    BOOST_LOG_TRIVIAL(error) << "error"
                             << ": " << cond.text();
  }
  return cond;
}

}  // namespace wsiToDicomConverter


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 (c) 2018, Open AI Lab
 * Author: jingyou@openailab.com
 */
// caffe.hpp is the header file that you need to include in your code. It wraps
// all the internal caffe header files into one for simpler inclusion.

#ifndef __CAFFE_CAFFE_HPP_
#define __CAFFE_CAFFE_HPP_

#include <boost/shared_ptr.hpp>

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/net.hpp"
#include "caffe/io.hpp"
#include "caffe.pb.h"

#endif  // __CAFFE_CAFFE_HPP_

max_stars_repo_name: xiangchaosheng/Tengine

max_issues_repo_name: xiangchaosheng/Tengine

max_forks_repo_name: xiangchaosheng/Tengine