<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2015, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

/** @file
 * Definitions for ConnectionsPerformanceTest
 */

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

#ifndef NTA_CONNECTIONS_PERFORMANCE_TEST
#define NTA_CONNECTIONS_PERFORMANCE_TEST

#include <nupic/algorithms/Connections.hpp>

using namespace nupic::algorithms::connections;

namespace nupic
{

  class ConnectionsPerformanceTest
  {
  public:
    ConnectionsPerformanceTest() {}
    virtual ~ConnectionsPerformanceTest() {}

    // Run all appropriate tests
    virtual void RunTests();

  private:
    void testTemporalMemoryUsage();
    void testSpatialPoolerUsage();

    void checkpoint(clock_t timer, std::string text);
    std::vector<Cell> randomSDR(UInt n, UInt w);

  }; // end class ConnectionsPerformanceTest

} // end namespace nupic

#endif // NTA_CONNECTIONS_PERFORMANCE_TEST
<commit_msg>Made some functions public<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2015, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

/** @file
 * Definitions for ConnectionsPerformanceTest
 */

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

#ifndef NTA_CONNECTIONS_PERFORMANCE_TEST
#define NTA_CONNECTIONS_PERFORMANCE_TEST

#include <nupic/algorithms/Connections.hpp>

using namespace nupic::algorithms::connections;

namespace nupic
{

  class ConnectionsPerformanceTest
  {
  public:
    ConnectionsPerformanceTest() {}
    virtual ~ConnectionsPerformanceTest() {}

    // Run all appropriate tests
    virtual void RunTests();

    void testTemporalMemoryUsage();
    void testSpatialPoolerUsage();

  private:
    void checkpoint(clock_t timer, std::string text);
    std::vector<Cell> randomSDR(UInt n, UInt w);

  }; // end class ConnectionsPerformanceTest

} // end namespace nupic

#endif // NTA_CONNECTIONS_PERFORMANCE_TEST
<|endoftext|>


<commit_before>#include <array>
#include <iostream>
#include <memory>

using namespace std;

template<class T>
class Matrix {
	array<int, 2> dim;
	T *elem;
	template<class S>
		friend Matrix<S> operator+(const Matrix<S> &T1, const Matrix<S> &T2);
	template<class R>
		friend ostream& operator<<(ostream &os, const Matrix<R>& M);
public:
	Matrix(int d1, int d2): dim{{d1, d2}}, elem { new T[d1*d2] } {}
	size_t size() const { return dim[0]*dim[1]; }

	Matrix(const Matrix &);
	Matrix &operator=(const Matrix &);

	Matrix(Matrix&&);
	Matrix& operator=(Matrix&&);

	~Matrix() { delete[] elem; }

	T& operator[](size_t i);
};

template<class T>
ostream& operator<<(ostream &os, const Matrix<T>& M) {
	auto n = M.size();
	for (size_t i = 0; i != n; ++i) {
		os << M.elem[i] << " ";
	}
	return os;
}

template<class T>
Matrix<T> operator+(const Matrix<T> &T1, const Matrix<T> &T2) {
	if (T1.dim[0] != T2.dim[0] || T1.dim[1] != T2.dim[1]) {
		throw runtime_error("bad size in Matrix +");
	}
	cout << "I am in operator+ " << endl;
	Matrix<T> tmp{T1.dim[0], T1.dim[1]};
	auto n = T1.size();
	for (size_t i = 0; i != n; ++i) {
		tmp.elem[i] = T1.elem[i] + T2.elem[i];
	}
	return tmp;
}

template<class T>
Matrix<T>::Matrix(Matrix&& m):
	dim(m.dim),
	elem{m.elem} {
		cout << "Call the move constructor " << endl;
		m.dim = {{0, 0}};
		m.elem = nullptr;
}

template<class T>
Matrix<T>& Matrix<T>::operator=(Matrix&& m) {
	cout << "Call the move operator= " << endl;
	swap(dim, m.dim);
	swap(elem, m.elem);
	return *this;
}

template<class T>
Matrix<T>::Matrix(const Matrix& m):
	dim(m.dim),
	elem{new T[m.size()]} {
		cout << "Call the copy constructor " << endl;
		uninitialized_copy(m.elem, m.elem+m.size(), elem);
	}

template<class T>
Matrix<T>& Matrix<T>::operator=(const Matrix& m) {
	cout << "Call the operator= " << endl;
	if (dim[0] != m.dim[0] || dim[1] != m.dim[1]) {
		throw runtime_error("bad size in Matrix =");
	}
	copy(m.elem, m.elem+m.size(), elem);
	return *this;
}

template<class T>
T& Matrix<T>::operator[](size_t i) {
	if (i < size()) {
		return elem[i];
	}
	return elem[0];
}

int f() {
	int i = 0;
	cout << i << endl;
	return i;
}

int main() {

	Matrix<int> m0(10, 9);
	for (size_t i = 0; i < m0.size(); ++i) {
		m0[i] = i;
	}
	cout << m0 << endl;
	Matrix<int> m1{m0};
	cout << m1 << endl;
	Matrix<int> m2(10, 9);
	m2 = m0;
	for (size_t i = 0; i < m2.size(); ++i) {
		m2[i] = -i;
	}
	cout << m2 << endl;
	cout << "creating m3" << endl;
	Matrix<int> m3 = m0 + m2;
	cout << m3 << endl;
	cout << "creating m4" << endl;
	Matrix<int> m4 = m0;
	m4 = m0 + m2;
	cout << m4 << endl;
	return 0;
}
<commit_msg>Define operator+=  and use it in operator+<commit_after>#include <array>
#include <iostream>
#include <memory>

using namespace std;

template<class T>
class Matrix {
	array<int, 2> dim;
	T *elem;
	template<class S>
		friend Matrix<S> operator+(const Matrix<S> &T1, const Matrix<S> &T2);
	template<class R>
		friend ostream& operator<<(ostream &os, const Matrix<R>& M);
public:
	Matrix(int d1, int d2): dim{{d1, d2}}, elem { new T[d1*d2] } {}
	size_t size() const { return dim[0]*dim[1]; }

	Matrix(const Matrix &);
	Matrix &operator=(const Matrix &);

	Matrix(Matrix&&);
	Matrix& operator=(Matrix&&);

	~Matrix() { delete[] elem; }

	T& operator[](size_t i);
	Matrix& operator+=(const Matrix &);
};

template<class T>
ostream& operator<<(ostream &os, const Matrix<T>& M) {
	auto n = M.size();
	for (size_t i = 0; i != n; ++i) {
		os << M.elem[i] << " ";
	}
	return os;
}

template<class T>
Matrix<T> operator+(const Matrix<T> &T1, const Matrix<T> &T2) {

	cout << "I am in operator+ " << endl;
	Matrix<T> res {T1};
	res += T2;
	return res;
}

template<class T>
Matrix<T> &Matrix<T>::operator+=(const Matrix<T> &a) {
	if (dim[0] != a.dim[0] || dim[1] != a.dim[1]) {
		throw runtime_error("Bad Matrix += argument");
	}
	cout << "I am in operator+= " << endl;

	T* p = elem;
	T* q = a.elem;
	T* end = elem + dim[0]*dim[1];
	while (p != end) {
		*p++ = *q++;
	}

	return *this;
}

template<class T>
Matrix<T>::Matrix(Matrix&& m):
	dim(m.dim),
	elem{m.elem} {
		cout << "Call the move constructor " << endl;
		m.dim = {{0, 0}};
		m.elem = nullptr;
}

template<class T>
Matrix<T>& Matrix<T>::operator=(Matrix&& m) {
	cout << "Call the move operator= " << endl;
	swap(dim, m.dim);
	swap(elem, m.elem);
	return *this;
}

template<class T>
Matrix<T>::Matrix(const Matrix& m):
	dim(m.dim),
	elem{new T[m.size()]} {
		cout << "Call the copy constructor " << endl;
		uninitialized_copy(m.elem, m.elem+m.size(), elem);
	}

template<class T>
Matrix<T>& Matrix<T>::operator=(const Matrix& m) {
	cout << "Call the operator= " << endl;
	if (dim[0] != m.dim[0] || dim[1] != m.dim[1]) {
		throw runtime_error("bad size in Matrix =");
	}
	copy(m.elem, m.elem+m.size(), elem);
	return *this;
}

template<class T>
T& Matrix<T>::operator[](size_t i) {
	if (i < size()) {
		return elem[i];
	}
	return elem[0];
}

int f() {
	int i = 0;
	cout << i << endl;
	return i;
}

