text:
#include "system/terms/term.h"

#include <memory>
#include <unordered_set>

#include <deal.II/lac/petsc_vector.h>
#include <deal.II/base/mpi.h>

#include "system/system_types.h"
#include "test_helpers/gmock_wrapper.h"

namespace  {

using namespace bart;
using system::MPIVector;
using VariableLinearTerms = system::terms::VariableLinearTerms;

class SystemLinearTermTest : public ::testing::Test {
 protected:
  SystemLinearTermTest()
      : test_linear_term({VariableLinearTerms::kScatteringSource}) {};

  system::terms::MPILinearTerm test_linear_term;

  std::shared_ptr<MPIVector> test_vector, double_test_vector;
  void SetUp() override;
  void FillVector(MPIVector& to_fill, int multiple = 1);
};

void SystemLinearTermTest::SetUp() {
  const int entries_per_processor = 10;
  const int n_processors =
      dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);

  test_vector = std::make_shared<MPIVector>(MPI_COMM_WORLD,
                                            entries_per_processor*n_processors,
                                            entries_per_processor);
  double_test_vector = std::make_shared<MPIVector>();
  double_test_vector->reinit(*test_vector);

  FillVector(*test_vector);
  FillVector(*double_test_vector, 2);
}

void SystemLinearTermTest::FillVector(MPIVector& to_fill,
                                         const int multiple) {
  auto [first_entry, last_entry] = to_fill.local_range();
  for (unsigned int i = first_entry; i < last_entry; ++i) {
    to_fill(i) = i * multiple;
  }
  to_fill.compress(dealii::VectorOperation::insert);
}

TEST_F(SystemLinearTermTest, Constructor) {
  std::unordered_set<VariableLinearTerms> variable_terms =
      {VariableLinearTerms::kScatteringSource};

  EXPECT_EQ(test_linear_term.GetVariableTerms(), variable_terms);
}

TEST_F(SystemLinearTermTest, SetFixedPtrTest) {
  test_linear_term.SetFixedTermPtr({0, 0}, test_vector);
  test_linear_term.SetFixedTermPtr(1, double_test_vector);

  EXPECT_EQ(test_vector.use_count(), 2);
  EXPECT_EQ(double_test_vector.use_count(), 2);
}

TEST_F(SystemLinearTermTest, GetFixedPtrIndexTest) {
  test_linear_term.SetFixedTermPtr({0, 0}, test_vector);
  test_linear_term.SetFixedTermPtr({0, 1}, double_test_vector);

  EXPECT_EQ(test_linear_term.GetFixedTermPtr({0, 0}), test_vector);
  EXPECT_EQ(test_linear_term.GetFixedTermPtr({0, 1}), double_test_vector);

  EXPECT_EQ(test_linear_term.GetFixedTermPtr({2, 0}), nullptr);
}

TEST_F(SystemLinearTermTest, GetFixedPtrGroupTest) {
  test_linear_term.SetFixedTermPtr(0, test_vector);
  test_linear_term.SetFixedTermPtr({0, 1}, double_test_vector);
  test_linear_term.SetFixedTermPtr(1, double_test_vector);
  test_linear_term.SetFixedTermPtr({1, 1}, test_vector);

  EXPECT_EQ(test_linear_term.GetFixedTermPtr(0), test_vector);
  EXPECT_EQ(test_linear_term.GetFixedTermPtr({0, 1}), double_test_vector);
  EXPECT_EQ(test_linear_term.GetFixedTermPtr(1), double_test_vector);
  EXPECT_EQ(test_linear_term.GetFixedTermPtr({1, 1}), test_vector);

  EXPECT_EQ(test_linear_term.GetFixedTermPtr(2), nullptr);
}

TEST_F(SystemLinearTermTest, SetVariablePtrTest) {
  test_linear_term.SetVariableTermPtr({0, 0}, VariableLinearTerms::kScatteringSource, test_vector);
  test_linear_term.SetVariableTermPtr(1,
                              VariableLinearTerms::kScatteringSource,
                              double_test_vector);
  EXPECT_EQ(test_vector.use_count(), 2);
  EXPECT_EQ(double_test_vector.use_count(), 2);

  EXPECT_ANY_THROW(test_linear_term.SetVariableTermPtr({0, 0},
                                               VariableLinearTerms::kFissionSource,
                                               test_vector));
  EXPECT_ANY_THROW(test_linear_term.SetVariableTermPtr(1,
                                               VariableLinearTerms::kFissionSource,
                                               test_vector));
}

TEST_F(SystemLinearTermTest, GetVariablePtrIndexTest) {
  auto term = VariableLinearTerms::kScatteringSource;
  test_linear_term.SetVariableTermPtr({0, 0}, term, test_vector);
  test_linear_term.SetVariableTermPtr({0, 1}, term, double_test_vector);

  EXPECT_EQ(test_linear_term.GetVariableTermPtr({0, 0}, term), test_vector);
  EXPECT_EQ(test_linear_term.GetVariableTermPtr({0, 1}, term), double_test_vector);

  EXPECT_EQ(test_linear_term.GetVariableTermPtr({2, 0}, term), nullptr);
  EXPECT_ANY_THROW(test_linear_term.GetVariableTermPtr({0, 0},
                                               VariableLinearTerms::kFissionSource));
}

TEST_F(SystemLinearTermTest, GetVariablePtrGroupTest) {
  auto term = VariableLinearTerms::kScatteringSource;

  test_linear_term.SetVariableTermPtr(0, term, test_vector);
  test_linear_term.SetVariableTermPtr({0, 1}, term, double_test_vector);
  test_linear_term.SetVariableTermPtr(1, term, double_test_vector);
  test_linear_term.SetVariableTermPtr({1, 1}, term, test_vector);

  EXPECT_EQ(test_linear_term.GetVariableTermPtr(0, term), test_vector);
  EXPECT_EQ(test_linear_term.GetVariableTermPtr({0, 1}, term), double_test_vector);
  EXPECT_EQ(test_linear_term.GetVariableTermPtr(1, term), double_test_vector);
  EXPECT_EQ(test_linear_term.GetVariableTermPtr({1, 1}, term), test_vector);

  EXPECT_EQ(test_linear_term.GetVariableTermPtr(2, term), nullptr);
  EXPECT_ANY_THROW(test_linear_term.GetVariableTermPtr(0,
                                               VariableLinearTerms::kFissionSource));
}

} // namespace

max_stars_repo_name: narang-amit/BART

max_issues_repo_name: jsrehak/BART

max_forks_repo_name: jsrehak/BART


text:
#include "stdafx.h"
#include "session_mem_cac.h"
#include "icommand_executor.h"
#include <boost/algorithm/string.hpp>

SessionMemCac::SessionMemCac(tcp::socket		_socket,
							 u32				_sessionId,
							 const std::string&	_msgSeparateSymbol,
							 iSessionOwner&		_sessionOwner,
							 iCommandExecutor*  _commandExecutor)
: Inherited(std::move(_socket)
			, _sessionId
			, _msgSeparateSymbol
			, _sessionOwner)
, executor(_commandExecutor)
{}

void SessionMemCac::Dispatch(const std::string& _message)
{
	if(isDataBlockExpected)
	{
		tempRecord.data = _message.substr(0, tempLength);
		executor->OnSetCmdReceived(tempKey, tempRecord, tempIsNoReply, this);
		isDataBlockExpected = false;
		return;
	}

	std::vector<std::string> args;
	boost::split(args, _message, [](char c){ return c == ' '; });

	const std::string& cmd = args.front();

	if(cmd == CMD_SET)
	{
		DispatchCmdSet(args);
	}
	else if(cmd == CMD_GET)
	{
		DispatchCmdGet(args);
	}
	else if(cmd == CMD_DELETE)
	{
		DispatchCmdDelete(args);
	}
	else
	{
		SendErrorRequestMalformed();
	}
	return;
}

void SessionMemCac::DispatchCmdSet(std::vector<std::string> &args)
{
	if(args.size() > 6 || args.size() < 5)
	{
		SendErrorRequestMalformed();
		return;
	}

	const std::string& key			= args[1];

	u32				   flag;
	u64				   expTime;
	size_t			   length;
	bool			   isNoReply	= false;
	try
	{
		flag	= std::stol(args[2]);
		expTime = std::stoll(args[3]);
		length	= std::stoll(args[4]);

		expTime = expTime	== 0 ? -1 : expTime;
		length	= length	== 0 ? -1 : length;
	}
	catch(const std::invalid_argument&)
	{
		SendErrorRequestMalformed();
		return;
	}

	if (args.size() == 6)
	{
		if(args[5] == "noreply")
		{
			isNoReply = true;
		}
		else
		{
			SendErrorRequestMalformed();
			return;
		}
	}

	tempKey						= key;
	tempRecord.flag				= flag;
	tempRecord.expirationDate	= expTime == -1 ? -1 : expTime + std::time(nullptr);
	tempLength					= length;
	tempIsNoReply				= isNoReply;

	isDataBlockExpected			= true;
}

void SessionMemCac::DispatchCmdGet(std::vector<std::string>& _args)
{
	if(!EraseFirstAndSendErrorIfEmpty(_args))
	{
		return;
	}
	executor->OnGetCmdReceived(_args, this);
}

void SessionMemCac::DispatchCmdDelete(std::vector<std::string>& _args)
{

	if(!EraseFirstAndSendErrorIfEmpty(_args))
	{
		return;
	}

	if(_args.size() > 2)
	{
		SendErrorRequestMalformed();
		return;
	}

	bool isNoReply = false;
	if(_args.size() == 2)
	{
		if(FLAG_NO_REPLY == _args[1])
		{
			isNoReply = true;
		}
	}

	executor->OnDeleteCmdReceived(_args[0], isNoReply, this);
}

bool SessionMemCac::EraseFirstAndSendErrorIfEmpty(std::vector<std::string>& _args)
{
	_args.erase(_args.begin());
	if(_args.empty())
	{
		SendErrorRequestMalformed();
		return false;
	}
	return true;
}

void SessionMemCac::SendErrorRequestMalformed()
{
	Send("ERROR request malformed");
}

void SessionMemCac::SendCmdGetResponse(const Pairs& _pairs)
{
	for(const std::pair<std::string, Record>& pair : _pairs)
	{
		Send("VALUE " + pair.first + " " + std::to_string(pair.second.flag) + " " + std::to_string(pair.second.data.size()));
		Send(pair.second.data);
	}

}

void SessionMemCac::SendCmdSetReponse()
{
	Send("STORED");
}

void SessionMemCac::SendCmdDeleteResponse()
{
	Send("DELETED");
}

ext: cpp


text:
// Copyright (C) 2007 Anthony Williams
// Copyright (C) 2013 Tim Blechmann
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#define BOOST_TEST_MODULE Boost.Threads: physical_concurrency test suite

#include <boost/thread/thread_only.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread/mutex.hpp>

BOOST_AUTO_TEST_CASE(test_physical_concurrency_is_non_zero)
{
    BOOST_CHECK(boost::thread::physical_concurrency()!=0);
}


text:
#ifndef SHIFT_NETWORK_TCPSOCKETLISTENER_HPP
#define SHIFT_NETWORK_TCPSOCKETLISTENER_HPP

#include <memory>
#include <shift/core/boost_disable_warnings.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <shift/core/boost_restore_warnings.hpp>
#include "shift/network/network.hpp"
#include "shift/network/socket_base.hpp"

namespace shift::network
{
/// A server-side connection which allows listening on sockets and
/// duplicating itself on each incomming connection to handle communication.
class tcp_socket_listener final
: public socket_base,
  public std::enable_shared_from_this<tcp_socket_listener>
{
public:
  /// Constructor creating the server instance.
  tcp_socket_listener(network::options options);

  /// Destructor.
  ~tcp_socket_listener();

  /// Closes the connection and eventually cancels any pending accept.
  /// @remarks:
  ///   On system shutdown you need to wait until all queued coroutines are
  ///   finished.
  void close();

  /// Starts listening on the server socket.
  /// @param bind_port
  ///   If this parameter is set to zero, the port will be chosen
  ///   automatically by the OS. You may query the port once listen has been
  ///   called using socket::port.
  bool listen(boost::asio::ip::address bind_address, std::uint16_t bind_port);

  /// Returns the local endpoint which the socket is listening on.
  boost::asio::ip::tcp::endpoint local_endpoint() const;

public:
  /// Event handler which gets called once a Tcp connection is established.
  on_connected_t on_connected;

  /// Event handler which gets called when a Tcp connection gets closed or a
  /// connect attempt failed.
  on_closed_t on_closed;

  class impl;

protected:
  std::unique_ptr<impl> _impl;
};
}

