<commit_before>/*
	autojson: A JSON parser base on the automaton provided by json.org
	Copyright (C) 2014  Wan Wai Ho

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation version 2
	of the License.

	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, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
	02110-1301, USA.
*/

#include "JSON_checker.h"

#include <functional>
#include <cassert>
#include <vector>
#include <string>
#include <gtest/gtest.h>

struct JsonToken
{
	JSON_event	type;
	std::string	value;
};

std::ostream& operator<<(std::ostream& os, const JsonToken& t)
{
	static const char *state[] =
	{
		"JSON_array_start",
		"JSON_array_end",
		"JSON_object_start",
		"JSON_object_key",	// string as object key
		"JSON_object_end",
		"JSON_string",		// string as object
		"JSON_number",		// number
		"JSON_null",
		"JSON_true",
		"JSON_false"
	};

	return os << "{" << state[t.type] << ", \"" << t.value << "\"}";
}

bool operator==(const JsonToken& t1, const JsonToken& t2)
{
	return t1.type == t2.type && t1.value == t2.value;
}

void Callback(void *pvec, JSON_event type, const char *data, int len)
{
	std::vector<JsonToken>	*vec = reinterpret_cast<std::vector<JsonToken>*>(pvec);

	// MSVC needs two lines
	JsonToken t {type, data != nullptr ? std::string(data, len) : ""};
	vec->push_back(t);
	assert(vec->back().value.size() == len);
}

TEST(ParsedOutputInCallback, JsonTest)
{
	JSON_checker jc = new_JSON_checker(5);

	std::vector<JsonToken> actual;

	const char js[] = "{ \"hello\": 100, \"world\": 200.03, \"a\\tr\"   : [1,true,3,4,{\"k\":5},\"abc\\u00fF\", false] }";
	ASSERT_EQ(JSON_ok, JSON_checker_char(jc, js, sizeof(js)-1, &Callback, &actual));

	std::vector<JsonToken> expect =
	{
		{JSON_object_start, ""},
		{JSON_object_key, "hello"},
		{JSON_number, "100"},
		{JSON_object_key, "world"},
		{JSON_number, "200.03"},
		{JSON_object_key, "a\\tr"},
		{JSON_array_start, ""},
		{JSON_number, "1"},
		{JSON_true, ""},
		{JSON_number, "3"},
		{JSON_number, "4"},
		{JSON_object_start, ""},
		{JSON_object_key, "k"},
		{JSON_number, "5"},
		{JSON_object_end, ""},
		{JSON_string, "abc\\u00fF"},
		{JSON_false, ""},
		{JSON_array_end, ""},
		{JSON_object_end, ""},
	};

	ASSERT_EQ(expect, actual);
}

TEST(PartialJsonCanBeParsed, JsonTest)
{
	JSON_checker jc = new_JSON_checker(5);

	std::vector<JsonToken> actual;

	const char js[] = "{ \"hello\": \"1234567890abcdefghijk\" }";
	ASSERT_EQ(JSON_ok, JSON_checker_char(jc, js, 20, &Callback, &actual));
	ASSERT_EQ(JSON_ok, JSON_checker_char(jc, js+20, sizeof(js)-20-1, &Callback, &actual));

	std::vector<JsonToken> expect =
	{
		{JSON_object_start, ""},
		{JSON_object_key, "hello"},
		{JSON_string, "1234567890abcdefghijk"},
		{JSON_object_end, ""},
	};
	ASSERT_EQ(expect, actual);
}
<commit_msg>ground works for the parsing framework<commit_after>/*
	autojson: A JSON parser base on the automaton provided by json.org
	Copyright (C) 2014  Wan Wai Ho

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation version 2
	of the License.

	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, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
	02110-1301, USA.
*/

#include "JSON_checker.h"

#include <functional>
#include <cassert>
#include <vector>
#include <string>
#include <gtest/gtest.h>

#include <iostream>
#include <map>

struct JsonToken
{
	JSON_event	type;
	std::string	value;
};

std::ostream& operator<<(std::ostream& os, const JsonToken& t)
{
	static const char *state[] =
	{
		"JSON_array_start",
		"JSON_array_end",
		"JSON_object_start",
		"JSON_object_key",	// string as object key
		"JSON_object_end",
		"JSON_string",		// string as object
		"JSON_number",		// number
		"JSON_null",
		"JSON_true",
		"JSON_false"
	};

	return os << "{" << state[t.type] << ", \"" << t.value << "\"}";
}

bool operator==(const JsonToken& t1, const JsonToken& t2)
{
	return t1.type == t2.type && t1.value == t2.value;
}

void Callback(void *pvec, JSON_event type, const char *data, int len)
{
	std::vector<JsonToken>	*vec = reinterpret_cast<std::vector<JsonToken>*>(pvec);

	// MSVC needs two lines
	JsonToken t {type, data != nullptr ? std::string(data, len) : ""};
	vec->push_back(t);
	assert(vec->back().value.size() == len);
}

TEST(ParsedOutputInCallback, JsonTest)
{
	JSON_checker jc = new_JSON_checker(5);

	std::vector<JsonToken> actual;

	const char js[] = "{ \"hello\": 100, \"world\": 200.03, \"a\\tr\"   : [1,true,3,4,{\"k\":5},\"abc\\u00fF\", false] }";
	ASSERT_EQ(JSON_ok, JSON_checker_char(jc, js, sizeof(js)-1, &Callback, &actual));

	std::vector<JsonToken> expect =
	{
		{JSON_object_start, ""},
		{JSON_object_key, "hello"},
		{JSON_number, "100"},
		{JSON_object_key, "world"},
		{JSON_number, "200.03"},
		{JSON_object_key, "a\\tr"},
		{JSON_array_start, ""},
		{JSON_number, "1"},
		{JSON_true, ""},
		{JSON_number, "3"},
		{JSON_number, "4"},
		{JSON_object_start, ""},
		{JSON_object_key, "k"},
		{JSON_number, "5"},
		{JSON_object_end, ""},
		{JSON_string, "abc\\u00fF"},
		{JSON_false, ""},
		{JSON_array_end, ""},
		{JSON_object_end, ""},
	};

	ASSERT_EQ(expect, actual);
}

TEST(PartialJsonCanBeParsed, JsonTest)
{
	JSON_checker jc = new_JSON_checker(5);

	std::vector<JsonToken> actual;

	const char js[] = "{ \"hello\": \"1234567890abcdefghijk\" }";
	ASSERT_EQ(JSON_ok, JSON_checker_char(jc, js, 20, &Callback, &actual));
	ASSERT_EQ(JSON_ok, JSON_checker_char(jc, js+20, sizeof(js)-20-1, &Callback, &actual));

	std::vector<JsonToken> expect =
	{
		{JSON_object_start, ""},
		{JSON_object_key, "hello"},
		{JSON_string, "1234567890abcdefghijk"},
		{JSON_object_end, ""},
	};
	ASSERT_EQ(expect, actual);
}

template <typename DestType>
class Handler
{
public :
	virtual void Do(DestType& t, const std::string& value) = 0;
};

template <typename DestType, typename T>
class SaveToMember : public Handler<DestType>
{
public :
	SaveToMember(T DestType::*member) : m_member(member)
	{
	}

	void Do(DestType& t, const std::string& value) override
	{
		t.*m_member = value;
	}

private :
	T DestType::*m_member;
};

template <typename DestType>
class JsonReactor
{
public:
	JsonReactor() : m_next(nullptr)
	{
	}

	void Start(DestType& t)
	{
		m_subj = &t;

		// fake it
		On(JSON_object_start,	nullptr,0);
		On(JSON_object_key,		"haha", 4);
		On(JSON_string,			"fun", 3);
	}

	template <typename T>
	void Add(const std::string& name, T DestType::*member)
	{
		m_actions[name] = new SaveToMember<DestType,T>(member);
	}

	void On(JSON_event event, const char *data, int len)
	{
		if (event == JSON_object_key)
		{
			auto i = m_actions.find(std::string(data,len)) ;
			m_next = (i != m_actions.end() ? i->second : nullptr);
		}
		else if (m_next != nullptr)
		{
			m_next->Do(*m_subj, std::string(data,len));
		}
	}

private :
	DestType	*m_subj;

	std::map<std::string, Handler<DestType>*> m_actions;
	Handler<DestType> *m_next;
};

TEST(TryOutCpp, JsonTest)
{
	struct Subject
	{
		std::string value;
	};

	JsonReactor<Subject> r;
	Subject j {};
	r.Add("haha", &Subject::value);
	r.Start(j);
	ASSERT_EQ("fun", j.value) ;
}
<|endoftext|>


<commit_before>#include <cassert>
#include <cmath>
#include <complex>
#include <limits>
#include <fstream>
#include <iterator>

#include "Modulator_USR.hpp"

/*
 * Constructor / Destructor
 */
template <typename B, typename R, typename Q, proto_max<Q> MAX>
Modulator_USR<B,R,Q,MAX>
::Modulator_USR(const int N, const int bits_per_symbol, const std::string const_path, const R sigma,
                const bool disable_sig2, const int n_frames, const std::string name)
: Modulator<B,R,Q>(N, std::ceil((float)N / (float)bits_per_symbol) * 2, n_frames, name),
  bits_per_symbol(bits_per_symbol),
  nbr_symbols    (1 << bits_per_symbol),
  sigma          (sigma),
  sqrt_es        (0.0),
  disable_sig2   (disable_sig2),
  constellation  ()
{
	std::fstream const_file(const_path, std::ios_base::in);

	std::string temp;
	while (std::getline(const_file, temp))
	{
		if (temp[0] == '#') continue;

		std::istringstream buffer(temp);
		std::vector<R> line((std::istream_iterator<R>(buffer)), std::istream_iterator<R>());
		assert (line.size() < 3);

		if (line.size() == 2)
			constellation.push_back(std::complex<R>(line[0],line[1]));
		else
			constellation.push_back(std::complex<R>(line[0],0.0));
		sqrt_es += std::norm(constellation.back());
	}
	sqrt_es = sqrt(sqrt_es/nbr_symbols);

	assert (constellation.size() == nbr_symbols);

	for (auto i = 0; i < nbr_symbols; i++)
		constellation[i] /= (std::complex<R>)sqrt_es;

	const_file.close();
}

template <typename B, typename R, typename Q, proto_max<Q> MAX>
Modulator_USR<B,R,Q,MAX>
::~Modulator_USR()
{
}

/*
 * int get_buffer_size_after_modulation(const int N)
 * N = number of input bits
 * returns number of output symbols
 */
template <typename B, typename R, typename Q, proto_max<Q> MAX>
int Modulator_USR<B,R,Q,MAX>
::get_buffer_size_after_modulation(const int N)
{
	assert(this->bits_per_symbol % 2 == 0);
	return std::ceil((float)N / (float)this->bits_per_symbol) * 2;
}

/*
 * Modulator
 */
template <typename B,typename R, typename Q, proto_max<Q> MAX>
void Modulator_USR<B,R,Q,MAX>
::modulate(const mipp::vector<B>& X_N1, mipp::vector<R>& X_N2)
{
	auto size_in  = (int)X_N1.size();
	auto size_out = (int)X_N2.size();
	auto bps      = this->bits_per_symbol;

	auto main_loop_size = size_in / bps;
	for (auto i = 0; i < main_loop_size; i++)
	{
		unsigned idx = 0;
		for (auto j = 0; j < bps; j++)
			idx += (1 << (bps-j-1)) * X_N1[i * bps +j];
		auto symbol = this->constellation[idx];

		X_N2[2*i   ] = symbol.real();
		X_N2[2*i +1] = symbol.imag();
	}

	// last elements if "size_in" is not a multiple of the number of bits per symbol
	if (main_loop_size * bps < size_in)
	{
		unsigned idx = 0;
		for (auto j = 0; j < size_in - (main_loop_size * bps); j++)
			idx += (1 << (bps-j-1)) * X_N1[main_loop_size * bps +j];
		auto symbol = this->constellation[idx];

		X_N2[size_out -2] = symbol.real();
		X_N2[size_out -1] = symbol.imag();
	}
}

/*
 * Demodulator
 */
template <typename B,typename R, typename Q, proto_max<Q> MAX>
void Modulator_USR<B,R,Q,MAX>
::demodulate(const mipp::vector<Q>& Y_N1, mipp::vector<Q>& Y_N2)
{
	assert(typeid(R) == typeid(Q));
	assert(typeid(Q) == typeid(float) || typeid(Q) == typeid(double));

	auto size       = (int)Y_N2.size();
	auto inv_sigma2 = disable_sig2 ? (Q)1.0 : (Q)1.0 / (this->sigma * this->sigma);
	auto bps = this->bits_per_symbol;
	for (auto n = 0; n < size; n++)// Boucle sur les LLRs
	{
		auto L0 = -std::numeric_limits<Q>::infinity();
		auto L1 = -std::numeric_limits<Q>::infinity();
		auto b  = n % bps; // position du bit
		auto k  = n / bps; // Position du symbole

		auto complex_Yk = std::complex<Q>(Y_N1[2*k], Y_N1[2*k+1]);

		for (auto j = 0; j < this->nbr_symbols; j++)
			if ((j &(1 << (bps-b-1))) == 0)
				L0 = MAX(L0, -std::norm(complex_Yk - std::complex<Q>(this->constellation[j]))* inv_sigma2);
			else
				L1 = MAX(L1, -std::norm(complex_Yk - std::complex<Q>(this->constellation[j]))* inv_sigma2);

		Y_N2[n] = (L0 - L1);
	}
}

