<commit_before>/**
 * Copyright 2013 Da Zheng
 *
 * This file is part of SAFSlib.
 *
 * SAFSlib is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SAFSlib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SAFSlib.  If not, see <http://www.gnu.org/licenses/>.
 */

#include<algorithm>

#include "parameters.h"
#include "common.h"
#include "RAID_config.h"
#include "cache_config.h"

sys_parameters params;

str2int RAID_options[] = {
	{"RAID0", RAID0},
	{"RAID5", RAID5},
	{"HASH", HASH},
};

str2int cache_types[] = {
	{ "tree", TREE_CACHE } ,
	{ "associative", ASSOCIATIVE_CACHE },
	{ "hash-index", HASH_INDEX_CACHE },
	{ "cuckoo", CUCKOO_CACHE },
	{ "lru2q", LRU2Q_CACHE },
	{ "gclock", GCLOCK_CACHE },
};

sys_parameters::sys_parameters()
{
	RAID_block_size = 64;
	SA_min_cell_size = 12;
	test_hit_rate = -1;		// this disables generating the artificial hit rate.
	io_depth_per_file = 32;
	cache_type = ASSOCIATIVE_CACHE;
	cache_size = 512 * 1024 * 1024;
	RAID_mapping_option = RAID5;
	use_virt_aio = false;
	verify_content = false;
	use_flusher = false;
	vaio_print_freq = 1000000;
	numa_num_process_threads = 1;
	num_nodes = 1;
}

void sys_parameters::init(const std::map<std::string, std::string> &configs)
{
	str2int_map cache_map(cache_types,
			sizeof(cache_types) / sizeof(cache_types[0]));
	str2int_map RAID_option_map(RAID_options,
			sizeof(RAID_options) / sizeof(RAID_options[0]));
	std::map<std::string, std::string>::const_iterator it;

	it = configs.find("RAID_block_size");
	if (it != configs.end()) {
		RAID_block_size = (int) str2size(it->second) / PAGE_SIZE;
	}

	it = configs.find("SA_cell_size");
	if(it != configs.end()) {
		SA_min_cell_size = atoi(it->second.c_str());
	}

	it = configs.find("io_depth");
	if(it != configs.end()) {
		io_depth_per_file = atoi(it->second.c_str());
	}

	it = configs.find("hit_percent");
	if(it != configs.end()) {
		test_hit_rate = atoi(it->second.c_str());
	}

	it = configs.find("cache_type");
	if(it != configs.end()) {
		cache_type = cache_map.map(it->second);
		if (cache_type < 0) {
			fprintf(stderr, "can't find the right cache type\n");
			exit(1);
		}
	}

	it = configs.find("cache_size");
	if(it != configs.end()) {
		cache_size = str2size(it->second);
	}

	it = configs.find("RAID_mapping");
	if (it != configs.end()) {
		RAID_mapping_option = RAID_option_map.map(it->second);
		if (RAID_mapping_option < 0) {
			fprintf(stderr, "can't find the right mapping option\n");
			exit(1);
		}
	}

	it = configs.find("virt_aio");
	if (it != configs.end())
		use_virt_aio = true;

	it = configs.find("verify_content");
	if (it != configs.end()) {
		verify_content = true;
	}

	it = configs.find("use_flusher");
	if (it != configs.end()) {
		use_flusher = true;
	}

	it = configs.find("cache_large_write");
	if (it != configs.end()) {
		cache_large_write = true;
	}

	it = configs.find("vaio_print_freq");
	if (it != configs.end()) {
		vaio_print_freq = str2size(it->second);
	}

	it = configs.find("numa_num_process_threads");
	if (it != configs.end()) {
		numa_num_process_threads = str2size(it->second);
	}

	it = configs.find("num_nodes");
	if (it != configs.end()) {
		num_nodes = str2size(it->second);
	}
}

void sys_parameters::print()
{
	std::cout << "system parameters: " << std::endl;
	std::cout << "\tRAID_block_size: " << RAID_block_size << std::endl;
	std::cout << "\tSA_cell_size: " << SA_min_cell_size << std::endl;
	std::cout << "\tio_depth:" << io_depth_per_file << std::endl;
	std::cout << "\thit_percent: " << test_hit_rate << std::endl;
	std::cout << "\tcache_type: " << cache_type << std::endl;
	std::cout << "\tcache_size: " << cache_size << std::endl;
	std::cout << "\tRAID_mapping: " << RAID_mapping_option << std::endl;
	std::cout << "\tvirt_aio: " << use_virt_aio << std::endl;
	std::cout << "\tverify_content: " << verify_content << std::endl;
	std::cout << "\tuse_flusher: " << use_flusher << std::endl;
	std::cout << "\tcache_large_write: " << cache_large_write << std::endl;
	std::cout << "\tvaio_print_freq: " << vaio_print_freq << std::endl;
	std::cout << "\tnuma_num_process_threads: " << numa_num_process_threads << std::endl;
	std::cout << "\tnum_nodes: " << num_nodes << std::endl;
}

void sys_parameters::print_help()
{
	str2int_map cache_map(cache_types,
			sizeof(cache_types) / sizeof(cache_types[0]));
	str2int_map RAID_option_map(RAID_options,
			sizeof(RAID_options) / sizeof(RAID_options[0]));

	std::cout << "system parameters: " << std::endl;
	std::cout << "\tRAID_block_size: x(k, K, m, M, g, G)" << std::endl;
	std::cout << "\tSA_cell_size: the size of a page set" << std::endl;
	std::cout << "\tio_depth: the number of pending I/O requests per file"
		<< std::endl;
	std::cout << "\thit_percent: the artificial cache hit rate (%)" << std::endl;
	cache_map.print("\tcache_type: ");
	std::cout << "\tcache_size: x(k, K, m, M, g, G)" << std::endl;
	RAID_option_map.print("\tRAID_mapping: ");
	std::cout << "\tvirt_aio: enable virtual AIO for debugging and performance evaluation"
		<< std::endl;
	std::cout << "\tverify_content: verify data for testing" << std::endl;
	std::cout << "\tuse_flusher: use flusher in the page cache" << std::endl;
	std::cout << "\tcache_large_write: enable large write in the page cache."
		<< std::endl;
	std::cout << "\tvaio_print_freq: how frequently a virtual SSD print stat info (in us)"
		<< std::endl;
	std::cout << "\tnuma_num_process_threads: the number of request processing threads per node in part_global_cached_io"
		<< std::endl;
	std::cout << "\tnum_nodes: the number of NUMA nodes the test program should run"
		<< std::endl;
}

static void read_config_file(const std::string &conf_file,
		std::map<std::string, std::string> &configs)
{
	FILE *f = fopen(conf_file.c_str(), "r");
	if (f == NULL) {
		perror("fopen");
		assert(0);
	}

	char *line = NULL;
	size_t len = 0;
	ssize_t read;
	while ((read = getline(&line, &len, f)) > 0) {
		std::string str = line;
		if (str.length() == 1)
			continue;
		if (line[0] == '#')
			continue;

		size_t found = str.find("=");
		/* if there isn't `=', I assume it's a file name*/
		if (found == std::string::npos) {
			fprintf(stderr, "wrong format: %s\n", line);
			assert(0);
		}

		std::string value = str.substr(found + 1);
		value.erase(std::remove_if(value.begin(), value.end(), isspace),
				value.end());
		std::string key = str.substr(0, found);
		key.erase(std::remove_if(key.begin(), key.end(), isspace),
				key.end());
		bool res = configs.insert(std::pair<std::string, std::string>(key,
					value)).second;
		if (!res)
			configs[key] = value;
	}
	fclose(f);
}

config_map::config_map(const std::string &conf_file)
{
	read_config_file(conf_file, configs);
}

/**
 * All options should have the following format:
 *		key=value.
 * All options that don't have the format are ignored.
 */
void config_map::add_options(char *argv[], int argc)
{
	for (int i = 0; i < argc; i++) {
		std::string str = argv[i];

		size_t found = str.find("=");
		if (found == std::string::npos) {
			continue;
		}

		std::string value = str.substr(found + 1);
		value.erase(std::remove_if(value.begin(), value.end(), isspace),
				value.end());
		std::string key = str.substr(0, found);
		key.erase(std::remove_if(key.begin(), key.end(), isspace),
				key.end());
		bool res = configs.insert(std::pair<std::string, std::string>(key,
					value)).second;
		if (!res)
			configs[key] = value;
	}
}
<commit_msg>[SAFS]: set the default value for cache_large_write.<commit_after>/**
 * Copyright 2013 Da Zheng
 *
 * This file is part of SAFSlib.
 *
 * SAFSlib is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SAFSlib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SAFSlib.  If not, see <http://www.gnu.org/licenses/>.
 */

#include<algorithm>

#include "parameters.h"
#include "common.h"
#include "RAID_config.h"
#include "cache_config.h"

sys_parameters params;

str2int RAID_options[] = {
	{"RAID0", RAID0},
	{"RAID5", RAID5},
	{"HASH", HASH},
};

str2int cache_types[] = {
	{ "tree", TREE_CACHE } ,
	{ "associative", ASSOCIATIVE_CACHE },
	{ "hash-index", HASH_INDEX_CACHE },
	{ "cuckoo", CUCKOO_CACHE },
	{ "lru2q", LRU2Q_CACHE },
	{ "gclock", GCLOCK_CACHE },
};

sys_parameters::sys_parameters()
{
	RAID_block_size = 64;
	SA_min_cell_size = 12;
	test_hit_rate = -1;		// this disables generating the artificial hit rate.
	io_depth_per_file = 32;
	cache_type = ASSOCIATIVE_CACHE;
	cache_size = 512 * 1024 * 1024;
	RAID_mapping_option = RAID5;
	use_virt_aio = false;
	verify_content = false;
	use_flusher = false;
	cache_large_write = false;
	vaio_print_freq = 1000000;
	numa_num_process_threads = 1;
	num_nodes = 1;
}

void sys_parameters::init(const std::map<std::string, std::string> &configs)
{
	str2int_map cache_map(cache_types,
			sizeof(cache_types) / sizeof(cache_types[0]));
	str2int_map RAID_option_map(RAID_options,
			sizeof(RAID_options) / sizeof(RAID_options[0]));
	std::map<std::string, std::string>::const_iterator it;

	it = configs.find("RAID_block_size");
	if (it != configs.end()) {
		RAID_block_size = (int) str2size(it->second) / PAGE_SIZE;
	}

	it = configs.find("SA_cell_size");
	if(it != configs.end()) {
		SA_min_cell_size = atoi(it->second.c_str());
	}

	it = configs.find("io_depth");
	if(it != configs.end()) {
		io_depth_per_file = atoi(it->second.c_str());
	}

	it = configs.find("hit_percent");
	if(it != configs.end()) {
		test_hit_rate = atoi(it->second.c_str());
	}

	it = configs.find("cache_type");
	if(it != configs.end()) {
		cache_type = cache_map.map(it->second);
		if (cache_type < 0) {
			fprintf(stderr, "can't find the right cache type\n");
			exit(1);
		}
	}

	it = configs.find("cache_size");
	if(it != configs.end()) {
		cache_size = str2size(it->second);
	}

	it = configs.find("RAID_mapping");
	if (it != configs.end()) {
		RAID_mapping_option = RAID_option_map.map(it->second);
		if (RAID_mapping_option < 0) {
			fprintf(stderr, "can't find the right mapping option\n");
			exit(1);
		}
	}

	it = configs.find("virt_aio");
	if (it != configs.end())
		use_virt_aio = true;

	it = configs.find("verify_content");
	if (it != configs.end()) {
		verify_content = true;
	}

	it = configs.find("use_flusher");
	if (it != configs.end()) {
		use_flusher = true;
	}

	it = configs.find("cache_large_write");
	if (it != configs.end()) {
		cache_large_write = true;
	}

	it = configs.find("vaio_print_freq");
	if (it != configs.end()) {
		vaio_print_freq = str2size(it->second);
	}

	it = configs.find("numa_num_process_threads");
	if (it != configs.end()) {
		numa_num_process_threads = str2size(it->second);
	}

	it = configs.find("num_nodes");
	if (it != configs.end()) {
		num_nodes = str2size(it->second);
	}
}

void sys_parameters::print()
{
	std::cout << "system parameters: " << std::endl;
	std::cout << "\tRAID_block_size: " << RAID_block_size << std::endl;
	std::cout << "\tSA_cell_size: " << SA_min_cell_size << std::endl;
	std::cout << "\tio_depth:" << io_depth_per_file << std::endl;
	std::cout << "\thit_percent: " << test_hit_rate << std::endl;
	std::cout << "\tcache_type: " << cache_type << std::endl;
	std::cout << "\tcache_size: " << cache_size << std::endl;
	std::cout << "\tRAID_mapping: " << RAID_mapping_option << std::endl;
	std::cout << "\tvirt_aio: " << use_virt_aio << std::endl;
	std::cout << "\tverify_content: " << verify_content << std::endl;
	std::cout << "\tuse_flusher: " << use_flusher << std::endl;
	std::cout << "\tcache_large_write: " << cache_large_write << std::endl;
	std::cout << "\tvaio_print_freq: " << vaio_print_freq << std::endl;
	std::cout << "\tnuma_num_process_threads: " << numa_num_process_threads << std::endl;
	std::cout << "\tnum_nodes: " << num_nodes << std::endl;
}

