<commit_before>//
// Created by user on 16.03.19.
//

#include <chrono>
#include <random>
#include <iostream>

#define NDEBUG

#include <cassert>

#define CALCULATE_RECURSION (0)
#if CALCULATE_RECURSION
static size_t rec = 0;
static size_t maxrec = 0;
#endif

template<typename T>
void print(const T *a, const T *b)
{
	for (const T *n = a; n != b; ++n)
	{
		std::cout << n << ": " << *n << std::endl;
	}
	std::cout << b << ": " << *b << std::endl;
}

template<typename T>
T hash(const T *a, const T *b)
{
	T H = *b;
	for (const T *n = a; n != b; ++n)
	{
		H ^= *n;
	}
	return H;
}

template<typename T>
long long int sum(const T *a, const T *b)
{
	long long int S = *b;
	for (const T *n = a; n != b; ++n)
	{
		S += *n;
	}
	return S;
}

template<typename T>
bool verify(const T *a, const T *b, const T h)
{
	return (h == hash(a, b));
}

template<typename T>
bool test(const T *a, const T *b)
{
	for (const T *n = a; n != b; ++n)
	{
		if (*n > *(n + 1))
			return false;
	}
	return true;
}

template<typename T>
inline void swap(T *a, T *b)
{
	//std::cout << "swap: " << a << " <-> " << b << std::endl;
	const T t = *a;
	*a = *b;
	*b = t;
}

template<typename T>
inline void sort(T *a, T *b)
{
	if (*b < *a)
		swap(a, b);
}

template<typename T>
inline void sort(T *a, T *b, T *c)
{
	T A = *a;
	T B = *b;
	T C = *c;

	char abc = 0;
	abc |= ((A < B) ? 001 : 0) | ((B < A) ? 010 : 0);
	abc |= ((B < C) ? 002 : 0) | ((C < B) ? 020 : 0);
	abc |= ((A < C) ? 004 : 0) | ((C < A) ? 040 : 0);

	switch (abc)
	{
		case 000:
			// A:1 B:1 C:1
			// A:2 B:2 C:2
			// A:3 B:3 C:3
		case 005:
			// A:1 B:2 C:2
			// A:1 B:3 C:3
			// A:2 B:3 C:3
		case 006:
			// A:1 B:1 C:2
			// A:1 B:1 C:3
			// A:2 B:2 C:3
		case 007:
			// A:1 B:2 C:3
			break;

		case 012:
			// A:3 B:2 C:3
			// A:2 B:1 C:2
			// A:3 B:1 C:3
		case 016:
			// A:2 B:1 C:3
			*a = B;
			*b = A;
			break;

		case 021:
			// A:1 B:2 C:1
			// A:1 B:3 C:1
			// A:2 B:3 C:2
		case 025:
			// A:1 B:3 C:2
			*b = C;
			*c = B;
			break;

		case 050:
			// A:2 B:1 C:1
			// A:3 B:1 C:1
			// A:3 B:2 C:2
		case 060:
			// A:2 B:2 C:1
			// A:3 B:3 C:1
			// A:3 B:3 C:2
		case 070:
			// A:3 B:2 C:1
			*a = C;
			*c = A;
			break;

		case 052:
			// A:3 B:1 C:2
			*a = B;
			*b = C;
			*c = A;
			break;

		case 061:
			// A:2 B:3 C:1
			*a = C;
			*b = A;
			*c = B;
			break;

		default:
		{
			std::cerr << "wrong case:" << std::oct << static_cast<short>(abc) //
					  << " A:" << A << " B:" << B << " C:" << C << std::endl;
		}
			break;
	}
}

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

template<typename T>
void qsort3(T *aa, T *bb)
{

#if CALCULATE_RECURSION
	rec++;
	if (rec > maxrec)
		maxrec = rec;
#endif
	if (aa >= bb)
	{
#if CALCULATE_RECURSION
		rec--;
#endif
		return;
	}
	if ((aa + 1) == bb)
	{
		//std::cout << "duo sort: " << aa << " , " << bb << std::endl;
		sort(aa, bb);
#if CALCULATE_RECURSION
		rec--;
#endif
		return;
	}
	if ((aa + 2) == bb)
	{
		// std::cout << "triple sort: " << aa << " , " << bb << std::endl;

		sort(aa, aa + 1, bb);
#if CALCULATE_RECURSION
		rec--;
#endif
		return;
	}
	// todo case of 3 elements
	T *a = aa;
	T *b = bb;

	T *x = (a + ((b - a) >> 1));

	sort(a, x, b);

	T A = *a;
	T B = *b;
	const T X = *x;
	//std::cout << "quick sort: " << aa << " , " << bb << " : " << X << std::endl;

	T *_a = x;
	T *b_ = x;
	while (true)
	{
		while (a < _a)
		{
			while (A < X)
			{
				++a;
				A = *a;
			}
			while (A == X)
			{
				--_a;
				if (_a < a)
				{
					_a = a;
					break;
				}
				//swap(a, _a);
				A = *_a;
				*_a = X;
				*a = A;
			}
			if (X < A)
				break;
		}

		while (b_ < b)
		{
			while (X < B)
			{
				--b;
				B = *b;
			}
			while (B == X)
			{
				++b_;
				if (b < b_)
				{
					b_ = b;
					break;
				}
				//swap(b, b_);
				B = *b_;
				*b_ = X;
				*b = B;
			}
			if (B < X)
				break;
		}

		if (a < _a and b_ < b)
		{
			assert(*_a == X);
			assert(*b_ == X);
			assert(X < A);
			assert(B < X);
			assert(*a == A);
			assert(*b == B);
			*b = A;
			*a = B;
			++a;
			--b;
			A = *a;
			B = *b;
		}
		else if (a == _a and b_ < b)
		{
			assert(*a == X);
			assert(*_a == X);
			assert(*b == B);
			assert(*b_ == X);
			assert(B < X);
			++b_;
			if (b_ < b)
			{
				*a = B;
				++a;
				++_a;
				B = *b_;
				*b = B;
				*b_ = X;
			}
			else
			{
				*a = B;
				*b = X;
				break;
			}
		}
		else if (a < _a and b_ == b)
		{
			assert(*a == A);
			assert(X < A);

			assert(*b == X);
			assert(*b_ == X);
			--_a;
			if (a < _a)
			{
				*b = A;
				--b;
				--b_;
				A = *_a;
				*a = A;
				*_a = X;
			}
			else
			{
				*b = A;
				*a = X;
				break;
			}
		}
		else
		{
			assert(b == b_);
			assert(a == _a);
			break;
		}
	}

	assert(b == b_);
	assert(a == _a);

	if (aa < a)
		qsort3(aa, a);
	if (b < bb)
		qsort3(b, bb);
#if CALCULATE_RECURSION
	rec--;
#endif
}

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

template<typename T>
void qsort2(T *a, T *b)
{
#if CALCULATE_RECURSION
	rec++;
	if (rec > maxrec)
		maxrec = rec;
#endif
	if (not(a < b))
	{
#if CALCULATE_RECURSION
		rec--;
#endif
		return;
	}
	if ((a + 1) == b)
	{
		if (*b < *a)
			swap(a, b);
#if CALCULATE_RECURSION
		rec--;
#endif
		return;
	}

	T *A = a;
	T *B = b;
	const T *c = a + ((b - a) >> 1);
	T P = *c;

	do
	{
		while (*a < P)
			++a;

		while (P < *b )
			--b;

		if (a < b)
		{
			swap(a, b);
			++a;
			--b;
		}
	}
	while (a < b);

	if (A < b)
		qsort2(A, b);
	if (a < B)
		qsort2(a, B);
#if CALCULATE_RECURSION
	rec--;
#endif
}

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

int main()
{

	const unsigned lim = 1000000;
	/*

	10000000

	unsigned

	qs3
	AVG=2397.97
	SIGM=72.0195

	qs2
	AVG=1825.08
	SIGM=14.4573

	char
	qs3
	AVG=665.82
	SIGM=21.6039

	qs2
	AVG=1196.53
	SIGM=10.4244

	short
	qs2
	AVG=1502.58
	SIGM=10.5482
	qs3
	AVG=1485.86
	SIGM=23.222

	1000000
	long long int
	qs3
	AVG=201.7
	SIGM=2.52784
	qs2
	AVG=164.03
	SIGM=2.44726

	-O
	qs3
	AVG=108.32
	SIGM=10.4727
	qs2
	AVG=74.94
	SIGM=2.17633
	*/
	typedef long long int T;
	T *V = new T[lim];//
	const T W[lim] = {9, 8, 7, 6};
	T *a = V;
	T *b = V + lim - 1;

	std::mt19937_64 generator(time(nullptr));
	assert(0);
	double S = 0;
	const unsigned stat_size = 100;
	long long stat[stat_size];
	for (unsigned s = 0; s < stat_size; ++s)
	{
		for (int n = 0; n < lim; ++n)
		{
			V[n] = generator();
			//V[n] = W[n];
		}
		const T H = hash(a, b);
		const auto sm = sum(a, b);

		//std::cout << H << std::endl;
		//print(0, lim - 1, V);
		if (test(V, b))
		{
			//std::cout << "sorted?!?!?!" << std::endl;
			continue;
		}

		std::cout << "test:" << s << " hash:" << H << " sum:" << sm
				  << std::endl;
		//print(a, b);
#if CALCULATE_RECURSION
		rec = 0;
#endif
		const auto start = std::chrono::system_clock::now();
		qsort3(a, b);
		const auto duration = std::chrono::system_clock::now() - start;
		if (not verify(a, b, H) or sm != sum(a, b))
		{
			std::cout << "FAIL array:" << s << std::endl;
			//print(a, b);
			return 1;
		}
		if (not test(a, b))
		{
			std::cout << "FAIL sort:" << s << std::endl;
			//print(a, b);
			return 1;
		}
		stat[s] = std::chrono::duration_cast<std::chrono::milliseconds>(
			duration).count();

		std::cout << "PASS:" << stat[s] << " msec" << std::endl;
		S += stat[s];
	}

	S /= (1.0 * stat_size);
	std::cout << " AVG=" << S << std::endl;

	double Z = 0;
	for (unsigned s = 0; s < stat_size; ++s)
	{
		const double t = (stat[s] - S);
		Z += (t * t);
	}
	std::cout << " SIGM=" << sqrt(Z / (1.0 * stat_size)) << std::endl;
#if CALCULATE_RECURSION
	std::cout << " MAXREC=" << maxrec << std::endl;
#endif
	delete[]V;
	return 0;
}<commit_msg>bruteforce search<commit_after>//
// Created by user on 16.03.19.
//

#include <chrono>
#include <random>
#include <iostream>

#define NDEBUG

#include <cassert>

#define CALCULATE_RECURSION (0)
#if CALCULATE_RECURSION
static size_t rec = 0;
static size_t maxrec = 0;
#endif

template<typename T>
const T *brute_search(const T *a, const T *b, const T X)
{
	for (const T *x = a; x <= b; ++x)
	{
		if (X == *x)
			return x;
	}
	return nullptr;
}

template<typename T>
void print(const T *a, const T *b)
{
	for (const T *n = a; n != b; ++n)
	{
		std::cout << n << ": " << *n << std::endl;
	}
	std::cout << b << ": " << *b << std::endl;
}

template<typename T>
T hash(const T *a, const T *b)
{
	T H = *b;
	for (const T *n = a; n != b; ++n)
	{
		H ^= *n;
	}
	return H;
}

template<typename T>
long long int sum(const T *a, const T *b)
{
	long long int S = *b;
	for (const T *n = a; n != b; ++n)
	{
		S += *n;
	}
	return S;
}

template<typename T>
bool verify(const T *a, const T *b, const T h)
{
	return (h == hash(a, b));
}

template<typename T>
bool test(const T *a, const T *b)
{
	for (const T *n = a; n != b; ++n)
	{
		if (*n > *(n + 1))
			return false;
	}
	return true;
}

template<typename T>
inline void swap(T *a, T *b)
{
	//std::cout << "swap: " << a << " <-> " << b << std::endl;
	const T t = *a;
	*a = *b;
	*b = t;
}

template<typename T>
inline void sort(T *a, T *b)
{
	if (*b < *a)
		swap(a, b);
}

