<commit_before>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "QueueWorkingModuleTest.h"

//--- module under test --------------------------------------------------------
#include "QueueWorkingModule.h"

//--- test modules used --------------------------------------------------------
#include "TestSuite.h"

//--- project modules used ----------------------------------------------------
#include "Queue.h"

//--- standard modules used ----------------------------------------------------
#include "System.h"
#include "Dbg.h"

//--- c-modules used -----------------------------------------------------------

//---- QueueWorkingModuleTest ----------------------------------------------------------------
QueueWorkingModuleTest::QueueWorkingModuleTest(TString tstrName)
	: TestCaseType(tstrName)
{
	StartTrace(QueueWorkingModuleTest.QueueWorkingModuleTest);
}

TString QueueWorkingModuleTest::getConfigFileName()
{
	return "QueueWorkingModuleTestConfig";
}

QueueWorkingModuleTest::~QueueWorkingModuleTest()
{
	StartTrace(QueueWorkingModuleTest.Dtor);
}

void QueueWorkingModuleTest::InitFinisNoModuleConfigTest()
{
	StartTrace(QueueWorkingModuleTest.InitFinisNoModuleConfigTest);
	QueueWorkingModule aModule("QueueWorkingModule");
	t_assertm( !aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have failed due to missing configuration" );
}

void QueueWorkingModuleTest::InitFinisDefaultsTest()
{
	StartTrace(QueueWorkingModuleTest.InitFinisDefaultsTest);
	QueueWorkingModule aModule("QueueWorkingModule");
	if ( t_assertm( aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have succeeded" ) ) {
		if ( t_assert( aModule.fpContext != NULL ) ) {
			assertAnyEqual(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"], aModule.fpContext->GetEnvStore());
		}
		if ( t_assert( aModule.fpQueue != NULL ) ) {
			assertEqualm(0L, aModule.fpQueue->GetSize(), "expected queue to be empty");
			Anything anyStatistics;
			aModule.fpQueue->GetStatistics(anyStatistics);
			assertEqualm(100L, anyStatistics["QueueSize"].AsLong(-1L), "expected default queue size to be 100");
		}
		// terminate module and perform some checks
		t_assert( aModule.Finis() );
		t_assert( aModule.fpContext == NULL );
		t_assert( aModule.fpQueue == NULL );
	}
}

void QueueWorkingModuleTest::InitFinisTest()
{
	StartTrace(QueueWorkingModuleTest.InitFinisTest);
	QueueWorkingModule aModule("QueueWorkingModule");
	if ( t_assertm( aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have succeeded" ) ) {
		if ( t_assert( aModule.fpContext != NULL ) ) {
			// check for invalid Server
			t_assertm( NULL == aModule.fpContext->GetServer(), "server must be NULL because of non-existing server");
			assertAnyEqual(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"], aModule.fpContext->GetEnvStore());
		}
		if ( t_assert( aModule.fpQueue != NULL ) ) {
			assertEqualm(0L, aModule.fpQueue->GetSize(), "expected queue to be empty");
			Anything anyStatistics;
			aModule.fpQueue->GetStatistics(anyStatistics);
			assertEqualm(25L, anyStatistics["QueueSize"].AsLong(-1L), "expected queue size to be 25 as configured");
		}

		// terminate module and perform some checks
		t_assert( aModule.Finis() );
		t_assert( aModule.fpContext == NULL );
		t_assert( aModule.fpQueue == NULL );
	}
}

void QueueWorkingModuleTest::GetAndPutbackTest()
{
	StartTrace(QueueWorkingModuleTest.GetAndPutbackTest);
	QueueWorkingModule aModule("QueueWorkingModule");
	// set modules fAlive-field to enable working of the functions
	// first check if they don't work
	{
		Anything anyMsg;
		// must fail
		t_assert( !aModule.PutElement(anyMsg, false) );
		// fails because of uninitialized queue
		t_assert( !aModule.GetElement(anyMsg, false) );
	}
	aModule.IntInitQueue(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"]);
	{
		Anything anyMsg;
		// must still fail because of dead-state
		t_assert( !aModule.GetElement(anyMsg, false) );
	}
	aModule.fAlive = 0xf007f007;
	if ( t_assertm( aModule.fpQueue != NULL , "queue should be created" ) ) {
		// queue is empty, so retrieving an element with tryLock=true should
		// return immediately and fail.
		{
			Anything anyElement;
			t_assert( !(aModule.GetElement(anyElement, true)) );
		}
		// queue size is 1, so we load it with 1 element
		{
			Anything anyMsg;
			anyMsg["Number"] = 1;
			// this one must succeed
			t_assert( aModule.PutElement(anyMsg, false) );
		}
		// now putback one message
		{
			Anything anyMsg;
			anyMsg["Number"] = 2;
			// this one must fail
			if ( t_assert( !aModule.PutElement(anyMsg, true) ) ) {
				aModule.PutBackElement(anyMsg);
				assertEqualm(1, aModule.fFailedPutbackMessages.GetSize(), "expected overflow buffer to contain an element");
			}
		}
		Anything anyElement;
		if ( t_assert( aModule.GetElement(anyElement) ) ) {
			assertEqualm( 2, anyElement["Number"].AsLong(-1L), "expected to get putback element first");
		}
		assertEqualm( 0, aModule.fFailedPutbackMessages.GetSize(), "expected overflow buffer to be empty now");
		if ( t_assert( aModule.GetElement(anyElement) ) ) {
			assertEqualm( 1, anyElement["Number"].AsLong(-1L), "expected to get regular queue element last");
		}
		assertEqualm( 0, aModule.fpQueue->GetSize(), "expected queue to be empty now");
		aModule.IntCleanupQueue();
	}
}

// builds up a suite of tests, add a line for each testmethod
Test *QueueWorkingModuleTest::suite ()
{
	StartTrace(QueueWorkingModuleTest.suite);
	TestSuite *testSuite = new TestSuite;

	ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisNoModuleConfigTest);
	ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisDefaultsTest);
	ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisTest);
	ADD_CASE(testSuite, QueueWorkingModuleTest, GetAndPutbackTest);

	return testSuite;
}
<commit_msg>adjusted StatusCode checking of method calls<commit_after>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "QueueWorkingModuleTest.h"

//--- module under test --------------------------------------------------------
#include "QueueWorkingModule.h"

//--- test modules used --------------------------------------------------------
#include "TestSuite.h"

//--- project modules used ----------------------------------------------------
#include "Queue.h"

//--- standard modules used ----------------------------------------------------
#include "System.h"
#include "Dbg.h"

//--- c-modules used -----------------------------------------------------------

//---- QueueWorkingModuleTest ----------------------------------------------------------------
QueueWorkingModuleTest::QueueWorkingModuleTest(TString tstrName)
	: TestCaseType(tstrName)
{
	StartTrace(QueueWorkingModuleTest.QueueWorkingModuleTest);
}

TString QueueWorkingModuleTest::getConfigFileName()
{
	return "QueueWorkingModuleTestConfig";
}

QueueWorkingModuleTest::~QueueWorkingModuleTest()
{
	StartTrace(QueueWorkingModuleTest.Dtor);
}

void QueueWorkingModuleTest::InitFinisNoModuleConfigTest()
{
	StartTrace(QueueWorkingModuleTest.InitFinisNoModuleConfigTest);
	QueueWorkingModule aModule("QueueWorkingModule");
	t_assertm( !aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have failed due to missing configuration" );
}

void QueueWorkingModuleTest::InitFinisDefaultsTest()
{
	StartTrace(QueueWorkingModuleTest.InitFinisDefaultsTest);
	QueueWorkingModule aModule("QueueWorkingModule");
	if ( t_assertm( aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have succeeded" ) ) {
		if ( t_assert( aModule.fpContext != NULL ) ) {
			assertAnyEqual(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"], aModule.fpContext->GetEnvStore());
		}
		if ( t_assert( aModule.fpQueue != NULL ) ) {
			assertEqualm(0L, aModule.fpQueue->GetSize(), "expected queue to be empty");
			Anything anyStatistics;
			aModule.fpQueue->GetStatistics(anyStatistics);
			assertEqualm(100L, anyStatistics["QueueSize"].AsLong(-1L), "expected default queue size to be 100");
		}
		// terminate module and perform some checks
		t_assert( aModule.Finis() );
		t_assert( aModule.fpContext == NULL );
		t_assert( aModule.fpQueue == NULL );
	}
}

void QueueWorkingModuleTest::InitFinisTest()
{
	StartTrace(QueueWorkingModuleTest.InitFinisTest);
	QueueWorkingModule aModule("QueueWorkingModule");
	if ( t_assertm( aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have succeeded" ) ) {
		if ( t_assert( aModule.fpContext != NULL ) ) {
			// check for invalid Server
			t_assertm( NULL == aModule.fpContext->GetServer(), "server must be NULL because of non-existing server");
			assertAnyEqual(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"], aModule.fpContext->GetEnvStore());
		}
		if ( t_assert( aModule.fpQueue != NULL ) ) {
			assertEqualm(0L, aModule.fpQueue->GetSize(), "expected queue to be empty");
			Anything anyStatistics;
			aModule.fpQueue->GetStatistics(anyStatistics);
			assertEqualm(25L, anyStatistics["QueueSize"].AsLong(-1L), "expected queue size to be 25 as configured");
		}

		// terminate module and perform some checks
		t_assert( aModule.Finis() );
		t_assert( aModule.fpContext == NULL );
		t_assert( aModule.fpQueue == NULL );
	}
}

void QueueWorkingModuleTest::GetAndPutbackTest()
{
	StartTrace(QueueWorkingModuleTest.GetAndPutbackTest);
	QueueWorkingModule aModule("QueueWorkingModule");
	// set modules fAlive-field to enable working of the functions
	// first check if they don't work
	{
		Anything anyMsg;
		// must fail
		assertEqual( Queue::eDead, aModule.PutElement(anyMsg, false) );
		// fails because of uninitialized queue
		assertEqual( Queue::eDead, aModule.GetElement(anyMsg, false) );
	}
	aModule.IntInitQueue(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"]);
	{
		Anything anyMsg;
		// must still fail because of dead-state
		assertEqual( Queue::eDead, aModule.GetElement(anyMsg, false) );
	}
	aModule.fAlive = 0xf007f007;
	if ( t_assertm( aModule.fpQueue != NULL , "queue should be created" ) ) {
		// queue is empty, so retrieving an element with tryLock=true should
		// return immediately and fail.
		{
			Anything anyElement;
			assertEqual( Queue::eEmpty, aModule.GetElement(anyElement, true) );
		}
		// queue size is 1, so we load it with 1 element
		{
			Anything anyMsg;
			anyMsg["Number"] = 1;
			// this one must succeed
			assertEqual( Queue::eSuccess, aModule.PutElement(anyMsg, false) );
		}
		// now putback one message
		{
			Anything anyMsg;
			anyMsg["Number"] = 2;
			// this one must fail
			if ( assertEqual( Queue::eFull, aModule.PutElement(anyMsg, true) ) ) {
				aModule.PutBackElement(anyMsg);
				assertEqualm(1, aModule.fFailedPutbackMessages.GetSize(), "expected overflow buffer to contain an element");
			}
		}
		Anything anyElement;
		if ( assertEqual( Queue::eSuccess, aModule.GetElement(anyElement) ) ) {
			assertEqualm( 2, anyElement["Number"].AsLong(-1L), "expected to get putback element first");
		}
		assertEqualm( 0, aModule.fFailedPutbackMessages.GetSize(), "expected overflow buffer to be empty now");
		if ( assertEqual( Queue::eSuccess, aModule.GetElement(anyElement) ) ) {
			assertEqualm( 1, anyElement["Number"].AsLong(-1L), "expected to get regular queue element last");
		}
		assertEqualm( 0, aModule.fpQueue->GetSize(), "expected queue to be empty now");
		aModule.IntCleanupQueue();
	}
}

// builds up a suite of tests, add a line for each testmethod
Test *QueueWorkingModuleTest::suite ()
{
	StartTrace(QueueWorkingModuleTest.suite);
	TestSuite *testSuite = new TestSuite;

	ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisNoModuleConfigTest);
	ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisDefaultsTest);
	ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisTest);
	ADD_CASE(testSuite, QueueWorkingModuleTest, GetAndPutbackTest);

	return testSuite;
}
<|endoftext|>


<commit_before>#include <fcntl.h>

constexpr size_t ev_buffsz = 512;

#ifdef __linux__
#include "epoll.hpp"
typedef nntpchan::ev::EpollLoop<ev_buffsz> LoopImpl;
#else
#ifdef __freebsd__
#include "kqueue.hpp"
typedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl;
#else
#ifdef __netbsd__
typedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl;
#else
#error "unsupported platform"
#endif
#endif
#endif

namespace nntpchan
{
namespace ev
{
bool ev::Loop::BindTCP(const sockaddr *addr, ev::io *handler)
{
  assert(handler->acceptable());
  socklen_t slen;
  switch (addr->sa_family)
  {
  case AF_INET:
    slen = sizeof(sockaddr_in);
    break;
  case AF_INET6:
    slen = sizeof(sockaddr_in6);
    break;
  case AF_UNIX:
    slen = sizeof(sockaddr_un);
    break;
  default:
    return false;
  }
  int fd = socket(addr->sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0);
  if (fd == -1)
  {
    return false;
  }

  if (bind(fd, addr, slen) == -1)
  {
    ::close(fd);
    return false;
  }

  if (listen(fd, 5) == -1)
  {
    ::close(fd);
    return false;
  }

  handler->fd = fd;
  return TrackConn(handler);
}

bool Loop::SetNonBlocking(ev::io *handler)
{
  return fcntl(handler->fd, F_SETFL, fcntl(handler->fd, F_GETFL, 0) | O_NONBLOCK) != -1;
}
}

ev::Loop *NewMainLoop() { return new LoopImpl; }
}<commit_msg>correct define<commit_after>#include <fcntl.h>

constexpr size_t ev_buffsz = 512;

#ifdef __linux__
#include "epoll.hpp"
typedef nntpchan::ev::EpollLoop<ev_buffsz> LoopImpl;
#else
#ifdef __FreeBSD__
#include "kqueue.hpp"
typedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl;
#else
#ifdef __netbsd__
typedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl;
#else
#error "unsupported platform"
#endif
#endif
#endif

namespace nntpchan
{
namespace ev
{
bool ev::Loop::BindTCP(const sockaddr *addr, ev::io *handler)
{
  assert(handler->acceptable());
  socklen_t slen;
  switch (addr->sa_family)
  {
  case AF_INET:
    slen = sizeof(sockaddr_in);
    break;
  case AF_INET6:
    slen = sizeof(sockaddr_in6);
    break;
  case AF_UNIX:
    slen = sizeof(sockaddr_un);
    break;
  default:
    return false;
  }
  int fd = socket(addr->sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0);
  if (fd == -1)
  {
    return false;
  }

  if (bind(fd, addr, slen) == -1)
  {
    ::close(fd);
    return false;
  }

  if (listen(fd, 5) == -1)
  {
    ::close(fd);
    return false;
  }

  handler->fd = fd;
  return TrackConn(handler);
}

bool Loop::SetNonBlocking(ev::io *handler)
{
  return fcntl(handler->fd, F_SETFL, fcntl(handler->fd, F_GETFL, 0) | O_NONBLOCK) != -1;
}
}

ev::Loop *NewMainLoop() { return new LoopImpl; }
}<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "../../main/models/baseline/TransitionProbabilityModel.h"
#include "../../main/models/baseline/TransitionProbabilityModelUpdater.h"
#include "../../main/loggers/TransitionModelEndLogger.h"

namespace{

class TestTransitionProbabilityModel : public ::testing::Test {
  public:
    TestTransitionProbabilityModel(){}
    virtual ~TestTransitionProbabilityModel(){}
    virtual void SetUp(){
    }
    virtual void TearDown(){
    }
    RecDat create_recdat(int time,int user,int item,int score){
      RecDat rec_dat;
      rec_dat.time = time;
      rec_dat.user = user;
      rec_dat.item = item;
      rec_dat.score = score;
      return rec_dat;
    }
};
class TestTransitionEndLogger : public ::testing::Test {
  public:
    TestTransitionEndLogger(){}
    virtual ~TestTransitionEndLogger(){}
    virtual void SetUp(){
    }
    virtual void TearDown(){
      for(int i=0;i<rec_dat_container_.size();i++){
        delete rec_dat_container_[i];
      }
    }
    vector<RecDat*> rec_dat_container_;
    RecDat* create_recdat(int time,int user,int item,int score){
      RecDat* rec_dat = new RecDat;
      rec_dat->time = time;
      rec_dat->user = user;
      rec_dat->item = item;
      rec_dat->score = score;
      rec_dat_container_.push_back(rec_dat);
      return rec_dat;
    }
};

}

TEST_F(TestTransitionProbabilityModel, test){
  //data
  vector<RecDat> timeline;
  timeline.push_back(create_recdat(0,10,20,1));
  timeline.push_back(create_recdat(1,10,10,1));
  timeline.push_back(create_recdat(2,10,20,1));
  timeline.push_back(create_recdat(3,10,10,1));
  timeline.push_back(create_recdat(4,10,20,1));
  timeline.push_back(create_recdat(5,10,30,1));
  timeline.push_back(create_recdat(5,20,20,1)); //another user
  timeline.push_back(create_recdat(6,10,20,1));
  timeline.push_back(create_recdat(7,10,30,1));
  timeline.push_back(create_recdat(8,10,20,1));
  timeline.push_back(create_recdat(9,10,30,1));
  timeline.push_back(create_recdat(10,10,20,1));
  //statistics: a 20-as itemet 3-szor a 30-as, 2-szer a 10-es kovette
  //statistics: a 10-es itemet 2-szor a 20-as, 0-szor a 30-es kovette
  //statistics: a 30-as itemet 3-szor a 20-as, 0-szor a 10-es kovette

  TransitionProbabilityModel model;
  TransitionProbabilityModelUpdaterParameters params;
  TransitionProbabilityModelUpdater updater(&params);
  updater.set_model(&model);
  EXPECT_TRUE(model.self_test());
  EXPECT_TRUE(updater.self_test());
  RecDat rec_dat;
  rec_dat = create_recdat(30,10,30,1);
  EXPECT_EQ(0, model.prediction(&rec_dat));
  rec_dat = create_recdat(30,20,30,1);
  EXPECT_EQ(0, model.prediction(&rec_dat));
  for(RecDat rec_dat : timeline){
    updater.update(&rec_dat);
  }
  rec_dat = create_recdat(30,10,30,1);
  EXPECT_EQ(log(3+1), model.prediction(&rec_dat));
  rec_dat = create_recdat(30,20,30,1);
  EXPECT_EQ(log(3+1), model.prediction(&rec_dat));
  rec_dat = create_recdat(30,10,10,1);
  EXPECT_EQ(log(2+1), model.prediction(&rec_dat));
  rec_dat = create_recdat(30,20,10,1);
  EXPECT_EQ(log(2+1), model.prediction(&rec_dat));
}

TEST_F(TestTransitionEndLogger, test){
  vector<RecDat> timeline;
  TransitionProbabilityModel model;
  TransitionProbabilityModelUpdaterParameters params;
  params.filter_freq_updates = false; //default: do not do any filtering
  TransitionProbabilityModelUpdater updater(&params);
  updater.set_model(&model);
  EXPECT_TRUE(model.self_test());
  EXPECT_TRUE(updater.self_test());
  TransitionModelEndLoggerParameters logger_params;
  logger_params.max_length=5;
  TransitionModelEndLogger logger(&logger_params);
  logger.set_model(&model);
  PopContainer pop_container;
  logger.set_pop_container(&pop_container);
  EXPECT_TRUE(logger.self_test());
  pop_container.increase(2);
  pop_container.increase(2);
  pop_container.increase(2);
  pop_container.increase(2); //4x
  pop_container.increase(3);
  pop_container.increase(3); //2x
  pop_container.increase(5);
  pop_container.increase(5);
  pop_container.increase(5);
  pop_container.increase(5);
  pop_container.increase(5);
  pop_container.increase(5); //6x
  RecDat* rec_dat;
  rec_dat = create_recdat(1,1,1,1);
  updater.update(rec_dat);
  for(int i=0;i<10;i++){
    rec_dat = create_recdat(1,1,2,1);
    updater.update(rec_dat);
    rec_dat = create_recdat(1,1,3,1);
    updater.update(rec_dat);
  }
  rec_dat = create_recdat(1,1,1,1);
  updater.update(rec_dat);
  for(int i=0;i<10;i++){
    rec_dat = create_recdat(1,1,4,1);
    updater.update(rec_dat);
    rec_dat = create_recdat(1,1,5,1);
    updater.update(rec_dat);
    rec_dat = create_recdat(1,1,6,1);
    updater.update(rec_dat);
  }
  rec_dat = create_recdat(1,1,1,1);
  updater.update(rec_dat);
  for(int i=0;i<10;i++){
    RecDat* rec_dat_1 = create_recdat(1,1,7,1);
    RecDat* rec_dat_2 = create_recdat(1,1,i,1);
    for(int j=0;j<i;j++){
      updater.update(rec_dat_1);
      updater.update(rec_dat_2);
    }
  }
  std::stringstream ss;
  logger.run_core(ss);
  vector<string> expected_lines;
  expected_lines.push_back("0 0 0");
  expected_lines.push_back("1 3 0 7,2 2,1 4,1");
  expected_lines.push_back("2 2 4 3,10 7,2");
  expected_lines.push_back("3 3 2 2,9 7,3 1,1");
  expected_lines.push_back("4 2 0 5,10 7,4");
  expected_lines.push_back("5 2 6 6,10 7,5");
  expected_lines.push_back("6 3 0 4,9 7,6 1,1");
  expected_lines.push_back("7 9 0 7,14 9,9 8,8 6,6 5,5");// 4,4 3,3 2,2 1,1");
  expected_lines.push_back("8 1 0 7,8");
  expected_lines.push_back("9 1 0 7,8");
  for(int i=0;i<expected_lines.size();i++){
    string actual_line;
    std::getline(ss,actual_line);
    EXPECT_EQ(expected_lines[i],actual_line);
  }
  //cerr << ss.str() << endl;
}

int main (int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>expanded test of TransitionModel<commit_after>#include <gtest/gtest.h>
#include "../../main/models/baseline/TransitionProbabilityModel.h"
#include "../../main/models/baseline/TransitionProbabilityModelUpdater.h"
#include "../../main/loggers/TransitionModelEndLogger.h"

namespace{

class TestTransitionProbabilityModel : public ::testing::Test {
  public:
    TestTransitionProbabilityModel(){}
    virtual ~TestTransitionProbabilityModel(){}
    virtual void SetUp(){
    }
    virtual void TearDown(){
    }
    RecDat create_recdat(int time,int user,int item,int score){
      RecDat rec_dat;
      rec_dat.time = time;
      rec_dat.user = user;
      rec_dat.item = item;
      rec_dat.score = score;
      return rec_dat;
    }
};
class TestTransitionEndLogger : public ::testing::Test {
  public:
    TestTransitionEndLogger(){}
    virtual ~TestTransitionEndLogger(){}
    virtual void SetUp(){
    }
    virtual void TearDown(){
      for(int i=0;i<rec_dat_container_.size();i++){
        delete rec_dat_container_[i];
      }
    }
    vector<RecDat*> rec_dat_container_;
    RecDat* create_recdat(int time,int user,int item,int score){
      RecDat* rec_dat = new RecDat;
      rec_dat->time = time;
      rec_dat->user = user;
      rec_dat->item = item;
      rec_dat->score = score;
      rec_dat_container_.push_back(rec_dat);
      return rec_dat;
    }
};

}

TEST_F(TestTransitionProbabilityModel, test_prediction){
  //data
  vector<RecDat> timeline;
  timeline.push_back(create_recdat(0,10,20,1));
  timeline.push_back(create_recdat(1,10,10,1));
  timeline.push_back(create_recdat(2,10,20,1));
  timeline.push_back(create_recdat(3,10,10,1));
  timeline.push_back(create_recdat(4,10,20,1));
  timeline.push_back(create_recdat(5,10,30,1));
  timeline.push_back(create_recdat(5,20,20,1)); //another user
  timeline.push_back(create_recdat(6,10,20,1));
  timeline.push_back(create_recdat(7,10,30,1));
  timeline.push_back(create_recdat(8,10,20,1));
  timeline.push_back(create_recdat(9,10,30,1));
  timeline.push_back(create_recdat(10,10,20,1));
  timeline.push_back(create_recdat(11,30,10,1)); //another user
  //statistics: a 20-as itemet 3-szor a 30-as, 2-szer a 10-es kovette
  //statistics: a 10-es itemet 2-szor a 20-as, 0-szor a 30-as kovette
  //statistics: a 30-as itemet 3-szor a 20-as, 0-szor a 10-es kovette

  TransitionProbabilityModel model;
  TransitionProbabilityModelUpdaterParameters params;
  TransitionProbabilityModelUpdater updater(&params);
  updater.set_model(&model);
  EXPECT_TRUE(model.self_test());
  EXPECT_TRUE(updater.self_test());
  RecDat rec_dat;
  rec_dat = create_recdat(30,10,30,1);
  EXPECT_EQ(0, model.prediction(&rec_dat));
  rec_dat = create_recdat(30,20,30,1);
  EXPECT_EQ(0, model.prediction(&rec_dat));
  for(RecDat rec_dat : timeline){
    updater.update(&rec_dat);
  }
  rec_dat = create_recdat(30,10,10,1);
  EXPECT_EQ(log(2+1), model.prediction(&rec_dat));
  rec_dat = create_recdat(30,10,30,1);
  EXPECT_EQ(log(3+1), model.prediction(&rec_dat));
  rec_dat = create_recdat(30,20,10,1);
  EXPECT_EQ(log(2+1), model.prediction(&rec_dat));
  rec_dat = create_recdat(30,20,30,1);
  EXPECT_EQ(log(3+1), model.prediction(&rec_dat));
  rec_dat = create_recdat(30,30,20,1);
  EXPECT_EQ(log(2+1), model.prediction(&rec_dat));
  rec_dat = create_recdat(30,30,30,1);
  EXPECT_EQ(0, model.prediction(&rec_dat));
}

TEST_F(TestTransitionProbabilityModel, test_rsi){
  //data
  vector<RecDat> timeline;
  timeline.push_back(create_recdat(0,10,20,1));
  timeline.push_back(create_recdat(1,10,10,1));
  timeline.push_back(create_recdat(2,10,20,1));
  timeline.push_back(create_recdat(3,10,10,1));
  timeline.push_back(create_recdat(4,10,20,1));
  timeline.push_back(create_recdat(5,10,30,1));
  timeline.push_back(create_recdat(5,20,20,1)); //another user
  timeline.push_back(create_recdat(6,10,20,1));
  timeline.push_back(create_recdat(7,10,30,1));
  timeline.push_back(create_recdat(8,10,20,1));
  timeline.push_back(create_recdat(9,10,30,1));
  timeline.push_back(create_recdat(10,10,20,1));
  timeline.push_back(create_recdat(11,30,10,1)); //another user
  //statistics: a 20-as itemet 3-szor a 30-as, 2-szer a 10-es kovette
  //statistics: a 10-es itemet 2-szor a 20-as, 0-szor a 30-es kovette
  //statistics: a 30-as itemet 3-szor a 20-as, 0-szor a 10-es kovette

  TransitionProbabilityModel model;
  TransitionProbabilityModelUpdaterParameters params;
  TransitionProbabilityModelUpdater updater(&params);
  updater.set_model(&model);
  EXPECT_TRUE(model.self_test());
  EXPECT_TRUE(updater.self_test());
  for(RecDat rec_dat : timeline){
    updater.update(&rec_dat);
  }
  RankingScoreIterator* rsi;
  double item_score;
  int item_id;
  vector<int> users = {10, 20};
  for(user : users){
    rsi = model.get_ranking_score_iterator(user);
    EXPECT_TRUE(rsi->has_next());
    tie(item_id, item_score) = rsi->get_next();
    EXPECT_EQ(30,item_id);
    EXPECT_DOUBLE_EQ(log(3+1),item_score);
    EXPECT_TRUE(rsi->has_next());
    tie(item_id, item_score) = rsi->get_next();
    EXPECT_EQ(10,item_id);
    EXPECT_DOUBLE_EQ(log(2+1),item_score);
    EXPECT_FALSE(rsi->has_next());
  }

  rsi = model.get_ranking_score_iterator(30); //user 30
  EXPECT_TRUE(rsi->has_next());
  EXPECT_FALSE(rsi->has_next(log(2+1)+0.1));
  EXPECT_TRUE(rsi->has_next(log(2+1)-0.1));
  EXPECT_FALSE(rsi->has_next(log(2+1),true)); //strict
  EXPECT_TRUE(rsi->has_next(log(2+1),false)); //not strict
  tie(item_id, item_score) = rsi->get_next();
  EXPECT_EQ(20,item_id);
  EXPECT_DOUBLE_EQ(log(2+1),item_score);
  EXPECT_FALSE(rsi->has_next());
}

TEST_F(TestTransitionEndLogger, test){
  vector<RecDat> timeline;
  TransitionProbabilityModel model;
  TransitionProbabilityModelUpdaterParameters params;
  params.filter_freq_updates = false; //default: do not do any filtering
  TransitionProbabilityModelUpdater updater(&params);
  updater.set_model(&model);
  EXPECT_TRUE(model.self_test());
  EXPECT_TRUE(updater.self_test());
  TransitionModelEndLoggerParameters logger_params;
  logger_params.max_length=5;
  TransitionModelEndLogger logger(&logger_params);
  logger.set_model(&model);
  PopContainer pop_container;
  logger.set_pop_container(&pop_container);
  EXPECT_TRUE(logger.self_test());
  pop_container.increase(2);
  pop_container.increase(2);
  pop_container.increase(2);
  pop_container.increase(2); //4x
  pop_container.increase(3);
  pop_container.increase(3); //2x
  pop_container.increase(5);
  pop_container.increase(5);
  pop_container.increase(5);
  pop_container.increase(5);
  pop_container.increase(5);
  pop_container.increase(5); //6x
  RecDat* rec_dat;
  rec_dat = create_recdat(1,1,1,1);
  updater.update(rec_dat);
  for(int i=0;i<10;i++){
    rec_dat = create_recdat(1,1,2,1);
    updater.update(rec_dat);
    rec_dat = create_recdat(1,1,3,1);
    updater.update(rec_dat);
  }
  rec_dat = create_recdat(1,1,1,1);
  updater.update(rec_dat);
  for(int i=0;i<10;i++){
    rec_dat = create_recdat(1,1,4,1);
    updater.update(rec_dat);
    rec_dat = create_recdat(1,1,5,1);
    updater.update(rec_dat);
    rec_dat = create_recdat(1,1,6,1);
    updater.update(rec_dat);
  }
  rec_dat = create_recdat(1,1,1,1);
  updater.update(rec_dat);
  for(int i=0;i<10;i++){
    RecDat* rec_dat_1 = create_recdat(1,1,7,1);
    RecDat* rec_dat_2 = create_recdat(1,1,i,1);
    for(int j=0;j<i;j++){
      updater.update(rec_dat_1);
      updater.update(rec_dat_2);
    }
  }
  std::stringstream ss;
  logger.run_core(ss);
  vector<string> expected_lines;
  expected_lines.push_back("0 0 0");
  expected_lines.push_back("1 3 0 7,2 2,1 4,1");
  expected_lines.push_back("2 2 4 3,10 7,2");
  expected_lines.push_back("3 3 2 2,9 7,3 1,1");
  expected_lines.push_back("4 2 0 5,10 7,4");
  expected_lines.push_back("5 2 6 6,10 7,5");
  expected_lines.push_back("6 3 0 4,9 7,6 1,1");
  expected_lines.push_back("7 9 0 7,14 9,9 8,8 6,6 5,5");// 4,4 3,3 2,2 1,1");
  expected_lines.push_back("8 1 0 7,8");
  expected_lines.push_back("9 1 0 7,8");
  for(int i=0;i<expected_lines.size();i++){
    string actual_line;
    std::getline(ss,actual_line);
    EXPECT_EQ(expected_lines[i],actual_line);
  }
  //cerr << ss.str() << endl;
}

int main (int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// 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/gpu_operations.h"
#include "Eigen/Dense"
#include "gtest/gtest.h"

TEST(GPU_MATRIX_SCALAR_ADD, Basic_Test) {
  Nice::Matrix<float> a(3,4);
  a << 1, 2, 3, 4,
       1, 2, 3, 4,
       1, 2, 3, 4;
  Nice::Matrix<float> b = Nice::GpuOperations<float>::Add(a, 1);
  Nice::Matrix<float> answer(3, 4);
  answer << 2, 3, 4, 5,
            2, 3, 4, 5,
            2, 3, 4, 5;
  ASSERT_TRUE(answer.isApprox(b));
}
<commit_msg>completed matrix-scalar-add<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// 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/gpu_operations.h"
#include "Eigen/Dense"
#include "gtest/gtest.h"

template<class T>
class GPU_MATRIX_SCALAR_ADD : public ::testing::Test {
 public:
  Nice::Matrix<T> a;
  Nice::Matrix<T> correct_ans;
  Nice::Matrix<T> calc_ans;
  T scalar;

  void Add() {
    calc_ans = Nice::GpuOperations<T>::Add(a, scalar);
  }
};

typedef ::testing::Types<float, double> dataTypes;
TYPED_TEST_CASE(GPU_MATRIX_SCALAR_ADD, dataTypes);

TYPED_TEST(GPU_MATRIX_SCALAR_ADD, Basic_Test) {
  this->a.resize(3,4);
  this->a << 1, 2, 3, 4,
             1, 2, 3, 4,
             1, 2, 3, 4;
  this->scalar = 1;
  this->Add();
  this->correct_ans.resize(3, 4);
  this->correct_ans << 2, 3, 4, 5,
                       2, 3, 4, 5,
                       2, 3, 4, 5;
  ASSERT_TRUE(this->correct_ans.isApprox(this->calc_ans));
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//

//------------------------------------------------------------------------------
//
// Example: WebSocket server, synchronous
//
//------------------------------------------------------------------------------

#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>
#include <boost/functional/hash.hpp>
//#include <boost/asio/buffers_iterator.hpp>
//#include <cstdlib>
//#include <functional>
#include <iostream>
#include <string>
#include <thread>

#include <array>
#include <unordered_map>
#include <strawpoll.hpp>

using tcp = boost::asio::ip::tcp;               // from <boost/asio/ip/tcp.hpp>
namespace websocket = boost::beast::websocket;  // from <boost/beast/websocket.hpp>

//------------------------------------------------------------------------------

namespace detail
{
  template<typename T> struct hash
  {
    size_t operator() (const T& v) const noexcept
    {
      if (v.is_v4()) return v.to_v4().to_ulong();
      if (v.is_v6())
      {
          auto const& range = v.to_v6().to_bytes();
          return boost::hash_range(range.begin(), range.end());
      }
      if (v.is_unspecified()) return 0x4751301174351161ul;
      return boost::hash_value(v.to_string());
    }
  };

  template<typename T, typename M> class member_func_ptr_closure
  {
  public:
    using obj_ptr_t = T*;
    using member_func_ptr_t = M;

    constexpr member_func_ptr_closure(
      obj_ptr_t obj_ptr,
      member_func_ptr_t member_func_ptr
    ) noexcept
      : obj_ptr_{obj_ptr}, member_func_ptr_{member_func_ptr}
    {}

    template<typename... Args> auto operator() (Args&&... args)
    {
      return ((obj_ptr_)->*(member_func_ptr_))(std::forward<Args>(args)...);
    }

  private:
    obj_ptr_t obj_ptr_;
    member_func_ptr_t member_func_ptr_;
  };

  namespace conv
  {
    boost::asio::const_buffer m_b(FlatBufferRef buffer)
    {
      return { buffer.data, buffer.size };
    }
  }
} // namespace detail

//using poll_data_t = PollData<VoteGuard<boost::asio::ip::address, detail::hash>>;
using poll_data_t = PollData<HippieVoteGuard<boost::asio::ip::address>>;

// Report a failure
void fail(boost::system::error_code ec, char const* what)
{
    std::cerr << what << ": " << ec.message() << "\n";
}

// Echoes back all received WebSocket messages
template<typename FC, typename FB> class session
{
public:
  // Take ownership of the socket
  explicit session(
    tcp::socket&& socket,
    boost::asio::ip::address address,
    FC on_close,
    FB broadcast,
    size_t session_id,
    poll_data_t& poll_data
  )
      : ws_{std::move(socket)}
      , address_{address}
      , strand_{ws_.get_io_service()}
      , read_in_process_{false}
      , write_in_process_{false}
      , on_close_{on_close}
      , broadcast_{broadcast}
      , session_id_{session_id}
      , poll_data_{poll_data}
  {
    ws_.binary(true); // we'll only write binary

    // Accept the websocket handshake
    ws_.async_accept(
        strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); })
    );
  }

  session(const session&) = delete;
  session(session&&) = default;

  session& operator= (const session&) = delete;
  session& operator= (session&&) = default;

  ~session() = default;

  void add_message(FlatBufferRef br)
  {
    if (
      std::is_same_v<
        poll_data_t::vote_guard_t,
        HippieVoteGuard<boost::asio::ip::address>
      >
      || !write_in_process_ // write should always write the most recent
      || poll_data_.vote_guard.has_voted(address_)
    )
      message_queue_.push_back(detail::conv::m_b(br));
  }

  void flush_message_queue()
  {
    if (write_in_process_) return;

    if (message_queue_.empty()) return;

    ws_.async_write(
      std::array<boost::asio::const_buffer, 1>{{
        std::move(message_queue_.back())
      }},
      strand_.wrap(
        [this](boost::system::error_code ec, size_t bytes_transferred)
        {
          write_in_process_ = false;
          on_write(ec, bytes_transferred);
        }
      )
    );

    write_in_process_ = true;
    message_queue_.pop_back();
  }

private:
  websocket::stream<tcp::socket> ws_;
  boost::asio::ip::address address_;
  boost::asio::io_service::strand strand_;
  boost::beast::multi_buffer buffer_;
  std::vector<boost::asio::const_buffer> message_queue_;
  bool read_in_process_;
  bool write_in_process_;
  FC on_close_;
  FB broadcast_;
  size_t session_id_;
  poll_data_t& poll_data_;

  void on_accept(boost::system::error_code ec)
  {
    if (ec) return fail(ec, "accept");

    // Read a message
    do_read();
  }

  void do_read()
  {
    if (read_in_process_) return;
    // Clear the buffer
    buffer_.consume(buffer_.size());

    // Read a message into our buffer
    ws_.async_read(
      buffer_,
      strand_.wrap(
        [this](boost::system::error_code ec, size_t bytes_transferred)
        {
          read_in_process_ = false;
          on_read(ec, bytes_transferred);
        }
      )
    );
    read_in_process_ = true;
  }

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

    // This indicates that the session was closed
    if (ec == websocket::error::closed)
    {
      on_close_(session_id_);
      return;
    }

    if (ec) fail(ec, "read");

    build_responses();
    flush_message_queue();
  }

  void on_write(
    boost::system::error_code ec,
    size_t// bytes_transferred
  ) {
    //boost::ignore_unused(bytes_transferred);

    if (ec) return fail(ec, "write");

    if (!message_queue_.empty())
    {
      flush_message_queue();
      return;
    }

    // Do another read
    do_read();
  }

  void build_responses()
  {
    const auto add_response = [&queue = message_queue_](FlatBufferRef br)
    {
      queue.push_back(detail::conv::m_b(br));
    };

    for (const auto buffer : buffer_.data())
    {
      const auto ok = flatbuffers::Verifier(
        boost::asio::buffer_cast<const uint8_t*>(buffer),
        boost::asio::buffer_size(buffer)
      ).VerifyBuffer<Strawpoll::Request>(nullptr);

      if (!ok) {
        add_response(poll_data_.error_responses.invalid_message.ref());
        continue;
      }

      const auto request = flatbuffers::GetRoot<Strawpoll::Request>(
        boost::asio::buffer_cast<const uint8_t*>(buffer)
      );

      switch(request->type())
      {
        case Strawpoll::RequestType_Poll:
          add_response(poll_data_.poll_response.ref());

          if (poll_data_.vote_guard.has_voted(address_))
            add_response(poll_data_.result_ref());
          break;
        case Strawpoll::RequestType_Result:
          poll_data_.register_vote(
            request->vote(),
            address_,
            add_response,
            [&broadcast = broadcast_](FlatBufferRef br) { broadcast(br); }
          );
          break;
        default:
          add_response(poll_data_.error_responses.invalid_type.ref());
      }
    }
  }
};

// Accepts incoming connections and launches the sessions
class listener
{
public:
  void on_session_close(size_t session_id)
  {
    sessions_.erase(session_id);
  }

  void broadcast(FlatBufferRef br)
  {
    for (auto& [key, session] : sessions_)
    {
      session.add_message(br);
      session.flush_message_queue();
    }
  }

  using on_session_close_t = detail::member_func_ptr_closure<
    listener,
    decltype(&listener::on_session_close)
  >;
  using broadcast_t = detail::member_func_ptr_closure<
    listener,
    decltype(&listener::broadcast)
  >;

  using session_t = session<on_session_close_t, broadcast_t>;
  using sessions_t = std::unordered_map<size_t, session_t>;

  explicit listener(
      boost::asio::io_service& ios,
      tcp::endpoint endpoint)
      : strand_{ios}
      , acceptor_{ios}
      , socket_{ios}
      , session_id_counter_{}
      , on_session_close_{this, &listener::on_session_close}
      , broadcast_{this, &listener::broadcast}
      , poll_data_{}
  {
    boost::system::error_code ec;

    // Open the acceptor
    acceptor_.open(endpoint.protocol(), ec);
    if (ec)
    {
      fail(ec, "open");
      return;
    }

    // Bind to the server address
    acceptor_.bind(endpoint, ec);
    if (ec)
    {
      fail(ec, "bind");
      return;
    }

    // Start listening for connections
    acceptor_.listen(boost::asio::socket_base::max_connections, ec);
    if (ec)
    {
      fail(ec, "listen");
      return;
    }

    if (! acceptor_.is_open()) return;
    do_accept();
  }

  listener(const listener&) = delete;
  listener(listener&&) = default;

  listener& operator= (const listener&) = delete;
  listener& operator= (listener&&) = default;

  ~listener() = default;

  void do_accept()
  {
    acceptor_.async_accept(
      socket_,
      strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); })
    );
  }

  void on_accept(boost::system::error_code ec)
  {
    if (ec)
    {
      fail(ec, "accept");
    }
    else
    {
      // Create the session and run it
      const auto address = socket_.remote_endpoint().address();
      sessions_.try_emplace(
        session_id_counter_,
        std::move(socket_),
        std::move(address),
        on_session_close_,
        broadcast_,
        session_id_counter_,
        poll_data_
      );
      ++session_id_counter_;
    }

    // Accept another connection
    do_accept();
  }

private:
  boost::asio::io_service::strand strand_;
  tcp::acceptor acceptor_;
  tcp::socket socket_;
  size_t session_id_counter_;
  on_session_close_t on_session_close_;
  broadcast_t broadcast_;
  sessions_t sessions_;
  poll_data_t poll_data_;
};

//------------------------------------------------------------------------------

int main()
{
  const auto address = boost::asio::ip::address::from_string("127.0.0.1");
  const auto port = static_cast<unsigned short>(3003);

  boost::asio::io_service ios{1};
  listener lis{ios, tcp::endpoint{address, port}};
  ios.run(); // blocking
}
<commit_msg>Beast example cleanup<commit_after>//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//

//------------------------------------------------------------------------------
//
// Example: WebSocket server, synchronous
//
//------------------------------------------------------------------------------

#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>
#include <boost/functional/hash.hpp>
#include <iostream>

#include <array>
#include <unordered_map>
#include <strawpoll.hpp>

using tcp = boost::asio::ip::tcp;               // from <boost/asio/ip/tcp.hpp>
namespace websocket = boost::beast::websocket;  // from <boost/beast/websocket.hpp>

//------------------------------------------------------------------------------

namespace detail
{
  template<typename T> struct hash
  {
    size_t operator() (const T& v) const noexcept
    {
      if (v.is_v4()) return v.to_v4().to_ulong();
      if (v.is_v6())
      {
          auto const& range = v.to_v6().to_bytes();
          return boost::hash_range(range.begin(), range.end());
      }
      if (v.is_unspecified()) return 0x4751301174351161ul;
      return boost::hash_value(v.to_string());
    }
  };

  template<typename T, typename M> class member_func_ptr_closure
  {
  public:
    using obj_ptr_t = T*;
    using member_func_ptr_t = M;

    constexpr member_func_ptr_closure(
      obj_ptr_t obj_ptr,
      member_func_ptr_t member_func_ptr
    ) noexcept
      : obj_ptr_{obj_ptr}, member_func_ptr_{member_func_ptr}
    {}

    template<typename... Args> auto operator() (Args&&... args)
    {
      return ((obj_ptr_)->*(member_func_ptr_))(std::forward<Args>(args)...);
    }

  private:
    obj_ptr_t obj_ptr_;
    member_func_ptr_t member_func_ptr_;
  };

  namespace conv
  {
    boost::asio::const_buffer m_b(FlatBufferRef buffer)
    {
      return { buffer.data, buffer.size };
    }
  }
} // namespace detail

//using poll_data_t = PollData<VoteGuard<boost::asio::ip::address, detail::hash>>;
using poll_data_t = PollData<HippieVoteGuard<boost::asio::ip::address>>;

// Report a failure
void fail(boost::system::error_code ec, char const* what)
{
    std::cerr << what << ": " << ec.message() << "\n";
}

// Echoes back all received WebSocket messages
template<typename FC, typename FB> class session
{
public:
  // Take ownership of the socket
  explicit session(
    tcp::socket&& socket,
    boost::asio::ip::address address,
    FC on_close,
    FB broadcast,
    size_t session_id,
    poll_data_t& poll_data
  )
      : ws_{std::move(socket)}
      , address_{address}
      , strand_{ws_.get_io_service()}
      , read_in_process_{false}
      , write_in_process_{false}
      , on_close_{on_close}
      , broadcast_{broadcast}
      , session_id_{session_id}
      , poll_data_{poll_data}
  {
    ws_.binary(true); // we'll only write binary

    // Accept the websocket handshake
    ws_.async_accept(
      strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); })
    );
  }

  session(const session&) = delete;
  session(session&&) = default;

  session& operator= (const session&) = delete;
  session& operator= (session&&) = default;

  ~session() = default;

  void add_message(FlatBufferRef br)
  {
    if (
      std::is_same_v<
        poll_data_t::vote_guard_t,
        HippieVoteGuard<boost::asio::ip::address>
      >
      || !write_in_process_ // write should always write the most recent
      || poll_data_.vote_guard.has_voted(address_)
    )
      message_queue_.push_back(detail::conv::m_b(br));
  }

  void flush_message_queue()
  {
    if (write_in_process_) return;

    if (message_queue_.empty()) return;

    ws_.async_write(
      std::array<boost::asio::const_buffer, 1>{{
        std::move(message_queue_.back())
      }},
      strand_.wrap(
        [this](boost::system::error_code ec, size_t bytes_transferred)
        {
          write_in_process_ = false;
          on_write(ec, bytes_transferred);
        }
      )
    );

    write_in_process_ = true;
    message_queue_.pop_back();
  }