void sys_parameters::print_help()
{
	str2int_map cache_map(cache_types,
			sizeof(cache_types) / sizeof(cache_types[0]));
	str2int_map RAID_option_map(RAID_options,
			sizeof(RAID_options) / sizeof(RAID_options[0]));

	std::cout << "system parameters: " << std::endl;
	std::cout << "\tRAID_block_size: x(k, K, m, M, g, G)" << std::endl;
	std::cout << "\tSA_cell_size: the size of a page set" << std::endl;
	std::cout << "\tio_depth: the number of pending I/O requests per file"
		<< std::endl;
	std::cout << "\thit_percent: the artificial cache hit rate (%)" << std::endl;
	cache_map.print("\tcache_type: ");
	std::cout << "\tcache_size: x(k, K, m, M, g, G)" << std::endl;
	RAID_option_map.print("\tRAID_mapping: ");
	std::cout << "\tvirt_aio: enable virtual AIO for debugging and performance evaluation"
		<< std::endl;
	std::cout << "\tverify_content: verify data for testing" << std::endl;
	std::cout << "\tuse_flusher: use flusher in the page cache" << std::endl;
	std::cout << "\tcache_large_write: enable large write in the page cache."
		<< std::endl;
	std::cout << "\tvaio_print_freq: how frequently a virtual SSD print stat info (in us)"
		<< std::endl;
	std::cout << "\tnuma_num_process_threads: the number of request processing threads per node in part_global_cached_io"
		<< std::endl;
	std::cout << "\tnum_nodes: the number of NUMA nodes the test program should run"
		<< std::endl;
}

static void read_config_file(const std::string &conf_file,
		std::map<std::string, std::string> &configs)
{
	FILE *f = fopen(conf_file.c_str(), "r");
	if (f == NULL) {
		perror("fopen");
		assert(0);
	}

	char *line = NULL;
	size_t len = 0;
	ssize_t read;
	while ((read = getline(&line, &len, f)) > 0) {
		std::string str = line;
		if (str.length() == 1)
			continue;
		if (line[0] == '#')
			continue;

		size_t found = str.find("=");
		/* if there isn't `=', I assume it's a file name*/
		if (found == std::string::npos) {
			fprintf(stderr, "wrong format: %s\n", line);
			assert(0);
		}

		std::string value = str.substr(found + 1);
		value.erase(std::remove_if(value.begin(), value.end(), isspace),
				value.end());
		std::string key = str.substr(0, found);
		key.erase(std::remove_if(key.begin(), key.end(), isspace),
				key.end());
		bool res = configs.insert(std::pair<std::string, std::string>(key,
					value)).second;
		if (!res)
			configs[key] = value;
	}
	fclose(f);
}

config_map::config_map(const std::string &conf_file)
{
	read_config_file(conf_file, configs);
}

/**
 * All options should have the following format:
 *		key=value.
 * All options that don't have the format are ignored.
 */
void config_map::add_options(char *argv[], int argc)
{
	for (int i = 0; i < argc; i++) {
		std::string str = argv[i];

		size_t found = str.find("=");
		if (found == std::string::npos) {
			continue;
		}

		std::string value = str.substr(found + 1);
		value.erase(std::remove_if(value.begin(), value.end(), isspace),
				value.end());
		std::string key = str.substr(0, found);
		key.erase(std::remove_if(key.begin(), key.end(), isspace),
				key.end());
		bool res = configs.insert(std::pair<std::string, std::string>(key,
					value)).second;
		if (!res)
			configs[key] = value;
	}
}
<|endoftext|>


<commit_before><commit_msg>Use OUStringBuffer instead of rtl_uString in EditDoc::GetText<commit_after><|endoftext|>


<commit_before>#include "Sphere.h"

Intersection Sphere::intersect(Ray ray) {
   Vector deltap = ray.origin - center;
   double a = ray.direction.dot(ray.direction);
   double b = deltap.dot(ray.direction) * 2;
   double c = deltap.dot(deltap) - (radius * radius);

   double disc = b * b - 4 * a * c;
   if (disc < 0) {
      return Intersection(false); // No intersection.
   }

   disc = sqrt(disc);

   double q;
   if (b < 0) {
      q = (-b - disc) * 0.5;
   } else {
      q = (-b + disc) * 0.5;
   }

   double r1 = q / a;
   double r2 = c / q;

   if (r1 > r2) {
      double tmp = r1;
      r1 = r2;
      r2 = tmp;
   }

   double distance = r1;
   if (distance < 0) {
      distance = r2;
   }

   if (distance < 0) {
      return Intersection(false); // No intersection.
   }

   Vector point = ray.origin + (ray.direction * distance);
   Vector normal = (point - center).normalize();

   return Intersection(point, normal, Color(normal.x, normal.y, normal.z), this);
}
<commit_msg>Correctly display sphere color normals<commit_after>#include "Sphere.h"

Intersection Sphere::intersect(Ray ray) {
   Vector deltap = ray.origin - center;
   double a = ray.direction.dot(ray.direction);
   double b = deltap.dot(ray.direction) * 2;
   double c = deltap.dot(deltap) - (radius * radius);

   double disc = b * b - 4 * a * c;
   if (disc < 0) {
      return Intersection(false); // No intersection.
   }

   disc = sqrt(disc);

   double q;
   if (b < 0) {
      q = (-b - disc) * 0.5;
   } else {
      q = (-b + disc) * 0.5;
   }

   double r1 = q / a;
   double r2 = c / q;

   if (r1 > r2) {
      double tmp = r1;
      r1 = r2;
      r2 = tmp;
   }

   double distance = r1;
   if (distance < 0) {
      distance = r2;
   }

   if (distance < 0) {
      return Intersection(false); // No intersection.
   }

   Vector point = ray.origin + (ray.direction * distance);
   Vector normal = (point - center).normalize();

   return Intersection(point, normal, Color(fabs(normal.x), fabs(normal.y), fabs(normal.z)), this);
}
<|endoftext|>


<commit_before>/*
	A = U S t(V)
	t(U) U = I
	t(V) V = I
*/
#include <cybozu/test.hpp>
#define CYBOZU_NLP_SVD_USE_RANDOM
#include <cybozu/nlp/svd.hpp>
#include <cybozu/file.hpp>

const double defaultEPS = 1e-5;

template<class Matrix>
void testSame(const Matrix& A, const Matrix& B)
{
	double x = (A - B).norm();
	CYBOZU_TEST_NEAR(x, 0, defaultEPS);
}

template<class Matrix, class Vector>
void testUSV(const Matrix& U, const Vector& S, const Matrix& V, const Matrix& A)
{
	const Matrix B = U * S.asDiagonal() * V.transpose();
	testSame(A, B);
}
/*
	verity t(A) A = I
*/
template<class Matrix>
void testUnitary(const Matrix& A)
{
	Matrix B = A.transpose() * A;
	Matrix I;
	I.setIdentity(B.cols(), B.cols());
	testSame(B, I);
}

template<class Matrix>
void testSVD(const Matrix& A, int m, int n, int r)
{
	Matrix U, V;
	Eigen::VectorXd S;

	cybozu::nlp::ComputeSVD(U, S, V, A, r);

	CYBOZU_TEST_EQUAL(U.rows(), m);
	CYBOZU_TEST_EQUAL(U.cols(), r);
	CYBOZU_TEST_EQUAL(S.rows(), r);
	CYBOZU_TEST_EQUAL(V.rows(), n);
	CYBOZU_TEST_EQUAL(V.cols(), r);

	testUnitary(U);
	testUnitary(V);

	testUSV(U, S, V, A);
}

CYBOZU_TEST_AUTO(rank2)
{
	const int m = 4;
	const int n = 3;
	const int r = 2;
	Eigen::MatrixXd A(m, n);
	A << 1, 2, 3, 4,
	     5, 6, 7, 8,
	     9, 10, 11, 12;

	testSVD(A, m, n, r);
}

CYBOZU_TEST_AUTO(rank3)
{
	const int m = 4;
	const int n = 3;
	const int r = 3;
	Eigen::MatrixXd A(m, n);
	A << 1, 2, 3, 4,
	     5, 6, 7, 8,
	     9, 10, 11, 13;

	testSVD(A, m, n, r);
}

CYBOZU_TEST_AUTO(file)
{
	const int m = 3;
	const int n = 4;
	const std::string testName = cybozu::file::GetExePath() + "svd_test.txt";
	Eigen::MatrixXd A(m, n);
	cybozu::nlp::svd::InitRandomMatrix(A);
	CYBOZU_TEST_ASSERT(cybozu::nlp::svd::SaveMatrix(testName, A));
	Eigen::MatrixXd B;
	CYBOZU_TEST_ASSERT(cybozu::nlp::svd::LoadMatrix(B, testName));
	testSame(A, B);
}

CYBOZU_TEST_AUTO(file2)
{
	std::string path = cybozu::file::GetExePath() + "../sample/data/svd/";
	Eigen::MatrixXd A;
	Eigen::MatrixXd B;
	CYBOZU_TEST_ASSERT(cybozu::nlp::svd::LoadMatrix(A, path + "test1"));
	CYBOZU_TEST_ASSERT(cybozu::nlp::svd::LoadMatrix(B, path + "test2"));
	testSame(A, B);
}

CYBOZU_TEST_AUTO(random1)
{
	const int m = 10;
	const int n = 30;
	const int r = 10;
	Eigen::MatrixXd A(m, n);
	cybozu::nlp::svd::InitRandomMatrix(A);
	testSVD(A, m, n, r);
}

CYBOZU_TEST_AUTO(random2)
{
	const int m = 10;
	const int n = 30;
	const int r = 8;
	Eigen::MatrixXd A(m, n), U(m, r), V(n, r), U2, V2;
	Eigen::VectorXd S(r), S2;
	cybozu::nlp::svd::InitRandomMatrix(U);
	cybozu::nlp::svd::OrthonormalizeMatrix(U);
	cybozu::nlp::svd::InitRandomMatrix(V);
	cybozu::nlp::svd::OrthonormalizeMatrix(V);
	// descending order
	for (int i = 0; i < r; i++) {
		S(i) = r - i;
	}
	A = U * S.asDiagonal() * V.transpose();
	cybozu::nlp::ComputeSVD(U2, S2, V2, A, r);
	testUnitary(U2);
	testUnitary(V2);
	testSame(S, S2);
	testUSV(U2, S2, V2, A);
}

CYBOZU_TEST_AUTO(multiUnitMatrix)
{
	int row = 13;
	int col = 15;
	int r = 4;
	Eigen::MatrixXd R(col, r);
	cybozu::nlp::svd::InitUnitMatrix(R);
	Eigen::MatrixXd A(row, col), B;
	cybozu::nlp::svd::InitRandomMatrix(A);
	cybozu::nlp::svd::CompressCol(B, A, r);
	double diff = ((A * R) - B).norm();
	CYBOZU_TEST_NEAR(diff, 0, defaultEPS);
}

CYBOZU_TEST_AUTO(multiUnitMatrix2)
{
	int row = 13;
	int col = 15;
	int r = 5;
	Eigen::MatrixXd R(col, r);
	cybozu::nlp::svd::InitUnitMatrix(R);
	Eigen::MatrixXd A(row, col), B;
	cybozu::nlp::svd::InitRandomMatrix(A);
	cybozu::nlp::svd::CompressCol(B, A, r);
	double diff = ((A * R) - B).norm();
	CYBOZU_TEST_NEAR(diff, 0, defaultEPS);
}

<commit_msg>add test for innerproduct of row vector of A<commit_after>/*
	A = U S t(V)
	t(U) U = I
	t(V) V = I
*/
#include <cybozu/test.hpp>
#define CYBOZU_NLP_SVD_USE_RANDOM
#include <cybozu/nlp/svd.hpp>
#include <cybozu/file.hpp>

const double defaultEPS = 1e-5;

template<class Matrix>
void testSame(const Matrix& A, const Matrix& B)
{
	double x = (A - B).norm();
	CYBOZU_TEST_NEAR(x, 0, defaultEPS);
}

template<class Matrix, class Vector>
void testUSV(const Matrix& U, const Vector& S, const Matrix& V, const Matrix& A)
{
	const Matrix B = U * S.asDiagonal() * V.transpose();
	testSame(A, B);
}
/*
	verity t(A) A = I
*/
template<class Matrix>
void testUnitary(const Matrix& A)
{
	Matrix B = A.transpose() * A;
	Matrix I;
	I.setIdentity(B.cols(), B.cols());
	testSame(B, I);
}