template<typename T>
inline void sort(T *a, T *b, T *c)
{
	T A = *a;
	T B = *b;
	T C = *c;

	char abc = 0;
	abc |= ((A < B) ? 001 : 0) | ((B < A) ? 010 : 0);
	abc |= ((B < C) ? 002 : 0) | ((C < B) ? 020 : 0);
	abc |= ((A < C) ? 004 : 0) | ((C < A) ? 040 : 0);

	switch (abc)
	{
		case 000:
			// A:1 B:1 C:1
			// A:2 B:2 C:2
			// A:3 B:3 C:3
		case 005:
			// A:1 B:2 C:2
			// A:1 B:3 C:3
			// A:2 B:3 C:3
		case 006:
			// A:1 B:1 C:2
			// A:1 B:1 C:3
			// A:2 B:2 C:3
		case 007:
			// A:1 B:2 C:3
			break;

		case 012:
			// A:3 B:2 C:3
			// A:2 B:1 C:2
			// A:3 B:1 C:3
		case 016:
			// A:2 B:1 C:3
			*a = B;
			*b = A;
			break;

		case 021:
			// A:1 B:2 C:1
			// A:1 B:3 C:1
			// A:2 B:3 C:2
		case 025:
			// A:1 B:3 C:2
			*b = C;
			*c = B;
			break;

		case 050:
			// A:2 B:1 C:1
			// A:3 B:1 C:1
			// A:3 B:2 C:2
		case 060:
			// A:2 B:2 C:1
			// A:3 B:3 C:1
			// A:3 B:3 C:2
		case 070:
			// A:3 B:2 C:1
			*a = C;
			*c = A;
			break;

		case 052:
			// A:3 B:1 C:2
			*a = B;
			*b = C;
			*c = A;
			break;

		case 061:
			// A:2 B:3 C:1
			*a = C;
			*b = A;
			*c = B;
			break;

		default:
		{
			std::cerr << "wrong case:" << std::oct << static_cast<short>(abc) //
					  << " A:" << A << " B:" << B << " C:" << C << std::endl;
		}
			break;
	}
}

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

template<typename T>
void qsort3(T *aa, T *bb)
{

#if CALCULATE_RECURSION
	rec++;
	if (rec > maxrec)
		maxrec = rec;
#endif
	if (aa >= bb)
	{
#if CALCULATE_RECURSION
		rec--;
#endif
		return;
	}
	if ((aa + 1) == bb)
	{
		//std::cout << "duo sort: " << aa << " , " << bb << std::endl;
		sort(aa, bb);
#if CALCULATE_RECURSION
		rec--;
#endif
		return;
	}
	if ((aa + 2) == bb)
	{
		// std::cout << "triple sort: " << aa << " , " << bb << std::endl;

		sort(aa, aa + 1, bb);
#if CALCULATE_RECURSION
		rec--;
#endif
		return;
	}
	// todo case of 3 elements
	T *a = aa;
	T *b = bb;

	T *x = (a + ((b - a) >> 1));

	sort(a, x, b);

	T A = *a;
	T B = *b;
	const T X = *x;
	//std::cout << "quick sort: " << aa << " , " << bb << " : " << X << std::endl;

	T *_a = x;
	T *b_ = x;
	while (true)
	{
		while (a < _a)
		{
			while (A < X)
			{
				++a;
				A = *a;
			}
			while (A == X)
			{
				--_a;
				if (_a < a)
				{
					_a = a;
					break;
				}
				//swap(a, _a);
				A = *_a;
				*_a = X;
				*a = A;
			}
			if (X < A)
				break;
		}

		while (b_ < b)
		{
			while (X < B)
			{
				--b;
				B = *b;
			}
			while (B == X)
			{
				++b_;
				if (b < b_)
				{
					b_ = b;
					break;
				}
				//swap(b, b_);
				B = *b_;
				*b_ = X;
				*b = B;
			}
			if (B < X)
				break;
		}

		if (a < _a and b_ < b)
		{
			assert(*_a == X);
			assert(*b_ == X);
			assert(X < A);
			assert(B < X);
			assert(*a == A);
			assert(*b == B);
			*b = A;
			*a = B;
			++a;
			--b;
			A = *a;
			B = *b;
		}
		else if (a == _a and b_ < b)
		{
			assert(*a == X);
			assert(*_a == X);
			assert(*b == B);
			assert(*b_ == X);
			assert(B < X);
			++b_;
			if (b_ < b)
			{
				*a = B;
				++a;
				++_a;
				B = *b_;
				*b = B;
				*b_ = X;
			}
			else
			{
				*a = B;
				*b = X;
				break;
			}
		}
		else if (a < _a and b_ == b)
		{
			assert(*a == A);
			assert(X < A);

			assert(*b == X);
			assert(*b_ == X);
			--_a;
			if (a < _a)
			{
				*b = A;
				--b;
				--b_;
				A = *_a;
				*a = A;
				*_a = X;
			}
			else
			{
				*b = A;
				*a = X;
				break;
			}
		}
		else
		{
			assert(b == b_);
			assert(a == _a);
			break;
		}
	}

	assert(b == b_);
	assert(a == _a);

	if (aa < a)
		qsort3(aa, a);
	if (b < bb)
		qsort3(b, bb);
#if CALCULATE_RECURSION
	rec--;
#endif
}

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

template<typename T>
void qsort2(T *a, T *b)
{
#if CALCULATE_RECURSION
	rec++;
	if (rec > maxrec)
		maxrec = rec;
#endif
	if (not(a < b))
	{
#if CALCULATE_RECURSION
		rec--;
#endif
		return;
	}
	if ((a + 1) == b)
	{
		if (*b < *a)
			swap(a, b);
#if CALCULATE_RECURSION
		rec--;
#endif
		return;
	}

	T *A = a;
	T *B = b;
	const T *c = a + ((b - a) >> 1);
	T P = *c;

	do
	{
		while (*a < P)
			++a;

		while (P < *b)
			--b;

		if (a < b)
		{
			swap(a, b);
			++a;
			--b;
		}
	}
	while (a < b);

	if (A < b)
		qsort2(A, b);
	if (a < B)
		qsort2(a, B);
#if CALCULATE_RECURSION
	rec--;
#endif
}

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

int main()
{

	const unsigned lim = 1000000000;
	typedef short T;
	/*

	10000000

	unsigned

	qs3
	AVG=2397.97
	SIGM=72.0195

	qs2
	AVG=1825.08
	SIGM=14.4573

	char
	qs3
	AVG=665.82
	SIGM=21.6039

	qs2
	AVG=1196.53
	SIGM=10.4244

	short
	qs2
	AVG=1502.58
	SIGM=10.5482
	qs3
	AVG=1485.86
	SIGM=23.222

	1000000
	long long int
	qs3
	AVG=201.7
	SIGM=2.52784
	qs2
	AVG=164.03
	SIGM=2.44726

	-O
	qs3
	AVG=108.32
	SIGM=10.4727
	qs2
	AVG=74.94
	SIGM=2.17633
	*/
	T *V = new T[lim];//
	const T W[lim] = {9, 8, 7, 6};
	T *a = V;
	T *b = V + lim - 1;

	std::mt19937_64 generator(time(nullptr));
	assert(0);
	double S = 0;
	const unsigned stat_size = 100;
	long long stat[stat_size];
	for (unsigned s = 0; s < stat_size; ++s)
	{
		for (int n = 0; n < lim; ++n)
		{
			V[n] = generator();
			//V[n] = W[n];
		}

		//std::cout << H << std::endl;
		//print(0, lim - 1, V);
		if (test(V, b))
		{
			//std::cout << "sorted?!?!?!" << std::endl;
			continue;
		}

		//print(a, b);
#if CALCULATE_RECURSION
		rec = 0;
#endif

		const T H = hash(a, b);
		const auto sm = sum(a, b);

		std::cout << "test:" << s << " hash:" << H << " sum:" << sm
				  << std::endl;

		qsort2(a, b);

		const T X = *(b-1);

		if (not verify(a, b, H) or sm != sum(a, b))
		{
			std::cout << "FAIL array:" << s << std::endl;
			//print(a, b);
			return 1;
		}
		if (not test(a, b))
		{
			std::cout << "FAIL sort:" << s << std::endl;
			//print(a, b);
			return 1;
		}

		const auto start = std::chrono::system_clock::now();
		const T *x = brute_search(a, b, X);
		const auto duration = std::chrono::system_clock::now() - start;
		if (nullptr == x or *x != X)
		{
			std::cout << X << " not found" << std::endl;
			return 1;
		}
		stat[s] = std::chrono::duration_cast<std::chrono::milliseconds>(
			duration).count();

		std::cout << "PASS:" << stat[s] << " msec" << std::endl;
		S += stat[s];
	}

	S /= (1.0 * stat_size);
	std::cout << " AVG=" << S << std::endl;

	double Z = 0;
	for (unsigned s = 0; s < stat_size; ++s)
	{
		const double t = (stat[s] - S);
		Z += (t * t);
	}
	std::cout << " SIGM=" << sqrt(Z / (1.0 * stat_size)) << std::endl;
#if CALCULATE_RECURSION
	std::cout << " MAXREC=" << maxrec << std::endl;
#endif
	delete[]V;
	return 0;
}<|endoftext|>


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

#include "chrome/common/render_messages.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURLError.h"
#include "webkit/glue/form_data.h"

using webkit_glue::FormData;
using WebKit::WebCompositionCommand;
using WebKit::WebFrame;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebURLError;

typedef RenderViewTest FormAutocompleteTest;

// Tests that submitting a form generates a FormSubmitted message
// with the form fields.
TEST_F(FormAutocompleteTest, NormalFormSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm'><input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/></form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(
      ViewHostMsg_FormSubmitted::ID);
  ASSERT_TRUE(message != NULL);

  Tuple1<FormData> forms;
  ViewHostMsg_FormSubmitted::Read(message, &forms);
  ASSERT_EQ(2U, forms.a.fields.size());

  webkit_glue::FormField& form_field = forms.a.fields[0];
  EXPECT_EQ(WebString("fname"), form_field.name());
  EXPECT_EQ(WebString("Rick"), form_field.value());

  form_field = forms.a.fields[1];
  EXPECT_EQ(WebString("lname"), form_field.name());
  EXPECT_EQ(WebString("Deckard"), form_field.value());
}

// Tests that submitting a form that has autocomplete="off" does not generate a
// FormSubmitted message.
TEST_F(FormAutocompleteTest, AutoCompleteOffFormSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm' autocomplete='off'>"
           "<input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/>"
           "</form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(
      ViewHostMsg_FormSubmitted::ID));
}

// Tests that fields with autocomplete off are not submitted.
TEST_F(FormAutocompleteTest, AutoCompleteOffInputSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm'>"
           "<input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard' autocomplete='off'/>"
           "</form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(
      ViewHostMsg_FormSubmitted::ID);
  ASSERT_TRUE(message != NULL);

  Tuple1<FormData> forms;
  ViewHostMsg_FormSubmitted::Read(message, &forms);
  ASSERT_EQ(1U, forms.a.fields.size());

  webkit_glue::FormField& form_field = forms.a.fields[0];
  EXPECT_EQ(WebString("fname"), form_field.name());
  EXPECT_EQ(WebString("Rick"), form_field.value());
}

// Tests that submitting a form that has been dynamically set as autocomplete
// off does not generate a FormSubmitted message.
// http://crbug.com/36520
// TODO(jcampan): Waiting on WebKit bug 35823.
TEST_F(FormAutocompleteTest, FAILS_DynamicAutoCompleteOffFormSubmit) {
  LoadHTML("<form id='myForm'><input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/></form>");

  WebKit::WebElement element =
      GetMainFrame()->document().getElementById(WebKit::WebString("myForm"));
  ASSERT_FALSE(element.isNull());
  WebKit::WebFormElement form = element.to<WebKit::WebFormElement>();
  EXPECT_TRUE(form.autoComplete());

  // Dynamically mark the form as autocomplete off.
  ExecuteJavaScript("document.getElementById('myForm').autocomplete='off';");
  ProcessPendingMessages();
  EXPECT_FALSE(form.autoComplete());

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(
      ViewHostMsg_FormSubmitted::ID));
}
<commit_msg>Fix a build failure caused by the patch of https://bugs.webkit.org/show_bug.cgi?id=41244<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/render_messages.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURLError.h"
#include "webkit/glue/form_data.h"

using webkit_glue::FormData;
using WebKit::WebFrame;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebURLError;

typedef RenderViewTest FormAutocompleteTest;

// Tests that submitting a form generates a FormSubmitted message
// with the form fields.
TEST_F(FormAutocompleteTest, NormalFormSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm'><input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/></form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(
      ViewHostMsg_FormSubmitted::ID);
  ASSERT_TRUE(message != NULL);

  Tuple1<FormData> forms;
  ViewHostMsg_FormSubmitted::Read(message, &forms);
  ASSERT_EQ(2U, forms.a.fields.size());

  webkit_glue::FormField& form_field = forms.a.fields[0];
  EXPECT_EQ(WebString("fname"), form_field.name());
  EXPECT_EQ(WebString("Rick"), form_field.value());

  form_field = forms.a.fields[1];
  EXPECT_EQ(WebString("lname"), form_field.name());
  EXPECT_EQ(WebString("Deckard"), form_field.value());
}