template <typename B,typename R, typename Q, proto_max<Q> MAX>
void Modulator_USR<B,R,Q,MAX>
::demodulate(const mipp::vector<Q>& Y_N1, const mipp::vector<Q>& Y_N2,mipp::vector<Q>& Y_N3)
{
	assert(typeid(R) == typeid(Q));
	assert(typeid(Q) == typeid(float) || typeid(Q) == typeid(double));

	auto size       = (int)Y_N3.size();
	auto inv_sigma2 = disable_sig2 ? (Q)1.0 : (Q)1.0 / (this->sigma * this->sigma);
	auto bps = this->bits_per_symbol;

	for (auto n = 0; n < size; n++)// Boucle sur les LLRs
	{
		auto L0 = -std::numeric_limits<Q>::infinity();
		auto L1 = -std::numeric_limits<Q>::infinity();
		auto b  = n % bps; // position du bit
		auto k  = n / bps; // Position du symbole

		auto complex_Yk = std::complex<Q>(Y_N1[2*k], Y_N1[2*k+1]);

		for (auto j = 0; j < this->nbr_symbols; j++)
		{
			auto tempL  = std::norm(complex_Yk - std::complex<Q>(this->constellation[j])) * inv_sigma2;
			for(auto l=0; l < b ; l++)
			{
				tempL += (j & (1 << (bps-l-1)))*Y_N2[k*bps+l];
			}
			for(auto l=b+1; l < bps ; l++)
			{
				tempL += (j & (1 << (bps-l-1)))*Y_N2[k*bps+l];
			}
			if ((j & (1 << (bps-b-1))) == 0)
				L0 = MAX(L0, -tempL);
			else
				L1 = MAX(L1, -tempL);
		}

		Y_N3[n] = (L0 - L1);
	}
}

<commit_msg>Correction of minor bugs in USR<commit_after>#include <cassert>
#include <cmath>
#include <complex>
#include <limits>
#include <fstream>
#include <iterator>

#include "Modulator_USR.hpp"

/*
 * Constructor / Destructor
 */
template <typename B, typename R, typename Q, proto_max<Q> MAX>
Modulator_USR<B,R,Q,MAX>
::Modulator_USR(const int N, const int bits_per_symbol, const std::string const_path, const R sigma,
                const bool disable_sig2, const int n_frames, const std::string name)
: Modulator<B,R,Q>(N, std::ceil((float)N / (float)bits_per_symbol) * 2, n_frames, name),
  bits_per_symbol(bits_per_symbol),
  nbr_symbols    (1 << bits_per_symbol),
  sigma          (sigma),
  sqrt_es        (0.0),
  disable_sig2   (disable_sig2),
  constellation  ()
{
	std::fstream const_file(const_path, std::ios_base::in);

	std::string temp;
	while (std::getline(const_file, temp))
	{
		if (temp[0] == '#') continue;

		std::istringstream buffer(temp);
		std::vector<R> line((std::istream_iterator<R>(buffer)), std::istream_iterator<R>());
		assert (line.size() < 3);

		if (line.size() == 2)
			constellation.push_back(std::complex<R>(line[0],line[1]));
		else
			constellation.push_back(std::complex<R>(line[0],0.0));
		sqrt_es += std::norm(constellation.back());
	}
	sqrt_es = sqrt(sqrt_es/nbr_symbols);

	assert (constellation.size() == nbr_symbols);

	for (auto i = 0; i < nbr_symbols; i++)
		constellation[i] /= (std::complex<R>)sqrt_es;

	const_file.close();
}

template <typename B, typename R, typename Q, proto_max<Q> MAX>
Modulator_USR<B,R,Q,MAX>
::~Modulator_USR()
{
}

/*
 * int get_buffer_size_after_modulation(const int N)
 * N = number of input bits
 * returns number of output symbols
 */
template <typename B, typename R, typename Q, proto_max<Q> MAX>
int Modulator_USR<B,R,Q,MAX>
::get_buffer_size_after_modulation(const int N)
{
	assert(this->bits_per_symbol % 2 == 0);
	return std::ceil((float)N / (float)this->bits_per_symbol) * 2;
}

/*
 * Modulator
 */
template <typename B,typename R, typename Q, proto_max<Q> MAX>
void Modulator_USR<B,R,Q,MAX>
::modulate(const mipp::vector<B>& X_N1, mipp::vector<R>& X_N2)
{
	auto size_in  = (int)X_N1.size();
	auto size_out = (int)X_N2.size();
	auto bps      = this->bits_per_symbol;

	auto main_loop_size = size_in / bps;
	for (auto i = 0; i < main_loop_size; i++)
	{
		unsigned idx = 0;
		for (auto j = 0; j < bps; j++)
			idx += (1 << (bps-j-1)) * X_N1[i * bps +j];
		auto symbol = this->constellation[idx];

		X_N2[2*i   ] = symbol.real();
		X_N2[2*i +1] = symbol.imag();
	}

	// last elements if "size_in" is not a multiple of the number of bits per symbol
	if (main_loop_size * bps < size_in)
	{
		unsigned idx = 0;
		for (auto j = 0; j < size_in - (main_loop_size * bps); j++)
			idx += (1 << (bps-j-1)) * X_N1[main_loop_size * bps +j];
		auto symbol = this->constellation[idx];

		X_N2[size_out -2] = symbol.real();
		X_N2[size_out -1] = symbol.imag();
	}
}

/*
 * Demodulator
 */
template <typename B,typename R, typename Q, proto_max<Q> MAX>
void Modulator_USR<B,R,Q,MAX>
::demodulate(const mipp::vector<Q>& Y_N1, mipp::vector<Q>& Y_N2)
{
	assert(typeid(R) == typeid(Q));
	assert(typeid(Q) == typeid(float) || typeid(Q) == typeid(double));

	auto size       = (int)Y_N2.size();
	auto inv_sigma2 = disable_sig2 ? (Q)1.0 : (Q)1.0 / (this->sigma * this->sigma);

	for (auto n = 0; n < size; n++) // boucle sur les LLRs
	{
		auto L0 = -std::numeric_limits<Q>::infinity();
		auto L1 = -std::numeric_limits<Q>::infinity();

		auto b  = n % this->bits_per_symbol; // position du bit
		auto k  = n / this->bits_per_symbol; // position du symbole

		auto complex_Yk = std::complex<Q>(Y_N1[2*k], Y_N1[2*k+1]);

		for (auto j = 0; j < this->nbr_symbols; j++)
			if ((j &(1 << (this->bits_per_symbol -b -1))) == 0)
				L0 = MAX(L0, -std::norm(complex_Yk - std::complex<Q>(this->constellation[j])) * inv_sigma2);
			else
				L1 = MAX(L1, -std::norm(complex_Yk - std::complex<Q>(this->constellation[j])) * inv_sigma2);

		Y_N2[n] = (L0 - L1);
	}
}

template <typename B, typename R, typename Q, proto_max<Q> MAX>
void Modulator_USR<B,R,Q,MAX>
::demodulate(const mipp::vector<Q>& Y_N1, const mipp::vector<Q>& Y_N2, mipp::vector<Q>& Y_N3)
{
	assert(typeid(R) == typeid(Q));
	assert(typeid(Q) == typeid(float) || typeid(Q) == typeid(double));

	auto size       = (int)Y_N3.size();
	auto inv_sigma2 = disable_sig2 ? (Q)1.0 : (Q)1.0 / (this->sigma * this->sigma);

	for (auto n = 0; n < size; n++) // boucle sur les LLRs
	{
		auto L0 = -std::numeric_limits<Q>::infinity();
		auto L1 = -std::numeric_limits<Q>::infinity();
		auto b  = n % this->bits_per_symbol; // position du bit
		auto k  = n / this->bits_per_symbol; // position du symbole

		auto complex_Yk = std::complex<Q>(Y_N1[2*k], Y_N1[2*k+1]);

		for (auto j = 0; j < this->nbr_symbols; j++)
		{
			auto tempL = std::norm(complex_Yk - std::complex<Q>(this->constellation[j])) * inv_sigma2;
			for (auto l = 0; l < b; l++)
				tempL += (j & (1 << (this->bits_per_symbol -l -1))) * Y_N2[k * this->bits_per_symbol +l];

			for (auto l = b + 1; l < this->bits_per_symbol; l++)
				tempL += (j & (1 << (this->bits_per_symbol-l-1))) * Y_N2[k * this->bits_per_symbol +l];

			if ((j & (1 << (this->bits_per_symbol-b-1))) == 0)
				L0 = MAX(L0, -tempL);
			else
				L1 = MAX(L1, -tempL);
		}

		Y_N3[n] = (L0 - L1);
	}
}

<|endoftext|>


<commit_before>#include "SqlTest.h"
#include "SqlStorable.h"
#include "SqlStatement.h"
#include "SqlTransaction.h"
#include <thread>
#ifdef HAVE_SQLITE3
#include "SqliteConnector.h"
#endif
#ifdef HAVE_POSTGRES
#include "PostgresConnector.h"
#endif

using namespace ::metacpp;
using namespace ::metacpp::db;
using namespace ::metacpp::db::sql;

class City : public Object
{
public:
    int             id;
    String          name;

    META_INFO_DECLARE(City)
};

STRUCT_INFO_BEGIN(City)
    FIELD(City, id)
    FIELD(City, name, "Moscow")
STRUCT_INFO_END(City)

REFLECTIBLE_F(City)

META_INFO(City)

DEFINE_STORABLE(City,
                 PRIMARY_KEY(COL(City::id)),
                 UNIQUE_INDEX(COL(City::id))
                 )

class Person : public Object
{
public:
    int                 id;
    String              name;
    Nullable<int>       age;
    Nullable<double>    cat_weight;
    int                 cityId;
    Nullable<DateTime>  birthday;

    META_INFO_DECLARE(Person)
};

STRUCT_INFO_BEGIN(Person)
    FIELD(Person, id)
    FIELD(Person, name)
    FIELD(Person, age)
    FIELD(Person, cat_weight)
    FIELD(Person, cityId)
    FIELD(Person, birthday)
STRUCT_INFO_END(Person)

REFLECTIBLE_F(Person)

META_INFO(Person)

DEFINE_STORABLE(Person,
                 PRIMARY_KEY(COL(Person::id)),
                 REFERENCES(COL(Person::cityId), COL(City::id)),
                 UNIQUE_INDEX(COL(Person::id)),
                 INDEX(COL(Person::cityId)),
                 CHECK(COL(Person::age), COL(Person::age) < 120)    // humans do not live so much
                 )

void SqlTest::SetUp()
{
#ifdef HAVE_SQLITE3
    m_conn = std::move(connectors::SqlConnectorBase::createConnector(Uri("sqlite3://memdb?mode=memory&cache=shared")));
#elif defined(HAVE_POSTGRES)
    m_conn = std::move(connectors::SqlConnectorBase::createConnector(Uri("postgres://?dbname=alien&hostaddr=127.0.0.1")));
#endif
    ASSERT_TRUE(m_conn.get()) << "Sql connector unavailable";
    m_conn->setConnectionPooling(3);
    connectors::SqlConnectorBase::setDefaultConnector(m_conn.get());
    ASSERT_TRUE(m_conn->connect());
    prepareSchema();
}

void SqlTest::TearDown()
{
    connectors::SqlConnectorBase::setDefaultConnector(nullptr);
    ASSERT_TRUE(m_conn.get());
    EXPECT_TRUE(m_conn->disconnect());
    m_conn.reset();
}

void SqlTest::SetUpTestCase()
{
#ifdef HAVE_SQLITE3
    connectors::SqlConnectorBase::registerConnectorFactory("sqlite3", std::make_shared<connectors::sqlite::SqliteConnectorFactory>());
#endif
#ifdef HAVE_POSTGRES
    connectors::SqlConnectorBase::registerConnectorFactory("postgres", std::make_shared<connectors::postgres::PostgresConnectorFactory>());
#endif
}

void SqlTest::TearDownTestCase()
{
#ifdef HAVE_SQLITE3
    connectors::SqlConnectorBase::unregisterConnectorFactory("sqlite3");
#endif
#ifdef HAVE_POSTGRES
    connectors::SqlConnectorBase::unregisterConnectorFactory("postgres");
#endif
}

void SqlTest::prepareSchema()
{
    SqlTransaction transaction;
    Storable<City>::createSchema(transaction);
    Storable<Person>::createSchema(transaction);
    transaction.commit();
}