template<class Matrix>
double innerProductRow(const Matrix& A, int s, int t)
{
	double ret = 0;
	for (int i = 0; i < A.cols(); i++) {
		ret += A(s, i) * A(t, i);
	}
	return ret;
}

template<class Matrix, class Vector>
double innerProductUS(const Matrix& U, const Vector& S, int s, int t)
{
	double ret = 0;
	for (int i = 0; i < U.cols(); i++) {
		double v = S(i);
		ret += v * v * U(s, i) * U(t, i);
	}
	return ret;
}

/*
	A = U S trans(V)
	m = A.rows()
	A = trans(a_1, ..., a_m), U = trans(u_1, ..., u_m)
	product(a_s, a_t) = sum_{i=0}^{U.cols()} S(i)^2 * (u_s)_i (u_t)_i
*/
template<class Matrix, class Vector>
void testProduct(const Matrix& A, const Matrix& U, const Vector& S)
{
	for (int s = 0; s < U.rows(); s++) {
		for (int t = s; t < U.rows(); t++) {
			double x = innerProductRow(A, s, t);
			double y = innerProductUS(U, S, s, t);
			CYBOZU_TEST_NEAR(x, y, defaultEPS);
		}
	}
}

template<class Matrix>
void testSVD(const Matrix& A, int m, int n, int r)
{
	Matrix U, V;
	Eigen::VectorXd S;

	cybozu::nlp::ComputeSVD(U, S, V, A, r);

	CYBOZU_TEST_EQUAL(U.rows(), m);
	CYBOZU_TEST_EQUAL(U.cols(), r);
	CYBOZU_TEST_EQUAL(S.rows(), r);
	CYBOZU_TEST_EQUAL(V.rows(), n);
	CYBOZU_TEST_EQUAL(V.cols(), r);

	testUnitary(U);
	testUnitary(V);

	testUSV(U, S, V, A);
	testProduct(A, U, S);
}

CYBOZU_TEST_AUTO(rank2)
{
	const int m = 4;
	const int n = 3;
	const int r = 2;
	Eigen::MatrixXd A(m, n);
	A << 1, 2, 3, 4,
	     5, 6, 7, 8,
	     9, 10, 11, 12;

	testSVD(A, m, n, r);
}

CYBOZU_TEST_AUTO(rank3)
{
	const int m = 4;
	const int n = 3;
	const int r = 3;
	Eigen::MatrixXd A(m, n);
	A << 1, 2, 3, 4,
	     5, 6, 7, 8,
	     9, 10, 11, 13;

	testSVD(A, m, n, r);
}

CYBOZU_TEST_AUTO(file)
{
	const int m = 3;
	const int n = 4;
	const std::string testName = cybozu::file::GetExePath() + "svd_test.txt";
	Eigen::MatrixXd A(m, n);
	cybozu::nlp::svd::InitRandomMatrix(A);
	CYBOZU_TEST_ASSERT(cybozu::nlp::svd::SaveMatrix(testName, A));
	Eigen::MatrixXd B;
	CYBOZU_TEST_ASSERT(cybozu::nlp::svd::LoadMatrix(B, testName));
	testSame(A, B);
}

CYBOZU_TEST_AUTO(file2)
{
	std::string path = cybozu::file::GetExePath() + "../sample/data/svd/";
	Eigen::MatrixXd A;
	Eigen::MatrixXd B;
	CYBOZU_TEST_ASSERT(cybozu::nlp::svd::LoadMatrix(A, path + "test1"));
	CYBOZU_TEST_ASSERT(cybozu::nlp::svd::LoadMatrix(B, path + "test2"));
	testSame(A, B);
}

CYBOZU_TEST_AUTO(random1)
{
	const int m = 10;
	const int n = 30;
	const int r = 10;
	Eigen::MatrixXd A(m, n);
	cybozu::nlp::svd::InitRandomMatrix(A);
	testSVD(A, m, n, r);
}

CYBOZU_TEST_AUTO(random2)
{
	const int m = 10;
	const int n = 30;
	const int r = 8;
	Eigen::MatrixXd A(m, n), U(m, r), V(n, r), U2, V2;
	Eigen::VectorXd S(r), S2;
	cybozu::nlp::svd::InitRandomMatrix(U);
	cybozu::nlp::svd::OrthonormalizeMatrix(U);
	cybozu::nlp::svd::InitRandomMatrix(V);
	cybozu::nlp::svd::OrthonormalizeMatrix(V);
	// descending order
	for (int i = 0; i < r; i++) {
		S(i) = r - i;
	}
	A = U * S.asDiagonal() * V.transpose();
	cybozu::nlp::ComputeSVD(U2, S2, V2, A, r);
	testUnitary(U2);
	testUnitary(V2);
	testSame(S, S2);
	testUSV(U2, S2, V2, A);
}

CYBOZU_TEST_AUTO(multiUnitMatrix)
{
	int row = 13;
	int col = 15;
	int r = 4;
	Eigen::MatrixXd R(col, r);
	cybozu::nlp::svd::InitUnitMatrix(R);
	Eigen::MatrixXd A(row, col), B;
	cybozu::nlp::svd::InitRandomMatrix(A);
	cybozu::nlp::svd::CompressCol(B, A, r);
	double diff = ((A * R) - B).norm();
	CYBOZU_TEST_NEAR(diff, 0, defaultEPS);
}

CYBOZU_TEST_AUTO(multiUnitMatrix2)
{
	int row = 13;
	int col = 15;
	int r = 5;
	Eigen::MatrixXd R(col, r);
	cybozu::nlp::svd::InitUnitMatrix(R);
	Eigen::MatrixXd A(row, col), B;
	cybozu::nlp::svd::InitRandomMatrix(A);
	cybozu::nlp::svd::CompressCol(B, A, r);
	double diff = ((A * R) - B).norm();
	CYBOZU_TEST_NEAR(diff, 0, defaultEPS);
}

<|endoftext|>


<commit_before>#include "Sprite.h"

Sprite::Sprite()
	: center(0.f, 0.f, 0.f)
	, position(0.f, 0.f, 0.f)
	, texture(nullptr)
{

}

Sprite::Sprite(std::string path)
	: center(0.f,0.f,0.f)
	, position(0.f,0.f, 0.f)
{
	SetSprite(path);
}

Sprite::Sprite(std::string path, float x, float y, float z)
	: center(0.f, 0.f, 0.f)
	, position(x, y, z)
{
<<<<<<< HEAD
	HR(D3DXCreateTextureFromFile(gD3DDevice, path.c_str(), &texture));
=======
	SetSprite(path);
>>>>>>> f58ec29ffb4937ccfe95dad2b25e6d1525093741
}

Sprite::~Sprite()
{

}

void Sprite::Draw()
{
	if (texture)
	{
		HR(gD3DApp->GetSpriteBatch()->Draw(texture, 0, &center, &position, D3DCOLOR_XRGB(255, 255, 255)));
		HR(gD3DApp->GetSpriteBatch()->Flush());
	}
}
<commit_msg>Conflicts resolving<commit_after>#include "Sprite.h"

Sprite::Sprite()
	: center(0.f, 0.f, 0.f)
	, position(0.f, 0.f, 0.f)
	, texture(nullptr)
{

}

Sprite::Sprite(std::string path)
	: center(0.f,0.f,0.f)
	, position(0.f,0.f, 0.f)
{
	SetSprite(path);
}

Sprite::Sprite(std::string path, float x, float y, float z)
	: center(0.f, 0.f, 0.f)
	, position(x, y, z)
{
	SetSprite(path);
}

Sprite::~Sprite()
{
}

void Sprite::Draw()
{
	if (texture)
	{
		HR(gD3DApp->GetSpriteBatch()->Draw(texture, 0, &center, &position, D3DCOLOR_XRGB(255, 255, 255)));
		HR(gD3DApp->GetSpriteBatch()->Flush());
	}
}
<|endoftext|>


<commit_before><commit_msg>Fix `std::cerr` output of some `Brain` callback functions.<commit_after><|endoftext|>


<commit_before>#include "sem/core/pcl/cloud_2cloud_.h"

using namespace pcl;

typedef boost::shared_ptr<pcl::PointCloud<PointXYZ > > CloudXYZPtr;
typedef boost::shared_ptr<pcl::PointCloud<PointNormal > > CloudPointNrmlPtr;
typedef boost::shared_ptr<pcl::PointCloud<Normal > > CloudNrmlPtr;

namespace sem {

template <class TPointSrc, class TPointDst>
void CloudTruncate(CloudPointNrmlPtr &src, CloudXYZPtr &dst)
{
    dst.reset(new PointCloud<TPointDst>(src->width, src->height));

    size_t nb_floats_src = PCLPointTraits_<TPointSrc>::NbFloats();
    size_t nb_floats_dst = PCLPointTraits_<TPointDst>::NbFloats();

    size_t step_size = sizeof(float)*std::min(nb_floats_src, nb_floats_dst);

    typename pcl::PointCloud<TPointSrc>::iterator itr_src = src->begin();
    typename pcl::PointCloud<TPointDst>::iterator itr_dst = dst->begin();
    while(itr_src != src->end()) {
        \
        memcpy(&(*itr_src), &(*itr_dst), step_size); // dangerous?

        ++itr_src;
        ++itr_dst;
    }
}

/**
 * @brief template specialization for converting point cloud of pcl::PointNormal points to cloud of pcl::PointXYZ points
 *
 * Involves a deep copy of point data.
 *
 * @todo: make this the template implementation instead of throwing sem::ExceptionNotImpl?
 *
 */
template<>
void Cloud_2Cloud_<PointNormal, PointXYZ>::Convert(CloudPointNrmlPtr &src, CloudXYZPtr &dst)
{
    CloudTruncate<PointNormal, PointXYZ>(src, dst);
}

/**
 * @brief The Normal data is offsetted inside the PointNormal data
 */
template<>
void Cloud_2Cloud_<PointNormal, Normal>::Convert(CloudPointNrmlPtr &src, CloudNrmlPtr &dst)
{
    dst.reset(new PointCloud<Normal>(src->width, src->height));

     size_t nb_floats_src = PCLPointTraits_<PointNormal>::NbFloats();
     size_t nb_floats_dst = PCLPointTraits_<Normal>::NbFloats();

     size_t step_size = sizeof(float)*nb_floats_dst;
     size_t src_float_offset = nb_floats_src-nb_floats_dst;

     typename pcl::PointCloud<PointNormal>::iterator itr_src = src->begin();
     typename pcl::PointCloud<Normal>::iterator itr_dst = dst->begin();
     while(itr_src != src->end()) {

         float* pt_src_data_ptr = reinterpret_cast<float*>(&(*itr_src))+src_float_offset;
         memcpy(pt_src_data_ptr, &(*itr_dst), step_size); // dangerous?

         ++itr_src;
         ++itr_dst;
     }
}

}
<commit_msg>add define guard for when PCL support is missing<commit_after>#include "sem/core/pcl/cloud_2cloud_.h"

#ifdef __WITH_PCL // conversions from one point cloud to another require PCL support

using namespace pcl;

typedef boost::shared_ptr<pcl::PointCloud<PointXYZ > > CloudXYZPtr;
typedef boost::shared_ptr<pcl::PointCloud<PointNormal > > CloudPointNrmlPtr;
typedef boost::shared_ptr<pcl::PointCloud<Normal > > CloudNrmlPtr;

namespace sem {

template <class TPointSrc, class TPointDst>
void CloudTruncate(CloudPointNrmlPtr &src, CloudXYZPtr &dst)
{
    dst.reset(new PointCloud<TPointDst>(src->width, src->height));

    size_t nb_floats_src = PCLPointTraits_<TPointSrc>::NbFloats();
    size_t nb_floats_dst = PCLPointTraits_<TPointDst>::NbFloats();

    size_t step_size = sizeof(float)*std::min(nb_floats_src, nb_floats_dst);

    typename pcl::PointCloud<TPointSrc>::iterator itr_src = src->begin();
    typename pcl::PointCloud<TPointDst>::iterator itr_dst = dst->begin();
    while(itr_src != src->end()) {
        \
        memcpy(&(*itr_src), &(*itr_dst), step_size); // dangerous?

        ++itr_src;
        ++itr_dst;
    }
}

/**
 * @brief template specialization for converting point cloud of pcl::PointNormal points to cloud of pcl::PointXYZ points
 *
 * Involves a deep copy of point data.
 *
 * @todo: make this the template implementation instead of throwing sem::ExceptionNotImpl?
 *
 */
template<>
void Cloud_2Cloud_<PointNormal, PointXYZ>::Convert(CloudPointNrmlPtr &src, CloudXYZPtr &dst)
{
    CloudTruncate<PointNormal, PointXYZ>(src, dst);
}

/**
 * @brief The Normal data is offsetted inside the PointNormal data
 */
template<>
void Cloud_2Cloud_<PointNormal, Normal>::Convert(CloudPointNrmlPtr &src, CloudNrmlPtr &dst)
{
    dst.reset(new PointCloud<Normal>(src->width, src->height));

     size_t nb_floats_src = PCLPointTraits_<PointNormal>::NbFloats();
     size_t nb_floats_dst = PCLPointTraits_<Normal>::NbFloats();

     size_t step_size = sizeof(float)*nb_floats_dst;
     size_t src_float_offset = nb_floats_src-nb_floats_dst;

     typename pcl::PointCloud<PointNormal>::iterator itr_src = src->begin();
     typename pcl::PointCloud<Normal>::iterator itr_dst = dst->begin();
     while(itr_src != src->end()) {

         float* pt_src_data_ptr = reinterpret_cast<float*>(&(*itr_src))+src_float_offset;
         memcpy(pt_src_data_ptr, &(*itr_dst), step_size); // dangerous?

         ++itr_src;
         ++itr_dst;
     }
}

}