// Tests that submitting a form that has autocomplete="off" does not generate a
// FormSubmitted message.
TEST_F(FormAutocompleteTest, AutoCompleteOffFormSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm' autocomplete='off'>"
           "<input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/>"
           "</form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(
      ViewHostMsg_FormSubmitted::ID));
}

// Tests that fields with autocomplete off are not submitted.
TEST_F(FormAutocompleteTest, AutoCompleteOffInputSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm'>"
           "<input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard' autocomplete='off'/>"
           "</form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(
      ViewHostMsg_FormSubmitted::ID);
  ASSERT_TRUE(message != NULL);

  Tuple1<FormData> forms;
  ViewHostMsg_FormSubmitted::Read(message, &forms);
  ASSERT_EQ(1U, forms.a.fields.size());

  webkit_glue::FormField& form_field = forms.a.fields[0];
  EXPECT_EQ(WebString("fname"), form_field.name());
  EXPECT_EQ(WebString("Rick"), form_field.value());
}

// Tests that submitting a form that has been dynamically set as autocomplete
// off does not generate a FormSubmitted message.
// http://crbug.com/36520
// TODO(jcampan): Waiting on WebKit bug 35823.
TEST_F(FormAutocompleteTest, FAILS_DynamicAutoCompleteOffFormSubmit) {
  LoadHTML("<form id='myForm'><input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/></form>");

  WebKit::WebElement element =
      GetMainFrame()->document().getElementById(WebKit::WebString("myForm"));
  ASSERT_FALSE(element.isNull());
  WebKit::WebFormElement form = element.to<WebKit::WebFormElement>();
  EXPECT_TRUE(form.autoComplete());

  // Dynamically mark the form as autocomplete off.
  ExecuteJavaScript("document.getElementById('myForm').autocomplete='off';");
  ProcessPendingMessages();
  EXPECT_FALSE(form.autoComplete());

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(
      ViewHostMsg_FormSubmitted::ID));
}
<|endoftext|>


<commit_before>#include "Socket.h"

#include "Common.h"

#include <cstring>
#include <errno.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <relay/RelayServer.h>
#include <iomanip>
#include "proxy/ProxyServer.h"
#include "ConnectionData.h"
#include "Util.h"
#include "MasterController.h"

using namespace std;

struct Config
{
	Config() {
		proxyPort = -1;
		relayPort = -1;
		masterAddress;
		masterPort = -1;
	}

	int proxyPort;
	int relayPort;
	std::string masterAddress;
	int masterPort;
};

void initMasterController(Config& config) {

	if (config.masterAddress.empty()) {
		return;
	}

	auto master = MasterController::getInstance();
	char ipo[INET_ADDRSTRLEN];
	inet_pton(AF_INET, config.masterAddress.c_str(), (void*)ipo);

	AddressDetails masterInfo;
	masterInfo.addressType = IPV4_ADDRESS;
	masterInfo.address = std::string();
	masterInfo.address.append(ipo, 4);
	masterInfo.port = (uint16_t)config.masterPort;

	string ip;
	string data;

	Socket::getLocalIPAddress(ip, data);
	if (ip.empty()) {
		cerr << "Could not get Local IP Address: " << ip << endl;
		exit(1);
	}

	AddressDetails relayInfo;
	relayInfo.addressType = IPV4_ADDRESS;
	relayInfo.address = data;
	relayInfo.port = (uint16_t)config.relayPort;

	master->connect(relayInfo, masterInfo);
}

// Print an error message, usage, and then exit.
void Usage(string errorMessage)
{
	cerr << errorMessage << "\n"
"Usage: [-config <config.cfg (default)>] [-proxy port <port, default 1080>] [-relay port <port, default 1090>] [-master <ip>:<port]\n"
"Command line options supersedes  options in the config file.\n";
	exit(1);
}

Config ReadConfigFromFile(string filename)
{
	Config cfg;
	ifstream input(filename.c_str());

	string key;
	string temp;
	while (true) {

		input >> key;
		if (input.eof() || key.empty())
			break;

		if (key == "-proxy") {
			string type;
			input >> type;
			if (type == "port") {
				input >> cfg.proxyPort;
				if (cfg.proxyPort < 1 || cfg.proxyPort > 65535) {
					Usage("Proxy Port must be between 1 and 65535. You specified " + cfg.proxyPort);
				}
			}
		}
		else if (key == "-relay") {
			string type;
			input >> type;
			if (type == "port") {
				input >> cfg.relayPort;
				if (cfg.relayPort < 1 || cfg.relayPort > 65535) {
					Usage("Relay Port must be between 1 and 65535. You specified " + cfg.relayPort);
				}
			}
		}
		else if (key == "-master") {
			string value;
			input >> value;
			cfg.masterAddress = value.substr(0, value.find(':'));
			cfg.masterPort = StoI(value.substr(value.find(':') + 1), -1);
			if (cfg.masterPort < 1 || cfg.masterPort > 65535) {
				Usage("Master Port must be between 1 and 65535. You specified " + cfg.masterPort);
			}
		}
	}

	return cfg;
}

Config ParseCommandLine(int argc, char* argv[])
{
	Config cfg;

	string configFile = "config.cfg";

	int i = 1;
	while (i < argc - 1) {
		string key = argv[i++];

		if (key == "-config") {
			configFile = argv[i++];
		}
		else if (key == "-proxy") {
			string type = argv[i++];
			if (type == "port") {
				cfg.proxyPort = StoI(argv[i++], -1);
				if (cfg.proxyPort < 1 || cfg.proxyPort > 65535) {
					Usage("Proxy Port must be between 1 and 65535. You specified " + cfg.proxyPort);
				}
			}
		}
		else if (key == "-relay") {
			string type = argv[i++];
			if (type == "port") {
				cfg.relayPort = StoI(argv[i++], -1);
				if (cfg.relayPort < 1 || cfg.relayPort > 65535) {
					Usage("Relay Port must be between 1 and 65535. You specified " + cfg.relayPort);
				}
			}
		}
		else if (key == "-master") {
			string value = argv[i++];
			// parse ip
			cfg.masterAddress = value.substr(0, value.find(':'));
			cfg.masterPort = StoI(value.substr(value.find(':') + 1), -1);
			if (cfg.masterPort < 1 || cfg.masterPort > 65535) {
				Usage("Master Port must be between 1 and 65535. You specified " + cfg.masterPort);
			}
		}
		else
		{
			Usage("Unknown option: " + key);
		}
	}

	Config cfgFromFile = ReadConfigFromFile(configFile);
	// Load in defaults
	if (cfg.relayPort == -1)
		cfg.relayPort = cfgFromFile.relayPort;
	if (cfg.relayPort == -1)
		cfg.relayPort = 1090;

	if (cfg.proxyPort == -1)
		cfg.proxyPort = cfgFromFile.proxyPort ;
	if (cfg.proxyPort == -1)
		cfg.proxyPort = 1080;

	if (cfg.masterPort == -1)
		cfg.masterPort = cfgFromFile.masterPort ;
	if (cfg.masterPort == -1)
		cfg.masterPort = 1090;

	if (cfg.masterAddress.empty())
		cfg.masterAddress = cfgFromFile.masterAddress ;
	if (cfg.masterAddress.empty())
		cfg.masterAddress = "127.0.0.1";

	return cfg;
}

int main(int argc, char* argv[])
{
	// Command line options will be:
	// -config <file>
	// -proxy port <port>
	// -relay port <port>
	// -master <address>:<port>
	Config cfg = ParseCommandLine(argc, argv);

	AddressDetails t;
	t.addressType = DOMAIN_ADDRESS;
	t.address = "localhost";
	t.port = 443;

	stringstream ss;
	ss << t;
	string pp = ss.str();

	string ip;
	string data;
	Socket::getLocalIPAddress(ip, data);

	cout << "Local IP Address: " << ip << endl;

	thread p([&] {
		ProxyServer proxy = ProxyServer(cfg.proxyPort);
		proxy.Listen();
	});

	thread r([&] {
		RelayServer relay = RelayServer(cfg.relayPort);
		relay.Listen();
	});
	initMasterController(cfg);

	p.join();
	r.join();

	return 0;
}
<commit_msg>Fixed up by using pton<commit_after>#include "Socket.h"

#include "Common.h"

#include <cstring>
#include <errno.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <relay/RelayServer.h>
#include <iomanip>
#include "proxy/ProxyServer.h"
#include "ConnectionData.h"
#include "Util.h"
#include "MasterController.h"

using namespace std;

struct Config
{
	Config() {
		proxyPort = -1;
		relayPort = -1;
		masterAddress;
		masterPort = -1;
	}

	int proxyPort;
	int relayPort;
	std::string masterAddress;
	int masterPort;
};

void initMasterController(Config& config) {

	if (config.masterAddress.empty()) {
		return;
	}

	auto master = MasterController::getInstance();

	AddressDetails masterInfo;
	masterInfo.addressType = IPV4_ADDRESS;
	masterInfo.address = Util::PresentationToNetwork(config.masterAddress);
	masterInfo.port = (uint16_t)config.masterPort;

	string ip;
	string data;

	Socket::getLocalIPAddress(ip, data);
	if (ip.empty()) {
		cerr << "Could not get Local IP Address: " << ip << endl;
		exit(1);
	}

	AddressDetails relayInfo;
	relayInfo.addressType = IPV4_ADDRESS;
	relayInfo.address = Util::PresentationToNetwork(ip);
	relayInfo.port = (uint16_t)config.relayPort;

	master->connect(relayInfo, masterInfo);
}

// Print an error message, usage, and then exit.
void Usage(string errorMessage)
{
	cerr << errorMessage << "\n"
"Usage: [-config <config.cfg (default)>] [-proxy port <port, default 1080>] [-relay port <port, default 1090>] [-master <ip>:<port]\n"
"Command line options supersedes  options in the config file.\n";
	exit(1);
}

Config ReadConfigFromFile(string filename)
{
	Config cfg;
	ifstream input(filename.c_str());

	string key;
	string temp;
	while (true) {

		input >> key;
		if (input.eof() || key.empty())
			break;

		if (key == "-proxy") {
			string type;
			input >> type;
			if (type == "port") {
				input >> cfg.proxyPort;
				if (cfg.proxyPort < 1 || cfg.proxyPort > 65535) {
					Usage("Proxy Port must be between 1 and 65535. You specified " + cfg.proxyPort);
				}
			}
		}
		else if (key == "-relay") {
			string type;
			input >> type;
			if (type == "port") {
				input >> cfg.relayPort;
				if (cfg.relayPort < 1 || cfg.relayPort > 65535) {
					Usage("Relay Port must be between 1 and 65535. You specified " + cfg.relayPort);
				}
			}
		}
		else if (key == "-master") {
			string value;
			input >> value;
			cfg.masterAddress = value.substr(0, value.find(':'));
			cfg.masterPort = StoI(value.substr(value.find(':') + 1), -1);
			if (cfg.masterPort < 1 || cfg.masterPort > 65535) {
				Usage("Master Port must be between 1 and 65535. You specified " + cfg.masterPort);
			}
		}
	}

	return cfg;
}

Config ParseCommandLine(int argc, char* argv[])
{
	Config cfg;

	string configFile = "config.cfg";

	int i = 1;
	while (i < argc - 1) {
		string key = argv[i++];

		if (key == "-config") {
			configFile = argv[i++];
		}
		else if (key == "-proxy") {
			string type = argv[i++];
			if (type == "port") {
				cfg.proxyPort = StoI(argv[i++], -1);
				if (cfg.proxyPort < 1 || cfg.proxyPort > 65535) {
					Usage("Proxy Port must be between 1 and 65535. You specified " + cfg.proxyPort);
				}
			}
		}
		else if (key == "-relay") {
			string type = argv[i++];
			if (type == "port") {
				cfg.relayPort = StoI(argv[i++], -1);
				if (cfg.relayPort < 1 || cfg.relayPort > 65535) {
					Usage("Relay Port must be between 1 and 65535. You specified " + cfg.relayPort);
				}
			}
		}
		else if (key == "-master") {
			string value = argv[i++];
			// parse ip
			cfg.masterAddress = value.substr(0, value.find(':'));
			cfg.masterPort = StoI(value.substr(value.find(':') + 1), -1);
			if (cfg.masterPort < 1 || cfg.masterPort > 65535) {
				Usage("Master Port must be between 1 and 65535. You specified " + cfg.masterPort);
			}
		}
		else
		{
			Usage("Unknown option: " + key);
		}
	}

	Config cfgFromFile = ReadConfigFromFile(configFile);
	// Load in defaults
	if (cfg.relayPort == -1)
		cfg.relayPort = cfgFromFile.relayPort;
	if (cfg.relayPort == -1)
		cfg.relayPort = 1090;

	if (cfg.proxyPort == -1)
		cfg.proxyPort = cfgFromFile.proxyPort ;
	if (cfg.proxyPort == -1)
		cfg.proxyPort = 1080;

	if (cfg.masterPort == -1)
		cfg.masterPort = cfgFromFile.masterPort ;
	if (cfg.masterPort == -1)
		cfg.masterPort = 1090;

	if (cfg.masterAddress.empty())
		cfg.masterAddress = cfgFromFile.masterAddress ;
	if (cfg.masterAddress.empty())
		cfg.masterAddress = "127.0.0.1";

	return cfg;
}