#endif

ext: hpp

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
/*=============================================================================
Copyright (c) 2016 Paul W. Bible

Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef PRECOMPUTED_MATRIX_TERM_SIMILARITY
#define PRECOMPUTED_MATRIX_TERM_SIMILARITY

#include <vector>
#include <exception>

#include <ggtk/TermSimilarityInterface.hpp>

#include <boost/tokenizer.hpp>

//! A class to calculate similarity between go terms for 2 sets using a precomuted term similarity matrix.
/*! \class PrecomputedMatrixTermSimilarity
	This class allows the term similarity calculation to be decoupled
	 from term set (gene) similarity measure that use them.
	 Term similarity is loaded from a matrix file.
*/
class PrecomputedMatrixTermSimilarity: public TermSimilarityInterface{

public:

	//! A constructor
	/*!
		Parses a matrix file and creates the PrecomputedMatrixTermSimilarity object
	*/
	inline PrecomputedMatrixTermSimilarity(std::string matrix_file){
		std::ifstream in(matrix_file.c_str());
		//Tokenizer type
		typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
		boost::char_separator<char> tab_sep("\t","",boost::keep_empty_tokens);
		tokenizer::iterator it;
		std::string line;

		std::size_t line_count = 0;

		//first line
		getline(in,line);
		tokenizer tokens(line,tab_sep);
		it = tokens.begin();

		std::string firstTerm = *it;
		_termToIndex[firstTerm] = line_count;
		++line_count;
		++it;

		std::vector<double> firstRow;
		while(it != tokens.end()){
			std::string strval = *it;
			double val = atof(strval.c_str());
			firstRow.push_back(val);
			++it;
		}

		std::size_t nRows = firstRow.size();
		_matrix.reserve(nRows);
		_matrix.push_back(firstRow);

		while(in.good()){
			getline(in,line);
			tokenizer tokens(line,tab_sep);
			it = tokens.begin();
			if(it == tokens.end()){continue;}

			std::string term = *it;
			_termToIndex[term] = line_count;
			++line_count;
			++it;

			std::vector<double> row;
			row.reserve(nRows);
			while(it != tokens.end()){
				std::string strval = *it;
				double val = atof(strval.c_str());
				row.push_back(val);
				++it;
			}
			_matrix.push_back(row);
		}
		//std::cout << "rows " << _matrix.size() << std::endl;
		//std::cout << "cols " << _matrix.at(0).size() << std::endl;
		//std::cout << "terms " << _termToIndex.size() << std::endl;
	}

	//! A method to check if the file exists and fits the format
	/*!
		This method is used to test if a file can be used.
	*/
	bool isFileGood(const std::string &filename){
		std::ifstream in(filename.c_str());
		if (!in.good()){
			return false;
		}

		typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
		boost::char_separator<char> tab_sep("\t", "", boost::keep_empty_tokens);
		tokenizer::iterator it;
		std::string line;

		std::size_t line_count = 0;

		//first line
		getline(in, line);
		tokenizer tokens(line, tab_sep);
		it = tokens.begin();

		std::string firstTerm = *it;
		++line_count;
		++it;

		std::vector<double> firstRow;
		while (it != tokens.end()){
			std::string strval = *it;
			double val = atof(strval.c_str());
			firstRow.push_back(val);
			++it;
		}

		try{
			while (in.good() && line_count < 5){
				getline(in, line);
				tokenizer tokens(line, tab_sep);
				it = tokens.begin();
				if (it == tokens.end()){ continue; }

				std::string term = *it;
				++line_count;
				++it;

				std::vector<double> row;
				row.reserve(firstRow.size());
				while (it != tokens.end()){
					std::string strval = *it;
					double val = atof(strval.c_str());
					row.push_back(val);
					++it;
				}
				if (row.size() != firstRow.size()){
					return false;
				}
			}
		}
		catch (std::exception e){
			return false;
		}

		return true;
	}

	//! A method for calculating term-to-term similarity for GO terms using a precomputed similarity matrix.
	/*!
		This method returns the term similarity as defined by the matrix.
	*/
	inline double calculateTermSimilarity(std::string goTermA, std::string goTermB){
		if(hasTerm(goTermA) && hasTerm(goTermB)){
			std::size_t i = _termToIndex[goTermA];
			std::size_t j = _termToIndex[goTermB];
			return _matrix[i][j];
		}else{
			return 0.0;
		}
	}

	//! A method for calculating term-to-term similarity for GO terms using a precomputed similarity matrix.
	/*!
		This method returns the similarity scaled between 0 and 1 [0,1] inclusive
	*/
	inline double calculateNormalizedTermSimilarity(std::string goTermA, std::string goTermB){
		return calculateTermSimilarity(goTermA,goTermB);
	}

	//! This method projects a set of terms into it the kernel space
	/*!
		This method treats the term similarity matrix as a kernel
		 and projects a set of terms into it.
	*/
	std::vector<double> projectTermSet(const std::vector<std::string> &terms){
		std::vector<double> projectedVec(_matrix.size(),0.0);
		std::vector<std::string>::const_iterator it;

		for(std::size_t col = 0; col < _matrix.size(); ++col){
			double sum = 0.0;
			for(it = terms.begin(); it != terms.end(); ++it){
				std::string prot = *it;
				if(_termToIndex.find(prot) != _termToIndex.end()){
					std::size_t row = _termToIndex[prot];
					sum += _matrix.at(row).at(col);
				}
			}
			projectedVec[col] = sum;
		}
		return projectedVec;
	}

private:
	inline bool hasTerm(const std::string &term){
		return _termToIndex.find(term) != _termToIndex.end();
	}

	boost::unordered_map<std::string, std::size_t> _termToIndex;
	std::vector<std::vector<double> >   _matrix;

};
#endif

max_stars_repo_name: paulbible/ggtk

max_issues_repo_name: paulbible/ggtk

max_forks_repo_name: paulbible/ggtk