#endif // __WITH_PCL
<|endoftext|>


<commit_before><commit_msg>tdf#85496: editeng: suppress all duplicate attributes during export<commit_after><|endoftext|>


<commit_before><commit_msg>coverity#1242632 Untrusted loop bound<commit_after><|endoftext|>


<commit_before>#include <USB.h>

extern void dumpPacket(const uint8_t *data, uint32_t l);

#define KVA_TO_PA(v)  ((v) & 0x1fffffff)
#define PA_TO_KVA0(pa)  ((pa) | 0x80000000)  // cachable
#define PA_TO_KVA1(pa)  ((pa) | 0xa000000

/*-------------- USB FS ---------------*/

USBFS *USBFS::_this;

bool USBFS::enableUSB() {
    U1BDTP1 = (uint8_t)(KVA_TO_PA((uint32_t)&_bufferDescriptorTable[0][0]) >> 8);
    U1BDTP2 = (uint8_t)(KVA_TO_PA((uint32_t)&_bufferDescriptorTable[0][0]) >> 16);
    U1BDTP3 = (uint8_t)(KVA_TO_PA((uint32_t)&_bufferDescriptorTable[0][0]) >> 24);

    // enable usb device mode
    U1CONbits.SOFEN = 1;
    U1OTGCONbits.DPPULUP = 1;
	U1OTGCONbits.OTGEN = 1;
	U1IR = 0xFF;
	U1IEbits.URSTIE = 1;
	U1EIE = 0xFF;

	setIntVector(_USB_1_VECTOR, _usbInterrupt);
	setIntPriority(_USB_1_VECTOR, 5, 0);
	clearIntFlag(_USB_IRQ);
	setIntEnable(_USB_IRQ);

	U1SOFbits.CNT = 74;

	U1PWRCbits.USBPWR = 1;

    addEndpoint(0, EP_IN, EP_CTL, 64, _ctlRxA, _ctlRxB);
    addEndpoint(0, EP_OUT, EP_CTL, 64, _ctlTxA, _ctlTxB);
	return true;
}

bool USBFS::disableUSB() {
	U1PWRCbits.USBPWR = 0;
	return true;
}

bool USBFS::addEndpoint(uint8_t id, uint8_t direction, uint8_t type, uint8_t size, uint8_t *a, uint8_t *b) {
	if (id > 15) return false;
    _endpointBuffers[id].data = 0x40;
    _endpointBuffers[id].size = size;
	if (direction == EP_IN) {
        _endpointBuffers[id].rx[0] = a;
        _endpointBuffers[id].rx[1] = b;
		_bufferDescriptorTable[id][0].buffer = (uint8_t *)KVA_TO_PA((uint32_t)_endpointBuffers[id].rx[0]);
		_bufferDescriptorTable[id][0].flags = (_endpointBuffers[id].size << 16) | 0x80;
		_bufferDescriptorTable[id][1].buffer = (uint8_t *)KVA_TO_PA((uint32_t)_endpointBuffers[id].rx[1]);
		_bufferDescriptorTable[id][1].flags = (_endpointBuffers[id].size << 16) | 0x80;
		switch (id) {
			case 0: U1EP0bits.EPRXEN = 1; break;
			case 1: U1EP1bits.EPRXEN = 1; break;
			case 2: U1EP2bits.EPRXEN = 1; break;
			case 3: U1EP3bits.EPRXEN = 1; break;
			case 4: U1EP4bits.EPRXEN = 1; break;
			case 5: U1EP5bits.EPRXEN = 1; break;
			case 6: U1EP6bits.EPRXEN = 1; break;
			case 7: U1EP7bits.EPRXEN = 1; break;
			case 8: U1EP8bits.EPRXEN = 1; break;
			case 9: U1EP9bits.EPRXEN = 1; break;
			case 10: U1EP10bits.EPRXEN = 1; break;
			case 11: U1EP11bits.EPRXEN = 1; break;
			case 12: U1EP12bits.EPRXEN = 1; break;
			case 13: U1EP13bits.EPRXEN = 1; break;
			case 14: U1EP14bits.EPRXEN = 1; break;
			case 15: U1EP15bits.EPRXEN = 1; break;
		}
	} else {
        _endpointBuffers[id].tx[0] = a;
        _endpointBuffers[id].tx[1] = b;
		_bufferDescriptorTable[id][2].buffer = (uint8_t *)KVA_TO_PA((uint32_t)_endpointBuffers[id].tx[0]);
		_bufferDescriptorTable[id][2].flags = 0;
		_bufferDescriptorTable[id][3].buffer = (uint8_t *)KVA_TO_PA((uint32_t)_endpointBuffers[id].tx[1]);
		_bufferDescriptorTable[id][3].flags = 0;
		switch (id) {
			case 0: U1EP0bits.EPTXEN = 1; break;
			case 1: U1EP1bits.EPTXEN = 1; break;
			case 2: U1EP2bits.EPTXEN = 1; break;
			case 3: U1EP3bits.EPTXEN = 1; break;
			case 4: U1EP4bits.EPTXEN = 1; break;
			case 5: U1EP5bits.EPTXEN = 1; break;
			case 6: U1EP6bits.EPTXEN = 1; break;
			case 7: U1EP7bits.EPTXEN = 1; break;
			case 8: U1EP8bits.EPTXEN = 1; break;
			case 9: U1EP9bits.EPTXEN = 1; break;
			case 10: U1EP10bits.EPTXEN = 1; break;
			case 11: U1EP11bits.EPTXEN = 1; break;
			case 12: U1EP12bits.EPTXEN = 1; break;
			case 13: U1EP13bits.EPTXEN = 1; break;
			case 14: U1EP14bits.EPTXEN = 1; break;
			case 15: U1EP15bits.EPTXEN = 1; break;
		}
		_enabledEndpoints |= (1 << (id + 16));
	}

	switch (id) {
		case 0: U1EP0bits.EPHSHK = 1; break;
		case 1: U1EP1bits.EPHSHK = 1; break;
		case 2: U1EP2bits.EPHSHK = 1; break;
		case 3: U1EP3bits.EPHSHK = 1; break;
		case 4: U1EP4bits.EPHSHK = 1; break;
		case 5: U1EP5bits.EPHSHK = 1; break;
		case 6: U1EP6bits.EPHSHK = 1; break;
		case 7: U1EP7bits.EPHSHK = 1; break;
		case 8: U1EP8bits.EPHSHK = 1; break;
		case 9: U1EP9bits.EPHSHK = 1; break;
		case 10: U1EP10bits.EPHSHK = 1; break;
		case 11: U1EP11bits.EPHSHK = 1; break;
		case 12: U1EP12bits.EPHSHK = 1; break;
		case 13: U1EP13bits.EPHSHK = 1; break;
		case 14: U1EP14bits.EPHSHK = 1; break;
		case 15: U1EP15bits.EPHSHK = 1; break;
	}

	return true;
}

bool USBFS::canEnqueuePacket(uint8_t ep) {
    uint8_t buffer = _endpointBuffers[ep].txAB;
    uint8_t bdt_entry = buffer ? 3 : 2;
    if ((_bufferDescriptorTable[ep][bdt_entry].flags & 0x80) == 0) return true;
    return false;
}

bool USBFS::enqueuePacket(uint8_t ep, const uint8_t *data, uint32_t len) {
	bool sent = false;

    uint8_t buffer = _endpointBuffers[ep].txAB;
    uint8_t bdt_entry = buffer ? 3 : 2;

    while (!sent) {
        if ((_bufferDescriptorTable[ep][bdt_entry].flags & 0x80) == 0) {
            if (len > 0) memcpy(_endpointBuffers[ep].tx[buffer], data, min(len, _endpointBuffers[ep].size));
            _bufferDescriptorTable[ep][bdt_entry].flags = (len << 16) | 0x00 | _endpointBuffers[ep].data;
            sent = true;
            _bufferDescriptorTable[ep][bdt_entry].flags |= 0x80;
        }
	}

    _endpointBuffers[ep].txAB = 1 - _endpointBuffers[ep].txAB;
	_endpointBuffers[ep].data = _endpointBuffers[ep].data ? 0 : 0x40;

	return true;
}

bool USBFS::sendBuffer(uint8_t ep, const uint8_t *data, uint32_t len) {

    while (_endpointBuffers[ep].buffer != NULL) {
        if (canEnqueuePacket(ep)) {
            if (_endpointBuffers[ep].length > 0) {
                uint32_t toSend = min(_endpointBuffers[ep].size, _endpointBuffers[ep].length);
                enqueuePacket(ep, _endpointBuffers[ep].bufferPtr, toSend);
                _endpointBuffers[ep].length -= toSend;
                _endpointBuffers[ep].bufferPtr += toSend;
            } else {
                if (_endpointBuffers[ep].buffer != NULL) {
                    free(_endpointBuffers[ep].buffer);
                    _endpointBuffers[ep].buffer = NULL;
                }
            }

        }
    }

    _endpointBuffers[ep].length = len;
    _endpointBuffers[ep].buffer = (uint8_t *)malloc(len);
    if (!_endpointBuffers[ep].buffer) {
        return false;
    }
    memcpy(_endpointBuffers[ep].buffer, data, len);
    _endpointBuffers[ep].bufferPtr = _endpointBuffers[ep].buffer;

    while (!canEnqueuePacket(ep));

    uint32_t toSend = min(_endpointBuffers[ep].size, _endpointBuffers[ep].length);
    enqueuePacket(ep, _endpointBuffers[ep].bufferPtr, toSend);
    _endpointBuffers[ep].length -= toSend;
    _endpointBuffers[ep].bufferPtr += toSend;

    return true;
}

void USBFS::handleInterrupt() {
    uint32_t toSend;

	if (U1IRbits.TRNIF) {

		uint8_t ep = U1STATbits.ENDPT;
		uint8_t bdt_slot = U1STATbits.PPBI | (U1STATbits.DIR << 1);

		uint8_t pid = (_bufferDescriptorTable[ep][bdt_slot].flags >> 2) & 0x0F;

		switch (pid) {
			case 0x01: // OUT
                if (_manager) _manager->onOutPacket(ep, _endpointBuffers[ep].rx[U1STATbits.PPBI], _bufferDescriptorTable[ep][bdt_slot].flags >> 16);
     //           _endpointBuffers[ep].data = _endpointBuffers[ep].data ? 0 : 0x40;
				_bufferDescriptorTable[ep][bdt_slot].flags = (_endpointBuffers[ep].size << 16) | 0x80 | _endpointBuffers[ep].data;
				break;
			case 0x09: // IN
                if (_endpointBuffers[ep].length > 0) {
                    toSend = min(_endpointBuffers[ep].size, _endpointBuffers[ep].length);
                    enqueuePacket(ep, _endpointBuffers[ep].bufferPtr, toSend);
                    _endpointBuffers[ep].length -= toSend;
                    _endpointBuffers[ep].bufferPtr += toSend;
                } else {
                    if (_endpointBuffers[ep].buffer != NULL) {
                        free(_endpointBuffers[ep].buffer);
                        _endpointBuffers[ep].buffer = NULL;
                    }
                }

                if (_manager) _manager->onInPacket(ep, _endpointBuffers[ep].rx[U1STATbits.PPBI], _bufferDescriptorTable[ep][bdt_slot].flags >> 16);
				break;
			case 0x0d: // SETUP
				_endpointBuffers[ep].data = 0x40;
                if (_manager) _manager->onSetupPacket(ep, _endpointBuffers[ep].rx[U1STATbits.PPBI], _bufferDescriptorTable[ep][bdt_slot].flags >> 16);
				_bufferDescriptorTable[ep][bdt_slot].flags = (_endpointBuffers[ep].size << 16) | 0x80;
				break;
			default:
				break;
		}

		U1CONbits.TOKBUSY=0;
	}
	if (U1IRbits.URSTIF) {
		U1IEbits.IDLEIE = 1;
		U1IEbits.TRNIE = 1;
		U1ADDR = 0;
		U1CONbits.PPBRST = 1;
		U1CONbits.PPBRST = 0;
		for (int i  = 0; i < 16; i++) {
			_endpointBuffers[i].txAB = 0;
            _endpointBuffers[i].data = 0x00;
		}
	}
	if (U1IRbits.IDLEIF) {
		U1IEbits.IDLEIE = 0;
		U1IEbits.RESUMEIE = 1;
	}
	if (U1IRbits.RESUMEIF) {
		U1IEbits.IDLEIE = 1;
		U1IEbits.RESUMEIE = 0;
	}
	if (U1EIR) {

	}
	U1EIR = 0xFF;
	U1IR = 0xFF;
	clearIntFlag(_USB_IRQ);
}