int main(int argc, char* argv[])
{
	// Command line options will be:
	// -config <file>
	// -proxy port <port>
	// -relay port <port>
	// -master <address>:<port>
	Config cfg = ParseCommandLine(argc, argv);

	AddressDetails t;
	t.addressType = DOMAIN_ADDRESS;
	t.address = "localhost";
	t.port = 443;

	stringstream ss;
	ss << t;
	string pp = ss.str();

	string ip;
	string data;
	Socket::getLocalIPAddress(ip, data);

	cout << "Local IP Address: " << ip << endl;

	thread p([&] {
		ProxyServer proxy = ProxyServer(cfg.proxyPort);
		proxy.Listen();
	});

	thread r([&] {
		RelayServer relay = RelayServer(cfg.relayPort);
		relay.Listen();
	});
	initMasterController(cfg);

	p.join();
	r.join();

	return 0;
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include <QApplication>
#include <exception>
#include <iostream>
#include <cstdlib>

int main(int argc, char *argv[])
{
    try
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();

        return a.exec();
    }
    catch (const std::exception &ex)
    {
        std::cerr << "Fatal Error: " << ex.what() << "\nThe application will now exit." << std::endl;
        return EXIT_FAILURE;
    }
}
<commit_msg>Added messagebox for caught exceptions<commit_after>#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>
#include <QString>
#include <cstdlib>
#include <exception>

int main(int argc, char *argv[])
{
    // The QApplication is outside the try-catch because
    // QMessageBox requires an active QApplication to work.

    QApplication a(argc, argv);

    try
    {
        MainWindow w;
        w.show();

        return a.exec();
    }
    catch (const std::exception &ex)
    {
        QString errMsg = QString(ex.what()) + "\nThe application will now exit.";
        QMessageBox::critical(nullptr, "Fatal Error", errMsg);
        return EXIT_FAILURE;
    }
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/visualization/software-license/
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include <cassert> // assert
#include <cstdlib> // std::atof
#include <cmath> // std::sqrt, std::pow
#include <iostream> // std::cout
#include <fstream> // std::ifstream
#include <vector> // std::vector
#include <string> // std::string
#include <sstream> // std::stringstream
#include <iomanip> // std::setw
#include <limits> // inifity

#include "ApplicationUtilities.h"
#include "GaussianProcessEmulatorDirectoryFormatIO.h"
#include "Paths.h"
#include "System.h"

int main(int argc, char ** argv) {
  if (argc < 3) {
    std::cerr
      << "Usage\n  " << argv[0]
      << " statistics_directory trace_file\n\n";
    return EXIT_FAILURE;
  }
  std::string statisticsDirectory( argv[1] );
  madai::EnsurePathSeparatorAtEnd( statisticsDirectory );

  std::vector< madai::Parameter > parameters;
  int numberOfParameters = 0;

  if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseParameters(
           parameters, numberOfParameters, statisticsDirectory, false )) {
    std::cerr
      << "Could not read parameters from prior file '"
      << statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << "'\n";
    return EXIT_FAILURE;
  }
  assert (numberOfParameters = parameters.size());

  std::string traceFile( statisticsDirectory );
  traceFile.append( argv[2] );

  if ( !madai::System::IsFile( traceFile ) ) {
    std::cerr << "Trace file '" << traceFile << "' does not exist or is a directory.\n";
    return EXIT_FAILURE;
  }

  std::ifstream trace(traceFile.c_str());
  if ( !trace.good() ) {
    std::cerr << "Error reading trace file '" << traceFile << "'.\n";
    return EXIT_FAILURE;
  }

  std::string header;
  std::getline(trace,header);
  std::vector<std::string> headers = madai::SplitString(header, ',');

  size_t numberOfFields = headers.size();
  assert(static_cast<int>(numberOfFields) > numberOfParameters);

  std::string line;
  size_t lineCount = 0, bestIndex = 0;
  std::vector< double > sums(numberOfParameters, 0.0);
  std::vector< std::vector< double > > values(numberOfParameters);

  double bestLogLikelihood = -std::numeric_limits< double >::infinity();

  while (std::getline(trace,line)) {
    std::vector<std::string> fields = madai::SplitString(line, ',');
    assert(numberOfFields == fields.size());
    for (int i = 0; i < numberOfParameters; ++i) {
      double value = std::atof(fields[i].c_str());
      values[i].push_back(value);
      sums[i] += value;
    }
    double logLikelihood = std::atof(fields[numberOfFields - 1].c_str());
    if (logLikelihood > bestLogLikelihood) {
      bestLogLikelihood = logLikelihood;
      bestIndex = lineCount;
    }
    ++lineCount;
  }

  trace.close();
  std::vector< double > means(numberOfParameters,0.0);

  std::vector< double > priorStdDev(numberOfParameters,0.0);
  for (int i = 0; i < numberOfParameters; ++i) {
    priorStdDev[i] =
      parameters[i].GetPriorDistribution()->GetStandardDeviation();
  }
  std::cout << std::setw(14) << "parameter";
  std::cout << std::setw(14) << "mean";
  std::cout << std::setw(14) << "std.dev.";
  std::cout << std::setw(14) << "scaled dev.";
  std::cout << std::setw(14) << "best value";
  std::cout << '\n';

  for (int i = 0; i < numberOfParameters; ++i) {
    means[i] = sums[i] / lineCount;
    double variance = 0.0;
    for (size_t k = 0; k < lineCount; ++k) {
      variance += std::pow(values[i][k] - means[i], 2);
    }
    variance /= lineCount;
    std::cout
      << std::setw(14) << parameters[i].m_Name
      << std::setw(14) << means[i]
      << std::setw(14) << std::sqrt(variance)
      << std::setw(14) << std::sqrt(variance) / priorStdDev[i]
      << std::setw(14) << values[i][bestIndex]
      << '\n';
  }

  // Print the relative log-likelihood from the best point
  std::cout << "\nbest log likelihood\n";
  std::cout << std::setw(14) << bestLogLikelihood << "\n";

  std::vector< std::vector< double > > covariancematrix;
  for (int i = 0; i < numberOfParameters; ++i)
    covariancematrix.push_back(std::vector< double >(numberOfParameters, 0.0));

  for (int i = 0; i < numberOfParameters; ++i) {
    for (int j = 0; j <= i; ++j) {
      double covariance = 0.0;
      for (size_t k = 0; k < lineCount; ++k) {
        covariance += (values[i][k] - means[i]) * (values[j][k] - means[j]);
      }
      covariancematrix[i][j] = covariance /= lineCount;
      if (i != j)
        covariancematrix[j][i] = covariancematrix[i][j];
    }
  }

  std::cout << "\ncovariance:\n";
  std::cout << std::setw(14) << "";
  for (int j = 0; j < numberOfParameters; ++j)
    std::cout << std::setw(14) << parameters[j].m_Name;
  std::cout << "\n";
  for (int i = 0; i < numberOfParameters; ++i) {
    std::cout << std::setw(14) << parameters[i].m_Name;
    for (int j = 0; j < numberOfParameters; ++j) {
      std::cout << std::setw(14) << covariancematrix[i][j];
    }
    std::cout << "\n";
  }

  std::cout << "\nscaled covariance:\n";
  std::cout << std::setw(14) << "";
  for (int j = 0; j < numberOfParameters; ++j)
    std::cout << std::setw(14) << parameters[j].m_Name;
  std::cout << "\n";
  for (int i = 0; i < numberOfParameters; ++i) {
    std::cout << std::setw(14) << parameters[i].m_Name;
    for (int j = 0; j < numberOfParameters; ++j) {
      std::cout << std::setw(14) << covariancematrix[i][j] / (
          priorStdDev[i] * priorStdDev[j]);
    }
    std::cout << "\n";
  }

  return EXIT_SUCCESS;
}
<commit_msg>Added the printout of the correlation matrix between observables and parameters. The absolute values of these are related to the resolving power of a variable.<commit_after>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/visualization/software-license/
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include <cassert> // assert
#include <cstdlib> // std::atof
#include <cmath> // std::sqrt, std::pow
#include <iostream> // std::cout
#include <fstream> // std::ifstream
#include <vector> // std::vector
#include <string> // std::string
#include <sstream> // std::stringstream
#include <iomanip> // std::setw
#include <limits> // inifity

#include "ApplicationUtilities.h"
#include "GaussianProcessEmulatorDirectoryFormatIO.h"
#include "Paths.h"
#include "System.h"

int main(int argc, char ** argv) {
  if (argc < 3) {
    std::cerr
      << "Usage\n  " << argv[0]
      << " statistics_directory trace_file\n\n";
    return EXIT_FAILURE;
  }
  std::string statisticsDirectory( argv[1] );
  madai::EnsurePathSeparatorAtEnd( statisticsDirectory );

  std::vector< madai::Parameter > parameters;
  int numberOfParameters = 0;

  if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseParameters(
           parameters, numberOfParameters, statisticsDirectory, false )) {
    std::cerr
      << "Could not read parameters from prior file '"
      << statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << "'\n";
    return EXIT_FAILURE;
  }
  assert (numberOfParameters = parameters.size());

  std::vector< std::string > outputNames;
  int numberOfOutputs = 0;

  if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseOutputs(
           outputNames, numberOfOutputs, statisticsDirectory, false )) {
    std::cerr
      << "Could not read outputs from prior file '"
      << statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << "'\n";
    return EXIT_FAILURE;
  }
  assert (numberOfOutputs = outputNames.size());

  std::string traceFile( statisticsDirectory );
  traceFile.append( argv[2] );

  if ( !madai::System::IsFile( traceFile ) ) {
    std::cerr << "Trace file '" << traceFile << "' does not exist or is a directory.\n";
    return EXIT_FAILURE;
  }

  std::ifstream trace(traceFile.c_str());
  if ( !trace.good() ) {
    std::cerr << "Error reading trace file '" << traceFile << "'.\n";
    return EXIT_FAILURE;
  }

  std::string header;
  std::getline(trace,header);
  std::vector<std::string> headers = madai::SplitString(header, ',');

  int numberOfFields = headers.size();
  assert(numberOfFields == numberOfParameters + numberOfOutputs + 1);

  std::string line;
  size_t lineCount = 0, bestIndex = 0;
  std::vector< double > sums(numberOfFields - 1, 0.0);
  std::vector< std::vector< double > > values(numberOfFields - 1);

  double bestLogLikelihood = -std::numeric_limits< double >::infinity();

  while (std::getline(trace,line)) {
    std::vector<std::string> fields = madai::SplitString(line, ',');
    assert(numberOfFields == (int) fields.size());
    for (int i = 0; i < numberOfFields - 1; ++i) {
      double value = std::atof(fields[i].c_str());
      values[i].push_back(value);
      sums[i] += value;
    }
    double logLikelihood = std::atof(fields[numberOfFields - 1].c_str());
    if (logLikelihood > bestLogLikelihood) {
      bestLogLikelihood = logLikelihood;
      bestIndex = lineCount;
    }
    ++lineCount;
  }

  trace.close();
  std::vector< double > means(numberOfFields - 1,0.0);

  std::vector< double > priorStdDev(numberOfFields - 1,0.0);
  for (int i = 0; i < numberOfParameters; ++i) {
    priorStdDev[i] =
      parameters[i].GetPriorDistribution()->GetStandardDeviation();
  }
  std::cout << std::setw(14) << "parameter";
  std::cout << std::setw(14) << "mean";
  std::cout << std::setw(14) << "std.dev.";
  std::cout << std::setw(14) << "scaled dev.";
  std::cout << std::setw(14) << "best value";
  std::cout << '\n';

  for (int i = 0; i < numberOfFields - 1; ++i) {
    means[i] = sums[i] / lineCount;
  }
  for (int i = 0; i < numberOfParameters; ++i) {
    double variance = 0.0;
    for (size_t k = 0; k < lineCount; ++k) {
      variance += std::pow(values[i][k] - means[i], 2);
    }
    variance /= lineCount;
    std::cout
      << std::setw(14) << parameters[i].m_Name
      << std::setw(14) << means[i]
      << std::setw(14) << std::sqrt(variance)
      << std::setw(14) << std::sqrt(variance) / priorStdDev[i]
      << std::setw(14) << values[i][bestIndex]
      << '\n';
  }

  // Print the relative log-likelihood from the best point
  std::cout << "\nbest log likelihood\n";
  std::cout << std::setw(14) << bestLogLikelihood << "\n";

  std::vector< std::vector< double > > covariancematrix;
  for (int i = 0; i < numberOfFields - 1; ++i)
    covariancematrix.push_back(std::vector< double >(numberOfFields - 1, 0.0));

  for (int i = 0; i < numberOfFields - 1; ++i) {
    for (int j = 0; j <= i; ++j) {
      double covariance = 0.0;
      for (size_t k = 0; k < lineCount; ++k) {
        covariance += (values[i][k] - means[i]) * (values[j][k] - means[j]);
      }
      covariancematrix[i][j] = covariance /= lineCount;
      if (i != j)
        covariancematrix[j][i] = covariancematrix[i][j];
    }
  }

  std::cout << "\ncovariance:\n";
  std::cout << std::setw(14) << "";
  for (int j = 0; j < numberOfParameters; ++j)
    std::cout << std::setw(14) << parameters[j].m_Name;
  std::cout << "\n";
  for (int i = 0; i < numberOfParameters; ++i) {
    std::cout << std::setw(14) << parameters[i].m_Name;
    for (int j = 0; j < numberOfParameters; ++j) {
      std::cout << std::setw(14) << covariancematrix[i][j];
    }
    std::cout << "\n";
  }

  std::cout << "\nscaled covariance:\n";
  std::cout << std::setw(14) << "";
  for (int j = 0; j < numberOfParameters; ++j)
    std::cout << std::setw(14) << parameters[j].m_Name;
  std::cout << "\n";
  for (int i = 0; i < numberOfParameters; ++i) {
    std::cout << std::setw(14) << parameters[i].m_Name;
    for (int j = 0; j < numberOfParameters; ++j) {
      std::cout << std::setw(14) << covariancematrix[i][j] / (
          priorStdDev[i] * priorStdDev[j]);
    }
    std::cout << "\n";
  }

  std::cout << "\nobservable-parameter correlation:\n";
  std::cout << std::setw(14) << "";
  for (int j = 0; j < numberOfParameters; ++j)
    std::cout << std::setw(14) << parameters[j].m_Name;
  std::cout << "\n";
  for (int i = 0; i < numberOfOutputs; ++i) {
    std::cout << std::setw(14) << outputNames[i];
    for (int j = 0; j < numberOfParameters; ++j) {
      std::cout << std::setw(14) << covariancematrix[numberOfParameters + i][j] / (
          std::sqrt(covariancematrix[numberOfParameters + i][numberOfParameters + i]*
          covariancematrix[j][j]));
    }
    std::cout << "\n";
  }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 Copyright 2019 Alain Dargelas

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/*
 * File:   main.cpp
 * Author: alain
 *
 * Created on January 15, 2017, 12:15 AM
 */