private:
  websocket::stream<tcp::socket> ws_;
  boost::asio::ip::address address_;
  boost::asio::io_service::strand strand_;
  boost::beast::multi_buffer buffer_;
  std::vector<boost::asio::const_buffer> message_queue_;
  bool read_in_process_;
  bool write_in_process_;
  FC on_close_;
  FB broadcast_;
  size_t session_id_;
  poll_data_t& poll_data_;

  void on_accept(boost::system::error_code ec)
  {
    if (ec) return fail(ec, "accept");

    // Read a message
    do_read();
  }

  void do_read()
  {
    if (read_in_process_) return;
    // Clear the buffer
    buffer_.consume(buffer_.size());

    // Read a message into our buffer
    ws_.async_read(
      buffer_,
      strand_.wrap(
        [this](boost::system::error_code ec, size_t bytes_transferred)
        {
          read_in_process_ = false;
          on_read(ec, bytes_transferred);
        }
      )
    );
    read_in_process_ = true;
  }

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

    // This indicates that the session was closed
    if (ec == websocket::error::closed)
    {
      on_close_(session_id_);
      return;
    }

    if (ec) fail(ec, "read");

    build_responses();
    flush_message_queue();
  }

  void on_write(
    boost::system::error_code ec,
    size_t// bytes_transferred
  ) {
    //boost::ignore_unused(bytes_transferred);

    if (ec) return fail(ec, "write");

    if (!message_queue_.empty())
    {
      flush_message_queue();
      return;
    }

    // Do another read
    do_read();
  }

  void build_responses()
  {
    const auto add_response = [&queue = message_queue_](FlatBufferRef br)
    {
      queue.push_back(detail::conv::m_b(br));
    };

    for (const auto buffer : buffer_.data())
    {
      const auto ok = flatbuffers::Verifier(
        boost::asio::buffer_cast<const uint8_t*>(buffer),
        boost::asio::buffer_size(buffer)
      ).VerifyBuffer<Strawpoll::Request>(nullptr);

      if (!ok) {
        add_response(poll_data_.error_responses.invalid_message.ref());
        continue;
      }

      const auto request = flatbuffers::GetRoot<Strawpoll::Request>(
        boost::asio::buffer_cast<const uint8_t*>(buffer)
      );

      switch(request->type())
      {
        case Strawpoll::RequestType_Poll:
          add_response(poll_data_.poll_response.ref());

          if (poll_data_.vote_guard.has_voted(address_))
            add_response(poll_data_.result_ref());
          break;
        case Strawpoll::RequestType_Result:
          poll_data_.register_vote(
            request->vote(),
            address_,
            add_response,
            [&broadcast = broadcast_](FlatBufferRef br) { broadcast(br); }
          );
          break;
        default:
          add_response(poll_data_.error_responses.invalid_type.ref());
      }
    }
  }
};