text: #include <boost/math/special_functions/bessel_prime.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*=============================================================================
    Boost.Wave: A Standard compliant C++ preprocessor library

    http://www.boost.org/

    Copyright (c) 2001-2008 Hartmut Kaiser. Distributed under the Boost
    Software License, Version 1.0. (See accompanying file
    LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/

#if !defined(INTERPRET_PRAGMA_HPP_B1F2315E_C5CE_4ED1_A343_0EF548B7942A_INCLUDED)
#define INTERPRET_PRAGMA_HPP_B1F2315E_C5CE_4ED1_A343_0EF548B7942A_INCLUDED

#include <string>
#include <list>

#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_assign_actor.hpp>
#include <boost/spirit/include/classic_push_back_actor.hpp>
#include <boost/spirit/include/classic_confix.hpp>

#include <boost/wave/wave_config.hpp>

#include <boost/wave/util/pattern_parser.hpp>
#include <boost/wave/util/macro_helpers.hpp>

#include <boost/wave/token_ids.hpp>
#include <boost/wave/cpp_exceptions.hpp>
#include <boost/wave/cpp_iteration_context.hpp>
#include <boost/wave/language_support.hpp>

#if !defined(spirit_append_actor)
#define spirit_append_actor(actor) boost::spirit::classic::push_back_a(actor)
#define spirit_assign_actor(actor) boost::spirit::classic::assign_a(actor)
#endif // !defined(spirit_append_actor)

// this must occur after all of the includes and before any code appears
#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_PREFIX
#endif

///////////////////////////////////////////////////////////////////////////////
namespace boost {
namespace wave {
namespace util {

///////////////////////////////////////////////////////////////////////////////
//
//  The function interpret_pragma interprets the given token sequence as the
//  body of a #pragma directive (or parameter to the _Pragma operator) and
//  executes the actions associated with recognized Wave specific options.
//
///////////////////////////////////////////////////////////////////////////////
template <typename ContextT, typename IteratorT, typename ContainerT>
inline bool
interpret_pragma(ContextT &ctx, typename ContextT::token_type const &act_token,
    IteratorT it, IteratorT const &end, ContainerT &pending)
{
    typedef typename ContextT::token_type token_type;
    typedef typename token_type::string_type string_type;

    using namespace cpplexer;
    if (T_IDENTIFIER == token_id(*it)) {
    // check for pragma wave ...
        if ((*it).get_value() == BOOST_WAVE_PRAGMA_KEYWORD)
        {
        //  this is a wave specific option, it should have the form:
        //
        //      #pragma command option(value)
        //
        //  where
        //      'command' is the value of the preprocessor constant
        //                BOOST_WAVE_PRAGMA_KEYWORD (defaults to "wave") and
        //      '(value)' is required only for some pragma directives (this is
        //                optional)
        //
        //  All recognized #pragma operators are forwarded to the supplied
        //  preprocessing hook.
            using namespace boost::spirit::classic;
            token_type option;
            ContainerT values;

            if (!parse (++it, end,
                            (   ch_p(T_IDENTIFIER)
                                [
                                    spirit_assign_actor(option)
                                ]
                            |   pattern_p(KeywordTokenType, TokenTypeMask)
                                [
                                    spirit_assign_actor(option)
                                ]
                            |   pattern_p(OperatorTokenType|AltExtTokenType,
                                    ExtTokenTypeMask)   // and, bit_and etc.
                                [
                                    spirit_assign_actor(option)
                                ]
                            |   pattern_p(BoolLiteralTokenType, TokenTypeMask)
                                [
                                    spirit_assign_actor(option)
                                ]
                            )
                        >> !comment_nest_p(
                                ch_p(T_LEFTPAREN),
                                ch_p(T_RIGHTPAREN)
                            )[spirit_assign_actor(values)],
                    pattern_p(WhiteSpaceTokenType, TokenTypeMask)).hit)
            {
                BOOST_WAVE_THROW_CTX(ctx, preprocess_exception,
                    ill_formed_pragma_option,
                    impl::as_string<string_type>(it, end).c_str(),
                    act_token.get_position());
                return false;
            }

        // remove the falsely matched surrounding parenthesis's
            if (values.size() >= 2) {
                BOOST_ASSERT(T_LEFTPAREN == values.front() && T_RIGHTPAREN == values.back());
                values.erase(values.begin());
                typename ContainerT::reverse_iterator rit = values.rbegin();
                values.erase((++rit).base());
            }

        // decode the option (call the context_policy hook)
            if (!ctx.get_hooks().interpret_pragma(
                  ctx.derived(), pending, option, values, act_token))
            {
            // unknown #pragma option
            string_type option_str ((*it).get_value());

                option_str += option.get_value();
                if (values.size() > 0) {
                    option_str += "(";
                    option_str += impl::as_string(values);
                    option_str += ")";
                }
                BOOST_WAVE_THROW_CTX(ctx, preprocess_exception,
                    ill_formed_pragma_option,
                    option_str.c_str(), act_token.get_position());
                return false;
            }
            return true;
        }
#if BOOST_WAVE_SUPPORT_PRAGMA_ONCE != 0
        else if ((*it).get_value() == "once") {
        // #pragma once
            return ctx.add_pragma_once_header(ctx.get_current_filename());
        }
#endif
#if BOOST_WAVE_SUPPORT_PRAGMA_MESSAGE != 0
        else if ((*it).get_value() == "message") {
        // #pragma message(...) or #pragma message ...
            using namespace boost::spirit::classic;
            ContainerT values;

            if (!parse (++it, end,
                            (   (   ch_p(T_LEFTPAREN)
                                >>  lexeme_d[
                                        *(anychar_p[spirit_append_actor(values)] - ch_p(T_RIGHTPAREN))
                                    ]
                                >>  ch_p(T_RIGHTPAREN)
                                )
                            |   lexeme_d[
                                    *(anychar_p[spirit_append_actor(values)] - ch_p(T_NEWLINE))
                                ]
                            ),
                            pattern_p(WhiteSpaceTokenType, TokenTypeMask)
                       ).hit
               )
            {
                BOOST_WAVE_THROW_CTX(ctx, preprocess_exception,
                    ill_formed_pragma_message,
                    impl::as_string<string_type>(it, end).c_str(),
                    act_token.get_position());
                return false;
            }

        // remove the falsely matched closing parenthesis/newline
            if (values.size() > 0) {
                BOOST_ASSERT(T_RIGHTPAREN == values.back() || T_NEWLINE == values.back());
                typename ContainerT::reverse_iterator rit = values.rbegin();
                values.erase((++rit).base());
            }

        // output the message itself
            BOOST_WAVE_THROW_CTX(ctx, preprocess_exception,
                pragma_message_directive,
                impl::as_string(values).c_str(), act_token.get_position());
            return false;
        }
#endif
    }
    return false;
}

///////////////////////////////////////////////////////////////////////////////
}   // namespace util
}   // namespace wave
}   // namespace boost

// the suffix header occurs after all of the code
#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_SUFFIX
#endif

#endif // !defined(INTERPRET_PRAGMA_HPP_B1F2315E_C5CE_4ED1_A343_0EF548B7942A_INCLUDED)

max_stars_repo_name: jaredhoberock/gotham

max_issues_repo_name: jaredhoberock/gotham

max_forks_repo_name: jaredhoberock/gotham


text:
#include "FileDecompressor.hpp"

// Boost libraries
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>

// spdlog
#include <spdlog/spdlog.h>

using std::string;

namespace clp {
    bool FileDecompressor::decompress_file (streaming_archive::MetadataDB::FileIterator& file_metadata_ix, const string& output_dir,
                                            streaming_archive::reader::Archive& archive_reader, std::unordered_map<string, string>& temp_path_to_final_path)
    {
        // Open compressed file
        auto error_code = archive_reader.open_file(m_encoded_file, file_metadata_ix, true);
        if (ErrorCode_Success != error_code) {
            if (ErrorCode_errno == error_code) {
                SPDLOG_ERROR("Failed to open encoded file, errno={}", errno);
            } else {
                SPDLOG_ERROR("Failed to open encoded file, error_code={}", error_code);
            }
            return false;
        }

        boost::filesystem::path final_output_path = output_dir;
        final_output_path /= m_encoded_file.get_orig_path();

        boost::filesystem::path temp_output_path = output_dir;
        FileWriter::OpenMode open_mode;
        boost::system::error_code boost_error_code;
        if (m_encoded_file.is_split() || boost::filesystem::exists(final_output_path, boost_error_code)) {
            temp_output_path /= m_encoded_file.get_orig_file_id_as_string();
            open_mode = FileWriter::OpenMode::CREATE_IF_NONEXISTENT_FOR_APPENDING;
            auto temp_output_path_string = temp_output_path.string();
            if (0 == temp_path_to_final_path.count(temp_output_path_string)) {
                temp_path_to_final_path[temp_output_path_string] = final_output_path.string();
            }
        } else {
            temp_output_path = final_output_path;
            open_mode = FileWriter::OpenMode::CREATE_FOR_WRITING;
        }

        // Generate output directory
        error_code = create_directory_structure(final_output_path.parent_path().string(), 0700);
        if (ErrorCode_Success != error_code) {
            SPDLOG_ERROR("Failed to create directory structure {}, errno={}", final_output_path.parent_path().c_str(), errno);
            return false;
        }

        // Open output file
        m_decompressed_file_writer.open(temp_output_path.string(), open_mode);

        // Decompress
        archive_reader.reset_file_indices(m_encoded_file);
        while (archive_reader.get_next_message(m_encoded_file, m_encoded_message)) {
            if (!archive_reader.decompress_message(m_encoded_file, m_encoded_message, m_decompressed_message)) {
                // Can't decompress any more of file
                break;
            }
            m_decompressed_file_writer.write_string(m_decompressed_message);
        }

        // Close files
        m_decompressed_file_writer.close();
        archive_reader.close_file(m_encoded_file);

        return true;
    }
}

max_stars_repo_name: kirkrodrigues/clp

max_issues_repo_name: kirkrodrigues/clp

max_forks_repo_name: kirkrodrigues/clp


text:
/*
 * Created by Angel Leon (@gubatron), Alden Torres (aldenml)
 * Copyright (c) 2018, FrostWire(R). All rights reserved.
 */

#include "ltrpc/session_rpc.hpp"

#include <thread>
#include <vector>
#include <memory>

#include "ltrpc/aux/json_types.hpp"
#include "ltrpc/aux/handle_request.hpp"

#include <libtorrent/aux_/disable_warnings_push.hpp>

#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/bind_executor.hpp>

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>

#include <libtorrent/session.hpp>
#include <libtorrent/address.hpp>
#include <libtorrent/socket.hpp>
#include <libtorrent/settings_pack.hpp>

#include "ltrpc/aux/json.hpp"

#include <libtorrent/aux_/disable_warnings_pop.hpp>

using namespace std::placeholders;

using tcp = boost::asio::ip::tcp;

namespace http = boost::beast::http;

using json = nlohmann::json;

namespace ltrpc
{

struct session_logger
{
    virtual void on_error(int ec, std::string const& msg) const = 0;

protected:
    ~session_logger() = default;
};

namespace
{

std::string const rpc_listen_address_key = "rpc_listen_address";
std::string const rpc_listen_port_key = "rpc_listen_port";
std::string const rpc_num_threads_key = "rpc_num_threads";

std::string const rpc_listen_address_default = "127.0.0.1";
int const rpc_listen_port_default = 8181;
int const rpc_num_threads_default = 2;

class http_session : public std::enable_shared_from_this<http_session>
{
    struct send_lambda
    {
        http_session& m_self;

        explicit send_lambda(http_session& self)
            : m_self(self)
        {}

        template<bool isRequest, class Body, class Fields>
        void operator()(http::message<isRequest, Body, Fields>&& msg) const
        {
            // The lifetime of the message has to extend
            // for the duration of the async operation so
            // we use a shared_ptr to manage it.
            auto sp = std::make_shared<
                http::message<isRequest, Body, Fields>>(std::move(msg));

            // Store a type-erased version of the shared
            // pointer in the class to keep it alive.
            m_self.m_res = sp;

            // Write the response
            http::async_write(
                m_self.m_socket,
                *sp,
                boost::asio::bind_executor(
                    m_self.m_strand,
                    std::bind(
                        &http_session::on_write,
                        m_self.shared_from_this(),
                        std::placeholders::_1,
                        std::placeholders::_2,
                        sp->need_eof())));
        }
    };

public:

    explicit http_session(tcp::socket socket, session_logger& logger)
        : m_socket{std::move(socket)}
        , m_logger{logger}
        , m_strand{m_socket.get_executor()}
        , m_lambda{*this}
    {}

    void run()
    {
        do_read();
    }

    void do_read()
    {
        m_req = {};

        http::async_read(m_socket, m_buffer, m_req
            , boost::asio::bind_executor(m_strand
                , std::bind(&http_session::on_read
                    , shared_from_this(), _1, _2)));
    }

    void on_read(boost::system::error_code ec, std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);

        // this means they closed the connection
        if (ec == http::error::end_of_stream)
            return do_close();

        if (ec)
        {
            m_logger.on_error(ec.value(), "read");
            return;
        }

        // send the response
        aux::handle_request(std::move(m_req), m_lambda);
    }

    void on_write(boost::system::error_code ec, std::size_t bytes_transferred
        , bool const close)
    {
        boost::ignore_unused(bytes_transferred);

        if (ec)
        {
            m_logger.on_error(ec.value(), "write");
            return;
        }

        if (close)
        {
            // this means we should close the connection, usually because
            // the response indicated the "Connection: close" semantic.
            return do_close();
        }

        // we're done with the response so delete it
        m_res.reset();

        do_read();
    }

    void do_close()
    {
        boost::system::error_code ec;
        m_socket.shutdown(tcp::socket::shutdown_send, ec);
    }

private:

    tcp::socket m_socket;
    session_logger& m_logger;
    boost::asio::strand<boost::asio::io_context::executor_type> m_strand;
    boost::beast::flat_buffer m_buffer;
    http::request<http::string_body> m_req;
    std::shared_ptr<void> m_res;
    send_lambda m_lambda;
};

class http_listener : public std::enable_shared_from_this<http_listener>
{
public:

    http_listener(boost::asio::io_context& ioc, tcp::endpoint const& endp
        , session_logger& logger)
        : m_acceptor{ioc}
        , m_socket{ioc}
        , m_logger{logger}
    {
        boost::system::error_code ec;

        m_acceptor.open(endp.protocol(), ec);
        if (ec)
        {
            m_logger.on_error(ec.value(), "open");
            return;
        }

        m_acceptor.set_option(boost::asio::socket_base::reuse_address(true), ec);
        if (ec)
        {
            m_logger.on_error(ec.value(), "set_option");
            return;
        }

        m_acceptor.bind(endp, ec);
        if (ec)
        {
            m_logger.on_error(ec.value(), "bind");
            return;
        }

        m_acceptor.listen(boost::asio::socket_base::max_listen_connections, ec);
        if (ec)
        {
            m_logger.on_error(ec.value(), "listen");
            return;
        }
    }

    void run()
    {
        if (!m_acceptor.is_open())
            return;
        do_accept();
    }

    void do_accept()
    {
        m_acceptor.async_accept(m_socket
            , std::bind(&http_listener::on_accept, shared_from_this(), _1));
    }

    void on_accept(boost::system::error_code ec)
    {
        if (ec)
        {
            m_logger.on_error(ec.value(), "accept");
        }
        else
        {
            auto session = std::make_shared<http_session>(std::move(m_socket)
                , m_logger);
            session->run();
        }

        do_accept();
    }

private:

    tcp::acceptor m_acceptor;
    tcp::socket m_socket;
    session_logger& m_logger;
};

} // anonymous namespace

class session_rpc::impl final : public session_logger
{
public:

    impl() = default;

    void set_error_cb(std::function<void(int, std::string const&)> cb);

    void listen(std::string const settings);

    void on_error(int ec, std::string const& msg) const override;

private:

    std::function<void(int, std::string const&)> m_error_cb;
    std::unique_ptr<lt::session> m_session;
};

void session_rpc::impl::set_error_cb(
    std::function<void(int, std::string const&)> cb)
{
    m_error_cb = std::move(cb);
}

void session_rpc::impl::listen(std::string const settings)
{
    auto sett = json::parse(settings);

    auto const listen_address = sett.value(rpc_listen_address_key
        , rpc_listen_address_default);
    int const listen_port = sett.value(rpc_listen_port_key
        , rpc_listen_port_default);
    int const num_threads = sett.value(rpc_num_threads_key
        , rpc_num_threads_default);

    lt::settings_pack sp = sett;

    // in C++ 17 use std::make_unique
    m_session = std::unique_ptr<lt::session>(new lt::session(std::move(sp)));

    boost::asio::io_context ioc{num_threads};
    tcp::endpoint endp{lt::make_address(listen_address)
        , std::uint16_t(listen_port)};

    auto listener = std::make_shared<http_listener>(ioc, endp, *this);
    listener->run();

    // run the I/O service on the requested number of threads
    std::vector<std::thread> v;
    v.reserve(std::size_t(num_threads - 1));
    for (int i = num_threads - 1; i > 0; --i)
        v.emplace_back([&ioc] { ioc.run(); });
    ioc.run();
}

void session_rpc::impl::on_error(int ec, std::string const& msg) const
{
    if (m_error_cb)
        m_error_cb(ec, msg);
}

session_rpc::session_rpc()
    : m_impl{new impl()}
{}

session_rpc::~session_rpc() = default;

session_rpc::session_rpc(session_rpc&&) noexcept = default;
session_rpc& session_rpc::operator=(session_rpc&&) noexcept = default;

void session_rpc::set_error_cb(std::function<void(int, std::string const&)> cb)
{
    m_impl->set_error_cb(std::move(cb));
}

void session_rpc::listen(std::string settings)
{
    m_impl->listen(std::move(settings));
}

} // ltrpc

max_stars_repo_name: frostwire/libtorrent-rpc

max_issues_repo_name: frostwire/libtorrent-rpc

max_forks_repo_name: frostwire/libtorrent-rpc


text:
//
// file RDKitMolToQPainter.cc
//
// Contributed by:
// David Cosgrove
// AstraZeneca
// 28th June 2012
//
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
// Draw an RDKit Drawing into a QPainter object.
// Hacked together by analogy with the SVG drawer in
// $RDBASE/Code/Demos/RDKit/Draw/demo.cpp
//