#include <iostream>
#include <string>
#include <vector>
#include <sys/stat.h>
#include <sys/param.h>
#include <unistd.h>
#include <fstream>

#include "surelog.h"
#include "ErrorReporting/Report.h"
#include "API/PythonAPI.h"
#include "Utils/StringUtils.h"

unsigned int executeCompilation(int argc, const char ** argv, bool diff_comp_mode,
                                bool fileunit, SURELOG::ErrorContainer::Stats* overallStats = NULL)
{
  bool success = true;
  bool noFatalErrors = true;
  unsigned int codedReturn = 0;
  SURELOG::SymbolTable* symbolTable = new SURELOG::SymbolTable ();
  SURELOG::ErrorContainer* errors = new SURELOG::ErrorContainer (symbolTable);
  SURELOG::CommandLineParser* clp = new SURELOG::CommandLineParser (errors, symbolTable, diff_comp_mode, fileunit);
  success = clp->parseCommandLine (argc, argv);
  bool parseOnly = clp->parseOnly();
  errors->printMessages (clp->muteStdout ());
  if (success && (!clp->help()))
    {
      SURELOG::scompiler* compiler = SURELOG::start_compiler(clp);
      if (!compiler)
        codedReturn |= 1;
      SURELOG::shutdown_compiler(compiler);
    }
  SURELOG::ErrorContainer::Stats stats;
  if (!clp->help()) {
    stats = errors->getErrorStats ();
    if (overallStats)
      (*overallStats) += stats;
    if (stats.nbFatal)
      codedReturn |= 1;
    if (stats.nbSyntax)
      codedReturn |= 2;
    if (stats.nbError)
      codedReturn |= 4;
  }
  bool noFErrors = true;
  if (!clp->help())
     noFErrors = errors->printStats (stats,clp->muteStdout ());
  if (noFErrors == false) {
     noFatalErrors = false;
  }

  std::string ext_command = clp->getExeCommand();
  if (ext_command != "") {
    std::string directory = symbolTable->getSymbol(clp->getFullCompileDir());
    std::string fileList = directory + "/file.lst";
    std::string command = ext_command + " " + fileList;
    int result = system(command.c_str());
    codedReturn |= result;
    std::cout << "Command result: " << result << std::endl;
  }
  clp->logFooter();
  if (diff_comp_mode && fileunit)
    {
       SURELOG::Report* report = new SURELOG::Report();
       std::pair<bool, bool> results = report->makeDiffCompUnitReport(clp, symbolTable );
       success = results.first;
       noFatalErrors = results.second;
       delete report;
    }
  delete clp;
  delete symbolTable;
  delete errors;
  if ((!noFatalErrors) || (!success))
    codedReturn |= 1;
  if (parseOnly)
    return 0;
  else
    return codedReturn;
}
typedef enum {
    NORMAL,
    DIFF,
    BATCH
} COMP_MODE;

int batchCompilation(const char* argv0, std::string batchFile)
{
  char path [10000];
  int returnCode = 0;
  SURELOG::ErrorContainer::Stats overallStats;
  char* p = getcwd(path, 9999);
  if (!p)
    returnCode |= 1;
  std::ifstream stream;
  stream.open(batchFile);
  if (!stream.good()) {
    returnCode |= 1;
    return returnCode;
  }
  std::string line;
  int count = 0;
  while (std::getline(stream, line)) {
    std::cout << "Processing: " << line << std::endl << std::flush;
    std::vector<std::string> args;
    SURELOG::StringUtils::tokenize(line, " ", args);
    int argc = args.size() + 1;
    char** argv = new char*[argc];
    argv[0] = new char [strlen(argv0) + 1];
    strcpy(argv[0], argv0);
    for (int i = 0; i < argc-1; i++) {
      argv[i+1] = new char [args[i].length() + 1];
      strcpy(argv[i+1], args[i].c_str());
    }
    returnCode |= executeCompilation(argc, (const char**) argv, false, false, &overallStats);
    for (int i = 0; i < argc; i++) {
      delete [] argv[i];
    }
    delete [] argv;
    count++;
    int ret = chdir(path);
    if (ret < 0) {
      std::cout << "Could not change directory to " << path << "\n" << std::endl;
      returnCode |= 1;
    }
  }
  std::cout << "Processed " << count << " tests." << std::endl << std::flush;
  SURELOG::SymbolTable* symbolTable = new SURELOG::SymbolTable ();
  SURELOG::ErrorContainer* errors = new SURELOG::ErrorContainer (symbolTable);
  errors->printStats (overallStats);
  delete errors;
  delete symbolTable;
  stream.close();
  return returnCode;
}

int main(int argc, const char ** argv) {
  SURELOG::Waiver::initWaivers();

  unsigned int codedReturn = 0;
  COMP_MODE mode = NORMAL;
  bool python_mode = true;

  std::string batchFile;
  std::string diff_unit_opt = "-diffcompunit";
  std::string nopython_opt  = "-nopython";
  std::string parseonly_opt = "-parseonly";
  std::string batch_opt     = "-batch";
  for (int i = 1; i < argc; i++) {
    if (parseonly_opt == argv[i]) {
      int ret = chdir("..");
      if (ret < 0) {
        std::cout << "Could not change directory to ../\n" << std::endl;
      }
    } else if (diff_unit_opt == argv[i]) {
      mode = DIFF;
    } else if (nopython_opt == argv[i]) {
      python_mode = false;
    } else if (batch_opt == argv[i]) {
      batchFile = argv[i+1];
      i++;
      mode = BATCH;
    }
  }

  if (python_mode)
    SURELOG::PythonAPI::init(argc, argv);

  switch (mode) {
  case DIFF:
  {
    pid_t pid = fork();
    if (pid == 0) {
      // child process
      executeCompilation(argc, argv, true, false);
    } else if (pid > 0) {
      // parent process
      codedReturn = executeCompilation(argc, argv, true, true);
    } else {
      // fork failed
      printf("fork() failed!\n");
      return 1;
    }
    break;
  }
  case NORMAL:
    codedReturn = executeCompilation(argc, argv, false, false);
    break;
  case BATCH:
    codedReturn = batchCompilation(argv[0], batchFile);
    break;
  }

  if (python_mode)
    SURELOG::PythonAPI::shutdown();
  return codedReturn;
}

<commit_msg>Only return non-zero for fatal and syntax errors<commit_after>/*
 Copyright 2019 Alain Dargelas

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/*
 * File:   main.cpp
 * Author: alain
 *
 * Created on January 15, 2017, 12:15 AM
 */

#include <iostream>
#include <string>
#include <vector>
#include <sys/stat.h>
#include <sys/param.h>
#include <unistd.h>
#include <fstream>

#include "surelog.h"
#include "ErrorReporting/Report.h"
#include "API/PythonAPI.h"
#include "Utils/StringUtils.h"

unsigned int executeCompilation(int argc, const char ** argv, bool diff_comp_mode,
                                bool fileunit, SURELOG::ErrorContainer::Stats* overallStats = NULL)
{
  bool success = true;
  bool noFatalErrors = true;
  unsigned int codedReturn = 0;
  SURELOG::SymbolTable* symbolTable = new SURELOG::SymbolTable ();
  SURELOG::ErrorContainer* errors = new SURELOG::ErrorContainer (symbolTable);
  SURELOG::CommandLineParser* clp = new SURELOG::CommandLineParser (errors, symbolTable, diff_comp_mode, fileunit);
  success = clp->parseCommandLine (argc, argv);
  bool parseOnly = clp->parseOnly();
  errors->printMessages (clp->muteStdout ());
  if (success && (!clp->help()))
    {
      SURELOG::scompiler* compiler = SURELOG::start_compiler(clp);
      if (!compiler)
        codedReturn |= 1;
      SURELOG::shutdown_compiler(compiler);
    }
  SURELOG::ErrorContainer::Stats stats;
  if (!clp->help()) {
    stats = errors->getErrorStats ();
    if (overallStats)
      (*overallStats) += stats;
    if (stats.nbFatal)
      codedReturn |= 1;
    if (stats.nbSyntax)
      codedReturn |= 2;
    // Only return non-zero for fatal and syntax errors
    //if (stats.nbError)
    //  codedReturn |= 4;
  }
  bool noFErrors = true;
  if (!clp->help())
     noFErrors = errors->printStats (stats,clp->muteStdout ());
  if (noFErrors == false) {
     noFatalErrors = false;
  }

  std::string ext_command = clp->getExeCommand();
  if (ext_command != "") {
    std::string directory = symbolTable->getSymbol(clp->getFullCompileDir());
    std::string fileList = directory + "/file.lst";
    std::string command = ext_command + " " + fileList;
    int result = system(command.c_str());
    codedReturn |= result;
    std::cout << "Command result: " << result << std::endl;
  }
  clp->logFooter();
  if (diff_comp_mode && fileunit)
    {
       SURELOG::Report* report = new SURELOG::Report();
       std::pair<bool, bool> results = report->makeDiffCompUnitReport(clp, symbolTable );
       success = results.first;
       noFatalErrors = results.second;
       delete report;
    }
  delete clp;
  delete symbolTable;
  delete errors;
  if ((!noFatalErrors) || (!success))
    codedReturn |= 1;
  if (parseOnly)
    return 0;
  else
    return codedReturn;
}
typedef enum {
    NORMAL,
    DIFF,
    BATCH
} COMP_MODE;