// Accepts incoming connections and launches the sessions
class listener
{
public:
  void on_session_close(size_t session_id)
  {
    sessions_.erase(session_id);
  }

  void broadcast(FlatBufferRef br)
  {
    for (auto& [key, session] : sessions_)
    {
      session.add_message(br);
      session.flush_message_queue();
    }
  }

  using on_session_close_t = detail::member_func_ptr_closure<
    listener,
    decltype(&listener::on_session_close)
  >;
  using broadcast_t = detail::member_func_ptr_closure<
    listener,
    decltype(&listener::broadcast)
  >;

  using session_t = session<on_session_close_t, broadcast_t>;
  using sessions_t = std::unordered_map<size_t, session_t>;

  explicit listener(
      boost::asio::io_service& ios,
      tcp::endpoint endpoint)
      : strand_{ios}
      , acceptor_{ios}
      , socket_{ios}
      , session_id_counter_{}
      , on_session_close_{this, &listener::on_session_close}
      , broadcast_{this, &listener::broadcast}
      , poll_data_{}
  {
    boost::system::error_code ec;

    // Open the acceptor
    acceptor_.open(endpoint.protocol(), ec);
    if (ec)
    {
      fail(ec, "open");
      return;
    }

    // Bind to the server address
    acceptor_.bind(endpoint, ec);
    if (ec)
    {
      fail(ec, "bind");
      return;
    }

    // Start listening for connections
    acceptor_.listen(boost::asio::socket_base::max_connections, ec);
    if (ec)
    {
      fail(ec, "listen");
      return;
    }

    if (!acceptor_.is_open()) return;
    do_accept();
  }

