<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include <iostream>
#include <string>
#include <exception>
#include <vector>

#include <msgpack.hpp>
#include <jubatus/core/common/big_endian.hpp>
#include <jubatus/core/common/jsonconfig/config.hpp>
#include <jubatus/core/common/jsonconfig/cast.hpp>
#include <jubatus/util/data/serialization/unordered_map.h>
#include <jubatus/util/text/json.h>
#include <jubatus/util/lang/cast.h>

#include "third_party/cmdline/cmdline.h"

#include "jubatus/dump/classifier.hpp"
#include "jubatus/dump/recommender.hpp"
#include "jubatus/dump/anomaly.hpp"

using std::runtime_error;
using jubatus::core::common::read_big_endian;
using jubatus::util::lang::lexical_cast;
using jubatus::util::text::json::from_json;

namespace jubatus {
namespace dump {

struct model {
  std::string type_;
  jubatus::core::common::jsonconfig::config config_;
  std::vector<char> user_data_;
};

void read(std::ifstream& ifs, model& m) {
  // TODO(unno): This implementation ignores checksums, version, and all other
  // check codes. We need to re-implemenet such process like
  // jubatus::server::framework::save_server/load_server, or to use these
  // methods to show file format errors.

  ifs.exceptions(std::ifstream::failbit);

  std::vector<char> system_data_buf;
  try {
    char header_buf[48];
    ifs.read(header_buf, 48);

    uint64_t system_data_size = read_big_endian<uint64_t>(&header_buf[32]);
    system_data_buf.resize(system_data_size);
    ifs.read(&system_data_buf[0], system_data_size);

    uint64_t user_data_size = read_big_endian<uint64_t>(&header_buf[40]);
    m.user_data_.resize(user_data_size);
    ifs.read(&m.user_data_[0], user_data_size);
  } catch (std::ios_base::failure& e) {
    throw runtime_error("Input stream reached end of file.");
  }

  if (ifs.peek() != -1) {
    std::ifstream::pos_type pos = ifs.tellg();
    throw runtime_error("Input stream remains. Position: " +
        lexical_cast<std::string>(pos));
  }
  ifs.close();

  msgpack::unpacked msg;
  msgpack::unpack(&msg, system_data_buf.data(), system_data_buf.size());
  msgpack::object system_data = msg.get();
  std::string config;
  system_data.via.array.ptr[2].convert(&m.type_);
  system_data.via.array.ptr[4].convert(&config);
  m.config_ = jubatus::core::common::jsonconfig::config(
      jubatus::util::lang::lexical_cast<
          jubatus::util::text::json::json>(config));
}

template <typename T, typename D>
void dump(model& m, jubatus::util::text::json::json& js) {
  msgpack::unpacked msg_user;
  msgpack::unpack(&msg_user, m.user_data_.data(), m.user_data_.size());

  // obj[0] is the version of the saved model file
  T data;
  msg_user.get().via.array.ptr[1].convert(&data);

  D dump(data);
  js = jubatus::util::text::json::to_json(dump);
}

int run(const std::string& path) try {
  std::ifstream ifs(path.c_str());
  if (!ifs) {
    throw runtime_error("Cannot open: " + path);
  }

  model m;
  jubatus::util::text::json::json js;

  try {
    read(ifs, m);
  } catch (const std::exception& e) {
    throw runtime_error(std::string("invalid model file structure: ") +
                        e.what());
  }

  if (m.type_ == "classifier") {
    dump<classifier<local_storage>,
        classifier_dump<local_storage, local_storage_dump> >(m, js);
  } else if (m.type_ == "recommender") {
    std::string method;
    from_json<std::string>(m.config_["method"].get(), method);
    if (method == "inverted_index") {
      dump<recommender<inverted_index>,
           recommender_dump<inverted_index_recommender_dump> >(m, js);
    } else {
      throw runtime_error("recommender method \"" + method +
                          "\" is not supported for dump");
    }
  } else if (m.type_ == "anomaly") {
    std::string method, backend_method;
    from_json<std::string>(m.config_["method"].get(), method);
    from_json<std::string>(m.config_["parameter"]["method"].get(),
                           backend_method);
    if (method == "lof") {
      if (backend_method == "inverted_index") {
        dump<
            anomaly<lof<inverted_index> >,
            anomaly_dump<lof<inverted_index>, lof_dump<
                inverted_index, inverted_index_recommender_dump> > >(m, js);
      } else {
        throw runtime_error("backend recommender method \"" + backend_method +
                            "\" is not supported for dump");
      }
    } else {
      throw runtime_error("anomaly method \"" + method +
                          "\" is not supported for dump");
    }
  } else {
    throw runtime_error("type \"" + m.type_ +
                        "\" is not supported for dump");
  }

  js.pretty(std::cout, true);
  return 0;
} catch (const std::exception& e) {
  std::cerr << "Error: failed to dump \"" << path
            << "\": " << e.what() << std::endl;
  return -1;
}

}  // namespace dump
}  // namespace jubatus

int main(int argc, char* argv[]) {
  cmdline::parser p;
  p.add<std::string>("input", 'i', "Input file");
  p.parse_check(argc, argv);

  return jubatus::dump::run(p.get<std::string>("input"));
}
<commit_msg>support regression<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include <iostream>
#include <string>
#include <exception>
#include <vector>

#include <msgpack.hpp>
#include <jubatus/core/common/big_endian.hpp>
#include <jubatus/core/common/jsonconfig/config.hpp>
#include <jubatus/core/common/jsonconfig/cast.hpp>
#include <jubatus/util/data/serialization/unordered_map.h>
#include <jubatus/util/text/json.h>
#include <jubatus/util/lang/cast.h>

#include "third_party/cmdline/cmdline.h"

#include "jubatus/dump/classifier.hpp"
#include "jubatus/dump/recommender.hpp"
#include "jubatus/dump/anomaly.hpp"

using std::runtime_error;
using jubatus::core::common::read_big_endian;
using jubatus::util::lang::lexical_cast;
using jubatus::util::text::json::from_json;

namespace jubatus {
namespace dump {

struct model {
  std::string type_;
  jubatus::core::common::jsonconfig::config config_;
  std::vector<char> user_data_;
};

void read(std::ifstream& ifs, model& m) {
  // TODO(unno): This implementation ignores checksums, version, and all other
  // check codes. We need to re-implemenet such process like
  // jubatus::server::framework::save_server/load_server, or to use these
  // methods to show file format errors.

  ifs.exceptions(std::ifstream::failbit);

  std::vector<char> system_data_buf;
  try {
    char header_buf[48];
    ifs.read(header_buf, 48);

    uint64_t system_data_size = read_big_endian<uint64_t>(&header_buf[32]);
    system_data_buf.resize(system_data_size);
    ifs.read(&system_data_buf[0], system_data_size);

    uint64_t user_data_size = read_big_endian<uint64_t>(&header_buf[40]);
    m.user_data_.resize(user_data_size);
    ifs.read(&m.user_data_[0], user_data_size);
  } catch (std::ios_base::failure& e) {
    throw runtime_error("Input stream reached end of file.");
  }

  if (ifs.peek() != -1) {
    std::ifstream::pos_type pos = ifs.tellg();
    throw runtime_error("Input stream remains. Position: " +
        lexical_cast<std::string>(pos));
  }
  ifs.close();

  msgpack::unpacked msg;
  msgpack::unpack(&msg, system_data_buf.data(), system_data_buf.size());
  msgpack::object system_data = msg.get();
  std::string config;
  system_data.via.array.ptr[2].convert(&m.type_);
  system_data.via.array.ptr[4].convert(&config);
  m.config_ = jubatus::core::common::jsonconfig::config(
      jubatus::util::lang::lexical_cast<
          jubatus::util::text::json::json>(config));
}

template <typename T, typename D>
void dump(model& m, jubatus::util::text::json::json& js) {
  msgpack::unpacked msg_user;
  msgpack::unpack(&msg_user, m.user_data_.data(), m.user_data_.size());

  // obj[0] is the version of the saved model file
  T data;
  msg_user.get().via.array.ptr[1].convert(&data);

  D dump(data);
  js = jubatus::util::text::json::to_json(dump);
}

int run(const std::string& path) try {
  std::ifstream ifs(path.c_str());
  if (!ifs) {
    throw runtime_error("Cannot open: " + path);
  }

  model m;
  jubatus::util::text::json::json js;

  try {
    read(ifs, m);
  } catch (const std::exception& e) {
    throw runtime_error(std::string("invalid model file structure: ") +
                        e.what());
  }

  if (m.type_ == "classifier" || m.type_ == "regression") {
    dump<classifier<local_storage>,
        classifier_dump<local_storage, local_storage_dump> >(m, js);
  } else if (m.type_ == "recommender") {
    std::string method;
    from_json<std::string>(m.config_["method"].get(), method);
    if (method == "inverted_index") {
      dump<recommender<inverted_index>,
           recommender_dump<inverted_index_recommender_dump> >(m, js);
    } else {
      throw runtime_error("recommender method \"" + method +
                          "\" is not supported for dump");
    }
  } else if (m.type_ == "anomaly") {
    std::string method, backend_method;
    from_json<std::string>(m.config_["method"].get(), method);
    from_json<std::string>(m.config_["parameter"]["method"].get(),
                           backend_method);
    if (method == "lof") {
      if (backend_method == "inverted_index") {
        dump<
            anomaly<lof<inverted_index> >,
            anomaly_dump<lof<inverted_index>, lof_dump<
                inverted_index, inverted_index_recommender_dump> > >(m, js);
      } else {
        throw runtime_error("backend recommender method \"" + backend_method +
                            "\" is not supported for dump");
      }
    } else {
      throw runtime_error("anomaly method \"" + method +
                          "\" is not supported for dump");
    }
  } else {
    throw runtime_error("type \"" + m.type_ +
                        "\" is not supported for dump");
  }

  js.pretty(std::cout, true);
  return 0;
} catch (const std::exception& e) {
  std::cerr << "Error: failed to dump \"" << path
            << "\": " << e.what() << std::endl;
  return -1;
}

}  // namespace dump
}  // namespace jubatus