void SqlTest::prepareData()
{
    SqlTransaction transaction;
    Storable<City> city;
    city.init();
    city.name = "Moscow";
    city.insertOne(transaction);
    Storable<Person> person;
    person.init();
    person.name = "Pupkin";
    person.birthday = DateTime::fromString("2004-12-31 00:00:00");
    person.cityId = city.id;
    person.insertOne(transaction);
    transaction.commit();
}

void SqlTest::clearData()
{
    SqlTransaction transaction;
    Storable<City> city;
    Storable<Person> person;
    person.remove().exec(transaction);
    city.remove().exec(transaction);
    transaction.commit();
}

#ifdef HAVE_SQLITE3

TEST(StorableTest, testConstraints)
{
    ASSERT_EQ(Storable<Person>::numConstraints(), 5);
}

TEST_F(SqlTest, transactionCommitTest)
{
    SqlTransaction transaction;
    ASSERT_NO_THROW(transaction.commit());
}

TEST_F(SqlTest, transactionRollbackTest)
{
    SqlTransaction transaction;
    ASSERT_NO_THROW(transaction.rollback());
}

TEST_F(SqlTest, transactionManualBegin)
{
    SqlTransaction transaction(SqlTransactionAutoCloseManual);
    ASSERT_NO_THROW(transaction.begin());
    ASSERT_ANY_THROW(transaction.begin());
    ASSERT_NO_THROW(transaction.commit());
    ASSERT_ANY_THROW(transaction.commit());
}

TEST_F(SqlTest, multipleTransactionsTest)
{
    const size_t numThreads = 10;
    std::thread threads[numThreads];
    for (size_t i = 0; i < numThreads; ++i)
    {
        threads[i] = std::thread([]()
            {
                SqlTransaction transaction;
                std::this_thread::sleep_for(std::chrono::milliseconds(100));
            });
    }

    for (size_t i = 0; i < numThreads; ++i)
        if (threads[i].joinable())
            threads[i].join();
}

TEST_F(SqlTest, selectTest)
{
    prepareData();
    try
    {
        SqlTransaction transaction;
        Storable<Person> person;
        Storable<City> city;
        SqlResultSet resultSet = person.select().innerJoin<City>().where((COL(Person::age).isNull() ||
                (coalesce(COL(Person::age), db::random()) + 2.5  * COL(Person::cat_weight)) > 250) &&
                COL(Person::cityId) == COL(City::id) &&
                !lower(COL(Person::name)).like("invalid_%") &&
                coalesce(COL(Person::birthday), DateTime::fromString("2000-01-01 00:00:00")) >= DateTime::fromString("2000-01-01 00:00:00"))
                .limit(10).orderAsc(COL(Person::name), COL(City::name)).orderDesc(COL(Person::age)).exec(transaction);

        StringArray persons;
        for (auto it : resultSet)
        {
            (void)it;
            persons.push_back(person.name);
        }

        person.remove().exec(transaction);

        transaction.commit();
    }
    catch (const std::exception& ex)
    {
        throw;
    }
    clearData();
}

TEST_F(SqlTest, updateTest)
{
    prepareData();
    try
    {
        prepareData();
        SqlTransaction transaction;
        Storable<Person> person;
        person.update().ref<City>().set(COL(Person::age) = null, COL(Person::cat_weight) = null)
                .where(COL(Person::cityId) == COL(City::id) && COL(City::name) == String("Moscow") &&
                       (COL(Person::age) == null || COL(Person::cat_weight) == null)).exec(transaction);
        transaction.commit();
    }
    catch (const std::exception& ex)
    {
        throw;
    }
    clearData();
}

TEST_F(SqlTest, insertTest)
{
    try
    {
        SqlTransaction transaction;
        Storable<City> city;
        auto resultSet = city.select().where(COL(City::name) == String("Moscow"))
                .exec(transaction);
        auto it = resultSet.begin();
        if (it != resultSet.end())
        {
            Storable<Person> person;
            person.init();
            person.cityId = city.id;
            person.name = "Pupkin";
            ASSERT_TRUE(person.insertOne(transaction));
            person.name = "Pupkin new";
            ASSERT_TRUE(person.updateOne(transaction));
            ASSERT_TRUE(person.removeOne(transaction));
        }

        transaction.commit();
    }
    catch (const std::exception& ex)
    {
        throw;
    }
}

TEST_F(SqlTest, deleteTest)
{
    try
    {
        SqlTransaction transaction;
        Storable<Person> person;
        person.remove().ref<City>().where(COL(City::id) == COL(Person::cityId) &&
                                          COL(City::name) == String("Moscow") &&
                                          COL(Person::name).like("invalid_%")).exec(transaction);
    }
    catch (const std::exception& ex)
    {
        throw;
    }
}
#endif
<commit_msg>user-defined function example<commit_after>#include "SqlTest.h"
#include "SqlStorable.h"
#include "SqlStatement.h"
#include "SqlTransaction.h"
#include <thread>
#ifdef HAVE_SQLITE3
#include "SqliteConnector.h"
#endif
#ifdef HAVE_POSTGRES
#include "PostgresConnector.h"
#endif

using namespace ::metacpp;
using namespace ::metacpp::db;
using namespace ::metacpp::db::sql;

class City : public Object
{
public:
    int             id;
    String          name;

    META_INFO_DECLARE(City)
};

STRUCT_INFO_BEGIN(City)
    FIELD(City, id)
    FIELD(City, name, "Moscow")
STRUCT_INFO_END(City)

REFLECTIBLE_F(City)

META_INFO(City)

DEFINE_STORABLE(City,
                 PRIMARY_KEY(COL(City::id)),
                 UNIQUE_INDEX(COL(City::id))
                 )

class Person : public Object
{
public:
    int                 id;
    String              name;
    Nullable<int>       age;
    Nullable<double>    cat_weight;
    int                 cityId;
    Nullable<DateTime>  birthday;

    META_INFO_DECLARE(Person)
};

STRUCT_INFO_BEGIN(Person)
    FIELD(Person, id)
    FIELD(Person, name)
    FIELD(Person, age)
    FIELD(Person, cat_weight)
    FIELD(Person, cityId)
    FIELD(Person, birthday)
STRUCT_INFO_END(Person)

REFLECTIBLE_F(Person)

META_INFO(Person)

DEFINE_STORABLE(Person,
                 PRIMARY_KEY(COL(Person::id)),
                 REFERENCES(COL(Person::cityId), COL(City::id)),
                 UNIQUE_INDEX(COL(Person::id)),
                 INDEX(COL(Person::cityId)),
                 CHECK(COL(Person::age), COL(Person::age) < 120)    // humans do not live so much
                 )

// User-defined SQL function now() for Postgresql
inline ExpressionNodeFunctionCall<DateTime> db_now()
{
    return ExpressionNodeFunctionCall<DateTime>("now");
}

void SqlTest::SetUp()
{
#ifdef HAVE_SQLITE3
    m_conn = std::move(connectors::SqlConnectorBase::createConnector(Uri("sqlite3://memdb?mode=memory&cache=shared")));
#elif defined(HAVE_POSTGRES)
    m_conn = std::move(connectors::SqlConnectorBase::createConnector(Uri("postgres://?dbname=alien&hostaddr=127.0.0.1")));
#endif
    ASSERT_TRUE(m_conn.get()) << "Sql connector unavailable";
    m_conn->setConnectionPooling(3);
    connectors::SqlConnectorBase::setDefaultConnector(m_conn.get());
    ASSERT_TRUE(m_conn->connect());
    prepareSchema();
}

void SqlTest::TearDown()
{
    connectors::SqlConnectorBase::setDefaultConnector(nullptr);
    ASSERT_TRUE(m_conn.get());
    EXPECT_TRUE(m_conn->disconnect());
    m_conn.reset();
}

void SqlTest::SetUpTestCase()
{
#ifdef HAVE_SQLITE3
    connectors::SqlConnectorBase::registerConnectorFactory("sqlite3", std::make_shared<connectors::sqlite::SqliteConnectorFactory>());
#endif
#ifdef HAVE_POSTGRES
    connectors::SqlConnectorBase::registerConnectorFactory("postgres", std::make_shared<connectors::postgres::PostgresConnectorFactory>());
#endif
}

void SqlTest::TearDownTestCase()
{
#ifdef HAVE_SQLITE3
    connectors::SqlConnectorBase::unregisterConnectorFactory("sqlite3");
#endif
#ifdef HAVE_POSTGRES
    connectors::SqlConnectorBase::unregisterConnectorFactory("postgres");
#endif
}

void SqlTest::prepareSchema()
{
    SqlTransaction transaction;
    Storable<City>::createSchema(transaction);
    Storable<Person>::createSchema(transaction);
    transaction.commit();
}

void SqlTest::prepareData()
{
    SqlTransaction transaction;
    Storable<City> city;
    city.init();
    city.name = "Moscow";
    city.insertOne(transaction);
    Storable<Person> person;
    person.init();
    person.name = "Pupkin";
    person.birthday = DateTime::fromString("2004-12-31 00:00:00");
    person.cityId = city.id;
    person.insertOne(transaction);
    transaction.commit();
}

void SqlTest::clearData()
{
    SqlTransaction transaction;
    Storable<City> city;
    Storable<Person> person;
    person.remove().exec(transaction);
    city.remove().exec(transaction);
    transaction.commit();
}

#ifdef HAVE_SQLITE3

TEST(StorableTest, testConstraints)
{
    ASSERT_EQ(Storable<Person>::numConstraints(), 5);
}

TEST_F(SqlTest, transactionCommitTest)
{
    SqlTransaction transaction;
    ASSERT_NO_THROW(transaction.commit());
}

TEST_F(SqlTest, transactionRollbackTest)
{
    SqlTransaction transaction;
    ASSERT_NO_THROW(transaction.rollback());
}

TEST_F(SqlTest, transactionManualBegin)
{
    SqlTransaction transaction(SqlTransactionAutoCloseManual);
    ASSERT_NO_THROW(transaction.begin());
    ASSERT_ANY_THROW(transaction.begin());
    ASSERT_NO_THROW(transaction.commit());
    ASSERT_ANY_THROW(transaction.commit());
}

TEST_F(SqlTest, multipleTransactionsTest)
{
    const size_t numThreads = 10;
    std::thread threads[numThreads];
    for (size_t i = 0; i < numThreads; ++i)
    {
        threads[i] = std::thread([]()
            {
                SqlTransaction transaction;
                std::this_thread::sleep_for(std::chrono::milliseconds(100));
            });
    }

    for (size_t i = 0; i < numThreads; ++i)
        if (threads[i].joinable())
            threads[i].join();
}

TEST_F(SqlTest, selectTest)
{
    prepareData();
    try
    {
        SqlTransaction transaction;
        Storable<Person> person;
        Storable<City> city;
        SqlResultSet resultSet = person.select().innerJoin<City>().where((COL(Person::age).isNull() ||
                (coalesce(COL(Person::age), db::random()) + 2.5  * COL(Person::cat_weight)) > 250) &&
                COL(Person::cityId) == COL(City::id) &&
                !lower(COL(Person::name)).like("invalid_%") &&
                coalesce(COL(Person::birthday), DateTime::fromString("2000-01-01 00:00:00")) >= DateTime::fromString("2000-01-01 00:00:00"))
                .limit(10).orderAsc(COL(Person::name), COL(City::name)).orderDesc(COL(Person::age)).exec(transaction);

        StringArray persons;
        for (auto it : resultSet)
        {
            (void)it;
            persons.push_back(person.name);
        }

        person.remove().exec(transaction);

        transaction.commit();
    }
    catch (const std::exception& ex)
    {
        throw;
    }
    clearData();
}

TEST_F(SqlTest, updateTest)
{
    prepareData();
    try
    {
        prepareData();
        SqlTransaction transaction;
        Storable<Person> person;
        person.update().ref<City>().set(COL(Person::age) = null, COL(Person::cat_weight) = null)
                .where(COL(Person::cityId) == COL(City::id) && COL(City::name) == String("Moscow") &&
                       (COL(Person::age) == null || COL(Person::cat_weight) == null)).exec(transaction);
        transaction.commit();
    }
    catch (const std::exception& ex)
    {
        throw;
    }
    clearData();
}

TEST_F(SqlTest, insertTest)
{
    try
    {
        SqlTransaction transaction;
        Storable<City> city;
        auto resultSet = city.select().where(COL(City::name) == String("Moscow"))
                .exec(transaction);
        auto it = resultSet.begin();
        if (it != resultSet.end())
        {
            Storable<Person> person;
            person.init();
            person.cityId = city.id;
            person.name = "Pupkin";
            ASSERT_TRUE(person.insertOne(transaction));
            person.name = "Pupkin new";
            ASSERT_TRUE(person.updateOne(transaction));
            ASSERT_TRUE(person.removeOne(transaction));
        }

        transaction.commit();
    }
    catch (const std::exception& ex)
    {
        throw;
    }
}