  listener(const listener&) = delete;
  listener(listener&&) = default;

  listener& operator= (const listener&) = delete;
  listener& operator= (listener&&) = default;

  ~listener() = default;

  void do_accept()
  {
    acceptor_.async_accept(
      socket_,
      strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); })
    );
  }

  void on_accept(boost::system::error_code ec)
  {
    if (ec)
    {
      fail(ec, "accept");
    }
    else
    {
      // Create the session and run it
      const auto address = socket_.remote_endpoint().address();
      sessions_.try_emplace(
        session_id_counter_,
        std::move(socket_),
        std::move(address),
        on_session_close_,
        broadcast_,
        session_id_counter_,
        poll_data_
      );
      ++session_id_counter_;
    }

    // Accept another connection
    do_accept();
  }

private:
  boost::asio::io_service::strand strand_;
  tcp::acceptor acceptor_;
  tcp::socket socket_;
  size_t session_id_counter_;
  on_session_close_t on_session_close_;
  broadcast_t broadcast_;
  sessions_t sessions_;
  poll_data_t poll_data_;
};

//------------------------------------------------------------------------------

int main()
{
  const auto address = boost::asio::ip::address::from_string("127.0.0.1");
  const auto port = static_cast<unsigned short>(3003);

  boost::asio::io_service ios{1};
  listener lis{ios, tcp::endpoint{address, port}};
  ios.run(); // blocking
}
<|endoftext|>