bool USBFS::setAddress(uint8_t address) {
	U1ADDR = address;
	return true;
}

<commit_msg>Added timeout to sendBuffer<commit_after>#include <USB.h>

extern void dumpPacket(const uint8_t *data, uint32_t l);

#define KVA_TO_PA(v)  ((v) & 0x1fffffff)
#define PA_TO_KVA0(pa)  ((pa) | 0x80000000)  // cachable
#define PA_TO_KVA1(pa)  ((pa) | 0xa000000

/*-------------- USB FS ---------------*/

USBFS *USBFS::_this;

bool USBFS::enableUSB() {
    U1BDTP1 = (uint8_t)(KVA_TO_PA((uint32_t)&_bufferDescriptorTable[0][0]) >> 8);
    U1BDTP2 = (uint8_t)(KVA_TO_PA((uint32_t)&_bufferDescriptorTable[0][0]) >> 16);
    U1BDTP3 = (uint8_t)(KVA_TO_PA((uint32_t)&_bufferDescriptorTable[0][0]) >> 24);

    // enable usb device mode
    U1CONbits.SOFEN = 1;
    U1OTGCONbits.DPPULUP = 1;
	U1OTGCONbits.OTGEN = 1;
	U1IR = 0xFF;
	U1IEbits.URSTIE = 1;
	U1EIE = 0xFF;

	setIntVector(_USB_1_VECTOR, _usbInterrupt);
	setIntPriority(_USB_1_VECTOR, 5, 0);
	clearIntFlag(_USB_IRQ);
	setIntEnable(_USB_IRQ);

	U1SOFbits.CNT = 74;

	U1PWRCbits.USBPWR = 1;

    addEndpoint(0, EP_IN, EP_CTL, 64, _ctlRxA, _ctlRxB);
    addEndpoint(0, EP_OUT, EP_CTL, 64, _ctlTxA, _ctlTxB);
	return true;
}

bool USBFS::disableUSB() {
	U1PWRCbits.USBPWR = 0;
	return true;
}

bool USBFS::addEndpoint(uint8_t id, uint8_t direction, uint8_t type, uint8_t size, uint8_t *a, uint8_t *b) {
	if (id > 15) return false;
    _endpointBuffers[id].data = 0x40;
    _endpointBuffers[id].size = size;
	if (direction == EP_IN) {
        _endpointBuffers[id].rx[0] = a;
        _endpointBuffers[id].rx[1] = b;
		_bufferDescriptorTable[id][0].buffer = (uint8_t *)KVA_TO_PA((uint32_t)_endpointBuffers[id].rx[0]);
		_bufferDescriptorTable[id][0].flags = (_endpointBuffers[id].size << 16) | 0x80;
		_bufferDescriptorTable[id][1].buffer = (uint8_t *)KVA_TO_PA((uint32_t)_endpointBuffers[id].rx[1]);
		_bufferDescriptorTable[id][1].flags = (_endpointBuffers[id].size << 16) | 0x80;
		switch (id) {
			case 0: U1EP0bits.EPRXEN = 1; break;
			case 1: U1EP1bits.EPRXEN = 1; break;
			case 2: U1EP2bits.EPRXEN = 1; break;
			case 3: U1EP3bits.EPRXEN = 1; break;
			case 4: U1EP4bits.EPRXEN = 1; break;
			case 5: U1EP5bits.EPRXEN = 1; break;
			case 6: U1EP6bits.EPRXEN = 1; break;
			case 7: U1EP7bits.EPRXEN = 1; break;
			case 8: U1EP8bits.EPRXEN = 1; break;
			case 9: U1EP9bits.EPRXEN = 1; break;
			case 10: U1EP10bits.EPRXEN = 1; break;
			case 11: U1EP11bits.EPRXEN = 1; break;
			case 12: U1EP12bits.EPRXEN = 1; break;
			case 13: U1EP13bits.EPRXEN = 1; break;
			case 14: U1EP14bits.EPRXEN = 1; break;
			case 15: U1EP15bits.EPRXEN = 1; break;
		}
	} else {
        _endpointBuffers[id].tx[0] = a;
        _endpointBuffers[id].tx[1] = b;
		_bufferDescriptorTable[id][2].buffer = (uint8_t *)KVA_TO_PA((uint32_t)_endpointBuffers[id].tx[0]);
		_bufferDescriptorTable[id][2].flags = 0;
		_bufferDescriptorTable[id][3].buffer = (uint8_t *)KVA_TO_PA((uint32_t)_endpointBuffers[id].tx[1]);
		_bufferDescriptorTable[id][3].flags = 0;
		switch (id) {
			case 0: U1EP0bits.EPTXEN = 1; break;
			case 1: U1EP1bits.EPTXEN = 1; break;
			case 2: U1EP2bits.EPTXEN = 1; break;
			case 3: U1EP3bits.EPTXEN = 1; break;
			case 4: U1EP4bits.EPTXEN = 1; break;
			case 5: U1EP5bits.EPTXEN = 1; break;
			case 6: U1EP6bits.EPTXEN = 1; break;
			case 7: U1EP7bits.EPTXEN = 1; break;
			case 8: U1EP8bits.EPTXEN = 1; break;
			case 9: U1EP9bits.EPTXEN = 1; break;
			case 10: U1EP10bits.EPTXEN = 1; break;
			case 11: U1EP11bits.EPTXEN = 1; break;
			case 12: U1EP12bits.EPTXEN = 1; break;
			case 13: U1EP13bits.EPTXEN = 1; break;
			case 14: U1EP14bits.EPTXEN = 1; break;
			case 15: U1EP15bits.EPTXEN = 1; break;
		}
		_enabledEndpoints |= (1 << (id + 16));
	}

	switch (id) {
		case 0: U1EP0bits.EPHSHK = 1; break;
		case 1: U1EP1bits.EPHSHK = 1; break;
		case 2: U1EP2bits.EPHSHK = 1; break;
		case 3: U1EP3bits.EPHSHK = 1; break;
		case 4: U1EP4bits.EPHSHK = 1; break;
		case 5: U1EP5bits.EPHSHK = 1; break;
		case 6: U1EP6bits.EPHSHK = 1; break;
		case 7: U1EP7bits.EPHSHK = 1; break;
		case 8: U1EP8bits.EPHSHK = 1; break;
		case 9: U1EP9bits.EPHSHK = 1; break;
		case 10: U1EP10bits.EPHSHK = 1; break;
		case 11: U1EP11bits.EPHSHK = 1; break;
		case 12: U1EP12bits.EPHSHK = 1; break;
		case 13: U1EP13bits.EPHSHK = 1; break;
		case 14: U1EP14bits.EPHSHK = 1; break;
		case 15: U1EP15bits.EPHSHK = 1; break;
	}

	return true;
}

bool USBFS::canEnqueuePacket(uint8_t ep) {
    uint8_t buffer = _endpointBuffers[ep].txAB;
    uint8_t bdt_entry = buffer ? 3 : 2;
    if ((_bufferDescriptorTable[ep][bdt_entry].flags & 0x80) == 0) return true;
    return false;
}

bool USBFS::enqueuePacket(uint8_t ep, const uint8_t *data, uint32_t len) {
	bool sent = false;

    uint8_t buffer = _endpointBuffers[ep].txAB;
    uint8_t bdt_entry = buffer ? 3 : 2;

    while (!sent) {
        if ((_bufferDescriptorTable[ep][bdt_entry].flags & 0x80) == 0) {
            if (len > 0) memcpy(_endpointBuffers[ep].tx[buffer], data, min(len, _endpointBuffers[ep].size));
            _bufferDescriptorTable[ep][bdt_entry].flags = (len << 16) | 0x00 | _endpointBuffers[ep].data;
            sent = true;
            _bufferDescriptorTable[ep][bdt_entry].flags |= 0x80;
        }
	}

    _endpointBuffers[ep].txAB = 1 - _endpointBuffers[ep].txAB;
	_endpointBuffers[ep].data = _endpointBuffers[ep].data ? 0 : 0x40;

	return true;
}

bool USBFS::sendBuffer(uint8_t ep, const uint8_t *data, uint32_t len) {

    uint32_t ts = millis();
    while (_endpointBuffers[ep].buffer != NULL) {
        if (millis() - ts > USB_TX_TIMEOUT) return false;
        if (canEnqueuePacket(ep)) {
            if (_endpointBuffers[ep].length > 0) {
                uint32_t toSend = min(_endpointBuffers[ep].size, _endpointBuffers[ep].length);
                enqueuePacket(ep, _endpointBuffers[ep].bufferPtr, toSend);
                _endpointBuffers[ep].length -= toSend;
                _endpointBuffers[ep].bufferPtr += toSend;
            } else {
                if (_endpointBuffers[ep].buffer != NULL) {
                    free(_endpointBuffers[ep].buffer);
                    _endpointBuffers[ep].buffer = NULL;
                }
            }

        }
    }

    _endpointBuffers[ep].length = len;
    _endpointBuffers[ep].buffer = (uint8_t *)malloc(len);
    if (!_endpointBuffers[ep].buffer) {
        return false;
    }
    memcpy(_endpointBuffers[ep].buffer, data, len);
    _endpointBuffers[ep].bufferPtr = _endpointBuffers[ep].buffer;

    while (!canEnqueuePacket(ep));

    uint32_t toSend = min(_endpointBuffers[ep].size, _endpointBuffers[ep].length);
    enqueuePacket(ep, _endpointBuffers[ep].bufferPtr, toSend);
    _endpointBuffers[ep].length -= toSend;
    _endpointBuffers[ep].bufferPtr += toSend;

    return true;
}

void USBFS::handleInterrupt() {
    uint32_t toSend;

	if (U1IRbits.TRNIF) {

		uint8_t ep = U1STATbits.ENDPT;
		uint8_t bdt_slot = U1STATbits.PPBI | (U1STATbits.DIR << 1);

		uint8_t pid = (_bufferDescriptorTable[ep][bdt_slot].flags >> 2) & 0x0F;

		switch (pid) {
			case 0x01: // OUT
                if (_manager) _manager->onOutPacket(ep, _endpointBuffers[ep].rx[U1STATbits.PPBI], _bufferDescriptorTable[ep][bdt_slot].flags >> 16);
     //           _endpointBuffers[ep].data = _endpointBuffers[ep].data ? 0 : 0x40;
				_bufferDescriptorTable[ep][bdt_slot].flags = (_endpointBuffers[ep].size << 16) | 0x80 | _endpointBuffers[ep].data;
				break;
			case 0x09: // IN
                if (_endpointBuffers[ep].length > 0) {
                    toSend = min(_endpointBuffers[ep].size, _endpointBuffers[ep].length);
                    enqueuePacket(ep, _endpointBuffers[ep].bufferPtr, toSend);
                    _endpointBuffers[ep].length -= toSend;
                    _endpointBuffers[ep].bufferPtr += toSend;
                } else {
                    if (_endpointBuffers[ep].buffer != NULL) {
                        free(_endpointBuffers[ep].buffer);
                        _endpointBuffers[ep].buffer = NULL;
                    }
                }

                if (_manager) _manager->onInPacket(ep, _endpointBuffers[ep].rx[U1STATbits.PPBI], _bufferDescriptorTable[ep][bdt_slot].flags >> 16);
				break;
			case 0x0d: // SETUP
				_endpointBuffers[ep].data = 0x40;
                if (_manager) _manager->onSetupPacket(ep, _endpointBuffers[ep].rx[U1STATbits.PPBI], _bufferDescriptorTable[ep][bdt_slot].flags >> 16);
				_bufferDescriptorTable[ep][bdt_slot].flags = (_endpointBuffers[ep].size << 16) | 0x80;
				break;
			default:
				break;
		}

		U1CONbits.TOKBUSY=0;
	}
	if (U1IRbits.URSTIF) {
		U1IEbits.IDLEIE = 1;
		U1IEbits.TRNIE = 1;
		U1ADDR = 0;
		U1CONbits.PPBRST = 1;
		U1CONbits.PPBRST = 0;
		for (int i  = 0; i < 16; i++) {
			_endpointBuffers[i].txAB = 0;
            _endpointBuffers[i].data = 0x00;
		}
	}
	if (U1IRbits.IDLEIF) {
		U1IEbits.IDLEIE = 0;
		U1IEbits.RESUMEIE = 1;
	}
	if (U1IRbits.RESUMEIF) {
		U1IEbits.IDLEIE = 1;
		U1IEbits.RESUMEIE = 0;
	}
	if (U1EIR) {

	}
	U1EIR = 0xFF;
	U1IR = 0xFF;
	clearIntFlag(_USB_IRQ);
}