#include <GraphMol/RDKitBase.h>
#include <GraphMol/Depictor/RDDepictor.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/MolDrawing/MolDrawing.h>  // this is what does the 2D drawing!

#include <QFont>
#include <QPainter>
#include <QString>

#include <cstring>
#include <iostream>
#include <limits>
#include <map>
#include <string>

#include <boost/scoped_ptr.hpp>

using namespace boost;
using namespace std;
using namespace RDKit;

typedef scoped_ptr<RWMol> pRWMol;

static const int LINE_WIDTH_MULT = 4;
// this size seems to work well with the relative scale of the Drawing
static const float ORIGINAL_FONT_SIZE = 35.0;

// ****************************************************************************
QColor &colour_for_atomic_num(int atnum) {
  static QColor colours[10] = {
      QColor("Black"),  QColor("Blue"),   QColor("Red"),   QColor("LightGreen"),
      QColor("Orange"), QColor("Yellow"), QColor("Green"), QColor("Brown"),
      QColor("Purple"), QColor("Cyan")};

  switch (atnum) {
    case 6:
      return colours[0];
    case 7:
      return colours[1];
    case 8:
      return colours[2];
    case 9:
      return colours[3];
    case 15:
      return colours[4];
    case 16:
      return colours[5];
    case 17:
      return colours[6];
    case 37:
      return colours[7];
    case 53:
      return colours[8];
    default:
      return colours[9];
  }
}

#ifdef NOTYET
// ****************************************************************************
string colour_for_atomic_num(int atnum) {
  static map<int, string> colours;
  if (colours.empty()) {
    colours.insert(make_pair(6, "Black"));       // carbon
    colours.insert(make_pair(7, "Blue"));        // nitrogen
    colours.insert(make_pair(8, "Red"));         // oxygen
    colours.insert(make_pair(9, "LightGreen"));  // fluorine
    colours.insert(make_pair(15, "Orange"));     // phosphorous
    colours.insert(make_pair(16, "Yellow"));     // sulfur
    colours.insert(make_pair(17, "Green"));      // chlorine
    colours.insert(make_pair(37, "Brown"));      // bromine
    colours.insert(make_pair(53, "Purple"));     // iodine
  }

  map<int, string>::iterator q = colours.find(atnum);
  if (q == colours.end()) {
    return "Cyan";
  } else {
    return q->second;
  }
}
#endif

// ****************************************************************************
void get_scale(int width, int height, int qp_width, int qp_height,
               qreal &gscale) {
  qreal xscale = qreal(qp_width) / qreal(width);
  qreal yscale = qreal(qp_height) / qreal(height);

  gscale = std::min(xscale, yscale);

#ifdef NOTYET
  cout << "Scale for picture " << width << " by " << height << endl
       << " qpainter " << qp_width << " by " << qp_height << endl
       << "x and y scales : " << xscale << " , " << yscale << endl;
  cout << "Final scale : " << gscale << endl;
#endif
}

// ****************************************************************************
void set_scale(int width, int height, int min_x, int min_y, int qp_width,
               int qp_height, QPainter &qp, qreal &gscale) {
  qp.scale(gscale, gscale);
  qreal qp_width_in_scale = qreal(qp_width) / gscale;
  qreal qp_height_in_scale = qreal(qp_height) / gscale;

  // move it to a central point in the window
  qp.translate(-min_x + 0.5 * (qp_width_in_scale - width),
               -min_y + 0.5 * (qp_height_in_scale - height));
}

// ****************************************************************************
void set_font(QPainter &qp) {
  static QFont *font = 0;
  if (!font) {
    font = new QFont(qp.font());
  }

  font->setPointSizeF(ORIGINAL_FONT_SIZE);
  qp.setFont(*font);
}

// ****************************************************************************
void draw_line(vector<int>::iterator &pos, bool bow, QPainter &qp) {
  int width = *pos++;
  pos++;  // skip 'dashed' flag
  int atom1 = *pos++;
  int atom2 = *pos++;

  int xp1 = *pos++;
  int yp1 = *pos++;
  int xp2 = *pos++;
  int yp2 = *pos++;

  static QPen pen("Black");
  pen.setJoinStyle(Qt::RoundJoin);
  pen.setWidth(width * LINE_WIDTH_MULT);
  qp.setPen(pen);

  if (atom1 == atom2) {
    if (!bow) {
      pen.setColor(colour_for_atomic_num(atom1));
      qp.setPen(pen);
    }
    qp.drawLine(xp1, yp1, xp2, yp2);
  } else {
    int mx = xp1 + (xp2 - xp1) / 2;
    int my = yp1 + (yp2 - yp1) / 2;
    if (!bow) {
      pen.setColor(colour_for_atomic_num(atom1));
      qp.setPen(pen);
    }
    qp.drawLine(xp1, yp1, mx, my);
    if (!bow) {
      pen.setColor(colour_for_atomic_num(atom2));
      qp.setPen(pen);
    }
    qp.drawLine(mx, my, xp2, yp2);
  }
}

// ****************************************************************************
void draw_atom(vector<int>::iterator &pos, bool bow, QPainter &qp) {
  int atnum = *pos++;
  int xp = *pos++;
  int yp = *pos++;
  int slen = *pos++;
  QString label;
  for (int i = 0; i < slen; ++i) {
    label += static_cast<char>(*pos++);
  }
  pos++;  // move past orient flag, which is not being used

  char letter[2] = {'\0', '\0'};

  qp.save();

  QRectF whole_br = qp.boundingRect(0, 0, 100, 100, Qt::AlignHCenter, label);
  qp.translate(xp - whole_br.width() / 2.0, yp - whole_br.height() / 2.0);

  static QPen pen("Black");
  qp.setPen(pen);
  pen.setJoinStyle(Qt::RoundJoin);
  if (!bow) {
    pen.setColor(colour_for_atomic_num(atnum));
    qp.setPen(pen);
  }

  // blank out behind the letters, so bonds don't go through where the label is.
  // I think circles work better than rectangles for this, but it means going
  // through it all twice, as the circles overlap so would obscure the letter
  // that came afterwards This assumes the bonds are drawn before the atoms,
  // which is how it is set up in MolDrawing.h.
  static QBrush letter_brush(qp.background());
  letter_brush.setStyle(Qt::SolidPattern);

  qp.save();
  qp.setPen(qp.background().color());  // so the ellipse doesn't have a border
  qp.setBrush(letter_brush);

  // do things 1 letter at a time. We needed to stuff the characters into label
  // first, so as to get the bounding rectangle for the whole label.
  for (int i = 0; i < slen; ++i) {
    letter[0] = label.toLocal8Bit().data()[i];
    QString at_lab(letter);
    QRectF br = qp.boundingRect(0, 0, 1000, 1000, Qt::AlignHCenter, at_lab);

    // subscript for numbers, superscript for charge. Stretch the ellipse out so
    // the bond is obscured over the whole of its extent.
    qreal letter_top = 0.0, letter_height = br.height();
    if (isdigit(letter[0])) {
      qp.translate(0.0, br.height() / 2.0);
      letter_top = -br.height() / 2.0;
      letter_height += br.height() / 2.0;
    } else if ('+' == letter[0] || '-' == letter[0]) {
      qp.translate(0.0, -br.height() / 2.0);
      letter_height += br.height() / 2.0;
    }
    qp.drawEllipse(
        QRectF(-2.0, -2.0 + letter_top, br.width() + 2.0, letter_height + 2.0));
    qp.translate(br.width(), 0.0);

    // remove superscript/subscript
    if (isdigit(letter[0])) {
      qp.translate(0.0, -br.height() / 2.0);
    } else if ('+' == letter[0] || '-' == letter[0]) {
      qp.translate(0.0, br.height() / 2.0);
    }
  }
  qp.setPen(pen);
  qp.restore();

  // now the letters
  for (int i = 0; i < slen; ++i) {
    letter[0] = label.toLocal8Bit().data()[i];
    QString at_lab(letter);
    QRectF br = qp.boundingRect(0, 0, 1000, 1000, Qt::AlignHCenter, at_lab);

    // subscript for numbers, superscript for charge
    if (isdigit(letter[0])) {
      qp.translate(0.0, br.height() / 2.0);
    } else if ('+' == letter[0] || '-' == letter[0]) {
      qp.translate(0.0, -br.height() / 2.0);
    }
    qp.drawText(QRectF(0.0, 0.0, br.width(), br.height()), Qt::AlignHCenter,
                at_lab, &br);
    qp.translate(br.width(), 0.0);

    // remove superscript/subscript
    if (isdigit(letter[0])) {
      qp.translate(0.0, -br.height() / 2.0);
    } else if ('+' == letter[0] || '-' == letter[0]) {
      qp.translate(0.0, br.height() / 2.0);
    }
  }

  qp.restore();
}

// ****************************************************************************
void line_extremes(vector<int>::const_iterator &pos, int &min_x, int &max_x,
                   int &min_y, int &max_y) {
  pos += 4;  // past the line width, type and atom numbers
  int xp1 = *pos++;
  int yp1 = *pos++;
  int xp2 = *pos++;
  int yp2 = *pos++;

  min_x = xp1 < min_x ? xp1 : min_x;
  max_x = xp1 > max_x ? xp1 : max_x;
  min_y = yp1 < min_y ? yp1 : min_y;
  max_y = yp1 > max_y ? yp1 : max_y;

  min_x = xp2 < min_x ? xp2 : min_x;
  max_x = xp2 > max_x ? xp2 : max_x;
  min_y = yp2 < min_y ? yp2 : min_y;
  max_y = yp2 > max_y ? yp2 : max_y;
}

// ****************************************************************************
void atom_extremes(vector<int>::const_iterator &pos, QPainter &qp, int &min_x,
                   int &max_x, int &min_y, int &max_y) {
  pos++;  // skip the atomic number, not needed for this
  int xp = *pos++;
  int yp = *pos++;
  int slen = *pos++;
  QString label;
  for (int i = 0; i < slen; ++i) {
    label += static_cast<char>(*pos++);
  }
  pos++;  // move past orient flag, which is not being used, and indeed is not
          // understood!

  QRectF whole_br = qp.boundingRect(0, 0, 1000, 1000, Qt::AlignHCenter, label);

  int labx1 = xp - int(whole_br.width() / 2.0);
  int labx2 = xp + int(whole_br.width());
  // subscripts and superscripts may occur in the atom label. Just allow for
  // that willy-nilly.
  int laby1 = yp - int(0.5 * whole_br.height());
  int laby2 = yp + int(0.5 * whole_br.height());

  min_x = labx1 < min_x ? labx1 : min_x;
  max_x = labx2 > max_x ? labx2 : max_x;
  min_y = laby1 < min_y ? laby1 : min_y;
  max_y = laby2 > max_y ? laby2 : max_y;
}

// ****************************************************************************
void setup_scale(vector<int> &drawing, QPainter &qp, int qp_width,
                 int qp_height) {
  // calculate the width of the drawing. The values for width and height as
  // supplied in drawing by MolDrawing.h don't allow for the width of atom
  // labels so if there are non-carbon atoms at the extremes of the picture,
  // these will be drawn off the page.
  vector<int>::const_iterator pos = drawing.begin() + 7;
  int min_x = numeric_limits<int>::max();
  int max_x = numeric_limits<int>::min();
  int min_y = numeric_limits<int>::max();
  int max_y = numeric_limits<int>::min();

  while (pos != drawing.end()) {
    int token = *pos++;
    switch (token) {
      case Drawing::LINE:
        line_extremes(pos, min_x, max_x, min_y, max_y);
        break;
      case Drawing::ATOM:
        atom_extremes(pos, qp, min_x, max_x, min_y, max_y);
        break;
      default:
        break;
    }
  }

  // allow for width of lines
  min_x -= LINE_WIDTH_MULT;
  max_x += LINE_WIDTH_MULT;
  min_y -= LINE_WIDTH_MULT;
  max_y += LINE_WIDTH_MULT;

  int width = max_x - min_x;
  int height = max_y - min_y;

  qreal gscale;
  get_scale(width, height, qp_width, qp_height, gscale);
  set_scale(width, height, min_x, min_y, qp_width, qp_height, qp, gscale);
}