TEST_F(SqlTest, deleteTest)
{
    try
    {
        SqlTransaction transaction;
        Storable<Person> person;
        person.remove().ref<City>().where(COL(City::id) == COL(Person::cityId) &&
                                          COL(City::name) == String("Moscow") &&
                                          COL(Person::name).like("invalid_%")).exec(transaction);
    }
    catch (const std::exception& ex)
    {
        throw;
    }
}
#endif
<|endoftext|>


<commit_before>///
/// @file  iterator.cpp
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve/iterator.hpp>
#include <primesieve/IteratorHelper.hpp>
#include <primesieve/PrimeGenerator.hpp>
#include <primesieve/macros.hpp>
#include <primesieve/pod_vector.hpp>

#include <stdint.h>
#include <cassert>
#include <cstring>

namespace {

using namespace primesieve;

void deletePrimeGenerator(primesieve::iterator* it)
{
  delete (PrimeGenerator*) it->primeGenerator_;
  it->primeGenerator_ = nullptr;
}

void deletePrimesVector(primesieve::iterator* it)
{
  delete (pod_vector<uint64_t>*) it->primesVector_;
  it->primesVector_ = nullptr;
}

pod_vector<uint64_t>& getPrimes(primesieve::iterator* it)
{
  return *(pod_vector<uint64_t>*) it->primesVector_;
}

} // namespace

namespace primesieve {

iterator::iterator() noexcept :
  i_(0),
  last_idx_(0),
  start_(0),
  stop_(0),
  stop_hint_(std::numeric_limits<uint64_t>::max()),
  dist_(0),
  primes_(nullptr),
  primesVector_(nullptr),
  primeGenerator_(nullptr)
{ }

iterator::iterator(uint64_t start,
                   uint64_t stop_hint) noexcept :
  i_(0),
  last_idx_(0),
  start_(start),
  stop_(start),
  stop_hint_(stop_hint),
  dist_(0),
  primes_(nullptr),
  primesVector_(nullptr),
  primeGenerator_(nullptr)
{ }

/// Move constructor
iterator::iterator(iterator&& other) noexcept :
  i_(other.i_),
  last_idx_(other.last_idx_),
  start_(other.start_),
  stop_(other.stop_),
  stop_hint_(other.stop_hint_),
  dist_(other.dist_),
  primes_(other.primes_),
  primesVector_(other.primesVector_),
  primeGenerator_(other.primeGenerator_)
{
  other.i_ = 0;
  other.last_idx_ = 0;
  other.start_ = 0;
  other.stop_ = 0;
  other.stop_hint_ = std::numeric_limits<uint64_t>::max();
  other.dist_ = 0;
  other.primes_ = nullptr;
  other.primesVector_ = nullptr;
  other.primeGenerator_ = nullptr;
}

/// Move assignment operator
iterator& iterator::operator=(iterator&& other) noexcept
{
  if (this != &other)
  {
    i_ = other.i_;
    last_idx_ = other.last_idx_;
    start_ = other.start_;
    stop_ = other.stop_;
    stop_hint_ = other.stop_hint_;
    dist_ = other.dist_;
    primes_ = other.primes_;
    primesVector_ = other.primesVector_;
    primeGenerator_ = other.primeGenerator_;

    other.i_ = 0;
    other.last_idx_ = 0;
    other.start_ = 0;
    other.stop_ = 0;
    other.stop_hint_ = std::numeric_limits<uint64_t>::max();
    other.dist_ = 0;
    other.primes_ = nullptr;
    other.primesVector_ = nullptr;
    other.primeGenerator_ = nullptr;
  }

  return *this;
}

void iterator::skipto(uint64_t start,
                      uint64_t stop_hint) noexcept
{
  i_ = 0;
  last_idx_ = 0;
  start_ = start;
  stop_ = start;
  stop_hint_ = stop_hint;
  dist_ = 0;
  primes_ = nullptr;
  deletePrimeGenerator(this);
}

iterator::~iterator()
{
  clear();
}

void iterator::clear() noexcept
{
  deletePrimeGenerator(this);
  deletePrimesVector(this);
}

void iterator::generate_next_primes()
{
  std::size_t size = 0;

  while (!size)
  {
    auto* primeGenerator = (PrimeGenerator*) primeGenerator_;

    if (!primeGenerator)
    {
      deletePrimeGenerator(this);
      IteratorHelper::next(&start_, &stop_, stop_hint_, &dist_);
      primeGenerator = new PrimeGenerator(start_, stop_);
      primeGenerator_ = primeGenerator;
      if (!primesVector_)
        primesVector_ = new pod_vector<uint64_t>();
    }

    auto& primes = getPrimes(this);
    primeGenerator->fillNextPrimes(primes, &size);

    // There are 3 different cases here:
    // 1) The primes array contains a few primes (<= 512).
    //    In this case we return the primes to the user.
    // 2) The primes array is empty because the next
    //    prime > stop_. In this case we reset the
    //    primeGenerator object, increase the start_ & stop_
    //    numbers and sieve the next segment.
    // 3) The next prime > 2^64. In this case the primes
    //    array contains an error code (UINT64_MAX) which
    //    is returned to the user.
    if (size == 0)
      deletePrimeGenerator(this);
  }

  auto& primes = getPrimes(this);
  i_ = 0;
  last_idx_ = size - 1;
  primes_ = &primes[0];
}

void iterator::generate_prev_primes()
{
  if (!primesVector_)
    primesVector_ = new pod_vector<uint64_t>();

  auto& primes = getPrimes(this);

  // Special case if generate_next_primes() has
  // been used before generate_prev_primes().
  if_unlikely(primeGenerator_)
  {
    assert(!primes.empty());
    start_ = primes.front();
    deletePrimeGenerator(this);
  }

  std::size_t size = 0;

  while (!size)
  {
    IteratorHelper::prev(&start_, &stop_, stop_hint_, &dist_);
    PrimeGenerator primeGenerator(start_, stop_);
    primeGenerator.fillPrevPrimes(primes, &size);
  }

  last_idx_ = size - 1;
  i_ = last_idx_;
  primes_ = &primes[0];
}

} // namespace
<commit_msg>Fix memory leak<commit_after>///
/// @file  iterator.cpp
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve/iterator.hpp>
#include <primesieve/IteratorHelper.hpp>
#include <primesieve/PrimeGenerator.hpp>
#include <primesieve/macros.hpp>
#include <primesieve/pod_vector.hpp>

#include <stdint.h>
#include <cassert>
#include <cstring>

namespace {

using namespace primesieve;

void deletePrimeGenerator(primesieve::iterator* it)
{
  delete (PrimeGenerator*) it->primeGenerator_;
  it->primeGenerator_ = nullptr;
}

void deletePrimesVector(primesieve::iterator* it)
{
  delete (pod_vector<uint64_t>*) it->primesVector_;
  it->primesVector_ = nullptr;
}

pod_vector<uint64_t>& getPrimes(primesieve::iterator* it)
{
  return *(pod_vector<uint64_t>*) it->primesVector_;
}

} // namespace

namespace primesieve {

iterator::iterator() noexcept :
  i_(0),
  last_idx_(0),
  start_(0),
  stop_(0),
  stop_hint_(std::numeric_limits<uint64_t>::max()),
  dist_(0),
  primes_(nullptr),
  primesVector_(nullptr),
  primeGenerator_(nullptr)
{ }

iterator::iterator(uint64_t start,
                   uint64_t stop_hint) noexcept :
  i_(0),
  last_idx_(0),
  start_(start),
  stop_(start),
  stop_hint_(stop_hint),
  dist_(0),
  primes_(nullptr),
  primesVector_(nullptr),
  primeGenerator_(nullptr)
{ }

/// Move constructor
iterator::iterator(iterator&& other) noexcept :
  i_(other.i_),
  last_idx_(other.last_idx_),
  start_(other.start_),
  stop_(other.stop_),
  stop_hint_(other.stop_hint_),
  dist_(other.dist_),
  primes_(other.primes_),
  primesVector_(other.primesVector_),
  primeGenerator_(other.primeGenerator_)
{
  other.i_ = 0;
  other.last_idx_ = 0;
  other.start_ = 0;
  other.stop_ = 0;
  other.stop_hint_ = std::numeric_limits<uint64_t>::max();
  other.dist_ = 0;
  other.primes_ = nullptr;
  other.primesVector_ = nullptr;
  other.primeGenerator_ = nullptr;
}

/// Move assignment operator
iterator& iterator::operator=(iterator&& other) noexcept
{
  if (this != &other)
  {
    clear();

    i_ = other.i_;
    last_idx_ = other.last_idx_;
    start_ = other.start_;
    stop_ = other.stop_;
    stop_hint_ = other.stop_hint_;
    dist_ = other.dist_;
    primes_ = other.primes_;
    primesVector_ = other.primesVector_;
    primeGenerator_ = other.primeGenerator_;

    other.i_ = 0;
    other.last_idx_ = 0;
    other.start_ = 0;
    other.stop_ = 0;
    other.stop_hint_ = std::numeric_limits<uint64_t>::max();
    other.dist_ = 0;
    other.primes_ = nullptr;
    other.primesVector_ = nullptr;
    other.primeGenerator_ = nullptr;
  }

  return *this;
}

void iterator::skipto(uint64_t start,
                      uint64_t stop_hint) noexcept
{
  i_ = 0;
  last_idx_ = 0;
  start_ = start;
  stop_ = start;
  stop_hint_ = stop_hint;
  dist_ = 0;
  primes_ = nullptr;
  deletePrimeGenerator(this);
}

iterator::~iterator()
{
  clear();
}

void iterator::clear() noexcept
{
  deletePrimeGenerator(this);
  deletePrimesVector(this);
}

void iterator::generate_next_primes()
{
  std::size_t size = 0;

  while (!size)
  {
    auto* primeGenerator = (PrimeGenerator*) primeGenerator_;

    if (!primeGenerator)
    {
      deletePrimeGenerator(this);
      IteratorHelper::next(&start_, &stop_, stop_hint_, &dist_);
      primeGenerator = new PrimeGenerator(start_, stop_);
      primeGenerator_ = primeGenerator;
      if (!primesVector_)
        primesVector_ = new pod_vector<uint64_t>();
    }

    auto& primes = getPrimes(this);
    primeGenerator->fillNextPrimes(primes, &size);

    // There are 3 different cases here:
    // 1) The primes array contains a few primes (<= 512).
    //    In this case we return the primes to the user.
    // 2) The primes array is empty because the next
    //    prime > stop_. In this case we reset the
    //    primeGenerator object, increase the start_ & stop_
    //    numbers and sieve the next segment.
    // 3) The next prime > 2^64. In this case the primes
    //    array contains an error code (UINT64_MAX) which
    //    is returned to the user.
    if (size == 0)
      deletePrimeGenerator(this);
  }

  auto& primes = getPrimes(this);
  i_ = 0;
  last_idx_ = size - 1;
  primes_ = &primes[0];
}

void iterator::generate_prev_primes()
{
  if (!primesVector_)
    primesVector_ = new pod_vector<uint64_t>();

  auto& primes = getPrimes(this);

  // Special case if generate_next_primes() has
  // been used before generate_prev_primes().
  if_unlikely(primeGenerator_)
  {
    assert(!primes.empty());
    start_ = primes.front();
    deletePrimeGenerator(this);
  }

  std::size_t size = 0;

  while (!size)
  {
    IteratorHelper::prev(&start_, &stop_, stop_hint_, &dist_);
    PrimeGenerator primeGenerator(start_, stop_);
    primeGenerator.fillPrevPrimes(primes, &size);
  }

  last_idx_ = size - 1;
  i_ = last_idx_;
  primes_ = &primes[0];
}

} // namespace
<|endoftext|>


<commit_before>// -------------------------------------------------------------
// cuDPP -- CUDA Data Parallel Primitives library
// -------------------------------------------------------------
// $Revision$
// $Date$
// -------------------------------------------------------------
// This source code is distributed under the terms of license.txt
// in the root directory of this source distribution.
// -------------------------------------------------------------

#include <stdio.h>
#include <math.h>
#include <cuda_runtime_api.h>

#include "cudpp.h"
#include "cudpp_testrig_options.h"
#include "cudpp_testrig_utils.h"
#include "cuda_util.h"
#include "commandline.h"

using namespace cudpp_app;