<commit_before>#include "Random.h"
#include "VectorMath.h"
#include "Common.h"

namespace ECSE
{

std::random_device randomDevice;
std::mt19937 ECSE::randomEngine(randomDevice());

sf::Vector2f ECSE::randomSpreadVector(float midAngle, float angleSpread, float minMag, float maxMag)
{
    auto angleDist = std::uniform_real_distribution<float>(
        midAngle - angleSpread * 0.5f,
        midAngle + angleSpread * 0.5f
        );
    auto magDist = std::uniform_real_distribution<float>(minMag, maxMag);

    float angle = angleDist(randomEngine);
    float mag = magDist(randomEngine);

    auto v = sf::Vector2f(mag, 0.f);
    setHeading(v, angle);

    return v;
}

sf::Vector2f ECSE::randomEllipticalVector(float xScale, float angle, float minMag, float maxMag)
{
    // Just generate a random circular vector, scale it, and rotate it
    auto vec = ECSE::randomSpreadVector(0.f, ECSE::twoPi, minMag, maxMag);
    vec.x *= xScale;
    ECSE::rotate(vec, angle);

    return vec;
}

}<commit_msg>Fix explicit qualification.<commit_after>#include "Random.h"
#include "VectorMath.h"
#include "Common.h"

namespace ECSE
{

std::random_device randomDevice;
std::mt19937 randomEngine(randomDevice());

sf::Vector2f randomSpreadVector(float midAngle, float angleSpread, float minMag, float maxMag)
{
    auto angleDist = std::uniform_real_distribution<float>(
        midAngle - angleSpread * 0.5f,
        midAngle + angleSpread * 0.5f
        );
    auto magDist = std::uniform_real_distribution<float>(minMag, maxMag);

    float angle = angleDist(randomEngine);
    float mag = magDist(randomEngine);

    auto v = sf::Vector2f(mag, 0.f);
    setHeading(v, angle);

    return v;
}

sf::Vector2f randomEllipticalVector(float xScale, float angle, float minMag, float maxMag)
{
    // Just generate a random circular vector, scale it, and rotate it
    auto vec = randomSpreadVector(0.f, ECSE::twoPi, minMag, maxMag);
    vec.x *= xScale;
    rotate(vec, angle);

    return vec;
}

}
<|endoftext|>


<commit_before>//===- Strings.cpp -------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Strings.h"
#include "Config.h"
#include "Error.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Demangle/Demangle.h"
#include <algorithm>
#include <cstring>

using namespace llvm;
using namespace lld;
using namespace lld::elf;

StringMatcher::StringMatcher(ArrayRef<StringRef> Pat) {
  for (StringRef S : Pat) {
    Expected<GlobPattern> Pat = GlobPattern::create(S);
    if (!Pat)
      error(toString(Pat.takeError()));
    else
      Patterns.push_back(*Pat);
  }
}

bool StringMatcher::match(StringRef S) const {
  for (const GlobPattern &Pat : Patterns)
    if (Pat.match(S))
      return true;
  return false;
}

// If an input string is in the form of "foo.N" where N is a number,
// return N. Otherwise, returns 65536, which is one greater than the
// lowest priority.
int elf::getPriority(StringRef S) {
  size_t Pos = S.rfind('.');
  if (Pos == StringRef::npos)
    return 65536;
  int V;
  if (S.substr(Pos + 1).getAsInteger(10, V))
    return 65536;
  return V;
}

bool elf::hasWildcard(StringRef S) {
  return S.find_first_of("?*[") != StringRef::npos;
}

StringRef elf::unquote(StringRef S) {
  if (!S.startswith("\""))
    return S;
  return S.substr(1, S.size() - 2);
}

// Converts a hex string (e.g. "deadbeef") to a vector.
std::vector<uint8_t> elf::parseHex(StringRef S) {
  std::vector<uint8_t> Hex;
  while (!S.empty()) {
    StringRef B = S.substr(0, 2);
    S = S.substr(2);
    uint8_t H;
    if (B.getAsInteger(16, H)) {
      error("not a hexadecimal value: " + B);
      return {};
    }
    Hex.push_back(H);
  }
  return Hex;
}