// ****************************************************************************
void MolToQPainter(vector<int> &drawing, int qp_width, int qp_height, bool bow,
                   QPainter &qp) {
  vector<int>::iterator pos = drawing.begin() + 2;
  if (*pos != Drawing::BOUNDS) {
    // no drawing made by RDKit
    QString msg("Bad Drawing");
    qp.drawText(0, qp_height / 2, msg);
    return;
  }
  pos += 3;

  // save current transformation matrix()
  qp.save();

  set_font(qp);
  setup_scale(drawing, qp, qp_width, qp_height);

  pos += 2;  // for the width and height in the drawing
  while (pos != drawing.end()) {
    int token = *pos++;
    switch (token) {
      case Drawing::LINE:
        draw_line(pos, bow, qp);
        break;
      case Drawing::ATOM:
        draw_atom(pos, bow, qp);
        break;
      default:
        cerr << "Duff token, expect a crash." << token << endl;
        break;
    }
  }

  // put the transformation matrix back to how it was on entry
  qp.restore();
}

// ****************************************************************************
void label_molecule(const QString &label, int width, int height,
                    int label_height, QPainter &qp) {
  int label_y = height - label_height;
  qp.drawText(QRect(0, label_y, width, label_height), Qt::AlignHCenter, label);
}

// ****************************************************************************
// width and height are the size of the rectangle in qp we are drawing into.
// bow is black on white- when false,  colours are used in drawing
void smiles_to_qpainter(const string &smiles, const QString &label, int width,
                        int height, bool bow, QPainter &qp) {
  // render into an RDKit drawing
  pRWMol mol(SmilesToMol(smiles));
  MolOps::Kekulize(*mol);
  RDDepict::compute2DCoords(*mol);
  vector<int> drawing = Drawing::DrawMol(*mol);

  qp.setRenderHint(QPainter::Antialiasing, true);
  qp.setRenderHint(QPainter::TextAntialiasing, true);

  // get the height that will be needed for the label, and allow the picture to
  // accommodate it
  QRect br;
  if (!label.isEmpty()) {
    br = qp.boundingRect(QRect(0, 0, width, height), Qt::AlignHCenter, label);
  }

  int label_height = br.height() + 5;
  int pict_height = height - label_height;
  MolToQPainter(drawing, width, pict_height, bow, qp);

  if (!label.isEmpty()) {
    label_molecule(label, width, height, label_height, qp);
  }
}

ext: cc

max_stars_repo_name: kazuyaujihara/rdkit

max_issues_repo_name: kazuyaujihara/rdkit

max_forks_repo_name: kazuyaujihara/rdkit


text:
/**
 * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved
 *
 * This file is part of GeoDa.
 *
 * GeoDa is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GeoDa 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/uuid/uuid_io.hpp>
#include <json_spirit/json_spirit.h>
#include <json_spirit/json_spirit_writer.h>
#include <wx/utils.h>
#include <wx/xrc/xmlres.h>
#include "../logger.h"
#include "../VarTools.h"
#include "../GeoDa.h"
#include "../Project.h"
#include "../FramesManager.h"
#include "../HighlightState.h"
#include "../DataViewer/TableInterface.h"
#include "../DataViewer/TableState.h"
#include "../DataViewer/TimeState.h"
#include "../ShapeOperations/WeightsManState.h"
#include "../VarCalc/WeightsManInterface.h"
#include "../DialogTools/VariableSettingsDlg.h"
#include "WebViewExampleWin.h"

WebViewExampleDlg::WebViewExampleDlg(Project* project_,
									 const wxString& url,
									 wxWindow* parent,
									 wxWindowID id, const wxString& caption,
									 const wxPoint& pos, const wxSize& size,
									 long style)
: wxDialog(parent, id, caption, pos, size,
		   wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER),
project(project_), highlight_state(project->GetHighlightState()),
frames_manager(project->GetFramesManager()),
table_state(project->GetTableState()), table_int(project->GetTableInt()),
time_state(project->GetTimeState()), w_man_state(project->GetWManState()),
web_view(0), load_url_called(false)
{
	LOG_MSG("Entering WebViewExampleDlg::WebViewExampleDlg");

	Init(get_blank(), url);

	frames_manager->registerObserver(this);
	highlight_state->registerObserver(this);
	table_state->registerObserver(this);
	time_state->registerObserver(this);
	w_man_state->registerObserver(this);

	LOG_MSG("Exiting WebViewExampleDlg::WebViewExampleDlg");
}

WebViewExampleDlg::WebViewExampleDlg(Project* project_,
									 const wxString& page_source,
									 std::vector<GdaVarTools::VarInfo> var_info_,
									 std::vector<int> col_ids_,
									 wxWindow* parent,
									 wxWindowID id, const wxString& caption,
									 const wxPoint& pos, const wxSize& size,
									 long style)
: wxDialog(parent, id, caption, pos, size,
		   wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER),
project(project_), highlight_state(project->GetHighlightState()),
frames_manager(project->GetFramesManager()),
table_state(project->GetTableState()), table_int(project->GetTableInt()),
time_state(project->GetTimeState()), w_man_state(project->GetWManState()),
var_info(var_info_), col_ids(col_ids_),
web_view(0), load_url_called(false)
{
	LOG_MSG("Entering WebViewExampleDlg::WebViewExampleDlg");

	Init(page_source);
	//web_view->RunScript("AppendP(\"It Works!\");");
	//web_view->RunScript("document.body.style.background = 'orange';");

	frames_manager->registerObserver(this);
	highlight_state->registerObserver(this);
	table_state->registerObserver(this);
	time_state->registerObserver(this);
	w_man_state->registerObserver(this);

	LOG_MSG("Exiting WebViewExampleDlg::WebViewExampleDlg");
}

WebViewExampleDlg::~WebViewExampleDlg()
{
	LOG_MSG("In ~WebViewExampleDlg::WebViewExampleDlg");
	w_man_state->removeObserver(this);
	time_state->removeObserver(this);
	table_state->removeObserver(this);
	highlight_state->removeObserver(this);
	frames_manager->removeObserver(this);
}

void WebViewExampleDlg::Init(const wxString& page_source, const wxString& url)
{
	panel = new wxPanel(this);
	panel->SetBackgroundColour(*wxWHITE);
	SetBackgroundColour(*wxWHITE);

	Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler(WebViewExampleDlg::OnClose) );

	web_view = wxWebView::New(panel, wxID_ANY, wxWebViewDefaultURLStr,
							  wxDefaultPosition,
							  wxSize(600, 400));

	Connect(web_view->GetId(), wxEVT_WEBVIEW_LOADED,
            wxWebViewEventHandler(WebViewExampleDlg::OnDocumentLoaded),
			NULL, this);
	Connect(web_view->GetId(), wxEVT_WEBVIEW_TITLE_CHANGED,
            wxWebViewEventHandler(WebViewExampleDlg::OnTitleChanged),
			NULL, this);

	// Arrange above widgets in panel using sizers.
	// Top level panel sizer will be panel_h_szr
	// Below that will be panel_v_szr
	// panel_v_szr will directly receive widgets

	wxBoxSizer* panel_v_szr = new wxBoxSizer(wxVERTICAL);

	panel_v_szr->Add(web_view, 1, wxEXPAND);

	wxBoxSizer* panel_h_szr = new wxBoxSizer(wxHORIZONTAL);
	panel_h_szr->Add(panel_v_szr, 1, wxEXPAND);

	panel->SetSizer(panel_h_szr);

	// Top Sizer
	wxBoxSizer* top_h_sizer = new wxBoxSizer(wxHORIZONTAL);
	top_h_sizer->Add(panel, 1, wxEXPAND|wxALL, 5);

	SetSizerAndFit(top_h_sizer);
	web_view->SetPage(page_source, "");
	web_view->EnableContextMenu(false);
	web_view->SetFocus();

	if (!url.IsEmpty()) {
		LOG_MSG("Loading URL: " + url);
		LoadURL(url);
	}
}

void WebViewExampleDlg::OnClose(wxCloseEvent& ev)
{
	// Note: it seems that if we don't explictly capture the close event
	//       and call Destory, then the destructor is not called.
	Destroy();
}

// { "action": "close" } // immediately closes the web view

void WebViewExampleDlg::OnTitleChanged(wxWebViewEvent& ev)
{
	LOG_MSG("Entering WebViewExampleDlg::OnTitleChanged");
	//wxString s;
	//s << "Title changed: " << ev.GetString();
	//LOG_MSG(s);
	//SetTitle(s);

	json_spirit::Value v;
	// try to parse as JSON
	try {
		if (!json_spirit::read( ev.GetString().ToStdString(), v)) {
			throw std::runtime_error("Could not parse title as JSON");
		}
		json_spirit::Value action_val;
		if (!GdaJson::findValue(v, action_val, "action")) {
			throw std::runtime_error("could not find action");
		}
		if (action_val.get_str() == "notify") {
			parseActionNotify(v);
		} else if (action_val.get_str() == "request") {
			parseActionRequest(v);
		} else if (action_val.get_str() == "close") {
			LOG_MSG("closing WebView");
			wxCloseEvent close_event;
			OnClose(close_event);
		}
	} catch (std::runtime_error e) {
		wxString msg;
		msg << "JSON parsing failed: ";
		msg << e.what();
		LOG_MSG(msg);
	}

	LOG_MSG("Exiting WebViewExampleDlg::OnTitleChanged");
}

void WebViewExampleDlg::parseActionNotify(const json_spirit::Value& v)
{
	LOG_MSG("In WebViewExampleDlg::parseActionNotify");
	json_spirit::Value observable_val;
	if (!GdaJson::findValue(v, observable_val, "observable")) {
		throw std::runtime_error("could not find observable");
	}
	if (observable_val.get_str() == "HighlightState") {
		parseHighlightStateNotify(v);
	} else if (observable_val.get_str() == "TimeState") {
		parseTimeStateNotify(v);
	} else {
		throw std::runtime_error("no handler defined for observable "
								 + observable_val.get_str());
	}
}

void WebViewExampleDlg::parseHighlightStateNotify(const json_spirit::Value& v)
{
	LOG_MSG("In WebViewExampleDlg::parseHighlightStateNotify");
	json_spirit::Value ev_type;
	if (!GdaJson::findValue(v, ev_type, "event_type")) {
		throw std::runtime_error("could not find event_type");
	}
	bool notify = false;
	LOG_MSG(ev_type.get_str());
	if (ev_type.get_str() == "delta") {
		json_spirit::Value new_hl;
		if (!GdaJson::findValue(v, new_hl, "newly_highlighted")) {
			throw std::runtime_error("newly_highlighted not found");
		}
		json_spirit::Value new_uhl;
		if (!GdaJson::findValue(v, new_uhl, "newly_unhighlighted")) {
			throw std::runtime_error("newly_unhighlighted not found");
		}
		std::vector<int> new_hl_vec;
		if (!GdaJson::arrayToVec(new_hl.get_array(), new_hl_vec)) {
			throw std::runtime_error("could not convert Array to vector<int>");
		}
		std::vector<int> new_uhl_vec;
		if (!GdaJson::arrayToVec(new_uhl.get_array(), new_uhl_vec)) {
			throw std::runtime_error("could not convert Array to vector<int>");
		}
		LOG(new_hl_vec.size());
		LOG(new_uhl_vec.size());
		if (new_hl_vec.size() > 0 || new_uhl_vec.size() > 0) {
			std::vector<int>& nh = highlight_state->GetNewlyHighlighted();
			std::vector<int>& nuh = highlight_state->GetNewlyUnhighlighted();
			for (size_t i=0, sz=new_hl_vec.size(); i<sz; ++i) {
				nh[i] = new_hl_vec[i];
			}
			for (size_t i=0, sz=new_uhl_vec.size(); i<sz; ++i) {
				nuh[i] = new_uhl_vec[i];
			}
			highlight_state->SetEventType(HLStateInt::delta);
			highlight_state->SetTotalNewlyHighlighted(new_hl_vec.size());
			highlight_state->SetTotalNewlyUnhighlighted(new_uhl_vec.size());
			notify = true;
		}
	} else if (ev_type.get_str() == "unhighlight_all") {
		highlight_state->SetEventType(HLStateInt::unhighlight_all);
		notify = true;
	} else if (ev_type.get_str() == "invert") {
		highlight_state->SetEventType(HLStateInt::invert);
		notify = true;
	} else if (ev_type.get_str() == "empty") {
		LOG_MSG("Empty HighlightState event is empty.  Not notifying.");
	} else {
		wxString s("HighlightState event unrecognized: ");
		s << ev_type.get_str();
		LOG_MSG(s);
		throw std::runtime_error(s.ToStdString());
	}
	if (notify) {
		LOG_MSG("About to call HighlightState::notifyObservers, excluding "
				"WebViewExampleDlg::this");
		highlight_state->notifyObservers(this);
	}
}

void WebViewExampleDlg::parseTimeStateNotify(const json_spirit::Value& v)
{
	json_spirit::Value new_time;
	if (!GdaJson::findValue(v, new_time, "time")) {
		throw std::runtime_error("could not find time");
	}
	int tm = new_time.get_int();
	if (tm < 0 || tm >= time_state->GetTimeSteps()) {
		wxString s = "time value out of range: ";
		s << tm;
		throw std::runtime_error(s.ToStdString());
	}
	time_state->SetCurrTime(tm);
	LOG_MSG("About to call TimeState::notifyObservers, excluding "
			"WebViewExampleDlg::this");
	time_state->notifyObservers(this);
}

/**
 Requests come as an array of requests along with a callback_id.  Here's
 an example of two Table::GetName requests.

 {  "action": "request",
	"callback_id": "13032",
	"requests" : [
		{ "interface": "table",
			"operation": "getName",
			"params": { "col": 4, "time": 0 }
		},
		{ "interface": "table",
			"operation": "getName",
			"params": { "col": 2, "time": 0 }
		}
	]
 }

 Valid requests are given a response.  An example response for the
 above request could be:

 {
	"callback_id": 13032,
	"responses" : [ "HOVAL", "AREA" ]
 }

 JS function gda.response() is then called with this JSON object as
 the parameter.

 Other examples:

 { "action": "request",
	"callback_id": "43",
	"requests" : [
		{ "interface": "table",
			"operation": "GetColData",
			"col": 3
		},
		{ "interface": "table",
			"operation": "GetColData",
			"col": 6
			}
		]
 }

 response:

 { "callback_id": "43",
	"responses": [
		[ [1, 2, 3, 4, 5, 6], [2.1, 2.2, 2.3, 2.4, 2.5, 2.6] ],
		[ [13, 22, 43, 24, 54, 16], [23.1, 22.2, 42.3, 22.4, 221.5, 21.6] ]
	]
 }

 */