bool USBFS::setAddress(uint8_t address) {
	U1ADDR = address;
	return true;
}

<|endoftext|>


<commit_before>// ----------------------------------------------------------------------------
// TLE72X.cpp
//
// Authors:
// Peter Polidoro polidorop@janelia.hhmi.org
// ----------------------------------------------------------------------------

#include "TLE72X.h"

TLE72X::TLE72X()
{
  initialized_ = false;
}

TLE72X::TLE72X(const size_t cs_pin) :
  cs_pin_(cs_pin)
{
  initialized_ = false;

  pinMode(cs_pin_,OUTPUT);
  digitalWrite(cs_pin_,HIGH);
}

TLE72X::TLE72X(const size_t cs_pin, const size_t reset_pin) :
  cs_pin_(cs_pin),
  reset_pin_(reset_pin)
{
  initialized_ = false;

  pinMode(cs_pin,OUTPUT);
  digitalWrite(cs_pin,HIGH);

  pinMode(reset_pin,OUTPUT);
  digitalWrite(reset_pin,HIGH);
}

void TLE72X::setup(const size_t ic_count, const boolean spi_reset)
{
  spi_reset_ = spi_reset;
  if ((0 < ic_count) && (ic_count <= IC_COUNT_MAX))
  {
    ic_count_ = ic_count;
  }
  else
  {
    ic_count_ = IC_COUNT_MIN;
  }
  spiBegin();
  setAllChannelsMapTrue();
  setAllChannelsBooleanAnd();
  setAllChannelsOff();
  initialized_ = true;
}

void TLE72X::setChannels(const uint32_t channels)
{
  if (spi_reset_)
  {
    spiBegin();
  }
  digitalWrite(cs_pin_,LOW);
  noInterrupts();
  channels_ = channels;
  for (size_t ic = (ic_count_ - 1); ic >= 0; --ic)
  {
    SPI.transfer(CMD_WRITE + ADDR_CTL);
    SPI.transfer(channels_>>(ic*8));
  }
  interrupts();
  digitalWrite(cs_pin_,HIGH);
  digitalRead(cs_pin_);
}

void TLE72X::setChannelOn(const size_t channel)
{
  if ((0 <= channel) && (channel < CHANNEL_COUNT_MAX))
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    channels_ |= bit;
    interrupts();
    setChannels(channels_);
  }
}

void TLE72X::setChannelOff(const size_t channel)
{
  if ((0 <= channel) && (channel < CHANNEL_COUNT_MAX))
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    channels_ &= ~bit;
    interrupts();
    setChannels(channels_);
  }
}

void TLE72X::setChannelsOn(const uint32_t channels)
{
  noInterrupts();
  channels_ |= channels;
  interrupts();
  setChannels(channels_);
}

void TLE72X::setChannelsOff(const uint32_t channels)
{
  noInterrupts();
  channels_ &= ~channels;
  interrupts();
  setChannels(channels_);
}

void TLE72X::toggleChannel(const size_t channel)
{
  if ((0 <= channel) && (channel < CHANNEL_COUNT_MAX))
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    channels_ ^= bit;
    interrupts();
    setChannels(channels_);
  }
}

void TLE72X::toggleChannels(const uint32_t channels)
{
  noInterrupts();
  channels_ ^= channels;
  interrupts();
  setChannels(channels_);
}

void TLE72X::toggleAllChannels()
{
  noInterrupts();
  channels_ = ~channels_;
  interrupts();
  setChannels(channels_);
}

void TLE72X::setAllChannelsOn()
{
  uint32_t bit = 1;
  noInterrupts();
  channels_ = (bit << getChannelCount()) - 1;
  interrupts();
  setChannels(channels_);
}

void TLE72X::setAllChannelsOff()
{
  noInterrupts();
  channels_ = 0;
  interrupts();
  setChannels(channels_);
}

void TLE72X::setChannelOnAllOthersOff(const size_t channel)
{
  if ((0 <= channel) && (channel < CHANNEL_COUNT_MAX))
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    channels_ = bit;
    interrupts();
    setChannels(channels_);
  }
}

void TLE72X::setChannelOffAllOthersOn(const size_t channel)
{
  if ((0 <= channel) && (channel < CHANNEL_COUNT_MAX))
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    channels_ = ~bit;
    interrupts();
    setChannels(channels_);
  }
}

void TLE72X::setChannelsOnAllOthersOff(const uint32_t channels)
{
  noInterrupts();
  channels_ = channels;
  interrupts();
  setChannels(channels_);
}

void TLE72X::setChannelsOffAllOthersOn(const uint32_t channels)
{
  noInterrupts();
  channels_ = ~channels;
  interrupts();
  setChannels(channels_);
}

uint32_t TLE72X::getChannelsOn()
{
  return channels_;
}

int TLE72X::getChannelCount()
{
  return ic_count_*CHANNEL_COUNT_PER_IC;
}

void TLE72X::reset()
{
  digitalWrite(reset_pin_,LOW);
  delay(RESET_DELAY);
  digitalWrite(reset_pin_,HIGH);
  noInterrupts();
  channels_ = 0;
  interrupts();
}

void TLE72X::setChannelsMap(const uint32_t channels)
{
  if (spi_reset_)
  {
    spiBegin();
  }
  digitalWrite(cs_pin_,LOW);
  noInterrupts();
  mapped_ = channels;
  for (size_t ic = (ic_count_ - 1); ic >= 0; --ic)
  {
    SPI.transfer(CMD_WRITE + ADDR_MAP);
    SPI.transfer(mapped_>>(ic*8));
  }
  interrupts();
  digitalWrite(cs_pin_,HIGH);
  digitalRead(cs_pin_);
}

void TLE72X::setChannelMapTrue(const size_t channel)
{
  if ((0 <= channel) && (channel < CHANNEL_COUNT_MAX))
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    mapped_ |= bit;
    interrupts();
    setChannelsMap(mapped_);
  }
}

void TLE72X::setChannelMapFalse(const size_t channel)
{
  if ((0 <= channel) && (channel < CHANNEL_COUNT_MAX))
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    mapped_ &= ~bit;
    interrupts();
    setChannelsMap(mapped_);
  }
}

void TLE72X::setAllChannelsMapTrue()
{
  uint32_t bit = 1;
  noInterrupts();
  mapped_ = (bit << getChannelCount()) - 1;
  interrupts();
  setChannelsMap(mapped_);
}

void TLE72X::setAllChannelsMapFalse()
{
  noInterrupts();
  mapped_ = 0;
  interrupts();
  setChannelsMap(mapped_);
}

void TLE72X::setChannelsBoolean(const uint32_t bool_state)
{
  if (spi_reset_)
  {
    spiBegin();
  }
  digitalWrite(cs_pin_,LOW);
  noInterrupts();
  bool_state_ = bool_state;
  for (size_t ic = (ic_count_ - 1); ic >= 0; --ic)
  {
    SPI.transfer(CMD_WRITE + ADDR_BOL);
    SPI.transfer(bool_state_>>(ic*8));
  }
  interrupts();
  digitalWrite(cs_pin_,HIGH);
  digitalRead(cs_pin_);
}

void TLE72X::setChannelBooleanAnd(const size_t channel)
{
  if ((0 <= channel) && (channel < CHANNEL_COUNT_MAX))
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    bool_state_ |= bit;
    interrupts();
    setChannelsBoolean(bool_state_);
  }
}

void TLE72X::setChannelBooleanOr(const size_t channel)
{
  if ((0 <= channel) && (channel < CHANNEL_COUNT_MAX))
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    bool_state_ &= ~bit;
    interrupts();
    setChannelsBoolean(bool_state_);
  }
}

void TLE72X::setAllChannelsBooleanAnd()
{
  uint32_t bit = 1;
  noInterrupts();
  bool_state_ = (bit << getChannelCount()) - 1;
  interrupts();
  setChannelsBoolean(bool_state_);
}

void TLE72X::setAllChannelsBooleanOr()
{
  noInterrupts();
  bool_state_ = 0;
  interrupts();
  setChannelsBoolean(bool_state_);
}

void TLE72X::spiBegin()
{
  SPI.setDataMode(SPI_MODE1);
  SPI.setClockDivider(SPI_CLOCK_DIV4);
  SPI.setBitOrder(MSBFIRST);
  SPI.begin();
}

<commit_msg>Do not check if unsigned parameter is less than zero.<commit_after>// ----------------------------------------------------------------------------
// TLE72X.cpp
//
// Authors:
// Peter Polidoro polidorop@janelia.hhmi.org
// ----------------------------------------------------------------------------

#include "TLE72X.h"

TLE72X::TLE72X()
{
  initialized_ = false;
}

TLE72X::TLE72X(const size_t cs_pin) :
  cs_pin_(cs_pin)
{
  initialized_ = false;

  pinMode(cs_pin_,OUTPUT);
  digitalWrite(cs_pin_,HIGH);
}

TLE72X::TLE72X(const size_t cs_pin, const size_t reset_pin) :
  cs_pin_(cs_pin),
  reset_pin_(reset_pin)
{
  initialized_ = false;

  pinMode(cs_pin,OUTPUT);
  digitalWrite(cs_pin,HIGH);

  pinMode(reset_pin,OUTPUT);
  digitalWrite(reset_pin,HIGH);
}

void TLE72X::setup(const size_t ic_count, const boolean spi_reset)
{
  spi_reset_ = spi_reset;
  if ((0 < ic_count) && (ic_count <= IC_COUNT_MAX))
  {
    ic_count_ = ic_count;
  }
  else
  {
    ic_count_ = IC_COUNT_MIN;
  }
  spiBegin();
  setAllChannelsMapTrue();
  setAllChannelsBooleanAnd();
  setAllChannelsOff();
  initialized_ = true;
}

void TLE72X::setChannels(const uint32_t channels)
{
  if (spi_reset_)
  {
    spiBegin();
  }
  digitalWrite(cs_pin_,LOW);
  noInterrupts();
  channels_ = channels;
  for (size_t ic = (ic_count_ - 1); ic >= 0; --ic)
  {
    SPI.transfer(CMD_WRITE + ADDR_CTL);
    SPI.transfer(channels_>>(ic*8));
  }
  interrupts();
  digitalWrite(cs_pin_,HIGH);
  digitalRead(cs_pin_);
}

void TLE72X::setChannelOn(const size_t channel)
{
  if (channel < CHANNEL_COUNT_MAX)
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    channels_ |= bit;
    interrupts();
    setChannels(channels_);
  }
}

void TLE72X::setChannelOff(const size_t channel)
{
  if (channel < CHANNEL_COUNT_MAX)
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    channels_ &= ~bit;
    interrupts();
    setChannels(channels_);
  }
}

void TLE72X::setChannelsOn(const uint32_t channels)
{
  noInterrupts();
  channels_ |= channels;
  interrupts();
  setChannels(channels_);
}

void TLE72X::setChannelsOff(const uint32_t channels)
{
  noInterrupts();
  channels_ &= ~channels;
  interrupts();
  setChannels(channels_);
}

void TLE72X::toggleChannel(const size_t channel)
{
  if (channel < CHANNEL_COUNT_MAX)
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    channels_ ^= bit;
    interrupts();
    setChannels(channels_);
  }
}

void TLE72X::toggleChannels(const uint32_t channels)
{
  noInterrupts();
  channels_ ^= channels;
  interrupts();
  setChannels(channels_);
}

void TLE72X::toggleAllChannels()
{
  noInterrupts();
  channels_ = ~channels_;
  interrupts();
  setChannels(channels_);
}

void TLE72X::setAllChannelsOn()
{
  uint32_t bit = 1;
  noInterrupts();
  channels_ = (bit << getChannelCount()) - 1;
  interrupts();
  setChannels(channels_);
}

void TLE72X::setAllChannelsOff()
{
  noInterrupts();
  channels_ = 0;
  interrupts();
  setChannels(channels_);
}

void TLE72X::setChannelOnAllOthersOff(const size_t channel)
{
  if (channel < CHANNEL_COUNT_MAX)
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    channels_ = bit;
    interrupts();
    setChannels(channels_);
  }
}

void TLE72X::setChannelOffAllOthersOn(const size_t channel)
{
  if (channel < CHANNEL_COUNT_MAX)
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    channels_ = ~bit;
    interrupts();
    setChannels(channels_);
  }
}

void TLE72X::setChannelsOnAllOthersOff(const uint32_t channels)
{
  noInterrupts();
  channels_ = channels;
  interrupts();
  setChannels(channels_);
}

void TLE72X::setChannelsOffAllOthersOn(const uint32_t channels)
{
  noInterrupts();
  channels_ = ~channels;
  interrupts();
  setChannels(channels_);
}