int batchCompilation(const char* argv0, std::string batchFile)
{
  char path [10000];
  int returnCode = 0;
  SURELOG::ErrorContainer::Stats overallStats;
  char* p = getcwd(path, 9999);
  if (!p)
    returnCode |= 1;
  std::ifstream stream;
  stream.open(batchFile);
  if (!stream.good()) {
    returnCode |= 1;
    return returnCode;
  }
  std::string line;
  int count = 0;
  while (std::getline(stream, line)) {
    std::cout << "Processing: " << line << std::endl << std::flush;
    std::vector<std::string> args;
    SURELOG::StringUtils::tokenize(line, " ", args);
    int argc = args.size() + 1;
    char** argv = new char*[argc];
    argv[0] = new char [strlen(argv0) + 1];
    strcpy(argv[0], argv0);
    for (int i = 0; i < argc-1; i++) {
      argv[i+1] = new char [args[i].length() + 1];
      strcpy(argv[i+1], args[i].c_str());
    }
    returnCode |= executeCompilation(argc, (const char**) argv, false, false, &overallStats);
    for (int i = 0; i < argc; i++) {
      delete [] argv[i];
    }
    delete [] argv;
    count++;
    int ret = chdir(path);
    if (ret < 0) {
      std::cout << "Could not change directory to " << path << "\n" << std::endl;
      returnCode |= 1;
    }
  }
  std::cout << "Processed " << count << " tests." << std::endl << std::flush;
  SURELOG::SymbolTable* symbolTable = new SURELOG::SymbolTable ();
  SURELOG::ErrorContainer* errors = new SURELOG::ErrorContainer (symbolTable);
  errors->printStats (overallStats);
  delete errors;
  delete symbolTable;
  stream.close();
  return returnCode;
}

int main(int argc, const char ** argv) {
  SURELOG::Waiver::initWaivers();

  unsigned int codedReturn = 0;
  COMP_MODE mode = NORMAL;
  bool python_mode = true;

  std::string batchFile;
  std::string diff_unit_opt = "-diffcompunit";
  std::string nopython_opt  = "-nopython";
  std::string parseonly_opt = "-parseonly";
  std::string batch_opt     = "-batch";
  for (int i = 1; i < argc; i++) {
    if (parseonly_opt == argv[i]) {
      int ret = chdir("..");
      if (ret < 0) {
        std::cout << "Could not change directory to ../\n" << std::endl;
      }
    } else if (diff_unit_opt == argv[i]) {
      mode = DIFF;
    } else if (nopython_opt == argv[i]) {
      python_mode = false;
    } else if (batch_opt == argv[i]) {
      batchFile = argv[i+1];
      i++;
      mode = BATCH;
    }
  }

  if (python_mode)
    SURELOG::PythonAPI::init(argc, argv);

  switch (mode) {
  case DIFF:
  {
    pid_t pid = fork();
    if (pid == 0) {
      // child process
      executeCompilation(argc, argv, true, false);
    } else if (pid > 0) {
      // parent process
      codedReturn = executeCompilation(argc, argv, true, true);
    } else {
      // fork failed
      printf("fork() failed!\n");
      return 1;
    }
    break;
  }
  case NORMAL:
    codedReturn = executeCompilation(argc, argv, false, false);
    break;
  case BATCH:
    codedReturn = batchCompilation(argv[0], batchFile);
    break;
  }

  if (python_mode)
    SURELOG::PythonAPI::shutdown();
  return codedReturn;
}

<|endoftext|>


<commit_before>/**
  *     PartsBasedDetectorOnVideo
  *
  *  Huge chuncks of code shamelessly taken from Hilton Bristow's demo for
  *  PartsBasedDetector.
  *
  *
  *  File:      main.cpp
  *  Author:    Mirko Raca
  *  Created:   November 5, 2013
  *
  */

#include <glog/logging.h>
#include <boost/filesystem.hpp>

#include <opencv2/highgui/highgui.hpp>

#include "PartsBasedDetector.hpp"
#include "Candidate.hpp"
#include "FileStorageModel.hpp"

#define WITH_MATLABIO
#ifdef WITH_MATLABIO
    #include "MatlabIOModel.hpp"
#endif

using namespace cv;
using namespace std;

int main(int argc, char *argv[])
{
    google::InitGoogleLogging(argv[0]);
    DLOG(INFO) << "Execution started";
    if (argc != 5) {
        printf("Usage: PartsBasedDetectorOnVideo model_file video_file output_folder\n");
        exit(-1);
    }

    // determine the type of model to read
    boost::scoped_ptr<Model> model;
    string ext = boost::filesystem::path(argv[1]).extension().string();
    if (ext.compare(".xml") == 0 || ext.compare(".yaml") == 0) {
        model.reset(new FileStorageModel);
    }
#ifdef WITH_MATLABIO
    else if (ext.compare(".mat") == 0) {
        model.reset(new MatlabIOModel);
    }
#endif
    else {
        printf("Unsupported model format: %s\n", ext.c_str());
        LOG(FATAL) << "Unsupported model format: " << ext.c_str();
        exit(-2);
    }
    bool ok = model->deserialize(argv[1]);
    if (!ok) {
        printf("Error deserializing file\n");
        LOG(FATAL) << "Error deserializing file.";
        exit(-3);
    }

    // create the PartsBasedDetector and distribute the model parameters
    Mat_<float> depth; // we don't have one for the video, so it's just a dummy variable
    PartsBasedDetector<float> pbd;
    pbd.distributeModel(*model);

    // load video sequence
    VideoCapture videoSrc((string)argv[2]);
    if( !videoSrc.isOpened() ){
        printf("Could not read video file\n");
        LOG(FATAL) << "Could not read video file: " << argv[2];
        exit(-4);
    }
    double frameCount = videoSrc.get(CV_CAP_PROP_FRAME_COUNT);

    // main loop
    // detect potential candidates in the image
    DLOG(INFO) << "main loop";
    vector<Candidate> candidates;
    Mat curFrameIm;
    while(1){
        candidates.clear();
        videoSrc >> curFrameIm;
        pbd.detect(curFrameIm, depth, candidates);
    }

    // cleanup
    DLOG(INFO) << "Cleanup part";
    videoSrc.release();

    DLOG(INFO) << "Execution finished";
    return 0;
}
<commit_msg>w.i.p.<commit_after>/**
  *     PartsBasedDetectorOnVideo
  *
  *  Huge chunks of code shamelessly taken from Hilton Bristow's demo for
  *  PartsBasedDetector.
  *
  *
  *  File:      main.cpp
  *  Author:    Mirko Raca
  *  Created:   November 5, 2013
  *
  */

#include <glog/logging.h>
#include <boost/filesystem.hpp>
#include <stdio.h>

#include <opencv2/highgui/highgui.hpp>

#include "PartsBasedDetector.hpp"
#include "Candidate.hpp"
#include "FileStorageModel.hpp"

#define WITH_MATLABIO
#ifdef WITH_MATLABIO
    #include "MatlabIOModel.hpp"
#endif

using namespace cv;
using namespace std;

#define OUTPUT_FILENAME_FORMAT "detection_frame%06d.txt"

int main(int argc, char *argv[])
{
    google::InitGoogleLogging(argv[0]);
    DLOG(INFO) << "Execution started";
    if (argc != 5) {
        printf("Usage: PartsBasedDetectorOnVideo model_file video_file output_folder\n");
        exit(-1);
    }

    // determine the type of model to read
    boost::scoped_ptr<Model> model;
    string ext = boost::filesystem::path(argv[1]).extension().string();
    if (ext.compare(".xml") == 0 || ext.compare(".yaml") == 0) {
        model.reset(new FileStorageModel);
    }
#ifdef WITH_MATLABIO
    else if (ext.compare(".mat") == 0) {
        model.reset(new MatlabIOModel);
    }
#endif
    else {
        printf("Unsupported model format: %s\n", ext.c_str());
        LOG(FATAL) << "Unsupported model format: " << ext.c_str();
        exit(-2);
    }
    bool ok = model->deserialize(argv[1]);
    if (!ok) {
        printf("Error deserializing file\n");
        LOG(FATAL) << "Error deserializing file.";
        exit(-3);
    }

    // TODO: check
    // check output folder
    string outputFilePattern = (string) argv[3];
    if( outputFilePattern[outputFilePattern.length()-1] != '/' ){
        outputFilePattern.append("/");
    }
    outputFilePattern.append(OUTPUT_FILENAME_FORMAT);

    // create the PartsBasedDetector and distribute the model parameters
    Mat_<float> depth; // we don't have one for the video, so it's just a dummy variable
    PartsBasedDetector<float> pbd;
    pbd.distributeModel(*model);

    // load video sequence
    VideoCapture videoSrc((string)argv[2]);
    if( !videoSrc.isOpened() ){
        printf("Could not read video file\n");
        LOG(FATAL) << "Could not read video file: " << argv[2];
        exit(-4);
    }
    double frameCount = videoSrc.get(CV_CAP_PROP_FRAME_COUNT);
    double frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES);
    DLOG(INFO) << "Frame count: " << frameCount;
    DLOG(INFO) << "Start frame no: " << frameNo;

    // main loop
    DLOG(INFO) << "main loop";
    vector<Candidate> candidates;
    Mat curFrameIm;
    char outputFilenameBuffer[1024];
    while(frameNo < frameCount){
        candidates.clear();
        videoSrc >> curFrameIm;
        frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES);
        pbd.detect(curFrameIm, depth, candidates);
        // TODO: non-maximum suppression here

        sprintf(outputFilenameBuffer, outputFilePattern.c_str(), frameNo);
        // TODO: output part here
        // cleanup
        if(!curFrameIm.empty())
            curFrameIm.release();
    }

    // cleanup
    DLOG(INFO) << "Cleanup part";
    videoSrc.release();

    DLOG(INFO) << "Execution finished";
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "libaps.h"
#include "constants.h"
#include <thread>

using namespace std;

int main ()
{
  cout << "BBN X6-1000 Test Executable" << endl;

  set_logging_level(5);

  int numDevices;
  numDevices = get_numDevices();

  cout << numDevices << " X6 device" << (numDevices > 1 ? "s": "")  << " found" << endl;

  if (numDevices < 1)
  	return 0;

  char s[] = "stdout";
  set_log(s);

  cout << "Attempting to initialize libaps" << endl;

  init();

  char serialBuffer[100];

  for (int cnt; cnt < numDevices; cnt++) {
  	get_deviceSerial(cnt, serialBuffer);
  	cout << "Device " << cnt << " serial #: " << serialBuffer << endl;
  }

  int rc;
  rc = connect_by_ID(0);

  cout << "connect_by_ID(0) returned " << rc << endl;

  cout << "current logic temperature = " << get_logic_temperature(0) << endl;

  cout << "current PLL frequency = " << get_sampleRate(0) << " MHz" << endl;

  cout << "setting trigger source = EXTERNAL" << endl;

  set_trigger_source(0, EXTERNAL);

  cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;

  cout << "setting trigger source = INTERNAL" << endl;

  set_trigger_source(0, INTERNAL);

  cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;

  cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;

  cout << "set channel(0) enabled = 1" << endl;

  set_channel_enabled(0,0,true);

#if 0

  cout << "enable ramp output" << endl;

  enable_test_generator(0,0,0.001);

  std::this_thread::sleep_for(std::chrono::seconds(5));

  cout << "enable sine wave output" << endl;

  disable_test_generator(0);
  enable_test_generator(0,1,0.001);

  std::this_thread::sleep_for(std::chrono::seconds(5));

  cout << "disabling channel" << endl;
  disable_test_generator(0);

#else

  const int wfs = 10000;
 short wf[wfs];
  for (int cnt = 0; cnt < wfs; cnt++)
    wf[cnt] = (cnt < wfs/2) ? 32767 : -32767;

  set_waveform_int(0, 0, wf, wfs);

  cout << "Running" << endl;

  run(0);

  std::this_thread::sleep_for(std::chrono::seconds(10));

  cout << "Stopping" << endl;

  stop(0);

  std::this_thread::sleep_for(std::chrono::seconds(1));
#endif

  set_channel_enabled(0,0,false);

  cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;

  rc = disconnect_by_ID(0);

  cout << "disconnect_by_ID(0) returned " << rc << endl;

  return 0;
}<commit_msg>Enabled generator tests in main test<commit_after>#include <iostream>

#include "libaps.h"
#include "constants.h"
#include <thread>

using namespace std;