static bool isAlpha(char C) {
  return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';
}

static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }

// Returns true if S is valid as a C language identifier.
bool elf::isValidCIdentifier(StringRef S) {
  return !S.empty() && isAlpha(S[0]) &&
         std::all_of(S.begin() + 1, S.end(), isAlnum);
}

// Returns the demangled C++ symbol name for Name.
Optional<std::string> elf::demangle(StringRef Name) {
  // __cxa_demangle can be used to demangle strings other than symbol
  // names which do not necessarily start with "_Z". Name can be
  // either a C or C++ symbol. Don't call __cxa_demangle if the name
  // does not look like a C++ symbol name to avoid getting unexpected
  // result for a C symbol that happens to match a mangled type name.
  if (!Name.startswith("_Z"))
    return None;

  char *Buf = itaniumDemangle(Name.str().c_str(), nullptr, nullptr, nullptr);
  if (!Buf)
    return None;
  std::string S(Buf);
  free(Buf);
  return S;
}
<commit_msg>[ELF] __cxa_demangle is now called itaniumDemangle. Update.<commit_after>//===- Strings.cpp -------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Strings.h"
#include "Config.h"
#include "Error.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Demangle/Demangle.h"
#include <algorithm>
#include <cstring>

using namespace llvm;
using namespace lld;
using namespace lld::elf;

StringMatcher::StringMatcher(ArrayRef<StringRef> Pat) {
  for (StringRef S : Pat) {
    Expected<GlobPattern> Pat = GlobPattern::create(S);
    if (!Pat)
      error(toString(Pat.takeError()));
    else
      Patterns.push_back(*Pat);
  }
}

bool StringMatcher::match(StringRef S) const {
  for (const GlobPattern &Pat : Patterns)
    if (Pat.match(S))
      return true;
  return false;
}

// If an input string is in the form of "foo.N" where N is a number,
// return N. Otherwise, returns 65536, which is one greater than the
// lowest priority.
int elf::getPriority(StringRef S) {
  size_t Pos = S.rfind('.');
  if (Pos == StringRef::npos)
    return 65536;
  int V;
  if (S.substr(Pos + 1).getAsInteger(10, V))
    return 65536;
  return V;
}

bool elf::hasWildcard(StringRef S) {
  return S.find_first_of("?*[") != StringRef::npos;
}

StringRef elf::unquote(StringRef S) {
  if (!S.startswith("\""))
    return S;
  return S.substr(1, S.size() - 2);
}

// Converts a hex string (e.g. "deadbeef") to a vector.
std::vector<uint8_t> elf::parseHex(StringRef S) {
  std::vector<uint8_t> Hex;
  while (!S.empty()) {
    StringRef B = S.substr(0, 2);
    S = S.substr(2);
    uint8_t H;
    if (B.getAsInteger(16, H)) {
      error("not a hexadecimal value: " + B);
      return {};
    }
    Hex.push_back(H);
  }
  return Hex;
}

static bool isAlpha(char C) {
  return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';
}

static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }

// Returns true if S is valid as a C language identifier.
bool elf::isValidCIdentifier(StringRef S) {
  return !S.empty() && isAlpha(S[0]) &&
         std::all_of(S.begin() + 1, S.end(), isAlnum);
}

// Returns the demangled C++ symbol name for Name.
Optional<std::string> elf::demangle(StringRef Name) {
  // itaniumDemangle can be used to demangle strings other than symbol
  // names which do not necessarily start with "_Z". Name can be
  // either a C or C++ symbol. Don't call itaniumDemangle if the name
  // does not look like a C++ symbol name to avoid getting unexpected
  // result for a C symbol that happens to match a mangled type name.
  if (!Name.startswith("_Z"))
    return None;

  char *Buf = itaniumDemangle(Name.str().c_str(), nullptr, nullptr, nullptr);
  if (!Buf)
    return None;
  std::string S(Buf);
  free(Buf);
  return S;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/location_bar/chrome_to_mobile_view.h"

#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/browser_dialogs.h"
#include "chrome/browser/ui/views/location_bar/location_bar_view.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "grit/theme_resources_standard.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"

ChromeToMobileView::ChromeToMobileView(
    LocationBarView* location_bar_view,
    CommandUpdater* command_updater)
    : location_bar_view_(location_bar_view),
      command_updater_(command_updater) {
  set_id(VIEW_ID_CHROME_TO_MOBILE_BUTTON);
  set_accessibility_focusable(true);
  SetImage(ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_STAR));
  SetTooltipText(
      l10n_util::GetStringUTF16(IDS_CHROME_TO_MOBILE_BUBBLE_TOOLTIP));
  SetVisible(command_updater_->IsCommandEnabled(IDC_CHROME_TO_MOBILE_PAGE));
  command_updater_->AddCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this);
}

ChromeToMobileView::~ChromeToMobileView() {
  command_updater_->RemoveCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this);
}

void ChromeToMobileView::EnabledStateChangedForCommand(int id, bool enabled) {
  DCHECK_EQ(id, IDC_CHROME_TO_MOBILE_PAGE);
  if (enabled != visible()) {
    SetVisible(enabled);
    location_bar_view_->Update(NULL);
  }
}

void ChromeToMobileView::GetAccessibleState(ui::AccessibleViewState* state) {
  state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_CHROME_TO_MOBILE);
  state->role = ui::AccessibilityTypes::ROLE_PUSHBUTTON;
}

bool ChromeToMobileView::GetTooltipText(const gfx::Point& p,
                                        string16* tooltip) const {
  // Don't show tooltip to distract user if ChromeToMobileBubbleView is showing.
  if (browser::IsChromeToMobileBubbleViewShowing())
    return false;

  return ImageView::GetTooltipText(p, tooltip);
}

bool ChromeToMobileView::OnMousePressed(const views::MouseEvent& event) {
  // Show the bubble on mouse release; that is standard button behavior.
  return true;
}

void ChromeToMobileView::OnMouseReleased(const views::MouseEvent& event) {
  if (event.IsOnlyLeftMouseButton() && HitTest(event.location()))
    command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE);
}

bool ChromeToMobileView::OnKeyPressed(const views::KeyEvent& event) {
  if (event.key_code() == ui::VKEY_SPACE ||
      event.key_code() == ui::VKEY_RETURN) {
    command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE);
    return true;
  }
  return false;
}
<commit_msg>Use Chrome To Mobile's new mobile device/phone icon. Replace IDR_STAR with IDR_MOBILE for the page action icon.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/location_bar/chrome_to_mobile_view.h"

#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/browser_dialogs.h"
#include "chrome/browser/ui/views/location_bar/location_bar_view.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "grit/theme_resources_standard.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"

ChromeToMobileView::ChromeToMobileView(
    LocationBarView* location_bar_view,
    CommandUpdater* command_updater)
    : location_bar_view_(location_bar_view),
      command_updater_(command_updater) {
  set_id(VIEW_ID_CHROME_TO_MOBILE_BUTTON);
  set_accessibility_focusable(true);
  SetImage(ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_MOBILE));
  SetTooltipText(
      l10n_util::GetStringUTF16(IDS_CHROME_TO_MOBILE_BUBBLE_TOOLTIP));
  SetVisible(command_updater_->IsCommandEnabled(IDC_CHROME_TO_MOBILE_PAGE));
  command_updater_->AddCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this);
}

ChromeToMobileView::~ChromeToMobileView() {
  command_updater_->RemoveCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this);
}

void ChromeToMobileView::EnabledStateChangedForCommand(int id, bool enabled) {
  DCHECK_EQ(id, IDC_CHROME_TO_MOBILE_PAGE);
  if (enabled != visible()) {
    SetVisible(enabled);
    location_bar_view_->Update(NULL);
  }
}

void ChromeToMobileView::GetAccessibleState(ui::AccessibleViewState* state) {
  state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_CHROME_TO_MOBILE);
  state->role = ui::AccessibilityTypes::ROLE_PUSHBUTTON;
}

bool ChromeToMobileView::GetTooltipText(const gfx::Point& p,
                                        string16* tooltip) const {
  // Don't show tooltip to distract user if ChromeToMobileBubbleView is showing.
  if (browser::IsChromeToMobileBubbleViewShowing())
    return false;

  return ImageView::GetTooltipText(p, tooltip);
}

bool ChromeToMobileView::OnMousePressed(const views::MouseEvent& event) {
  // Show the bubble on mouse release; that is standard button behavior.
  return true;
}

void ChromeToMobileView::OnMouseReleased(const views::MouseEvent& event) {
  if (event.IsOnlyLeftMouseButton() && HitTest(event.location()))
    command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE);
}

bool ChromeToMobileView::OnKeyPressed(const views::KeyEvent& event) {
  if (event.key_code() == ui::VKEY_SPACE ||
      event.key_code() == ui::VKEY_RETURN) {
    command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE);
    return true;
  }
  return false;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if !defined(OS_CHROMEOS)

#include "chrome/browser/ui/webui/options/advanced_options_utils.h"

#include "base/environment.h"
#include "base/file_util.h"
#include "base/nix/xdg_util.h"
#include "base/process_util.h"
#include "base/string_tokenizer.h"
#include "chrome/browser/ui/browser_list.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/process_watcher.h"
#include "ui/base/gtk/gtk_signal.h"

// Command used to configure GNOME proxy settings. The command was renamed
// in January 2009, so both are used to work on both old and new systems.
const char* kOldGNOMEProxyConfigCommand[] = {"gnome-network-preferences", NULL};
const char* kGNOMEProxyConfigCommand[] = {"gnome-network-properties", NULL};
// KDE3 and KDE4 are only slightly different, but incompatible. Go figure.
const char* kKDE3ProxyConfigCommand[] = {"kcmshell", "proxy", NULL};
const char* kKDE4ProxyConfigCommand[] = {"kcmshell4", "proxy", NULL};

// The URL for Linux proxy configuration help when not running under a
// supported desktop environment.
const char kLinuxProxyConfigUrl[] = "about:linux-proxy-config";

struct ProxyConfigCommand {
  std::string binary;
  const char** argv;
};

namespace {

// Search $PATH to find one of the commands. Store the full path to
// it in the |binary| field and the command array index in in |index|.
bool SearchPATH(ProxyConfigCommand* commands, size_t ncommands, size_t* index) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  const char* path = getenv("PATH");
  if (!path)
    return false;
  FilePath bin_path;
  CStringTokenizer tk(path, path + strlen(path), ":");
  // Search $PATH looking for the commands in order.
  while (tk.GetNext()) {
    for (size_t i = 0; i < ncommands; i++) {
      bin_path = FilePath(tk.token()).Append(commands[i].argv[0]);
      if (file_util::PathExists(bin_path)) {
        commands[i].binary = bin_path.value();
        if (index)
          *index = i;
        return true;
      }
    }
  }
  // Did not find any of the binaries in $PATH.
  return false;
}

// Show the proxy config URL in the given tab.
void ShowLinuxProxyConfigUrl(TabContents* tab_contents) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  scoped_ptr<base::Environment> env(base::Environment::Create());
  const char* name = base::nix::GetDesktopEnvironmentName(env.get());
  if (name)
    LOG(ERROR) << "Could not find " << name << " network settings in $PATH";
  tab_contents->OpenURL(GURL(kLinuxProxyConfigUrl), GURL(),
                        NEW_FOREGROUND_TAB, PageTransition::LINK);
}