uint32_t TLE72X::getChannelsOn()
{
  return channels_;
}

int TLE72X::getChannelCount()
{
  return ic_count_*CHANNEL_COUNT_PER_IC;
}

void TLE72X::reset()
{
  digitalWrite(reset_pin_,LOW);
  delay(RESET_DELAY);
  digitalWrite(reset_pin_,HIGH);
  noInterrupts();
  channels_ = 0;
  interrupts();
}

void TLE72X::setChannelsMap(const uint32_t channels)
{
  if (spi_reset_)
  {
    spiBegin();
  }
  digitalWrite(cs_pin_,LOW);
  noInterrupts();
  mapped_ = channels;
  for (size_t ic = (ic_count_ - 1); ic >= 0; --ic)
  {
    SPI.transfer(CMD_WRITE + ADDR_MAP);
    SPI.transfer(mapped_>>(ic*8));
  }
  interrupts();
  digitalWrite(cs_pin_,HIGH);
  digitalRead(cs_pin_);
}

void TLE72X::setChannelMapTrue(const size_t channel)
{
  if (channel < CHANNEL_COUNT_MAX)
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    mapped_ |= bit;
    interrupts();
    setChannelsMap(mapped_);
  }
}

void TLE72X::setChannelMapFalse(const size_t channel)
{
  if (channel < CHANNEL_COUNT_MAX)
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    mapped_ &= ~bit;
    interrupts();
    setChannelsMap(mapped_);
  }
}

void TLE72X::setAllChannelsMapTrue()
{
  uint32_t bit = 1;
  noInterrupts();
  mapped_ = (bit << getChannelCount()) - 1;
  interrupts();
  setChannelsMap(mapped_);
}

void TLE72X::setAllChannelsMapFalse()
{
  noInterrupts();
  mapped_ = 0;
  interrupts();
  setChannelsMap(mapped_);
}

void TLE72X::setChannelsBoolean(const uint32_t bool_state)
{
  if (spi_reset_)
  {
    spiBegin();
  }
  digitalWrite(cs_pin_,LOW);
  noInterrupts();
  bool_state_ = bool_state;
  for (size_t ic = (ic_count_ - 1); ic >= 0; --ic)
  {
    SPI.transfer(CMD_WRITE + ADDR_BOL);
    SPI.transfer(bool_state_>>(ic*8));
  }
  interrupts();
  digitalWrite(cs_pin_,HIGH);
  digitalRead(cs_pin_);
}

void TLE72X::setChannelBooleanAnd(const size_t channel)
{
  if (channel < CHANNEL_COUNT_MAX)
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    bool_state_ |= bit;
    interrupts();
    setChannelsBoolean(bool_state_);
  }
}

void TLE72X::setChannelBooleanOr(const size_t channel)
{
  if (channel < CHANNEL_COUNT_MAX)
  {
    uint32_t bit = 1;
    bit = bit << channel;
    noInterrupts();
    bool_state_ &= ~bit;
    interrupts();
    setChannelsBoolean(bool_state_);
  }
}

void TLE72X::setAllChannelsBooleanAnd()
{
  uint32_t bit = 1;
  noInterrupts();
  bool_state_ = (bit << getChannelCount()) - 1;
  interrupts();
  setChannelsBoolean(bool_state_);
}

void TLE72X::setAllChannelsBooleanOr()
{
  noInterrupts();
  bool_state_ = 0;
  interrupts();
  setChannelsBoolean(bool_state_);
}

void TLE72X::spiBegin()
{
  SPI.setDataMode(SPI_MODE1);
  SPI.setClockDivider(SPI_CLOCK_DIV4);
  SPI.setBitOrder(MSBFIRST);
  SPI.begin();
}

<|endoftext|>


<commit_before>// Copyright 2015 Olivier Gillet.
//
// Author: Olivier Gillet (ol.gillet@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// See http://creativecommons.org/licenses/MIT/ for more information.
//
// -----------------------------------------------------------------------------
//
// Example using the polyblep class.

#include "dsp/oscillator.h"
#include "test/wav_writer.h"

using namespace stmlib;

const size_t kSampleRate = 96000;
const size_t kAudioBlockSize = 24;
const size_t kSampleDuration = 10;

int main(void) {
  Oscillator osc;
  osc.Init();

  WavWriter wav_writer(1, kSampleRate, kSampleDuration);
  wav_writer.Open("sample.wav");

  size_t num_blocks = kSampleDuration * kSampleRate / kAudioBlockSize;
  for (size_t i = 0; i < num_blocks; ++i) {
    float out[kAudioBlockSize];
    osc.Render<true>(
        100.00f / 96000.0f,  // master
        100.00f * (0.5f + 4.0f * float(i) / num_blocks) / 96000.0f,  // slave
        0.5f,  // pulse-width
        0.9f,  // shape: 0.0 for saw, 1.0 for square
        out, kAudioBlockSize);
    wav_writer.Write(out, kAudioBlockSize);
  }
}
<commit_msg>Add saw sweep test.<commit_after>// Copyright 2015 Olivier Gillet.
//
// Author: Olivier Gillet (ol.gillet@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// See http://creativecommons.org/licenses/MIT/ for more information.
//
// -----------------------------------------------------------------------------
//
// Example using the polyblep class.

#include "dsp/oscillator.h"
#include "test/wav_writer.h"

using namespace stmlib;

const size_t kSampleRate = 96000;
const size_t kAudioBlockSize = 24;
const size_t kSampleDuration = 10;

float Mix(float s, float a, float b) {
    return (1-s)*a + s*b;
}

int main(void) {
  Oscillator osc;
  osc.Init();

  WavWriter wav_writer(1, kSampleRate, kSampleDuration);
  wav_writer.Open("sample.wav");

  size_t num_blocks = kSampleDuration * kSampleRate / kAudioBlockSize;
  for (size_t i = 0; i < num_blocks; ++i) {
    float out[kAudioBlockSize];
    osc.Render<true>(
        100.00f / 96000.0f,  // master
        100.00f * (0.5f + 4.0f * float(i) / num_blocks) / 96000.0f,  // slave
        0.5f,  // pulse-width
        0.9f,  // shape: 0.0 for saw, 1.0 for square
        out, kAudioBlockSize);
    wav_writer.Write(out, kAudioBlockSize);
  }

  WavWriter wav_writer2(1, kSampleRate, kSampleDuration);
  wav_writer2.Open("sweep.wav");

  const int n = kSampleRate * kSampleDuration;
  for (size_t i = 0; i < n; ++i) {
    float out;
    osc.Render<false>(
        Mix(float(i)/n, 100.00f, 15000.f) / 44100,  // master
        0.5f,  // pulse-width
        0.0f,  // shape: 0.0 for saw, 1.0 for square
        &out, 1);
    wav_writer2.Write(&out, 1);
  }

}
<|endoftext|>


<commit_before>#include "Streak.h"

Streak::Streak(uint16_t columns,
  uint16_t rows,
  uint8_t hue,
  uint8_t saturation,
  CRGB * leds)
: Visualization(columns, rows, hue, saturation, leds)
{
  this->length = 0;
  this->minLength = 8;
  this->maxLength = 16;
  this->minInterval = 0;
  this->maxInterval = 90;
  this->randomHue = false;
  this->fade = true;
}

void Streak::inititalize() {
  this->interval = random8(this->minInterval, this->maxInterval);
  this->column = random8(this->columns);
  this->length = random8(this->minLength, this->maxLength);
  if (this->randomHue) {
    this->setHue(random(256));
  }
}

void Streak::display (unsigned long currentTime) {
  int currentFrame = this->frame % (this->rows + this->length);

  if (currentFrame == 0) {
    this->inititalize();
  }

  if (currentTime > this->nextTime) {
    // Serial.print(this->id);
    // Serial.print(": ");
    // Serial.println(currentTime);
    this->frame++;
    this->nextTime = currentTime + this->interval;
  }

  int y = currentFrame;
  int pos;
  for (uint8_t i=0; i<this->length; i++) {
    if ((y - i >= 0) && (y - i < this->rows)) {
      pos = this->xy2Pos(this->column, y - i);
      this->leds[pos] = this->color;

      if (this->fade) {
        this->leds[pos].fadeLightBy((256 / this->length) * i);
      }
    }
  }
}

void Streak::setLengthMinMax(uint8_t min, uint8_t max) {
  this->minLength = min;
  this->maxLength = max;
}

void Streak::setIntervalMinMax(uint8_t min, uint8_t max) {
  this->minInterval = min;
  this->maxInterval = max;
}

void Streak::setFade(bool on) {
  this->fade = on;
}

void Streak::setRandomHue(bool on) {
  this->randomHue = on;
}
<commit_msg>Streak: fix start/end bugs<commit_after>#include "Streak.h"

Streak::Streak(uint16_t columns,
  uint16_t rows,
  uint8_t hue,
  uint8_t saturation,
  CRGB * leds)
: Visualization(columns, rows, hue, saturation, leds)
{
  this->length = 0;
  this->minLength = 8;
  this->maxLength = 16;
  this->minInterval = 0;
  this->maxInterval = 90;
  this->randomHue = false;
  this->fade = true;
}

void Streak::inititalize() {
<<<<<<< Updated upstream
=======
  Serial.print("inititalize - ");
  Serial.println(this->frame);
  this->frame = 0;
>>>>>>> Stashed changes
  this->interval = random8(this->minInterval, this->maxInterval);
  this->column = random8(this->columns);
  this->length = random8(this->minLength, this->maxLength);
  if (this->randomHue) {
    this->setHue(random(256));
  }
}

void Streak::display (unsigned long currentTime) {
  if (currentTime > this->nextTime) {
    Serial.println(this->frame);
    this->frame++;
    this->nextTime = currentTime + this->interval;

    if (this->frame > (this->rows + this->length)) {
      this->inititalize();
    }
  }

  int y = this->frame;
  int pos;
  for (uint8_t i=0; i<this->length; i++) {
    if ((y - i >= 0) && (y - i < this->rows)) {
      pos = this->xy2Pos(this->column, y - i);
      this->leds[pos] = this->color;

      if (this->fade) {
        this->leds[pos].fadeLightBy((256 / this->length) * i);
      }
    }
  }
}

void Streak::setLengthMinMax(uint8_t min, uint8_t max) {
  this->minLength = min;
  this->maxLength = max;
}

void Streak::setIntervalMinMax(uint8_t min, uint8_t max) {
  this->minInterval = min;
  this->maxInterval = max;
}

void Streak::setFade(bool on) {
  this->fade = on;
}

void Streak::setRandomHue(bool on) {
  this->randomHue = on;
}
<|endoftext|>


<commit_before>#pragma once

#include "Registry.hpp"
#include "Environment.hpp"
#include "Locale.hpp"
#include <string>

namespace WinApiHelper
{
	namespace System
	{
		static bool IsX64()
		{
			SYSTEM_INFO si = { 0 };
			::GetNativeSystemInfo(&si);
			return si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64;
		}

		bool IsWow64()
		{
			typedef BOOL(WINAPI *ISWOW64PROCESS) (HANDLE, PBOOL);
			ISWOW64PROCESS fnIsWow64Process =
				(ISWOW64PROCESS)::GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "IsWow64Process");
			BOOL bIsWow64 = false;
			if (NULL != fnIsWow64Process)
			{
				if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
				{
					return false;
				}
			}

			return bIsWow64 != 0;
		}

		static std::wstring GetDefaultLocaleName()
		{
			std::wstring locale;
			Locale::LCIDToLocaleName(GetSystemDefaultLCID(), locale);
			return locale;
		}

		struct WindowsVersion
		{
			std::wstring CurrentBuildNumber;
			std::wstring BuildLabEx;
			std::wstring CurrentVersion;
			std::wstring EditionId;
			std::wstring ProductName;
			std::wstring Architecture;
			std::wstring Language;
			DWORD CurrentMajorVersionNumber;
			DWORD CurrentMinorVersionNumber;

			std::wstring ToString()
			{
				// will produce something like "Windows 10 Pro x64 en"
				return ProductName + L" " + Architecture + L" " + Language.substr(0,2);
			}

			std::wstring ToExtendedString()
			{
				// will produce somethin like "Windows 10 Pro x64 en-US (Build 10240)"
				return ProductName + L" " + Architecture + L" " + Language + L" (Build " + CurrentBuildNumber + L")";
			}