template <typename T>
int radixSortTest(CUDPPHandle theCudpp, CUDPPConfiguration config, size_t *tests,
                  unsigned int numTests, size_t numElements,
                  testrigOptions testOptions, bool quiet)
{
    int retval = 0;

    T *h_keys, *h_keysSorted, *d_keys;
    unsigned int *h_values, *h_valuesSorted, *d_values;

    h_keys       = (T*)malloc(numElements*sizeof(T));
    h_keysSorted = (T*)malloc(numElements*sizeof(T));
    h_values     = 0;
    h_valuesSorted = 0;

    if (config.options & CUDPP_OPTION_KEY_VALUE_PAIRS)
    {
        h_values       = (unsigned int*)malloc(numElements*sizeof(unsigned int));
        h_valuesSorted = (unsigned int*)malloc(numElements*sizeof(unsigned int));

        for(unsigned int i=0; i < numElements; ++i)
            h_values[i] = i;
    }

    // Fill up with some random data
    VectorSupport<T>::fillVector(h_keys, numElements, 32);

    CUDA_SAFE_CALL(cudaMalloc((void **)&d_keys, numElements*sizeof(T)));
    if (config.options & CUDPP_OPTION_KEY_VALUE_PAIRS)
    {
        CUDA_SAFE_CALL(cudaMalloc((void **)&d_values, numElements*sizeof(unsigned int)));
    }
    else
    {
        d_values = 0;
    }

    CUDPPHandle plan;
    CUDPPResult result = cudppPlan(theCudpp, &plan, config, numElements, 1, 0);

    if(result != CUDPP_SUCCESS)
    {
        printf("Error in plan creation\n");
        retval = numTests;
        cudppDestroyPlan(plan);
        return retval;
    }

    // run multiple iterations to compute an average sort time
    cudaEvent_t start_event, stop_event;
    CUDA_SAFE_CALL( cudaEventCreate(&start_event) );
    CUDA_SAFE_CALL( cudaEventCreate(&stop_event) );

    for (unsigned int k = 0; k < numTests; ++k)
    {
        if (!quiet)
        {
            printf("Running a %s radix sort of %ld %s %s\n",
                  (config.options & CUDPP_OPTION_BACKWARD) ? " backward" : "forward",
                  tests[k],
                  datatype_to_string[(int) config.datatype],
                  (config.options & CUDPP_OPTION_KEY_VALUE_PAIRS) ? "key-value pairs" : "keys");
            fflush(stdout);
        }

        if(numTests == 1)
            tests[0] = numElements;

        float totalTime = 0;

        for (int i = 0; i < testOptions.numIterations; i++)
        {
            CUDA_SAFE_CALL(cudaMemcpy(d_keys, h_keys, tests[k] * sizeof(T), cudaMemcpyHostToDevice));
            if(config.options & CUDPP_OPTION_KEY_VALUE_PAIRS)
            {
                CUDA_SAFE_CALL( cudaMemcpy((void*)d_values,
                                           (void*)h_values,
                                           tests[k] * sizeof(unsigned int),
                                           cudaMemcpyHostToDevice) );
            }

            CUDA_SAFE_CALL( cudaEventRecord(start_event, 0) );

            cudppSort(plan, d_keys, (void*)d_values, tests[k]);

            CUDA_SAFE_CALL( cudaEventRecord(stop_event, 0) );
            CUDA_SAFE_CALL( cudaEventSynchronize(stop_event) );

            float time = 0;
            CUDA_SAFE_CALL( cudaEventElapsedTime(&time, start_event, stop_event));
            totalTime += time;
        }

        CUDA_CHECK_ERROR("testradixSort - cudppRadixSort");

        // copy results
        CUDA_SAFE_CALL(cudaMemcpy(h_keysSorted, d_keys, tests[k] * sizeof(T), cudaMemcpyDeviceToHost));
        if (config.options & CUDPP_OPTION_KEY_VALUE_PAIRS)
        {
            CUDA_SAFE_CALL( cudaMemcpy((void*)h_valuesSorted,
                                       (void*)d_values,
                                       tests[k] * sizeof(unsigned int),
                                       cudaMemcpyDeviceToHost) );
        }
        else
            h_values = 0;

        retval += VectorSupport<T>::verifySort(h_keysSorted, h_valuesSorted, h_keys, tests[k],
                                               config.options & CUDPP_OPTION_BACKWARD);

        if(!quiet)
        {
            printf("test %s\n", (retval == 0) ? "PASSED" : "FAILED");
            printf("Average execution time: %f ms\n", totalTime / testOptions.numIterations);
        }
        else
        {
            printf("\t%10ld\t%0.4f\n", tests[k], totalTime / testOptions.numIterations);
        }
    }
    printf("\n");

    CUDA_CHECK_ERROR("after radixsort");

    result = cudppDestroyPlan(plan);

    if (result != CUDPP_SUCCESS)
    {
        printf("Error destroying CUDPPPlan for Scan\n");
        retval = numTests;
    }

    cudaFree(d_keys);
    if (config.options & CUDPP_OPTION_KEY_VALUE_PAIRS)
        cudaFree(d_values);
    free(h_keys);
    free(h_values);

    return retval;
}

/**
 * testRadixSort tests cudpp's radix sort
 * Possible command line arguments:
 * - --keysonly, tests only a set of keys
 * - --keyval, tests a set of keys with associated values
 * - --n=#, number of elements in sort
 * @param argc Number of arguments on the command line, passed
 * directly from main
 * @param argv Array of arguments on the command line, passed directly
 * from main
 * @param configPtr Configuration for scan, set by caller
 * @return Number of tests that failed regression (0 for all pass)
 * @see cudppSort
*/
int testRadixSort(int argc, const char **argv, const CUDPPConfiguration *configPtr)
{

    int cmdVal;
    int retval = 0;

    bool quiet = checkCommandLineFlag(argc, argv, "quiet");
    testrigOptions testOptions;
    setOptions(argc, argv, testOptions);

    CUDPPConfiguration config;
    config.algorithm = CUDPP_SORT_RADIX;
    config.datatype = CUDPP_UINT;
    config.options = CUDPP_OPTION_KEY_VALUE_PAIRS;

    size_t test[] = {39, 128, 256, 512, 513, 1000, 1024, 1025, 32768,
                     45537, 65536, 131072, 262144, 500001, 524288,
                     1048577, 1048576, 1048581, 2097152, 4194304,
                     8388608};

    int numTests = sizeof(test)/sizeof(test[0]);

    size_t numElements = test[numTests - 1];

    if(configPtr != NULL)
    {
        config = *configPtr;
    }
    else
    {
        config.datatype = getDatatypeFromArgv(argc, argv);

        bool keysOnly = checkCommandLineFlag(argc, argv, "keysonly");
        bool backward = checkCommandLineFlag(argc, argv, "backward");

        config.options = CUDPP_OPTION_KEY_VALUE_PAIRS;

        if(keysOnly)
            config.options = CUDPP_OPTION_KEYS_ONLY;

        if (backward)
            config.options |= CUDPP_OPTION_BACKWARD;
    }

    if( commandLineArg( cmdVal, argc, (const char**)argv, "n" ) )
    {
        numElements = cmdVal;
        numTests = 1;
    }

    CUDPPResult result = CUDPP_SUCCESS;
    CUDPPHandle theCudpp;
    result = cudppCreate(&theCudpp);
    if(result != CUDPP_SUCCESS)
    {
        printf("Error initializing CUDPP Library.\n");
        retval = numTests;
        return retval;
    }

    switch(config.datatype)
    {
    case CUDPP_CHAR:
        retval = radixSortTest<char>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_UCHAR:
        retval = radixSortTest<unsigned char>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_INT:
        retval = radixSortTest<int>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_UINT:
        retval = radixSortTest<unsigned int>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_FLOAT:
        retval = radixSortTest<float>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_DOUBLE:
        retval = radixSortTest<double>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_LONGLONG:
        retval = radixSortTest<long long>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_ULONGLONG:
        retval = radixSortTest<unsigned long long>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    default:
        break;
    }

    result = cudppDestroy(theCudpp);

    if (result != CUDPP_SUCCESS)
    {
        printf("Error shutting down CUDPP Library.\n");
        retval = numTests;
    }

    return retval;
}

// Leave this at the end of the file
// Local Variables:
// mode:c++
// c-file-style: "NVIDIA"
// End:
<commit_msg>fixed bug in output of radix sort test\n<commit_after>// -------------------------------------------------------------
// cuDPP -- CUDA Data Parallel Primitives library
// -------------------------------------------------------------
// $Revision$
// $Date$
// -------------------------------------------------------------
// This source code is distributed under the terms of license.txt
// in the root directory of this source distribution.
// -------------------------------------------------------------

#include <stdio.h>
#include <math.h>
#include <cuda_runtime_api.h>

#include "cudpp.h"
#include "cudpp_testrig_options.h"
#include "cudpp_testrig_utils.h"
#include "cuda_util.h"
#include "commandline.h"

using namespace cudpp_app;

template <typename T>
int radixSortTest(CUDPPHandle theCudpp, CUDPPConfiguration config, size_t *tests,
                  unsigned int numTests, size_t numElements,
                  testrigOptions testOptions, bool quiet)
{
    int retval = 0;

    T *h_keys, *h_keysSorted, *d_keys;
    unsigned int *h_values, *h_valuesSorted, *d_values;

    h_keys       = (T*)malloc(numElements*sizeof(T));
    h_keysSorted = (T*)malloc(numElements*sizeof(T));
    h_values     = 0;
    h_valuesSorted = 0;

    if (config.options & CUDPP_OPTION_KEY_VALUE_PAIRS)
    {
        h_values       = (unsigned int*)malloc(numElements*sizeof(unsigned int));
        h_valuesSorted = (unsigned int*)malloc(numElements*sizeof(unsigned int));

        for(unsigned int i=0; i < numElements; ++i)
            h_values[i] = i;
    }

    // Fill up with some random data
    VectorSupport<T>::fillVector(h_keys, numElements, 32);

    CUDA_SAFE_CALL(cudaMalloc((void **)&d_keys, numElements*sizeof(T)));
    if (config.options & CUDPP_OPTION_KEY_VALUE_PAIRS)
    {
        CUDA_SAFE_CALL(cudaMalloc((void **)&d_values, numElements*sizeof(unsigned int)));
    }
    else
    {
        d_values = 0;
    }

    CUDPPHandle plan;
    CUDPPResult result = cudppPlan(theCudpp, &plan, config, numElements, 1, 0);

    if(result != CUDPP_SUCCESS)
    {
        printf("Error in plan creation\n");
        retval = numTests;
        cudppDestroyPlan(plan);
        return retval;
    }

    // run multiple iterations to compute an average sort time
    cudaEvent_t start_event, stop_event;
    CUDA_SAFE_CALL( cudaEventCreate(&start_event) );
    CUDA_SAFE_CALL( cudaEventCreate(&stop_event) );

    for (unsigned int k = 0; k < numTests; ++k)
    {
        if(numTests == 1)
            tests[0] = numElements;

        if (!quiet)
        {
            printf("Running a %s radix sort of %ld %s %s\n",
                  (config.options & CUDPP_OPTION_BACKWARD) ? " backward" : "forward",
                  tests[k],
                  datatype_to_string[(int) config.datatype],
                  (config.options & CUDPP_OPTION_KEY_VALUE_PAIRS) ? "key-value pairs" : "keys");
            fflush(stdout);
        }

        float totalTime = 0;

        for (int i = 0; i < testOptions.numIterations; i++)
        {
            CUDA_SAFE_CALL(cudaMemcpy(d_keys, h_keys, tests[k] * sizeof(T), cudaMemcpyHostToDevice));
            if(config.options & CUDPP_OPTION_KEY_VALUE_PAIRS)
            {
                CUDA_SAFE_CALL( cudaMemcpy((void*)d_values,
                                           (void*)h_values,
                                           tests[k] * sizeof(unsigned int),
                                           cudaMemcpyHostToDevice) );
            }

            CUDA_SAFE_CALL( cudaEventRecord(start_event, 0) );

            cudppSort(plan, d_keys, (void*)d_values, tests[k]);

            CUDA_SAFE_CALL( cudaEventRecord(stop_event, 0) );
            CUDA_SAFE_CALL( cudaEventSynchronize(stop_event) );

            float time = 0;
            CUDA_SAFE_CALL( cudaEventElapsedTime(&time, start_event, stop_event));
            totalTime += time;
        }

        CUDA_CHECK_ERROR("testradixSort - cudppRadixSort");

        // copy results
        CUDA_SAFE_CALL(cudaMemcpy(h_keysSorted, d_keys, tests[k] * sizeof(T), cudaMemcpyDeviceToHost));
        if (config.options & CUDPP_OPTION_KEY_VALUE_PAIRS)
        {
            CUDA_SAFE_CALL( cudaMemcpy((void*)h_valuesSorted,
                                       (void*)d_values,
                                       tests[k] * sizeof(unsigned int),
                                       cudaMemcpyDeviceToHost) );
        }
        else
            h_values = 0;

        retval += VectorSupport<T>::verifySort(h_keysSorted, h_valuesSorted, h_keys, tests[k],
                                               config.options & CUDPP_OPTION_BACKWARD);

        if(!quiet)
        {
            printf("test %s\n", (retval == 0) ? "PASSED" : "FAILED");
            printf("Average execution time: %f ms\n", totalTime / testOptions.numIterations);
        }
        else
        {
            printf("\t%10ld\t%0.4f\n", tests[k], totalTime / testOptions.numIterations);
        }
    }
    printf("\n");

    CUDA_CHECK_ERROR("after radixsort");

    result = cudppDestroyPlan(plan);

    if (result != CUDPP_SUCCESS)
    {
        printf("Error destroying CUDPPPlan for Scan\n");
        retval = numTests;
    }

    cudaFree(d_keys);
    if (config.options & CUDPP_OPTION_KEY_VALUE_PAIRS)
        cudaFree(d_values);
    free(h_keys);
    free(h_values);

    return retval;
}