// Start the given proxy configuration utility.
void StartProxyConfigUtil(TabContents* tab_contents,
                          const ProxyConfigCommand& command) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  std::vector<std::string> argv;
  argv.push_back(command.binary);
  for (size_t i = 1; command.argv[i]; i++)
    argv.push_back(command.argv[i]);
  base::file_handle_mapping_vector no_files;
  base::ProcessHandle handle;
  if (!base::LaunchApp(argv, no_files, false, &handle)) {
    LOG(ERROR) << "StartProxyConfigUtil failed to start " << command.binary;
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
        NewRunnableFunction(&ShowLinuxProxyConfigUrl, tab_contents));
    return;
  }
  ProcessWatcher::EnsureProcessGetsReaped(handle);
}

// Detect, and if possible, start the appropriate proxy config utility. On
// failure to do so, show the Linux proxy config URL in a new tab instead.
void DetectAndStartProxyConfigUtil(TabContents* tab_contents) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  scoped_ptr<base::Environment> env(base::Environment::Create());

  ProxyConfigCommand command;
  bool found_command = false;
  switch (base::nix::GetDesktopEnvironment(env.get())) {
    case base::nix::DESKTOP_ENVIRONMENT_GNOME: {
      size_t index;
      ProxyConfigCommand commands[2];
      commands[0].argv = kGNOMEProxyConfigCommand;
      commands[1].argv = kOldGNOMEProxyConfigCommand;
      found_command = SearchPATH(commands, 2, &index);
      if (found_command)
        command = commands[index];
      break;
    }

    case base::nix::DESKTOP_ENVIRONMENT_KDE3:
      command.argv = kKDE3ProxyConfigCommand;
      found_command = SearchPATH(&command, 1, NULL);
      break;

    case base::nix::DESKTOP_ENVIRONMENT_KDE4:
      command.argv = kKDE4ProxyConfigCommand;
      found_command = SearchPATH(&command, 1, NULL);
      break;

    case base::nix::DESKTOP_ENVIRONMENT_XFCE:
    case base::nix::DESKTOP_ENVIRONMENT_OTHER:
      break;
  }

  if (found_command) {
    StartProxyConfigUtil(tab_contents, command);
  } else {
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
        NewRunnableFunction(&ShowLinuxProxyConfigUrl, tab_contents));
  }
}

}  // anonymous namespace

void AdvancedOptionsUtilities::ShowNetworkProxySettings(
    TabContents* tab_contents) {
  BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
      NewRunnableFunction(&DetectAndStartProxyConfigUtil, tab_contents));
}

#endif  // !defined(OS_CHROMEOS)
<commit_msg>Cleanup: Simplify the Linux proxy options code.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if !defined(OS_CHROMEOS)

#include "chrome/browser/ui/webui/options/advanced_options_utils.h"

#include "base/environment.h"
#include "base/nix/xdg_util.h"
#include "base/process_util.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/process_watcher.h"

// Command used to configure GNOME proxy settings. The command was renamed
// in January 2009, so both are used to work on both old and new systems.
// As on April 2011, many systems do not have the old command anymore.
// TODO(thestig) Remove the old command in the future.
const char* kOldGNOMEProxyConfigCommand[] = {"gnome-network-preferences", NULL};
const char* kGNOMEProxyConfigCommand[] = {"gnome-network-properties", NULL};
// KDE3 and KDE4 are only slightly different, but incompatible. Go figure.
const char* kKDE3ProxyConfigCommand[] = {"kcmshell", "proxy", NULL};
const char* kKDE4ProxyConfigCommand[] = {"kcmshell4", "proxy", NULL};

// The URL for Linux proxy configuration help when not running under a
// supported desktop environment.
const char kLinuxProxyConfigUrl[] = "about:linux-proxy-config";

namespace {

// Show the proxy config URL in the given tab.
void ShowLinuxProxyConfigUrl(TabContents* tab_contents) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  scoped_ptr<base::Environment> env(base::Environment::Create());
  const char* name = base::nix::GetDesktopEnvironmentName(env.get());
  if (name)
    LOG(ERROR) << "Could not find " << name << " network settings in $PATH";
  tab_contents->OpenURL(GURL(kLinuxProxyConfigUrl), GURL(),
                        NEW_FOREGROUND_TAB, PageTransition::LINK);
}

// Start the given proxy configuration utility.
bool StartProxyConfigUtil(TabContents* tab_contents, const char* command[]) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  std::vector<std::string> argv;
  for (size_t i = 0; command[i]; ++i)
    argv.push_back(command[i]);
  base::file_handle_mapping_vector no_files;
  base::ProcessHandle handle;
  if (!base::LaunchApp(argv, no_files, false, &handle)) {
    LOG(ERROR) << "StartProxyConfigUtil failed to start " << command[0];
    return false;
  }
  ProcessWatcher::EnsureProcessGetsReaped(handle);
  return true;
}

// Detect, and if possible, start the appropriate proxy config utility. On
// failure to do so, show the Linux proxy config URL in a new tab instead.
void DetectAndStartProxyConfigUtil(TabContents* tab_contents) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  scoped_ptr<base::Environment> env(base::Environment::Create());

  bool launched = false;
  switch (base::nix::GetDesktopEnvironment(env.get())) {
    case base::nix::DESKTOP_ENVIRONMENT_GNOME: {
      launched = StartProxyConfigUtil(tab_contents, kGNOMEProxyConfigCommand);
      if (!launched) {
        launched = StartProxyConfigUtil(tab_contents,
                                        kOldGNOMEProxyConfigCommand);
      }
      break;
    }

    case base::nix::DESKTOP_ENVIRONMENT_KDE3:
      launched = StartProxyConfigUtil(tab_contents, kKDE3ProxyConfigCommand);
      break;

    case base::nix::DESKTOP_ENVIRONMENT_KDE4:
      launched = StartProxyConfigUtil(tab_contents, kKDE4ProxyConfigCommand);
      break;

    case base::nix::DESKTOP_ENVIRONMENT_XFCE:
    case base::nix::DESKTOP_ENVIRONMENT_OTHER:
      break;
  }

  if (launched)
    return;
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
      NewRunnableFunction(&ShowLinuxProxyConfigUrl, tab_contents));
}

}  // anonymous namespace

void AdvancedOptionsUtilities::ShowNetworkProxySettings(
    TabContents* tab_contents) {
  BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
      NewRunnableFunction(&DetectAndStartProxyConfigUtil, tab_contents));
}

#endif  // !defined(OS_CHROMEOS)
<|endoftext|>


<commit_before>#include "FileChooser.h"
#include "Settings.h"
#include "GUIHelper.h"
#include <QFileDialog>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QUrl>
#include <QMenu>
#include <QDesktopServices>
#include <QMimeData>
#include <QBoxLayout>

FileChooser::FileChooser(FileChooser::Type type, QWidget *parent)
	: QWidget(parent)
	, type_(type)
{
	setAcceptDrops(true);

	//create layout
	QBoxLayout* layout = new QBoxLayout(QBoxLayout::LeftToRight);
	layout->setMargin(0);
	layout->setSpacing(3);
	setLayout(layout);

	//add widgets
	text_ = new QLineEdit();
	layout->addWidget(text_);
	button_ = new QPushButton("browse");
	layout->addWidget(button_);

	connect(button_, SIGNAL(clicked()), this, SLOT(browseFile()));
}

QString FileChooser::file()
{
	return text_->text();
}

void FileChooser::setFile(QString file)
{
	text_->setText(file);
}

void FileChooser::browseFile()
{
	QString file = "";

	if (type_==LOAD)
	{
		file = QFileDialog::getOpenFileName(this, "Select input file.", Settings::path("open_data_folder"), "*.*");
		if (file!="")
		{
			Settings::setPath("open_data_folder", file);
		}
	}
	else
	{
		file = QFileDialog::getSaveFileName(this, "Select output file.", Settings::path("store_data_folder"), "*.*");
		if (file!="")
		{
			Settings::setPath("store_data_folder", file);
		}
	}

	text_->setText(file);
	text_->setToolTip(file);
}

void FileChooser::dragEnterEvent(QDragEnterEvent* e)
{
	if (e->mimeData()->hasFormat("text/uri-list") && e->mimeData()->urls().count()==1)
	{
		e->acceptProposedAction();
	}
}

void FileChooser::dropEvent(QDropEvent* e)
{
	QString filename = e->mimeData()->urls().first().toLocalFile();

	if (filename.isEmpty())  return;

	text_->setText(filename);
}

void FileChooser::contextMenuEvent(QContextMenuEvent* e)
{
	//create menu
	QMenu* menu = new QMenu();
	menu->addAction("Copy");
	menu->addAction("Paste");
	menu->addAction("Delete");
	menu->addSeparator();
	if (text_->text()!="")
	{
		menu->addAction("Open");
	}

	//execute
	QAction* selected = menu->exec(e->globalPos());

	//evaluate
	if (selected!=0)
	{
		if(selected->text()=="Copy")
		{
			text_->selectAll();
			text_->copy();
			text_->deselect();
		}
		else if(selected->text()=="Paste")
		{
			QString previous = text_->text();

			//paste
			text_->selectAll();
			text_->paste();
			text_->deselect();

			//check file exists
			if (!QFile::exists(text_->text()))
			{
				GUIHelper::showMessage("Error", "File '" + text_->text() + "' does not exist!");
				text_->setText(previous);
			}
		}
		else if(selected->text()=="Delete")
		{
			text_->clear();
		}
		else if(selected->text()=="Open")
		{
			QDesktopServices::openUrl("file:///" + text_->text());
		}
	}
}
<commit_msg>Updated because of settings handling.<commit_after>#include "FileChooser.h"
#include "Settings.h"
#include "GUIHelper.h"
#include <QFileDialog>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QUrl>
#include <QMenu>
#include <QDesktopServices>
#include <QMimeData>
#include <QBoxLayout>

FileChooser::FileChooser(FileChooser::Type type, QWidget *parent)
	: QWidget(parent)
	, type_(type)
{
	setAcceptDrops(true);

	//create layout
	QBoxLayout* layout = new QBoxLayout(QBoxLayout::LeftToRight);
	layout->setMargin(0);
	layout->setSpacing(3);
	setLayout(layout);

	//add widgets
	text_ = new QLineEdit();
	layout->addWidget(text_);
	button_ = new QPushButton("browse");
	layout->addWidget(button_);

	connect(button_, SIGNAL(clicked()), this, SLOT(browseFile()));
}

QString FileChooser::file()
{
	return text_->text();
}

void FileChooser::setFile(QString file)
{
	text_->setText(file);
}

void FileChooser::browseFile()
{
	QString file = "";

	if (type_==LOAD)
	{
		file = QFileDialog::getOpenFileName(this, "Select input file.", Settings::path("open_data_folder", true), "*.*");
		if (file!="")
		{
			Settings::setPath("open_data_folder", file);
		}
	}
	else
	{
		file = QFileDialog::getSaveFileName(this, "Select output file.", Settings::path("store_data_folder", true), "*.*");
		if (file!="")
		{
			Settings::setPath("store_data_folder", file);
		}
	}

	text_->setText(file);
	text_->setToolTip(file);
}

void FileChooser::dragEnterEvent(QDragEnterEvent* e)
{
	if (e->mimeData()->hasFormat("text/uri-list") && e->mimeData()->urls().count()==1)
	{
		e->acceptProposedAction();
	}
}

void FileChooser::dropEvent(QDropEvent* e)
{
	QString filename = e->mimeData()->urls().first().toLocalFile();

	if (filename.isEmpty())  return;

	text_->setText(filename);
}