void WebViewExampleDlg::parseActionRequest(const json_spirit::Value& v)
{
	using namespace json_spirit;
	using namespace GdaJson;

	Value cb_v;
	if (!findValue(v, cb_v, "callback_id")) {
		throw std::runtime_error("could not find callback_id");
	}
	std::string cb_id = cb_v.get_str();
	LOG_MSG("Entering WebViewExampleDlg::parseActionRequest");

	Value requests_v;
	if (!findValue(v, requests_v, "requests")) {
		throw std::runtime_error("could not find requests array");
	}
	Array& req_a = requests_v.get_array();

	Object ret_obj;
	ret_obj.push_back(Pair("callback_id", cb_id));

	Array resp_a;
	for (size_t i=0, sz=req_a.size(); i<sz; ++i) {
		Value resp_val;
		if (req_a[i].type() != json_spirit::obj_type) {
			throw std::runtime_error("found a request not of JSON object type.");
		}
		if (getStrValFromObj(req_a[i], "interface") == "project" &&
			getStrValFromObj(req_a[i], "operation") == "promptVarSettings") {
			promptVarSettings(req_a[i].get_obj(), resp_val);
		}
		resp_a.push_back(resp_val);
	}
	ret_obj.push_back(Pair("responses", resp_a));

	std::string json_str = write(ret_obj);
	wxString js_call;
	js_call << "gda.response(" << json_str << ");";
	LOG_MSG(js_call);
	web_view->RunScript(js_call);
}

/**

 { "action": "request",
	"callback_id": "53",
	"requests" : [ {
		"interface": "project",
		"operation": "promptVarSettings",
		"arity": "bivariate", // also (uni/bi/tri/quad)variate
		"show_weights": false, // default
		"title": "Variable Settings" // optional
		"var1_title": "First Variable (X)" // optional
		"var2_title": "Second Variable (Y)", // optional
		"var3_title": "Third Variable (Z)", // optional
		"var4_title": "Fourth Variable" // optional
	}]
 }

 response:

 { "callback_id": "43",
	"responses": [
		{ "time_info": [ "1960", "1970", "1980", "1990" ],
		"current_time": 0,
		"var1": {
			"col": 4,
			"name": "POP",
			"time": 0,
			"time_variant": true,
			"displayed_decimals": 4, // or -1 for default
			"type": "real"
			"data": [ [1, 2, 3, 4, 5, 6], [2.1, 2.2, 2.3, 2.4, 2.5, 2.6] ] ],
		},
		"var2": {},
		"weights": { // full weights details and actual weights
		  },
		"selected": [1, 2, 3, 32]
		}
	]
 }

 or response:

 { "callback_id": "43",
	"responses": [
		{ "user_cancel" : null } ]
 }

 */
void WebViewExampleDlg::promptVarSettings(const json_spirit::Object& req,
										  json_spirit::Value& response_val)
{
	using namespace json_spirit;
	using namespace GdaJson;
	using namespace std;

	VariableSettingsDlg::VarType arity = VariableSettingsDlg::univariate;
	wxString arity_str = getStrValFromObj(req, "arity");
	if (arity_str == "univariate") {
		arity = VariableSettingsDlg::univariate;
	} else if (arity_str == "bivariate") {
		arity = VariableSettingsDlg::bivariate;
	} else if (arity_str == "trivariate") {
		arity = VariableSettingsDlg::trivariate;
	} else if (arity_str == "quadvariate") {
		arity = VariableSettingsDlg::quadvariate;
	} else {
		throw std::runtime_error("arity missing or invalid");
	}
	wxString title = "Variable Settings";
	wxString var1_title = "First Variable (X)";
	wxString var2_title = "Second Variable (Y)";
	wxString var3_title = "Third Variable (Z)";
	wxString var4_title = "Fourth Variable";
	if (hasName(req, "var1_title")) {
		var1_title = getStrValFromObj(req, "var1_title");
	}
	if (hasName(req, "var2_title")) {
		var2_title = getStrValFromObj(req, "var2_title");
	}
	if (hasName(req, "var3_title")) {
		var3_title = getStrValFromObj(req, "var3_title");
	}
	if (hasName(req, "var4_title")) {
		var4_title = getStrValFromObj(req, "var4_title");
	}
	bool show_weights = getBoolValFromObj(req, "show_weights");

	VariableSettingsDlg VS(project, arity, show_weights, false, title,
						   var1_title, var2_title, var3_title, var4_title);
	if (VS.ShowModal() != wxID_OK) {
		wxString s;
		s << "{ \"user_cancel\": null}";
		response_val = Value(s.ToStdString());
		return;
	}

	Object response_obj;

	vector<string> var_nms;
	var_nms.push_back("var1");
	var_nms.push_back("var2");
	var_nms.push_back("var3");
	var_nms.push_back("var4");

	vector<wxString> tm_strs;
	table_int->GetTimeStrings(tm_strs);
	Value tm_strs_val;
	toValue(tm_strs_val, tm_strs);
	response_obj.push_back(Pair("time_info", tm_strs_val));
	response_obj.push_back(toPair("current_time", time_state->GetCurrTime()));

	for (size_t i=0; i<VS.col_ids.size(); ++i) {
		Object o;
		int col = VS.col_ids[i];
		o.push_back(toPair("col", col));
		o.push_back(toPair("name", VS.var_info[i].name));
		o.push_back(toPair("time", VS.var_info[i].time));
		o.push_back(toPair("time_variant", VS.var_info[i].is_time_variant));
		o.push_back(toPair("displayed_decimals",
						   table_int->GetColDispDecimals(col)));
		GdaConst::FieldType ft = table_int->GetColType(col);
		o.push_back(toPair("type", GdaConst::FieldTypeToStr(ft)));
		Value data;
		b_array_type undefined;
		table_int->GetColUndefined(col, undefined);
		vector<GdaConst::FieldType> f_types = table_int->GetColTypes(col);
		if (ft == GdaConst::double_type) {
			d_array_type d;
			table_int->GetColData(col, d);
			toValue(data, d);
		} else if (ft == GdaConst::long64_type) {
			l_array_type d;
			table_int->GetColData(col, d);
			toValue(data, d);
		} else { // assume GdaConst::string
			s_array_type d;
			table_int->GetColData(col, d);
			toValue(data, d);
		}
		o.push_back(Pair("data", data));
		response_obj.push_back(Pair(var_nms[i], Value(o)));
	}

	// get current selection
	std::vector<int> sel;
	project->GetSelectedRows(sel);
	Value sel_val;
	toValue(sel_val, sel);
	response_obj.push_back(Pair("selected", sel_val));

	response_val = Value(response_obj);

	std::string json_str = write(response_obj);
	//LOG_MSG(json_str);
}

void WebViewExampleDlg::OnDocumentLoaded(wxWebViewEvent& ev)
{
	LOG_MSG("Entering WebViewExampleDlg::OnDocumentLoaded");
    //Only notify if the document is the main frame, not a subframe
    if (ev.GetURL() == web_view->GetCurrentURL()) {
		wxString s;
		s << "url: " << ev.GetURL();
		LOG_MSG(s);

		if (load_url_called) {
			web_view->RunScript("gda.readyToInit();");

			load_url_called = false;
		}

		//web_view->RunScript("document.body.style.background = 'orange';");
		//web_view->RunScript("AppendP(\"It Works!\");");

		/*
		if (load_url_called) {
			// call various JS functions to initialize.
			// initFromDataset expects the following init_obj JSON message:
			 // {
			 // var1_title: "title",
			 // var2_title: "title2",
			 // var1_data: [ 1, 2, 3, 4 ],
			 // var2_data: [ 1.1, 2.2, 3.3, 4.4 ],
			 // selected: [ 3, 12, 23, 33 ]
			 // }

			using namespace json_spirit;
			Object o;

			o.push_back(Pair("var1_title", var_info[0].name.ToStdString()));
			o.push_back(Pair("var2_title", var_info[1].name.ToStdString()));

			std::vector<double> v1;
			std::vector<double> v2;
			table_int->GetColData(col_ids[0], var_info[0].time, v1);
			table_int->GetColData(col_ids[1], var_info[1].time, v2);
			Array v1_array;
			Array v2_array;
			for (size_t i=0, sz=v1.size(); i<sz; ++i) {
				v1_array.push_back(Value(v1[i]));
				v2_array.push_back(Value(v2[i]));
			}
			o.push_back(Pair("var1_data", v1_array));
			o.push_back(Pair("var2_data", v2_array));

			Array init_sel;
			std::vector<bool>& hs = highlight_state->GetHighlight();
			for (size_t i=0, sz=hs.size(); i<sz; ++i) {
				if (hs[i]) init_sel.push_back((int) i);
			}
			o.push_back(Pair("selected", init_sel));

			std::string json_str = write(o);
			wxString js_call;
			js_call << "gda.initFromDataset(" << json_str << ");";
			//LOG_MSG(js_call);
			web_view->RunScript(js_call);

			load_url_called = false;
		}
	*/
    }
	LOG_MSG("Exiting WebViewExampleDlg::OnDocumentLoaded");
}

void WebViewExampleDlg::LoadURL(const wxString& url)
{
	load_url_called = true;
	web_view->LoadURL(url);
}

void WebViewExampleDlg::update(HLStateInt* o)
{
	LOG_MSG("Entering WebViewExampleDlg::update(HLStateInt*)");
	if (o->GetEventType() == HLStateInt::empty) return;

	wxString js_method = "gda.update";
	wxString s;
	s << js_method << "({";
	s << "\"observable\": \"HighlightState\",\n";
	s << "\"event\": \"" << o->GetEventTypeStr() << "\"";
	if (o->GetEventType() == HLStateInt::delta) {
		s << ",\n";
		s << "\"newly_highlighted\": [";
		std::vector<int>& nh = o->GetNewlyHighlighted();
		for (size_t i=0, sz=o->GetTotalNewlyHighlighted(); i<sz; ++i) {
			s << nh[i];
			if (i+1 < sz) s << ",";
		}
		s << "],\n";
		s << "\"newly_unhighlighted\": [";
		std::vector<int>& nuh = o->GetNewlyUnhighlighted();
		for (size_t i=0, sz=o->GetTotalNewlyUnhighlighted(); i<sz; ++i) {
			s << nuh[i];
			if (i+1 < sz) s << ",";
		}
		s << "]";
	}
	s << "});";

	/*
	 gda.update({"update": "HighlightState",
	 "event": "delta",
	 "newly_highlighted": [3,2,32,4],
	 "newly_unhighlighted": [23, 6, 7]
	 };
	 */

	//LOG_MSG(s);
	web_view->RunScript(s);

	LOG_MSG("Exiting WebViewExampleDlg::update(HLStateInt*)");
}