int main ()
{
  cout << "BBN X6-1000 Test Executable" << endl;

  set_logging_level(5);

  int numDevices;
  numDevices = get_numDevices();

  cout << numDevices << " X6 device" << (numDevices > 1 ? "s": "")  << " found" << endl;

  if (numDevices < 1)
  	return 0;

  char s[] = "stdout";
  set_log(s);

  cout << "Attempting to initialize libaps" << endl;

  init();

  char serialBuffer[100];

  for (int cnt; cnt < numDevices; cnt++) {
  	get_deviceSerial(cnt, serialBuffer);
  	cout << "Device " << cnt << " serial #: " << serialBuffer << endl;
  }

  int rc;
  rc = connect_by_ID(0);

  cout << "connect_by_ID(0) returned " << rc << endl;

  cout << "current logic temperature = " << get_logic_temperature(0) << endl;

  cout << "current PLL frequency = " << get_sampleRate(0) << " MHz" << endl;

  cout << "setting trigger source = EXTERNAL" << endl;

  set_trigger_source(0, EXTERNAL);

  cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;

  cout << "setting trigger source = INTERNAL" << endl;

  set_trigger_source(0, INTERNAL);

  cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;

  cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;

  cout << "set channel(0) enabled = 1" << endl;

  set_channel_enabled(0,0,true);

  cout << "enable ramp output" << endl;

  enable_test_generator(0,0,0.001);

  std::this_thread::sleep_for(std::chrono::seconds(5));

  cout << "enable sine wave output" << endl;

  disable_test_generator(0);
  enable_test_generator(0,1,0.001);

  std::this_thread::sleep_for(std::chrono::seconds(5));

  cout << "disabling test generator" << endl;
  disable_test_generator(0);

  const int wfs = 10000;
  short wf[wfs];
  for (int cnt = 0; cnt < wfs; cnt++)
    wf[cnt] = (cnt < wfs/2) ? 32767 : -32767;

  cout << "loading waveform" << endl;

  set_waveform_int(0, 0, wf, wfs);

  cout << "Running" << endl;

  run(0);

  std::this_thread::sleep_for(std::chrono::seconds(10));

  cout << "Stopping" << endl;

  stop(0);

  set_channel_enabled(0,0,false);

  cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;

  rc = disconnect_by_ID(0);

  cout << "disconnect_by_ID(0) returned " << rc << endl;

  return 0;
}<|endoftext|>