int main() {

	Matrix<int> m0(10, 9);
	for (size_t i = 0; i < m0.size(); ++i) {
		m0[i] = i;
	}
	cout << m0 << endl;
	Matrix<int> m1{m0};
	cout << m1 << endl;
	Matrix<int> m2(10, 9);
	m2 = m0;
	for (size_t i = 0; i < m2.size(); ++i) {
		m2[i] = -i;
	}
	cout << m2 << endl;
	cout << "creating m3" << endl;
	Matrix<int> m3 = m0 + m2;
	cout << m3 << endl;
	cout << "creating m4" << endl;
	Matrix<int> m4 = m0;
	m4 = m0 + m2;
	cout << m4 << endl;
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vpp/image2d.hh>

int main()
{
  using vpp::boxNd_iterator;
  using vpp::image2d;
  using vpp::vint2;

  image2d<int> img(3, 3);

  vint2 ref[] = {
    vint2(0, 0),
    vint2(0, 1),
    vint2(0, 2),
    vint2(1, 0),
    vint2(1, 1),
    vint2(1, 2),
    vint2(2, 0),
    vint2(2, 1),
    vint2(2, 2)
  };

  int i = 0;
  for (auto p : img)
  {
    assert(p.addr() == &img(ref[i]));
    assert(p.coord() == ref[i]);
    i++;
  }

}
<commit_msg>Fix imageNd_iterator test for the new api<commit_after>#include <iostream>
#include <vpp/image2d.hh>

int main()
{
  using vpp::boxNd_iterator;
  using vpp::image2d;
  using vpp::vint2;

  image2d<int> img(3, 3);

  vint2 ref[] = {
    vint2(0, 0),
    vint2(0, 1),
    vint2(0, 2),
    vint2(1, 0),
    vint2(1, 1),
    vint2(1, 2),
    vint2(2, 0),
    vint2(2, 1),
    vint2(2, 2)
  };

  int i = 0;
  for (auto& p : img)
  {
    assert(&p == &img(ref[i]));
    i++;
  }
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * tests/net/test-stream.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <c7a/net/stream.hpp>

using::testing::_;
using::testing::InvokeArgument;
using::testing::Return;
using::testing::ByRef;

using namespace c7a::net;
using namespace c7a;

struct StreamTest : public::testing::Test {
    StreamTest()
    {
        candidate.channel_id = 2;
        candidate.num_elements = 3;
        candidate.boundaries = data;
    }

    size_t                   data[3] = { 22, 23, 55 };
    struct StreamBlockHeader candidate;
};

TEST_F(StreamTest, StreamBlockHeaderParsesAndSerializesIdAndNumElements) {
    auto seri = candidate.Serialize();
    struct StreamBlockHeader result;
    result.ParseIdAndNumElem(seri);

    ASSERT_EQ(candidate.channel_id, result.channel_id);
    ASSERT_EQ(candidate.num_elements, result.num_elements);
}

TEST_F(StreamTest, StreamBlockHeaderParsesAndSerializesBoundaries) {
    auto seri = candidate.Serialize();
    struct StreamBlockHeader result;
    result.ParseIdAndNumElem(seri);
    result.ParseBoundaries(seri);

    ASSERT_EQ(22, result.boundaries[0]);
    ASSERT_EQ(23, result.boundaries[1]);
    ASSERT_EQ(55, result.boundaries[2]);
}
<commit_msg>more tests on stream block header<commit_after>/*******************************************************************************
 * tests/net/test-stream.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <c7a/net/stream.hpp>

using::testing::_;
using::testing::InvokeArgument;
using::testing::Return;
using::testing::ByRef;

using namespace c7a::net;
using namespace c7a;

struct StreamTest : public::testing::Test {
    StreamTest()
    {
        candidate.channel_id = 2;
        candidate.num_elements = 3;
        candidate.boundaries = data;
    }

    size_t                   data[3] = { 22, 23, 55 };
    struct StreamBlockHeader candidate;
};

TEST_F(StreamTest, StreamBlockHeaderParsesAndSerializesIdAndNumElements) {
    auto seri = candidate.Serialize();
    struct StreamBlockHeader result;
    result.ParseIdAndNumElem(seri);

    ASSERT_EQ(candidate.channel_id, result.channel_id);
    ASSERT_EQ(candidate.num_elements, result.num_elements);
}

TEST_F(StreamTest, StreamBlockHeaderParsesAndSerializesBoundaries) {
    auto seri = candidate.Serialize();
    struct StreamBlockHeader result;
    result.ParseIdAndNumElem(seri);
    result.ParseBoundaries(seri);

    ASSERT_EQ(22, result.boundaries[0]);
    ASSERT_EQ(23, result.boundaries[1]);
    ASSERT_EQ(55, result.boundaries[2]);
}

TEST_F(StreamTest, StreamBlockHeaderParsesAndSerializesBoundariesIfEmpty) {
    candidate.num_elements = 0;
    auto seri = candidate.Serialize();
    struct StreamBlockHeader result;
    result.ParseIdAndNumElem(seri);
    result.ParseBoundaries(seri);

    ASSERT_EQ(0, result.num_elements);
}

TEST_F(StreamTest, StreamBlockHeaderIsStreamEnd) {
    ASSERT_EQ(false, candidate.IsStreamEnd());
    candidate.num_elements = 0;
    ASSERT_EQ(true, candidate.IsStreamEnd());
}
<|endoftext|>


<commit_before>#include <v8.h>
#include <node.h>
#include <node_buffer.h>

#include <sstream>
#include <cstring>
#include <string>

using namespace v8;
using namespace node;

namespace {

// this is an application of the Curiously Recurring Template Pattern
template <class Derived> struct UnaryAction {
	Handle<Value> apply(Buffer& buffer, const Arguments& args, HandleScope& scope);

	Handle<Value> operator()(const Arguments& args) {
		HandleScope scope;
		return static_cast<Derived*>(this)->apply(*Buffer::Unwrap<Buffer>(args.This()), args, scope);
	}
};

template <class Derived> struct BinaryAction {
	Handle<Value> apply(Buffer& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope);

	Handle<Value> operator()(const Arguments& args) {
		HandleScope scope;

		Buffer& buffer = *Buffer::Unwrap<Buffer>(args.This());
		if (args[0]->IsString()) {
			String::AsciiValue s(args[0]->ToString());
			return static_cast<Derived*>(this)->apply(buffer, *s, s.length(), args, scope);
		}
		if (Buffer::HasInstance(args[0])) {
			Buffer& other = *Buffer::Unwrap<Buffer>(args[0]->ToObject());
			return static_cast<Derived*>(this)->apply(buffer, other.data(), other.length(), args, scope);
		}

		static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New(
				"Second argument must be a string or a buffer."));
		return ThrowException(Exception::TypeError(illegalArgumentException));
	}
};

//
// helper functions
//
Handle<Value> clear(Buffer& buffer, int c) {
	memset(buffer.data(), c, buffer.length());
	return buffer.handle_;
}

Handle<Value> fill(Buffer& buffer, void* pattern, size_t size) {
	if (size >= buffer.length()) {
		memcpy(buffer.data(), pattern, buffer.length());
	} else {
		const int n_copies = buffer.length() / size;
		const int remainder = buffer.length() % size;
		for (int i = 0; i < n_copies; i++) {
			memcpy(buffer.data() + size * i, pattern, size);
		}
		memcpy(buffer.data() + size * n_copies, pattern, remainder);
	}
	return buffer.handle_;
}

int compare(Buffer& a, const char* data, size_t length) {
	if (a.length() != length) {
		return a.length() > length ? 1 : -1;
	}
	return memcmp(a.data(), data, length);
}

//
// actions
//
struct ClearAction: UnaryAction<ClearAction> {
	Handle<Value> apply(Buffer& buffer, const Arguments& args, HandleScope& scope) {
		return clear(buffer, 0);
	}
};

struct FillAction: UnaryAction<FillAction> {
	Handle<Value> apply(Buffer& buffer, const Arguments& args, HandleScope& scope) {
		if (args[0]->IsInt32()) {
			int c = args[0]->ToInt32()->Int32Value();
			return clear(buffer, c);
		}

		if (args[0]->IsString()) {
			String::AsciiValue s(args[0]->ToString());
			return fill(buffer, *s, s.length());
		}

		if (Buffer::HasInstance(args[0])) {
			Buffer& other = *Buffer::Unwrap<Buffer>(args[0]->ToObject());
			return fill(buffer, other.data(), other.length());
		}

		static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New(
				"Second argument should be either a string, a buffer or an integer."));
		return ThrowException(Exception::TypeError(illegalArgumentException));
	}
};

struct EqualsAction: BinaryAction<EqualsAction> {
	Handle<Value> apply(Buffer& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) {
		return compare(buffer, data, size) == 0 ? True() : False();
	}
};

struct CompareAction: BinaryAction<CompareAction> {
	Handle<Value> apply(Buffer& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) {
		return scope.Close(Integer::New(compare(buffer, data, size)));
	}
};

struct IndexOfAction: BinaryAction<IndexOfAction> {
	Handle<Value> apply(Buffer& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) {
		// FIXME memmem is a GNU extension
		const char* p = (const char*) memmem(buffer.data(), buffer.length(), data, size);
		// FIXME ptrdiff_t may be larger than the range of a JS integer
		const ptrdiff_t offset = p ? p - buffer.data() : -1;
		return scope.Close(Integer::New(offset));
	}
};

static char toHexTable[] = "0123456789abcdef";

// CHECKME is this cache efficient?
static char fromHexTable[] = {
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,
		10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};

inline Handle<Value> decodeHex(const char* data, size_t size, const Arguments& args, HandleScope& scope) {
	if (size & 1) {
		return ThrowException(Exception::Error(String::New(
				"Odd string length, this is not hexadecimal data.")));
	}

	if (size == 0) {
		return String::Empty();
	}

	Buffer& buffer = *Buffer::New(size / 2);
	for (char* s = buffer.data(); size > 0; size -= 2) {
		int a = fromHexTable[*data++];
		int b = fromHexTable[*data++];

		if (a == -1 || b == -1) {
			return ThrowException(Exception::Error(String::New(
					"This is not hexadecimal data.")));
		}

		*s++ = b | (a << 4);
	}

	return buffer.handle_;
}

struct FromHexAction: UnaryAction<FromHexAction> {
	Handle<Value> apply(Buffer& buffer, const Arguments& args, HandleScope& scope) {
		return decodeHex(buffer.data(), buffer.length(), args, scope);
	}
};

struct ToHexAction: UnaryAction<ToHexAction> {
	Handle<Value> apply(Buffer& buffer, const Arguments& args, HandleScope& scope) {
		const size_t size = buffer.length();

		if (size == 0) {
			return String::Empty();
		}

		std::string s(size * 2, 0);
		for (size_t i = 0; i < size; ++i) {
			const int c = buffer.data()[i];
			s[i * 2] = toHexTable[c >> 4];
			s[i * 2 + 1] = toHexTable[c & 15];
		}

		return scope.Close(String::New(s.c_str(), s.size()));
	}
};

//
// V8 function callbacks
//
Handle<Value> Clear(const Arguments& args) {
	return ClearAction()(args);
}

Handle<Value> Fill(const Arguments& args) {
	return FillAction()(args);
}

Handle<Value> Equals(const Arguments& args) {
	return EqualsAction()(args);
}

Handle<Value> Compare(const Arguments& args) {
	return CompareAction()(args);
}

Handle<Value> IndexOf(const Arguments& args) {
	return IndexOfAction()(args);
}

Handle<Value> FromHex(const Arguments& args) {
	return FromHexAction()(args);
}

Handle<Value> ToHex(const Arguments& args) {
	return ToHexAction()(args);
}

Handle<Value> Concat(const Arguments& args) {
	HandleScope scope;

	size_t size = 0;
	for (int index = 0, length = args.Length(); index < length; ++index) {
		Local<Value> arg = args[index];
		if (arg->IsString()) {
			// Utf8Length() because we need the length in bytes, not characters
			size += arg->ToString()->Utf8Length();
		}
		else if (Buffer::HasInstance(arg)) {
			Buffer& b = *Buffer::Unwrap<Buffer>(arg->ToObject());
			size += b.length();
		}
		else {
			std::stringstream s;
			s << "Argument #" << index << " is neither a string nor a buffer object.";
			const char* message = s.str().c_str();
			return ThrowException(Exception::TypeError(String::New(message)));
		}
	}

	Buffer& dst = *Buffer::New(size);
	char* s = dst.data();

	for (int index = 0, length = args.Length(); index < length; ++index) {
		Local<Value> arg = args[index];
		if (arg->IsString()) {
			String::Utf8Value v(arg->ToString());
			memcpy(s, *v, v.length());
			s += v.length();
		}
		else if (Buffer::HasInstance(arg)) {
			Buffer& b = *Buffer::Unwrap<Buffer>(arg->ToObject());
			memcpy(s, b.data(), b.length());
			s += b.length();
		}
		else {
			return ThrowException(Exception::Error(String::New(
					"Congratulations! You have run into a bug: argument is neither a string nor a buffer object. "
					"Please make the world a better place and report it.")));
		}
	}

	return scope.Close(dst.handle_);
}

extern "C" void init(Handle<Object> target) {
	HandleScope scope;

	target->Set(String::NewSymbol("concat"), FunctionTemplate::New(Concat)->GetFunction());

	Local<Object> proto = Buffer::New(0)->handle_->GetPrototype()->ToObject();
	proto->Set(String::NewSymbol("fill"), FunctionTemplate::New(Fill)->GetFunction());
	proto->Set(String::NewSymbol("clear"), FunctionTemplate::New(Clear)->GetFunction());
	proto->Set(String::NewSymbol("equals"), FunctionTemplate::New(Equals)->GetFunction());
	proto->Set(String::NewSymbol("compare"), FunctionTemplate::New(Compare)->GetFunction());
	proto->Set(String::NewSymbol("indexOf"), FunctionTemplate::New(IndexOf)->GetFunction());
	proto->Set(String::NewSymbol("fromHex"), FunctionTemplate::New(FromHex)->GetFunction());
	proto->Set(String::NewSymbol("toHex"), FunctionTemplate::New(ToHex)->GetFunction());
}

}
<commit_msg>Convert string argument to UTF-8, not ASCII.<commit_after>#include <v8.h>
#include <node.h>
#include <node_buffer.h>

#include <sstream>
#include <cstring>
#include <string>

using namespace v8;
using namespace node;

namespace {

// this is an application of the Curiously Recurring Template Pattern
template <class Derived> struct UnaryAction {
	Handle<Value> apply(Buffer& buffer, const Arguments& args, HandleScope& scope);

	Handle<Value> operator()(const Arguments& args) {
		HandleScope scope;
		return static_cast<Derived*>(this)->apply(*Buffer::Unwrap<Buffer>(args.This()), args, scope);
	}
};

template <class Derived> struct BinaryAction {
	Handle<Value> apply(Buffer& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope);

	Handle<Value> operator()(const Arguments& args) {
		HandleScope scope;

		Buffer& buffer = *Buffer::Unwrap<Buffer>(args.This());
		if (args[0]->IsString()) {
			String::Utf8Value s(args[0]->ToString());
			return static_cast<Derived*>(this)->apply(buffer, *s, s.length(), args, scope);
		}
		if (Buffer::HasInstance(args[0])) {
			Buffer& other = *Buffer::Unwrap<Buffer>(args[0]->ToObject());
			return static_cast<Derived*>(this)->apply(buffer, other.data(), other.length(), args, scope);
		}

		static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New(
				"Second argument must be a string or a buffer."));
		return ThrowException(Exception::TypeError(illegalArgumentException));
	}
};

//
// helper functions
//
Handle<Value> clear(Buffer& buffer, int c) {
	memset(buffer.data(), c, buffer.length());
	return buffer.handle_;
}

Handle<Value> fill(Buffer& buffer, void* pattern, size_t size) {
	if (size >= buffer.length()) {
		memcpy(buffer.data(), pattern, buffer.length());
	} else {
		const int n_copies = buffer.length() / size;
		const int remainder = buffer.length() % size;
		for (int i = 0; i < n_copies; i++) {
			memcpy(buffer.data() + size * i, pattern, size);
		}
		memcpy(buffer.data() + size * n_copies, pattern, remainder);
	}
	return buffer.handle_;
}

int compare(Buffer& a, const char* data, size_t length) {
	if (a.length() != length) {
		return a.length() > length ? 1 : -1;
	}
	return memcmp(a.data(), data, length);
}

//
// actions
//
struct ClearAction: UnaryAction<ClearAction> {
	Handle<Value> apply(Buffer& buffer, const Arguments& args, HandleScope& scope) {
		return clear(buffer, 0);
	}
};

struct FillAction: UnaryAction<FillAction> {
	Handle<Value> apply(Buffer& buffer, const Arguments& args, HandleScope& scope) {
		if (args[0]->IsInt32()) {
			int c = args[0]->ToInt32()->Int32Value();
			return clear(buffer, c);
		}

		if (args[0]->IsString()) {
			String::Utf8Value s(args[0]->ToString());
			return fill(buffer, *s, s.length());
		}

		if (Buffer::HasInstance(args[0])) {
			Buffer& other = *Buffer::Unwrap<Buffer>(args[0]->ToObject());
			return fill(buffer, other.data(), other.length());
		}

		static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New(
				"Second argument should be either a string, a buffer or an integer."));
		return ThrowException(Exception::TypeError(illegalArgumentException));
	}
};

struct EqualsAction: BinaryAction<EqualsAction> {
	Handle<Value> apply(Buffer& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) {
		return compare(buffer, data, size) == 0 ? True() : False();
	}
};

struct CompareAction: BinaryAction<CompareAction> {
	Handle<Value> apply(Buffer& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) {
		return scope.Close(Integer::New(compare(buffer, data, size)));
	}
};

struct IndexOfAction: BinaryAction<IndexOfAction> {
	Handle<Value> apply(Buffer& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) {
		// FIXME memmem is a GNU extension
		const char* p = (const char*) memmem(buffer.data(), buffer.length(), data, size);
		// FIXME ptrdiff_t may be larger than the range of a JS integer
		const ptrdiff_t offset = p ? p - buffer.data() : -1;
		return scope.Close(Integer::New(offset));
	}
};

static char toHexTable[] = "0123456789abcdef";

// CHECKME is this cache efficient?
static char fromHexTable[] = {
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,
		10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};

inline Handle<Value> decodeHex(const char* data, size_t size, const Arguments& args, HandleScope& scope) {
	if (size & 1) {
		return ThrowException(Exception::Error(String::New(
				"Odd string length, this is not hexadecimal data.")));
	}

	if (size == 0) {
		return String::Empty();
	}

	Buffer& buffer = *Buffer::New(size / 2);
	for (char* s = buffer.data(); size > 0; size -= 2) {
		int a = fromHexTable[*data++];
		int b = fromHexTable[*data++];

		if (a == -1 || b == -1) {
			return ThrowException(Exception::Error(String::New(
					"This is not hexadecimal data.")));
		}

		*s++ = b | (a << 4);
	}

	return buffer.handle_;
}

struct FromHexAction: UnaryAction<FromHexAction> {
	Handle<Value> apply(Buffer& buffer, const Arguments& args, HandleScope& scope) {
		return decodeHex(buffer.data(), buffer.length(), args, scope);
	}
};

struct ToHexAction: UnaryAction<ToHexAction> {
	Handle<Value> apply(Buffer& buffer, const Arguments& args, HandleScope& scope) {
		const size_t size = buffer.length();

		if (size == 0) {
			return String::Empty();
		}

		std::string s(size * 2, 0);
		for (size_t i = 0; i < size; ++i) {
			const int c = buffer.data()[i];
			s[i * 2] = toHexTable[c >> 4];
			s[i * 2 + 1] = toHexTable[c & 15];
		}

		return scope.Close(String::New(s.c_str(), s.size()));
	}
};

//
// V8 function callbacks
//
Handle<Value> Clear(const Arguments& args) {
	return ClearAction()(args);
}

Handle<Value> Fill(const Arguments& args) {
	return FillAction()(args);
}

Handle<Value> Equals(const Arguments& args) {
	return EqualsAction()(args);
}

Handle<Value> Compare(const Arguments& args) {
	return CompareAction()(args);
}

Handle<Value> IndexOf(const Arguments& args) {
	return IndexOfAction()(args);
}

Handle<Value> FromHex(const Arguments& args) {
	return FromHexAction()(args);
}

Handle<Value> ToHex(const Arguments& args) {
	return ToHexAction()(args);
}

Handle<Value> Concat(const Arguments& args) {
	HandleScope scope;

	size_t size = 0;
	for (int index = 0, length = args.Length(); index < length; ++index) {
		Local<Value> arg = args[index];
		if (arg->IsString()) {
			// Utf8Length() because we need the length in bytes, not characters
			size += arg->ToString()->Utf8Length();
		}
		else if (Buffer::HasInstance(arg)) {
			Buffer& b = *Buffer::Unwrap<Buffer>(arg->ToObject());
			size += b.length();
		}
		else {
			std::stringstream s;
			s << "Argument #" << index << " is neither a string nor a buffer object.";
			const char* message = s.str().c_str();
			return ThrowException(Exception::TypeError(String::New(message)));
		}
	}

	Buffer& dst = *Buffer::New(size);
	char* s = dst.data();

	for (int index = 0, length = args.Length(); index < length; ++index) {
		Local<Value> arg = args[index];
		if (arg->IsString()) {
			String::Utf8Value v(arg->ToString());
			memcpy(s, *v, v.length());
			s += v.length();
		}
		else if (Buffer::HasInstance(arg)) {
			Buffer& b = *Buffer::Unwrap<Buffer>(arg->ToObject());
			memcpy(s, b.data(), b.length());
			s += b.length();
		}
		else {
			return ThrowException(Exception::Error(String::New(
					"Congratulations! You have run into a bug: argument is neither a string nor a buffer object. "
					"Please make the world a better place and report it.")));
		}
	}

	return scope.Close(dst.handle_);
}

extern "C" void init(Handle<Object> target) {
	HandleScope scope;

	target->Set(String::NewSymbol("concat"), FunctionTemplate::New(Concat)->GetFunction());

	Local<Object> proto = Buffer::New(0)->handle_->GetPrototype()->ToObject();
	proto->Set(String::NewSymbol("fill"), FunctionTemplate::New(Fill)->GetFunction());
	proto->Set(String::NewSymbol("clear"), FunctionTemplate::New(Clear)->GetFunction());
	proto->Set(String::NewSymbol("equals"), FunctionTemplate::New(Equals)->GetFunction());
	proto->Set(String::NewSymbol("compare"), FunctionTemplate::New(Compare)->GetFunction());
	proto->Set(String::NewSymbol("indexOf"), FunctionTemplate::New(IndexOf)->GetFunction());
	proto->Set(String::NewSymbol("fromHex"), FunctionTemplate::New(FromHex)->GetFunction());
	proto->Set(String::NewSymbol("toHex"), FunctionTemplate::New(ToHex)->GetFunction());
}

}
<|endoftext|>


<commit_before>//challenge_0 by:flavabox

#include <iostream>
using namespace std;

int main() {

	cout << "Hello World!" << endl;

	return 0;
}<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>#include "catch.hpp"

#include <parallel.hpp>

TEST_CASE("test parallel_remove", "[parallel_remove]")
{

    std::vector<int> intrange{1, 2, 3, 4};
    std::vector<char> charange{'a', 'b', 'c', 'd'};

    auto rem_it = helene::parallel_remove(
        intrange.begin(), intrange.end(), charange.begin(), 3);

    intrange.erase(rem_it.first, intrange.end());
    charange.erase(rem_it.second, charange.end());

    REQUIRE(intrange.size() == 3);
    REQUIRE(charange.size() == 3);
}
<commit_msg>Add more tests. 	modified:   tests/test_algorithms.cpp<commit_after>#include "catch.hpp"

#include <parallel.hpp>
#include <vector>
#include <deque>

TEST_CASE("test parallel_remove with parallel vectors", "[parallel_remove]")
{

    std::vector<int> intrange{1, 2, 3, 4};
    std::vector<char> charange{'a', 'b', 'c', 'd'};

    SECTION("remove by value")
    {
        auto rem_it = helene::parallel_remove(
            intrange.begin(), intrange.end(), charange.begin(), 3);

        intrange.erase(rem_it.first, intrange.end());
        charange.erase(rem_it.second, charange.end());

        REQUIRE(intrange.size() == 3);
        REQUIRE(charange.size() == 3);
        REQUIRE(intrange[0] == 1);
        REQUIRE(charange[0] == 'a');
        REQUIRE(intrange[1] == 2);
        REQUIRE(charange[1] == 'b');
        REQUIRE(intrange[2] == 4);
        REQUIRE(charange[2] == 'd');
    }
}

TEST_CASE("test parallel_remove with one vector and one deque",
          "[parallel_remove]")
{
    std::vector<int> intrange{1, 2, 3, 4, 5, 6};
    std::deque<std::string> stringrange{
        "one", "two", "three", "four", "five", "six"};

    auto rem_pair = helene::parallel_remove(
        intrange.begin(), intrange.end(), stringrange.begin(), 2);

    intrange.erase(rem_pair.first, intrange.end());
    stringrange.erase(rem_pair.second, stringrange.end());

    REQUIRE(intrange.size() == 5);
    REQUIRE(stringrange.size() == 5);
    REQUIRE(intrange[1] == 3);
    REQUIRE(stringrange[1] == std::string("three"));
}
<|endoftext|>


<commit_before>#include "test_convergence.h"
#include "parameters.h"

const double ConvergenceTest::m_roll_tol = 2.5 * constants::as_radians;
const double ConvergenceTest::m_steer_tol = 0.1 * constants::as_degrees;
const double ConvergenceTest::m_roll_rate_tol = 10 * ConvergenceTest::m_roll_tol;
const double ConvergenceTest::m_steer_rate_tol = ConvergenceTest::m_steer_tol;
const double ConvergenceTest::m_dt = 1.0/200;
const uint32_t ConvergenceTest::m_N = 1000;
const uint32_t ConvergenceTest::m_n = 100;

void ConvergenceTest::SetUp() {
    // set initial state
    m_x << 0, 10, 10, 0; // define x in degrees
    m_x *= constants::as_radians;

    m_bicycle = new model::Bicycle(parameters::benchmark::M, parameters::benchmark::C1,
            parameters::benchmark::K0, parameters::benchmark::K2, GetParam(), m_dt);
    m_bicycle->set_C(parameters::defaultvalue::bicycle::C);
    m_kalman = new observer::Kalman<model::Bicycle>(*m_bicycle,
            parameters::defaultvalue::kalman::Q(m_dt),
            parameters::defaultvalue::kalman::R,
            model::Bicycle::state_t::Zero(),
            std::pow(m_x[0]/2, 2) * model::Bicycle::state_matrix_t::Identity());
    m_lqr = new controller::Lqr<model::Bicycle>(*m_bicycle,
            controller::Lqr<model::Bicycle>::state_cost_t::Identity(),
            0.1 * controller::Lqr<model::Bicycle>::input_cost_t::Identity(),
            model::Bicycle::state_t::Zero(), m_n);
    m_gen = std::mt19937(m_rd());
    m_r0 = std::normal_distribution<>(0, parameters::defaultvalue::kalman::R(0, 0));
    m_r1 = std::normal_distribution<>(0, parameters::defaultvalue::kalman::R(1, 1));
}

void ConvergenceTest::TearDown() {
    delete m_bicycle;
    delete m_kalman;
    delete m_lqr;
    m_bicycle = nullptr;
    m_kalman = nullptr;
    m_lqr = nullptr;
}

void ConvergenceTest::test_state_near(model::Bicycle::state_t actual, model::Bicycle::state_t expected) {
    EXPECT_NEAR(actual(0), expected(0), m_roll_tol);
    EXPECT_NEAR(actual(1), expected(1), m_steer_tol);
    EXPECT_NEAR(actual(2), expected(2), m_roll_rate_tol);
    EXPECT_NEAR(actual(3), expected(3), m_steer_rate_tol);
}
<commit_msg>Fix convergence test tolerances<commit_after>#include "test_convergence.h"
#include "parameters.h"

const double ConvergenceTest::m_roll_tol = 0.1 * constants::as_radians;
const double ConvergenceTest::m_steer_tol = 0.1 * constants::as_radians;
const double ConvergenceTest::m_roll_rate_tol = 10 * ConvergenceTest::m_roll_tol;
const double ConvergenceTest::m_steer_rate_tol = 10 * ConvergenceTest::m_steer_tol;
const double ConvergenceTest::m_dt = 1.0/200;
const uint32_t ConvergenceTest::m_N = 1000;
const uint32_t ConvergenceTest::m_n = 100;

void ConvergenceTest::SetUp() {
    // set initial state
    m_x << 5, 5, 0, 0; // define x in degrees
    m_x *= constants::as_radians;

    m_bicycle = new model::Bicycle(parameters::benchmark::M, parameters::benchmark::C1,
            parameters::benchmark::K0, parameters::benchmark::K2, GetParam(), m_dt);
    m_bicycle->set_C(parameters::defaultvalue::bicycle::C);
    m_kalman = new observer::Kalman<model::Bicycle>(*m_bicycle,
            parameters::defaultvalue::kalman::Q(m_dt),
            parameters::defaultvalue::kalman::R,
            model::Bicycle::state_t::Zero(),
            std::pow(m_x[0]/2, 2) * model::Bicycle::state_matrix_t::Identity());
    m_lqr = new controller::Lqr<model::Bicycle>(*m_bicycle,
            controller::Lqr<model::Bicycle>::state_cost_t::Identity(),
            0.1 * controller::Lqr<model::Bicycle>::input_cost_t::Identity(),
            model::Bicycle::state_t::Zero(), m_n);
    m_gen = std::mt19937(m_rd());
    m_r0 = std::normal_distribution<>(0, parameters::defaultvalue::kalman::R(0, 0));
    m_r1 = std::normal_distribution<>(0, parameters::defaultvalue::kalman::R(1, 1));
}

void ConvergenceTest::TearDown() {
    delete m_bicycle;
    delete m_kalman;
    delete m_lqr;
    m_bicycle = nullptr;
    m_kalman = nullptr;
    m_lqr = nullptr;
}

void ConvergenceTest::test_state_near(model::Bicycle::state_t actual, model::Bicycle::state_t expected) {
    EXPECT_NEAR(actual(0), expected(0), m_roll_tol);
    EXPECT_NEAR(actual(1), expected(1), m_steer_tol);
    EXPECT_NEAR(actual(2), expected(2), m_roll_rate_tol);
    EXPECT_NEAR(actual(3), expected(3), m_steer_rate_tol);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xrmmerge.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-25 12:40:06 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// global includes
#include <tools/string.hxx>

//
// XRMResParser
//

class XRMResParser
{
private:
    ByteString sGID;
    ByteString sLID;

    BOOL bError;
    BOOL bText;

    ByteString sLocalized;

    ByteString sCurrentOpenTag;
    ByteString sCurrentCloseTag;
    ByteString sCurrentText;
    std::vector<ByteString> aLanguages;

protected:
    ByteString GetAttribute( const ByteString &rToken, const ByteString &rAttribute );
    void Error( const ByteString &rError );

    virtual void Output( const ByteString& rOutput );
    virtual void WorkOnText(
        const ByteString &rOpenTag,
        ByteString &rText
    );
    virtual void EndOfText(
        const ByteString &rOpenTag,
        const ByteString &rCloseTag
    );

    ByteString GetGID() { return sGID; }
    ByteString GetLID() { return sLID; }

    void ConvertStringToDBFormat( ByteString &rString );
    void ConvertStringToXMLFormat( ByteString &rString );

public:
    XRMResParser();
    virtual ~XRMResParser();

    int Execute( int nToken, char * pToken );

    void SetError( BOOL bErr = TRUE ) { bError = bErr; }
    BOOL GetError() { return bError; }
};

//
// class XRMResOutputParser
//

class XRMResOutputParser : public XRMResParser
{
private:
    std::vector<ByteString> aLanguages;
protected:
    SvFileStream *pOutputStream;
public:
    XRMResOutputParser ( const ByteString &rOutputFile );
    virtual ~XRMResOutputParser();
};

//
// XRMResExport
//

class XRMResExport : public XRMResOutputParser
{
private:
    ResData *pResData;
    ByteString sPrj;
    ByteString sPath;
    std::vector<ByteString> aLanguages;

protected:
    virtual void WorkOnText(
        const ByteString &rOpenTag,
        ByteString &rText
    );
    virtual void EndOfText(
        const ByteString &rOpenTag,
        const ByteString &rCloseTag
    );

public:
    XRMResExport(
        const ByteString &rOutputFile,
        const ByteString &rProject,
        const ByteString &rFilePath
    );
    virtual ~XRMResExport();
};

//
// class XRMResMerge
//

class XRMResMerge : public XRMResOutputParser
{
private:
    MergeDataFile *pMergeDataFile;
    ResData *pResData;
    std::vector<ByteString> aLanguages;

protected:
    virtual void WorkOnText(
        const ByteString &rOpenTag,
        ByteString &rText
    );
    virtual void EndOfText(
        const ByteString &rOpenTag,
        const ByteString &rCloseTag
    );
    virtual void Output( const ByteString& rOutput );
public:
    XRMResMerge(
        const ByteString &rMergeSource,
        const ByteString &rOutputFile,
        BOOL bErrorLog
    );
    virtual ~XRMResMerge();
};

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.96); FILE MERGED 2005/09/05 11:28:35 rt 1.2.96.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xrmmerge.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:58:25 $
 *
 *  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
 *
 ************************************************************************/

// global includes
#include <tools/string.hxx>

//
// XRMResParser
//

class XRMResParser
{
private:
    ByteString sGID;
    ByteString sLID;

    BOOL bError;
    BOOL bText;

    ByteString sLocalized;

    ByteString sCurrentOpenTag;
    ByteString sCurrentCloseTag;
    ByteString sCurrentText;
    std::vector<ByteString> aLanguages;

protected:
    ByteString GetAttribute( const ByteString &rToken, const ByteString &rAttribute );
    void Error( const ByteString &rError );

    virtual void Output( const ByteString& rOutput );
    virtual void WorkOnText(
        const ByteString &rOpenTag,
        ByteString &rText
    );
    virtual void EndOfText(
        const ByteString &rOpenTag,
        const ByteString &rCloseTag
    );

    ByteString GetGID() { return sGID; }
    ByteString GetLID() { return sLID; }

    void ConvertStringToDBFormat( ByteString &rString );
    void ConvertStringToXMLFormat( ByteString &rString );

public:
    XRMResParser();
    virtual ~XRMResParser();

    int Execute( int nToken, char * pToken );

    void SetError( BOOL bErr = TRUE ) { bError = bErr; }
    BOOL GetError() { return bError; }
};

//
// class XRMResOutputParser
//

class XRMResOutputParser : public XRMResParser
{
private:
    std::vector<ByteString> aLanguages;
protected:
    SvFileStream *pOutputStream;
public:
    XRMResOutputParser ( const ByteString &rOutputFile );
    virtual ~XRMResOutputParser();
};

//
// XRMResExport
//

class XRMResExport : public XRMResOutputParser
{
private:
    ResData *pResData;
    ByteString sPrj;
    ByteString sPath;
    std::vector<ByteString> aLanguages;

protected:
    virtual void WorkOnText(
        const ByteString &rOpenTag,
        ByteString &rText
    );
    virtual void EndOfText(
        const ByteString &rOpenTag,
        const ByteString &rCloseTag
    );

public:
    XRMResExport(
        const ByteString &rOutputFile,
        const ByteString &rProject,
        const ByteString &rFilePath
    );
    virtual ~XRMResExport();
};

//
// class XRMResMerge
//

class XRMResMerge : public XRMResOutputParser
{
private:
    MergeDataFile *pMergeDataFile;
    ResData *pResData;
    std::vector<ByteString> aLanguages;

protected:
    virtual void WorkOnText(
        const ByteString &rOpenTag,
        ByteString &rText
    );
    virtual void EndOfText(
        const ByteString &rOpenTag,
        const ByteString &rCloseTag
    );
    virtual void Output( const ByteString& rOutput );
public:
    XRMResMerge(
        const ByteString &rMergeSource,
        const ByteString &rOutputFile,
        BOOL bErrorLog
    );
    virtual ~XRMResMerge();
};

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swcli.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 15:32:38 $
 *
 *  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 _SWCLI_HXX
#define _SWCLI_HXX
#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#endif

#include <svtools/embedhlp.hxx>

#ifndef _SFX_CLIENTSH_HXX //autogen
#include <sfx2/ipclient.hxx>
#endif

class SwView;
class SwEditWin;

class SwOleClient : public SfxInPlaceClient
{
    BOOL bInDoVerb;
    BOOL bOldCheckForOLEInCaption;

    virtual void ObjectAreaChanged();
    virtual void RequestNewObjectArea( Rectangle& );
    virtual void ViewChanged();
    virtual void MakeVisible();

public:
    SwOleClient( SwView *pView, SwEditWin *pWin, const svt::EmbeddedObjectRef& );

    void SetInDoVerb( BOOL bFlag )              { bInDoVerb = bFlag; }

    BOOL IsCheckForOLEInCaption() const         { return bOldCheckForOLEInCaption; }
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.738); FILE MERGED 2008/04/01 12:53:34 thb 1.4.738.2: #i85898# Stripping all external header guards 2008/03/31 16:52:42 rt 1.4.738.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: swcli.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SWCLI_HXX
#define _SWCLI_HXX
#include <com/sun/star/embed/XEmbeddedObject.hpp>

#include <svtools/embedhlp.hxx>

#ifndef _SFX_CLIENTSH_HXX //autogen
#include <sfx2/ipclient.hxx>
#endif

class SwView;
class SwEditWin;

class SwOleClient : public SfxInPlaceClient
{
    BOOL bInDoVerb;
    BOOL bOldCheckForOLEInCaption;

    virtual void ObjectAreaChanged();
    virtual void RequestNewObjectArea( Rectangle& );
    virtual void ViewChanged();
    virtual void MakeVisible();

public:
    SwOleClient( SwView *pView, SwEditWin *pWin, const svt::EmbeddedObjectRef& );

    void SetInDoVerb( BOOL bFlag )              { bInDoVerb = bFlag; }

    BOOL IsCheckForOLEInCaption() const         { return bOldCheckForOLEInCaption; }
};

#endif
<|endoftext|>


<commit_before>#ifndef __COSMOLOGY_H
#define __COSMOLOGY_H

#include "physconst.h"
#include <valarray>

/** Class to store various cosmological parameters. Any function that relies on Omega or OmegaLambda should ultimately be in here */
class Cosmology
{
    public:
        //Note: Omega here should be the matter density in the background at z=0.
        //This always includes neutrinos and baryons.
        Cosmology(double HubbleParam, double Omega, double OmegaLambda, double MNu, int Hierarchy, bool NoRadiation): HubbleParam(HubbleParam), Omega(Omega), OmegaLambda(OmegaLambda), MNu(MNu), Hierarchy(Hierarchy), NoRadiation(NoRadiation)
        {}
        //Hubble H(z) / h0. Returns in units of 1/s, not internal units.
        double Hubble(double a);
        /* Return the total matter density in all neutrino species.*/
        double OmegaNu(double a);
        //Radiation density
        double OmegaR(double a);
        double GrowthFactor(double astart, double aend);
        double F_Omega(double a);
        double F2_Omega(double a);
        //The matter density
        double OmegaMatter(double a);
    private:
        double growth(double a, double *dDda);
        /* Return the matter density in a single neutrino species.
        * Not externally callable*/
        double OmegaNu_single(double a,double mnu);
        /*The derivative wrt a of the total matter density in all neutrino species*/
        double HubbleParam;
        double Omega;
        double OmegaLambda;
        double MNu;
        int Hierarchy;
        bool NoRadiation;
};

#endif
<commit_msg>Constify parameters<commit_after>#ifndef __COSMOLOGY_H
#define __COSMOLOGY_H

#include "physconst.h"
#include <valarray>

/** Class to store various cosmological parameters. Any function that relies on Omega or OmegaLambda should ultimately be in here */
class Cosmology
{
    public:
        //Note: Omega here should be the matter density in the background at z=0.
        //This always includes neutrinos and baryons.
        Cosmology(double HubbleParam, double Omega, double OmegaLambda, double MNu, int Hierarchy, bool NoRadiation): HubbleParam(HubbleParam), Omega(Omega), OmegaLambda(OmegaLambda), MNu(MNu), Hierarchy(Hierarchy), NoRadiation(NoRadiation)
        {}
        //Hubble H(z) / h0. Returns in units of 1/s, not internal units.
        double Hubble(double a);
        /* Return the total matter density in all neutrino species.*/
        double OmegaNu(double a);
        //Radiation density
        double OmegaR(double a);
        double GrowthFactor(double astart, double aend);
        double F_Omega(double a);
        double F2_Omega(double a);
        //The matter density
        double OmegaMatter(double a);
    private:
        double growth(double a, double *dDda);
        /* Return the matter density in a single neutrino species.
        * Not externally callable*/
        double OmegaNu_single(double a,double mnu);
        const double HubbleParam;
        const double Omega;
        const double OmegaLambda;
        const double MNu;
        const int Hierarchy;
        const bool NoRadiation;
};

#endif
<|endoftext|>


<commit_before>#ifndef TAMER_ADAPTER_HH
#define TAMER_ADAPTER_HH 1
#include <tamer/xadapter.hh>
namespace tamer {

namespace outcome {
const int success = 0;
const int cancel = -ECANCELED;
const int timeout = -ETIMEDOUT;
const int signal = -EINTR;
}

/** @brief  Create event that triggers @a e1 and @a e2 when triggered.
 *  @param  e1  First event.
 *  @param  e2  Second event.
 *  @return  Distributer event.
 *
 *  When the distributer event is triggered, @a e1 and @a e2 are both
 *  triggered instantly.  When both @a e1 and @a e2 are canceled, the
 *  distributer event is itself canceled.
 */
inline event<> distribute(const event<> &e1, const event<> &e2) {
    if (e1.empty())
	return e2;
    else if (e2.empty())
	return e1;
    else
	return tamerpriv::hard_distribute(e1, e2);
}

/** @brief  Create event that triggers @a e1, @a e2, and @a e3 when triggered.
 *  @param  e1  First event.
 *  @param  e2  Second event.
 *  @param  e3  Third event.
 *  @return  Distributer event.
 *
 *  When the distributer event is triggered, @a e1, @a e2, and @a e3 are all
 *  triggered instantly.  When @a e1, @a e2, and @a e3 are all canceled, the
 *  distributer event is itself canceled.
 */
inline event<> distribute(const event<> &e1, const event<> &e2, const event<> &e3) {
    return distribute(distribute(e1, e2), e3);
}

/** @brief  Create event that triggers @a e with @a v0 when triggered.
 *  @param  e   Event.
 *  @param  v0  Trigger value
 *  @return  Adapter event.
 *
 *  When the adapter event is triggered, @a e is triggered instantly with
 *  trigger value @a v0.  When @a e is canceled, the adapter event is itself
 *  canceled.
 */
template <typename T0, typename V0>
event<> bind(const event<T0> &e, const V0 &v0) {
    tamerpriv::bind_rendezvous<T0> *ur = new tamerpriv::bind_rendezvous<T0>(e, v0);
    return event<>(*ur, 1);
}

/** @brief  Create 1-slot event that triggers @a e when triggered.
 *  @param  e  Event.
 *  @return  Adapter event.
 *
 *  When the adapter event is triggered, its @c T0 trigger value is ignored
 *  and @a e is triggered instantly.  When @a e is canceled, the adapter
 *  event is itself canceled.
 */
template <typename T0>
event<T0> ignore_slot(const event<> &e) {
    tamerpriv::unbind_rendezvous<T0> *ur = new tamerpriv::unbind_rendezvous<T0>(e);
    return event<T0>(*ur, 1, *((T0 *) 0));
}

/** @brief  Create event that cancels @a e when triggered.
 *  @param  e  Event.
 *  @return  Canceler event.
 *
 *  When the canceler event is triggered, @a e is canceled instantly.  When
 *  @a e is canceled or triggered, the canceler event is itself canceled.
 */
template <typename T0, typename T1, typename T2, typename T3>
inline event<> make_canceler(const event<T0, T1, T2, T3> &e) {
    tamerpriv::canceler_rendezvous *r = new tamerpriv::canceler_rendezvous(e);
    return event<>(*r);
}

/** @brief  Cause @a e1 to cancel when @a e2 is canceled.
 *  @param  e1  Event.
 *  @param  e2  Event.
 *  @return  @a e2.
 *
 *  When @a e2 is canceled, @a e1 is canceled immediately.
 */
template <typename T0, typename T1, typename T2, typename T3,
	  typename U0, typename U1, typename U2, typename U3>
inline event<T0, T1, T2, T3> spread_cancel(const event<U0, U1, U2, U3> &e1, event<T0, T1, T2, T3> e2) {
    tamerpriv::canceler_rendezvous *r = new tamerpriv::canceler_rendezvous(e1);
    e2.at_cancel(event<>(*r));
    return e2;
}

/** @brief  Add a cancel notifier to an event.
 *  @param  r   Rendezvous.
 *  @param  i0  First event ID.
 *  @param  i1  Second event ID.
 *  @param  e   Event.
 *  @return  @a e.
 *
 *  Equivalent to
 *  @code
 *  e.at_cancel(make_event(r, i0, i1)); return e;
 *  @endcode
 */
template <typename R, typename I0, typename I1, typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> make_cancel(R &r, const I0 &i0, const I1 &i1, event<T0, T1, T2, T3> e) {
    e.at_cancel(make_event(r, i0, i1));
    return e;
}

template <typename R, typename I0, typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> make_cancel(R &r, const I0 &i0, event<T0, T1, T2, T3> e) {
    e.at_cancel(make_event(r, i0));
    return e;
}

template <typename R, typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> make_cancel(R &r, event<T0, T1, T2, T3> e) {
    e.at_cancel(make_event(r));
    return e;
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout(const timeval &delay, event<T0, T1, T2, T3> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, 0);
    at_delay(delay, event<>(*r, outcome::timeout));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout(const timeval &delay, event<T0, T1, T2, T3> e, int &result) {
    result = outcome::success;
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, &result);
    at_delay(delay, event<>(*r, outcome::timeout));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout_sec(int delay, event<T0, T1, T2, T3> e) {
    timeval tv;
    tv.tv_sec = delay;
    tv.tv_usec = 0;
    return with_timeout(tv, e);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout_sec(int delay, event<T0, T1, T2, T3> e, int &result) {
    timeval tv;
    tv.tv_sec = delay;
    tv.tv_usec = 0;
    return with_timeout(tv, e, result);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout_msec(int delay, event<T0, T1, T2, T3> e) {
    timeval tv;
    tv.tv_sec = delay / 1000;
    tv.tv_usec = delay % 1000;
    return with_timeout(tv, e);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout_msec(int delay, event<T0, T1, T2, T3> e, int &result) {
    timeval tv;
    tv.tv_sec = delay / 1000;
    tv.tv_usec = delay % 1000;
    return with_timeout(tv, e, result);
}

inline event<int> add_timeout(const timeval &delay, event<int> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, e.slot0());
    at_delay(delay, event<>(*r, outcome::timeout));
    return e.make_rebind(*r, outcome::success);
}

inline event<int> add_timeout_sec(int delay, event<int> e) {
    timeval tv;
    tv.tv_sec = delay;
    tv.tv_usec = 0;
    return add_timeout(tv, e);
}

inline event<int> add_timeout_msec(int delay, event<int> e) {
    timeval tv;
    tv.tv_sec = delay / 1000;
    tv.tv_usec = delay % 1000;
    return add_timeout(tv, e);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_signal(int sig, event<T0, T1, T2, T3> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, 0);
    at_signal(sig, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_signal(int sig, event<T0, T1, T2, T3> e, int &result) {
    result = outcome::success;
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, &result);
    at_signal(sig, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_signal(const std::vector<int> &sig, event<T0, T1, T2, T3> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, 0);
    for (std::vector<int>::const_iterator i = sig.begin(); i != sig.end(); i++)
	at_signal(*i, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_signal(const std::vector<int> &sig, event<T0, T1, T2, T3> e, int &result) {
    result = outcome::success;
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, &result);
    for (std::vector<int>::const_iterator i = sig.begin(); i != sig.end(); i++)
	at_signal(*i, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

inline event<int> add_signal(int sig, event<int> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, e.slot0());
    at_signal(sig, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

inline event<int> add_signal(const std::vector<int> &sig, event<int> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, e.slot0());
    for (std::vector<int>::const_iterator i = sig.begin(); i != sig.end(); i++)
	at_signal(*i, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_cancel(event<T0, T1, T2, T3> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, 0);
    return e.make_rebind(*r, outcome::success);
}

inline event<int> add_cancel(event<int> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, e.slot0());
    return e.make_rebind(*r, outcome::success);
}

} /* namespace tamer */
#endif /* TAMER_ADAPTER_HH */
<commit_msg>minipiconit<commit_after>#ifndef TAMER_ADAPTER_HH
#define TAMER_ADAPTER_HH 1
#include <tamer/xadapter.hh>
namespace tamer {

namespace outcome {
const int success = 0;
const int cancel = -ECANCELED;
const int timeout = -ETIMEDOUT;
const int signal = -EINTR;
}

/** @brief  Create event that triggers @a e1 and @a e2 when triggered.
 *  @param  e1  First event.
 *  @param  e2  Second event.
 *  @return  Distributer event.
 *
 *  When the distributer event is triggered, @a e1 and @a e2 are both
 *  triggered instantly.  When both @a e1 and @a e2 are canceled, the
 *  distributer event is itself canceled.
 */
inline event<> distribute(const event<> &e1, const event<> &e2) {
    if (e1.empty())
	return e2;
    else if (e2.empty())
	return e1;
    else
	return tamerpriv::hard_distribute(e1, e2);
}

/** @brief  Create event that triggers @a e1, @a e2, and @a e3 when triggered.
 *  @param  e1  First event.
 *  @param  e2  Second event.
 *  @param  e3  Third event.
 *  @return  Distributer event.
 *
 *  When the distributer event is triggered, @a e1, @a e2, and @a e3 are all
 *  triggered instantly.  When @a e1, @a e2, and @a e3 are all canceled, the
 *  distributer event is itself canceled.
 */
inline event<> distribute(const event<> &e1, const event<> &e2, const event<> &e3) {
    return distribute(distribute(e1, e2), e3);
}

/** @brief  Create event that triggers @a e with @a v0 when triggered.
 *  @param  e   Event.
 *  @param  v0  Trigger value.
 *  @return  Adapter event.
 *
 *  When the adapter event is triggered, @a e is triggered instantly with
 *  trigger value @a v0.  When @a e is canceled, the adapter event is itself
 *  canceled.
 */
template <typename T0, typename V0>
event<> bind(const event<T0> &e, const V0 &v0) {
    tamerpriv::bind_rendezvous<T0> *ur = new tamerpriv::bind_rendezvous<T0>(e, v0);
    return event<>(*ur, 1);
}

/** @brief  Create 1-slot event that triggers @a e when triggered.
 *  @param  e  Event.
 *  @return  Adapter event.
 *
 *  When the adapter event is triggered, its @c T0 trigger value is ignored
 *  and @a e is triggered instantly.  When @a e is canceled, the adapter
 *  event is itself canceled.
 */
template <typename T0>
event<T0> ignore_slot(const event<> &e) {
    tamerpriv::unbind_rendezvous<T0> *ur = new tamerpriv::unbind_rendezvous<T0>(e);
    return event<T0>(*ur, 1, *((T0 *) 0));
}

/** @brief  Create event that cancels @a e when triggered.
 *  @param  e  Event.
 *  @return  Canceler event.
 *
 *  When the canceler event is triggered, @a e is canceled instantly.  When
 *  @a e is canceled or triggered, the canceler event is itself canceled.
 */
template <typename T0, typename T1, typename T2, typename T3>
inline event<> make_canceler(const event<T0, T1, T2, T3> &e) {
    tamerpriv::canceler_rendezvous *r = new tamerpriv::canceler_rendezvous(e);
    return event<>(*r);
}

/** @brief  Cause @a e1 to cancel when @a e2 is canceled.
 *  @param  e1  Event.
 *  @param  e2  Event.
 *  @return  @a e2.
 *
 *  When @a e2 is canceled, @a e1 is canceled immediately.
 */
template <typename T0, typename T1, typename T2, typename T3,
	  typename U0, typename U1, typename U2, typename U3>
inline event<T0, T1, T2, T3> spread_cancel(const event<U0, U1, U2, U3> &e1, event<T0, T1, T2, T3> e2) {
    tamerpriv::canceler_rendezvous *r = new tamerpriv::canceler_rendezvous(e1);
    e2.at_cancel(event<>(*r));
    return e2;
}

/** @brief  Add a cancel notifier to an event.
 *  @param  r   Rendezvous.
 *  @param  i0  First event ID.
 *  @param  i1  Second event ID.
 *  @param  e   Event.
 *  @return  @a e.
 *
 *  Equivalent to
 *  @code
 *  e.at_cancel(make_event(r, i0, i1)); return e;
 *  @endcode
 */
template <typename R, typename I0, typename I1, typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> make_cancel(R &r, const I0 &i0, const I1 &i1, event<T0, T1, T2, T3> e) {
    e.at_cancel(make_event(r, i0, i1));
    return e;
}

template <typename R, typename I0, typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> make_cancel(R &r, const I0 &i0, event<T0, T1, T2, T3> e) {
    e.at_cancel(make_event(r, i0));
    return e;
}

template <typename R, typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> make_cancel(R &r, event<T0, T1, T2, T3> e) {
    e.at_cancel(make_event(r));
    return e;
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout(const timeval &delay, event<T0, T1, T2, T3> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, 0);
    at_delay(delay, event<>(*r, outcome::timeout));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout(const timeval &delay, event<T0, T1, T2, T3> e, int &result) {
    result = outcome::success;
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, &result);
    at_delay(delay, event<>(*r, outcome::timeout));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout_sec(int delay, event<T0, T1, T2, T3> e) {
    timeval tv;
    tv.tv_sec = delay;
    tv.tv_usec = 0;
    return with_timeout(tv, e);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout_sec(int delay, event<T0, T1, T2, T3> e, int &result) {
    timeval tv;
    tv.tv_sec = delay;
    tv.tv_usec = 0;
    return with_timeout(tv, e, result);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout_msec(int delay, event<T0, T1, T2, T3> e) {
    timeval tv;
    tv.tv_sec = delay / 1000;
    tv.tv_usec = delay % 1000;
    return with_timeout(tv, e);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_timeout_msec(int delay, event<T0, T1, T2, T3> e, int &result) {
    timeval tv;
    tv.tv_sec = delay / 1000;
    tv.tv_usec = delay % 1000;
    return with_timeout(tv, e, result);
}

inline event<int> add_timeout(const timeval &delay, event<int> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, e.slot0());
    at_delay(delay, event<>(*r, outcome::timeout));
    return e.make_rebind(*r, outcome::success);
}

inline event<int> add_timeout_sec(int delay, event<int> e) {
    timeval tv;
    tv.tv_sec = delay;
    tv.tv_usec = 0;
    return add_timeout(tv, e);
}

inline event<int> add_timeout_msec(int delay, event<int> e) {
    timeval tv;
    tv.tv_sec = delay / 1000;
    tv.tv_usec = delay % 1000;
    return add_timeout(tv, e);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_signal(int sig, event<T0, T1, T2, T3> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, 0);
    at_signal(sig, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_signal(int sig, event<T0, T1, T2, T3> e, int &result) {
    result = outcome::success;
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, &result);
    at_signal(sig, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_signal(const std::vector<int> &sig, event<T0, T1, T2, T3> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, 0);
    for (std::vector<int>::const_iterator i = sig.begin(); i != sig.end(); i++)
	at_signal(*i, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_signal(const std::vector<int> &sig, event<T0, T1, T2, T3> e, int &result) {
    result = outcome::success;
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, &result);
    for (std::vector<int>::const_iterator i = sig.begin(); i != sig.end(); i++)
	at_signal(*i, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

inline event<int> add_signal(int sig, event<int> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, e.slot0());
    at_signal(sig, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

inline event<int> add_signal(const std::vector<int> &sig, event<int> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, e.slot0());
    for (std::vector<int>::const_iterator i = sig.begin(); i != sig.end(); i++)
	at_signal(*i, event<>(*r, outcome::signal));
    return e.make_rebind(*r, outcome::success);
}

template <typename T0, typename T1, typename T2, typename T3>
inline event<T0, T1, T2, T3> with_cancel(event<T0, T1, T2, T3> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, 0);
    return e.make_rebind(*r, outcome::success);
}

inline event<int> add_cancel(event<int> e) {
    tamerpriv::cancel_adapter_rendezvous *r = new tamerpriv::cancel_adapter_rendezvous(e, e.slot0());
    return e.make_rebind(*r, outcome::success);
}

} /* namespace tamer */
#endif /* TAMER_ADAPTER_HH */
<|endoftext|>


<commit_before>#include <NfcTag.h>

NfcTag::NfcTag()
{
    _uid = 0;
    _uidLength = 0;
    _tagType = "Unknown";
    _ndefMessage = (NdefMessage*)NULL;
}

NfcTag::NfcTag(byte *uid, unsigned int uidLength)
{
    _uid = uid;
    _uidLength = uidLength;
    _tagType = "Unknown";
    _ndefMessage = (NdefMessage*)NULL;
}

NfcTag::NfcTag(byte *uid, unsigned int  uidLength, String tagType)
{
    _uid = uid;
    _uidLength = uidLength;
    _tagType = tagType;
    _ndefMessage = (NdefMessage*)NULL;
}

NfcTag::NfcTag(byte *uid, unsigned int  uidLength, String tagType, NdefMessage& ndefMessage)
{
    _uid = uid;
    _uidLength = uidLength;
    _tagType = tagType;
    _ndefMessage = new NdefMessage(ndefMessage);
}

// I don't like this version, but it will use less memory
NfcTag::NfcTag(byte *uid, unsigned int uidLength, String tagType, const byte *ndefData, const int ndefDataLength)
{
    _uid = uid;
    _uidLength = uidLength;
    _tagType = tagType;
    _ndefMessage = new NdefMessage(ndefData, ndefDataLength);
}

NfcTag::~NfcTag()
{
    delete _ndefMessage;
}

NfcTag& NfcTag::operator=(const NfcTag& rhs)
{
    if (this != &rhs)
    {
        delete _ndefMessage;
        _uid = rhs._uid;
        _uidLength = rhs._uidLength;
        _tagType = rhs._tagType;
        // TODO do I need a copy here?
        _ndefMessage = rhs._ndefMessage;
    }
    return *this;
}

uint8_t NfcTag::getUidLength()
{
    return _uidLength;
}

void NfcTag::getUid(byte *uid, unsigned int uidLength)
{
    memcpy(uid, _uid, uidLength);
}

String NfcTag::getUidString()
{
    String uidString = "";
    for (int i = 0; i < _uidLength; i++)
    {
        if (i > 0)
        {
            uidString += " ";
        }

        if (_uid[i] < 0xF)
        {
            uidString += "0";
        }

        uidString += String((unsigned int)_uid[i], (unsigned char)HEX);
    }
    uidString.toUpperCase();
    return uidString;
}

String NfcTag::getTagType()
{
    return _tagType;
}

boolean NfcTag::hasNdefMessage()
{
    return (_ndefMessage != NULL);
}

NdefMessage NfcTag::getNdefMessage()
{
    return *_ndefMessage;
}

void NfcTag::print()
{
    Serial.print(F("NFC Tag - "));Serial.println(_tagType);
    Serial.print(F("UID "));Serial.println(getUidString());
    if (_ndefMessage == NULL)
    {
        Serial.println(F("\nNo NDEF Message"));
    }
    else
    {
        _ndefMessage->print();
    }
}
<commit_msg>use shorter length<commit_after>#include <NfcTag.h>

NfcTag::NfcTag()
{
    _uid = 0;
    _uidLength = 0;
    _tagType = "Unknown";
    _ndefMessage = (NdefMessage*)NULL;
}

NfcTag::NfcTag(byte *uid, unsigned int uidLength)
{
    _uid = uid;
    _uidLength = uidLength;
    _tagType = "Unknown";
    _ndefMessage = (NdefMessage*)NULL;
}

NfcTag::NfcTag(byte *uid, unsigned int  uidLength, String tagType)
{
    _uid = uid;
    _uidLength = uidLength;
    _tagType = tagType;
    _ndefMessage = (NdefMessage*)NULL;
}

NfcTag::NfcTag(byte *uid, unsigned int  uidLength, String tagType, NdefMessage& ndefMessage)
{
    _uid = uid;
    _uidLength = uidLength;
    _tagType = tagType;
    _ndefMessage = new NdefMessage(ndefMessage);
}

// I don't like this version, but it will use less memory
NfcTag::NfcTag(byte *uid, unsigned int uidLength, String tagType, const byte *ndefData, const int ndefDataLength)
{
    _uid = uid;
    _uidLength = uidLength;
    _tagType = tagType;
    _ndefMessage = new NdefMessage(ndefData, ndefDataLength);
}

NfcTag::~NfcTag()
{
    delete _ndefMessage;
}

NfcTag& NfcTag::operator=(const NfcTag& rhs)
{
    if (this != &rhs)
    {
        delete _ndefMessage;
        _uid = rhs._uid;
        _uidLength = rhs._uidLength;
        _tagType = rhs._tagType;
        // TODO do I need a copy here?
        _ndefMessage = rhs._ndefMessage;
    }
    return *this;
}

uint8_t NfcTag::getUidLength()
{
    return _uidLength;
}

void NfcTag::getUid(byte *uid, unsigned int uidLength)
{
    memcpy(uid, _uid, _uidLength < uidLength ? _uidLength : uidLength);
}

String NfcTag::getUidString()
{
    String uidString = "";
    for (int i = 0; i < _uidLength; i++)
    {
        if (i > 0)
        {
            uidString += " ";
        }

        if (_uid[i] < 0xF)
        {
            uidString += "0";
        }

        uidString += String((unsigned int)_uid[i], (unsigned char)HEX);
    }
    uidString.toUpperCase();
    return uidString;
}

String NfcTag::getTagType()
{
    return _tagType;
}

boolean NfcTag::hasNdefMessage()
{
    return (_ndefMessage != NULL);
}

NdefMessage NfcTag::getNdefMessage()
{
    return *_ndefMessage;
}

void NfcTag::print()
{
    Serial.print(F("NFC Tag - "));Serial.println(_tagType);
    Serial.print(F("UID "));Serial.println(getUidString());
    if (_ndefMessage == NULL)
    {
        Serial.println(F("\nNo NDEF Message"));
    }
    else
    {
        _ndefMessage->print();
    }
}
<|endoftext|>


<commit_before>#include "SparseMatrixData.h"

#if defined(_OPENMP)
#include <omp.h>
#endif

using namespace smurff;

SparseMatrixData::SparseMatrixData(Eigen::SparseMatrix<double> Y)
   : FullMatrixData<Eigen::SparseMatrix<double>>(Y)
{
   this->name = "SparseMatrixData [fully known]";
}

void SparseMatrixData::center(double global_mean)
{
    this->global_mean = global_mean;
    if (center_mode == CENTER_GLOBAL)
    {
        Yc.at(0).coeffs() -= global_mean;
        Yc.at(1).coeffs() -= global_mean;
    }
    else if (center_mode == CENTER_VIEW)
    {
        Yc.at(0).coeffs() -= cwise_mean;
        Yc.at(1).coeffs() -= cwise_mean;
    }
    else if (center_mode == CENTER_COLS)
    {
        // you cannot col/row center fully know sparse matrices
        // without converting to dense
        assert(false);
    }
    else if (center_mode == CENTER_ROWS)
    {
        // you cannot col/row center fully know sparse matrices
        // without converting to dense
        assert(false);
    }
}

double SparseMatrixData::train_rmse(const SubModel& model) const
{
   double se = 0.;
#pragma omp parallel for schedule(guided) reduction(+:se)
   for(int c=0; c<Y.cols();++c)
   {
      int r = 0;
      for (Eigen::SparseMatrix<double>::InnerIterator it(Y, c); it; ++it)
      {
         while (r<it.row()) se += square(predict({r++,c}, model));
         se += square(it.value() - predict({r,c}, model));
      }
      for(;r<Y.rows();r++) se += square(predict({r,c}, model));
   }
   return sqrt( se / Y.rows() / Y.cols() );
}
<commit_msg>Never center fully known sparse matrix<commit_after>#include "SparseMatrixData.h"

#if defined(_OPENMP)
#include <omp.h>
#endif

using namespace smurff;

SparseMatrixData::SparseMatrixData(Eigen::SparseMatrix<double> Y)
   : FullMatrixData<Eigen::SparseMatrix<double>>(Y)
{
   this->name = "SparseMatrixData [fully known]";
}

void SparseMatrixData::center(double global_mean)
{
    this->global_mean = global_mean;
    assert(center_mode == CENTER_NONE && "you cannot center fully know sparse matrix without converting to dense");
}

double SparseMatrixData::train_rmse(const SubModel& model) const
{
   double se = 0.;
#pragma omp parallel for schedule(guided) reduction(+:se)
   for(int c=0; c<Y.cols();++c)
   {
      int r = 0;
      for (Eigen::SparseMatrix<double>::InnerIterator it(Y, c); it; ++it)
      {
         while (r<it.row()) se += square(predict({r++,c}, model));
         se += square(it.value() - predict({r,c}, model));
      }
      for(;r<Y.rows();r++) se += square(predict({r,c}, model));
   }
   return sqrt( se / Y.rows() / Y.cols() );
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include "contextc.h"
#include "service.h"
#include "property.h"
#include "group.h"
#include "logging.h"
#include "sconnect.h"
#include "listeners.h"
#include "loggingfeatures.h"

#include <QCoreApplication>

namespace ContextProvider {
}

using namespace ContextProvider;

/*!
    \page CApi C Api

    \brief The libcontextprovider library offers a simple plain-C API to be used
    from any C program.

    \section Usage

    \code
    context_provider_init(DBUS_BUS_SESSION, "org.test.provider");

    context_provider_install_key("Battery.OnBattery", 0, NULL, NULL);
    context_provider_install_key("Battery.ChargePercentage", 0, NULL, NULL);

    context_provider_set_boolean("Battery.OnBattery", 1);
    context_provider_set_integer("Battery.ChargePercentage", 55);
    \endcode

    The above code snippet starts a service at "org.test.provider" with two
    keys ("Battery.OnBattery", "Battery.ChargePercentage") and sets their
    respective values.

    \section Callbacks

    The context_provider_install_key function and context_provider_install_group function
    take arguments specyfying the callback function. The callback is executed when the
    subscription status changes for the key or the key group (first subscriber
    appears or last subscriber goes away). Basing on this info the provider can
    manage it's resources. It's okay also to use the callback function to actually
    set the value.

    \code
    void callback_function_example(int subscribed, void* user_data)
    {
        if (subscribed) {
            // First subscriber appeared.
            // Start ie. pooling the data.
        } else {
            // Last subscribed disappeared.
            // Stop  pooling data, release resources.
        }
    }
    \endcode
*/

static Service *cService;

QList<Listener*> *listeners = NULL;

char argv[] = "libcontextprovider";
char* p= argv;
int argc = 1;
QCoreApplication* app = 0;

/// Initializes and starts the service with a given \a bus_type and a \a bus_name.
/// Te \a bus_type can be DBUS_BUS_SESSION or DBUS_BUS_SYSTEM. This function can be
/// called only once till a matching context_provider_stop is called.
int context_provider_init (DBusBusType bus_type, const char* bus_name)
{
    contextDebug() << F_C << bus_name;

    if (QCoreApplication::instance() == 0) {
        // No QCoreApplication created, so crate one.
        // This will also create an event dispatcher (QEventDispatcherGlibPrivate.)
        app = new QCoreApplication(argc, &p);
    }

    if (cService != NULL) {
        contextCritical() << "Service already initialize. You can only initialize one service with C API";
        return 0;
    }

    cService = new Service(bus_type == DBUS_BUS_SESSION
                           ? QDBusConnection::SessionBus
                           : QDBusConnection::SystemBus,
                           bus_name);
    listeners = new QList<Listener*>;

    return 1;
}

/// Stops the currently started service with context_provider_init. After calling
/// this function a new service can be started by calling context_provider_init.
void context_provider_stop (void)
{
    contextDebug() << F_C;
    if (cService) {
        contextDebug() << "Stopping service";

        // Delete all listeners
        if (listeners) {
            foreach (Listener *listener, *listeners)
                delete listener;
        }
        delete listeners; listeners = NULL;

        delete cService;
        cService = NULL;
    }
    // FIXME: Do we need to do something with the QCoreApplication we might have constructed?
}

/// Installs (adds) a \a key to be provided by the service. The callback function \a
/// subscription_changed_cb will be called with the passed user data \a subscription_changed_cb_target
/// when the status of the subscription changes -- when the first subscriber appears or the
/// last subscriber disappears. The \a clear_values_on_subscribe when enabled will automatically
/// clear (set to null/undetermined) the group keys on first subscribe.
void context_provider_install_key (const char* key,
                                   int clear_values_on_subscribe,
                                   ContextProviderSubscriptionChangedCallback subscription_changed_cb,
                                   void* subscription_changed_cb_target)
{
    contextDebug() << F_C << key;

    if (! cService) {
        contextCritical() << "Can't install key:" << key << "because no service started.";
        return;
    }

    listeners->append(new PropertyListener(*cService, key,
                                           clear_values_on_subscribe,
                                           subscription_changed_cb, subscription_changed_cb_target));
    cService->restart();
}

/// Installs (adds) a \a key_group to be provided by the service. The \a key_group is a NULL-terminated
/// array containing the keys. The callback function \a subscription_changed_cb will be called with the
/// passed user data \a subscription_changed_cb_target when the status of the subscription changes --
/// when the first subscriber appears or the last subscriber disappears. The \a clear_values_on_subscribe
/// when enabled will automatically clear (set to null/undetermined) the group keys on first subscribe.
void context_provider_install_group (const char** key_group,
                                     int clear_values_on_subscribe,
                                     ContextProviderSubscriptionChangedCallback subscription_changed_cb,
                                     void* subscription_changed_cb_target)
{
    contextDebug() << F_C;

    if (! cService) {
        contextCritical() << "Can't install key group because no service started.";
        return;
    }

    QStringList keys;
    int i = 0;
    while(key_group[i] != NULL) {
        QString key = QString(key_group[i]);

        keys << key;
        i++;
    }

    listeners->append(new GroupListener(*cService, keys,
                                        clear_values_on_subscribe,
                                        subscription_changed_cb, subscription_changed_cb_target));
    cService->restart();
}

/// Sets the \a key to a specified integer \a value.
void context_provider_set_integer (const char* key, int value)
{
    contextDebug() << F_C << key << value;
    if (cService)
        cService->setValue(key, value);
}

/// Sets the \a key to a specified double \a value.
void context_provider_set_double (const char* key, double value)
{
    contextDebug() << F_C << key << value;
    if (cService)
        cService->setValue(key, value);
}

/// Sets the \a key to a specified boolean \a value.
void context_provider_set_boolean (const char* key, int value)
{
    contextDebug() << F_C << key << value;
    if (cService)
        cService->setValue(key, value);
}

/// Sets the \a key to a specified string \a value.
void context_provider_set_string (const char* key, const char* value)
{
    contextDebug() << F_C << key << value;
    if (cService)
        cService->setValue(key, value);
}

/// Sets the \a key to NULL. In other words - unsets the key.
void context_provider_set_null (const char* key)
{
    contextDebug() << F_C << key;
    if (cService)
        cService->setValue(key, QVariant());
}
<commit_msg>libcontextprovider: Fixing context_provider_set_bool so that it produces bool QVariants, not int QVariants.<commit_after>/*
 * Copyright (C) 2008 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include "contextc.h"
#include "service.h"
#include "property.h"
#include "group.h"
#include "logging.h"
#include "sconnect.h"
#include "listeners.h"
#include "loggingfeatures.h"

#include <QCoreApplication>

namespace ContextProvider {
}

using namespace ContextProvider;

/*!
    \page CApi C Api

    \brief The libcontextprovider library offers a simple plain-C API to be used
    from any C program.

    \section Usage

    \code
    context_provider_init(DBUS_BUS_SESSION, "org.test.provider");

    context_provider_install_key("Battery.OnBattery", 0, NULL, NULL);
    context_provider_install_key("Battery.ChargePercentage", 0, NULL, NULL);

    context_provider_set_boolean("Battery.OnBattery", 1);
    context_provider_set_integer("Battery.ChargePercentage", 55);
    \endcode

    The above code snippet starts a service at "org.test.provider" with two
    keys ("Battery.OnBattery", "Battery.ChargePercentage") and sets their
    respective values.

    \section Callbacks

    The context_provider_install_key function and context_provider_install_group function
    take arguments specyfying the callback function. The callback is executed when the
    subscription status changes for the key or the key group (first subscriber
    appears or last subscriber goes away). Basing on this info the provider can
    manage it's resources. It's okay also to use the callback function to actually
    set the value.

    \code
    void callback_function_example(int subscribed, void* user_data)
    {
        if (subscribed) {
            // First subscriber appeared.
            // Start ie. pooling the data.
        } else {
            // Last subscribed disappeared.
            // Stop  pooling data, release resources.
        }
    }
    \endcode
*/

static Service *cService;

QList<Listener*> *listeners = NULL;

char argv[] = "libcontextprovider";
char* p= argv;
int argc = 1;
QCoreApplication* app = 0;

/// Initializes and starts the service with a given \a bus_type and a \a bus_name.
/// Te \a bus_type can be DBUS_BUS_SESSION or DBUS_BUS_SYSTEM. This function can be
/// called only once till a matching context_provider_stop is called.
int context_provider_init (DBusBusType bus_type, const char* bus_name)
{
    contextDebug() << F_C << bus_name;

    if (QCoreApplication::instance() == 0) {
        // No QCoreApplication created, so crate one.
        // This will also create an event dispatcher (QEventDispatcherGlibPrivate.)
        app = new QCoreApplication(argc, &p);
    }

    if (cService != NULL) {
        contextCritical() << "Service already initialize. You can only initialize one service with C API";
        return 0;
    }

    cService = new Service(bus_type == DBUS_BUS_SESSION
                           ? QDBusConnection::SessionBus
                           : QDBusConnection::SystemBus,
                           bus_name);
    listeners = new QList<Listener*>;

    return 1;
}

/// Stops the currently started service with context_provider_init. After calling
/// this function a new service can be started by calling context_provider_init.
void context_provider_stop (void)
{
    contextDebug() << F_C;
    if (cService) {
        contextDebug() << "Stopping service";

        // Delete all listeners
        if (listeners) {
            foreach (Listener *listener, *listeners)
                delete listener;
        }
        delete listeners; listeners = NULL;

        delete cService;
        cService = NULL;
    }
    // FIXME: Do we need to do something with the QCoreApplication we might have constructed?
}

/// Installs (adds) a \a key to be provided by the service. The callback function \a
/// subscription_changed_cb will be called with the passed user data \a subscription_changed_cb_target
/// when the status of the subscription changes -- when the first subscriber appears or the
/// last subscriber disappears. The \a clear_values_on_subscribe when enabled will automatically
/// clear (set to null/undetermined) the group keys on first subscribe.
void context_provider_install_key (const char* key,
                                   int clear_values_on_subscribe,
                                   ContextProviderSubscriptionChangedCallback subscription_changed_cb,
                                   void* subscription_changed_cb_target)
{
    contextDebug() << F_C << key;

    if (! cService) {
        contextCritical() << "Can't install key:" << key << "because no service started.";
        return;
    }

    listeners->append(new PropertyListener(*cService, key,
                                           clear_values_on_subscribe,
                                           subscription_changed_cb, subscription_changed_cb_target));
    cService->restart();
}

/// Installs (adds) a \a key_group to be provided by the service. The \a key_group is a NULL-terminated
/// array containing the keys. The callback function \a subscription_changed_cb will be called with the
/// passed user data \a subscription_changed_cb_target when the status of the subscription changes --
/// when the first subscriber appears or the last subscriber disappears. The \a clear_values_on_subscribe
/// when enabled will automatically clear (set to null/undetermined) the group keys on first subscribe.
void context_provider_install_group (const char** key_group,
                                     int clear_values_on_subscribe,
                                     ContextProviderSubscriptionChangedCallback subscription_changed_cb,
                                     void* subscription_changed_cb_target)
{
    contextDebug() << F_C;

    if (! cService) {
        contextCritical() << "Can't install key group because no service started.";
        return;
    }

    QStringList keys;
    int i = 0;
    while(key_group[i] != NULL) {
        QString key = QString(key_group[i]);

        keys << key;
        i++;
    }

    listeners->append(new GroupListener(*cService, keys,
                                        clear_values_on_subscribe,
                                        subscription_changed_cb, subscription_changed_cb_target));
    cService->restart();
}

/// Sets the \a key to a specified integer \a value.
void context_provider_set_integer (const char* key, int value)
{
    contextDebug() << F_C << key << value;
    if (cService)
        cService->setValue(key, value);
}

/// Sets the \a key to a specified double \a value.
void context_provider_set_double (const char* key, double value)
{
    contextDebug() << F_C << key << value;
    if (cService)
        cService->setValue(key, value);
}

/// Sets the \a key to a specified boolean \a value.
void context_provider_set_boolean (const char* key, int value)
{
    contextDebug() << F_C << key << value;
    if (cService)
        cService->setValue(key, (value != 0));
}

/// Sets the \a key to a specified string \a value.
void context_provider_set_string (const char* key, const char* value)
{
    contextDebug() << F_C << key << value;
    if (cService)
        cService->setValue(key, value);
}

/// Sets the \a key to NULL. In other words - unsets the key.
void context_provider_set_null (const char* key)
{
    contextDebug() << F_C << key;
    if (cService)
        cService->setValue(key, QVariant());
}
<|endoftext|>