void WebViewExampleDlg::update(FramesManager* o)
{
}

void WebViewExampleDlg::update(TableState* o)
{
	LOG_MSG("In WebViewExampleDlg::update(TableState*)");
	TableState::EventType ev_type = o->GetEventType();
}

void WebViewExampleDlg::update(TimeState* o)
{
	LOG_MSG("Entering WebViewExampleDlg::update(TimeState*)");
	LOG(o->GetCurrTime());
	LOG(o->GetCurrTimeString());
	wxString js_method = "gda.update";
	wxString s;
	s << js_method << "({";
	s << "\"observable\": \"TimeState\",\n";
	s << "\"curr_time\": " << o->GetCurrTime() << ",\n";
	s << "\"curr_time_str\": \"" << o->GetCurrTimeString() << "\"";
	s << "});";

	LOG_MSG(s);
	web_view->RunScript(s);
	LOG_MSG("Exiting WebViewExampleDlg::update(TimeState*)");
}

void WebViewExampleDlg::update(WeightsManState* o)
{
	LOG_MSG("Entering WebViewExampleDlg::update(WeightsManState*)");
	LOG(o->GetEventTypeStr());
	wxString js_method = "gda.update";

	using namespace json_spirit;
	Object js_obj;

	js_obj.push_back(Pair("observable", "WeightsManState"));
	js_obj.push_back(Pair("event", o->GetEventTypeStr().ToStdString()));
	js_obj.push_back(Pair("weights_uuid",
						  boost::uuids::to_string(o->GetWeightsId())));
	if (o->GetEventType() == WeightsManState::name_change_evt) {
		js_obj.push_back(Pair("new_title",
							  project->GetWManInt()->
								GetTitle(o->GetWeightsId()).ToStdString()));
	}

	std::string json_str = write(js_obj);
	wxString js_call;
	js_call << js_method << "(" << json_str << ");";
	LOG_MSG(js_call);
	web_view->RunScript(js_call);

	LOG_MSG("Exiting WebViewExampleDlg::update(WeightsManState*)");
}

// wxWidgets Ticket: http://trac.wxwidgets.org/ticket/15548

wxString WebViewExampleDlg::get_blank()
{
	wxString s =
	"<!DOCTYPE html>\n"
	"<html lang=\"en\">\n"
	"  <head>\n"
	"    <meta charset=\"utf-8\"/>\n"
	"  </head>\n"
	"  <body>\n"
	"  </body>\n"
	"</html>\n";
	return s;
}

wxString WebViewExampleDlg::get_hover_example()
{
	wxString s = "<html><body><div "
	"onmouseover=\"this.style.background='red';\" "
	"onmouseout=\"this.style.background='blue';\"> "
	"onmouseover and onmouseout test<br/><br/> "
	"Move your mouse over here<br/> "
	"and background color should change.<br/><br/> "
	"It works on OSX when you click (=wrong) "
	"</div></body></html>";

	return s;
}

wxString WebViewExampleDlg::get_d3_chord_diagram()
{
	wxString s;
	s << "<!DOCTYPE html>\n";
	s << "<meta charset=\"utf-8\">\n";
	s << "<style>\n";

	s << "body {\n";
	s << "font: 10px sans-serif;\n";
	s << "}\n";

	s << ".chord path {\n";
	s << "	fill-opacity: .67;\n";
	s << "stroke: #000;\n";
	s << "	stroke-width: .5px;\n";
	s << "}\n";

	s << "</style>\n";
	s << "<body>\n";
	s << "<script src=\"http://d3js.org/d3.v3.min.js\"></script>\n";
	s << "<script>\n";

	s << "// From http://mkweb.bcgsc.ca/circos/guide/tables/\n";
	s << "var matrix = [\n";
	s << "			  [11975,  5871, 8916, 2868],\n";
	s << "			  [ 1951, 10048, 2060, 6171],\n";
	s << "			  [ 8010, 16145, 8090, 8045],\n";
	s << "			  [ 1013,   990,  940, 6907]\n";
	s << "			  ];\n";

	s << "var chord = d3.layout.chord()\n";
    s << ".padding(.05)\n";
    s << ".sortSubgroups(d3.descending)\n";
    s << ".matrix(matrix);\n";

	s << "var width = 960,\n";
    s << "height = 500,\n";
    s << "innerRadius = Math.min(width, height) * .41,\n";
    s << "outerRadius = innerRadius * 1.1;\n";

	s << "var fill = d3.scale.ordinal()\n";
    s << ".domain(d3.range(4))\n";
    s << ".range([\"#000000\", \"#FFDD89\", \"#957244\", \"#F26223\"]);\n";

	s << "var svg = d3.select(\"body\").append(\"svg\")\n";
    s << ".attr(\"width\", width)\n";
    s << ".attr(\"height\", height)\n";
	s << ".append(\"g\")\n";
    s << ".attr(\"transform\", \"translate(\" + width / 2 + \",\" + height / 2 + \")\");\n";

	s << "svg.append(\"g\").selectAll(\"path\")\n";
    s << ".data(chord.groups)\n";
	s << ".enter().append(\"path\")\n";
    s << ".style(\"fill\", function(d) { return fill(d.index); })\n";
    s << ".style(\"stroke\", function(d) { return fill(d.index); })\n";
    s << ".attr(\"d\", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius))\n";
    s << ".on(\"mouseover\", fade(.1))\n";
    s << ".on(\"mouseout\", fade(1));\n";

	s << "var ticks = svg.append(\"g\").selectAll(\"g\")\n";
    s << ".data(chord.groups)\n";
	s << ".enter().append(\"g\").selectAll(\"g\")\n";
    s << ".data(groupTicks)\n";
	s << ".enter().append(\"g\")\n";
    s << ".attr(\"transform\", function(d) {\n";
	s << "	return \"rotate(\" + (d.angle * 180 / Math.PI - 90) + \")\"\n";
	s << "	+ \"translate(\" + outerRadius + \",0)\";\n";
    s << "});\n";

	s << "ticks.append(\"line\")\n";
    s << ".attr(\"x1\", 1)\n";
    s << ".attr(\"y1\", 0)\n";
    s << ".attr(\"x2\", 5)\n";
    s << ".attr(\"y2\", 0)\n";
    s << ".style(\"stroke\", \"#000\");\n";

	s << "ticks.append(\"text\")\n";
    s << ".attr(\"x\", 8)\n";
    s << ".attr(\"dy\", \".35em\")\n";
    s << ".attr(\"transform\", function(d) { return d.angle > Math.PI ? \"rotate(180)translate(-16)\" : null; })\n";
    s << ".style(\"text-anchor\", function(d) { return d.angle > Math.PI ? \"end\" : null; })\n";
    s << ".text(function(d) { return d.label; });\n";

	s << "svg.append(\"g\")\n";
    s << ".attr(\"class\", \"chord\")\n";
	s << ".selectAll(\"path\")\n";
    s << ".data(chord.chords)\n";
	s << ".enter().append(\"path\")\n";
    s << ".attr(\"d\", d3.svg.chord().radius(innerRadius))\n";
    s << ".style(\"fill\", function(d) { return fill(d.target.index); })\n";
    s << ".style(\"opacity\", 1);\n";

	s << "// Returns an array of tick angles and labels, given a group.\n";
	s << "function groupTicks(d) {\n";
	s << "	var k = (d.endAngle - d.startAngle) / d.value;\n";
	s << "	return d3.range(0, d.value, 1000).map(function(v, i) {\n";
	s << "		return {\n";
	s << "		angle: v * k + d.startAngle,\n";
	s << "		label: i % 5 ? null : v / 1000 + \"k\"\n";
	s << "		};\n";
	s << "	});\n";
	s << "}\n";

	s << "// Returns an event handler for fading a given chord group.\n";
	s << "function fade(opacity) {\n";
	s << "	return function(g, i) {\n";
	s << "	  svg.selectAll(\".chord path\")\n";
	s << "		.filter(function(d) { return d.source.index != i && d.target.index != i; })\n";
    s << "  .transition()\n";
    s << "    .style(\"opacity\", opacity);\n";
	s << "};\n";
	s << "}\n";

	s << "</script>\n";

	return s;
}

wxString WebViewExampleDlg::get_zoomable_map_tiles()
{
	wxString s;

	s << "<!DOCTYPE html>";
	s << "<meta charset=\"utf-8\">";
	s << "<style>";

	s << "body {";
	s << "margin: 0;";
	s << "}";

	s << ".map {";
	s << "position: relative;";
	s << "overflow: hidden;";
	s << "}";

	s << ".layer {";
	s << "position: absolute;";
	s << "}";

	s << ".tile {";
	s << "	pointer-events: none;";
	s << "position: absolute;";
	s << "width: 256px;";
	s << "height: 256px;";
	s << "}";

	s << ".info {";
	s << "position: absolute;";
	s << "bottom: 10px;";
	s << "left: 10px;";
	s << "}";

	s << "</style>";
	s << "<body>";
	s << "<script src=\"http://d3js.org/d3.v3.min.js\"></script>";
	s << "<script src=\"http://d3js.org/d3.geo.tile.v0.min.js\"></script>";
	s << "<script>";

	s << "var width = Math.max(960, window.innerWidth),";
    s << "height = Math.max(500, window.innerHeight),";
    s << "prefix = prefixMatch([\"webkit\", \"ms\", \"Moz\", \"O\"]);";

	s << "var tile = d3.geo.tile()";
    s << ".size([width, height]);";

	s << "var projection = d3.geo.mercator();";

	s << "var zoom = d3.behavior.zoom()";
    s << ".scale(1 << 12)";
    s << ".scaleExtent([1 << 9, 1 << 23])";
    s << ".translate([width / 2, height / 2])";
    s << ".on(\"zoom\", zoomed);";

	s << "var map = d3.select(\"body\").append(\"div\")";
    s << ".attr(\"class\", \"map\")";
    s << ".style(\"width\", width + \"px\")";
    s << ".style(\"height\", height + \"px\")";
    s << ".call(zoom)";
    s << ".on(\"mousemove\", mousemoved);";

    s << "var layer = map.append(\"div\")";
    s << ".attr(\"class\", \"layer\");";

    s << "var info = map.append(\"div\")";
    s << ".attr(\"class\", \"info\");";

    s << "zoomed();";

    s << "function zoomed() {";
    s << "	var tiles = tile";
	s << "	.scale(zoom.scale())";
	s << "	.translate(zoom.translate())";
	s << "	();";

	s << "	projection";
	s << "	.scale(zoom.scale() / 2 / Math.PI)";
	s << "	.translate(zoom.translate());";

	s << "	var image = layer";
	s << "	.style(prefix + \"transform\", matrix3d(tiles.scale, tiles.translate))";
	s << "	.selectAll(\".tile\")";
	s << "	.data(tiles, function(d) { return d; });";

	s << "	image.exit()";
	s << "	.remove();";

	s << "	image.enter().append(\"img\")";
	s << "	.attr(\"class\", \"tile\")";
	s << "	.attr(\"src\", function(d) { return \"http://\" + [\"a\", \"b\", \"c\", \"d\"][Math.random() * 4 | 0] + \".tiles.mapbox.com/v3/examples.map-i86nkdio/\" + d[2] + \"/\" + d[0] + \"/\" + d[1] + \".png\"; })";
	s << "	.style(\"left\", function(d) { return (d[0] << 8) + \"px\"; })";
	s << "	.style(\"top\", function(d) { return (d[1] << 8) + \"px\"; });";
	s << "}";

	s << "function mousemoved() {";
	s << "	info.text(formatLocation(projection.invert(d3.mouse(this)), zoom.scale()));";
	s << "}";

	s << "function matrix3d(scale, translate) {";
	s << "	var k = scale / 256, r = scale % 1 ? Number : Math.round;";
	s << "	return \"matrix3d(\" + [k, 0, 0, 0, 0, k, 0, 0, 0, 0, k, 0, r(translate[0] * scale), r(translate[1] * scale), 0, 1 ] + \")\";";
	s << "}";

	s << "function prefixMatch(p) {";
	s << "	var i = -1, n = p.length, s = document.body.style;";
	s << "	while (++i < n) if (p[i] + \"Transform\" in s) return \"-\" + p[i].toLowerCase() + \"-\";";
	s << "	return \"\";";
	s << "}";

	s << "function formatLocation(p, k) {";
	s << "	var format = d3.format(\".\" + Math.floor(Math.log(k) / 2 - 2) + \"f\");";
	s << "	return (p[1] < 0 ? format(-p[1]) + \"°S\" : format(p[1]) + \"°N\") + \" \"";
    s << "   + (p[0] < 0 ? format(-p[0]) + \"°W\" : format(p[0]) + \"°E\");";
	s << "}";

    s << "</script>";

	return s;
}