<commit_before>#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace std;
static void error_callback(int error, const char* description)
{
    fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
}
int main(int argc, const char ** argv)
{

    GLFWwindow* window;
    glfwSetErrorCallback(error_callback);
    if (!glfwInit())
        exit(EXIT_FAILURE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

    window = glfwCreateWindow(640, 480, "Edit Academy 3D", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    glfwSetKeyCallback(window, key_callback);

// glewInit();
    cout<< glGetString(GL_VERSION)<<endl;
    glClear(GL_COLOR_BUFFER_BIT);
    while (!glfwWindowShouldClose(window))
    {
        float ratio;
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        ratio = width / (float) height;
        glViewport(0, 0, width, height);

        //	glMatrixMode(GL_PROJECTION);
        //	glLoadIdentity();
        //	glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
        //	glMatrixMode(GL_MODELVIEW);
        //	glLoadIdentity();
        //	glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);
        //	glBegin(GL_TRIANGLES);
        //	glColor3f(1.f, 0.f, 0.f);
        //	glVertex3f(-0.6f, -0.4f, 0.f);
        //	glColor3f(0.f, 1.f, 0.f);
        //	glVertex3f(0.6f, -0.4f, 0.f);
        //	glColor3f(0.f, 0.f, 1.f);
        //	glVertex3f(0.f, 0.6f, 0.f);
        //	glEnd();
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<commit_msg>skip glew<commit_after>
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace std;
static void error_callback(int error, const char* description)
{
    fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
}
int main(int argc, const char ** argv)
{

    GLFWwindow* window;
    glfwSetErrorCallback(error_callback);
    if (!glfwInit())
        exit(EXIT_FAILURE);
//    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
//    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
//    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

    window = glfwCreateWindow(640, 480, "Edit Academy 3D", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    glfwSetKeyCallback(window, key_callback);

//    cout<< glGetString(GL_VERSION)<<endl;
//
    while (!glfwWindowShouldClose(window))
    {
        float ratio;
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        ratio = width / (float) height;
        glViewport(0, 0, width, height);
        glClear(GL_COLOR_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
        glMatrixMode(GL_MODELVIEW);

        glLoadIdentity();
        glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);
        glBegin(GL_TRIANGLES);
        glColor3f(1.f, 0.f, 0.f);
        glVertex3f(-0.6f, -0.4f, 0.f);
        glColor3f(0.f, 1.f, 0.f);
        glVertex3f(0.6f, -0.4f, 0.f);
        glColor3f(0.f, 0.f, 1.f);
        glVertex3f(0.f, 0.6f, 0.f);
        glEnd();
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<|endoftext|>


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

#if defined(BROWSER_SYNC)

#include "chrome/test/live_sync/bookmark_model_verifier.h"

#include <vector>
#include <stack>

#include "app/tree_node_iterator.h"
#include "base/rand_util.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/test/live_sync/live_bookmarks_sync_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"

// static
void BookmarkModelVerifier::ExpectBookmarkInfoMatch(
    const BookmarkNode* expected, const BookmarkNode* actual) {
  EXPECT_EQ(expected->GetTitle(), actual->GetTitle());
  EXPECT_EQ(expected->is_folder(), actual->is_folder());
  EXPECT_EQ(expected->GetURL(), actual->GetURL());
  EXPECT_EQ(expected->GetParent()->IndexOfChild(expected),
            actual->GetParent()->IndexOfChild(actual));
}

BookmarkModelVerifier::BookmarkModelVerifier() {
  verifier_profile_.reset(LiveBookmarksSyncTest::MakeProfile(L"verifier"));
  verifier_ = verifier_profile_->GetBookmarkModel();
}

BookmarkModelVerifier* BookmarkModelVerifier::Create() {
  BookmarkModelVerifier* v = new BookmarkModelVerifier();
  LiveBookmarksSyncTest::BlockUntilLoaded(v->verifier_);
  return v;
}

void BookmarkModelVerifier::ExpectMatch(BookmarkModel* actual) {
  ExpectModelsMatch(verifier_, actual);
}

// static
void BookmarkModelVerifier::ExpectModelsMatchIncludingFavicon(
    BookmarkModel* expected, BookmarkModel* actual, bool compare_favicon) {
  TreeNodeIterator<const BookmarkNode> e_iterator(expected->root_node());
  TreeNodeIterator<const BookmarkNode> a_iterator(actual->root_node());

  // Pre-order traversal of each model, comparing at each step.
  while (e_iterator.has_next()) {
    const BookmarkNode* e_node = e_iterator.Next();
    ASSERT_TRUE(a_iterator.has_next());
    const BookmarkNode* a_node = a_iterator.Next();
    ExpectBookmarkInfoMatch(e_node, a_node);
    // Get Favicon and compare if compare_favicon flag is true.
    if (compare_favicon) {
      const SkBitmap& e_node_favicon = expected->GetFavIcon(e_node);
      const SkBitmap& a_node_favicon = actual->GetFavIcon(a_node);
      EXPECT_GT(e_node_favicon.getSize(), (size_t) 0);
      EXPECT_EQ(e_node_favicon.getSize(), a_node_favicon.getSize());
      EXPECT_EQ(e_node_favicon.width(), a_node_favicon.width());
      EXPECT_EQ(e_node_favicon.height(), a_node_favicon.height());
      SkAutoLockPixels bitmap_lock_e(e_node_favicon);
      SkAutoLockPixels bitmap_lock_a(a_node_favicon);
      void* e_node_pixel_addr = e_node_favicon.getPixels();
      ASSERT_TRUE(e_node_pixel_addr);
      void* a_node_pixel_addr = a_node_favicon.getPixels();
      ASSERT_TRUE(a_node_pixel_addr);
      EXPECT_EQ(memcmp(e_node_pixel_addr, a_node_pixel_addr,
          e_node_favicon.getSize()), 0);
    }
  }
  ASSERT_FALSE(a_iterator.has_next());
}

void BookmarkModelVerifier::VerifyNoDuplicates(BookmarkModel* model) {
  TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
  // Pre-order traversal of model tree, looking for duplicate node at
  // each step.
  while (iterator.has_next()) {
    const BookmarkNode* node = iterator.Next();
    std::vector<const BookmarkNode*> nodes;
    if (node->type() != BookmarkNode::URL) { continue; }
    // Get nodes with same URL.
    model->GetNodesByURL(node->GetURL(),&nodes);
    EXPECT_TRUE(nodes.size()>=1);
    for(std::vector<const BookmarkNode*>::const_iterator i=nodes.begin(), e=nodes.end(); i!=e; i++) {
      // Skip if it's same node.
      int64 id = node->id();
      if ( id == (*i)->id()) { continue; }
      else {
        // Make sure title are not same.
        EXPECT_NE(node->GetTitle(),(*i)->GetTitle());
      }
    }
  } // end of while
}

void BookmarkModelVerifier::FindNodeInVerifier(BookmarkModel* foreign_model,
                                               const BookmarkNode* foreign_node,
                                               const BookmarkNode** result) {
  // Climb the tree.
  std::stack<int> path;
  const BookmarkNode* walker = foreign_node;
  while (walker != foreign_model->root_node()) {
    path.push(walker->GetParent()->IndexOfChild(walker));
    walker = walker->GetParent();
  }

  // Swing over to the other tree.
  walker = verifier_->root_node();

  // Climb down.
  while (!path.empty()) {
    ASSERT_TRUE(walker->is_folder());
    ASSERT_LT(path.top(), walker->GetChildCount());
    walker = walker->GetChild(path.top());
    path.pop();
  }

  ExpectBookmarkInfoMatch(foreign_node, walker);
  *result = walker;
}

const BookmarkNode* BookmarkModelVerifier::AddGroup(BookmarkModel* model,
    const BookmarkNode* parent, int index, const string16& title) {
  const BookmarkNode* v_parent = NULL;
  FindNodeInVerifier(model, parent, &v_parent);
  const BookmarkNode* result = model->AddGroup(parent, index, title);
  EXPECT_TRUE(result);
  if (!result) return NULL;
  const BookmarkNode* v_node = verifier_->AddGroup(v_parent, index, title);
  EXPECT_TRUE(v_node);
  if (!v_node) return NULL;
  ExpectBookmarkInfoMatch(v_node, result);
  return result;
}

const BookmarkNode* BookmarkModelVerifier::AddNonEmptyGroup(
    BookmarkModel* model, const BookmarkNode* parent, int index,
    const string16& title, int children_count) {
  const BookmarkNode* bm_folder = AddGroup(model, parent, index, title);
  EXPECT_TRUE(bm_folder);
  if (!bm_folder) return NULL;
  for (int child_index = 0; child_index < children_count; child_index++) {
    int random_int = base::RandInt(1, 100);
    // To create randomness in order, 60% of time add bookmarks
    if (random_int > 40) {
      string16 child_bm_title(bm_folder->GetTitle());
      child_bm_title.append(L"-ChildBM");
      string16 url(L"http://www.nofaviconurl");
      string16 index_str = IntToString16(child_index);
      child_bm_title.append(index_str);
      url.append(index_str);
      url.append(L".com");
      const BookmarkNode* child_nofavicon_bm =
         AddURL(model, bm_folder, child_index, child_bm_title, GURL(url));
    } else {
      // Remaining % of time - Add Bookmark folders
      string16 child_bmfolder_title(bm_folder->GetTitle());
      child_bmfolder_title.append(L"-ChildBMFolder");
      string16 index_str = IntToString16(child_index);
      child_bmfolder_title.append(index_str);
      const BookmarkNode* child_bm_folder =
          AddGroup(model, bm_folder, child_index, child_bmfolder_title);
    }
  }
  return bm_folder;
}

const BookmarkNode* BookmarkModelVerifier::AddURL(BookmarkModel* model,
    const BookmarkNode* parent, int index, const string16& title,
    const GURL& url) {
  const BookmarkNode* v_parent = NULL;
  FindNodeInVerifier(model, parent, &v_parent);
  const BookmarkNode* result = model->AddURL(parent, index, title, url);
  EXPECT_TRUE(result);
  if (!result) return NULL;
  const BookmarkNode* v_node = verifier_->AddURL(v_parent, index, title, url);
  EXPECT_TRUE(v_node);
  if (!v_node) return NULL;
  ExpectBookmarkInfoMatch(v_node, result);
  return result;
}

void BookmarkModelVerifier::SetTitle(BookmarkModel* model,
                                     const BookmarkNode* node,
                                     const string16& title) {
  const BookmarkNode* v_node = NULL;
  FindNodeInVerifier(model, node, &v_node);
  model->SetTitle(node, title);
  verifier_->SetTitle(v_node, title);
}

void BookmarkModelVerifier::Move(BookmarkModel* model, const BookmarkNode* node,
                                 const BookmarkNode* new_parent, int index) {
  const BookmarkNode* v_new_parent = NULL;
  const BookmarkNode* v_node = NULL;
  FindNodeInVerifier(model, new_parent, &v_new_parent);
  FindNodeInVerifier(model, node, &v_node);
  model->Move(node, new_parent, index);
  verifier_->Move(v_node, v_new_parent, index);
}

void BookmarkModelVerifier::Remove(BookmarkModel* model,
                                   const BookmarkNode* parent,
                                   int index) {
  const BookmarkNode* v_parent = NULL;
  FindNodeInVerifier(model, parent, &v_parent);
  ExpectBookmarkInfoMatch(parent->GetChild(index), v_parent->GetChild(index));
  model->Remove(parent, index);
  verifier_->Remove(v_parent, index);
}

void BookmarkModelVerifier::SortChildren(BookmarkModel* model,
                                         const BookmarkNode* parent) {
  const BookmarkNode* v_parent = NULL;
  FindNodeInVerifier(model, parent, &v_parent);
  model->SortChildren(parent);
  verifier_->SortChildren(v_parent);
}

void BookmarkModelVerifier::ReverseChildOrder(BookmarkModel* model,
                                         const BookmarkNode* parent) {
  int child_count = parent->GetChildCount();
  if (child_count <= 0) return;
  for (int index = 0; index < child_count; index++) {
    Move(model, parent->GetChild(index), parent, child_count-index);
  }
}

const BookmarkNode* BookmarkModelVerifier::SetURL(BookmarkModel* model,
                                   const BookmarkNode* node,
                                   const GURL& new_url) {
  const BookmarkNode* v_node = NULL;
  FindNodeInVerifier(model, node, &v_node);
  const BookmarkNode* result = bookmark_utils::ApplyEditsWithNoGroupChange(
      model, node->GetParent(), BookmarkEditor::EditDetails(node),
      node->GetTitle(), new_url, NULL);
  bookmark_utils::ApplyEditsWithNoGroupChange(verifier_, v_node->GetParent(),
      BookmarkEditor::EditDetails(v_node), v_node->GetTitle(), new_url, NULL);
  return result;
}

#endif  // defined(BROWSER_SYNC)
<commit_msg>Fix style issues in BookmarkModelVerifier class.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if defined(BROWSER_SYNC)

#include "chrome/test/live_sync/bookmark_model_verifier.h"

#include <vector>
#include <stack>

#include "app/tree_node_iterator.h"
#include "base/rand_util.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/test/live_sync/live_bookmarks_sync_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"

// static
void BookmarkModelVerifier::ExpectBookmarkInfoMatch(
    const BookmarkNode* expected, const BookmarkNode* actual) {
  EXPECT_EQ(expected->GetTitle(), actual->GetTitle());
  EXPECT_EQ(expected->is_folder(), actual->is_folder());
  EXPECT_EQ(expected->GetURL(), actual->GetURL());
  EXPECT_EQ(expected->GetParent()->IndexOfChild(expected),
            actual->GetParent()->IndexOfChild(actual));
}

BookmarkModelVerifier::BookmarkModelVerifier() {
  verifier_profile_.reset(LiveBookmarksSyncTest::MakeProfile(L"verifier"));
  verifier_ = verifier_profile_->GetBookmarkModel();
}

BookmarkModelVerifier* BookmarkModelVerifier::Create() {
  BookmarkModelVerifier* v = new BookmarkModelVerifier();
  LiveBookmarksSyncTest::BlockUntilLoaded(v->verifier_);
  return v;
}

void BookmarkModelVerifier::ExpectMatch(BookmarkModel* actual) {
  ExpectModelsMatch(verifier_, actual);
}

// static
void BookmarkModelVerifier::ExpectModelsMatchIncludingFavicon(
    BookmarkModel* expected, BookmarkModel* actual, bool compare_favicon) {
  TreeNodeIterator<const BookmarkNode> e_iterator(expected->root_node());
  TreeNodeIterator<const BookmarkNode> a_iterator(actual->root_node());

  // Pre-order traversal of each model, comparing at each step.
  while (e_iterator.has_next()) {
    const BookmarkNode* e_node = e_iterator.Next();
    ASSERT_TRUE(a_iterator.has_next());
    const BookmarkNode* a_node = a_iterator.Next();
    ExpectBookmarkInfoMatch(e_node, a_node);
    // Get Favicon and compare if compare_favicon flag is true.
    if (compare_favicon) {
      const SkBitmap& e_node_favicon = expected->GetFavIcon(e_node);
      const SkBitmap& a_node_favicon = actual->GetFavIcon(a_node);
      EXPECT_GT(e_node_favicon.getSize(), (size_t) 0);
      EXPECT_EQ(e_node_favicon.getSize(), a_node_favicon.getSize());
      EXPECT_EQ(e_node_favicon.width(), a_node_favicon.width());
      EXPECT_EQ(e_node_favicon.height(), a_node_favicon.height());
      SkAutoLockPixels bitmap_lock_e(e_node_favicon);
      SkAutoLockPixels bitmap_lock_a(a_node_favicon);
      void* e_node_pixel_addr = e_node_favicon.getPixels();
      ASSERT_TRUE(e_node_pixel_addr);
      void* a_node_pixel_addr = a_node_favicon.getPixels();
      ASSERT_TRUE(a_node_pixel_addr);
      EXPECT_EQ(memcmp(e_node_pixel_addr, a_node_pixel_addr,
          e_node_favicon.getSize()), 0);
    }
  }
  ASSERT_FALSE(a_iterator.has_next());
}

void BookmarkModelVerifier::VerifyNoDuplicates(BookmarkModel* model) {
  TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
  // Pre-order traversal of model tree, looking for duplicate node at
  // each step.
  while (iterator.has_next()) {
    const BookmarkNode* node = iterator.Next();
    std::vector<const BookmarkNode*> nodes;
    if (node->type() != BookmarkNode::URL)
      continue;
    // Get nodes with same URL.
    model->GetNodesByURL(node->GetURL(), &nodes);
    EXPECT_TRUE(nodes.size() >= 1);
    for (std::vector<const BookmarkNode*>::const_iterator i = nodes.begin(),
         e = nodes.end(); i != e; i++) {
      // Skip if it's same node.
      int64 id = node->id();
      if (id == (*i)->id()) {
        continue;
      } else {
        // Make sure title are not same.
        EXPECT_NE(node->GetTitle(), (*i)->GetTitle());
      }
    }
  }  // end of while
}

void BookmarkModelVerifier::FindNodeInVerifier(BookmarkModel* foreign_model,
                                               const BookmarkNode* foreign_node,
                                               const BookmarkNode** result) {
  // Climb the tree.
  std::stack<int> path;
  const BookmarkNode* walker = foreign_node;
  while (walker != foreign_model->root_node()) {
    path.push(walker->GetParent()->IndexOfChild(walker));
    walker = walker->GetParent();
  }

  // Swing over to the other tree.
  walker = verifier_->root_node();

  // Climb down.
  while (!path.empty()) {
    ASSERT_TRUE(walker->is_folder());
    ASSERT_LT(path.top(), walker->GetChildCount());
    walker = walker->GetChild(path.top());
    path.pop();
  }

  ExpectBookmarkInfoMatch(foreign_node, walker);
  *result = walker;
}

const BookmarkNode* BookmarkModelVerifier::AddGroup(BookmarkModel* model,
    const BookmarkNode* parent, int index, const string16& title) {
  const BookmarkNode* v_parent = NULL;
  FindNodeInVerifier(model, parent, &v_parent);
  const BookmarkNode* result = model->AddGroup(parent, index, title);
  EXPECT_TRUE(result);
  if (!result)
    return NULL;
  const BookmarkNode* v_node = verifier_->AddGroup(v_parent, index, title);
  EXPECT_TRUE(v_node);
  if (!v_node)
    return NULL;
  ExpectBookmarkInfoMatch(v_node, result);
  return result;
}

const BookmarkNode* BookmarkModelVerifier::AddNonEmptyGroup(
    BookmarkModel* model, const BookmarkNode* parent, int index,
    const string16& title, int children_count) {
  const BookmarkNode* bm_folder = AddGroup(model, parent, index, title);
  EXPECT_TRUE(bm_folder);
  if (!bm_folder)
    return NULL;
  for (int child_index = 0; child_index < children_count; child_index++) {
    int random_int = base::RandInt(1, 100);
    // To create randomness in order, 60% of time add bookmarks
    if (random_int > 40) {
      string16 child_bm_title(bm_folder->GetTitle());
      child_bm_title.append(L"-ChildBM");
      string16 url(L"http://www.nofaviconurl");
      string16 index_str = IntToString16(child_index);
      child_bm_title.append(index_str);
      url.append(index_str);
      url.append(L".com");
      const BookmarkNode* child_nofavicon_bm =
         AddURL(model, bm_folder, child_index, child_bm_title, GURL(url));
    } else {
      // Remaining % of time - Add Bookmark folders
      string16 child_bmfolder_title(bm_folder->GetTitle());
      child_bmfolder_title.append(L"-ChildBMFolder");
      string16 index_str = IntToString16(child_index);
      child_bmfolder_title.append(index_str);
      const BookmarkNode* child_bm_folder =
          AddGroup(model, bm_folder, child_index, child_bmfolder_title);
    }
  }
  return bm_folder;
}

const BookmarkNode* BookmarkModelVerifier::AddURL(BookmarkModel* model,
    const BookmarkNode* parent, int index, const string16& title,
    const GURL& url) {
  const BookmarkNode* v_parent = NULL;
  FindNodeInVerifier(model, parent, &v_parent);
  const BookmarkNode* result = model->AddURL(parent, index, title, url);
  EXPECT_TRUE(result);
  if (!result)
    return NULL;
  const BookmarkNode* v_node = verifier_->AddURL(v_parent, index, title, url);
  EXPECT_TRUE(v_node);
  if (!v_node)
    return NULL;
  ExpectBookmarkInfoMatch(v_node, result);
  return result;
}

void BookmarkModelVerifier::SetTitle(BookmarkModel* model,
                                     const BookmarkNode* node,
                                     const string16& title) {
  const BookmarkNode* v_node = NULL;
  FindNodeInVerifier(model, node, &v_node);
  model->SetTitle(node, title);
  verifier_->SetTitle(v_node, title);
}

void BookmarkModelVerifier::Move(BookmarkModel* model, const BookmarkNode* node,
                                 const BookmarkNode* new_parent, int index) {
  const BookmarkNode* v_new_parent = NULL;
  const BookmarkNode* v_node = NULL;
  FindNodeInVerifier(model, new_parent, &v_new_parent);
  FindNodeInVerifier(model, node, &v_node);
  model->Move(node, new_parent, index);
  verifier_->Move(v_node, v_new_parent, index);
}

void BookmarkModelVerifier::Remove(BookmarkModel* model,
                                   const BookmarkNode* parent,
                                   int index) {
  const BookmarkNode* v_parent = NULL;
  FindNodeInVerifier(model, parent, &v_parent);
  ExpectBookmarkInfoMatch(parent->GetChild(index), v_parent->GetChild(index));
  model->Remove(parent, index);
  verifier_->Remove(v_parent, index);
}

void BookmarkModelVerifier::SortChildren(BookmarkModel* model,
                                         const BookmarkNode* parent) {
  const BookmarkNode* v_parent = NULL;
  FindNodeInVerifier(model, parent, &v_parent);
  model->SortChildren(parent);
  verifier_->SortChildren(v_parent);
}

void BookmarkModelVerifier::ReverseChildOrder(BookmarkModel* model,
                                         const BookmarkNode* parent) {
  int child_count = parent->GetChildCount();
  if (child_count <= 0)
    return;
  for (int index = 0; index < child_count; index++)
    Move(model, parent->GetChild(index), parent, child_count-index);
}

const BookmarkNode* BookmarkModelVerifier::SetURL(BookmarkModel* model,
                                   const BookmarkNode* node,
                                   const GURL& new_url) {
  const BookmarkNode* v_node = NULL;
  FindNodeInVerifier(model, node, &v_node);
  const BookmarkNode* result = bookmark_utils::ApplyEditsWithNoGroupChange(
      model, node->GetParent(), BookmarkEditor::EditDetails(node),
      node->GetTitle(), new_url, NULL);
  bookmark_utils::ApplyEditsWithNoGroupChange(verifier_, v_node->GetParent(),
      BookmarkEditor::EditDetails(v_node), v_node->GetTitle(), new_url, NULL);
  return result;
}

#endif  // defined(BROWSER_SYNC)
<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>

using namespace std;

int main() {
        string userinput = "";
	char hostname[64];
	if(gethostname(hostname, sizeof hostname))
		perror("failed to obtain hostname");
	while(userinput != "exit") {
		cout << getlogin() << "@" << hostname <<  "$ ";
		getline(cin, userinput);
	}
	return 0;
}
<commit_msg>changed perror<commit_after>#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>

using namespace std;

int main() {
        string userinput = "";
	string login;
	char hostname[64];
	if(gethostname(hostname, sizeof hostname))
		perror("gethostname");
	while(userinput != "exit") {
		cout << getlogin() << "@" << hostname <<  "$ ";
		getline(cin, userinput);
	}
	return 0;
}
<|endoftext|>