int main(int argc, char* argv[]) {
  cmdline::parser p;
  p.add<std::string>("input", 'i', "Input file");
  p.parse_check(argc, argv);

  return jubatus::dump::run(p.get<std::string>("input"));
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <random>
#include <nanikanizer/nanikanizer.hpp>

typedef std::pair<int, std::valarray<float>> image_type;
static const std::size_t channel_size = 32 * 32;
static const std::size_t whole_size = channel_size * 3;

template <class Iterator>
void load_images(const std::string& file, Iterator it)
{
	std::ifstream is(file, std::ios_base::binary);

	std::vector<char> buffer(whole_size);
	std::valarray<float> values(whole_size);

	while (true)
	{
		int type = is.get();
		if (is.eof())
			break;

		is.read(buffer.data(), whole_size);

		for (std::size_t i = 0; i < channel_size; ++i)
		{
			values[i * 3] = static_cast<float>(static_cast<unsigned char>(buffer[i]));
			values[i * 3 + 1] = static_cast<float>(static_cast<unsigned char>(buffer[i + channel_size]));
			values[i * 3 + 2] = static_cast<float>(static_cast<unsigned char>(buffer[i + channel_size * 2]));
		}

		values -= values.sum() / values.size();
		values /= (values * values).sum() / values.size();

		*it++ = image_type(type, values);
	}
}

int main(int /*argc*/, char* /*argv*/[])
{
	try
	{
		std::vector<std::string> data_files =
		{
			"data_batch_1.bin",
			"data_batch_2.bin",
			"data_batch_3.bin",
			"data_batch_4.bin",
			"data_batch_5.bin",
		};

		std::string test_file = "test_batch.bin";

		std::vector<image_type> data_images;
		std::vector<image_type> test_images;

		for (const std::string& file : data_files)
			load_images(file, std::back_inserter(data_images));

		load_images(test_file, std::back_inserter(test_images));

		std::size_t id_size = 10;

		std::vector<std::valarray<float>> ids(id_size);

		for (std::size_t i = 0; i < id_size; ++i)
		{
			std::valarray<float> id(id_size);
			id[i] = 1.0f;
			ids[i] = id;
		}

		typedef std::pair<std::string, std::shared_ptr<nnk::optimizer_base>> named_optimizer_type;

		std::vector<named_optimizer_type> optimizers =
		{
			std::make_pair("SGD", std::make_shared<nnk::sgd_optimizer>()),
			std::make_pair("AdaGrad", std::make_shared<nnk::adagrad_optimizer>()),
			std::make_pair("RMSProp", std::make_shared<nnk::rmsprop_optimizer>()),
			std::make_pair("AdaDelta", std::make_shared<nnk::adadelta_optimizer>()),
			std::make_pair("Adam", std::make_shared<nnk::adam_optimizer>()),
		};

		for (auto& key_value : optimizers)
		{
			std::ofstream os(key_value.first + ".log");

			std::cout << std::fixed << std::setprecision(5);
			os << std::fixed << std::setprecision(5);

			std::cout << key_value.first << std::endl;
			os << key_value.first << std::endl;

			nnk::linear_layer<float> l1(75, 6);
			nnk::linear_layer<float> l2(150, 16);
			nnk::linear_layer<float> l3(400, 120);
			nnk::linear_layer<float> l4(120, 84);
			nnk::linear_layer<float> l5(84, id_size);

			std::size_t batch_size = 900;

			nnk::variable<float> x1;
			nnk::variable<float> y;

			auto x2 = nnk::convolution_2d(x1.expr(), 32, 32, 3, 5, 5);
			auto x3 = nnk::relu(l1(x2));
			auto x4 = nnk::max_pooling_2d(x3, 28, 28, 6, 2, 2);
			auto x5 = nnk::convolution_2d(x4, 14, 14, 6, 5, 5);
			auto x6 = nnk::relu(l2(x5));
			auto x7 = nnk::max_pooling_2d(x6, 10, 10, 16, 2, 2);
			auto x8 = nnk::relu(l3(x7));
			auto x9 = nnk::relu(l4(x8));
			auto x10 = nnk::softmax(l5(x9), id_size);
			auto loss = nnk::cross_entropy(x10 - y.expr());

			auto get_answer = [&](std::size_t index)
			{
				const auto& r = x10.root()->output();
				auto begin = &r[index * id_size];
				auto end = begin + id_size;
				auto it = std::max_element(begin, end);
				return it - begin;
			};

			nnk::evaluator<float> ev(loss);

			auto& optimizer = *key_value.second;

			optimizer.add_parameter(l1);
			optimizer.add_parameter(l2);
			optimizer.add_parameter(l3);
			optimizer.add_parameter(l4);
			optimizer.add_parameter(l5);

			std::mt19937 generator;
			std::uniform_int<std::size_t> index_generator(0, data_images.size() - 1);

			for (std::size_t i = 0; i < 100; ++i)
			{
				x1.value().resize(batch_size * whole_size);
				y.value().resize(batch_size * id_size);

				for (std::size_t j = 0; j < 300; ++j)
				{
					for (std::size_t k = 0; k < batch_size; ++k)
					{
						std::size_t index = index_generator(generator);
						const image_type& image = data_images[index];

						for (std::size_t l = 0; l < whole_size; ++l)
							x1.value()[k * whole_size + l] = image.second[l];

						for (std::size_t l = 0; l < id_size; ++l)
							y.value()[k * id_size + l] = ids[image.first][l];
					}

					optimizer.zero_grads();

					double loss_value = ev.forward()[0];
					ev.backward();

					std::cout << loss_value << std::endl;
					os << loss_value << std::endl;

					optimizer.update();
				}

				std::size_t count_ok = 0;

				for (const auto& image : test_images)
				{
					x1.value() = image.second;

					ev.forward();

					if (get_answer(0) == image.first)
						++count_ok;
				}

				double rate = static_cast<double>(count_ok) / static_cast<double>(test_images.size());
				std::cout << "rate: " << rate << std::endl;
			}
		}
	}
	catch (std::exception& e)
	{
		std::cerr << e.what() << std::endl;
		return -1;
	}

	return 0;
}
<commit_msg>Regularization<commit_after>#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <random>
#include <nanikanizer/nanikanizer.hpp>

typedef std::pair<int, std::valarray<float>> image_type;
static const std::size_t channel_size = 32 * 32;
static const std::size_t whole_size = channel_size * 3;

template <class Iterator>
void load_images(const std::string& file, Iterator it)
{
	std::ifstream is(file, std::ios_base::binary);

	std::vector<char> buffer(whole_size);
	std::valarray<float> values(whole_size);

	while (true)
	{
		int type = is.get();
		if (is.eof())
			break;

		is.read(buffer.data(), whole_size);

		for (std::size_t i = 0; i < channel_size; ++i)
		{
			values[i * 3] = static_cast<float>(static_cast<unsigned char>(buffer[i]));
			values[i * 3 + 1] = static_cast<float>(static_cast<unsigned char>(buffer[i + channel_size]));
			values[i * 3 + 2] = static_cast<float>(static_cast<unsigned char>(buffer[i + channel_size * 2]));
		}

		values -= values.sum() / values.size();
		values /= (values * values).sum() / values.size();

		*it++ = image_type(type, values);
	}
}

int main(int /*argc*/, char* /*argv*/[])
{
	try
	{
		std::vector<std::string> data_files =
		{
			"data_batch_1.bin",
			"data_batch_2.bin",
			"data_batch_3.bin",
			"data_batch_4.bin",
			"data_batch_5.bin",
		};

		std::string test_file = "test_batch.bin";

		std::vector<image_type> data_images;
		std::vector<image_type> test_images;

		for (const std::string& file : data_files)
			load_images(file, std::back_inserter(data_images));

		load_images(test_file, std::back_inserter(test_images));

		std::size_t id_size = 10;

		std::vector<std::valarray<float>> ids(id_size);

		for (std::size_t i = 0; i < id_size; ++i)
		{
			std::valarray<float> id(id_size);
			id[i] = 1.0f;
			ids[i] = id;
		}

		typedef std::pair<std::string, std::shared_ptr<nnk::optimizer_base>> named_optimizer_type;

		std::vector<named_optimizer_type> optimizers =
		{
			std::make_pair("SGD", std::make_shared<nnk::sgd_optimizer>()),
			std::make_pair("AdaGrad", std::make_shared<nnk::adagrad_optimizer>()),
			std::make_pair("RMSProp", std::make_shared<nnk::rmsprop_optimizer>()),
			std::make_pair("AdaDelta", std::make_shared<nnk::adadelta_optimizer>()),
			std::make_pair("Adam", std::make_shared<nnk::adam_optimizer>()),
		};

		for (auto& key_value : optimizers)
		{
			std::ofstream os(key_value.first + ".log");

			std::cout << std::fixed << std::setprecision(5);
			os << std::fixed << std::setprecision(5);

			std::cout << key_value.first << std::endl;
			os << key_value.first << std::endl;

			nnk::linear_layer<float> l1(75, 6);
			nnk::linear_layer<float> l2(150, 16);
			nnk::linear_layer<float> l3(400, 120);
			nnk::linear_layer<float> l4(120, 84);
			nnk::linear_layer<float> l5(84, id_size);

			std::size_t batch_size = 900;

			nnk::variable<float> x1;
			nnk::variable<float> y;

			auto x2 = nnk::convolution_2d(x1.expr(), 32, 32, 3, 5, 5);
			auto x3 = nnk::relu(l1(x2));
			auto x4 = nnk::max_pooling_2d(x3, 28, 28, 6, 2, 2);
			auto x5 = nnk::convolution_2d(x4, 14, 14, 6, 5, 5);
			auto x6 = nnk::relu(l2(x5));
			auto x7 = nnk::max_pooling_2d(x6, 10, 10, 16, 2, 2);
			auto x8 = nnk::relu(l3(x7));
			auto x9 = nnk::relu(l4(x8));
			auto x10 = nnk::softmax(l5(x9), id_size);
			auto x11 = nnk::cross_entropy(x10 - y.expr());

			auto reg =
				nnk::sum(nnk::abs(l1.weight())) +
				nnk::sum(nnk::abs(l2.weight())) +
				nnk::sum(nnk::abs(l3.weight())) +
				nnk::sum(nnk::abs(l4.weight())) +
				nnk::sum(nnk::abs(l5.weight()));

			auto loss = x11 + reg * nnk::expression<float>(0.1f);

			auto get_answer = [&](std::size_t index)
			{
				const auto& r = x10.root()->output();
				auto begin = &r[index * id_size];
				auto end = begin + id_size;
				auto it = std::max_element(begin, end);
				return it - begin;
			};

			nnk::evaluator<float> ev(loss);

			auto& optimizer = *key_value.second;

			optimizer.add_parameter(l1);
			optimizer.add_parameter(l2);
			optimizer.add_parameter(l3);
			optimizer.add_parameter(l4);
			optimizer.add_parameter(l5);

			std::mt19937 generator;
			std::uniform_int<std::size_t> index_generator(0, data_images.size() - 1);

			for (std::size_t i = 0; i < 100; ++i)
			{
				x1.value().resize(batch_size * whole_size);
				y.value().resize(batch_size * id_size);

				float last_loss = 0.0f;

				for (std::size_t j = 0; j < 100; ++j)
				{
					for (std::size_t k = 0; k < batch_size; ++k)
					{
						std::size_t index = index_generator(generator);
						const image_type& image = data_images[index];

						for (std::size_t l = 0; l < whole_size; ++l)
							x1.value()[k * whole_size + l] = image.second[l];

						for (std::size_t l = 0; l < id_size; ++l)
							y.value()[k * id_size + l] = ids[image.first][l];
					}

					optimizer.zero_grads();

					last_loss = ev.forward()[0];
					ev.backward();

					optimizer.update();
				}

				std::size_t count_ok = 0;

				for (const auto& image : test_images)
				{
					x1.value() = image.second;

					ev.forward();

					if (get_answer(0) == image.first)
						++count_ok;
				}

				double rate = static_cast<double>(count_ok) / static_cast<double>(test_images.size());
				std::cout << last_loss << "\t" << rate << std::endl;
				os << last_loss << "\t" << rate << std::endl;
			}
		}
	}
	catch (std::exception& e)
	{
		std::cerr << e.what() << std::endl;
		return -1;
	}

	return 0;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Minimalistic Vulkan Triangle sample
//
//

#define USE_GLSL
#define VERTEX_BUFFER_BIND_ID 0

// vulkan utilities.
#include "vku.hpp"

class triangle_example : public vku::window
{
public:
  struct {
    glm::mat4 projectionMatrix;
    glm::mat4 modelMatrix;
    glm::mat4 viewMatrix;
  } uniform_data;

  vku::buffer vertex_buffer;
  vku::buffer index_buffer;
  vku::buffer uniform_buffer;
  vku::descriptorPool descPool;
  vku::pipeline pipe;
  vku::shaderModule vertexShader;
  vku::shaderModule fragmentShader;
  size_t num_indices;

  triangle_example() : vku::window(false, 1280, 720, -2.5f, "triangle") {

    // Vertices
    struct Vertex { float pos[3]; float col[3]; };

    static const Vertex vertex_data[] = {
      { { 1.0f,  1.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } },
      { { -1.0f,  1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } },
      { { 0.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f} }
    };

    vertex_buffer = vku::buffer(device(), (void*)vertex_data, sizeof(vertex_data), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);

    // Indices
    static const uint32_t index_data[] = { 0, 1, 2 };
    index_buffer = vku::buffer(device(), (void*)index_data, sizeof(index_data), VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
    num_indices = 3;

    // Binding state
    vku::pipelineCreateHelper pipeHelper;
    pipeHelper.binding(VERTEX_BUFFER_BIND_ID, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX);
    pipeHelper.attrib(0, VERTEX_BUFFER_BIND_ID, VK_FORMAT_R32G32B32_SFLOAT, 0);
    pipeHelper.attrib(1, VERTEX_BUFFER_BIND_ID, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 3);

    uniform_buffer = vku::buffer(device(), (void*)nullptr, sizeof(uniform_data), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);

    vertexShader = vku::shaderModule(device(), "data/shaders/triangle.vert", VK_SHADER_STAGE_VERTEX_BIT);
    fragmentShader = vku::shaderModule(device(), "data/shaders/triangle.frag", VK_SHADER_STAGE_FRAGMENT_BIT);

    pipeHelper.uniformBuffers(1, VK_SHADER_STAGE_VERTEX_BIT);

    pipeHelper.shader(vertexShader, VK_SHADER_STAGE_VERTEX_BIT);
    pipeHelper.shader(fragmentShader, VK_SHADER_STAGE_FRAGMENT_BIT);

    pipe = vku::pipeline(device(), swapChain().renderPass(), pipelineCache(), pipeHelper);

    descPool = vku::descriptorPool(device());

    pipe.allocateDescriptorSets(descPool);
    pipe.updateDescriptorSets(uniform_buffer);

    for (int32_t i = 0; i < swapChain().imageCount(); ++i) {
      const vku::cmdBuffer &cmdbuf = drawCmdBuffer(i);
      cmdbuf.begin(swapChain().renderPass(), swapChain().frameBuffer(i), width(), height());

      cmdbuf.bindPipeline(pipe);
      cmdbuf.bindVertexBuffer(vertex_buffer, VERTEX_BUFFER_BIND_ID);
      cmdbuf.bindIndexBuffer(index_buffer);
      cmdbuf.drawIndexed((uint32_t)num_indices, 1, 0, 0, 1);

      cmdbuf.end(swapChain().image(i));
    }

    updateUniformBuffers();
  }

  void draw()
  {
    present();
  }

  void updateUniformBuffers()
  {
    uniform_data.projectionMatrix = defaultProjectionMatrix();
    uniform_data.viewMatrix = defaultViewMatrix();
    uniform_data.modelMatrix = defaultModelMatrix();

    void *dest = uniform_buffer.map();
    memcpy(dest, &uniform_data, sizeof(uniform_data));
    uniform_buffer.unmap();
  }

  void render() override
  {
    device().waitIdle();
    draw();
    device().waitIdle();
  }

  void viewChanged() override
  {
    // This function is called by the base example class
    // each time the view is changed by user input
    updateUniformBuffers();
  }
};

int main(const int argc, const char *argv[]) {
  try {
    triangle_example my_example;

    while (vku::window::poll()) {
      if (my_example.windowIsClosed()) {
        break;
      }
      my_example.render();
    }
  } catch(std::runtime_error &e) {
    printf("fail: %s\n", e.what());
  }

  return 0;
}
<commit_msg>Lance's feedback<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Minimalistic Vulkan Triangle sample
//
//

// vulkan utilities.
#include "vku.hpp"

class triangle_example : public vku::window
{
public:
  struct {
    glm::mat4 projectionMatrix;
    glm::mat4 modelMatrix;
    glm::mat4 viewMatrix;
  } uniform_data;

  vku::buffer vertex_buffer;
  vku::buffer index_buffer;
  vku::buffer uniform_buffer;

  vku::descriptorPool descPool;
  vku::pipeline pipe;

  vku::shaderModule vertexShader;
  vku::shaderModule fragmentShader;
  size_t num_indices;

  static const int VERTEX_BUFFER_BIND_ID = 0;

  triangle_example() : vku::window(false, 1280, 720, -2.5f, "triangle") {

    // Vertices
    struct Vertex { float pos[3]; float col[3]; };

    static const Vertex vertex_data[] = {
      { { 1.0f,  1.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } },
      { { -1.0f,  1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } },
      { { 0.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f} }
    };

    vertex_buffer = vku::buffer(device(), (void*)vertex_data, sizeof(vertex_data), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);

    // Indices
    static const uint32_t index_data[] = { 0, 1, 2 };
    index_buffer = vku::buffer(device(), (void*)index_data, sizeof(index_data), VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
    num_indices = 3;

    // Binding state
    vku::pipelineCreateHelper pipeHelper;
    pipeHelper.binding(VERTEX_BUFFER_BIND_ID, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX);
    pipeHelper.attrib(0, VERTEX_BUFFER_BIND_ID, VK_FORMAT_R32G32B32_SFLOAT, 0);
    pipeHelper.attrib(1, VERTEX_BUFFER_BIND_ID, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 3);

    uniform_buffer = vku::buffer(device(), (void*)nullptr, sizeof(uniform_data), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);

    vertexShader = vku::shaderModule(device(), "data/shaders/triangle.vert", VK_SHADER_STAGE_VERTEX_BIT);
    fragmentShader = vku::shaderModule(device(), "data/shaders/triangle.frag", VK_SHADER_STAGE_FRAGMENT_BIT);

    pipeHelper.uniformBuffers(1, VK_SHADER_STAGE_VERTEX_BIT);

    pipeHelper.shader(vertexShader, VK_SHADER_STAGE_VERTEX_BIT);
    pipeHelper.shader(fragmentShader, VK_SHADER_STAGE_FRAGMENT_BIT);

    pipe = vku::pipeline(device(), swapChain().renderPass(), pipelineCache(), pipeHelper);

    descPool = vku::descriptorPool(device());

    pipe.allocateDescriptorSets(descPool);
    pipe.updateDescriptorSets(uniform_buffer);

    for (int32_t i = 0; i < swapChain().imageCount(); ++i) {
      const vku::cmdBuffer &cmdbuf = drawCmdBuffer(i);
      cmdbuf.begin(swapChain().renderPass(), swapChain().frameBuffer(i), width(), height());

      cmdbuf.bindPipeline(pipe);
      cmdbuf.bindVertexBuffer(vertex_buffer, VERTEX_BUFFER_BIND_ID);
      cmdbuf.bindIndexBuffer(index_buffer);
      cmdbuf.drawIndexed((uint32_t)num_indices, 1, 0, 0, 1);

      cmdbuf.end(swapChain().image(i));
    }

    updateUniformBuffers();
  }

  void updateUniformBuffers()
  {
    uniform_data.projectionMatrix = defaultProjectionMatrix();
    uniform_data.viewMatrix = defaultViewMatrix();
    uniform_data.modelMatrix = defaultModelMatrix();

    void *dest = uniform_buffer.map();
    memcpy(dest, &uniform_data, sizeof(uniform_data));
    uniform_buffer.unmap();
  }

  void render() override
  {
    device().waitIdle();
    present();
    device().waitIdle();
  }

  void viewChanged() override
  {
    // This function is called by the base example class
    // each time the view is changed by user input
    updateUniformBuffers();
  }
};

int main(const int argc, const char *argv[]) {
  try {
    triangle_example my_example;

    while (vku::window::poll()) {
      if (my_example.windowIsClosed()) {
        break;
      }
      my_example.render();
    }
  } catch(std::runtime_error &e) {
    printf("fail: %s\n", e.what());
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

int main() {
  std::cout << "Hello World" << std::endl;
}<commit_msg>Code sample to show how pool works<commit_after>#include <iostream>

#include "SafeQueue.h"
#include "ThreadPool.h"
#include <utility>

// Simple function that adds multiplies two numbers and prints the result
void multiply(const int a, const int b) {
  // Simulate hard computation
  _sleep(2000);
  const int res = a * b;
  std::cout << a << " * " << b << " = " << res << std::endl;
}

// Same as before but now we have an output parameter
void multiply_output(const int a, const int b, int & res) {
  // Simulate hard computation
  _sleep(2000);
  res = a * b;
  std::cout << a << " * " << b << " = " << res << std::endl;
}

int main() {
  // Create pool with 3 threads
  ThreadPool pool(3);
  // Initialize pool
  pool.init();

  // Initialize local variables
  int res;
  const int a = 2, b = 3, c = 4, d = 5;

  // Submit multiplication table
  for (int i = 1; i < 10; ++i) {
    for (int j = 1; j < 10; ++j) {
      pool.submit(multiply, i, j);
    }
  }

  // Submit some functions to execute
  auto multiply_future = pool.submit(multiply_output, a, b, std::ref(res));

  // Wait for multiplication output to finish
  multiply_future.get();
  std::cout << "Last operation result is equals to " << res << std::endl;

  _sleep(10000);
  pool.shutdown();
}<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-2014, Dan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "main.h"

#include <map>

#include "sdk/amx/amx.h"
#include "sdk/amx/amx2.h"
#include "sdk/plugincommon.h"

#include "time.h"
#include "timers.h"
#include "natives.h"

extern void *pAMXFunctions;
logprintf_t logprintf;

const AMX_NATIVE_INFO NATIVES[] =
{
    {"KillPlayerTimers", Natives::KillPlayerTimers},
    {"SetTimer_", Natives::SetTimer_},
    {"SetTimerEx_", Natives::SetTimerEx_},
    {"SetPlayerTimer", Natives::SetPlayerTimer},
    {"SetPlayerTimerEx", Natives::SetPlayerTimerEx},
    {"SetPlayerTimer_", Natives::SetPlayerTimer_},
    {"SetPlayerTimerEx_", Natives::SetPlayerTimerEx_},
    {"GetTimerFunctionName", Natives::GetTimerFunctionName},
    {"SetTimerInterval", Natives::SetTimerInterval},
    {"GetTimerInterval", Natives::GetTimerInterval},
    {"GetTimerIntervalLeft", Natives::GetTimerIntervalLeft},
    {"SetTimerDelay", Natives::SetTimerDelay},
    {"SetTimerCount", Natives::SetTimerCount},
    {"GetTimerCallsLeft", Natives::GetTimerCallsLeft},
    {NULL, NULL}
};

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()
{
    return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData)
{
    logprintf = (logprintf_t) ppData[PLUGIN_DATA_LOGPRINTF];
    pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
    InitTime();
    logprintf("  >> TimerFix " PLUGIN_VERSION " successfully loaded.");
    return true;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx)
{
    amx_Redirect(amx, "SetTimer", (ucell) Natives::SetTimer, NULL);
    amx_Redirect(amx, "SetTimerEx", (ucell) Natives::SetTimerEx, NULL);
    amx_Redirect(amx, "KillTimer", (ucell) Natives::KillTimer, NULL);
    amx_Redirect(amx, "GetTickCount", (ucell) Natives::GetTickCount, NULL);
    return amx_Register(amx, NATIVES, -1);
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx)
{
    for (std::map<int, struct timer*>::iterator it = timers.begin(), next = it; it != timers.end(); it = next)
    {
        ++next;
        struct timer *t = it->second;
        if (t->amx == amx)
        {
            DestroyTimer(t);
            timers.erase(it);
        }
    }
    return AMX_ERR_NONE;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload()
{
    logprintf("[plugin.timerfix] Plugsin successfully unloaded!");
}

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick()
{
    unsigned long long now = GetMsTime();
    for (std::map<int, struct timer*>::iterator it = timers.begin(), next = it; it != timers.end(); it = next)
    {
        ++next;
        struct timer *t = it->second;
        if (t->repeat != 0)
        {
            if (t->next < now)
            {
                t->next += t->interval;
                ExecuteTimer(it->second);
                if (t->repeat > 0)
                {
                    --t->repeat;
                }
            }
        }
        else
        {
            DestroyTimer(t);
            timers.erase(it);
        }
    }
}
<commit_msg>Fixed typo.<commit_after>/**
 * Copyright (c) 2013-2014, Dan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "main.h"

#include <map>

#include "sdk/amx/amx.h"
#include "sdk/amx/amx2.h"
#include "sdk/plugincommon.h"

#include "time.h"
#include "timers.h"
#include "natives.h"

extern void *pAMXFunctions;
logprintf_t logprintf;

const AMX_NATIVE_INFO NATIVES[] =
{
    {"KillPlayerTimers", Natives::KillPlayerTimers},
    {"SetTimer_", Natives::SetTimer_},
    {"SetTimerEx_", Natives::SetTimerEx_},
    {"SetPlayerTimer", Natives::SetPlayerTimer},
    {"SetPlayerTimerEx", Natives::SetPlayerTimerEx},
    {"SetPlayerTimer_", Natives::SetPlayerTimer_},
    {"SetPlayerTimerEx_", Natives::SetPlayerTimerEx_},
    {"GetTimerFunctionName", Natives::GetTimerFunctionName},
    {"SetTimerInterval", Natives::SetTimerInterval},
    {"GetTimerInterval", Natives::GetTimerInterval},
    {"GetTimerIntervalLeft", Natives::GetTimerIntervalLeft},
    {"SetTimerDelay", Natives::SetTimerDelay},
    {"SetTimerCount", Natives::SetTimerCount},
    {"GetTimerCallsLeft", Natives::GetTimerCallsLeft},
    {NULL, NULL}
};

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()
{
    return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData)
{
    logprintf = (logprintf_t) ppData[PLUGIN_DATA_LOGPRINTF];
    pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
    InitTime();
    logprintf("  >> TimerFix " PLUGIN_VERSION " successfully loaded.");
    return true;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx)
{
    amx_Redirect(amx, "SetTimer", (ucell) Natives::SetTimer, NULL);
    amx_Redirect(amx, "SetTimerEx", (ucell) Natives::SetTimerEx, NULL);
    amx_Redirect(amx, "KillTimer", (ucell) Natives::KillTimer, NULL);
    amx_Redirect(amx, "GetTickCount", (ucell) Natives::GetTickCount, NULL);
    return amx_Register(amx, NATIVES, -1);
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx)
{
    for (std::map<int, struct timer*>::iterator it = timers.begin(), next = it; it != timers.end(); it = next)
    {
        ++next;
        struct timer *t = it->second;
        if (t->amx == amx)
        {
            DestroyTimer(t);
            timers.erase(it);
        }
    }
    return AMX_ERR_NONE;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload()
{
    logprintf("[plugin.timerfix] Plugin successfully unloaded!");
}

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick()
{
    unsigned long long now = GetMsTime();
    for (std::map<int, struct timer*>::iterator it = timers.begin(), next = it; it != timers.end(); it = next)
    {
        ++next;
        struct timer *t = it->second;
        if (t->repeat != 0)
        {
            if (t->next < now)
            {
                t->next += t->interval;
                ExecuteTimer(it->second);
                if (t->repeat > 0)
                {
                    --t->repeat;
                }
            }
        }
        else
        {
            DestroyTimer(t);
            timers.erase(it);
        }
    }
}
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Vivek Galatage
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <include/v8.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace v8;
using namespace std;

Handle<ObjectTemplate> global_template;
Isolate *isolate;
class Point;

Handle<String> ReadFile(const char* name);

class Point
{
public:
    Point(){x_ = 0; y_ = 0;}
    Point(int x, int y) : x_(x), y_(y) {}
    int x_, y_;

    inline void mul( const double scale )
    {
        x_ *= scale;
        y_ *= scale;
    }
};

Point* UnwrapPoint( const FunctionCallbackInfo<v8::Value>& info )
{
        //Get the self object,
    Local<v8::Object> self = info.Holder();
        //Fetch the c++ pointer.
    Local<External> external = Local<External>::Cast( self->GetInternalField(0) );
        //Get back to the type.
    Point* pt = static_cast<Point*>( external->Value());
        //Return it
    return pt;
}

void GetPointX(Local<String> property,
                        const PropertyCallbackInfo<Value>& info)
{
    Local<Object> self = info.Holder();
    Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
    void* ptr = wrap->Value();
    int value = static_cast<Point*>(ptr)->x_;
    info.GetReturnValue().Set(Number::New(isolate, value));
}

void SetPointX(Local<String> property,
               Local<Value> value,
               const PropertyCallbackInfo<Value>& info)
{
    Local<Object> self = info.Holder();
    Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
    void* ptr = wrap->Value();
    static_cast<Point*>(ptr)->x_ = value->Int32Value();
}

void GetPointY(Local<String> property,
                        const PropertyCallbackInfo<Value>& info)
{
    Local<Object> self = info.Holder();
    Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
    void* ptr = wrap->Value();
    int value = static_cast<Point*>(ptr)->y_;
    info.GetReturnValue().Set(Number::New(isolate, value));
}

void SetPointY(Local<String> property,
               Local<Value> value,
               const PropertyCallbackInfo<Value>& info)
{
    Local<Object> self = info.Holder();
    Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
    void* ptr = wrap->Value();
    static_cast<Point*>(ptr)->y_ = value->Int32Value();
}

void MulCallback(const FunctionCallbackInfo<v8::Value>& args){
    int product = args.This()->Get(String::NewFromUtf8(isolate, "x"))->Int32Value() * args[0]->Int32Value();
    args.This()->Set(String::NewFromUtf8(isolate, "x"), Number::New(isolate, product));

    product = args.This()->Get(String::NewFromUtf8(isolate, "y"))->Int32Value() * args[0]->Int32Value();
    args.This()->Set(String::NewFromUtf8(isolate, "y"), Number::New(isolate, product));
}

// Defines a Point() JS Object
void PointConstructor( const FunctionCallbackInfo<v8::Value>& args )
{
    //Locker lock;
    HandleScope scope(isolate);
    Handle<ObjectTemplate> t = v8::ObjectTemplate::New();

    //The JavaScript point object only has 1 C++ object
    t->SetInternalFieldCount(1);

    // Create x and y members with starting values of 0
    //t->Set(String::New("x"), Number::New(0));
    t->SetAccessor(String::NewFromUtf8(isolate, "x"),
        (AccessorGetterCallback)GetPointX,
        (AccessorSetterCallback)SetPointX);

    //t->Set(String::New("y"), Number::New(0));
    t->SetAccessor(String::NewFromUtf8(isolate, "y"),
        (AccessorGetterCallback)GetPointY,
        (AccessorSetterCallback)SetPointY);

    // Create a mul(number) function that scales the point
    t->Set(String::NewFromUtf8(isolate, "mul"), FunctionTemplate::New(isolate, MulCallback));

    // for use in the if statement
    Point *p = NULL;
    Local<Object> obj;

    // If Point(x, y) ctor was passed in values assign them
    if(!args[0].IsEmpty() && args[0]->IsNumber() &&
        !args[1].IsEmpty() && args[1]->IsNumber()) {
            //t->Set(String::New("x"), args[0]);
            //t->Set(String::New("y"), args[1]);
            p = new Point(args[0]->Int32Value(), args[1]->Int32Value());
            obj = t->NewInstance();
            obj->SetInternalField(0, External::New(isolate, p));
    } else {
        /**
         * Wrap a point object
         */
        p = new Point(0, 0);
        obj = t->NewInstance();
        obj->SetInternalField(0, External::New(isolate, p));
    }

    // Return this newly created object
    args.GetReturnValue().Set(obj);
}

#define ANSI_COLOR_RED     "\x1b[31m"
#define ANSI_COLOR_GREEN   "\x1b[32m"
#define ANSI_COLOR_YELLOW  "\x1b[33m"
#define ANSI_COLOR_BLUE    "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN    "\x1b[36m"
#define ANSI_COLOR_RESET   "\x1b[0m"
void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
    const char* color = nullptr;
    const char* resetColor = ANSI_COLOR_RESET;
    if (!args[0].IsEmpty() && args[0]->IsNumber()) {
        switch (args[0]->Int32Value()) {
        case 1:
            color = ANSI_COLOR_GREEN;
            break;
        case 2:
            color = ANSI_COLOR_YELLOW;
            break;
        case 3:
            color = ANSI_COLOR_RED;
            break;
        }
    }
    for (int i = 1; i < args.Length(); i++) {
        v8::HandleScope handle_scope(args.GetIsolate());
        v8::String::Utf8Value str(args[i]);
        string myStr = *(str);
        const char* cstr = myStr.c_str();
        printf("%s%s %s", color, cstr, resetColor);
    }
    printf("\n", NULL);
}

int main()
{
    //Create the v8 environment
    /*Isolate**/ isolate = Isolate::New();
    Isolate::Scope isolate_scope(isolate);
    HandleScope handle_scope(isolate);

    /*Handle<ObjectTemplate>*/ global_template = ObjectTemplate::New(isolate);

    Handle<FunctionTemplate> obj = FunctionTemplate::New(isolate);
    obj->Set(String::NewFromUtf8(isolate, "Point"), FunctionTemplate::New(isolate, PointConstructor));

    // Tell global A JS Obj Point() can now be create and instructions on how to set up
    global_template->Set(String::NewFromUtf8(isolate, "Point"), FunctionTemplate::New(isolate, PointConstructor));

    Local<Context> context = Context::New(isolate, NULL, global_template);

    Context::Scope context_scope(context);

    Handle<v8::Object> global = context->Global();

    //global->Set(String::New("Point"), t);
    global->Set(v8::String::NewFromUtf8(isolate, "print"), v8::FunctionTemplate::New(isolate, Print)->GetFunction());

    string file = "foo.js";

    while(true){
        cout << "How many times do you want to run the script? \n" << endl;

        int n;

        cin >> n;

        cout << "" << endl;

        std::cin.get();

        Handle<String> source = ReadFile(file.c_str());

        if(source.IsEmpty())
        {
            cout << "Error reading file" << endl;
            cout << "Press enter to quit" << endl;
            cin.get();
            return 0;
        }

        //Compile
        Handle<Script> script = Script::Compile(source);

        //Run the script and print
        Handle<Value> result;

        result = script->Run();

    } // End of while

    //Exit program
    cout << "\nTest completed.  Press enter to exit program. \n" << endl;
    std::cin.get();

    return 0;
}

v8::Handle<String> ReadFile(const char* name)
{
    //Open the file
    FILE* file;
    file = fopen(name, "rb");

    //If there is no file, return an empty string
    if (file == NULL) return v8::Handle<v8::String>();

    //Set the pointer to the end of the file
    fseek(file, 0, SEEK_END);

    //Get the size of file
    int size = ftell(file);

    //Rewind the pointer to the beginning of the stream
    rewind(file);

    //Set up and read into the buffer
    char* chars = new char[size + 1];
    chars[size] = '\0';
    for (int i = 0 ; i < size;)
    {
        int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
        i += read;
    }

    //Close file
    fclose(file);

    v8::Handle<v8::String> result = v8::String::NewFromUtf8(isolate, chars, String::kNormalString, size);
    delete[] chars;
    return result;
}
<commit_msg>In case of no color, remove the 'null' apperaing on the log<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Vivek Galatage
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <include/v8.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace v8;
using namespace std;

Handle<ObjectTemplate> global_template;
Isolate *isolate;
class Point;

Handle<String> ReadFile(const char* name);

class Point
{
public:
    Point(){x_ = 0; y_ = 0;}
    Point(int x, int y) : x_(x), y_(y) {}
    int x_, y_;

    inline void mul( const double scale )
    {
        x_ *= scale;
        y_ *= scale;
    }
};

Point* UnwrapPoint( const FunctionCallbackInfo<v8::Value>& info )
{
        //Get the self object,
    Local<v8::Object> self = info.Holder();
        //Fetch the c++ pointer.
    Local<External> external = Local<External>::Cast( self->GetInternalField(0) );
        //Get back to the type.
    Point* pt = static_cast<Point*>( external->Value());
        //Return it
    return pt;
}

void GetPointX(Local<String> property,
                        const PropertyCallbackInfo<Value>& info)
{
    Local<Object> self = info.Holder();
    Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
    void* ptr = wrap->Value();
    int value = static_cast<Point*>(ptr)->x_;
    info.GetReturnValue().Set(Number::New(isolate, value));
}

void SetPointX(Local<String> property,
               Local<Value> value,
               const PropertyCallbackInfo<Value>& info)
{
    Local<Object> self = info.Holder();
    Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
    void* ptr = wrap->Value();
    static_cast<Point*>(ptr)->x_ = value->Int32Value();
}

void GetPointY(Local<String> property,
                        const PropertyCallbackInfo<Value>& info)
{
    Local<Object> self = info.Holder();
    Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
    void* ptr = wrap->Value();
    int value = static_cast<Point*>(ptr)->y_;
    info.GetReturnValue().Set(Number::New(isolate, value));
}

void SetPointY(Local<String> property,
               Local<Value> value,
               const PropertyCallbackInfo<Value>& info)
{
    Local<Object> self = info.Holder();
    Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
    void* ptr = wrap->Value();
    static_cast<Point*>(ptr)->y_ = value->Int32Value();
}

void MulCallback(const FunctionCallbackInfo<v8::Value>& args){
    int product = args.This()->Get(String::NewFromUtf8(isolate, "x"))->Int32Value() * args[0]->Int32Value();
    args.This()->Set(String::NewFromUtf8(isolate, "x"), Number::New(isolate, product));

    product = args.This()->Get(String::NewFromUtf8(isolate, "y"))->Int32Value() * args[0]->Int32Value();
    args.This()->Set(String::NewFromUtf8(isolate, "y"), Number::New(isolate, product));
}

// Defines a Point() JS Object
void PointConstructor( const FunctionCallbackInfo<v8::Value>& args )
{
    //Locker lock;
    HandleScope scope(isolate);
    Handle<ObjectTemplate> t = v8::ObjectTemplate::New();

    //The JavaScript point object only has 1 C++ object
    t->SetInternalFieldCount(1);

    // Create x and y members with starting values of 0
    //t->Set(String::New("x"), Number::New(0));
    t->SetAccessor(String::NewFromUtf8(isolate, "x"),
        (AccessorGetterCallback)GetPointX,
        (AccessorSetterCallback)SetPointX);

    //t->Set(String::New("y"), Number::New(0));
    t->SetAccessor(String::NewFromUtf8(isolate, "y"),
        (AccessorGetterCallback)GetPointY,
        (AccessorSetterCallback)SetPointY);

    // Create a mul(number) function that scales the point
    t->Set(String::NewFromUtf8(isolate, "mul"), FunctionTemplate::New(isolate, MulCallback));

    // for use in the if statement
    Point *p = NULL;
    Local<Object> obj;

    // If Point(x, y) ctor was passed in values assign them
    if(!args[0].IsEmpty() && args[0]->IsNumber() &&
        !args[1].IsEmpty() && args[1]->IsNumber()) {
            //t->Set(String::New("x"), args[0]);
            //t->Set(String::New("y"), args[1]);
            p = new Point(args[0]->Int32Value(), args[1]->Int32Value());
            obj = t->NewInstance();
            obj->SetInternalField(0, External::New(isolate, p));
    } else {
        /**
         * Wrap a point object
         */
        p = new Point(0, 0);
        obj = t->NewInstance();
        obj->SetInternalField(0, External::New(isolate, p));
    }

    // Return this newly created object
    args.GetReturnValue().Set(obj);
}

#define ANSI_COLOR_RED     "\x1b[31m"
#define ANSI_COLOR_GREEN   "\x1b[32m"
#define ANSI_COLOR_YELLOW  "\x1b[33m"
#define ANSI_COLOR_BLUE    "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN    "\x1b[36m"
#define ANSI_COLOR_RESET   "\x1b[0m"
void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
    const char* color = nullptr;
    const char* resetColor = ANSI_COLOR_RESET;
    if (!args[0].IsEmpty() && args[0]->IsNumber()) {
        switch (args[0]->Int32Value()) {
        case 1:
            color = ANSI_COLOR_GREEN;
            break;
        case 2:
            color = ANSI_COLOR_YELLOW;
            break;
        case 3:
            color = ANSI_COLOR_RED;
            break;
        }
    }
    for (int i = 1; i < args.Length(); i++) {
        v8::HandleScope handle_scope(args.GetIsolate());
        v8::String::Utf8Value str(args[i]);
        string myStr = *(str);
        const char* cstr = myStr.c_str();
        if (color)
            printf("%s%s %s", color, cstr, resetColor);
        else
            printf("%s %s", cstr, resetColor);
    }
    printf("\n", NULL);
}

int main()
{
    //Create the v8 environment
    /*Isolate**/ isolate = Isolate::New();
    Isolate::Scope isolate_scope(isolate);
    HandleScope handle_scope(isolate);

    /*Handle<ObjectTemplate>*/ global_template = ObjectTemplate::New(isolate);

    Handle<FunctionTemplate> obj = FunctionTemplate::New(isolate);
    obj->Set(String::NewFromUtf8(isolate, "Point"), FunctionTemplate::New(isolate, PointConstructor));

    // Tell global A JS Obj Point() can now be create and instructions on how to set up
    global_template->Set(String::NewFromUtf8(isolate, "Point"), FunctionTemplate::New(isolate, PointConstructor));

    Local<Context> context = Context::New(isolate, NULL, global_template);

    Context::Scope context_scope(context);

    Handle<v8::Object> global = context->Global();

    //global->Set(String::New("Point"), t);
    global->Set(v8::String::NewFromUtf8(isolate, "print"), v8::FunctionTemplate::New(isolate, Print)->GetFunction());

    string file = "foo.js";

    while(true){
        cout << "How many times do you want to run the script? \n" << endl;

        int n;

        cin >> n;

        cout << "" << endl;

        std::cin.get();

        Handle<String> source = ReadFile(file.c_str());

        if(source.IsEmpty())
        {
            cout << "Error reading file" << endl;
            cout << "Press enter to quit" << endl;
            cin.get();
            return 0;
        }

        //Compile
        Handle<Script> script = Script::Compile(source);

        //Run the script and print
        Handle<Value> result;

        result = script->Run();

    } // End of while

    //Exit program
    cout << "\nTest completed.  Press enter to exit program. \n" << endl;
    std::cin.get();

    return 0;
}

v8::Handle<String> ReadFile(const char* name)
{
    //Open the file
    FILE* file;
    file = fopen(name, "rb");

    //If there is no file, return an empty string
    if (file == NULL) return v8::Handle<v8::String>();

    //Set the pointer to the end of the file
    fseek(file, 0, SEEK_END);

    //Get the size of file
    int size = ftell(file);

    //Rewind the pointer to the beginning of the stream
    rewind(file);

    //Set up and read into the buffer
    char* chars = new char[size + 1];
    chars[size] = '\0';
    for (int i = 0 ; i < size;)
    {
        int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
        i += read;
    }

    //Close file
    fclose(file);

    v8::Handle<v8::String> result = v8::String::NewFromUtf8(isolate, chars, String::kNormalString, size);
    delete[] chars;
    return result;
}
<|endoftext|>


<commit_before>//      easyblogger V 2.0
//
//      Copyright 2011 Florian Weber <florian.weber@sfz-bw.de>
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU Affero General Public License as published by
//      the Free Software Foundation; either version 3 of the License, or
//      (at your option) any later version.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU Affero General Public License for more details.
//
//      You should have received a copy of the GNU Affero General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.
//

#include <iostream>

#include <string>
#include <vector>

#include "settings.hpp"
#include "help.hpp"
#include "actions.hpp"
#include "config.hpp"

using namespace std;

int main(int argc, char **argv){
	///bring parameters into a reasonable form:
	vector<string> args;
	args.resize(argc);
	for(int i=0;i<argc;++i){
		args[i]=(string(argv[i]));
	}
	settings S;
	if(argc==1){
		print_help();
		return 0;
	}
	else if(argc==2){
		if(args[1]=="-h"||args[1]=="--help"){
			print_help();
			return 0;
		}
		else if(args[1]=="--about"){
			print_info();
			return 0;
		}
		else if(args[1]=="--create"||args[1]=="-c"){
			S=get_blog_by_name();
			create_all(S);
		}
		else if(args[1]=="--list-entries"||args[1]=="-l"){
			S=get_blog_by_name();
			return list_entries(S);
		}
		else if(args[1]=="--configure"){
			S=get_blog_by_name();
			return configure_blog(S);
		}
		else{
			print_help();
			return 1;
		}
	}
	else if(argc==3){
		if(args[2]=="--create"||args[2]=="-c"){
			S=get_blog_by_name(args[1]);
			return create_all(S);
		}
		else if(args[1]=="--import"||args[1]=="-i"){
			S=get_blog_by_name();
			return import(S,args[2]);
		}
		else if(args[1]=="--edit"||args[1]=="-e"){
			S=get_blog_by_name();
			return edit(S,ID(args[2]));
		}
		else if(args[1]=="--edit-comment"||args[1]=="-E"){
			S=get_blog_by_name();
			return edit_comment(S,ID(args[2]));
		}
		else if(args[2]=="--configure"){
			S=get_blog_by_name(args[1]);
			return configure_blog(S,args[1]);
		}
		else if(args[2]=="--list-entries"||args[2]=="-l"){
			S=get_blog_by_name(args[1]);
			return list_entries(S);
		}
		else{
			print_help();
			return 1;
		}
	}
	else if(argc==4){
		if(args[2]=="--import"||args[2]=="-i"){
			S=get_blog_by_name(args[1]);
			return import(S,args[3]);
		}
		else if(args[2]=="--edit"||args[2]=="-e"){
			S=get_blog_by_name(args[1]);
			return edit(S,ID(args[3]));
		}
		else if(args[2]=="--edit-comment"||args[2]=="-E"){
			S=get_blog_by_name(args[1]);
			return edit_comment(S,ID(args[3]));
		}
		else if(args[1]=="--comment"){
			S=get_blog_by_name();
			comment(S,ID(args[2]),args[3]);
		}
		else{
			print_help();
			return 1;
		}
	}
	else if(argc==5){
		if(args[2]=="--comment"){
			S=get_blog_by_name(args[1]);
			comment(S,ID(args[3]),args[4]);
		}
		else{
			print_help();
			return 1;
		}
	}
	else{
		print_help();
		return 1;
	}
	return 0;
}
<commit_msg>tiny change<commit_after>//      easyblogger V 2.0
//
//      Copyright 2011 Florian Weber <florian.weber@sfz-bw.de>
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU Affero General Public License as published by
//      the Free Software Foundation; either version 3 of the License, or
//      (at your option) any later version.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU Affero General Public License for more details.
//
//      You should have received a copy of the GNU Affero General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.
//

#include <iostream>

#include <string>
#include <vector>

#include "settings.hpp"
#include "help.hpp"
#include "actions.hpp"
#include "config.hpp"

using namespace std;

int main(int argc, char **argv){
	///bring parameters into a reasonable form:
	vector<string> args(&argv[0],&argv[argc-1]);
	settings S;
	if(argc==1){
		print_help();
		return 0;
	}
	else if(argc==2){
		if(args[1]=="-h"||args[1]=="--help"){
			print_help();
			return 0;
		}
		else if(args[1]=="--about"){
			print_info();
			return 0;
		}
		else if(args[1]=="--create"||args[1]=="-c"){
			S=get_blog_by_name();
			create_all(S);
		}
		else if(args[1]=="--list-entries"||args[1]=="-l"){
			S=get_blog_by_name();
			return list_entries(S);
		}
		else if(args[1]=="--configure"){
			S=get_blog_by_name();
			return configure_blog(S);
		}
		else{
			print_help();
			return 1;
		}
	}
	else if(argc==3){
		if(args[2]=="--create"||args[2]=="-c"){
			S=get_blog_by_name(args[1]);
			return create_all(S);
		}
		else if(args[1]=="--import"||args[1]=="-i"){
			S=get_blog_by_name();
			return import(S,args[2]);
		}
		else if(args[1]=="--edit"||args[1]=="-e"){
			S=get_blog_by_name();
			return edit(S,ID(args[2]));
		}
		else if(args[1]=="--edit-comment"||args[1]=="-E"){
			S=get_blog_by_name();
			return edit_comment(S,ID(args[2]));
		}
		else if(args[2]=="--configure"){
			S=get_blog_by_name(args[1]);
			return configure_blog(S,args[1]);
		}
		else if(args[2]=="--list-entries"||args[2]=="-l"){
			S=get_blog_by_name(args[1]);
			return list_entries(S);
		}
		else{
			print_help();
			return 1;
		}
	}
	else if(argc==4){
		if(args[2]=="--import"||args[2]=="-i"){
			S=get_blog_by_name(args[1]);
			return import(S,args[3]);
		}
		else if(args[2]=="--edit"||args[2]=="-e"){
			S=get_blog_by_name(args[1]);
			return edit(S,ID(args[3]));
		}
		else if(args[2]=="--edit-comment"||args[2]=="-E"){
			S=get_blog_by_name(args[1]);
			return edit_comment(S,ID(args[3]));
		}
		else if(args[1]=="--comment"){
			S=get_blog_by_name();
			comment(S,ID(args[2]),args[3]);
		}
		else{
			print_help();
			return 1;
		}
	}
	else if(argc==5){
		if(args[2]=="--comment"){
			S=get_blog_by_name(args[1]);
			comment(S,ID(args[3]),args[4]);
		}
		else{
			print_help();
			return 1;
		}
	}
	else{
		print_help();
		return 1;
	}
	return 0;
}
<|endoftext|>


<commit_before>#include "rift/bucket.hpp"
#include "rift/cache.hpp"
#include "rift/common.hpp"
#include "rift/index.hpp"
#include "rift/io.hpp"
#include "rift/server.hpp"

using namespace ioremap;

class example_server : public thevoid::server<example_server>
{
public:
	struct signature_info {
		std::string key;
		std::string path;
	};

	example_server() : m_noauth_allowed(false) {
	}

	~example_server() {
		m_async.stop();
		m_cache.reset();
	}

	virtual bool initialize(const rapidjson::Value &config) {
		daemonize();

		if (!m_elliptics.initialize(config, logger()))
			return false;

		m_async.initialize(logger());

		if (config.HasMember("noauth")) {
			m_noauth_allowed = std::string(config["noauth"].GetString()) == "allowed";
		}

		if (config.HasMember("cache")) {
			m_cache = std::make_shared<rift::cache>();
			if (!m_cache->initialize(config["cache"], m_elliptics.node(), logger(),
						&m_async, m_elliptics.metadata_groups()))
				return false;
		}

		if (config.HasMember("bucket")) {
			m_bucket = std::make_shared<rift::bucket>();
			if (!m_bucket->initialize(config["bucket"], m_elliptics, &m_async))
				return false;
		}

		if (config.HasMember("redirect")) {
			m_redirect_read = config["redirect"].GetBool();
		} else {
			m_redirect_read = false;
		}

		if (config.HasMember("redirect-port")) {
			m_redirect_port = config["redirect-port"].GetInt();
		} else {
			m_redirect_port = -1;
		}

		if (config.HasMember("https")) {
			m_secured_http = config["https"].GetBool();
		} else {
			m_secured_http = false;
		}

		on<rift::index::on_update<example_server>>(
			options::exact_match("/update"),
			options::methods("POST")
		);
		on<rift::index::on_find<example_server>>(
			options::exact_match("/find"),
			options::methods("GET")
		);
		if (m_redirect_read) {
			on<rift::io::on_redirectable_get<example_server>>(
				options::exact_match("/get"),
				options::methods("GET")
			);
		} else {
			on<rift::io::on_get<example_server>>(
				options::exact_match("/get"),
				options::methods("GET")
			);
		}
		on<rift::io::on_buffered_get<example_server>>(
			options::exact_match("/get-big"),
			options::methods("GET")
		);
		on<rift::io::on_upload<example_server>>(
			options::exact_match("/upload"),
			options::methods("POST")
		);
		on<rift::io::on_buffered_upload<example_server>>(
			options::exact_match("/upload-big"),
			options::methods("POST")
		);
		on<rift::io::on_download_info<example_server>>(
			options::exact_match("/download-info"),
			options::methods("GET")
		);
		on<rift::common::on_ping<example_server>>(
			options::exact_match("/ping"),
			options::methods("GET")
		);
		on<rift::common::on_echo<example_server>>(
			options::exact_match("/echo"),
			options::methods("GET")
		);

		return true;
	}

	swarm::url generate_url_base(dnet_addr *addr) {
		char buffer[128];

		swarm::url url;
		url.set_scheme(m_secured_http ? "https" : "http");
		url.set_host(dnet_server_convert_dnet_addr_raw(addr, buffer, sizeof(buffer)));
		if (m_redirect_port > 0) {
			url.set_port(m_redirect_port);
		}

		return std::move(url);
	}

	const rift::elliptics_base *elliptics() const {
		return &m_elliptics;
	}

	void process(const swarm::http_request &request, const boost::asio::const_buffer &buffer,
			const rift::continue_handler_t &continue_handler) const {
		auto ns = request.url().query().item_value("namespace");
		if (!ns || !m_bucket) {
			auto verdict = swarm::http_response::bad_request;
			if (m_noauth_allowed || !m_bucket)
				verdict = swarm::http_response::ok;

			rift::bucket_meta_raw meta;
			continue_handler(request, buffer, meta, verdict);
		} else {
			m_bucket->check(*ns, request, buffer, continue_handler);
		}
	}

	void check_cache(const elliptics::key &key, elliptics::session &sess) const {
		if (m_cache) {
			auto cache_groups = m_cache->groups(key);
			if (!cache_groups.empty()) {
				auto groups = sess.get_groups();
				groups.insert(groups.end(), cache_groups.begin(), cache_groups.end());
				sess.set_groups(groups);
			}
		}
	}

	bool query_ok(const swarm::http_request &request) const {
		const auto &query = request.url().query();

		if (auto name = query.item_value("name")) {
			return true;
		} else if (auto sid = query.item_value("id")) {
			return true;
		}

		return false;
	}

	elliptics::session extract_key(const swarm::http_request &request, const rift::bucket_meta_raw &meta,
			elliptics::key &key) const {
		const auto &query = request.url().query();

		if (auto name = query.item_value("name")) {
			key = *name;
		} else if (auto sid = query.item_value("id")) {
			struct dnet_id id;
			memset(&id, 0, sizeof(struct dnet_id));

			dnet_parse_numeric_id(sid->c_str(), id.id);

			key = id;
		}

		elliptics::session session = m_elliptics.session();
		session.set_namespace(meta.key.c_str(), meta.key.size());
		session.set_groups(meta.groups);
		session.transform(key);

		return session;
	}

private:
	rift::async_performer m_async;
	bool m_redirect_read;
	int m_redirect_port;
	bool m_secured_http;
	std::shared_ptr<rift::cache> m_cache;
	std::shared_ptr<rift::bucket> m_bucket;
	rift::elliptics_base m_elliptics;
	bool m_noauth_allowed;
};

int main(int argc, char **argv)
{
	return thevoid::run_server<example_server>(argc, argv);
}
<commit_msg>rift: only allow query by elliptics ID if 'noauth: allowed' is set and authentication is globally turned off<commit_after>#include "rift/bucket.hpp"
#include "rift/cache.hpp"
#include "rift/common.hpp"
#include "rift/index.hpp"
#include "rift/io.hpp"
#include "rift/server.hpp"

using namespace ioremap;

class example_server : public thevoid::server<example_server>
{
public:
	struct signature_info {
		std::string key;
		std::string path;
	};

	example_server() : m_noauth_allowed(false) {
	}

	~example_server() {
		m_async.stop();
		m_cache.reset();
	}

	virtual bool initialize(const rapidjson::Value &config) {
		daemonize();

		if (!m_elliptics.initialize(config, logger()))
			return false;

		m_async.initialize(logger());

		if (config.HasMember("noauth")) {
			m_noauth_allowed = std::string(config["noauth"].GetString()) == "allowed";
		}

		if (config.HasMember("cache")) {
			m_cache = std::make_shared<rift::cache>();
			if (!m_cache->initialize(config["cache"], m_elliptics.node(), logger(),
						&m_async, m_elliptics.metadata_groups()))
				return false;
		}

		if (config.HasMember("bucket")) {
			m_bucket = std::make_shared<rift::bucket>();
			if (!m_bucket->initialize(config["bucket"], m_elliptics, &m_async))
				return false;
		}

		if (config.HasMember("redirect")) {
			m_redirect_read = config["redirect"].GetBool();
		} else {
			m_redirect_read = false;
		}

		if (config.HasMember("redirect-port")) {
			m_redirect_port = config["redirect-port"].GetInt();
		} else {
			m_redirect_port = -1;
		}

		if (config.HasMember("https")) {
			m_secured_http = config["https"].GetBool();
		} else {
			m_secured_http = false;
		}

		on<rift::index::on_update<example_server>>(
			options::exact_match("/update"),
			options::methods("POST")
		);
		on<rift::index::on_find<example_server>>(
			options::exact_match("/find"),
			options::methods("GET")
		);
		if (m_redirect_read) {
			on<rift::io::on_redirectable_get<example_server>>(
				options::exact_match("/get"),
				options::methods("GET")
			);
		} else {
			on<rift::io::on_get<example_server>>(
				options::exact_match("/get"),
				options::methods("GET")
			);
		}
		on<rift::io::on_buffered_get<example_server>>(
			options::exact_match("/get-big"),
			options::methods("GET")
		);
		on<rift::io::on_upload<example_server>>(
			options::exact_match("/upload"),
			options::methods("POST")
		);
		on<rift::io::on_buffered_upload<example_server>>(
			options::exact_match("/upload-big"),
			options::methods("POST")
		);
		on<rift::io::on_download_info<example_server>>(
			options::exact_match("/download-info"),
			options::methods("GET")
		);
		on<rift::common::on_ping<example_server>>(
			options::exact_match("/ping"),
			options::methods("GET")
		);
		on<rift::common::on_echo<example_server>>(
			options::exact_match("/echo"),
			options::methods("GET")
		);

		return true;
	}

	swarm::url generate_url_base(dnet_addr *addr) {
		char buffer[128];

		swarm::url url;
		url.set_scheme(m_secured_http ? "https" : "http");
		url.set_host(dnet_server_convert_dnet_addr_raw(addr, buffer, sizeof(buffer)));
		if (m_redirect_port > 0) {
			url.set_port(m_redirect_port);
		}

		return std::move(url);
	}

	const rift::elliptics_base *elliptics() const {
		return &m_elliptics;
	}

	void process(const swarm::http_request &request, const boost::asio::const_buffer &buffer,
			const rift::continue_handler_t &continue_handler) const {
		auto ns = request.url().query().item_value("namespace");
		if (!ns || !m_bucket) {
			auto verdict = swarm::http_response::bad_request;
			if (m_noauth_allowed || !m_bucket)
				verdict = swarm::http_response::ok;

			rift::bucket_meta_raw meta;
			continue_handler(request, buffer, meta, verdict);
		} else {
			m_bucket->check(*ns, request, buffer, continue_handler);
		}
	}

	void check_cache(const elliptics::key &key, elliptics::session &sess) const {
		if (m_cache) {
			auto cache_groups = m_cache->groups(key);
			if (!cache_groups.empty()) {
				auto groups = sess.get_groups();
				groups.insert(groups.end(), cache_groups.begin(), cache_groups.end());
				sess.set_groups(groups);
			}
		}
	}

	bool query_ok(const swarm::http_request &request) const {
		const auto &query = request.url().query();

		if (auto name = query.item_value("name")) {
			return true;
		} else if (auto sid = query.item_value("id")) {
			if (m_noauth_allowed)
				return true;
		}

		return false;
	}

	elliptics::session extract_key(const swarm::http_request &request, const rift::bucket_meta_raw &meta,
			elliptics::key &key) const {
		const auto &query = request.url().query();

		if (auto name = query.item_value("name")) {
			key = *name;
		} else if (auto sid = query.item_value("id")) {
			struct dnet_id id;
			memset(&id, 0, sizeof(struct dnet_id));

			dnet_parse_numeric_id(sid->c_str(), id.id);

			key = id;
		}

		elliptics::session session = m_elliptics.session();
		session.set_namespace(meta.key.c_str(), meta.key.size());
		session.set_groups(meta.groups);
		session.transform(key);

		return session;
	}

private:
	rift::async_performer m_async;
	bool m_redirect_read;
	int m_redirect_port;
	bool m_secured_http;
	std::shared_ptr<rift::cache> m_cache;
	std::shared_ptr<rift::bucket> m_bucket;
	rift::elliptics_base m_elliptics;
	bool m_noauth_allowed;
};

int main(int argc, char **argv)
{
	return thevoid::run_server<example_server>(argc, argv);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <map>
#include <memory>
#include <fstream>
#include <iomanip>
#include <boost/filesystem.hpp>
#include <memory.h>

extern "C" {
#include <libircclient.h>
}

struct DCCFile
{
    irc_dcc_t id;
    std::string filename;
    unsigned long size;
    unsigned long received;
    std::ofstream stream;

    DCCFile(irc_dcc_t id, const char *filename, unsigned long size)
        :   id(id),
            filename(filename),
            size(size),
            received(0)
    { stream.open(filename, std::fstream::binary); }
};

typedef std::shared_ptr<DCCFile> DCCFilePtr;

struct IRCContext
{
    std::vector<std::string> channels;
    std::string nick;
    std::map<irc_dcc_t, DCCFilePtr> files;
};

void event_connect(irc_session_t* session, const char* event, const char* origin, const char** params, unsigned int count)
{
    IRCContext* ctx = (IRCContext*) irc_get_ctx(session);

    for (auto &c : ctx->channels)
    {
        irc_cmd_join (session, c.c_str(), 0);
    }
}

void event_channel(irc_session_t* session, const char* event, const char* origin, const char** params, unsigned int count)
{
    char nickbuf[128];

    if ( count != 2 )
        return;

    std::cout << origin << "@" << params[0] << ": " << params[1] << std::endl;

    if ( !origin )
        return;
}

void dcc_file_recv_callback (irc_session_t* session, irc_dcc_t id, int status, void* fp, const char* data, unsigned int length)
{
    IRCContext* ctx = (IRCContext*) irc_get_ctx(session);
    DCCFilePtr fileptr = ctx->files[id];

    if (status == 0 && length == 0)
    {
        std::cout << "File " << fileptr->filename << " received successfully!" << std::endl;
        fileptr->stream.close();
        ctx->files.erase(id);
    }
    else if (status)
    {
        std::cout << "Error receiving file '" << fileptr->filename << "': " << status << std::endl;
        fileptr->stream.close();
        ctx->files.erase(id);
    }
    else
    {
        fileptr->received += length;
        float percent = ((float)fileptr->received / (float)fileptr->size) * 100.0f;

        std::cout << "File '" << fileptr->filename << "': "
              << std::setprecision(4) << percent << "%"
              << " (" << fileptr->received << "/" << fileptr->size << ")" << std::endl;

        fileptr->stream.write(data, length);
    }
}

void event_dcc_send_req(irc_session_t* session, const char* nick, const char* addr, const char* filename, unsigned long size, irc_dcc_t dccid)
{
    IRCContext* ctx = (IRCContext*) irc_get_ctx(session);
    boost::filesystem::path p(filename);
    DCCFilePtr fileptr = std::make_shared<DCCFile>(dccid, filename, size);

    ctx->files[dccid] = fileptr;

    std::cout << "Receiving file " << filename << ", size: " << size << std::endl;

    irc_dcc_accept(session, dccid, nullptr, dcc_file_recv_callback);
}

int main(int argc, char **argv)
{
    irc_callbacks_t    callbacks;
    IRCContext ctx;
    irc_session_t * s;
    unsigned short port = 6667;

    if ( argc < 4 )
    {
        printf ("Usage: %s <server> <nick> <channel>\n", argv[0]);
        return 1;
    }

    memset (&callbacks, 0, sizeof(callbacks));

    callbacks.event_connect = event_connect;
    callbacks.event_channel = event_channel;
    //callbacks.event_privmsg = event_privmsg;

    callbacks.event_dcc_send_req = event_dcc_send_req;

    s = irc_create_session (&callbacks);

    if ( !s )
    {
        printf ("Could not create session\n");
        return 1;
    }

    ctx.nick = argv[2];
    unsigned int channel = 3;

    while (channel < argc)
    {
        ctx.channels.push_back(argv[channel]);
        channel++;
    }

    irc_set_ctx (s, &ctx);

    // If the port number is specified in the server string, use the port 0 so it gets parsed
    if ( strchr( argv[1], ':' ) != 0 )
        port = 0;

    // To handle the "SSL certificate verify failed" from command line we allow passing ## in front
    // of the server name, and in this case tell libircclient not to verify the cert
    if ( argv[1][0] == '#' && argv[1][1] == '#' )
    {
        // Skip the first character as libircclient needs only one # for SSL support, i.e. #irc.freenode.net
        argv[1]++;

        irc_option_set( s, LIBIRC_OPTION_SSL_NO_VERIFY );
    }

    // Initiate the IRC server connection
    if ( irc_connect (s, argv[1], port, 0, argv[2], 0, 0) )
    {
        printf ("Could not connect: %s\n", irc_strerror (irc_errno(s)));
        return 1;
    }

    // and run into forever loop, generating events
    if ( irc_run (s) )
    {
        printf ("Could not connect or I/O error: %s\n", irc_strerror (irc_errno(s)));
        return 1;
    }

    return 1;
}
<commit_msg>Download files to subdirectory, only print status every 5%<commit_after>#include <iostream>
#include <vector>
#include <map>
#include <memory>
#include <fstream>
#include <iomanip>
#include <boost/filesystem.hpp>
#include <memory.h>

extern "C" {
#include <libircclient.h>
}

struct DCCFile
{
    irc_dcc_t id;
    std::string filename;
    unsigned long size;
    unsigned long received;
    std::ofstream stream;
    float old_percent;

    DCCFile(irc_dcc_t id, const char *filename, unsigned long size)
        :   id(id),
            filename(filename),
            size(size),
            received(0),
            old_percent(0.0f)
    {
        boost::filesystem::path p("downloads");
        p /= filename;
        stream.open(p.string(), std::fstream::binary);
    }
};

typedef std::shared_ptr<DCCFile> DCCFilePtr;

struct IRCContext
{
    std::vector<std::string> channels;
    std::string nick;
    std::map<irc_dcc_t, DCCFilePtr> files;
};

void event_connect(irc_session_t* session, const char* event, const char* origin, const char** params, unsigned int count)
{
    IRCContext* ctx = (IRCContext*) irc_get_ctx(session);

    for (auto &c : ctx->channels)
    {
        irc_cmd_join (session, c.c_str(), 0);
    }
}

void event_channel(irc_session_t* session, const char* event, const char* origin, const char** params, unsigned int count)
{
    char nickbuf[128];

    if ( count != 2 )
        return;

    std::cout << origin << "@" << params[0] << ": " << params[1] << std::endl;

    if ( !origin )
        return;
}

void dcc_file_recv_callback (irc_session_t* session, irc_dcc_t id, int status, void* fp, const char* data, unsigned int length)
{
    IRCContext* ctx = (IRCContext*) irc_get_ctx(session);
    DCCFilePtr fileptr = ctx->files[id];

    if (status == 0 && length == 0)
    {
        std::cout << "File " << fileptr->filename << " received successfully!" << std::endl;
        fileptr->stream.close();
        ctx->files.erase(id);
    }
    else if (status)
    {
        std::cout << "Error receiving file '" << fileptr->filename << "': " << status << std::endl;
        fileptr->stream.close();
        ctx->files.erase(id);
    }
    else
    {
        fileptr->received += length;
        float percent = ((float)fileptr->received / (float)fileptr->size) * 100.0f;

        if (percent - fileptr->old_percent > 5.0f)
        {
            std::cout << "File '" << fileptr->filename << "': "
                  << std::setprecision(4) << percent << "%"
                  << " (" << fileptr->received << "/" << fileptr->size << ")" << std::endl;

            fileptr->old_percent = percent;
        }

        fileptr->stream.write(data, length);
    }
}

void event_dcc_send_req(irc_session_t* session, const char* nick, const char* addr, const char* filename, unsigned long size, irc_dcc_t dccid)
{
    IRCContext* ctx = (IRCContext*) irc_get_ctx(session);
    DCCFilePtr fileptr = std::make_shared<DCCFile>(dccid, filename, size);

    ctx->files[dccid] = fileptr;

    std::cout << "Receiving file " << filename << ", size: " << size << std::endl;

    irc_dcc_accept(session, dccid, nullptr, dcc_file_recv_callback);
}

int main(int argc, char **argv)
{
    irc_callbacks_t    callbacks;
    IRCContext ctx;
    irc_session_t * s;
    unsigned short port = 6667;

    if ( argc < 4 )
    {
        printf ("Usage: %s <server> <nick> <channel>\n", argv[0]);
        return 1;
    }

    memset (&callbacks, 0, sizeof(callbacks));

    callbacks.event_connect = event_connect;
    callbacks.event_channel = event_channel;
    //callbacks.event_privmsg = event_privmsg;

    callbacks.event_dcc_send_req = event_dcc_send_req;

    s = irc_create_session (&callbacks);

    if ( !s )
    {
        printf ("Could not create session\n");
        return 1;
    }

    ctx.nick = argv[2];

    unsigned int channel = 3;

    while (channel < argc)
    {
        ctx.channels.push_back(argv[channel]);
        channel++;
    }

    irc_set_ctx (s, &ctx);

    // If the port number is specified in the server string, use the port 0 so it gets parsed
    if ( strchr( argv[1], ':' ) != 0 )
        port = 0;

    // To handle the "SSL certificate verify failed" from command line we allow passing ## in front
    // of the server name, and in this case tell libircclient not to verify the cert
    if ( argv[1][0] == '#' && argv[1][1] == '#' )
    {
        // Skip the first character as libircclient needs only one # for SSL support, i.e. #irc.freenode.net
        argv[1]++;

        irc_option_set( s, LIBIRC_OPTION_SSL_NO_VERIFY );
    }

    // Initiate the IRC server connection
    if ( irc_connect (s, argv[1], port, 0, argv[2], 0, 0) )
    {
        printf ("Could not connect: %s\n", irc_strerror (irc_errno(s)));
        return 1;
    }

    // and run into forever loop, generating events
    if ( irc_run (s) )
    {
        printf ("Could not connect or I/O error: %s\n", irc_strerror (irc_errno(s)));
        return 1;
    }

    return 1;
}
<|endoftext|>


<commit_before>#include "GarrysMod/Lua/Interface.h"

#include "interface.h"
#include "vgui/VGUI.h"

#include "IGameConsole.h"
#include "CGameConsoleDialog.h"

using namespace GarrysMod;

IGameConsole *g_GameConsole = NULL;
CGameConsoleDialog *g_GameConsoleDialog = NULL;

int console_Activate(lua_State *state) {
	g_GameConsole->Activate();

	return 0;
}

int console_Initialize(lua_State *state) {
	g_GameConsole->Initialize();

	return 0;
}

int console_Hide(lua_State *state) {
	g_GameConsole->Hide();

	return 0;
}

int console_Clear(lua_State *state) {
	g_GameConsole->Clear();

	return 0;
}

int console_IsConsoleVisible(lua_State *state) {
	LUA->PushBool(g_GameConsole->IsConsoleVisible());

	return 1;
}

int console_Get(lua_State *state) {
	Lua::UserData *ud = (Lua::UserData *)LUA->NewUserdata(sizeof(Lua::UserData));
	// ud->data = *(((void **)g_GameConsole) + 2);
	ud->data = g_GameConsoleDialog;
	ud->type = 420;

	LUA->CreateMetaTableType("Console", 420);

	LUA->SetMetaTable(-2);

	return 1;
}

int CONSOLE_SetParent(lua_State *state) {
	LUA->CheckType(1, Lua::Type::PANEL);

	vgui::Panel *pPanel = *(vgui::Panel **)LUA->GetUserdata(1);

	g_GameConsoleDialog->SetParent(pPanel*);

	return 0;
}

GMOD_MODULE_OPEN() {
	CreateInterfaceFn GameUIFactory = Sys_GetFactory("gameui.dll");
	g_GameConsole = (IGameConsole*)GameUIFactory(GAMECONSOLE_INTERFACE_VERSION, NULL);

	if (g_GameConsole == NULL) {
		LUA->ThrowError("gm_console: Error getting IGameConsole interface.");

		return 0;
	}

	g_GameConsoleDialog = *((CGameConsoleDialog **)(g_GameConsole) + 2);

	LUA->PushSpecial(Lua::SPECIAL_GLOB);
		LUA->CreateTable();
			LUA->PushCFunction(console_Activate);
			LUA->SetField(-2, "Activate");

			LUA->PushCFunction(console_Initialize);
			LUA->SetField(-2, "Initialize");

			LUA->PushCFunction(console_Hide);
			LUA->SetField(-2, "Hide");

			LUA->PushCFunction(console_Clear);
			LUA->SetField(-2, "Clear");

			LUA->PushCFunction(console_IsConsoleVisible);
			LUA->SetField(-2, "IsConsoleVisible");

			LUA->PushCFunction(console_Get);
			LUA->SetField(-2, "Get");
		LUA->SetField(-2, "console");
	LUA->Pop();

	LUA->CreateMetaTableType("Console", 420);
		LUA->CreateTable();
			LUA->PushCFunction(CONSOLE_SetParent);
			LUA->SetField(-2, "SetParent");
		LUA->SetField(-2, "__index");
	LUA->Pop();

	return 0;
}
<commit_msg>linux gameui lib<commit_after>#ifdef _LINUX
	#define GAMEUI_LIB "GameUI.so"
#else
	#define GAMEUI_LIB "GameUI.dll"
#endif

#include "GarrysMod/Lua/Interface.h"

#include "interface.h"
#include "vgui/VGUI.h"

#include "IGameConsole.h"
#include "CGameConsoleDialog.h"

using namespace GarrysMod;

IGameConsole *g_GameConsole = NULL;
CGameConsoleDialog *g_GameConsoleDialog = NULL;

int console_Activate(lua_State *state) {
	g_GameConsole->Activate();

	return 0;
}

int console_Initialize(lua_State *state) {
	g_GameConsole->Initialize();

	return 0;
}

int console_Hide(lua_State *state) {
	g_GameConsole->Hide();

	return 0;
}

int console_Clear(lua_State *state) {
	g_GameConsole->Clear();

	return 0;
}

int console_IsConsoleVisible(lua_State *state) {
	LUA->PushBool(g_GameConsole->IsConsoleVisible());

	return 1;
}

int console_Get(lua_State *state) {
	Lua::UserData *ud = (Lua::UserData *)LUA->NewUserdata(sizeof(Lua::UserData));
	// ud->data = *(((void **)g_GameConsole) + 2);
	ud->data = g_GameConsoleDialog;
	ud->type = 420;

	LUA->CreateMetaTableType("Console", 420);

	LUA->SetMetaTable(-2);

	return 1;
}

int CONSOLE_SetParent(lua_State *state) {
	LUA->CheckType(1, Lua::Type::PANEL);

	vgui::Panel *pPanel = *(vgui::Panel **)LUA->GetUserdata(1);

	g_GameConsoleDialog->SetParent(pPanel*);

	return 0;
}

GMOD_MODULE_OPEN() {
	CreateInterfaceFn GameUIFactory = Sys_GetFactory(GAMEUI_LIB);
	g_GameConsole = (IGameConsole*)GameUIFactory(GAMECONSOLE_INTERFACE_VERSION, NULL);

	if (g_GameConsole == NULL) {
		LUA->ThrowError("gm_console: Error getting IGameConsole interface.");

		return 0;
	}

	g_GameConsoleDialog = *((CGameConsoleDialog **)(g_GameConsole) + 2);

	LUA->PushSpecial(Lua::SPECIAL_GLOB);
		LUA->CreateTable();
			LUA->PushCFunction(console_Activate);
			LUA->SetField(-2, "Activate");

			LUA->PushCFunction(console_Initialize);
			LUA->SetField(-2, "Initialize");

			LUA->PushCFunction(console_Hide);
			LUA->SetField(-2, "Hide");

			LUA->PushCFunction(console_Clear);
			LUA->SetField(-2, "Clear");

			LUA->PushCFunction(console_IsConsoleVisible);
			LUA->SetField(-2, "IsConsoleVisible");

			LUA->PushCFunction(console_Get);
			LUA->SetField(-2, "Get");
		LUA->SetField(-2, "console");
	LUA->Pop();

	LUA->CreateMetaTableType("Console", 420);
		LUA->CreateTable();
			LUA->PushCFunction(CONSOLE_SetParent);
			LUA->SetField(-2, "SetParent");
		LUA->SetField(-2, "__index");
	LUA->Pop();

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <list>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <netdb.h>
#include <pwd.h>
#include <sys/socket.h>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost::algorithm;

int main () {

    return 0;
}
<commit_msg>Added Base class <commit_after>#include <iostream>
#include <vector>
#include <list>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <netdb.h>
#include <pwd.h>
#include <sys/socket.h>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost::algorithm;

class Base{
public:
    Base(){};
    virtual bool evaluate() =0;

}

int main () {

    return 0;
}
<|endoftext|>


<commit_before>#include <dirent.h>
#include <unistd.h>
#include "cartridge.hpp"
#include "menu.hpp"

namespace GUI {

using namespace std;

Entry::Entry(string label, function<void()> callback, int x, int y) : callback(callback), x(x), y(y)
{
    setLabel(label);
}

Entry::~Entry()
{
    SDL_DestroyTexture(whiteTexture);
    SDL_DestroyTexture(redTexture);
}

void Entry::setLabel(string label)
{
    this->label = label;

    if (whiteTexture != nullptr) SDL_DestroyTexture(whiteTexture);
    if (redTexture   != nullptr) SDL_DestroyTexture(redTexture);

    whiteTexture = gen_text(label, { 255, 255, 255 });
    redTexture   = gen_text(label, { 255,   0,   0 });
}

void Entry::render()
{
    render_texture(selected ? redTexture : whiteTexture, getX(), getY());
}

ControlEntry::ControlEntry(string action, SDL_Scancode* key, int x, int y) : key(key),
    Entry::Entry(
        action,
        [&]{ keyEntry->setLabel(SDL_GetScancodeName(*(this->key) = query_key())); },
        x,
        y)
{
    this->keyEntry = new Entry(SDL_GetScancodeName(*key), []{}, TEXT_RIGHT, y);
}

ControlEntry::ControlEntry(string action, int* button, int x, int y) : button(button),
    Entry::Entry(
        action,
        [&]{ keyEntry->setLabel(to_string(*(this->button) = query_button())); },
        x,
        y)
{
    this->keyEntry = new Entry(to_string(*button), []{}, TEXT_RIGHT, y);
}

void Menu::add(Entry* entry)
{
    if (entries.empty())
        entry->select();
    entry->setY(entries.size() * FONT_SZ);
    entries.push_back(entry);
}

void Menu::clear()
{
    for (auto entry : entries)
        delete entry;
    entries.clear();
    cursor = 0;
}

void Menu::update(u8 const* keys)
{
    int oldCursor = cursor;

    if (keys[SDL_SCANCODE_DOWN] and cursor < entries.size() - 1)
        cursor++;
    else if (keys[SDL_SCANCODE_UP] and cursor > 0)
        cursor--;

    entries[oldCursor]->unselect();
    entries[cursor]->select();

    if (keys[SDL_SCANCODE_RETURN])
        entries[cursor]->trigger();
}

void Menu::render()
{
    for (auto entry : entries)
        entry->render();
}

void FileMenu::change_dir(string dir)
{
    clear();

    struct dirent* dirp;
    DIR* dp = opendir(dir.c_str());

    while ((dirp = readdir(dp)) != NULL)
    {
        string name = dirp->d_name;
        string path = dir + "/" + name;

        if (name[0] == '.' and name != "..") continue;

        if (dirp->d_type == DT_DIR)
        {
            add(new Entry(name + "/",
                          [=]{ change_dir(path); },
                          0));
        }
        else if (name.size() > 4 and name.substr(name.size() - 4) == ".nes")
        {
            add(new Entry(name,
                          [=]{ Cartridge::load(path.c_str()); toggle_pause(); },
                          0));
        }
    }
    closedir(dp);
}

FileMenu::FileMenu()
{
    change_dir(getwd(NULL));
}

}
<commit_msg>Fixed Linux.<commit_after>#include <dirent.h>
#include <unistd.h>
#include "cartridge.hpp"
#include "menu.hpp"

namespace GUI {

using namespace std;

Entry::Entry(string label, function<void()> callback, int x, int y) : callback(callback), x(x), y(y)
{
    setLabel(label);
}

Entry::~Entry()
{
    SDL_DestroyTexture(whiteTexture);
    SDL_DestroyTexture(redTexture);
}

void Entry::setLabel(string label)
{
    this->label = label;

    if (whiteTexture != nullptr) SDL_DestroyTexture(whiteTexture);
    if (redTexture   != nullptr) SDL_DestroyTexture(redTexture);

    whiteTexture = gen_text(label, { 255, 255, 255 });
    redTexture   = gen_text(label, { 255,   0,   0 });
}

void Entry::render()
{
    render_texture(selected ? redTexture : whiteTexture, getX(), getY());
}

ControlEntry::ControlEntry(string action, SDL_Scancode* key, int x, int y) : key(key),
    Entry::Entry(
        action,
        [&]{ keyEntry->setLabel(SDL_GetScancodeName(*(this->key) = query_key())); },
        x,
        y)
{
    this->keyEntry = new Entry(SDL_GetScancodeName(*key), []{}, TEXT_RIGHT, y);
}

ControlEntry::ControlEntry(string action, int* button, int x, int y) : button(button),
    Entry::Entry(
        action,
        [&]{ keyEntry->setLabel(to_string(*(this->button) = query_button())); },
        x,
        y)
{
    this->keyEntry = new Entry(to_string(*button), []{}, TEXT_RIGHT, y);
}

void Menu::add(Entry* entry)
{
    if (entries.empty())
        entry->select();
    entry->setY(entries.size() * FONT_SZ);
    entries.push_back(entry);
}

void Menu::clear()
{
    for (auto entry : entries)
        delete entry;
    entries.clear();
    cursor = 0;
}

void Menu::update(u8 const* keys)
{
    int oldCursor = cursor;

    if (keys[SDL_SCANCODE_DOWN] and cursor < entries.size() - 1)
        cursor++;
    else if (keys[SDL_SCANCODE_UP] and cursor > 0)
        cursor--;

    entries[oldCursor]->unselect();
    entries[cursor]->select();

    if (keys[SDL_SCANCODE_RETURN])
        entries[cursor]->trigger();
}

void Menu::render()
{
    for (auto entry : entries)
        entry->render();
}

void FileMenu::change_dir(string dir)
{
    clear();

    struct dirent* dirp;
    DIR* dp = opendir(dir.c_str());

    while ((dirp = readdir(dp)) != NULL)
    {
        string name = dirp->d_name;
        string path = dir + "/" + name;

        if (name[0] == '.' and name != "..") continue;

        if (dirp->d_type == DT_DIR)
        {
            add(new Entry(name + "/",
                          [=]{ change_dir(path); },
                          0));
        }
        else if (name.size() > 4 and name.substr(name.size() - 4) == ".nes")
        {
            add(new Entry(name,
                          [=]{ Cartridge::load(path.c_str()); toggle_pause(); },
                          0));
        }
    }
    closedir(dp);
}

FileMenu::FileMenu()
{
    char cwd[512];

    change_dir(getcwd(cwd, 512));
}

}
<|endoftext|>