<commit_before>#ifndef _ARBITRARY_ORDER_MAP_
#define _ARBITRARY_ORDER_MAP_

#include <map>
#include <deque>
#include <memory>

template<class keyType, class valueType, class A = std::allocator<valueType> >
class arbitrary_order_map
{
public:
    class pairType
    {
    public:
        pairType(const pairType & in) : first(in.first), second(in.second) {}
        pairType(const keyType & in) : first(in) {}
        pairType(const keyType & in, const valueType & inv) : first(in), second(inv) {}
        pairType(const std::pair<keyType, valueType> & pair) : first(pair.first), second(pair.second) {}
        keyType first;
        valueType second;
    };
//	typedef  std::pair<keyType, valueType> pairType;
	typedef  std::shared_ptr<pairType> ptrType;

	arbitrary_order_map(){}

	~arbitrary_order_map(){}

	valueType &operator[](const keyType &key)
	{
        typename std::map<keyType, ptrType>::iterator it = data.find(key);
		if(it == data.end()){
			;

            return (*(*(keys.emplace(keys.end(),
                                     data.insert(std::pair<keyType, ptrType>(key,
                                                                             ptrType(new pairType(key)))).first->second)))).second;
//			data.emplace(key, keys.back());
//            return t.get()->second;
		}
		return (*(*it).second).second;
	}

	valueType &operator[](size_t index)
	{
		return *keys[index];
	}

	size_t size() const
	{
		return data.size();
	}

	void clear()
	{
		data.clear();
		keys.clear();
	}

	size_t count(keyType)
	{
		return 1;
	}

	bool empty() const
	{
		return data.empty();
	}

	size_t erase(keyType key)
	{
        typename std::map<keyType, ptrType>::iterator it = data.find(key);
		if(it == data.end()){
			return 0;
		}
		pairType * p = (*it).second.get();
		for(typename std::deque<ptrType>::iterator it2 = keys.begin(); it2 != keys.end(); ++it2){
			if((*it2).get() == p){
				keys.erase(it2);
				break;
			}
		}

		return data.erase(key);
	}

	class iterator : public std::iterator<std::input_iterator_tag, std::pair<keyType, ptrType>>
	{
	public:
		friend class reverse_iterator;
		friend class const_iterator;
		iterator()
		{

		}

		iterator(const typename std::deque<ptrType>::iterator & in) : it(in)
		{

		}

		iterator(const iterator& in) : it(in.it)
		{

		}

		~iterator()
		{

		}

		iterator& operator++()
		{
			++it;
			return *this;
		}

		iterator& operator++(int)
		{
			iterator tmp(*this);
			operator++();
			return tmp;
		}
		iterator& operator--()
		{
			--it;
			return *this;
		}

		iterator& operator--(int)
		{
			iterator tmp(*this);
			operator--();
			return tmp;
		}

		bool operator==(const iterator & rhs)
		{
			return it == rhs.it;
		}

		bool operator!=(const iterator & rhs)
		{
			return it != rhs.it;
		}

		pairType &operator*()
		{
			return **it;
		}

		pairType *operator->()
		{
			return (*it).get();
		}

		typename std::deque<ptrType>::iterator &real()
		{
			return it;
		}

	public:
		typename std::deque<ptrType>::iterator 	it;
	};

		class const_iterator : public std::iterator<std::input_iterator_tag, std::pair<keyType, ptrType>>
	{
	public:
		friend class reverse_iterator;
		const_iterator()
		{

		}

		const_iterator(const typename std::deque<ptrType>::const_iterator & in) : it(in)
		{

		}

		const_iterator(typename std::deque<ptrType>::iterator & in) : it(in)
		{

		}

		const_iterator(const const_iterator& in) : it(in.it)
		{

		}

		const_iterator(const iterator& in) : it(in.it)
		{

		}

		~const_iterator()
		{

		}

		const_iterator& operator++()
		{
			++it;
			return *this;
		}

		const_iterator& operator++(int)
		{
			iterator tmp(*this);
			operator++();
			return tmp;
		}
		const_iterator& operator--()
		{
			--it;
			return *this;
		}

		const_iterator& operator--(int)
		{
			iterator tmp(*this);
			operator--();
			return tmp;
		}

		bool operator==(const const_iterator & rhs)
		{
			return it == rhs.it;
		}

		bool operator!=(const const_iterator & rhs)
		{
			return it != rhs.it;
		}

		const pairType &operator*()
		{
			return (*it).get();
		}

		const pairType *operator->()
		{
			return (*it).get();
		}

		const typename std::deque<ptrType>::const_iterator &real()
		{
			return it;
		}

	public:
		typename std::deque<ptrType>::const_iterator 	it;
	};

	class reverse_iterator : public std::iterator<std::input_iterator_tag, std::pair<keyType, ptrType>>
	{
	public:
		reverse_iterator()
		{

		}

		reverse_iterator(const typename std::deque<ptrType>::reverse_iterator & in) : it(in)
		{

		}

		reverse_iterator(const reverse_iterator& in) : it(in.it)
		{

		}

		reverse_iterator(const iterator& in) : it(typename std::deque<ptrType>::reverse_iterator(in.it))
		{

		}

		~reverse_iterator()
		{

		}

		reverse_iterator& operator++()
		{
			++it;
			return *this;
		}

		reverse_iterator& operator++(int)
		{
			reverse_iterator tmp(*this);
			operator++();
			return tmp;
		}
		reverse_iterator& operator--()
		{
			--it;
			return *this;
		}

		reverse_iterator& operator--(int)
		{
			reverse_iterator tmp(*this);
			operator--();
			return tmp;
		}

		bool operator==(const reverse_iterator & rhs) const
		{
			return it == rhs.it;
		}

		bool operator!=(const reverse_iterator & rhs) const
		{
			return it != rhs.it;
		}

		pairType &operator*() const
		{
			return (*it).get();
		}

		pairType *operator->() const
		{
			return (*it).get();
		}

		typename std::deque<ptrType>::reverse_iterator &real()
		{
			return it;
		}

	public:
		typename std::deque<ptrType>::reverse_iterator 	it;
	};

	iterator begin()
	{
		return keys.begin();
	}

	iterator end()
	{
		return keys.end();
	}

	const_iterator begin() const
	{
		return keys.begin();
	}

	const_iterator end() const
	{
		return keys.end();
	}

	reverse_iterator rbegin()
	{
		return keys.rbegin();
	}

	reverse_iterator rend()
	{
		return keys.rend();
	}

	iterator find(keyType key)
	{
        typename std::map<keyType, ptrType>::iterator it = data.find(key);
        if(it == data.end()){
            return keys.end();
        }
        pairType * p = (*it).second.get();
		for(typename std::deque<ptrType>::iterator keyIt = keys.begin(); keyIt != keys.end(); ++keyIt){
			if((*keyIt).get() == p){
				return keyIt;
			}
		}
		return keys.end();
	}

	void erase(iterator it)
	{
		data.erase((*it).first);
		keys.erase(it.real());
	}

	void erase(iterator &start, iterator &finnish)
	{
		for(typename std::deque<ptrType>::iterator keyIt = start.real(); keyIt != finnish.real(); ++keyIt){
			data.erase((*keyIt)->first);
		}

		keys.erase(start.real(), finnish.real());
	}

	bool operator==(const arbitrary_order_map& rhs)
	{
		return data == rhs.data;
	}

	bool operator!=(const arbitrary_order_map& rhs)
	{
		return data != rhs.data;
	}

	bool operator<=(const arbitrary_order_map& rhs)
	{
		return data <= rhs.data;
	}

	bool operator>=(const arbitrary_order_map& rhs)
	{
		return data >= rhs.data;
	}

	bool operator>(const arbitrary_order_map& rhs)
	{
		return data > rhs.data;
	}

	bool operator<(const arbitrary_order_map& rhs)
	{
		return data < rhs.data;
	}

	iterator insert(iterator at, pairType  val)
	{
		ptrType n(new pairType(val));
		iterator it = keys.insert(at.real(), n);
		data[val.first] = n;
		return it;
	}

	void insert(iterator start, iterator finnish)
	{
		for(typename std::deque<ptrType>::iterator keyIt = start.real(); keyIt != finnish.real(); ++keyIt){
			insert(end(), *(*keyIt));
		}
	}
protected:
	std::map<keyType, ptrType>		data;
	std::deque<ptrType> 			keys;
};

#endif
<commit_msg>arbitrary_order_map is twice as fast as it was.<commit_after>#ifndef _ARBITRARY_ORDER_MAP_
#define _ARBITRARY_ORDER_MAP_

#include <map>
#include <vector>
#include <memory>

template<class keyType, class valueType, class A = std::allocator<valueType> >
class arbitrary_order_map
{
public:
//    class pairType
//    {
//    public:
//        pairType(const pairType & in) : first(in.first), second(in.second) {}
//        pairType(const keyType & in) : first(in) {}
//        pairType(const keyType & in, const valueType & inv) : first(in), second(inv) {}
//        pairType(const std::pair<keyType, valueType> & pair) : first(pair.first), second(pair.second) {}
//        keyType first;
//        valueType second;
//    };
    typedef std::pair<keyType, valueType> pairType;
    typedef std::shared_ptr<pairType> ptrType;
	typedef typename std::map<keyType, pairType*>::iterator dataIterator;
	typedef typename std::vector<ptrType>::iterator keyIterator;
    typedef std::pair<keyType, pairType*> dataType;
    typedef std::pair<keyType, pairType> data2Type;

    arbitrary_order_map(){}

	~arbitrary_order_map()
    {
    }

	valueType &operator[](const keyType &key)
	{
        dataIterator it = data.find(key);
		if(it == data.end()){
            pairType* p = new pairType(key, valueType());
            keys.emplace_back(ptrType(p));
            data.emplace_hint(data.end(), dataType(key, p));
            return p->second;
		}
		return ((*it).second)->second;
	}

	valueType &operator[](size_t index)
	{
		return *keys[index];
	}

	size_t size() const
	{
		return data.size();
	}

	void clear()
	{
		data.clear();
		keys.clear();
	}

	size_t count(keyType)
	{
		return 1;
	}

	bool empty() const
	{
		return data.empty();
	}

	size_t erase(keyType key)
	{
        dataIterator it = data.find(key);
		if(it == data.end()){
			return 0;
		}
		pairType * p = (*it).second.get();
		for(keyIterator it2 = keys.begin(); it2 != keys.end(); ++it2){
			if((*it2).get() == p){
				keys.erase(it2);
				break;
			}
		}

		return data.erase(key);
	}

	class iterator : public std::iterator<std::input_iterator_tag, data2Type>
	{
	public:
		friend class reverse_iterator;
		friend class const_iterator;
		iterator()
		{

		}

		iterator(const keyIterator & in) : it(in)
		{

		}

		iterator(const iterator& in) : it(in.it)
		{

		}

		~iterator()
		{

		}

		iterator& operator++()
		{
			++it;
			return *this;
		}

		iterator& operator++(int)
		{
			iterator tmp(*this);
			operator++();
			return tmp;
		}
		iterator& operator--()
		{
			--it;
			return *this;
		}

		iterator& operator--(int)
		{
			iterator tmp(*this);
			operator--();
			return tmp;
		}

		bool operator==(const iterator & rhs)
		{
			return it == rhs.it;
		}

		bool operator!=(const iterator & rhs)
		{
			return it != rhs.it;
		}

		pairType &operator*()
		{
			return **it;
		}

		pairType *operator->()
		{
			return (*it).get();
		}

		keyIterator &real()
		{
			return it;
		}

	public:
		keyIterator	it;
	};

    typedef iterator fIterator; // Kludge for Microsoft's compiler casting
                                // const iterator & it to it's parent class
                                // instead of iterator in
                                // reverse_iterator(const fIterator& in)...

	class const_iterator : public std::iterator<std::input_iterator_tag, data2Type>
	{
	public:
		friend class reverse_iterator;
		const_iterator()
		{

		}

		const_iterator(const typename std::vector<ptrType>::const_iterator & in) : it(in)
		{

		}