wxString WebViewExampleDlg::get_json_spirit_ex1()
{
	LOG_MSG("Entering WebViewExampleDlg::get_json_spirit_ex1");
	json_spirit::Value jv1;
	json_spirit::Object addr_obj;
	addr_obj.push_back( json_spirit::Pair( "house_number", 42 ) );
	addr_obj.push_back( json_spirit::Pair( "road", "East Street" ) );
	addr_obj.push_back( json_spirit::Pair( "town", "Newtown" ) );
	std::string s;
	s = json_spirit::write(addr_obj, json_spirit::pretty_print);
	wxString ws(s);
	LOG_MSG(ws);
	LOG_MSG("Exiting WebViewExampleDlg::get_json_spirit_ex1");
	return s;
}

wxString WebViewExampleDlg::get_d3_circles_ex1()
{
	wxString s;
	s << "<!DOCTYPE html>";
	s << "<html lang=\"en\">";
	s << "<head>";
    s << "<meta charset=\"utf-8\" />";
    s << "<title>D3 Test</title>";
	s << "<script src=\"http://d3js.org/d3.v3.min.js\"></script>";
    //s << "<script type=\"text/javascript\" src=\"http://d3js.org/d3.v3.min.js\"></script>";
    s << "<style type=\"text/css\">";
    s << "</style>";
    s << "<script type=\"text/javascript\">";
	s << "function setDataset()";
	s << "{";
	s << "	window.dataset = [];";
	s << "	var i;";
	s << "	for (i = 0; i < arguments.length; i++) {";
	s << "		window.dataset[i] = arguments[i];";
	s << "	}";
	s << "}";
    s << "</script>";
	s << "</head>";
	s << "<body>";
    s << "<script type=\"text/javascript\">";
	s << "var w = 500; // width";
	s << "var h = 50; // height";
	s << "setDataset(5, 10, 15, 20, 25);";
	s << "var svg = d3.select(\"body\").append(\"svg\");";
	s << "svg.selectAll(\"circle\")";
	s << ".data(dataset)";
	s << ".enter()";
	s << ".append(\"circle\")";
	s << ".attr(\"cx\", function(d, i) { return (i*50)+25; })";
	s << ".attr(\"cy\", h/2)";
	s << ".attr(\"r\", function(d) { return d; })";
	s << ".attr(\"fill\", \"orange\");";
    s << "</script>";
	s << "</body>";
	s << "</html>";
	return s;
}

wxString WebViewExampleDlg::get_hello_world()
{
	wxString s;
	s << "<!DOCTYPE html>\n";
	s << "<html lang=\"en\">\n";
	s << "<head>\n";
	s <<   "<meta charset=\"utf-8\">\n";
	s <<   "<style>\n";
	s <<     "body {\n";
	s <<       "font: 12px sans-serif;\n";
	s <<     "}\n";
	s <<   "</style>\n";
	s << "</head>\n";
	s << "<body>\n";
	s <<   "<p>Hello World.</p>\n";
	s << "</body>\n";
	s << "</html>\n";

	return s;
};

wxString WebViewExampleDlg::get_bars_example()
{
	wxString s;
	s << "<!DOCTYPE html>\n";
	s << "<html lang=\"en\">\n";
	s << "<head>\n";
    s << "<meta charset=\"utf-8\">\n";
    s << "<title>D3 Demo: Making a bar chart with SVG</title>\n";
    s << "<script type=\"text/javascript\" src=\"http://d3js.org/d3.v3.min.js\"></script>\n";
    s << "<style type=\"text/css\">\n";
    s << "</style>\n";
	s << "</head>\n";
	s << "<body>\n";
    s << "<script type=\"text/javascript\">\n";
	s << "var w = 500;\n";
	s << "var h = 100;\n";
	s << "var barPadding = 1;\n";
	s << "var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,\n";
	s << "			   11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];\n";
	s << "//Create SVG element\n";
	s << "var svg = d3.select(\"body\")\n";
	s << ".append(\"svg\")\n";
	s << ".attr(\"width\", w)\n";
	s << ".attr(\"height\", h);\n";
	s << "svg.selectAll(\"rect\")\n";
	s << ".data(dataset)\n";
	s << ".enter()\n";
	s << ".append(\"rect\")\n";
	s << ".attr(\"x\", function(d, i) {\n";
	s << "	return i * (w / dataset.length);\n";
	s << "})\n";
	s << ".attr(\"y\", function(d) {\n";
	s << "	return h - (d * 4);\n";
	s << "})\n";
	s << ".attr(\"width\", w / dataset.length - barPadding)\n";
	s << ".attr(\"height\", function(d) {\n";
	s << "	return d * 4;\n";
	s << "})\n";
	s << ".attr(\"fill\", function(d) {\n";
	s << "	return \"rgb(0, 0, \" + (d * 10) + \")\";\n";
	s << "});\n";
    s << "</script>\n";
	s << "</body>\n";
	s << "</html>\n";
	return s;
}

max_stars_repo_name: chenyoujie/GeoDa

max_issues_repo_name: chenyoujie/GeoDa

max_forks_repo_name: chenyoujie/GeoDa


text:
#ifndef LOCIC_CODEGEN_MODULE_HPP
#define LOCIC_CODEGEN_MODULE_HPP

#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

#include <boost/functional/hash.hpp>

#include <llvm-abi/ABI.hpp>

#include <locic/CodeGen/ASTFunctionGenerator.hpp>
#include <locic/CodeGen/BuildOptions.hpp>
#include <locic/CodeGen/Debug.hpp>
#include <locic/CodeGen/PrimitiveMap.hpp>
#include <locic/CodeGen/Primitives.hpp>
#include <locic/CodeGen/TemplateBuilder.hpp>
#include <locic/CodeGen/VirtualCallABI.hpp>

#include <locic/Support/FastMap.hpp>
#include <locic/Support/Map.hpp>
#include <locic/Support/String.hpp>

namespace locic {

	class PrimitiveID;

	namespace AST {

		class Function;
		class Type;
		class TypeInstance;

	}

	namespace Debug {

		class Module;

	}

	namespace CodeGen {

		enum CompareResult {
			COMPARE_EQUAL,
			COMPARE_LESS,
			COMPARE_MORE
		};

		enum AttributeKind {
			AttributeVirtualCallStub
		};

		enum StandardTypeKind {
			TemplateGeneratorType,
			TypeInfoType
		};

		template <typename Key, typename Value>
		struct hashPair {
			std::size_t operator()(const std::pair<Key, Value>& pair) const {
				std::size_t seed = 0;
				std::hash<Key> keyHashFn;
				boost::hash_combine(seed, keyHashFn(pair.first));
				std::hash<Value> valueHashFn;
				boost::hash_combine(seed, valueHashFn(pair.second));
				return seed;
			}
		};

		typedef FastMap<AttributeKind, llvm::AttributeList> AttributeMap;
		typedef std::unordered_map<TemplateBuilder*, llvm::GlobalAlias*> BitsRequiredGlobalMap;
		typedef std::unordered_map<const AST::TypeInstance*, llvm::Function*> DestructorMap;
		typedef FastMap<String, llvm::Function*> FunctionMap;
		typedef FastMap<std::pair<llvm::Function*, llvm::FunctionType*>, llvm::Function*> FunctionPtrStubMap;
		typedef std::unordered_map<const AST::Function*, llvm::Function*> FunctionDeclMap;
		typedef std::unordered_map<std::pair<String, Name>, String, hashPair<String, Name>> MangledNameMap;
		typedef std::unordered_map<const AST::TypeInstance*, llvm::Function*> MemberOffsetFunctionMap;
		typedef std::unordered_map<const AST::TypeInstance*, llvm::Function*> MoveFunctionMap;
		typedef FastMap<StandardTypeKind, llvm_abi::Type> StandardTypeMap;
		typedef FastMap<TemplatedObject, TemplateBuilder> TemplateBuilderMap;
		typedef FastMap<TemplateInst, llvm::Function*> TemplateRootFunctionMap;
		typedef FastMap<String, llvm_abi::Type> TypeMap;
		typedef std::unordered_map<const AST::TypeInstance*, llvm::StructType*> TypeInstanceMap;

		class InternalContext;
		class Primitive;

		class Module {
		public:
			Module(InternalContext& context, const std::string& name, Debug::Module& pDebugModule, const BuildOptions& pBuildOptions);

			InternalContext& context();

			String getCString(const char* cString) const;

			String getString(std::string stringValue) const;

			void dump() const;

			void dumpToFile(const std::string& fileName) const;

			void writeBitCodeToFile(const std::string& fileName) const;

			llvm_abi::ABI& abi();

			const llvm_abi::ABI& abi() const;

			const llvm_abi::TypeBuilder& abiTypeBuilder() const;

			llvm::Type* getLLVMType(llvm_abi::Type type) const;

			VirtualCallABI& virtualCallABI();

			llvm::LLVMContext& getLLVMContext() const;

			std::unique_ptr<llvm::Module> releaseLLVMModule();

			llvm::Module& getLLVMModule() const;

			llvm::Module* getLLVMModulePtr() const;

			AttributeMap& attributeMap();

			BitsRequiredGlobalMap& bitsRequiredGlobalMap();

			DestructorMap& getDestructorMap();

			FunctionMap& getFunctionMap();

			FunctionDeclMap& getFunctionDeclMap();

			FunctionPtrStubMap& functionPtrStubMap();

			MangledNameMap& mangledNameMap();

			MemberOffsetFunctionMap& memberOffsetFunctionMap();

			MoveFunctionMap& getMoveFunctionMap();

			const Primitive& getPrimitive(const AST::TypeInstance& typeInstance) const;

			StandardTypeMap& standardTypeMap();

			TemplateBuilder& templateBuilder(TemplatedObject templatedObject);

			TemplateRootFunctionMap& templateRootFunctionMap();

			TypeMap& getTypeMap();

			const TypeMap& getTypeMap() const;

			TypeInstanceMap& typeInstanceMap();

			llvm::GlobalVariable* createConstGlobal(const String& name,
				llvm::Type* type, llvm::GlobalValue::LinkageTypes linkage,
				llvm::Constant* value = nullptr);

			DebugBuilder& debugBuilder();

			Debug::Module& debugModule();

			const BuildOptions& buildOptions() const;

			PrimitiveID primitiveID(const String& name) const;

			ASTFunctionGenerator& astFunctionGenerator();

			void verify() const;

		private:
			InternalContext& context_;
			std::unique_ptr<llvm::Module> module_;
			std::unique_ptr<llvm_abi::ABI> abi_;
			std::unique_ptr<VirtualCallABI> virtualCallABI_;
			AttributeMap attributeMap_;
			BitsRequiredGlobalMap bitsRequiredGlobalMap_;
			DestructorMap destructorMap_;
			FunctionMap functionMap_;
			FunctionDeclMap functionDeclMap_;
			FunctionPtrStubMap functionPtrStubMap_;
			MangledNameMap mangledNameMap_;
			MemberOffsetFunctionMap memberOffsetFunctionMap_;
			MoveFunctionMap moveFunctionMap_;
			PrimitiveMap primitiveMap_;
			StandardTypeMap standardTypeMap_;
			TemplateBuilderMap templateBuilderMap_;
			TemplateRootFunctionMap templateRootFunctionMap_;
			TypeMap typeMap_;
			TypeInstanceMap typeInstanceMap_;
			DebugBuilder debugBuilder_;
			Debug::Module& debugModule_;
			BuildOptions buildOptions_;
			ASTFunctionGenerator astFunctionGenerator_;

		};

	}

}

#endif