/**
 * testRadixSort tests cudpp's radix sort
 * Possible command line arguments:
 * - --keysonly, tests only a set of keys
 * - --keyval, tests a set of keys with associated values
 * - --n=#, number of elements in sort
 * @param argc Number of arguments on the command line, passed
 * directly from main
 * @param argv Array of arguments on the command line, passed directly
 * from main
 * @param configPtr Configuration for scan, set by caller
 * @return Number of tests that failed regression (0 for all pass)
 * @see cudppSort
*/
int testRadixSort(int argc, const char **argv, const CUDPPConfiguration *configPtr)
{

    int cmdVal;
    int retval = 0;

    bool quiet = checkCommandLineFlag(argc, argv, "quiet");
    testrigOptions testOptions;
    setOptions(argc, argv, testOptions);

    CUDPPConfiguration config;
    config.algorithm = CUDPP_SORT_RADIX;
    config.datatype = CUDPP_UINT;
    config.options = CUDPP_OPTION_KEY_VALUE_PAIRS;

    size_t test[] = {39, 128, 256, 512, 513, 1000, 1024, 1025, 32768,
                     45537, 65536, 131072, 262144, 500001, 524288,
                     1048577, 1048576, 1048581, 2097152, 4194304,
                     8388608};

    int numTests = sizeof(test)/sizeof(test[0]);

    size_t numElements = test[numTests - 1];

    if(configPtr != NULL)
    {
        config = *configPtr;
    }
    else
    {
        config.datatype = getDatatypeFromArgv(argc, argv);

        bool keysOnly = checkCommandLineFlag(argc, argv, "keysonly");
        bool backward = checkCommandLineFlag(argc, argv, "backward");

        config.options = CUDPP_OPTION_KEY_VALUE_PAIRS;

        if(keysOnly)
            config.options = CUDPP_OPTION_KEYS_ONLY;

        if (backward)
            config.options |= CUDPP_OPTION_BACKWARD;
    }

    if( commandLineArg( cmdVal, argc, (const char**)argv, "n" ) )
    {
        numElements = cmdVal;
        numTests = 1;
    }

    CUDPPResult result = CUDPP_SUCCESS;
    CUDPPHandle theCudpp;
    result = cudppCreate(&theCudpp);
    if(result != CUDPP_SUCCESS)
    {
        printf("Error initializing CUDPP Library.\n");
        retval = numTests;
        return retval;
    }

    switch(config.datatype)
    {
    case CUDPP_CHAR:
        retval = radixSortTest<char>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_UCHAR:
        retval = radixSortTest<unsigned char>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_INT:
        retval = radixSortTest<int>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_UINT:
        retval = radixSortTest<unsigned int>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_FLOAT:
        retval = radixSortTest<float>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_DOUBLE:
        retval = radixSortTest<double>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_LONGLONG:
        retval = radixSortTest<long long>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    case CUDPP_ULONGLONG:
        retval = radixSortTest<unsigned long long>(theCudpp, config, test, numTests, numElements, testOptions, quiet);
        break;
    default:
        break;
    }

    result = cudppDestroy(theCudpp);

    if (result != CUDPP_SUCCESS)
    {
        printf("Error shutting down CUDPP Library.\n");
        retval = numTests;
    }

    return retval;
}

// Leave this at the end of the file
// Local Variables:
// mode:c++
// c-file-style: "NVIDIA"
// End:
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE

#include "StableHeaders.h"

#include "LocalAssetStorage.h"
#include "LocalAssetProvider.h"
#include "AssetAPI.h"
#include "LoggingFunctions.h"

#include <Profiler.h>
#include <File.h>
#include <FileSystem.h>
#include <FileWatcher.h>
#include <StringUtils.h>

namespace Tundra
{

LocalAssetStorage::LocalAssetStorage(Urho3D::Context* context, bool writable_, bool liveUpdate_, bool autoDiscoverable_) :
    IAssetStorage(context),
    recursive(true),
    changeWatcher(0)
{
    // Override the parameters for the base class.
    writable = writable_;
    liveUpdate = liveUpdate_;
    autoDiscoverable = autoDiscoverable_;
}

LocalAssetStorage::~LocalAssetStorage()
{
    RemoveWatcher();
}

void LocalAssetStorage::LoadAllAssetsOfType(AssetAPI *assetAPI, const String &suffix, const String &assetType)
{
    Urho3D::FileSystem* fileSystem = GetSubsystem<Urho3D::FileSystem>();
    StringVector filenames;
    fileSystem->ScanDir(filenames, directory, "*.*", Urho3D::SCAN_FILES, recursive);
    foreach(String str, filenames)
    {
        if ((suffix == "" || str.EndsWith(suffix)) && !(str.Contains(".git") || str.Contains(".svn") || str.Contains(".hg")))
        {
            uint lastSlash = str.FindLast('/');
            if (lastSlash != String::NPOS)
                str = str.Substring(lastSlash + 1);
            assetAPI->RequestAsset("local://" + str, assetType);
        }
    }
}

void LocalAssetStorage::RefreshAssetRefs()
{
    Urho3D::FileSystem* fileSystem = GetSubsystem<Urho3D::FileSystem>();
    StringVector filenames;
    fileSystem->ScanDir(filenames, directory, "*.*", Urho3D::SCAN_FILES, recursive);

    foreach(String str, filenames)
    {
        if (!(str.Contains(".git") || str.Contains(".svn") || str.Contains(".hg")))
        {
            String diskSource = directory + str;
            uint lastSlash = str.FindLast('/');
            if (lastSlash != String::NPOS)
                str = str.Substring(lastSlash + 1);
            String localName = str;
            str = "local://" + str;
            if (!assetRefs.Contains(str))
            {
                assetRefs.Push(str);
                AssetChanged.Emit(this, localName, diskSource, IAssetStorage::AssetCreate);
            }
        }
    }
}

void LocalAssetStorage::CacheStorageContents()
{
    cachedFiles.clear();
    Urho3D::FileSystem* fileSystem = GetSubsystem<Urho3D::FileSystem>();
    StringVector filenames;
    fileSystem->ScanDir(filenames, directory, "*.*", Urho3D::SCAN_FILES, recursive);

    foreach(String str, filenames)
    {
        if (!(str.Contains(".git") || str.Contains(".svn") || str.Contains(".hg")))
        {
            String diskSource = directory + str;
            uint lastSlash = str.FindLast('/');
            if (lastSlash != String::NPOS)
                str = str.Substring(lastSlash + 1);
            String localName = str;

///\todo This is an often-received error condition if the user is not aware, but also occurs naturally in built-in Ogre Media storages.
/// Fix this check to occur somehow nicer (without additional constraints to asset load time) without a hardcoded check
/// against the storage name.
            if (cachedFiles.find(localName) != cachedFiles.end())
                LogWarning("Warning: Asset Storage \"" + Name() + "\" contains ambiguous assets \"" + cachedFiles[localName] + "\" and \"" + diskSource + "\" in two different subdirectories!");

            cachedFiles[localName] = diskSource;
        }
    }
}

String LocalAssetStorage::GetFullPathForAsset(const String &assetname, bool recursiveLookup)
{
    Urho3D::FileSystem* fileSystem = GetSubsystem<Urho3D::FileSystem>();
    if (fileSystem->FileExists(directory + assetname))
        return directory;

    std::map<String, String, StringCompareCaseInsensitive>::iterator iter = cachedFiles.find(assetname);
    if (iter == cachedFiles.end())
    {
        if (!recursive || !recursiveLookup)
            return "";
        else
            CacheStorageContents();
    }

    iter = cachedFiles.find(assetname);
    if (iter != cachedFiles.end())
    {
        if (fileSystem->FileExists(iter->second))
            return directory;
    }

    return "";
}

/// @todo Make this function handle arbitrary asset refs.
String LocalAssetStorage::GetFullAssetURL(const String &localName)
{
    String filename;
    String subAssetName;
    AssetAPI::ParseAssetRef(localName, 0, 0, 0, 0, &filename, 0, 0, &subAssetName);
    return BaseURL() + filename + (subAssetName.Empty() ? "" : ("#" + subAssetName));
}

String LocalAssetStorage::Type() const
{
    return "LocalAssetStorage";
}

String LocalAssetStorage::SerializeToString(bool networkTransfer) const
{
    if (networkTransfer)
        return ""; // Cannot transfer a LocalAssetStorage through network to another computer, since it is local to this system!
    else
        return "type=" + Type() + ";name=" + name + ";src=" + directory + ";recursive=" + String(recursive) + ";readonly=" + String(!writable) +
            ";liveupdate=" + String(liveUpdate) + ";autodiscoverable=" + String(autoDiscoverable) + ";replicated=" + String(isReplicated)
            + ";trusted=" + TrustStateToString(GetTrustState());
}

void LocalAssetStorage::EmitAssetChanged(String absoluteFilename, IAssetStorage::ChangeType change)
{
    String localName;
    uint lastSlash = absoluteFilename.FindLast('/');
    if (lastSlash != String::NPOS)
        localName = absoluteFilename.Substring(lastSlash + 1);
    String assetRef = "local://" + localName;
    if (assetRefs.Contains(assetRef) && change == IAssetStorage::AssetCreate)
        LogDebug("LocalAssetStorage::EmitAssetChanged: Emitting AssetCreate signal for already existing asset " + assetRef +
            ", file " + absoluteFilename + ". Asset was probably removed and then added back.");
    AssetChanged.Emit(this, localName, absoluteFilename, change);
}

void LocalAssetStorage::SetupWatcher()
{
    if (changeWatcher) // Remove the old watcher if one exists.
        RemoveWatcher();

    changeWatcher = new Urho3D::FileWatcher(GetContext());
    changeWatcher->StartWatching(directory, recursive);
    LogInfo("LocalAssetStorage: started watching " + directory);
}

void LocalAssetStorage::RemoveWatcher()
{
    changeWatcher.Reset();
}

}
<commit_msg>Fix recursive asset search path from LocalAssetStorage.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE

#include "StableHeaders.h"

#include "LocalAssetStorage.h"
#include "LocalAssetProvider.h"
#include "AssetAPI.h"
#include "LoggingFunctions.h"

#include <Profiler.h>
#include <File.h>
#include <FileSystem.h>
#include <FileWatcher.h>
#include <StringUtils.h>