		const_iterator(keyIterator & in) : it(in)
		{

		}

		const_iterator(const const_iterator& in) : it(in.it)
		{

		}

		const_iterator(const fIterator& in) : it(in.it)
		{

		}

		~const_iterator()
		{

		}

		const_iterator& operator++()
		{
			++it;
			return *this;
		}

		const_iterator& operator++(int)
		{
			iterator tmp(*this);
			operator++();
			return tmp;
		}
		const_iterator& operator--()
		{
			--it;
			return *this;
		}

		const_iterator& operator--(int)
		{
			iterator tmp(*this);
			operator--();
			return tmp;
		}

		bool operator==(const const_iterator & rhs)
		{
			return it == rhs.it;
		}

		bool operator!=(const const_iterator & rhs)
		{
			return it != rhs.it;
		}

		const pairType &operator*()
		{
			return (*it).get();
		}

		const pairType *operator->()
		{
			return (*it).get();
		}

		const typename std::vector<ptrType>::const_iterator &real()
		{
			return it;
		}

	public:
		typename std::vector<ptrType>::const_iterator 	it;
	};

	class reverse_iterator : public std::reverse_iterator<iterator>
	{
	public:
		reverse_iterator()
		{

		}

		reverse_iterator(const typename std::vector<ptrType>::reverse_iterator & in) : it(in)
		{

		}

		reverse_iterator(const reverse_iterator& in) : it(in.it)
		{

		}

		reverse_iterator(const fIterator& in) : it(typename std::vector<ptrType>::reverse_iterator(in.it))
		{

		}

		~reverse_iterator()
		{

		}

		reverse_iterator& operator++()
		{
			++it;
			return *this;
		}

		reverse_iterator& operator++(int)
		{
			reverse_iterator tmp(*this);
			operator++();
			return tmp;
		}
		reverse_iterator& operator--()
		{
			--it;
			return *this;
		}

		reverse_iterator& operator--(int)
		{
			reverse_iterator tmp(*this);
			operator--();
			return tmp;
		}

		bool operator==(const reverse_iterator & rhs) const
		{
			return it == rhs.it;
		}

		bool operator!=(const reverse_iterator & rhs) const
		{
			return it != rhs.it;
		}

		pairType &operator*() const
		{
			return (*it).get();
		}

		pairType *operator->() const
		{
			return (*it).get();
		}

		typename std::vector<ptrType>::reverse_iterator &real()
		{
			return it;
		}

	public:
		typename std::vector<ptrType>::reverse_iterator 	it;
	};

	iterator begin()
	{
		return keys.begin();
	}

	iterator end()
	{
		return keys.end();
	}

	const_iterator begin() const
	{
		return keys.begin();
	}

	const_iterator end() const
	{
		return keys.end();
	}

	reverse_iterator rbegin()
	{
		return keys.rbegin();
	}

	reverse_iterator rend()
	{
		return keys.rend();
	}

	iterator find(keyType key)
	{
        dataIterator it = data.find(key);
        if(it == data.end()){
            return keys.end();
        }
        pairType * p = (*it).second;
		for(keyIterator keyIt = keys.begin(); keyIt != keys.end(); ++keyIt){
			if((*keyIt).get() == p){
				return keyIt;
			}
		}
		return keys.end();
	}

	void erase(iterator it)
	{
		data.erase((*it).first);
		keys.erase(it.real());
	}

	void erase(iterator &start, iterator &finnish)
	{
		for(keyIterator keyIt = start.real(); keyIt != finnish.real(); ++keyIt){
			data.erase((*keyIt)->first);
		}

		keys.erase(start.real(), finnish.real());
	}

	bool operator==(const arbitrary_order_map& rhs)
	{
		return data == rhs.data;
	}

	bool operator!=(const arbitrary_order_map& rhs)
	{
		return data != rhs.data;
	}

	bool operator<=(const arbitrary_order_map& rhs)
	{
		return keys <= rhs.keys;
	}

	bool operator>=(const arbitrary_order_map& rhs)
	{
		return keys >= rhs.keys;
	}

	bool operator>(const arbitrary_order_map& rhs)
	{
		return keys > rhs.keys;
	}

	bool operator<(const arbitrary_order_map& rhs)
	{
		return keys < rhs.keys;
	}

	iterator insert(iterator at, pairType  val)
	{
		pairType* n = (new pairType(val));
		iterator it = keys.insert(at.real(), ptrType(n));
		data[val.first] = n;
		return it;
	}

	void insert(iterator start, iterator finnish)
	{
		for(keyIterator keyIt = start.real(); keyIt != finnish.real(); ++keyIt){
			insert(end(), *(*keyIt));
		}
	}
protected:
	std::map<keyType, pairType*>		data;
	std::vector<ptrType> 			keys;
};

#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <malloc.h>

#ifdef USE_MKL
#define MKL_ILP64
#define FLEXCOMPLEX
#define MKL_INT size_t
#include <mkl.h>
#else
#include <cblas.h>
#endif

inline static float time_diff(struct timeval time1, struct timeval time2)
{
	return time2.tv_sec - time1.tv_sec
			+ ((float)(time2.tv_usec - time1.tv_usec))/1000000;
}

void test_dgemm(size_t m, size_t n, size_t k)
{
	struct timeval start, end;
	double *A, *B, *C;

	printf("test tall col-wise matrix in MKL BLAS: M(%ld x %ld) * M(%ld %ld)\n",
			m, k, k, n);
	A = (double *) memalign(64, m*k*sizeof( double ));
	B = (double *) memalign(64, k*n*sizeof( double ));
	if (A == NULL || B == NULL) {
		printf( "\n ERROR: Can't allocate memory for matrices. Aborting... \n\n");
		free(A);
		free(B);
		return;
	}
#pragma omp parallel for
	for (size_t i = 0; i < (m*k); i++) {
		A[i] = (double)(i+1);
	}

	for (size_t i = 0; i < (k*n); i++) {
		B[i] = (double)(-i-1);
	}

//#pragma omp parallel for
//	for (size_t i = 0; i < (m*n); i++) {
//		C[i] = 0.0;
//	}

	gettimeofday(&start, NULL);
	C = (double *) memalign(64, m*n*sizeof( double ));
	cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1, A,
			m, B, k, 0, C, m);
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to multiply row matrix in parallel\n",
			time_diff(start, end));
}

int main()
{
	test_dgemm(1024 * 1024 * 100, 20, 20);
}
<commit_msg>[Matrix]: test MKL dense matrix multiplication.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <malloc.h>

#ifdef USE_MKL
#define MKL_ILP64
#define FLEXCOMPLEX
#define MKL_INT size_t
#include <mkl.h>
#else
#include <cblas.h>
#endif

size_t num_repeats = 1;

inline static float time_diff(struct timeval time1, struct timeval time2)
{
	return time2.tv_sec - time1.tv_sec
			+ ((float)(time2.tv_usec - time1.tv_usec))/1000000;
}

void test_dgemm(size_t m, size_t n, size_t k)
{
	struct timeval start, end;
	double *A, *B, *C;

	printf("test col-wise matrix in MKL BLAS: M(%ld x %ld) * M(%ld %ld)\n",
			m, k, k, n);
	A = (double *) memalign(64, m*k*sizeof( double ));
	B = (double *) memalign(64, k*n*sizeof( double ));
	if (A == NULL || B == NULL) {
		printf( "\n ERROR: Can't allocate memory for matrices. Aborting... \n\n");
		free(A);
		free(B);
		return;
	}
#pragma omp parallel for
	for (size_t i = 0; i < (m*k); i++) {
		A[i] = (double)(i+1);
	}

#pragma omp parallel for
	for (size_t i = 0; i < (k*n); i++) {
		B[i] = (double)(-i-1);
	}

//#pragma omp parallel for
//	for (size_t i = 0; i < (m*n); i++) {
//		C[i] = 0.0;
//	}

	for (size_t i = 0; i < num_repeats; i++) {
		gettimeofday(&start, NULL);
		C = (double *) memalign(64, m*n*sizeof( double ));
		cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1, A,
				m, B, k, 0, C, m);
		mkl_free(C);
		gettimeofday(&end, NULL);
		printf("It takes %.3f seconds\n", time_diff(start, end));
	}

	mkl_free(A);
	mkl_free(B);
}

void test_dgemms(size_t block_size, size_t max_num_blocks)
{
	size_t long_dim = 60 * 1024 * 1024;
	for (size_t num_blocks = 1; num_blocks <= max_num_blocks; num_blocks *= 2)
		test_dgemm(long_dim, block_size, num_blocks * block_size);

	for (size_t num_blocks = 1; num_blocks <= max_num_blocks; num_blocks *= 2)
		test_dgemm(num_blocks * block_size, block_size, long_dim);
}

int main()
{
	test_dgemms(4, 128);
	test_dgemms(64, 8);
}
<|endoftext|>


<commit_before>/*
 * main.c file
 */

#include <stdio.h>
#include <iostream>
#include <stdio.h>

#include "Driver.h"

#include "../common/Operations.h"

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

	for(int ai = 1; ai < argc; ++ai)
	{

		FILE* infile;
		infile = fopen(argv[ai],"rb");

		if (infile == NULL)
		{
			std::cerr << "Could not open file: " << argv[ai] << std::endl;
		}
		else
		{
			Driver driver(infile);
			driver.run();

			fclose(infile);
		}
	}

	return 0;
}
<commit_msg>->portability Linux, windows with defines<commit_after>/*
 * main.c file
 */
#define _CRT_SECURE_NO_WARNINGS //use of fopen

#include <stdio.h>
#include <iostream>
#include <stdio.h>

#include "Driver.h"

#include "../common/Operations.h"

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

	for(int ai = 1; ai < argc; ++ai)
	{

		FILE* infile;
		infile = fopen(argv[ai],"rb");

		if (infile == NULL)
		{
			std::cerr << "Could not open file: " << argv[ai] << std::endl;
		}
		else
		{
			Driver driver(infile);
			driver.run();

			fclose(infile);
		}
	}

	return 0;
}
<|endoftext|>


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

#include "base/basictypes.h"
#include "base/logging.h"

#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace logging {

namespace {

using ::testing::Return;

// Needs to be global since log assert handlers can't maintain state.
int log_sink_call_count = 0;

#if !defined(LOGGING_IS_OFFICIAL_BUILD)
void LogSink(const std::string& str) {
  ++log_sink_call_count;
}
#endif  // !defined(LOGGING_IS_OFFICIAL_BUILD)

// Class to make sure any manipulations we do to the min log level are
// contained (i.e., do not affect other unit tests).
class LogStateSaver {
 public:
  LogStateSaver() : old_min_log_level_(GetMinLogLevel()) {}

  ~LogStateSaver() {
    SetMinLogLevel(old_min_log_level_);
    SetLogAssertHandler(NULL);
    SetLogReportHandler(NULL);
    log_sink_call_count = 0;
  }

 private:
  int old_min_log_level_;