			DWORD Init()
			{
				Registry reg;
				auto result = reg.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", Registry::Mode::Read);
				if (result != ERROR_SUCCESS)
				{
					return result;
				}
				reg.TryReadString(L"CurrentBuildNumber", CurrentBuildNumber);
				reg.TryReadDword(L"CurrentMajorVersionNumber", CurrentMajorVersionNumber);
				reg.TryReadDword(L"CurrentMinorVersionNumber", CurrentMinorVersionNumber);
				reg.TryReadString(L"BuildLabEx", BuildLabEx);
				reg.TryReadString(L"CurrentVersion", CurrentVersion);
				reg.TryReadString(L"EditionId", EditionId);
				reg.TryReadString(L"ProductName", ProductName);
				if (CurrentMajorVersionNumber > 0)
				{
					CurrentVersion = std::to_wstring(CurrentMajorVersionNumber) + L"." + std::to_wstring(CurrentMinorVersionNumber);
				}
				else
				{
					reg.TryReadString(L"CurrentVersion", CurrentVersion);
				}

				Architecture = IsX64() ? L"x64" : L"x86";
				Language = GetDefaultLocaleName();// .substr(0, 2);

				return ERROR_SUCCESS;
			}
		};
	};
}
<commit_msg>Current*VersionNumber variables were not initialized by zero<commit_after>#pragma once

#include "Registry.hpp"
#include "Environment.hpp"
#include "Locale.hpp"
#include <string>

namespace WinApiHelper
{
	namespace System
	{
		static bool IsX64()
		{
			SYSTEM_INFO si = { 0 };
			::GetNativeSystemInfo(&si);
			return si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64;
		}

		bool IsWow64()
		{
			typedef BOOL(WINAPI *ISWOW64PROCESS) (HANDLE, PBOOL);
			ISWOW64PROCESS fnIsWow64Process =
				(ISWOW64PROCESS)::GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "IsWow64Process");
			BOOL bIsWow64 = false;
			if (NULL != fnIsWow64Process)
			{
				if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
				{
					return false;
				}
			}

			return bIsWow64 != 0;
		}

		static std::wstring GetDefaultLocaleName()
		{
			std::wstring locale;
			Locale::LCIDToLocaleName(GetSystemDefaultLCID(), locale);
			return locale;
		}

		struct WindowsVersion
		{
			std::wstring CurrentBuildNumber;
			std::wstring BuildLabEx;
			std::wstring CurrentVersion;
            std::wstring CSDBuildNumber; // up to windows 7
            std::wstring CSDVersion; // up to windows 7
			std::wstring EditionId;
			std::wstring ProductName;
			std::wstring Architecture;
			std::wstring Language;
			DWORD CurrentMajorVersionNumber = 0;
			DWORD CurrentMinorVersionNumber = 0;

			std::wstring ToString()
			{
				// will produce something like "Windows 10 Pro x64 en"
				return ProductName + L" " + Architecture + L" " + Language.substr(0,2);
			}

			std::wstring ToExtendedString()
			{
				// will produce somethin like "Windows 10 Pro x64 en-US (Build 10240)"
				return ProductName + L" " + Architecture + L" " + Language + L" (Build " + CurrentBuildNumber + L")";
			}

			DWORD Init()
			{
				Registry reg;
				auto result = reg.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", Registry::Mode::Read);
				if (result != ERROR_SUCCESS)
				{
					return result;
				}
				reg.TryReadString(L"CurrentBuildNumber", CurrentBuildNumber);
				reg.TryReadDword(L"CurrentMajorVersionNumber", CurrentMajorVersionNumber);
				reg.TryReadDword(L"CurrentMinorVersionNumber", CurrentMinorVersionNumber);
                reg.TryReadString(L"CSDbuildNumber", CSDBuildNumber);
                reg.TryReadString(L"CSDVersion", CSDVersion);
                if (reg.TryReadString(L"BuildLabEx", BuildLabEx) != NO_ERROR)
                {
                    reg.TryReadString(L"BuildLab", BuildLabEx);
                }
				reg.TryReadString(L"CurrentVersion", CurrentVersion);
				reg.TryReadString(L"EditionId", EditionId);
				reg.TryReadString(L"ProductName", ProductName);
				if (CurrentMajorVersionNumber > 0)
				{
					CurrentVersion = std::to_wstring(CurrentMajorVersionNumber) + L"." + std::to_wstring(CurrentMinorVersionNumber);
				}
				else
				{
					reg.TryReadString(L"CurrentVersion", CurrentVersion);
				}

				Architecture = IsX64() ? L"x64" : L"x86";
				Language = GetDefaultLocaleName();// .substr(0, 2);

				return ERROR_SUCCESS;
			}
		};
	};
}
<|endoftext|>


<commit_before>#include "SolidWall.h"
#include "Simulation.h"
#include "FEProblem.h"
#include "Pipe.h"
//
#include "OneDMassSolidWallBC.h"
#include "OneDMomentumSolidWallBC.h"
#include "OneDEnergySolidWallBC.h"

template<>
InputParameters validParams<SolidWall>()
{
  InputParameters params = validParams<BoundaryBase>();
  params.addRequiredParam<std::string>("input", "Pipe name");
  return params;
}

SolidWall::SolidWall(const std::string & name, InputParameters params) :
    BoundaryBase(name, params),
    _input(getParam<std::string>("input"))
{
}

SolidWall::~SolidWall()
{
}

void
SolidWall::buildMesh()
{
  // NOTE: we are not building any mesh here, we just extract some mesh related info

  // extract boundary id so we can set up our BCs
  std::string comp_name;
  RELAP7::EEndType end_type;
  RELAP7::getConnectionInfo(_input, comp_name, end_type);

  Component * comp = _sim.getComponentByName(comp_name);
  if (dynamic_cast<PipeBase *>(comp) != NULL)
  {
    PipeBase * pipe = dynamic_cast<PipeBase *>(comp);
    _boundary_id = pipe->getBoundaryId(end_type);
  }
  else
  {
    mooseError("Component " << comp->name() << " is not of a pipe type");
  }
}

void
SolidWall::addVariables()
{
}

void
SolidWall::addMooseObjects()
{
  // coupling "vectors"
  std::vector<std::string> cv_p(1, Model::PRESSURE);
  std::vector<std::string> cv_rho(1, Model::RHO);
  std::vector<std::string> cv_rhoE(1, Model::RHOE);
  // boundary id
  std::vector<unsigned int> bnd_id(1, _boundary_id);
  {
    InputParameters params = validParams<OneDMassSolidWallBC>();
    params.set<std::string>("variable") = Model::RHO;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    _sim.addBoundaryCondition("OneDMassSolidWallBC", genName("bc", _id, "rho"), params);
  }
  {
    InputParameters params = validParams<OneDMomentumSolidWallBC>();
    params.set<std::string>("variable") = Model::RHOU;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    params.set<std::string>("eos_function") = Model::EOS_FUNCTION;
    // coupling
    params.set<std::vector<std::string> >("p") = cv_p;
    params.set<std::vector<std::string> >("rho") = cv_rho;
    if (_model_type == Model::EQ_MODEL_3)
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
    _sim.addBoundaryCondition("OneDMomentumSolidWallBC", genName("bc", _id, "rhou"), params);
  }

  if (_model_type == Model::EQ_MODEL_3)
  {
    InputParameters params = validParams<OneDEnergySolidWallBC>();
    params.set<std::string>("variable") = Model::RHOE;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    params.set<std::string>("eos_function") = Model::EOS_FUNCTION;

    // There is no coupling for the energy equation solid wall BC.
    // It simply returns zero...

    _sim.addBoundaryCondition("OneDEnergySolidWallBC", genName("bc", _id, "rhoE"), params);
  }
}
<commit_msg>eos is required for every component<commit_after>#include "SolidWall.h"
#include "Simulation.h"
#include "FEProblem.h"
#include "Pipe.h"
//
#include "OneDMassSolidWallBC.h"
#include "OneDMomentumSolidWallBC.h"
#include "OneDEnergySolidWallBC.h"

template<>
InputParameters validParams<SolidWall>()
{
  InputParameters params = validParams<BoundaryBase>();
  params.addRequiredParam<std::string>("input", "Pipe name");

  params.addRequiredParam<std::string>("eos_function", "The EOS function object");
  return params;
}

SolidWall::SolidWall(const std::string & name, InputParameters params) :
    BoundaryBase(name, params),
    _input(getParam<std::string>("input"))
{
}

SolidWall::~SolidWall()
{
}

void
SolidWall::buildMesh()
{
  // NOTE: we are not building any mesh here, we just extract some mesh related info

  // extract boundary id so we can set up our BCs
  std::string comp_name;
  RELAP7::EEndType end_type;
  RELAP7::getConnectionInfo(_input, comp_name, end_type);

  Component * comp = _sim.getComponentByName(comp_name);
  if (dynamic_cast<PipeBase *>(comp) != NULL)
  {
    PipeBase * pipe = dynamic_cast<PipeBase *>(comp);
    _boundary_id = pipe->getBoundaryId(end_type);
  }
  else
  {
    mooseError("Component " << comp->name() << " is not of a pipe type");
  }
}

void
SolidWall::addVariables()
{
}

void
SolidWall::addMooseObjects()
{
  // coupling "vectors"
  std::vector<std::string> cv_p(1, Model::PRESSURE);
  std::vector<std::string> cv_rho(1, Model::RHO);
  std::vector<std::string> cv_rhoE(1, Model::RHOE);
  // boundary id
  std::vector<unsigned int> bnd_id(1, _boundary_id);
  {
    InputParameters params = validParams<OneDMassSolidWallBC>();
    params.set<std::string>("variable") = Model::RHO;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    _sim.addBoundaryCondition("OneDMassSolidWallBC", genName("bc", _id, "rho"), params);
  }
  {
    InputParameters params = validParams<OneDMomentumSolidWallBC>();
    params.set<std::string>("variable") = Model::RHOU;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    //params.set<std::string>("eos_function") = Model::EOS_FUNCTION;
    params.set<std::string>("eos_function") = getParam<std::string>("eos_function");

    // coupling
    params.set<std::vector<std::string> >("p") = cv_p;
    params.set<std::vector<std::string> >("rho") = cv_rho;
    if (_model_type == Model::EQ_MODEL_3)
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
    _sim.addBoundaryCondition("OneDMomentumSolidWallBC", genName("bc", _id, "rhou"), params);
  }

  if (_model_type == Model::EQ_MODEL_3)
  {
    InputParameters params = validParams<OneDEnergySolidWallBC>();
    params.set<std::string>("variable") = Model::RHOE;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    //params.set<std::string>("eos_function") = Model::EOS_FUNCTION;
    params.set<std::string>("eos_function") = getParam<std::string>("eos_function");

    // There is no coupling for the energy equation solid wall BC.
    // It simply returns zero...

    _sim.addBoundaryCondition("OneDEnergySolidWallBC", genName("bc", _id, "rhoE"), params);
  }
}
<|endoftext|>


<commit_before><commit_msg>ImpEditView::SetEditSelection: fix missing tiled rendering selection callbacks<commit_after><|endoftext|>


<commit_before>/**
 * Copyright 2008 Matthew Graham
 * 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.
 */

#include "request_test.h"
#include <testpp/test.h>

/**
 * Test that the constructor works and the parameters are
 * set correctly and can be requested again.
 */
TESTPP( test_constructor_1 )
{
	request_c req( "renew" );
	req.parse_args( "renew dog" );

	assertpp( req.type() ) == "renew";
	assertpp( req.argc() ) == 2;
	assertpp( req.argv( 1 ) ) == "dog";
}

/**
 * Test the constructor and simple getters again, slightly
 * differently.  This test is probably not necessary.
 */
TESTPP( test_constructor_2 )
{
	request_c req( "create cat mouse" );

	assertpp( req.type() ) == "create";
	assertpp( req.argc() ) == 2;
	assertpp( req.argv( 0 ) ) == "cat";
	assertpp( req.argv( 1 ) ) == "mouse";
}

/**
 * Test that an invalid request type name still shows up as something.
 */
TESTPP( test_invalid_request_type )
{
	request_c req( "dog 5" );

	assertpp( req.type() ) == "dog";
	assertpp( req.argc() ) == 1;
	assertpp( req.argv( 0 ) ) == "5";
}

/**
 * Test mock request constructor.
 */
TESTPP( test_mock_request_constructor )
{
	mock_request_c req;
	req.set( "id_34", 23 );

	assertpp( req.id() ) == "id_34";
	assertpp( req.number() ) == 23;
}

<commit_msg>fixed the request tests to work for the class being derived from the message base class.<commit_after>/**
 * Copyright 2008 Matthew Graham
 * 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.
 */

#include "request_test.h"
#include <testpp/test.h>

/**
 * Test that the default constructor with a basic request_type param works
 * and the type is set correctly and can be requested again.
 */
TESTPP( test_request_default_constructor )
{
	request_c req( "renew" );

	assertpp( req.type() ) == "renew";
	assertpp( req.argc() ) == 1;
	assertpp( req.argv( 0 ) ) == "renew";
}

/**
 * Test mock request constructor.
 */
TESTPP( test_mock_request_constructor )
{
	mock_request_c req;
	req.set( "id_34", 23 );

	assertpp( req.id() ) == "id_34";
	assertpp( req.number() ) == 23;
}

<|endoftext|>


<commit_before><commit_msg>All uses of LINE_SEP are fine with a char literal<commit_after><|endoftext|>