namespace Tundra
{

LocalAssetStorage::LocalAssetStorage(Urho3D::Context* context, bool writable_, bool liveUpdate_, bool autoDiscoverable_) :
    IAssetStorage(context),
    recursive(true),
    changeWatcher(0)
{
    // Override the parameters for the base class.
    writable = writable_;
    liveUpdate = liveUpdate_;
    autoDiscoverable = autoDiscoverable_;
}

LocalAssetStorage::~LocalAssetStorage()
{
    RemoveWatcher();
}

void LocalAssetStorage::LoadAllAssetsOfType(AssetAPI *assetAPI, const String &suffix, const String &assetType)
{
    Urho3D::FileSystem* fileSystem = GetSubsystem<Urho3D::FileSystem>();
    StringVector filenames;
    fileSystem->ScanDir(filenames, directory, "*.*", Urho3D::SCAN_FILES, recursive);
    foreach(String str, filenames)
    {
        if ((suffix == "" || str.EndsWith(suffix)) && !(str.Contains(".git") || str.Contains(".svn") || str.Contains(".hg")))
        {
            uint lastSlash = str.FindLast('/');
            if (lastSlash != String::NPOS)
                str = str.Substring(lastSlash + 1);
            assetAPI->RequestAsset("local://" + str, assetType);
        }
    }
}

void LocalAssetStorage::RefreshAssetRefs()
{
    Urho3D::FileSystem* fileSystem = GetSubsystem<Urho3D::FileSystem>();
    StringVector filenames;
    fileSystem->ScanDir(filenames, directory, "*.*", Urho3D::SCAN_FILES, recursive);

    foreach(String str, filenames)
    {
        if (!(str.Contains(".git") || str.Contains(".svn") || str.Contains(".hg")))
        {
            String diskSource = directory + str;
            uint lastSlash = str.FindLast('/');
            if (lastSlash != String::NPOS)
                str = str.Substring(lastSlash + 1);
            String localName = str;
            str = "local://" + str;
            if (!assetRefs.Contains(str))
            {
                assetRefs.Push(str);
                AssetChanged.Emit(this, localName, diskSource, IAssetStorage::AssetCreate);
            }
        }
    }
}

void LocalAssetStorage::CacheStorageContents()
{
    cachedFiles.clear();
    Urho3D::FileSystem* fileSystem = GetSubsystem<Urho3D::FileSystem>();
    StringVector filenames;
    fileSystem->ScanDir(filenames, directory, "*.*", Urho3D::SCAN_FILES, recursive);

    foreach(String str, filenames)
    {
        if (!(str.Contains(".git") || str.Contains(".svn") || str.Contains(".hg")))
        {
            String diskSource = directory + str;
            uint lastSlash = str.FindLast('/');
            if (lastSlash != String::NPOS)
                str = str.Substring(lastSlash + 1);
            String localName = str;

///\todo This is an often-received error condition if the user is not aware, but also occurs naturally in built-in Ogre Media storages.
/// Fix this check to occur somehow nicer (without additional constraints to asset load time) without a hardcoded check
/// against the storage name.
            if (cachedFiles.find(localName) != cachedFiles.end())
                LogWarning("Warning: Asset Storage \"" + Name() + "\" contains ambiguous assets \"" + cachedFiles[localName] + "\" and \"" + diskSource + "\" in two different subdirectories!");

            cachedFiles[localName] = diskSource;
        }
    }
}

String LocalAssetStorage::GetFullPathForAsset(const String &assetname, bool recursiveLookup)
{
    Urho3D::FileSystem* fileSystem = GetSubsystem<Urho3D::FileSystem>();
    if (fileSystem->FileExists(directory + assetname))
        return directory;

    std::map<String, String, StringCompareCaseInsensitive>::iterator iter = cachedFiles.find(assetname);
    if (iter == cachedFiles.end())
    {
        if (!recursive || !recursiveLookup)
            return "";
        else
            CacheStorageContents();
    }

    iter = cachedFiles.find(assetname);
    if (iter != cachedFiles.end())
    {
        if (fileSystem->FileExists(iter->second))
            return Urho3D::GetPath(iter->second);
    }

    return "";
}

/// @todo Make this function handle arbitrary asset refs.
String LocalAssetStorage::GetFullAssetURL(const String &localName)
{
    String filename;
    String subAssetName;
    AssetAPI::ParseAssetRef(localName, 0, 0, 0, 0, &filename, 0, 0, &subAssetName);
    return BaseURL() + filename + (subAssetName.Empty() ? "" : ("#" + subAssetName));
}

String LocalAssetStorage::Type() const
{
    return "LocalAssetStorage";
}

String LocalAssetStorage::SerializeToString(bool networkTransfer) const
{
    if (networkTransfer)
        return ""; // Cannot transfer a LocalAssetStorage through network to another computer, since it is local to this system!
    else
        return "type=" + Type() + ";name=" + name + ";src=" + directory + ";recursive=" + String(recursive) + ";readonly=" + String(!writable) +
            ";liveupdate=" + String(liveUpdate) + ";autodiscoverable=" + String(autoDiscoverable) + ";replicated=" + String(isReplicated)
            + ";trusted=" + TrustStateToString(GetTrustState());
}

void LocalAssetStorage::EmitAssetChanged(String absoluteFilename, IAssetStorage::ChangeType change)
{
    String localName;
    uint lastSlash = absoluteFilename.FindLast('/');
    if (lastSlash != String::NPOS)
        localName = absoluteFilename.Substring(lastSlash + 1);
    String assetRef = "local://" + localName;
    if (assetRefs.Contains(assetRef) && change == IAssetStorage::AssetCreate)
        LogDebug("LocalAssetStorage::EmitAssetChanged: Emitting AssetCreate signal for already existing asset " + assetRef +
            ", file " + absoluteFilename + ". Asset was probably removed and then added back.");
    AssetChanged.Emit(this, localName, absoluteFilename, change);
}

void LocalAssetStorage::SetupWatcher()
{
    if (changeWatcher) // Remove the old watcher if one exists.
        RemoveWatcher();

    changeWatcher = new Urho3D::FileWatcher(GetContext());
    changeWatcher->StartWatching(directory, recursive);
    LogInfo("LocalAssetStorage: started watching " + directory);
}

void LocalAssetStorage::RemoveWatcher()
{
    changeWatcher.Reset();
}

}
<|endoftext|>


<commit_before>//===-- llc.cpp - Implement the LLVM Compiler -----------------------------===//
//
// This is the llc compiler driver.
//
//===----------------------------------------------------------------------===//

#include "llvm/Bytecode/Reader.h"
#include "llvm/Optimizations/Normalize.h"
#include "llvm/Target/Sparc.h"
#include "llvm/Target/Machine.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Module.h"
#include "llvm/Method.h"

cl::String InputFilename ("", "Input filename", cl::NoFlags, "-");
cl::String OutputFilename("o", "Output filename", cl::NoFlags, "");

static void NormalizeMethod(Method* method) {
  NormalizePhiConstantArgs(method);
}

//===----------------------------------------------------------------------===//
// Function main()
//===----------------------------------------------------------------------===//
//
// Entry point for the llc compiler.
//
int main(int argc, char** argv) {
  cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
  TargetMachine *Target = allocateSparcTargetMachine();

  Module *M = ParseBytecodeFile(InputFilename);
  if (M == 0) {
    cerr << "bytecode didn't read correctly.\n";
    delete Target;
    return 1;
  }

  bool Failed = false;
  for (Module::const_iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
    Method *Meth = *MI;

    NormalizeMethod(Meth);

    if (Target->compileMethod(Meth)) {
      cerr << "Error compiling " << InputFilename << "!\n";
      Failed = true;
      break;
    }
  }

  // Clean up and exit
  delete M;
  delete Target;
  return Failed;
}

<commit_msg>Minor changes.<commit_after>//===-- llc.cpp - Implement the LLVM Compiler ----------------------------===//
//
// This is the llc compiler driver.
//
//===---------------------------------------------------------------------===//

#include "llvm/Bytecode/Reader.h"
#include "llvm/Optimizations/Normalize.h"
#include "llvm/Target/Sparc.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Module.h"
#include "llvm/Method.h"

cl::String InputFilename ("", "Input filename", cl::NoFlags, "-");
cl::String OutputFilename("o", "Output filename", cl::NoFlags, "");

//-------------------------- Internal Functions -----------------------------//

static void
NormalizeMethod(Method* method)
{
  NormalizePhiConstantArgs(method);
}

//===---------------------------------------------------------------------===//
// Function main()
//
// Entry point for the llc compiler.
//===---------------------------------------------------------------------===//