  DISALLOW_COPY_AND_ASSIGN(LogStateSaver);
};

class LoggingTest : public testing::Test {
 private:
  LogStateSaver log_state_saver_;
};

class MockLogSource {
 public:
  MOCK_METHOD0(Log, const char*());
};

TEST_F(LoggingTest, BasicLogging) {
  MockLogSource mock_log_source;
  const int kExpectedDebugOrReleaseCalls = 6;
  const int kExpectedDebugCalls = 6;
  const int kExpectedCalls =
      kExpectedDebugOrReleaseCalls + (DEBUG_MODE ? kExpectedDebugCalls : 0);
  EXPECT_CALL(mock_log_source, Log()).Times(kExpectedCalls).
      WillRepeatedly(Return("log message"));

  SetMinLogLevel(LOG_INFO);

  EXPECT_TRUE(LOG_IS_ON(INFO));
  // As of g++-4.5, the first argument to EXPECT_EQ cannot be a
  // constant expression.
  const bool kIsDebugMode = (DEBUG_MODE != 0);
  EXPECT_TRUE(kIsDebugMode == DLOG_IS_ON(INFO));
  EXPECT_TRUE(VLOG_IS_ON(0));

  LOG(INFO) << mock_log_source.Log();
  LOG_IF(INFO, true) << mock_log_source.Log();
  PLOG(INFO) << mock_log_source.Log();
  PLOG_IF(INFO, true) << mock_log_source.Log();
  VLOG(0) << mock_log_source.Log();
  VLOG_IF(0, true) << mock_log_source.Log();

  DLOG(INFO) << mock_log_source.Log();
  DLOG_IF(INFO, true) << mock_log_source.Log();
  DPLOG(INFO) << mock_log_source.Log();
  DPLOG_IF(INFO, true) << mock_log_source.Log();
  DVLOG(0) << mock_log_source.Log();
  DVLOG_IF(0, true) << mock_log_source.Log();
}

TEST_F(LoggingTest, LogIsOn) {
#if defined(NDEBUG)
  const bool kDfatalIsFatal = false;
#else  // defined(NDEBUG)
  const bool kDfatalIsFatal = true;
#endif  // defined(NDEBUG)

  SetMinLogLevel(LOG_INFO);
  EXPECT_TRUE(LOG_IS_ON(INFO));
  EXPECT_TRUE(LOG_IS_ON(WARNING));
  EXPECT_TRUE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(LOG_IS_ON(DFATAL));

  SetMinLogLevel(LOG_WARNING);
  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_TRUE(LOG_IS_ON(WARNING));
  EXPECT_TRUE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(LOG_IS_ON(DFATAL));

  SetMinLogLevel(LOG_ERROR);
  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_FALSE(LOG_IS_ON(WARNING));
  EXPECT_TRUE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(LOG_IS_ON(DFATAL));

  SetMinLogLevel(LOG_ERROR_REPORT);
  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_FALSE(LOG_IS_ON(WARNING));
  EXPECT_FALSE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(kDfatalIsFatal == LOG_IS_ON(DFATAL));

  // LOG_IS_ON(ERROR_REPORT) should always be true.
  SetMinLogLevel(LOG_FATAL);
  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_FALSE(LOG_IS_ON(WARNING));
  EXPECT_FALSE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(kDfatalIsFatal == LOG_IS_ON(DFATAL));

  // So should LOG_IS_ON(FATAL).
  SetMinLogLevel(LOG_FATAL + 1);
  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_FALSE(LOG_IS_ON(WARNING));
  EXPECT_FALSE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(kDfatalIsFatal == LOG_IS_ON(DFATAL));
}

TEST_F(LoggingTest, LoggingIsLazy) {
  MockLogSource mock_log_source;
  EXPECT_CALL(mock_log_source, Log()).Times(0);

  SetMinLogLevel(LOG_WARNING);

  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_FALSE(DLOG_IS_ON(INFO));
  EXPECT_FALSE(VLOG_IS_ON(1));

  LOG(INFO) << mock_log_source.Log();
  LOG_IF(INFO, false) << mock_log_source.Log();
  PLOG(INFO) << mock_log_source.Log();
  PLOG_IF(INFO, false) << mock_log_source.Log();
  VLOG(1) << mock_log_source.Log();
  VLOG_IF(1, true) << mock_log_source.Log();

  DLOG(INFO) << mock_log_source.Log();
  DLOG_IF(INFO, true) << mock_log_source.Log();
  DPLOG(INFO) << mock_log_source.Log();
  DPLOG_IF(INFO, true) << mock_log_source.Log();
  DVLOG(1) << mock_log_source.Log();
  DVLOG_IF(1, true) << mock_log_source.Log();
}

// Official builds have CHECKs directly call BreakDebugger.
#if !defined(LOGGING_IS_OFFICIAL_BUILD)

TEST_F(LoggingTest, CheckStreamsAreLazy) {
  MockLogSource mock_log_source, uncalled_mock_log_source;
  EXPECT_CALL(mock_log_source, Log()).Times(8).
      WillRepeatedly(Return("check message"));
  EXPECT_CALL(uncalled_mock_log_source, Log()).Times(0);

  SetLogAssertHandler(&LogSink);

  CHECK(mock_log_source.Log()) << uncalled_mock_log_source.Log();
  PCHECK(!mock_log_source.Log()) << mock_log_source.Log();
  CHECK_EQ(mock_log_source.Log(), mock_log_source.Log())
      << uncalled_mock_log_source.Log();
  CHECK_NE(mock_log_source.Log(), mock_log_source.Log())
      << mock_log_source.Log();
}

#endif

TEST_F(LoggingTest, DebugLoggingReleaseBehavior) {
#if !defined(NDEBUG)
  int debug_only_variable = 1;
#endif
  // These should avoid emitting references to |debug_only_variable|
  // in release mode.
  DLOG_IF(INFO, debug_only_variable) << "test";
  DLOG_ASSERT(debug_only_variable) << "test";
  DPLOG_IF(INFO, debug_only_variable) << "test";
  DVLOG_IF(1, debug_only_variable) << "test";
}

TEST_F(LoggingTest, DcheckStreamsAreLazy) {
  MockLogSource mock_log_source;
  EXPECT_CALL(mock_log_source, Log()).Times(0);
#if !defined(LOGGING_IS_OFFICIAL_BUILD) && defined(NDEBUG) && \
    !defined(DCHECK_ALWAYS_ON)
  // Unofficial release build without dcheck enabled.
  set_dcheck_state(DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
  DCHECK(mock_log_source.Log()) << mock_log_source.Log();
  DPCHECK(mock_log_source.Log()) << mock_log_source.Log();
  DCHECK_EQ(0, 0) << mock_log_source.Log();
  DCHECK_EQ(mock_log_source.Log(), static_cast<const char*>(NULL))
      << mock_log_source.Log();
#endif
}

TEST_F(LoggingTest, Dcheck) {
#if LOGGING_IS_OFFICIAL_BUILD
  // Official build.
  EXPECT_FALSE(DCHECK_IS_ON());
  EXPECT_FALSE(DLOG_IS_ON(DCHECK));
#elif defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
  // Unofficial release build.
  set_dcheck_state(ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
  SetLogReportHandler(&LogSink);
  EXPECT_TRUE(DCHECK_IS_ON());
  EXPECT_FALSE(DLOG_IS_ON(DCHECK));
#elif defined(NDEBUG) && defined(DCHECK_ALWAYS_ON)
  // Unofficial release build with real DCHECKS.
  set_dcheck_state(ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
  SetLogAssertHandler(&LogSink);
  EXPECT_TRUE(DCHECK_IS_ON());
  EXPECT_FALSE(DLOG_IS_ON(DCHECK));
#else
  // Unofficial debug build.
  SetLogAssertHandler(&LogSink);
  EXPECT_TRUE(DCHECK_IS_ON());
  EXPECT_TRUE(DLOG_IS_ON(DCHECK));
#endif  // defined(LOGGING_IS_OFFICIAL_BUILD)

  EXPECT_EQ(0, log_sink_call_count);
  DCHECK(false);
  EXPECT_EQ(DCHECK_IS_ON() ? 1 : 0, log_sink_call_count);
  DPCHECK(false);
  EXPECT_EQ(DCHECK_IS_ON() ? 2 : 0, log_sink_call_count);
  DCHECK_EQ(0, 1);
  EXPECT_EQ(DCHECK_IS_ON() ? 3 : 0, log_sink_call_count);
}

TEST_F(LoggingTest, DcheckReleaseBehavior) {
  int some_variable = 1;
  // These should still reference |some_variable| so we don't get
  // unused variable warnings.
  DCHECK(some_variable) << "test";
  DPCHECK(some_variable) << "test";
  DCHECK_EQ(some_variable, 1) << "test";
}

}  // namespace

}  // namespace logging
<commit_msg>Try to fix build more after r234081 / r234112.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/basictypes.h"
#include "base/logging.h"

#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace logging {

namespace {

using ::testing::Return;

// Needs to be global since log assert handlers can't maintain state.
int log_sink_call_count = 0;

#if !LOGGING_IS_OFFICIAL_BUILD
void LogSink(const std::string& str) {
  ++log_sink_call_count;
}
#endif  // !LOGGING_IS_OFFICIAL_BUILD

// Class to make sure any manipulations we do to the min log level are
// contained (i.e., do not affect other unit tests).
class LogStateSaver {
 public:
  LogStateSaver() : old_min_log_level_(GetMinLogLevel()) {}

  ~LogStateSaver() {
    SetMinLogLevel(old_min_log_level_);
    SetLogAssertHandler(NULL);
    SetLogReportHandler(NULL);
    log_sink_call_count = 0;
  }

 private:
  int old_min_log_level_;

  DISALLOW_COPY_AND_ASSIGN(LogStateSaver);
};

class LoggingTest : public testing::Test {
 private:
  LogStateSaver log_state_saver_;
};

class MockLogSource {
 public:
  MOCK_METHOD0(Log, const char*());
};

TEST_F(LoggingTest, BasicLogging) {
  MockLogSource mock_log_source;
  const int kExpectedDebugOrReleaseCalls = 6;
  const int kExpectedDebugCalls = 6;
  const int kExpectedCalls =
      kExpectedDebugOrReleaseCalls + (DEBUG_MODE ? kExpectedDebugCalls : 0);
  EXPECT_CALL(mock_log_source, Log()).Times(kExpectedCalls).
      WillRepeatedly(Return("log message"));

  SetMinLogLevel(LOG_INFO);

  EXPECT_TRUE(LOG_IS_ON(INFO));
  // As of g++-4.5, the first argument to EXPECT_EQ cannot be a
  // constant expression.
  const bool kIsDebugMode = (DEBUG_MODE != 0);
  EXPECT_TRUE(kIsDebugMode == DLOG_IS_ON(INFO));
  EXPECT_TRUE(VLOG_IS_ON(0));

  LOG(INFO) << mock_log_source.Log();
  LOG_IF(INFO, true) << mock_log_source.Log();
  PLOG(INFO) << mock_log_source.Log();
  PLOG_IF(INFO, true) << mock_log_source.Log();
  VLOG(0) << mock_log_source.Log();
  VLOG_IF(0, true) << mock_log_source.Log();

  DLOG(INFO) << mock_log_source.Log();
  DLOG_IF(INFO, true) << mock_log_source.Log();
  DPLOG(INFO) << mock_log_source.Log();
  DPLOG_IF(INFO, true) << mock_log_source.Log();
  DVLOG(0) << mock_log_source.Log();
  DVLOG_IF(0, true) << mock_log_source.Log();
}

TEST_F(LoggingTest, LogIsOn) {
#if defined(NDEBUG)
  const bool kDfatalIsFatal = false;
#else  // defined(NDEBUG)
  const bool kDfatalIsFatal = true;
#endif  // defined(NDEBUG)

  SetMinLogLevel(LOG_INFO);
  EXPECT_TRUE(LOG_IS_ON(INFO));
  EXPECT_TRUE(LOG_IS_ON(WARNING));
  EXPECT_TRUE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(LOG_IS_ON(DFATAL));

  SetMinLogLevel(LOG_WARNING);
  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_TRUE(LOG_IS_ON(WARNING));
  EXPECT_TRUE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(LOG_IS_ON(DFATAL));

  SetMinLogLevel(LOG_ERROR);
  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_FALSE(LOG_IS_ON(WARNING));
  EXPECT_TRUE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(LOG_IS_ON(DFATAL));

  SetMinLogLevel(LOG_ERROR_REPORT);
  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_FALSE(LOG_IS_ON(WARNING));
  EXPECT_FALSE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(kDfatalIsFatal == LOG_IS_ON(DFATAL));

  // LOG_IS_ON(ERROR_REPORT) should always be true.
  SetMinLogLevel(LOG_FATAL);
  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_FALSE(LOG_IS_ON(WARNING));
  EXPECT_FALSE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(kDfatalIsFatal == LOG_IS_ON(DFATAL));

  // So should LOG_IS_ON(FATAL).
  SetMinLogLevel(LOG_FATAL + 1);
  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_FALSE(LOG_IS_ON(WARNING));
  EXPECT_FALSE(LOG_IS_ON(ERROR));
  EXPECT_TRUE(LOG_IS_ON(ERROR_REPORT));
  EXPECT_TRUE(LOG_IS_ON(FATAL));
  EXPECT_TRUE(kDfatalIsFatal == LOG_IS_ON(DFATAL));
}

TEST_F(LoggingTest, LoggingIsLazy) {
  MockLogSource mock_log_source;
  EXPECT_CALL(mock_log_source, Log()).Times(0);

  SetMinLogLevel(LOG_WARNING);

  EXPECT_FALSE(LOG_IS_ON(INFO));
  EXPECT_FALSE(DLOG_IS_ON(INFO));
  EXPECT_FALSE(VLOG_IS_ON(1));

  LOG(INFO) << mock_log_source.Log();
  LOG_IF(INFO, false) << mock_log_source.Log();
  PLOG(INFO) << mock_log_source.Log();
  PLOG_IF(INFO, false) << mock_log_source.Log();
  VLOG(1) << mock_log_source.Log();
  VLOG_IF(1, true) << mock_log_source.Log();

  DLOG(INFO) << mock_log_source.Log();
  DLOG_IF(INFO, true) << mock_log_source.Log();
  DPLOG(INFO) << mock_log_source.Log();
  DPLOG_IF(INFO, true) << mock_log_source.Log();
  DVLOG(1) << mock_log_source.Log();
  DVLOG_IF(1, true) << mock_log_source.Log();
}

// Official builds have CHECKs directly call BreakDebugger.
#if !LOGGING_IS_OFFICIAL_BUILD

TEST_F(LoggingTest, CheckStreamsAreLazy) {
  MockLogSource mock_log_source, uncalled_mock_log_source;
  EXPECT_CALL(mock_log_source, Log()).Times(8).
      WillRepeatedly(Return("check message"));
  EXPECT_CALL(uncalled_mock_log_source, Log()).Times(0);

  SetLogAssertHandler(&LogSink);

  CHECK(mock_log_source.Log()) << uncalled_mock_log_source.Log();
  PCHECK(!mock_log_source.Log()) << mock_log_source.Log();
  CHECK_EQ(mock_log_source.Log(), mock_log_source.Log())
      << uncalled_mock_log_source.Log();
  CHECK_NE(mock_log_source.Log(), mock_log_source.Log())
      << mock_log_source.Log();
}

#endif

TEST_F(LoggingTest, DebugLoggingReleaseBehavior) {
#if !defined(NDEBUG)
  int debug_only_variable = 1;
#endif
  // These should avoid emitting references to |debug_only_variable|
  // in release mode.
  DLOG_IF(INFO, debug_only_variable) << "test";
  DLOG_ASSERT(debug_only_variable) << "test";
  DPLOG_IF(INFO, debug_only_variable) << "test";
  DVLOG_IF(1, debug_only_variable) << "test";
}

TEST_F(LoggingTest, DcheckStreamsAreLazy) {
  MockLogSource mock_log_source;
  EXPECT_CALL(mock_log_source, Log()).Times(0);
#if !LOGGING_IS_OFFICIAL_BUILD && defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
  // Unofficial release build without dcheck enabled.
  set_dcheck_state(DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
  DCHECK(mock_log_source.Log()) << mock_log_source.Log();
  DPCHECK(mock_log_source.Log()) << mock_log_source.Log();
  DCHECK_EQ(0, 0) << mock_log_source.Log();
  DCHECK_EQ(mock_log_source.Log(), static_cast<const char*>(NULL))
      << mock_log_source.Log();
#endif
}

TEST_F(LoggingTest, Dcheck) {
#if LOGGING_IS_OFFICIAL_BUILD
  // Official build.
  EXPECT_FALSE(DCHECK_IS_ON());
  EXPECT_FALSE(DLOG_IS_ON(DCHECK));
#elif defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
  // Unofficial release build.
  set_dcheck_state(ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
  SetLogReportHandler(&LogSink);
  EXPECT_TRUE(DCHECK_IS_ON());
  EXPECT_FALSE(DLOG_IS_ON(DCHECK));
#elif defined(NDEBUG) && defined(DCHECK_ALWAYS_ON)
  // Unofficial release build with real DCHECKS.
  set_dcheck_state(ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
  SetLogAssertHandler(&LogSink);
  EXPECT_TRUE(DCHECK_IS_ON());
  EXPECT_FALSE(DLOG_IS_ON(DCHECK));
#else
  // Unofficial debug build.
  SetLogAssertHandler(&LogSink);
  EXPECT_TRUE(DCHECK_IS_ON());
  EXPECT_TRUE(DLOG_IS_ON(DCHECK));
#endif  // defined(LOGGING_IS_OFFICIAL_BUILD)

  EXPECT_EQ(0, log_sink_call_count);
  DCHECK(false);
  EXPECT_EQ(DCHECK_IS_ON() ? 1 : 0, log_sink_call_count);
  DPCHECK(false);
  EXPECT_EQ(DCHECK_IS_ON() ? 2 : 0, log_sink_call_count);
  DCHECK_EQ(0, 1);
  EXPECT_EQ(DCHECK_IS_ON() ? 3 : 0, log_sink_call_count);
}

TEST_F(LoggingTest, DcheckReleaseBehavior) {
  int some_variable = 1;
  // These should still reference |some_variable| so we don't get
  // unused variable warnings.
  DCHECK(some_variable) << "test";
  DPCHECK(some_variable) << "test";
  DCHECK_EQ(some_variable, 1) << "test";
}

}  // namespace

}  // namespace logging
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
// License:  LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
// Author:  David Burken
//
// Description:
//
// Filter for shifting input to an output range.
//
//----------------------------------------------------------------------------
// $Id$

#include <ossim/imaging/ossimShiftFilter.h>
#include <ossim/imaging/ossimImageDataFactory.h>
#include <ossim/base/ossimCommon.h>
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimTrace.h>

RTTI_DEF1(ossimShiftFilter, "ossimShiftFilter", ossimImageSourceFilter)

static ossimTrace traceDebug("ossimShiftFilter:debug");

ossimShiftFilter::ossimShiftFilter()
   :
   ossimImageSourceFilter(),  // base class
   m_tile(0),
   m_min(ossim::nan()),
   m_max(ossim::nan()),
   m_null(ossim::nan())
{
   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimShiftFilter::ossimShiftFilter entered...\n";
   }
}

ossimShiftFilter::~ossimShiftFilter()
{
}

void ossimShiftFilter::initialize()
{
   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimShiftFilter::initialize entered..." << endl;
   }

   //---
   // Call the base class initialize.
   // Note:  This will reset "theInputConnection" if it changed...
   //---
   ossimImageSourceFilter::initialize();

   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimShiftFilter::initialize exited..." << endl;
   }
}

ossimRefPtr<ossimImageData> ossimShiftFilter::getTile(
   const ossimIrect& tileRect,
   ossim_uint32 resLevel)
{
   ossimRefPtr<ossimImageData> result = 0;

   if ( theInputConnection )
   {
      ossimRefPtr<ossimImageData> inputTile = theInputConnection->getTile( tileRect, resLevel );

      if ( inputTile.get() && isSourceEnabled() &&
           !ossim::isnan(m_null) && !ossim::isnan(m_min) && !ossim::isnan(m_max) )
      {
         // Get its status of the input tile.
         ossimDataObjectStatus tile_status = inputTile->getDataObjectStatus();

         if ( tile_status != OSSIM_NULL )
         {
            if ( !m_tile )
            {
               allocate(); // First time through.
            }

            if ( tile_status != OSSIM_EMPTY )
            {
               // Set the origin,bands of the output tile.
               m_tile->setImageRectangle(tileRect);

               switch(inputTile->getScalarType())
               {
                  case OSSIM_UINT8:
                  {
                     fillTile( ossim_uint8(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_SINT8:
                  {
                     fillTile( ossim_sint8(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_UINT16:
                  case OSSIM_USHORT11:
                  {
                     fillTile( ossim_uint16(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_SINT16:
                  {
                     fillTile( ossim_sint16(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_SINT32:
                  {
                     fillTile( ossim_sint32(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_UINT32:
                  {
                     fillTile( ossim_uint32(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_FLOAT32:
                  case OSSIM_NORMALIZED_FLOAT:
                  {
                     fillTile( ossim_float32(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_FLOAT64:
                  case OSSIM_NORMALIZED_DOUBLE:
                  {
                     fillTile( ossim_float64(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_SCALAR_UNKNOWN:
                  default:
                  {
                     ossimNotify(ossimNotifyLevel_WARN)
                        << "ossimShiftFilter::getTile ERROR Unhandled scalar!" << endl;
                        break;
                  }

               } // Matches: switch(inputTile->getScalarType())

               m_tile->validate();
            }
            else
            {
               m_tile->makeBlank();
            }

            result = m_tile;

         } // Matches: if ( tile_status != OSSIM_NULL )

      } // Matches: if ( inputTile.get() ... )

      if ( !result && inputTile.get() )
      {
         result = inputTile;
      }

   } // Matches: if ( theInputConnection )

   return result;
}

template <class T> void ossimShiftFilter::fillTile(T /* dummy */,
                                                   const ossimImageData* inputTile,
                                                   ossimImageData* outputTile) const
{
   const double BANDS = inputTile->getNumberOfBands();
   const ossim_uint32 SPB = inputTile->getSizePerBand();
   std::vector<double> inNull(BANDS);
   std::vector<double> inMin(BANDS);
   std::vector<double> inMax(BANDS);
   std::vector<double> coef(BANDS);
   ossim_uint32 band = 0;

   for( ; band < BANDS; ++band )
   {
      inNull[band] = inputTile->getNullPix(band);
      inMin[band]  = inputTile->getMinPix(band);
      inMax[band]  = inputTile->getMaxPix(band);
      coef[band]   = (m_max-m_min)/(inMax[band]-inMin[band]);
   }

   double pix = 0;
   for( band = 0; band < BANDS; ++band )
   {
      const T* inBuf = static_cast<const T*>(inputTile->getBuf(band));
      T* outBuf = static_cast<T*>(outputTile->getBuf(band));

      for ( ossim_uint32 i = 0; i < SPB; ++i )
      {
         pix = inBuf[i];
         if (  pix == inNull[band] )
         {
            pix = m_null;
         }
         else
         {
            // Shift and multiply:
            pix = m_min + (pix - inMin[band]) * coef[band];

            // Range check:
            pix = pix <= m_max ? (pix >= m_min ? pix : m_min) : m_max;
         }

         outBuf[i] = static_cast<T>(pix);
      }
   }

   outputTile->validate();
}

ossimString ossimShiftFilter::getClassName() const
{
   return ossimString("ossimShiftFilter");
}

ossimString ossimShiftFilter::getLongName()const
{
   return ossimString("OSSIM shift filter");
}

ossimString ossimShiftFilter::getShortName()const
{
   return ossimString("shift filter");
}

double ossimShiftFilter::getNullPixelValue(ossim_uint32 band )const
{
   double result = 0;;
   if ( theEnableFlag && !ossim::isnan(m_null) )
   {
      result = m_null;
   }
   else
   {
      result = ossimImageSourceFilter::getNullPixelValue( band );
   }
   return result;
}

double ossimShiftFilter::getMinPixelValue(ossim_uint32 band )const
{
   double result = 0;;
   if ( theEnableFlag && !ossim::isnan(m_min) )
   {
      result = m_min;
   }
   else
   {
      result = ossimImageSourceFilter::getMinPixelValue( band );
   }
   return result;
}

double ossimShiftFilter::getMaxPixelValue(ossim_uint32 band )const
{
   double result = 0;;
   if ( theEnableFlag && !ossim::isnan(m_max) )
   {
      result = m_max;
   }
   else
   {
      result = ossimImageSourceFilter::getMaxPixelValue( band );
   }
   return result;
}

void ossimShiftFilter::setNullPixelValue(double null)
{
   m_null = null;
}

void ossimShiftFilter::setMinPixelValue(double min)
{
   m_min = min;
}

void ossimShiftFilter::setMaxPixelValue(double max)
{
   m_max = max;
}

void ossimShiftFilter::allocate()
{
   m_tile = ossimImageDataFactory::instance()->create(this,this);
   m_tile->initialize();
}

// Private to disallow use...
ossimShiftFilter::ossimShiftFilter(const ossimShiftFilter&)
{
}

// Private to disallow use...
ossimShiftFilter& ossimShiftFilter::operator=(const ossimShiftFilter&)
{
   return *this;
}

<commit_msg>Fixed compiler warning<commit_after>//----------------------------------------------------------------------------
// License:  LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
// Author:  David Burken
//
// Description:
//
// Filter for shifting input to an output range.
//
//----------------------------------------------------------------------------
// $Id$

#include <ossim/imaging/ossimShiftFilter.h>
#include <ossim/imaging/ossimImageDataFactory.h>
#include <ossim/base/ossimCommon.h>
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimTrace.h>

RTTI_DEF1(ossimShiftFilter, "ossimShiftFilter", ossimImageSourceFilter)

static ossimTrace traceDebug("ossimShiftFilter:debug");

ossimShiftFilter::ossimShiftFilter()
   :
   ossimImageSourceFilter(),  // base class
   m_tile(0),
   m_min(ossim::nan()),
   m_max(ossim::nan()),
   m_null(ossim::nan())
{
   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimShiftFilter::ossimShiftFilter entered...\n";
   }
}

ossimShiftFilter::~ossimShiftFilter()
{
}

void ossimShiftFilter::initialize()
{
   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimShiftFilter::initialize entered..." << endl;
   }

   //---
   // Call the base class initialize.
   // Note:  This will reset "theInputConnection" if it changed...
   //---
   ossimImageSourceFilter::initialize();

   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimShiftFilter::initialize exited..." << endl;
   }
}

ossimRefPtr<ossimImageData> ossimShiftFilter::getTile(
   const ossimIrect& tileRect,
   ossim_uint32 resLevel)
{
   ossimRefPtr<ossimImageData> result = 0;

   if ( theInputConnection )
   {
      ossimRefPtr<ossimImageData> inputTile = theInputConnection->getTile( tileRect, resLevel );

      if ( inputTile.get() && isSourceEnabled() &&
           !ossim::isnan(m_null) && !ossim::isnan(m_min) && !ossim::isnan(m_max) )
      {
         // Get its status of the input tile.
         ossimDataObjectStatus tile_status = inputTile->getDataObjectStatus();

         if ( tile_status != OSSIM_NULL )
         {
            if ( !m_tile )
            {
               allocate(); // First time through.
            }

            if ( tile_status != OSSIM_EMPTY )
            {
               // Set the origin,bands of the output tile.
               m_tile->setImageRectangle(tileRect);

               switch(inputTile->getScalarType())
               {
                  case OSSIM_UINT8:
                  {
                     fillTile( ossim_uint8(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_SINT8:
                  {
                     fillTile( ossim_sint8(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_UINT16:
                  case OSSIM_USHORT11:
                  {
                     fillTile( ossim_uint16(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_SINT16:
                  {
                     fillTile( ossim_sint16(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_SINT32:
                  {
                     fillTile( ossim_sint32(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_UINT32:
                  {
                     fillTile( ossim_uint32(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_FLOAT32:
                  case OSSIM_NORMALIZED_FLOAT:
                  {
                     fillTile( ossim_float32(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_FLOAT64:
                  case OSSIM_NORMALIZED_DOUBLE:
                  {
                     fillTile( ossim_float64(0), inputTile.get(), m_tile.get() );
                     break;
                  }
                  case OSSIM_SCALAR_UNKNOWN:
                  default:
                  {
                     ossimNotify(ossimNotifyLevel_WARN)
                        << "ossimShiftFilter::getTile ERROR Unhandled scalar!" << endl;
                        break;
                  }

               } // Matches: switch(inputTile->getScalarType())

               m_tile->validate();
            }
            else
            {
               m_tile->makeBlank();
            }

            result = m_tile;

         } // Matches: if ( tile_status != OSSIM_NULL )

      } // Matches: if ( inputTile.get() ... )

      if ( !result && inputTile.get() )
      {
         result = inputTile;
      }

   } // Matches: if ( theInputConnection )

   return result;
}

template <class T> void ossimShiftFilter::fillTile(T /* dummy */,
                                                   const ossimImageData* inputTile,
                                                   ossimImageData* outputTile) const
{
   const double BANDS = inputTile->getNumberOfBands();
   const ossim_uint32 SPB = inputTile->getSizePerBand();
   std::vector<double> inNull(BANDS);
   std::vector<double> inMin(BANDS);
   std::vector<double> inMax(BANDS);
   std::vector<double> coef(BANDS);
   ossim_uint32 band = 0;

   for( ; band < BANDS; ++band )
   {
      inNull[band] = inputTile->getNullPix(band);
      inMin[band]  = inputTile->getMinPix(band);
      inMax[band]  = inputTile->getMaxPix(band);
      coef[band]   = (m_max-m_min)/(inMax[band]-inMin[band]);
   }

   double pix = 0;
   for( band = 0; band < BANDS; ++band )
   {
      const T* inBuf = static_cast<const T*>(inputTile->getBuf(band));
      T* outBuf = static_cast<T*>(outputTile->getBuf(band));

      for ( ossim_uint32 i = 0; i < SPB; ++i )
      {
         pix = inBuf[i];
         if (  pix == inNull[band] )
         {
            pix = m_null;
         }
         else
         {
            // Shift and multiply:
            pix = m_min + (pix - inMin[band]) * coef[band];

            // Range check:
            pix = pix <= m_max ? (pix >= m_min ? pix : m_min) : m_max;
         }

         outBuf[i] = static_cast<T>(pix);
      }
   }

   outputTile->validate();
}

ossimString ossimShiftFilter::getClassName() const
{
   return ossimString("ossimShiftFilter");
}

ossimString ossimShiftFilter::getLongName()const
{
   return ossimString("OSSIM shift filter");
}

ossimString ossimShiftFilter::getShortName()const
{
   return ossimString("shift filter");
}

double ossimShiftFilter::getNullPixelValue(ossim_uint32 band )const
{
   double result = 0;;
   if ( theEnableFlag && !ossim::isnan(m_null) )
   {
      result = m_null;
   }
   else
   {
      result = ossimImageSourceFilter::getNullPixelValue( band );
   }
   return result;
}

double ossimShiftFilter::getMinPixelValue(ossim_uint32 band )const
{
   double result = 0;;
   if ( theEnableFlag && !ossim::isnan(m_min) )
   {
      result = m_min;
   }
   else
   {
      result = ossimImageSourceFilter::getMinPixelValue( band );
   }
   return result;
}

double ossimShiftFilter::getMaxPixelValue(ossim_uint32 band )const
{
   double result = 0;;
   if ( theEnableFlag && !ossim::isnan(m_max) )
   {
      result = m_max;
   }
   else
   {
      result = ossimImageSourceFilter::getMaxPixelValue( band );
   }
   return result;
}

void ossimShiftFilter::setNullPixelValue(double null)
{
   m_null = null;
}

void ossimShiftFilter::setMinPixelValue(double min)
{
   m_min = min;
}

void ossimShiftFilter::setMaxPixelValue(double max)
{
   m_max = max;
}

void ossimShiftFilter::allocate()
{
   m_tile = ossimImageDataFactory::instance()->create(this,this);
   m_tile->initialize();
}

// Private to disallow use...
ossimShiftFilter::ossimShiftFilter(const ossimShiftFilter&)
: m_min(0),m_max(0),m_null(0)
{
}

// Private to disallow use...
ossimShiftFilter& ossimShiftFilter::operator=(const ossimShiftFilter&)
{
   return *this;
}

<|endoftext|>


<commit_before>#include <control/control.hpp>
#include <model/game_state.hpp>
#include <core/game_state_eval.hpp>
#include <core/tetris_oracle.hpp>
#include <core/harmony.hpp>
#include <server/state.hpp>
#include <algorithm>
#include <queue>

void* DispatchThread(void* varg) {
    Control* c = static_cast<Control*>(varg);
    c->PollStateMessages();
}

Control::Control(zmq::context_t& context, ServerInterface& si)
    : m_context(context), m_si(si)
{
    pthread_mutex_init(&m_queueMutex, NULL);
}

Control::~Control() {
    pthread_mutex_destroy(&m_queueMutex);
}

void Control::PollStateMessages() {
    zmq::socket_t stateSocket(m_context, ZMQ_SUB);
    m_si.ConnectToStateServer(stateSocket);
    bool terminate = false;
    while (!terminate) {
        State const* state = m_si.GetState(stateSocket);
        terminate = state->ShouldTerminate();
        pthread_mutex_lock(&m_queueMutex);
        m_messageQueue.push(state);
        pthread_mutex_unlock(&m_queueMutex);
    }
    stateSocket.close();
}

void Control::Execute() {
    // Launches state messaging thread
    pthread_t worker = 0;
    pthread_create(&worker, NULL, DispatchThread, static_cast<void*>(this));

    zmq::socket_t commandSocket(m_context, ZMQ_REQ);
    bool success = m_si.ConnectToCommandServer(commandSocket);
    if (!success)
        exit(-1);
    std::cout << "Entering main loop." << std::endl;

    int weightCount = GetVarCount();
    // Original weights
    float weights[] = {0.413627, -0.723112, -0.214118, 0.0572252,
                        0.666599, -0.758947, 0.297272, 0.112221,
                        -0.571268, -0.255358, -0.63998, -0.572694,
                        0.870288, -0.777475, -0.13282, -0.329776,
                        0.285539, -0.739775, -0.163327};
    Harmony h;
    for (int i = 0; i < weightCount; ++i)
        h.push_back(weights[i]);

    bool gameOver = false;
    GameState game;
    Tetromino const* best = NULL;
    bool inMoveSequence = false;
    std::vector<enum Tetromino::Move> const* sequence = NULL;
    while (!gameOver) {
        if (best != NULL && game.GetPieceInPlay() != NULL && inMoveSequence) {
            if (sequence != NULL) {
                delete sequence;
                sequence = NULL;
            }
            sequence = FindPath(game, *(game.GetPieceInPlay()), *best);
			if (sequence->size() > 0)
				ExecuteSequence(*sequence, game.GetCurrentPieceNumber(),
                                    commandSocket);
        }
        pthread_mutex_lock(&m_queueMutex);
        while (!m_messageQueue.empty()) {
            State const* s = m_messageQueue.front();
            m_messageQueue.pop();
            gameOver = s->ExecuteUpdates(game);
            delete s;
        }
        pthread_mutex_unlock(&m_queueMutex);
        if (game.WasRowClearEvent() || game.PieceHasChanged()) {
            inMoveSequence = false;
        }
        if (game.GetPieceInPlay() != NULL && !inMoveSequence) {
            if (best != NULL) {
                delete best;
                best = NULL;
            }
            best = FindBestMove(game, h);
            GameState next = game;
            next.ApplyMove(*best);
            std::cout << next << std::endl;
            if (best != NULL && (*best) != *(game.GetPieceInPlay())) {
                inMoveSequence = true;
            }
        }
    }
    pthread_join(worker, NULL);
    commandSocket.close();
}

void Control::ExecuteSequence(std::vector<enum Tetromino::Move> const& sequence,
                               int pieceId, zmq::socket_t& commandSocket) {
    int sequenceSize = sequence.size();
    //int executeCount = std::min(sequenceSize, 10);
    int executeCount = sequenceSize;
    for (int i = 0; i < executeCount; ++i) {
        enum Tetromino::Move move = sequence.at(i);
        bool success = m_si.SendMove(move, pieceId, commandSocket);
        if (!success)
            return;
    }
}

<commit_msg>Fixed segfaults and memory leaks with valgrind<commit_after>#include <control/control.hpp>
#include <model/game_state.hpp>
#include <core/game_state_eval.hpp>
#include <core/tetris_oracle.hpp>
#include <core/harmony.hpp>
#include <server/state.hpp>
#include <algorithm>
#include <queue>

void* DispatchThread(void* varg) {
    Control* c = static_cast<Control*>(varg);
    c->PollStateMessages();
}

Control::Control(zmq::context_t& context, ServerInterface& si)
    : m_context(context), m_si(si)
{
    pthread_mutex_init(&m_queueMutex, NULL);
}

Control::~Control() {
    pthread_mutex_destroy(&m_queueMutex);
}

void Control::PollStateMessages() {
    zmq::socket_t stateSocket(m_context, ZMQ_SUB);
    m_si.ConnectToStateServer(stateSocket);
    bool terminate = false;
    while (!terminate) {
        State const* state = m_si.GetState(stateSocket);
        if (state != NULL) {
            terminate = state->ShouldTerminate();
            pthread_mutex_lock(&m_queueMutex);
            m_messageQueue.push(state);
            pthread_mutex_unlock(&m_queueMutex);
        }
    }
    stateSocket.close();
}

void Control::Execute() {
    // Launches state messaging thread
    pthread_t worker = 0;
    pthread_create(&worker, NULL, DispatchThread, static_cast<void*>(this));

    zmq::socket_t commandSocket(m_context, ZMQ_REQ);
    bool success = m_si.ConnectToCommandServer(commandSocket);
    if (!success)
        exit(-1);
    std::cout << "Entering main loop." << std::endl;

    int weightCount = GetVarCount();
    // Original weights
    float weights[] = {0.413627, -0.723112, -0.214118, 0.0572252,
                        0.666599, -0.758947, 0.297272, 0.112221,
                        -0.571268, -0.255358, -0.63998, -0.572694,
                        0.870288, -0.777475, -0.13282, -0.329776,
                        0.285539, -0.739775, -0.163327};
    Harmony h;
    for (int i = 0; i < weightCount; ++i)
        h.push_back(weights[i]);

    bool gameOver = false;
    GameState game;
    Tetromino const* best = NULL;
    bool inMoveSequence = false;
    std::vector<enum Tetromino::Move> const* sequence = NULL;
    while (!gameOver) {
        if (best != NULL && game.GetPieceInPlay() != NULL && inMoveSequence) {
            if (sequence != NULL) {
                delete sequence;
                sequence = NULL;
            }
            sequence = FindPath(game, *(game.GetPieceInPlay()), *best);
			if (sequence != NULL && sequence->size() > 0)
				ExecuteSequence(*sequence, game.GetCurrentPieceNumber(),
                                    commandSocket);
        }
        pthread_mutex_lock(&m_queueMutex);
        while (!m_messageQueue.empty()) {
            State const* s = m_messageQueue.front();
            m_messageQueue.pop();
            if (s != NULL) {
                gameOver = s->ExecuteUpdates(game);
                delete s;
            }
        }
        pthread_mutex_unlock(&m_queueMutex);
        if (game.WasRowClearEvent() || game.PieceHasChanged()) {
            inMoveSequence = false;
        }
        if (game.GetPieceInPlay() != NULL && !inMoveSequence) {
            if (best != NULL) {
                delete best;
                best = NULL;
            }
            best = FindBestMove(game, h);
            if (best != NULL) {
                GameState next = game;
                next.ApplyMove(*best);
                std::cout << next << std::endl;
            }
            if (best != NULL && game.GetPieceInPlay() != NULL &&
                    (*best) != *(game.GetPieceInPlay())) {
                inMoveSequence = true;
            }
        }
    }
    if (best != NULL) {
        delete best;
        best = NULL;
    }
    if (sequence != NULL) {
        delete sequence;
        sequence = NULL;
    }
    pthread_join(worker, NULL);
    commandSocket.close();
}

void Control::ExecuteSequence(std::vector<enum Tetromino::Move> const& sequence,
                               int pieceId, zmq::socket_t& commandSocket) {
    int sequenceSize = sequence.size();
    //int executeCount = std::min(sequenceSize, 10);
    int executeCount = sequenceSize;
    for (int i = 0; i < executeCount; ++i) {
        enum Tetromino::Move move = sequence.at(i);
        bool success = m_si.SendMove(move, pieceId, commandSocket);
        if (!success)
            return;
    }
}

<|endoftext|>


<commit_before>/*************************************************
* FIPS-140 Self Tests Source File                *
* (C) 1999-2007 The Botan Project                *
*************************************************/

#include <botan/fips140.h>
#include <botan/lookup.h>

namespace Botan {

namespace FIPS140 {

namespace {

/*************************************************
* Perform a Known Answer Test                    *
*************************************************/
void do_kat(const std::string& in, const std::string& out,
            const std::string& algo_name, Filter* filter)
   {
   if(out.length())
      {
      Pipe pipe(new Hex_Decoder, filter, new Hex_Encoder);
      pipe.process_msg(in);

      if(out != pipe.read_all_as_string())
         throw Self_Test_Failure("FIPS-140 " + algo_name + " test");
      }
   }

/*************************************************
* Perform a KAT for a cipher                     *
*************************************************/
void cipher_kat(const std::string& in, const std::string& out,
                  const std::string& key, const std::string& iv,
                  const std::string& cipher)
   {
   do_kat(in, out, cipher, get_cipher(cipher, key, iv, ENCRYPTION));
   do_kat(out, in, cipher, get_cipher(cipher, key, iv, DECRYPTION));
   }

/*************************************************
* Perform a KAT for a cipher                     *
*************************************************/
void cipher_kat(const std::string& cipher, const std::string& key,
                  const std::string& iv, const std::string& in,
                  const std::string& ecb_out, const std::string& cbc_out,
                  const std::string& cfb_out, const std::string& ofb_out,
                  const std::string& ctr_out)
   {
   if(!have_block_cipher(cipher))
      return;

   cipher_kat(in, ecb_out, key, "", cipher + "/ECB");
   cipher_kat(in, cbc_out, key, iv, cipher + "/CBC/NoPadding");
   cipher_kat(in, cfb_out, key, iv, cipher + "/CFB");
   cipher_kat(in, ofb_out, key, iv, cipher + "/OFB");
   cipher_kat(in, ctr_out, key, iv, cipher + "/CTR-BE");
   }

/*************************************************
* Perform a KAT for a hash                       *
*************************************************/
void hash_kat(const std::string& hash, const std::string& in,
                const std::string& out)
   {
   if(!have_hash(hash))
      return;
   do_kat(in, out, hash, new Hash_Filter(hash));
   }

/*************************************************
* Perform a KAT for a MAC                        *
*************************************************/
void mac_kat(const std::string& mac, const std::string& in,
               const std::string& out, const std::string& key)
   {
   if(!have_mac(mac))
      return;
   do_kat(in, out, mac, new MAC_Filter(mac, key));
   }

}

/*************************************************
* Perform FIPS 140 Self Tests                    *
*************************************************/
bool passes_self_tests()
  {
  try {
     cipher_kat("DES", "0123456789ABCDEF", "1234567890ABCDEF",
                "4E6F77206973207468652074696D6520666F7220616C6C20",
                "3FA40E8A984D48156A271787AB8883F9893D51EC4B563B53",
                "E5C7CDDE872BF27C43E934008C389C0F683788499A7C05F6",
                "F3096249C7F46E51A69E839B1A92F78403467133898EA622",
                "F3096249C7F46E5135F24A242EEB3D3F3D6D5BE3255AF8C3",
                "F3096249C7F46E51163A8CA0FFC94C27FA2F80F480B86F75");

     cipher_kat("TripleDES",
                "385D7189A5C3D485E1370AA5D408082B5CCCCB5E19F2D90E",
                "C141B5FCCD28DC8A",
                "6E1BD7C6120947A464A6AAB293A0F89A563D8D40D3461B68",
                "64EAAD4ACBB9CEAD6C7615E7C7E4792FE587D91F20C7D2F4",
                "6235A461AFD312973E3B4F7AA7D23E34E03371F8E8C376C9",
                "E26BA806A59B0330DE40CA38E77A3E494BE2B212F6DD624B",
                "E26BA806A59B03307DE2BCC25A08BA40A8BA335F5D604C62",
                "E26BA806A59B03303C62C2EFF32D3ACDD5D5F35EBCC53371");

     cipher_kat("AES",
                "2B7E151628AED2A6ABF7158809CF4F3C",
                "000102030405060708090A0B0C0D0E0F",
                "6BC1BEE22E409F96E93D7E117393172A"
                "AE2D8A571E03AC9C9EB76FAC45AF8E51",
                "3AD77BB40D7A3660A89ECAF32466EF97"
                "F5D3D58503B9699DE785895A96FDBAAF",
                "7649ABAC8119B246CEE98E9B12E9197D"
                "5086CB9B507219EE95DB113A917678B2",
                "3B3FD92EB72DAD20333449F8E83CFB4A"
                "C8A64537A0B3A93FCDE3CDAD9F1CE58B",
                "3B3FD92EB72DAD20333449F8E83CFB4A"
                "7789508D16918F03F53C52DAC54ED825",
                "3B3FD92EB72DAD20333449F8E83CFB4A"
                "010C041999E03F36448624483E582D0E");

     hash_kat("SHA-1", "", "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709");
     hash_kat("SHA-1", "616263", "A9993E364706816ABA3E25717850C26C9CD0D89D");
     hash_kat("SHA-1",
              "6162636462636465636465666465666765666768666768696768696A"
              "68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071",
              "84983E441C3BD26EBAAE4AA1F95129E5E54670F1");

     mac_kat("HMAC(SHA-1)", "4869205468657265",
             "B617318655057264E28BC0B6FB378C8EF146BE00",
             "0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");

     mac_kat("X9.19-MAC",
             "31311C3931383237333634351C1C35383134333237361C1C3B3132333435"
             "36373839303132333435363D3939313231303030303F1C30303031323530"
             "301C393738363533343132343837363932331C", "C209CCB78EE1B606",
             "0123456789ABCDEFFEDCBA9876543210");
  }
  catch(std::exception)
     {
     return false;
     }

  return true;
  }

}

}
<commit_msg>Add startup selftests for SHA-256 and HMAC(SHA-256)<commit_after>/*************************************************
* FIPS-140 Self Tests Source File                *
* (C) 1999-2007 The Botan Project                *
*************************************************/

#include <botan/fips140.h>
#include <botan/lookup.h>

namespace Botan {

namespace FIPS140 {

namespace {

/*************************************************
* Perform a Known Answer Test                    *
*************************************************/
void do_kat(const std::string& in, const std::string& out,
            const std::string& algo_name, Filter* filter)
   {
   if(out.length())
      {
      Pipe pipe(new Hex_Decoder, filter, new Hex_Encoder);
      pipe.process_msg(in);

      if(out != pipe.read_all_as_string())
         throw Self_Test_Failure("FIPS-140 " + algo_name + " test");
      }
   }

/*************************************************
* Perform a KAT for a cipher                     *
*************************************************/
void cipher_kat(const std::string& in, const std::string& out,
                  const std::string& key, const std::string& iv,
                  const std::string& cipher)
   {
   do_kat(in, out, cipher, get_cipher(cipher, key, iv, ENCRYPTION));
   do_kat(out, in, cipher, get_cipher(cipher, key, iv, DECRYPTION));
   }

/*************************************************
* Perform a KAT for a cipher                     *
*************************************************/
void cipher_kat(const std::string& cipher, const std::string& key,
                  const std::string& iv, const std::string& in,
                  const std::string& ecb_out, const std::string& cbc_out,
                  const std::string& cfb_out, const std::string& ofb_out,
                  const std::string& ctr_out)
   {
   if(!have_block_cipher(cipher))
      return;

   cipher_kat(in, ecb_out, key, "", cipher + "/ECB");
   cipher_kat(in, cbc_out, key, iv, cipher + "/CBC/NoPadding");
   cipher_kat(in, cfb_out, key, iv, cipher + "/CFB");
   cipher_kat(in, ofb_out, key, iv, cipher + "/OFB");
   cipher_kat(in, ctr_out, key, iv, cipher + "/CTR-BE");
   }

/*************************************************
* Perform a KAT for a hash                       *
*************************************************/
void hash_kat(const std::string& hash, const std::string& in,
                const std::string& out)
   {
   if(!have_hash(hash))
      return;
   do_kat(in, out, hash, new Hash_Filter(hash));
   }

/*************************************************
* Perform a KAT for a MAC                        *
*************************************************/
void mac_kat(const std::string& mac, const std::string& in,
               const std::string& out, const std::string& key)
   {
   if(!have_mac(mac))
      return;
   do_kat(in, out, mac, new MAC_Filter(mac, key));
   }

}

/*************************************************
* Perform FIPS 140 Self Tests                    *
*************************************************/
bool passes_self_tests()
  {
  try {
     cipher_kat("DES", "0123456789ABCDEF", "1234567890ABCDEF",
                "4E6F77206973207468652074696D6520666F7220616C6C20",
                "3FA40E8A984D48156A271787AB8883F9893D51EC4B563B53",
                "E5C7CDDE872BF27C43E934008C389C0F683788499A7C05F6",
                "F3096249C7F46E51A69E839B1A92F78403467133898EA622",
                "F3096249C7F46E5135F24A242EEB3D3F3D6D5BE3255AF8C3",
                "F3096249C7F46E51163A8CA0FFC94C27FA2F80F480B86F75");

     cipher_kat("TripleDES",
                "385D7189A5C3D485E1370AA5D408082B5CCCCB5E19F2D90E",
                "C141B5FCCD28DC8A",
                "6E1BD7C6120947A464A6AAB293A0F89A563D8D40D3461B68",
                "64EAAD4ACBB9CEAD6C7615E7C7E4792FE587D91F20C7D2F4",
                "6235A461AFD312973E3B4F7AA7D23E34E03371F8E8C376C9",
                "E26BA806A59B0330DE40CA38E77A3E494BE2B212F6DD624B",
                "E26BA806A59B03307DE2BCC25A08BA40A8BA335F5D604C62",
                "E26BA806A59B03303C62C2EFF32D3ACDD5D5F35EBCC53371");

     cipher_kat("AES",
                "2B7E151628AED2A6ABF7158809CF4F3C",
                "000102030405060708090A0B0C0D0E0F",
                "6BC1BEE22E409F96E93D7E117393172A"
                "AE2D8A571E03AC9C9EB76FAC45AF8E51",
                "3AD77BB40D7A3660A89ECAF32466EF97"
                "F5D3D58503B9699DE785895A96FDBAAF",
                "7649ABAC8119B246CEE98E9B12E9197D"
                "5086CB9B507219EE95DB113A917678B2",
                "3B3FD92EB72DAD20333449F8E83CFB4A"
                "C8A64537A0B3A93FCDE3CDAD9F1CE58B",
                "3B3FD92EB72DAD20333449F8E83CFB4A"
                "7789508D16918F03F53C52DAC54ED825",
                "3B3FD92EB72DAD20333449F8E83CFB4A"
                "010C041999E03F36448624483E582D0E");

     hash_kat("SHA-1", "", "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709");
     hash_kat("SHA-1", "616263", "A9993E364706816ABA3E25717850C26C9CD0D89D");
     hash_kat("SHA-1",
              "6162636462636465636465666465666765666768666768696768696A"
              "68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071",
              "84983E441C3BD26EBAAE4AA1F95129E5E54670F1");

     hash_kat("SHA-256", "",
              "E3B0C44298FC1C149AFBF4C8996FB924"
              "27AE41E4649B934CA495991B7852B855");
     hash_kat("SHA-256", "616263",
              "BA7816BF8F01CFEA414140DE5DAE2223"
              "B00361A396177A9CB410FF61F20015AD");
     hash_kat("SHA-256",
              "6162636462636465636465666465666765666768666768696768696A"
              "68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071",
              "248D6A61D20638B8E5C026930C3E6039"
              "A33CE45964FF2167F6ECEDD419DB06C1");

     mac_kat("HMAC(SHA-1)", "4869205468657265",
             "B617318655057264E28BC0B6FB378C8EF146BE00",
             "0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");

     mac_kat("HMAC(SHA-256)", "4869205468657265",
             "198A607EB44BFBC69903A0F1CF2BBDC5"
             "BA0AA3F3D9AE3C1C7A3B1696A0B68CF7",
             "0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B"
             "0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");

     mac_kat("X9.19-MAC",
             "31311C3931383237333634351C1C35383134333237361C1C3B3132333435"
             "36373839303132333435363D3939313231303030303F1C30303031323530"
             "301C393738363533343132343837363932331C", "C209CCB78EE1B606",
             "0123456789ABCDEFFEDCBA9876543210");
  }
  catch(std::exception)
     {
     return false;
     }

  return true;
  }

}

}
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////////////
// Program to Read in the Data generated by Simulation and Fit it in ROOT
//
// March 2009, M.Barnett
////////////////////////////////////////////////////////////////////////////////

#ifndef __CINT__

#include <iostream>
#include <fstream>
#include <cassert>

#include "TCanvas.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TF1.h"
#include "TStyle.h"
#include "TRint.h"
#include "TMath.h"
#include "TLegend.h"
#include "TGraphErrors.h"

#include "Constants.h"
#include "Units.h"
#include "TUCNDataParser.h"

using namespace Units;
using namespace Constants;

// -- Globals
Double_t total_energy = 200*neV;
Double_t neutronmass = (neutron_mass_c2/c_squared);

using namespace std;

Double_t poissonf(Double_t*x,Double_t*par);
Double_t densityf(Double_t*x, Double_t*par);

Int_t main(Int_t argc,Char_t **argv)
{
	string filename1;
	string filename2;

	if (argc == 3) {
		filename1 = argv[1];
		filename2 = argv[2];
	} else {
		cerr << "Usage:" << endl;
		cerr << "fitucndata <ucndata-filename> <initialangledata-filename>" << endl;
		return 1;
	}

	// --------------------------------------------------------------------------------------
	// Data Collection and Storage
	TUCNDataParser parser;
	parser.LoadFile(filename1);

	cout << "1" << endl;

	string columntitle1 = "Neutron Time";
	string columntitle2 = "Neutron Energy";
	string columntitle3 = "Neutron Path Length";
	string columntitle4 = "X Position";
	string columntitle5 = "Y Position";
	string columntitle6 = "Z Position";
	string columntitle7 = "PX";
	string columntitle8 = "PY";
	string columntitle9 = "PZ";

	vector<string> timedata;
	vector<string> energydata;
	vector<string> pathlengthdata;
	vector<string> xdata;
	vector<string> ydata;
	vector<string> zdata;
	vector<string> pxdata;
	vector<string> pydata;
	vector<string> pzdata;

	vector<double> neutrontimes;
	vector<double> neutronenergies;
	vector<double> neutronpathlengths;
	vector<double> neutronx;
	vector<double> neutrony;
	vector<double> neutronz;
	vector<double> neutronpx;
	vector<double> neutronpy;
	vector<double> neutronpz;

	parser.GetData(timedata, columntitle1);
	parser.ConvertVectorDouble(timedata, neutrontimes);
	parser.GetData(energydata, columntitle2);
	parser.ConvertVectorDouble(energydata, neutronenergies);
	parser.GetData(pathlengthdata, columntitle3);
	parser.ConvertVectorDouble(pathlengthdata, neutronpathlengths);
	parser.GetData(xdata, columntitle4);
	parser.ConvertVectorDouble(xdata, neutronx);
	parser.GetData(ydata, columntitle5);
	parser.ConvertVectorDouble(ydata, neutrony);
	parser.GetData(zdata, columntitle6);
	parser.ConvertVectorDouble(zdata, neutronz);
	parser.GetData(pxdata, columntitle7);
	parser.ConvertVectorDouble(pxdata, neutronpx);
	parser.GetData(pydata, columntitle8);
	parser.ConvertVectorDouble(pydata, neutronpy);
	parser.GetData(pzdata, columntitle9);
	parser.ConvertVectorDouble(pzdata, neutronpz);

	size_t numberofneutrons = neutrontimes.size();

	TRint *theApp = new TRint("UCN App", &argc, argv);
#else
Int_t fitucndata() {

#endif

	// --------------------------------------------------------------------------------------
	// -- Important Parameters
	Int_t nbins = 50;
	Double_t boxX = 0.2, boxY = 0.2, boxZ = 0.9;

	// Fill Histograms
	TH1F * Histogram1a = new TH1F("Histogram1a","Neutron X",nbins,-boxX/2,boxX/2);
	TH1F * Histogram1b = new TH1F("Histogram1b","Neutron Y",nbins,-boxY/2,boxY/2);
	TH1F * Histogram1c = new TH1F("Histogram1c","Neutron Energy",nbins,0.,total_energy/neV);
	//TH1F * Histogram1d = new TH1F("Histogram1d","Neutron Path length",nbins,100,400);
	TH1F * Histogram2a = new TH1F("Histogram2a","Neutron Momentum",nbins,0.0,30);
	TH1F * Histogram2b = new TH1F("Histogram2b","Neutron Px",nbins,-20.,+20.);
	TH1F * Histogram2c = new TH1F("Histogram2c","Neutron Py",nbins,-20.,+20.);
	TH1F * Histogram2d = new TH1F("Histogram2d","Neutron Pz",nbins,-20.,+20.);
	TH1F * Histogram3 = new TH1F("Histogram3a","Neutron Density versus height",nbins,0.0, 2.*boxZ);

	for (unsigned int j = 0; j < numberofneutrons; j++) {
		Histogram1a->Fill(neutronx[j]);
		Histogram1b->Fill(neutrony[j]);
		Histogram1c->Fill(neutronenergies[j]);
		//Histogram1d->Fill(neutronpathlengths[j]);
		Histogram2a->Fill(TMath::Sqrt(neutronpx[j]*neutronpx[j] + neutronpy[j]*neutronpy[j] + neutronpz[j]*neutronpz[j]));
		Histogram2b->Fill(neutronpx[j]);
		Histogram2c->Fill(neutronpy[j]);
		Histogram2d->Fill(neutronpz[j]);
		Histogram3->Fill(neutronz[j]);
	}

	// STYLE ELEMENTS
//	gStyle->SetOptFit(0111); // Sets which things to include in the Fit Box - currently prints chi2, rms and name/value of parameters
//	gStyle->SetPalette(1);

	TCanvas * histcanvas1 = new TCanvas("HistCanvas1","Position, Energy, PathLength",0,0,800,800);
	histcanvas1->Divide(2,2);
	histcanvas1->SetGrid();

	histcanvas1->cd(1);
	Histogram1a->SetXTitle("X Position");
	Histogram1a->SetYTitle("Neutrons");
	Histogram1a->Draw();

	histcanvas1->cd(2);
	Histogram1b->SetXTitle("Y Position");
	Histogram1b->SetYTitle("Neutrons");
	Histogram1b->Draw();

	histcanvas1->cd(3);
	Histogram1c->SetXTitle("Energy (neV)");
	Histogram1c->SetYTitle("Neutrons");
	Histogram1c->Draw();

	// --------------------------------------------------------------------------------------
	TCanvas * histcanvas2 = new TCanvas("HistCanvas2","Momentum",0,0,800,800);
	histcanvas2->Divide(2,2);
	histcanvas2->SetGrid();
	histcanvas2->cd(1);

	Histogram2a->SetXTitle("P (eV)");
	Histogram2a->SetYTitle("Number of Neutrons");
	Histogram2a->Draw();

	histcanvas2->cd(2);
	Histogram2b->SetXTitle("Px (eV)");
	Histogram2b->SetYTitle("Number of Neutrons");
	Histogram2b->Draw();

	histcanvas2->cd(3);
	Histogram2c->SetXTitle("Py (eV)");
	Histogram2c->SetYTitle("Number of Neutrons");
	Histogram2c->Draw();

	histcanvas2->cd(4);
	Histogram2d->SetXTitle("Pz (eV)");
	Histogram2d->SetYTitle("Number of Neutrons");
	Histogram2d->Draw();

	// --------------------------------------------------------------------------------------
	// Fit Neutron Density versus Height
	TCanvas * histcanvas3 = new TCanvas("HistCanvas3","Neutron Density versus height",0,0,800,800);
   histcanvas3->Divide(1,2);
	histcanvas3->SetGrid();
	histcanvas3->cd(1);

	// -- Max height of neutrons
	Double_t maxheight = total_energy/(neutronmass*grav_acceleration);

	// TF1 * theorydensf = new TF1("densityf", densityf,0.0,maxheight,1);
	// theorydensf->SetParName(0,"Const: Density at bottom of tube at time t");
	// theorydensf->SetParameter(0,10);
	// theorydensf->SetLineColor(kBlue);
	// theorydensf->Draw("same");

	TF1 * fitdensf = new TF1("fitdensf", densityf,0.0,maxheight,1);
	fitdensf->SetParName(0,"Const");
	fitdensf->SetParameter(0,240);
	fitdensf->SetLineColor(kRed);

	Histogram3->SetLineColor(kBlack);
	Histogram3->SetXTitle("Height from bottom of Tube (m)");
	Histogram3->SetYTitle("Number of Neutrons");

	Histogram3->Fit("fitdensf", "R");
	Histogram3->Draw("E1");

	// --------------------------------------------------------------------------------------
	// -- Plot difference between bin content and fitted distribution of above histogram
	histcanvas3->cd(2);
	Int_t n = nbins;
  	Double_t ex[n], ey[n], x[n], y[n];
  	for (Int_t i=1;i<n;i++) {
		x[i] = Histogram3->GetBinCenter(i);
		y[i] = Histogram3->GetBinContent(i) - fitdensf->Eval(x[i]);
		ex[i] = 0.;
		ey[i] = Histogram3->GetBinError(i);
	}
  	// create graph
  	TGraphErrors*gr1  = new TGraphErrors(n,x,y,ex,ey);
	gr1->SetTitle("Bin value minus fitted value versus height");
	gr1->Draw("AC*");

	//////////////////
	TCanvas * canvas4 = new TCanvas("Canvas4","Neutron Density versus log(KE/E)",0,0,800,800);
   canvas4->SetGrid();
  	Int_t m = nbins;
	Double_t p[m], q[m];
  	for (Int_t i=1; i<m; i++) {
		p[i] = TMath::Log(Histogram3->GetBinCenter(i));
    	q[i] = TMath::Log(Histogram3->GetBinContent(i));
	}
  	// create graph
  	TGraph *gr2  = new TGraph(m,p,q);
	gr2->Draw("AC*");

	// Set Up Canvas
//	TCanvas * histcanvas = new TCanvas("HistCanvas1","Neutron Travel Time",0,0,800,800);
//	histcanvas->Divide(2,2);
//	histcanvas->SetFillColor(33);
// histcanvas->SetFrameFillColor(41);
//	histcanvas->SetGrid();

	// --------------------------------------------------------------------------------------
	// Plot bounce angle data for one track
	TUCNDataParser parser2;
	parser2.LoadFile("bounceangledata.txt");
	string columntitle10 = "Entering Angle";
	string columntitle11 = "Exiting Angle";

	vector<string> bounceangledata1;
	vector<double> bounceneutronangles1;
	vector<string> bounceangledata2;
	vector<double> bounceneutronangles2;
	parser2.GetData(bounceangledata1, columntitle10);
	parser2.ConvertVectorDouble(bounceangledata1, bounceneutronangles1);
	parser2.GetData(bounceangledata2, columntitle11);
	parser2.ConvertVectorDouble(bounceangledata2, bounceneutronangles2);

	TH1F * Histogram4a = new TH1F("Histogram4a","Entering Angle",20,0.0,TMath::Pi()/2.0);
	TH1F * Histogram4b = new TH1F("Histogram4b","Exiting Angle",20,0.0,TMath::Pi()/2.0);
	cout << bounceneutronangles1.size()	<< "\t" << bounceangledata1.size() << endl;
	for (unsigned int j = 0; j < bounceneutronangles1.size(); j++) {
		cout << bounceneutronangles1[j] << endl;
		Histogram4a->Fill(bounceneutronangles1[j]);
		Histogram4b->Fill(bounceneutronangles2[j]);

	}
	TCanvas * canvas5 = new TCanvas("Canvas5","Bounce angles for 1 neutron out of 10000",0,0,800,800);
	canvas5->Divide(1,2);
	canvas5->cd(1);
	Histogram4a->SetXTitle("Theta (initial)");
	Histogram4a->Draw();
	canvas5->cd(2);
	Histogram4b->SetXTitle("Theta (after bounce)");
	Histogram4b->Draw();

	// --------------------------------------------------------------------------------------
	// Plot initial angle data
	TUCNDataParser parser3;
	parser3.LoadFile(filename2);
	string columntitle12 = "dx";
	string columntitle13 = "dy";
	string columntitle14 = "dz";
	string columntitle15 = "theta";
	string columntitle16 = "phi";

	vector<string> angledata1;
	vector<double> neutronangles1;
	vector<string> angledata2;
	vector<double> neutronangles2;
	vector<string> angledata3;
	vector<double> neutronangles3;
	vector<string> angledata4;
	vector<double> neutronangles4;
	vector<string> angledata5;
	vector<double> neutronangles5;

	parser3.GetData(angledata1, columntitle12);
	parser3.ConvertVectorDouble(angledata1, neutronangles1);
	parser3.GetData(angledata2, columntitle13);
	parser3.ConvertVectorDouble(angledata2, neutronangles2);
	parser3.GetData(angledata3, columntitle14);
	parser3.ConvertVectorDouble(angledata3, neutronangles3);
	parser3.GetData(angledata4, columntitle15);
	parser3.ConvertVectorDouble(angledata4, neutronangles4);
	parser3.GetData(angledata5, columntitle16);
	parser3.ConvertVectorDouble(angledata5, neutronangles5);

	TH3F * Histogram5a = new TH3F("Histogram5a","dx",50,-1.0,1.0, 50,-1.0,1.0, 50,-1.0,1.0);
	TH1F * Histogram5c = new TH1F("Histogram5c","phi", 100,0.0,TMath::Pi()*2);
	TH1F * Histogram5d = new TH1F("Histogram5d","theta",100,0.0,TMath::Pi());

	for (unsigned int j = 0; j < neutronangles3.size(); j++) {
//		cout << neutronangles1[j] << "\t" << neutronangles2[j] << "\t" << neutronangles3[j] << "\t" << neutronangles4[j] << endl;
		Histogram5a->Fill(neutronangles1[j], neutronangles2[j], neutronangles3[j]);
		Histogram5c->Fill(neutronangles5[j]);
		Histogram5d->Fill(neutronangles4[j]);

	}
	TCanvas * canvas6 = new TCanvas("Canvas6","Initial Direction Distribution",0,0,800,800);
	canvas6->cd(1);
	Histogram5a->SetXTitle("X");
	Histogram5a->SetYTitle("Y");
	Histogram5a->SetZTitle("Z");
	Histogram5a->Draw("");

	TCanvas * canvas7 = new TCanvas("Canvas7","Initial Angle Distributions",0,0,800,800);
	canvas7->Divide(1,2);
	canvas7->cd(1);
	Histogram5c->SetXTitle("Phi");
	Histogram5c->Draw("");
	canvas7->cd(2);
	Histogram5d->SetXTitle("Theta");
	Histogram5d->Draw("");

	// --------------------------------------------------------------------------------------
	// Fit Neutron Travel Time

//	histcanvas->cd(1);
/*	Double_t h1par[7];
	TF1 *h1f1  = new TF1("h1f1","gaus",1.0,1.3);
	TF1 *h1f2  = new TF1("h1f2","expo",3,10);
	TF1 *h1f3  = new TF1("h1f3", "expo", 1.4, 2);
	TF1 *h1total = new TF1("h1total","gaus(0)+expo(3)+expo(5)",1.0,10);
	h1f1->SetLineColor(kBlue);
	h1f2->SetLineColor(kBlue);
	h1f3->SetLineColor(kBlue);
	h1total->SetLineColor(kRed);

	Histogram1->SetLineColor(kBlack);
	Histogram1->SetXTitle("Travel Time (s)");
	Histogram1->SetYTitle("Number of Neutrons");

	Histogram1->Fit(h1f1, "R");
	Histogram1->Fit(h1f2, "R+");
	Histogram1->Fit(h1f3, "R+");

	h1f1->GetParameters(&h1par[0]);
	h1f2->GetParameters(&h1par[3]);
   h1f3->GetParameters(&h1par[5]);

	h1total->SetParameters(h1par);
	Histogram1->Fit(h1total,"R+");

	//	TF1 pois1("pois1",poissonf,0,20,2);
	//	pois1.SetParName(0,"Const");
	//	pois1.SetParName(1,"mu");
	//	pois1.SetParameter(0,40); //
	//	pois1.SetParameter(1,5); //
	//	Histogram1->Fit("pois1", "R");
*/
	// --------------------------------------------------------------------------------------
	// Fit Neutron Energy
//	histcanvas->cd(2);

/*	TCanvas * histcanvas2 = new TCanvas("HistCanvas2","Energy (neV)",0,0,800,800);
	histcanvas2->SetFillColor(33);
   //histcanvas2->SetFrameFillColor(41);
	histcanvas2->SetGrid();
	Histogram2->SetLineColor(1);
	Histogram2->SetXTitle("Energy (neV)");
	Histogram2->SetYTitle("Number of Neutrons");
//	Histogram2->Fit("gaus");
	Histogram2->Draw();
*/
	// --------------------------------------------------------------------------------------
	//
//	histcanvas->cd(3);
/*	TCanvas * histcanvas3 = new TCanvas("HistCanvas3","Path Length",0,0,800,800);
	histcanvas3->SetFillColor(33);
   //histcanvas3->SetFrameFillColor(41);
	histcanvas3->SetGrid();
	Histogram2->SetLineColor(2);
	Histogram3->SetXTitle("Path Length (m)");
	Histogram3->SetYTitle("Number of Neutrons");
	Histogram3->Draw();
*/
// --------------------------------------------------------------------------------------

#ifndef __CINT__
	theApp->Run();
#endif
	return 0;
}

Double_t poissonf(Double_t*x,Double_t*par)
{
  return par[0]*TMath::Poisson(x[0],par[1]);
}

Double_t densityf(Double_t*x, Double_t*par)
{
	Double_t value = (total_energy - neutronmass*grav_acceleration*x[0])/total_energy;
	assert(value >= 0.0);
	return par[0]*sqrt(value);
}

<commit_msg>Re-write of fitdata to read the runs.root files<commit_after>#include <iostream>
#include <fstream>
#include <cassert>

#include "TRint.h"
#include "TFile.h"
#include "TKey.h"
#include "TString.h"
#include "TCanvas.h"
#include "TH1.h"
#include "TF1.h"
#include "TMath.h"
#include "TLegend.h"
#include "TGraphErrors.h"

#include "Constants.h"
#include "Units.h"

using namespace std;

Int_t main(Int_t argc,Char_t **argv)
{
	TString filename;
	if (argc == 2) {
		filename = argv[1];
	} else {
		cerr << "Usage:" << endl;
		cerr << "fitdata <rundata-filename.root> " << endl;
		return -1;
	}

	TRint *theApp = new TRint("FittingApp", &argc, argv);

	TFile myfile(filename);
	myfile.ls();

	TIter next(myfile.GetListOfKeys());
	TKey* key;
	while ((key=(TKey*)next())) {
		printf("key: %s points to an object of class: %s at %i , with cycle number: %i \n", key->GetName(), key->GetClassName(),key->GetSeekKey(),key->GetCycle());
//		myfile.GetObject()
	}

	theApp->Run();
	return 0;
}
<|endoftext|>