void FileChooser::contextMenuEvent(QContextMenuEvent* e)
{
	//create menu
	QMenu* menu = new QMenu();
	menu->addAction("Copy");
	menu->addAction("Paste");
	menu->addAction("Delete");
	menu->addSeparator();
	if (text_->text()!="")
	{
		menu->addAction("Open");
	}

	//execute
	QAction* selected = menu->exec(e->globalPos());

	//evaluate
	if (selected!=0)
	{
		if(selected->text()=="Copy")
		{
			text_->selectAll();
			text_->copy();
			text_->deselect();
		}
		else if(selected->text()=="Paste")
		{
			QString previous = text_->text();

			//paste
			text_->selectAll();
			text_->paste();
			text_->deselect();

			//check file exists
			if (!QFile::exists(text_->text()))
			{
				GUIHelper::showMessage("Error", "File '" + text_->text() + "' does not exist!");
				text_->setText(previous);
			}
		}
		else if(selected->text()=="Delete")
		{
			text_->clear();
		}
		else if(selected->text()=="Open")
		{
			QDesktopServices::openUrl("file:///" + text_->text());
		}
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hyphenimp.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:40:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _LINGU2_HYPHENIMP_HXX_
#define _LINGU2_HYPHENIMP_HXX_

#include <uno/lbnames.h>            // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type
#include <cppuhelper/implbase1.hxx> // helper for implementations
#include <cppuhelper/implbase6.hxx> // helper for implementations

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEDISPLAYNAME_HPP_
#include <com/sun/star/lang/XServiceDisplayName.hpp>
#endif
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/PropertyValues.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/linguistic2/XHyphenator.hpp>
#include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp>
#include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp>

#ifndef _TOOLS_TABLE_HXX
#include <tools/table.hxx>
#endif

#include <unotools/charclass.hxx>

#include <linguistic/misc.hxx>
#include "hprophelp.hxx"
#include <stdio.h>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;

#define A2OU(x) ::rtl::OUString::createFromAscii( x )

#define OU2A(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ASCII_US).getStr()

#define OU2UTF8(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_UTF8).getStr()

#define OU2ISO_1(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ISO_8859_1).getStr()

#define OU2ENC(rtlOUString, rtlEncoding)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), rtlEncoding).getStr()

///////////////////////////////////////////////////////////////////////////

struct HDInfo {
  HyphenDict *     aPtr;
  OUString         aName;
  Locale           aLoc;
  rtl_TextEncoding aEnc;
  CharClass *      apCC;
};

class Hyphenator :
    public cppu::WeakImplHelper6
    <
        XHyphenator,
        XLinguServiceEventBroadcaster,
        XInitialization,
        XComponent,
        XServiceInfo,
        XServiceDisplayName
    >
{
    Sequence< Locale >                      aSuppLocales;
        HDInfo * aDicts;
        sal_Int32 numdict;

    ::cppu::OInterfaceContainerHelper       aEvtListeners;
    Reference< XPropertyChangeListener >    xPropHelper;
    Reference< XMultiServiceFactory > rSMgr;
    PropertyHelper_Hyphen *                 pPropHelper;
    BOOL                                    bDisposing;

    // disallow copy-constructor and assignment-operator for now
    Hyphenator(const Hyphenator &);
    Hyphenator & operator = (const Hyphenator &);

    PropertyHelper_Hyphen & GetPropHelper_Impl();
    PropertyHelper_Hyphen & GetPropHelper()
    {
        return pPropHelper ? *pPropHelper : GetPropHelper_Impl();
    }

public:
    Hyphenator();

    virtual ~Hyphenator();

    // XSupportedLocales (for XHyphenator)
    virtual Sequence< Locale > SAL_CALL getLocales()
        throw(RuntimeException);
    virtual sal_Bool SAL_CALL hasLocale( const Locale& rLocale )
        throw(RuntimeException);

    // XHyphenator
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL
    hyphenate( const ::rtl::OUString& aWord,
           const ::com::sun::star::lang::Locale& aLocale,
           sal_Int16 nMaxLeading,
           const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL
    queryAlternativeSpelling( const ::rtl::OUString& aWord,
                  const ::com::sun::star::lang::Locale& aLocale,
                  sal_Int16 nIndex,
                  const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XPossibleHyphens > SAL_CALL
    createPossibleHyphens( const ::rtl::OUString& aWord,
                   const ::com::sun::star::lang::Locale& aLocale,
                   const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    // XLinguServiceEventBroadcaster
    virtual sal_Bool SAL_CALL
        addLinguServiceEventListener(
            const Reference< XLinguServiceEventListener >& rxLstnr )
            throw(RuntimeException);
    virtual sal_Bool SAL_CALL
        removeLinguServiceEventListener(
            const Reference< XLinguServiceEventListener >& rxLstnr )
            throw(RuntimeException);

    // XServiceDisplayName
    virtual OUString SAL_CALL
        getServiceDisplayName( const Locale& rLocale )
            throw(RuntimeException);

    // XInitialization
    virtual void SAL_CALL
        initialize( const Sequence< Any >& rArguments )
            throw(Exception, RuntimeException);

    // XComponent
    virtual void SAL_CALL
        dispose()
            throw(RuntimeException);
    virtual void SAL_CALL
        addEventListener( const Reference< XEventListener >& rxListener )
            throw(RuntimeException);
    virtual void SAL_CALL
        removeEventListener( const Reference< XEventListener >& rxListener )
            throw(RuntimeException);

    ////////////////////////////////////////////////////////////
    // Service specific part
    //

    // XServiceInfo
    virtual OUString SAL_CALL
        getImplementationName()
            throw(RuntimeException);
    virtual sal_Bool SAL_CALL
        supportsService( const OUString& rServiceName )
            throw(RuntimeException);
    virtual Sequence< OUString > SAL_CALL
        getSupportedServiceNames()
            throw(RuntimeException);

    static inline OUString
        getImplementationName_Static() throw();
    static Sequence< OUString >
        getSupportedServiceNames_Static() throw();

private:
        OUString SAL_CALL makeLowerCase(const OUString&, CharClass *);

};

inline OUString Hyphenator::getImplementationName_Static() throw()
{
    return A2OU( "org.openoffice.lingu.LibHnjHyphenator" );
}

///////////////////////////////////////////////////////////////////////////

#endif

<commit_msg>INTEGRATION: CWS hyphenator2 (1.6.28); FILE MERGED 2006/01/27 00:44:15 nemeth 1.6.28.1: i61214 i58558<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hyphenimp.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2006-02-06 16:23:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _LINGU2_HYPHENIMP_HXX_
#define _LINGU2_HYPHENIMP_HXX_

#include <uno/lbnames.h>            // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type
#include <cppuhelper/implbase1.hxx> // helper for implementations
#include <cppuhelper/implbase6.hxx> // helper for implementations

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEDISPLAYNAME_HPP_
#include <com/sun/star/lang/XServiceDisplayName.hpp>
#endif
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/PropertyValues.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/linguistic2/XHyphenator.hpp>
#include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp>
#include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp>

#ifndef _TOOLS_TABLE_HXX
#include <tools/table.hxx>
#endif

#include <unotools/charclass.hxx>

#include <linguistic/misc.hxx>
#include "hprophelp.hxx"
#include <stdio.h>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;

#define A2OU(x) ::rtl::OUString::createFromAscii( x )

#define OU2A(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ASCII_US).getStr()

#define OU2UTF8(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_UTF8).getStr()

#define OU2ISO_1(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ISO_8859_1).getStr()

#define OU2ENC(rtlOUString, rtlEncoding)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), rtlEncoding).getStr()

///////////////////////////////////////////////////////////////////////////

struct HDInfo {
  HyphenDict *     aPtr;
  OUString         aName;
  Locale           aLoc;
  rtl_TextEncoding aEnc;
  CharClass *      apCC;
};

class Hyphenator :
    public cppu::WeakImplHelper6
    <
        XHyphenator,
        XLinguServiceEventBroadcaster,
        XInitialization,
        XComponent,
        XServiceInfo,
        XServiceDisplayName
    >
{
    Sequence< Locale >                      aSuppLocales;
        HDInfo * aDicts;
        sal_Int32 numdict;

    ::cppu::OInterfaceContainerHelper       aEvtListeners;
    Reference< XPropertyChangeListener >    xPropHelper;
    Reference< XMultiServiceFactory > rSMgr;
    PropertyHelper_Hyphen *                 pPropHelper;
    BOOL                                    bDisposing;

    // disallow copy-constructor and assignment-operator for now
    Hyphenator(const Hyphenator &);
    Hyphenator & operator = (const Hyphenator &);

    PropertyHelper_Hyphen & GetPropHelper_Impl();
    PropertyHelper_Hyphen & GetPropHelper()
    {
        return pPropHelper ? *pPropHelper : GetPropHelper_Impl();
    }

public:
    Hyphenator();

    virtual ~Hyphenator();

    // XSupportedLocales (for XHyphenator)
    virtual Sequence< Locale > SAL_CALL getLocales()
        throw(RuntimeException);
    virtual sal_Bool SAL_CALL hasLocale( const Locale& rLocale )
        throw(RuntimeException);

    // XHyphenator
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL
    hyphenate( const ::rtl::OUString& aWord,
           const ::com::sun::star::lang::Locale& aLocale,
           sal_Int16 nMaxLeading,
           const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL
    queryAlternativeSpelling( const ::rtl::OUString& aWord,
                  const ::com::sun::star::lang::Locale& aLocale,
                  sal_Int16 nIndex,
                  const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XPossibleHyphens > SAL_CALL
    createPossibleHyphens( const ::rtl::OUString& aWord,
                   const ::com::sun::star::lang::Locale& aLocale,
                   const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    // XLinguServiceEventBroadcaster
    virtual sal_Bool SAL_CALL
        addLinguServiceEventListener(
            const Reference< XLinguServiceEventListener >& rxLstnr )
            throw(RuntimeException);
    virtual sal_Bool SAL_CALL
        removeLinguServiceEventListener(
            const Reference< XLinguServiceEventListener >& rxLstnr )
            throw(RuntimeException);

    // XServiceDisplayName
    virtual OUString SAL_CALL
        getServiceDisplayName( const Locale& rLocale )
            throw(RuntimeException);

    // XInitialization
    virtual void SAL_CALL
        initialize( const Sequence< Any >& rArguments )
            throw(Exception, RuntimeException);

    // XComponent
    virtual void SAL_CALL
        dispose()
            throw(RuntimeException);
    virtual void SAL_CALL
        addEventListener( const Reference< XEventListener >& rxListener )
            throw(RuntimeException);
    virtual void SAL_CALL
        removeEventListener( const Reference< XEventListener >& rxListener )
            throw(RuntimeException);

    ////////////////////////////////////////////////////////////
    // Service specific part
    //

    // XServiceInfo
    virtual OUString SAL_CALL
        getImplementationName()
            throw(RuntimeException);
    virtual sal_Bool SAL_CALL
        supportsService( const OUString& rServiceName )
            throw(RuntimeException);
    virtual Sequence< OUString > SAL_CALL
        getSupportedServiceNames()
            throw(RuntimeException);

    static inline OUString
        getImplementationName_Static() throw();
    static Sequence< OUString >
        getSupportedServiceNames_Static() throw();

private:
        sal_uInt16 SAL_CALL capitalType(const OUString&, CharClass *);
        OUString SAL_CALL makeLowerCase(const OUString&, CharClass *);
        OUString SAL_CALL makeUpperCase(const OUString&, CharClass *);
        OUString SAL_CALL makeInitCap(const OUString&, CharClass *);
};

inline OUString Hyphenator::getImplementationName_Static() throw()
{
    return A2OU( "org.openoffice.lingu.LibHnjHyphenator" );
}

///////////////////////////////////////////////////////////////////////////

#endif

<|endoftext|>