int
main(int argc, char** argv)
{
  cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
  TargetMachine *Target = allocateSparcTargetMachine();

  Module *M = ParseBytecodeFile(InputFilename);
  if (M == 0)
    {
      cerr << "bytecode didn't read correctly.\n";
      delete Target;
      return 1;
    }

  bool Failed = false;
  for (Module::const_iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
    {
      Method *Meth = *MI;

      NormalizeMethod(Meth);

      if (Target->compileMethod(Meth))
	{
	  cerr << "Error compiling " << InputFilename << "!\n";
	  Failed = true;
	  break;
	}
    }

  // Clean up and exit
  delete M;
  delete Target;
  return Failed;
}

<|endoftext|>


<commit_before>/*
    addaccountwizard.cpp - Kopete Add Account Wizard

    Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be>

    Kopete    (c) 2002-2003 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qlayout.h>

#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <klineeditdlg.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <kdebug.h>

#include "addaccountwizard.h"
#include "kopeteprotocol.h"
#include "pluginloader.h"
#include "kopetemetacontact.h"
#include "editaccountwidget.h"

AddAccountWizard::AddAccountWizard( QWidget *parent, const char *name, bool modale )
: AddAccountWizard_Base( parent, name, modale )
{
	accountPage=0L;
	int pluginCount = 0;
	QListViewItem *pluginItem=0L;

	QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins();
	for( KopetePlugin *p = plugins.first() ; p ; p = plugins.next() )
	{
		KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p );
		if( proto )
		{
			pluginItem = new QListViewItem( protocolListView );
			pluginItem->setText(0, proto->displayName());
			pluginItem->setPixmap( 0, SmallIcon( proto->pluginIcon() ) );
			pluginCount++;
			m_protocolItems.insert(pluginItem, proto);
		}
	}

	if ( pluginCount == 1 )
	{
		pluginItem->setSelected( true );
		// I think it is important to select one protocl to make sure.
		//setAppropriate( selectService, false );
	}

	setNextEnabled(selectService, (pluginCount == 1));
	setFinishEnabled(finis, true);

	connect( protocolListView, SIGNAL(clicked(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *)));
}

AddAccountWizard::~AddAccountWizard()
{
}

void AddAccountWizard::slotProtocolListClicked( QListViewItem *)
{
	// Just makes sure only one protocol is selected before allowing the user to continue
	setNextEnabled(selectService, (bool)(protocolListView->selectedItem()));
}

void AddAccountWizard::accept()
{
	accountPage->apply();
	deleteLater();
}

void AddAccountWizard::next()
{
	if (currentPage() == selectService ||
		(currentPage() == intro && !appropriate( selectService )))
	{
		if(accountPage)
			delete accountPage;

		QListViewItem *lvi = protocolListView->selectedItem();
		if( lvi && m_protocolItems[lvi] )
		{
			if( accountPage )
				delete accountPage;

			accountPage = m_protocolItems[lvi]->createEditAccountWidget(0L,this);

			//that will not be possible, but if a protocol doesn't have yet this page, we should show a inform text or textbox
			if (!accountPage)
				return;

			insertPage( dynamic_cast<QWidget*>(accountPage), i18n( "Step Two: Account Information" ), indexOf(finis) );
			QWizard::next();
		}
		return;
	}
	else if( indexOf( currentPage() ) == 2 && !accountPage->validateData() )
			return;
	else
		QWizard::next();
}

#include "addaccountwizard.moc"

// vim: set noet ts=4 sts=4 sw=4:

<commit_msg>Show at least an error message.<commit_after>/*
    addaccountwizard.cpp - Kopete Add Account Wizard

    Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be>

    Kopete    (c) 2002-2003 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qlayout.h>

#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <klineeditdlg.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kdebug.h>

#include "addaccountwizard.h"
#include "kopeteprotocol.h"
#include "pluginloader.h"
#include "kopetemetacontact.h"
#include "editaccountwidget.h"

AddAccountWizard::AddAccountWizard( QWidget *parent, const char *name, bool modale )
: AddAccountWizard_Base( parent, name, modale )
{
	accountPage=0L;
	int pluginCount = 0;
	QListViewItem *pluginItem=0L;

	QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins();
	for( KopetePlugin *p = plugins.first() ; p ; p = plugins.next() )
	{
		KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p );
		if( proto )
		{
			pluginItem = new QListViewItem( protocolListView );
			pluginItem->setText(0, proto->displayName());
			pluginItem->setPixmap( 0, SmallIcon( proto->pluginIcon() ) );
			pluginCount++;
			m_protocolItems.insert(pluginItem, proto);
		}
	}

	if ( pluginCount == 1 )
	{
		pluginItem->setSelected( true );
		// I think it is important to select one protocl to make sure.
		//setAppropriate( selectService, false );
	}

	setNextEnabled(selectService, (pluginCount == 1));
	setFinishEnabled(finis, true);

	connect( protocolListView, SIGNAL(clicked(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *)));
}

AddAccountWizard::~AddAccountWizard()
{
}

void AddAccountWizard::slotProtocolListClicked( QListViewItem *)
{
	// Just makes sure only one protocol is selected before allowing the user to continue
	setNextEnabled(selectService, (bool)(protocolListView->selectedItem()));
}

void AddAccountWizard::accept()
{
	accountPage->apply();
	deleteLater();
}

void AddAccountWizard::next()
{
	if (currentPage() == selectService ||
		(currentPage() == intro && !appropriate( selectService )))
	{
		if(accountPage)
			delete accountPage;

		QListViewItem *lvi = protocolListView->selectedItem();
		if( lvi && m_protocolItems[lvi] )
		{
			if( accountPage )
				delete accountPage;

			accountPage = m_protocolItems[lvi]->createEditAccountWidget(0L,this);

			if (!accountPage) {
        KMessageBox::error( this, i18n( "The author of this protocol hasn't implemented Adding of Accounts" ),
														i18n( "Error while adding account" ) );
				return;
      }

			insertPage( dynamic_cast<QWidget*>(accountPage), i18n( "Step Two: Account Information" ), indexOf(finis) );
			QWizard::next();
		}
		return;
	}
	else if( indexOf( currentPage() ) == 2 && !accountPage->validateData() )
			return;
	else
		QWizard::next();
}

#include "addaccountwizard.moc"

// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>/*
    This file is part of KOrganizer.

    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "freebusyurldialog.h"

#include <kcal/attendee.h>
#include <kcal/freebusyurlstore.h>

#include <klineedit.h>
#include <klocale.h>
#include <kdebug.h>
#include <kstandarddirs.h>

#include <QLayout>
#include <QLabel>
//Added by qt3to4:
#include <QVBoxLayout>
#include <QFrame>
#include <QBoxLayout>

FreeBusyUrlDialog::FreeBusyUrlDialog( KCal::Attendee *attendee, QWidget *parent )
  : KDialog( parent )
{
  QFrame *topFrame = new QFrame(this);
  setMainWidget( topFrame );
  setModal( true );
  setCaption( i18n("Edit Free/Busy Location") );
  setButtons( Ok|Cancel );
  setDefaultButton( Ok );

  QBoxLayout *topLayout = new QVBoxLayout( topFrame );
  topLayout->setSpacing( spacingHint() );
  topLayout->setMargin( 0 );

  mWidget = new FreeBusyUrlWidget( attendee, topFrame );
  topLayout->addWidget( mWidget );

  mWidget->loadConfig();
  connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
}

void FreeBusyUrlDialog::slotOk()
{
  mWidget->saveConfig();
  accept();
}

FreeBusyUrlWidget::FreeBusyUrlWidget( KCal::Attendee *attendee, QWidget *parent )
  : QWidget( parent ), mAttendee( attendee )
{
  QBoxLayout *topLayout = new QVBoxLayout( this );
  topLayout->setSpacing( KDialog::spacingHint() );

  QLabel *label = new QLabel(
      i18n("Location of Free/Busy information for %1 <%2>:", //krazy:exclude=i18ncheckarg
        mAttendee->name(), mAttendee->email() ), this );
  topLayout->addWidget( label );

  mUrlEdit = new KLineEdit( this );
  topLayout->addWidget( mUrlEdit );
}

FreeBusyUrlWidget::~FreeBusyUrlWidget()
{
}

void FreeBusyUrlWidget::loadConfig()
{
  kDebug(5850) <<"FreeBusyUrlWidget::loadConfig()";

  QString url = KCal::FreeBusyUrlStore::self()->readUrl( mAttendee->email() );

  mUrlEdit->setText( url );
}

void FreeBusyUrlWidget::saveConfig()
{
  kDebug(5850) <<"FreeBusyUrlWidget::saveConfig()";

  QString url = mUrlEdit->text();

  KCal::FreeBusyUrlStore::self()->writeUrl( mAttendee->email(), url );

  KCal::FreeBusyUrlStore::self()->sync();
}

#include "freebusyurldialog.moc"
<commit_msg>fix i18n message coding style<commit_after>/*
  This file is part of KOrganizer.

  Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "freebusyurldialog.h"

#include <kcal/attendee.h>
#include <kcal/freebusyurlstore.h>

#include <klineedit.h>
#include <klocale.h>
#include <kdebug.h>
#include <kstandarddirs.h>

#include <QLayout>
#include <QLabel>
#include <QVBoxLayout>
#include <QFrame>
#include <QBoxLayout>

FreeBusyUrlDialog::FreeBusyUrlDialog( KCal::Attendee *attendee, QWidget *parent )
  : KDialog( parent )
{
  QFrame *topFrame = new QFrame( this );
  setMainWidget( topFrame );
  setModal( true );
  setCaption( i18n( "Edit Free/Busy Location" ) );
  setButtons( Ok|Cancel );
  setDefaultButton( Ok );

  QBoxLayout *topLayout = new QVBoxLayout( topFrame );
  topLayout->setSpacing( spacingHint() );
  topLayout->setMargin( 0 );

  mWidget = new FreeBusyUrlWidget( attendee, topFrame );
  topLayout->addWidget( mWidget );

  mWidget->loadConfig();
  connect( this, SIGNAL(okClicked()), this, SLOT(slotOk()) );
}

void FreeBusyUrlDialog::slotOk()
{
  mWidget->saveConfig();
  accept();
}

FreeBusyUrlWidget::FreeBusyUrlWidget( KCal::Attendee *attendee, QWidget *parent )
  : QWidget( parent ), mAttendee( attendee )
{
  QBoxLayout *topLayout = new QVBoxLayout( this );
  topLayout->setSpacing( KDialog::spacingHint() );

  QLabel *label =
    new QLabel( i18n( "Location of Free/Busy information for %1 <placeholder>%2</placeholder>:",
                     mAttendee->name(), mAttendee->email() ), this );
  topLayout->addWidget( label );

  mUrlEdit = new KLineEdit( this );
  topLayout->addWidget( mUrlEdit );
}

FreeBusyUrlWidget::~FreeBusyUrlWidget()
{
}

void FreeBusyUrlWidget::loadConfig()
{
  kDebug(5850);

  QString url = KCal::FreeBusyUrlStore::self()->readUrl( mAttendee->email() );
  mUrlEdit->setText( url );
}

void FreeBusyUrlWidget::saveConfig()
{
  kDebug(5850);

  QString url = mUrlEdit->text();
  KCal::FreeBusyUrlStore::self()->writeUrl( mAttendee->email(), url );
  KCal::FreeBusyUrlStore::self()->sync();
}

#include "freebusyurldialog.moc"
<|endoftext|>


<commit_before>#include <vector>
#include <string>

#include <math.h>

#include <ros/ros.h>
#include <geometry_msgs/Twist.h>

#include "hmmwv/joystick.hpp"

#define DEAD_ZONE 16384
#define AXIS_MAX  32767

using namespace ros;
using namespace std;

int main(int argc, char **argv) {

	// init sdl and connect to controller
	Joystick joystick;
	string name = joystick.getName();
	ROS_INFO("Used controller: %s", name.c_str());

	// init ros
	double linear, angular, l_scale, a_scale;

	init(argc, argv, "remotecontrol");
	NodeHandle n;
	Publisher pub;

	linear = angular = 0.0;
	l_scale = a_scale = 5.0;
	n.param("scale_angular", a_scale, a_scale);
  	n.param("scale_linear", l_scale, l_scale);

	pub = n.advertise<geometry_msgs::Twist>("turtle1/cmd_vel", 1);

	// startup key loop
	// use button.0 to stop
	bool dirty = false;
	bool quit  = false;
	while (!quit) {
		linear = angular = 0.0;

		// get axis values
		// use axis.0 for left/right
		// and axis.1 for up/down
		JoystickEvent event = joystick.getEvent();
		vector<short> axis = event.getAxis();

		// check for button.0 to stop
		vector<bool> buttons = event.getButtons();
		if (buttons.at(0) == true)
			quit = true;

		// check if there is an event
		if (abs(axis.at(0)) - DEAD_ZONE > 0
			|| abs(axis.at(1)) - DEAD_ZONE > 0)
			dirty = true;

		// calcutelate position values
		angular = (-1.0) * axis.at(0) / AXIS_MAX;
		linear  = (-1.0) * axis.at(1) / AXIS_MAX;

		geometry_msgs::Twist twist;
		twist.angular.z = a_scale * angular;
		twist.linear.x = l_scale  * linear;
		if (dirty == true) {
      		pub.publish(twist);
      		dirty = false;
    		}
	}

	return 0;
}
<commit_msg>removed scale factor for odometry data<commit_after>#include <vector>
#include <string>

#include <math.h>

#include <ros/ros.h>
#include <geometry_msgs/Twist.h>

#include "hmmwv/joystick.hpp"

#define DEAD_ZONE 16384
#define AXIS_MAX  32767

using namespace ros;
using namespace std;

int main(int argc, char **argv) {

	// init sdl and connect to controller
	Joystick joystick;
	string name = joystick.getName();
	ROS_INFO("Used controller: %s", name.c_str());

	// init ros
	double linear, angular, l_scale, a_scale;

	init(argc, argv, "remotecontrol");
	NodeHandle n;
	Publisher pub;

	linear = angular = 0.0;
	l_scale = a_scale = 1.0;
	n.param("scale_angular", a_scale, a_scale);
  	n.param("scale_linear", l_scale, l_scale);

	pub = n.advertise<geometry_msgs::Twist>("turtle1/cmd_vel", 1);

	// startup key loop
	// use button.0 to stop
	bool dirty = false;
	bool quit  = false;
	while (!quit) {
		linear = angular = 0.0;

		// get axis values
		// use axis.0 for left/right
		// and axis.1 for up/down
		JoystickEvent event = joystick.getEvent();
		vector<short> axis = event.getAxis();

		// check for button.0 to stop
		vector<bool> buttons = event.getButtons();
		if (buttons.at(0) == true)
			quit = true;

		// check if there is an event
		if (abs(axis.at(0)) - DEAD_ZONE > 0
			|| abs(axis.at(1)) - DEAD_ZONE > 0)
			dirty = true;

		// calcutelate position values
		angular = (-1.0) * axis.at(0) / AXIS_MAX;
		linear  = (-1.0) * axis.at(1) / AXIS_MAX;

		geometry_msgs::Twist twist;
		twist.angular.z = a_scale * angular;
		twist.linear.x = l_scale  * linear;
		if (dirty == true) {
      		pub.publish(twist);
      		dirty = false;
    		}
	}

	return 0;
}
<|endoftext|>


<commit_before>/* ========================================

ID: mathema6
TASK: circus
LANG: C++11
(...for USACO solutions)

 * File Name : circus.cpp

 * Creation Date : 01-01-2015

 * Last Modified :

 * Created By : Karel Ha <mathemage@gmail.com>

 * URL :

 * Points Gained (in case of online contest) :

 ==========================================*/

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <string>
#include <cctype>
#include <fstream>
#include <unordered_set>
#include <unordered_map>

using namespace std;

#define FOR(I,A,B) for(int I = (A); I < (B); ++I)
#define REP(I,N)   FOR(I,0,N)
#define ALL(A)     (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << a << endl;

// uncomment following line for debug mode
#define DEBUG

struct hw {
  int h, w;
};

inline bool operator<(const hw& lhs, const hw& rhs){
  return (lhs.h < rhs.h) || (lhs.h == rhs.h && lhs.w < rhs.w);
}

void show(const vector<hw> & seq) {
  REP(i,seq.size()) {
    cout << "(" << seq[i].h << ", " << seq[i].w << ") ";
  }
  cout << endl;
}

vector<hw> getMaxSeq(vector<hw> & seq) {
#ifdef DEBUG
  cout << "orig seq: ";
  show(seq);
#endif

  int n = seq.size(), maxL = 0, maxP;
  vector<int> l(n);
  vector<int> p(n);
  REP(i,n) {
    p[i] = i;
    REP(j,i) {
      if (seq[j].w <= seq[i].w && l[j] > l[i]) {
        l[i] = l[j];
        p[i] = j;
      }
    }
    l[i]++;

    if (maxL < l[i]) {
      maxL = l[i];
      maxP = i;
    }
  }

  vector<hw> result;
  while (maxP != p[maxP]) {
    result.push_back(seq[maxP]);
    maxP = p[maxP];
  }
  result.push_back(seq[maxP]);
  reverse(ALL(result));

#ifdef DEBUG
  MSG(maxL)
#endif
  return result;
}

int main() {
  int t, n, h, w;
  cin >> t;

  while(t--) {
    cin >> n;
    vector<hw> people(n);
    REP(i,n) {
      cin >> people[i].h >> people[i].w;
    }

    sort(ALL(people));
    show(getMaxSeq(people));
  }
  return 0;
}
<commit_msg>Include Problem statement for gdocs/circus<commit_after>/* ========================================

ID: mathema6
TASK: circus
LANG: C++11
(...for USACO solutions)

 * File Name : circus.cpp

 * Creation Date : 01-01-2015

 * Last Modified :

 * Created By : Karel Ha <mathemage@gmail.com>

 * Problem statement :
 *
 * A circus is designing a tower routine consisting of people standing atop one
 * another's shoulders. For practical and aesthetic reasons, each person must
 * be both shorter and lighter than the person below him or her. Given the
 * heights and weights of each person in the circus, write a method to compute
 * the largest possible number of people in such a tower.

 ==========================================*/

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <string>
#include <cctype>
#include <fstream>
#include <unordered_set>
#include <unordered_map>

using namespace std;

#define FOR(I,A,B) for(int I = (A); I < (B); ++I)
#define REP(I,N)   FOR(I,0,N)
#define ALL(A)     (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << a << endl;

// uncomment following line for debug mode
#define DEBUG

struct hw {
  int h, w;
};

inline bool operator<(const hw& lhs, const hw& rhs){
  return (lhs.h < rhs.h) || (lhs.h == rhs.h && lhs.w < rhs.w);
}

void show(const vector<hw> & seq) {
  REP(i,seq.size()) {
    cout << "(" << seq[i].h << ", " << seq[i].w << ") ";
  }
  cout << endl;
}

vector<hw> getMaxSeq(vector<hw> & seq) {
#ifdef DEBUG
  cout << "orig seq: ";
  show(seq);
#endif

  int n = seq.size(), maxL = 0, maxP;
  vector<int> l(n);
  vector<int> p(n);
  REP(i,n) {
    p[i] = i;
    REP(j,i) {
      if (seq[j].w <= seq[i].w && l[j] > l[i]) {
        l[i] = l[j];
        p[i] = j;
      }
    }
    l[i]++;

    if (maxL < l[i]) {
      maxL = l[i];
      maxP = i;
    }
  }

  vector<hw> result;
  while (maxP != p[maxP]) {
    result.push_back(seq[maxP]);
    maxP = p[maxP];
  }
  result.push_back(seq[maxP]);
  reverse(ALL(result));

#ifdef DEBUG
  MSG(maxL)
#endif
  return result;
}

int main() {
  int t, n, h, w;
  cin >> t;

  while(t--) {
    cin >> n;
    vector<hw> people(n);
    REP(i,n) {
      cin >> people[i].h >> people[i].w;
    }

    sort(ALL(people));
    show(getMaxSeq(people));
  }
  return 0;
}
<|endoftext|>