<commit_before>/*
 * Copyright (c) 2015-2018 JlnWntr (jlnwntr@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.
 */

#ifndef LUA_ADAPTER_H
#include "LuaAdapter.hpp"
#endif
#ifndef LUA_FUNCTION_H
#include "LuaFunction.hpp"
#endif
#ifndef LUA_TABLE_H
#include "LuaTable.hpp"
#endif

static int test_function(lua_State *L);

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

  LuaAdapter lua{"test.lua"};
  // lua.Debug();

  /**
   * Parameterize your application.
   */
  // get height
  int height{0};
  lua.Get("height", height);
  std::cout << "height: " << height << "\n\n";

  // get an int
  int width{0};
  lua.Get("width", width);
  std::cout << "width: " << width << "\n";

  // get double
  double number{0};
  lua.Get("number", number);
  std::cout << "Number: " << number << "\n";

  // get string
  std::string title{"empty"};
  lua.Get("title", title);
  std::cout << "title: " << title << "\n";

  // get boolean
  bool boolean{false};
  lua.Get("fullscreen", boolean);
  std::cout << "fullscreen: " << (boolean ? "true" : "false") << "\n";

  std::cout << "\n";

  /** - TABLE-TESTS ----------------------------------------------------*/
  LuaTable luaTable{lua};

  if (luaTable.Open("Table1")) {
    int ID{0};
    luaTable.Get("ID", ID);
    std::cout << "ID: " << ID << "\n";

    int Value{0};
    luaTable.Get("Value", Value);
    std::cout << "Value: " << Value << "\n";

    std::string Text{};
    luaTable.Get("Text", Text);
    std::cout << "Text: " << Text << "\n";

    luaTable.Close(); // close "Table1"
  }
  std::cout << "\n";

  if (luaTable.Open("matrix")) {

    // Get the length of the table
    const unsigned short int length{luaTable.Length()};
    std::cout << "Table-length: " << length << "\n";

    for (unsigned char j = 1; j <= length; j++) {
      for (unsigned char i = 1; i <= length; i++) {
        int temp = 0;
        luaTable.Get(j, i, temp); // matrix[j][i]
        std::cout << temp << " ";
      }
      std::cout << "\n";
    }
    luaTable.Close(); // close table "matrix"
  }
  std::cout << "\n";

  if (luaTable.Open("Table2")) {
    int X{0};
    luaTable.Get("X", X);
    std::cout << "X: " << X << "\n";

    int Y{0};
    luaTable.Get("Y", Y);
    std::cout << "Y: " << Y << "\n";

    if (luaTable.Open("Test")) { // open 'nested' table "Test"
      int A = 0;
      luaTable.Get("A", A);
      std::cout << "\t A: " << A << "\n";
      int B = 0;
      luaTable.Get("B", B);
      std::cout << "\t B: " << B << "\n";

      luaTable.Close(); // close nested table "Test"
    }
    luaTable.Close(); // close "Table2"
  }

  if (luaTable.Open("Strings")) {
    std::string k, v;

    // Get string-field by index
    luaTable.Get(1, k);
    luaTable.Get(2, v);

    std::cout << "Key: " << k << "\n";
    std::cout << "Value: " << v << "\n";

    luaTable.Close(); // close "Strings"
  }

  /* ------------------ ------------------------------------------------*/
  // Check lua's internal stack
  std::cout << "\n";
  std::cout << "Lua stack top: " << lua.GetTop() << "\n"; // should be 0

  // let's close ..
  lua.Close();
  // and (re-)initialize for further tests..
  lua.Init();

  /** - FUNCTION-TESTS -------------------------------------------------*/

  LuaFunction luaFunction{lua};
  /**
   * Define a C/C++-function that can be called from lua (see test.lua)
   **/
  luaFunction.Push(test_function, "test_function");
  /**
   * and THEN load the script:
   */
  lua.Load("test.lua");

  /**
   * calling a lua-function
   **/
  luaFunction.Call("test");

  /**
   * calling another lua-function (see test.lua)
   */
  int test[] = {36, 24};
  int result{0};
  luaFunction.Call("gcd", 2, test, result);
  std::cout << "gcd: " << result << "\n";
  std::cout << "\n";

  test_function(nullptr); // this is just to ignore a compile-warning

  return 0;
}

/**
 * This C++-function can be called from Lua
 */
static int test_function(lua_State *L) {
  if (!L)
    return 0;
  LuaAdapter lua{L};
  double number{lua_tonumber(L, 1)}; /* get argument */
  number *= 2;
  lua.Push(number);
  return 1;
}<commit_msg>tiny clean-up<commit_after>/*
 * Copyright (c) 2015-2018 JlnWntr (jlnwntr@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.
 */

#ifndef LUA_ADAPTER_H
#include "LuaAdapter.hpp"
#endif
#ifndef LUA_FUNCTION_H
#include "LuaFunction.hpp"
#endif
#ifndef LUA_TABLE_H
#include "LuaTable.hpp"
#endif

static int test_function(lua_State *L);

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

  LuaAdapter lua{"test.lua"};
  // lua.Debug();

  /**
   * Parameterize your application.
   */
  // get height
  int height{0};
  lua.Get("height", height);
  std::cout << "height: " << height << "\n\n";

  // get an int
  int width{0};
  lua.Get("width", width);
  std::cout << "width: " << width << "\n";

  // get double
  double number{0};
  lua.Get("number", number);
  std::cout << "Number: " << number << "\n";

  // get string
  std::string title{"empty"};
  lua.Get("title", title);
  std::cout << "title: " << title << "\n";

  // get boolean
  bool boolean{false};
  lua.Get("fullscreen", boolean);
  std::cout << "fullscreen: " << (boolean ? "true" : "false") << "\n";
  std::cout << "\n";

  /**
   * Test tables
   **/
  LuaTable luaTable{lua};

  if (luaTable.Open("Table1")) {
    int ID{0};
    luaTable.Get("ID", ID);
    std::cout << "ID: " << ID << "\n";

    int Value{0};
    luaTable.Get("Value", Value);
    std::cout << "Value: " << Value << "\n";

    std::string Text{};
    luaTable.Get("Text", Text);
    std::cout << "Text: " << Text << "\n";

    luaTable.Close(); // close "Table1"
  }
  std::cout << "\n";

  if (luaTable.Open("matrix")) {

    // Get the length of the table
    const unsigned short int length{luaTable.Length()};
    std::cout << "Table-length: " << length << "\n";

    for (unsigned char j = 1; j <= length; j++) {
      for (unsigned char i = 1; i <= length; i++) {
        int temp = 0;
        luaTable.Get(j, i, temp); // matrix[j][i]
        std::cout << temp << " ";
      }
      std::cout << "\n";
    }
    luaTable.Close(); // close table "matrix"
  }
  std::cout << "\n";

  if (luaTable.Open("Table2")) {
    int X{0};
    luaTable.Get("X", X);
    std::cout << "X: " << X << "\n";

    int Y{0};
    luaTable.Get("Y", Y);
    std::cout << "Y: " << Y << "\n";

    if (luaTable.Open("Test")) { // open 'nested' table "Test"
      int A = 0;
      luaTable.Get("A", A);
      std::cout << "\t A: " << A << "\n";
      int B = 0;
      luaTable.Get("B", B);
      std::cout << "\t B: " << B << "\n";

      luaTable.Close(); // close nested table "Test"
    }
    luaTable.Close(); // close "Table2"
  }

  if (luaTable.Open("Strings")) {
    std::string k, v;

    // Get string-field by index
    luaTable.Get(1, k);
    luaTable.Get(2, v);

    std::cout << "Key: " << k << "\n";
    std::cout << "Value: " << v << "\n";

    luaTable.Close(); // close "Strings"
  }

  /** ------------------ ------------------------------------------- **/
  // Check lua's internal stack
  std::cout << "\n";
  std::cout << "Lua stack top: " << lua.GetTop() << "\n"; // should be 0
  lua.Close();// let's close ..
  lua.Init();// and (re-)initialize for further tests..
  /** ------------------ ------------------------------------------- **/

  /**
   * Test function calls
   **/
  LuaFunction luaFunction{lua};

  // Define a C/C++-function that can be called from lua (see test.lua)
  luaFunction.Push(test_function, "test_function");

  // THEN load the script:
  lua.Load("test.lua");

  // call a lua-function
  luaFunction.Call("test");

  // call another lua-function (see test.lua)
  int test[] = {36, 24};
  int result{0};
  luaFunction.Call("gcd", 2, test, result);
  std::cout << "gcd: " << result << "\n";
  std::cout << "\n";

  test_function(nullptr); // this is to ignore a compile-warning
  std::cout << "Test ended!\n";
  return 0;
}

/**
 * This C++-function can be called from Lua
 */
static int test_function(lua_State *L) {
  if (!L)
    return 0;
  LuaAdapter lua{L};
  double number{lua_tonumber(L, 1)};
  number *= 2;
  lua.Push(number);
  return 1;
}<|endoftext|>


<commit_before>#include<string>

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

  return 0;
}
<commit_msg>at 2018年 12月 14日 星期五 22:55:55 PST<commit_after><|endoftext|>


<commit_before>#include "stdafx.h"
#include "stack.hpp"
#ifndef STACK_CPP
#define STACK_CPP

template <typename T>
stack<T>::stack()
{count_=0;
array_size_=1;
array_=new T[array_size_];
}
template <typename T>
size_t stack<T> :: count() const
{
	return count_;
}

template <typename T>
stack<T>::~stack()
{
delete[] array_;
}

template <typename T>
void stack <T> :: push(const T& b)
{
	if(count_==array_size_)
	{array_size_*=2;
	T*l=copy_new(array_,count_,array_size_);
	delete[] array_;
	array_=l;
	l=nullptr;}
	array_[count_]=b;
	count_++;
}
/*template<typename T>
T*stack<T>::copy_new(const T*arr,size_t count,size_t array_size)
{T*l=new T[array_size];
std::copy(arr,arr+count,l);
return;}*/

template<typename T>
stack<T>::top()
{
	if (count_ == 0) {
		throw std::range_error("stack is empty");
	}
	return array_[count_ - 1];
}

template <typename T>
stack<T>& stack<T>::operator=(const stack &b)
{
	array_size_ = b.array_size_;
	count_ = b.count_;
	array_ = new T[array_size_];
	if (this != &b)
	{
		for (size_t i = 0; i < count_; i++)
			array_[i] = b.array_[i];
	}

	return *this;
}

template <typename T>
stack<T>::pop() -> T
{
	if(!count_)
{
 throw "\nSTACK IS EMPTY!";
}

else
{
return array_[count_--];
}
}
template<typename T>
bool stack<T>::operator==(stack const & _s)
{
	if ((_s.count_ != count_) || (_s.array_size_ != array_size_)) {
	return false;
	}
	else {
	for (size_t i = 0; i < count_; i++) {
	if (_s.array_[i] != array_[i]) {
	return false;
	}
	}
	}
	return true;
}

#endif
<commit_msg>Update stack.cpp<commit_after>#include "stack.hpp"
#ifndef STACK_CPP
#define STACK_CPP

template <typename T>
stack<T>::stack()
{count_=0;
array_size_=1;
array_=new T[array_size_];
}
template <typename T>
size_t stack<T> :: count() const
{
	return count_;
}

template <typename T>
stack<T>::~stack()
{
delete[] array_;
}

template <typename T>
void stack <T> :: push(const T& b)
{
	if(count_==array_size_)
	{array_size_*=2;
	T*l=copy_new(array_,count_,array_size_);
	delete[] array_;
	array_=l;
	l=nullptr;}
	array_[count_]=b;
	count_++;
}
/*template<typename T>
T*stack<T>::copy_new(const T*arr,size_t count,size_t array_size)
{T*l=new T[array_size];
std::copy(arr,arr+count,l);
return;}*/

template<typename T>
stack<T>::top()
{
	if (count_ == 0) {
		throw std::range_error("stack is empty");
	}
	return array_[count_ - 1];
}

template <typename T>
stack<T>& stack<T>::operator=(const stack &b)
{
	array_size_ = b.array_size_;
	count_ = b.count_;
	array_ = new T[array_size_];
	if (this != &b)
	{
		for (size_t i = 0; i < count_; i++)
			array_[i] = b.array_[i];
	}

	return *this;
}

template <typename T>
stack<T>::pop() -> T
{
	if(!count_)
{
 throw "\nSTACK IS EMPTY!";
}

else
{
return array_[count_--];
}
}
template<typename T>
bool stack<T>::operator==(stack const & _s)
{
	if ((_s.count_ != count_) || (_s.array_size_ != array_size_)) {
	return false;
	}
	else {
	for (size_t i = 0; i < count_; i++) {
	if (_s.array_[i] != array_[i]) {
	return false;
	}
	}
	}
	return true;
}

#endif
<|endoftext|>


<commit_before>#include <iostream>
using namespace std;
template <typename T>
class stack
{
public:
	stack();
	stack(stack const &);
	~stack();
	size_t count() const;
	auto push(T const &) -> void;
	T pop();
	auto operator=(stack const & right)->stack &;
private:
	T * array_;
	size_t array_size_;
	size_t count_;
};

int main()
{
	stack<int> a;
	a.push(1);
	a.push(2);
	a.push(3);
	stack<int> b;
	b.push(2);
	a = b;
	system("pause");
}

template <typename T>
size_t stack<T>::count() const
{
	return count_;
}
template <typename T>
stack<T>::stack()
{
	array_size_ = 0;
	array_ = new T[array_size_];
	count_ = 0;
}

template<typename T>
stack<T>::stack(stack const & item)
{
	array_size_ = item.array_size_;
	count_ = item.count_;
	T * buff = new T[array_size_];
	copy(array_, array_ + array_size_, buff);
	delete[] array_;
	array_ = buff;
}

template <typename T>
stack<T>::~stack()
{
	delete[] array_;
}

template<typename T>
auto stack<T>::push(T const & item) -> void {
	if (count_ == array_size_) {
		size_t size = array_size_ * 2 + (array_size_ == 0) ;
		T * buff = new T[size];
		copy(array_, array_ + array_size_, buff);
		delete[] array_;
		array_ = buff;
		array_size_ = size;
	}
	++count_;
	array_[count_ - 1] = item;
}

template<typename T>
T stack<T>::pop() {
	if (count_ == 0) {
		throw std::logic_error("Stack is empty!");
	}
	return array_[--count_];
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack & {
	if (this != &right) {
	delete[] array_;
	count_ = right.count_;
	array_size_ = right.array_size_;
	array_ = new T[array_size_];
	copy(right.array_, right.array_ + count_, array_);	}
	return *this;
}
<commit_msg>Update stack.cpp<commit_after>#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
using namespace std;
template <typename T>
class stack
{
public:
	stack();
	stack(stack const &);
	~stack();
	size_t count() const;
	auto push(T const &) -> void;
	T pop();
	auto operator=(stack const & right)->stack &;
private:
	T * array_;
	size_t array_size_;
	size_t count_;
};

int main()
{
	stack<int> a;
	a.push(1);
	a.push(2);
	a.push(3);
	stack<int> b;
	b.push(2);
	a = b;
	system("pause");
}

template <typename T>
size_t stack<T>::count() const
{
	return count_;
}
template <typename T>
stack<T>::stack()
{
	array_size_ = 0;
	array_ = new T[array_size_];
	count_ = 0;
}

template<typename T>
stack<T>::stack(stack const & item)
{
	array_size_ = item.array_size_;
	count_ = item.count_;
	T * buff = new T[array_size_];
	copy(array_, array_ + array_size_, buff);
	delete[] array_;
	array_ = buff;
}

template <typename T>
stack<T>::~stack()
{
	delete[] array_;
}

template<typename T>
auto stack<T>::push(T const & item) -> void {
	if (count_ == array_size_) {
		size_t size = array_size_ * 2 + (array_size_ == 0) ;
		T * buff = new T[size];
		copy(array_, array_ + array_size_, buff);
		delete[] array_;
		array_ = buff;
		array_size_ = size;
	}
	++count_;
	array_[count_ - 1] = item;
}

template<typename T>
T stack<T>::pop() {
	if (count_ == 0) {
		throw std::logic_error("Stack is empty!");
	}
	return array_[--count_];
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack & {
	if (this != &right) {
	delete[] array_;
	count_ = right.count_;
	array_size_ = right.array_size_;
	array_ = new T[array_size_];
	copy(right.array_, right.array_ + count_, array_);	}
	return *this;
}

#endif
<|endoftext|>


<commit_before>#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
using namespace std;
template<typename T>
auto newcopy( const T * item, size_t size, size_t count) -> T*
{
	T * buff = new T[size];
	copy(item, item + count, buff);
	return buff;
}
template <typename T>
class stack
{
public:
	stack();
	stack(stack const &);
	~stack();
	size_t count() const;
	auto push(T const &) -> void;
	T pop();
	auto operator=(stack const & right)->stack &;
private:
	T * array_;
	size_t array_size_;
	size_t count_;
};
template <typename T>
size_t stack<T>::count() const
{
	return count_;
}
template <typename T>
stack<T>::stack():array_size_(0), count_(0), array_(new T[array_size_])
{

}

template<typename T>
stack<T>::stack(stack const & item):array_size_(item.array_size_), count_(item.count_),array_(newcopy(item.array_, item.array_size_,item.count_))
{

}

template <typename T>
stack<T>::~stack()
{
	delete[] array_;
}

template<typename T>
auto stack<T>::push(T const & item) -> void {
	if (count_ == array_size_) {
		size_t size = array_size_ * 2 + (array_size_ == 0) ;
		array_ = newcopy(array_, size, array_size_);
		delete[] array_;
		array_size_ = size;
	}
	array_[count_] = item;
	++count_;
}

template<typename T>
T stack<T>::pop() {
	if (count_ == 0) {
		throw std::logic_error("Stack is empty!");
	}
	return array_[--count_];
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack & {
	if (this != &right) {
	delete[] array_;
	count_ = right.count_;
	array_size_ = right.array_size_;
	newcopy(right.array_, array_size_, count_);
	}
	return *this;
}

#endif
<commit_msg>Update stack.cpp<commit_after>#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
using namespace std;
template<typename T>
auto newcopy( const T * item, size_t size, size_t count) -> T*
{
	T * buff = new T[size];
	copy(item, item + count, buff);
	return buff;
}
template <typename T>
class stack
{
public:
	stack();
	stack(stack const &);
	~stack();
	size_t count() const;
	auto push(T const &) -> void;
	T pop();
	auto operator=(stack const & right)->stack &;
private:
	T * array_;
	size_t array_size_;
	size_t count_;
};
template <typename T>
size_t stack<T>::count() const
{
	return count_;
}
template <typename T>
stack<T>::stack():array_(new T[array_size_], array_size_(0), count_(0))
{

}

template<typename T>
stack<T>::stack(stack const & item):array_size_(item.array_size_), count_(item.count_),array_(newcopy(item.array_, item.array_size_,item.count_))
{

}

template <typename T>
stack<T>::~stack()
{
	delete[] array_;
}

template<typename T>
auto stack<T>::push(T const & item) -> void {
	if (count_ == array_size_) {
		size_t size = array_size_ * 2 + (array_size_ == 0) ;
		array_ = newcopy(array_, size, array_size_);
		delete[] array_;
		array_size_ = size;
	}
	array_[count_] = item;
	++count_;
}

template<typename T>
T stack<T>::pop() {
	if (count_ == 0) {
		throw std::logic_error("Stack is empty!");
	}
	return array_[--count_];
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack & {
	if (this != &right) {
	delete[] array_;
	count_ = right.count_;
	array_size_ = right.array_size_;
	newcopy(right.array_, array_size_, count_);
	}
	return *this;
}

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <stdexcept>

template <typename T>
class stack
{
public:
	stack();
	~stack()noexcept;
	stack(stack<T> const&);
	stack& operator=(stack<T> const&)noexcept;
	size_t count()const noexcept;
	size_t array_size()const noexcept;
	void push(T const&);
	void pop();
	T top()const noexcept;
	void print(std::ostream&stream)const noexcept;
	void swap(stack<T>&)noexcept;
	bool empty()const noexcept;
private:
	T * array_;
	size_t array_size_;
	size_t count_;
};

template <typename T>
stack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}
template <typename T>
stack<T>::~stack()noexcept
{
	delete[] array_;
}
template <typename T>
stack<T>::stack(stack<T> const& other)
{
	array_size_ = other.array_size_;
	count_ = other.count_;
	std::copy(other.array_, other.array_ + count_, array_);
}
template <typename T>
stack<T>& stack<T>::operator=(stack<T> const & other)noexcept
{
	if (&other != this)
		stack(other).swap(*this);
	return *this;
}
template <typename T>
size_t stack<T>::array_size()const noexcept
{
	return array_size_;
}
template <typename T>
size_t stack<T>::count()const noexcept
{
	return count_;
}
template <typename T>
void stack<T>::push(T const & value)
{
	if (empty())
	{
		array_size_ = 1;
		array_ = new T[array_size_]();
	}
	else if (array_size_ == count_)
	{
		array_size_ *= 2;
		T * new_array = new T[array_size_]();
		std::copy(array_, array_ + count_, new_array);
		delete[] array_;
		array_ = new_array;
	}
	array_[count_++] = value;
}
template <typename T>
void stack<T>::pop()
{
	if (empty())
		throw std::logic_error("Stack is empty");
	else
	{
		T * new_array = new T[array_size_]();
		--count_;
		std::copy(array_, array_ + count_, new_array);
		delete[] array_;
		array_ = new_array;
	}
}
template <typename T>
T stack<T>::top()const noexcept
{
	if (empty())
		throw std::logic_error("Stack is empty");
	else return array_[count_ - 1];
}
template <typename T>
void stack<T>::print(std::ostream&stream)const noexcept
{
	for (unsigned int i = 0; i < count_; ++i)
		stream << array_[i] << " ";
	stream << std::endl;
}
template <typename T>
void stack<T>::swap(stack<T>& other)noexcept
{
	std::swap(array_, other.array_);
	std::swap(array_size_, other.array_size_);
	std::swap(count_, other.count_);
}
template <typename T>
bool stack<T>::empty()const noexcept
{
	return (count_ == 0);
}
<commit_msg>Update stack.hpp<commit_after>#include <iostream>
#include <algorithm>
#include <stdexcept>

template <typename T>
class stack
{
public:
	stack();
	~stack()/*noexcept*/;
	stack(stack<T> const&)/*basic*/;
	stack& operator=(stack<T> const&)/*basic*/;
	size_t count()const /*noexcept*/;
	size_t array_size()const /*noexcept*/;
	void push(T const&)/*basic*/;
	void pop()/*strong*/;
	T top()const /*strong*/;
	void print(std::ostream&stream)const /*noexcept*/;
	void swap(stack<T>&)/*noexcept*/;
	bool empty()const /*noexcept*/;
private:
	T * array_;
	size_t array_size_;
	size_t count_;
};

template <typename T>
stack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}
template <typename T>
stack<T>::~stack()noexcept
{
	delete[] array_;
}
template <typename T>
stack<T>::stack(stack<T> const& other)
{
	array_size_ = other.array_size_;
	count_ = other.count_;
	std::copy(other.array_, other.array_ + count_, array_);
}
template <typename T>
stack<T>& stack<T>::operator=(stack<T> const & other)noexcept
{
	if (&other != this)
		stack(other).swap(*this);
	return *this;
}
template <typename T>
size_t stack<T>::array_size()const noexcept
{
	return array_size_;
}
template <typename T>
size_t stack<T>::count()const noexcept
{
	return count_;
}
template <typename T>
void stack<T>::push(T const & value)
{
	if (empty())
	{
		array_size_ = 1;
		array_ = new T[array_size_]();
	}
	else if (array_size_ == count_)
	{
		array_size_ *= 2;
		T * new_array = new T[array_size_]();
		std::copy(array_, array_ + count_, new_array);
		delete[] array_;
		array_ = new_array;
	}
	array_[count_++] = value;
}
template <typename T>
void stack<T>::pop()
{
	if (empty())
		throw std::logic_error("Stack is empty");
	else
	{
		T * new_array = new T[array_size_]();
		--count_;
		std::copy(array_, array_ + count_, new_array);
		delete[] array_;
		array_ = new_array;
	}
}
template <typename T>
T stack<T>::top()const noexcept
{
	if (empty())
		throw std::logic_error("Stack is empty");
	else return array_[count_ - 1];
}
template <typename T>
void stack<T>::print(std::ostream&stream)const noexcept
{
	for (unsigned int i = 0; i < count_; ++i)
		stream << array_[i] << " ";
	stream << std::endl;
}
template <typename T>
void stack<T>::swap(stack<T>& other)noexcept
{
	std::swap(array_, other.array_);
	std::swap(array_size_, other.array_size_);
	std::swap(count_, other.count_);
}
template <typename T>
bool stack<T>::empty()const noexcept
{
	return (count_ == 0);
}
<|endoftext|>


<commit_before>#include "Param.h"

namespace Halide {

void OutputImageParam::add_implicit_args_if_placeholder(std::vector<Expr> &args,
                                                        Expr last_arg,
                                                        int total_args,
                                                        bool *placeholder_seen) const {
    const Internal::Variable *var = last_arg.as<Internal::Variable>();
    bool is_placeholder = var && Var::is_placeholder(var->name);
    if (is_placeholder) {
        user_assert(!(*placeholder_seen))
            << "Only one implicit placeholder ('_') allowed in argument list for ImageParam " << name() << "\n";
        *placeholder_seen = true;

        // The + 1 in the conditional is because one provided argument is an placeholder
        for (int i = 0; i < (dimensions() - total_args + 1); i++) {
            args.push_back(Var::implicit(i));
        }
    } else {
        args.push_back(last_arg);
    }
}

OutputImageParam::OutputImageParam(const Internal::Parameter &p) :
    param(p) {
}

OutputImageParam::~OutputImageParam() {
}

const std::string &OutputImageParam::name() const {
    return param.name();
}

Type OutputImageParam::type() const {
    return param.type();
}

bool OutputImageParam::defined() {
    return param.defined();
}

Expr OutputImageParam::min(int x) const {
    std::ostringstream s;
    s << name() << ".min." << x;
    return Internal::Variable::make(Int(32), s.str(), param);
}

Expr OutputImageParam::extent(int x) const {
    std::ostringstream s;
    s << name() << ".extent." << x;
    return Internal::Variable::make(Int(32), s.str(), param);
}

Expr OutputImageParam::stride(int x) const {
    std::ostringstream s;
    s << name() << ".stride." << x;
    return Internal::Variable::make(Int(32), s.str(), param);
}

OutputImageParam &OutputImageParam::set_extent(int dim, Expr extent) {
    param.set_extent_constraint(dim, extent);
    return *this;
}

OutputImageParam &OutputImageParam::set_min(int dim, Expr min) {
    param.set_min_constraint(dim, min);
    return *this;
}

OutputImageParam &OutputImageParam::set_stride(int dim, Expr stride) {
    param.set_stride_constraint(dim, stride);
    return *this;
}

OutputImageParam &OutputImageParam::set_bounds(int dim, Expr min, Expr extent) {
    return set_min(dim, min).set_extent(dim, extent);
}

int OutputImageParam::dimensions() const {
    return param.dimensions();
}

Expr OutputImageParam::left() const {
    user_assert(dimensions() > 0) << "Can't ask for the left of a zero-dimensional image\n";
    return min(0);
}

Expr OutputImageParam::right() const {
    user_assert(dimensions() > 0) << "Can't ask for the right of a zero-dimensional image\n";
    return Internal::Add::make(min(0), Internal::Sub::make(extent(0), 1));
}

Expr OutputImageParam::top() const {
    user_assert(dimensions() > 1) << "Can't ask for the top of a zero- or one-dimensional image\n";
    return min(1);
}

Expr OutputImageParam::bottom() const {
    user_assert(dimensions() > 1) << "Can't ask for the bottom of a zero- or one-dimensional image\n";
    return Internal::Add::make(min(1), Internal::Sub::make(extent(1), 1));
}

Expr OutputImageParam::width() const {
    user_assert(dimensions() > 0) << "Can't ask for the width of a zero-dimensional image\n";
    return extent(0);
}

Expr OutputImageParam::height() const {
    user_assert(dimensions() > 1) << "Can't ask for the height of a zero or one-dimensional image\n";
    return extent(1);
}

Expr OutputImageParam::channels() const {
    user_assert(dimensions() > 2) << "Can't ask for the channels of an image with fewer than three dimensions\n";
    return extent(2);
}

Internal::Parameter OutputImageParam::parameter() const {
    return param;
}

OutputImageParam::operator Argument() const {
    return Argument(name(), Argument::OutputBuffer, type(), dimensions());
}

OutputImageParam::operator ExternFuncArgument() const {
    return param;
}

ImageParam::ImageParam(Type t, int d) :
    OutputImageParam(Internal::Parameter(t, true, d, Internal::make_entity_name(this, "Halide::ImageParam", 'p'))) {}

ImageParam::ImageParam(Type t, int d, const std::string &n) :
    OutputImageParam(Internal::Parameter(t, true, d, n, /* is_explicit_name */ true)) {
    // Discourage future Funcs from having the same name
    Internal::unique_name(n);
}

ImageParam::~ImageParam() {
}

void ImageParam::set(Buffer b) {
    if (b.defined()) {
        user_assert(b.type() == type())
            << "Can't bind ImageParam " << name()
            << " of type " << type()
            << " to Buffer " << b.name()
            << " of type " << b.type() << "\n";
    }
    param.set_buffer(b);
}

Buffer ImageParam::get() const {
    return param.get_buffer();
}

Expr ImageParam::operator()() const {
    user_assert(dimensions() == 0)
        << "Zero-argument access to Buffer " << name()
        << ", which has " << dimensions() << "dimensions.\n";
    std::vector<Expr> args;
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(Expr x) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    add_implicit_args_if_placeholder(args, x, 1, &placeholder_seen);

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(Expr x, Expr y) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    add_implicit_args_if_placeholder(args, x, 2, &placeholder_seen);
    add_implicit_args_if_placeholder(args, y, 2, &placeholder_seen);

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(Expr x, Expr y, Expr z) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    add_implicit_args_if_placeholder(args, x, 3, &placeholder_seen);
    add_implicit_args_if_placeholder(args, y, 3, &placeholder_seen);
    add_implicit_args_if_placeholder(args, z, 3, &placeholder_seen);

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(Expr x, Expr y, Expr z, Expr w) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    add_implicit_args_if_placeholder(args, x, 4, &placeholder_seen);
    add_implicit_args_if_placeholder(args, y, 4, &placeholder_seen);
    add_implicit_args_if_placeholder(args, z, 4, &placeholder_seen);
    add_implicit_args_if_placeholder(args, w, 4, &placeholder_seen);

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(std::vector<Expr> args_passed) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    for (size_t i = 0; i < args_passed.size(); i++) {
        add_implicit_args_if_placeholder(args, args_passed[i],
                                         args_passed.size(), &placeholder_seen);
    }

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(std::vector<Var> args_passed) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    for (size_t i = 0; i < args_passed.size(); i++) {
        add_implicit_args_if_placeholder(args, args_passed[i],
                                         args_passed.size(), &placeholder_seen);
    }

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

ImageParam::operator Argument() const {
    return Argument(name(), Argument::InputBuffer, type(), dimensions());
}

}
<commit_msg>bool OutputImageParam::defined() => bool OutputImageParam::defined() const<commit_after>#include "Param.h"

namespace Halide {

void OutputImageParam::add_implicit_args_if_placeholder(std::vector<Expr> &args,
                                                        Expr last_arg,
                                                        int total_args,
                                                        bool *placeholder_seen) const {
    const Internal::Variable *var = last_arg.as<Internal::Variable>();
    bool is_placeholder = var && Var::is_placeholder(var->name);
    if (is_placeholder) {
        user_assert(!(*placeholder_seen))
            << "Only one implicit placeholder ('_') allowed in argument list for ImageParam " << name() << "\n";
        *placeholder_seen = true;

        // The + 1 in the conditional is because one provided argument is an placeholder
        for (int i = 0; i < (dimensions() - total_args + 1); i++) {
            args.push_back(Var::implicit(i));
        }
    } else {
        args.push_back(last_arg);
    }
}

OutputImageParam::OutputImageParam(const Internal::Parameter &p) :
    param(p) {
}

OutputImageParam::~OutputImageParam() {
}

const std::string &OutputImageParam::name() const {
    return param.name();
}

Type OutputImageParam::type() const {
    return param.type();
}

bool OutputImageParam::defined() const {
    return param.defined();
}

Expr OutputImageParam::min(int x) const {
    std::ostringstream s;
    s << name() << ".min." << x;
    return Internal::Variable::make(Int(32), s.str(), param);
}

Expr OutputImageParam::extent(int x) const {
    std::ostringstream s;
    s << name() << ".extent." << x;
    return Internal::Variable::make(Int(32), s.str(), param);
}

Expr OutputImageParam::stride(int x) const {
    std::ostringstream s;
    s << name() << ".stride." << x;
    return Internal::Variable::make(Int(32), s.str(), param);
}

OutputImageParam &OutputImageParam::set_extent(int dim, Expr extent) {
    param.set_extent_constraint(dim, extent);
    return *this;
}

OutputImageParam &OutputImageParam::set_min(int dim, Expr min) {
    param.set_min_constraint(dim, min);
    return *this;
}

OutputImageParam &OutputImageParam::set_stride(int dim, Expr stride) {
    param.set_stride_constraint(dim, stride);
    return *this;
}

OutputImageParam &OutputImageParam::set_bounds(int dim, Expr min, Expr extent) {
    return set_min(dim, min).set_extent(dim, extent);
}

int OutputImageParam::dimensions() const {
    return param.dimensions();
}

Expr OutputImageParam::left() const {
    user_assert(dimensions() > 0) << "Can't ask for the left of a zero-dimensional image\n";
    return min(0);
}

Expr OutputImageParam::right() const {
    user_assert(dimensions() > 0) << "Can't ask for the right of a zero-dimensional image\n";
    return Internal::Add::make(min(0), Internal::Sub::make(extent(0), 1));
}

Expr OutputImageParam::top() const {
    user_assert(dimensions() > 1) << "Can't ask for the top of a zero- or one-dimensional image\n";
    return min(1);
}

Expr OutputImageParam::bottom() const {
    user_assert(dimensions() > 1) << "Can't ask for the bottom of a zero- or one-dimensional image\n";
    return Internal::Add::make(min(1), Internal::Sub::make(extent(1), 1));
}

Expr OutputImageParam::width() const {
    user_assert(dimensions() > 0) << "Can't ask for the width of a zero-dimensional image\n";
    return extent(0);
}

Expr OutputImageParam::height() const {
    user_assert(dimensions() > 1) << "Can't ask for the height of a zero or one-dimensional image\n";
    return extent(1);
}

Expr OutputImageParam::channels() const {
    user_assert(dimensions() > 2) << "Can't ask for the channels of an image with fewer than three dimensions\n";
    return extent(2);
}

Internal::Parameter OutputImageParam::parameter() const {
    return param;
}

OutputImageParam::operator Argument() const {
    return Argument(name(), Argument::OutputBuffer, type(), dimensions());
}

OutputImageParam::operator ExternFuncArgument() const {
    return param;
}

ImageParam::ImageParam(Type t, int d) :
    OutputImageParam(Internal::Parameter(t, true, d, Internal::make_entity_name(this, "Halide::ImageParam", 'p'))) {}

ImageParam::ImageParam(Type t, int d, const std::string &n) :
    OutputImageParam(Internal::Parameter(t, true, d, n, /* is_explicit_name */ true)) {
    // Discourage future Funcs from having the same name
    Internal::unique_name(n);
}

ImageParam::~ImageParam() {
}

void ImageParam::set(Buffer b) {
    if (b.defined()) {
        user_assert(b.type() == type())
            << "Can't bind ImageParam " << name()
            << " of type " << type()
            << " to Buffer " << b.name()
            << " of type " << b.type() << "\n";
    }
    param.set_buffer(b);
}

Buffer ImageParam::get() const {
    return param.get_buffer();
}

Expr ImageParam::operator()() const {
    user_assert(dimensions() == 0)
        << "Zero-argument access to Buffer " << name()
        << ", which has " << dimensions() << "dimensions.\n";
    std::vector<Expr> args;
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(Expr x) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    add_implicit_args_if_placeholder(args, x, 1, &placeholder_seen);

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(Expr x, Expr y) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    add_implicit_args_if_placeholder(args, x, 2, &placeholder_seen);
    add_implicit_args_if_placeholder(args, y, 2, &placeholder_seen);

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(Expr x, Expr y, Expr z) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    add_implicit_args_if_placeholder(args, x, 3, &placeholder_seen);
    add_implicit_args_if_placeholder(args, y, 3, &placeholder_seen);
    add_implicit_args_if_placeholder(args, z, 3, &placeholder_seen);

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(Expr x, Expr y, Expr z, Expr w) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    add_implicit_args_if_placeholder(args, x, 4, &placeholder_seen);
    add_implicit_args_if_placeholder(args, y, 4, &placeholder_seen);
    add_implicit_args_if_placeholder(args, z, 4, &placeholder_seen);
    add_implicit_args_if_placeholder(args, w, 4, &placeholder_seen);

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(std::vector<Expr> args_passed) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    for (size_t i = 0; i < args_passed.size(); i++) {
        add_implicit_args_if_placeholder(args, args_passed[i],
                                         args_passed.size(), &placeholder_seen);
    }

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

Expr ImageParam::operator()(std::vector<Var> args_passed) const {
    std::vector<Expr> args;
    bool placeholder_seen = false;
    for (size_t i = 0; i < args_passed.size(); i++) {
        add_implicit_args_if_placeholder(args, args_passed[i],
                                         args_passed.size(), &placeholder_seen);
    }

    Internal::check_call_arg_types(name(), &args, dimensions());
    return Internal::Call::make(param, args);
}

ImageParam::operator Argument() const {
    return Argument(name(), Argument::InputBuffer, type(), dimensions());
}

}
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

template <typename T>
class stack
{
public:
	stack();/*noexept*/
	stack(const stack<T> &);/*strong*/
	size_t count() const; /*noexcept*/
	void print()const;/*noexcept*/
	void push(T const &); /*strong*/
	void swap(stack<T>&); /*noexcept*/
	auto pop()->std::shared_ptr<T>; /*strong*/
	T top(); /*strong*/
	bool empty() const; /*noexcept*/
	stack<T>& operator=(stack<T> &); /*noexcept*/
	~stack();/*noexcept*/
private:
	T * array_;
	mutable std::mutex mutex_;
	size_t array_size_;
	size_t count_;
};

template <typename T>
stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr }
{}

template<class T>
stack<T>::~stack()
{
	count_ = 0;
	array_size_ = 0;
	delete[] array_;
}

template <typename T>
stack<T>::stack(const stack<T>& copy)
{
	std::lock_guard<std::mutex> lock(mutex_);
	T *tmp = new T[copy.array_size_];
	count_ = copy.count_;
	array_size_ = copy.array_size_;
	array_ = tmp;
	if(array_ == nullptr){
		throw "error";
		delete[] array_;
	}
	std::copy(copy.array_, copy.array_ + count_, array_);
}

template<class T>
size_t stack<T>::count() const
{
	std::lock_guard<std::mutex> lock(mutex_);
	return count_;
}

template <typename T>
bool stack<T>::empty() const
{
	return (count_ == 0);
}

template<typename T>
void stack<T>::swap(stack& x)
{
	other.mutex_.lock();
	std::swap(x.array_size_, array_size_);
	std::swap(count_, x.count_);
	std::swap(x.array_, array_);
	other.mutex_.unlock();
}

template <typename T>
T stack<T>::top()
{
	if (empty())
	{
		throw "Stack is empty!";
	}
	return array_[count_ - 1];
}

template <typename T>
void stack<T>::push(T const &value)
{
	mutex_.lock();
	if (array_size_ == count_)
	{
		array_size_ *= 2;
		stack<T> temp(*this);
		swap(temp);
	}
	array_[count_] = value;
	++count_;
	mutex_.unlock();
}

template <typename T>
auto stack<T>::pop() -> std::shared_ptr<T>
{
	std::lock_guard<std::mutex> lock(mutex_);
	if (empty())
		throw "Stack is empty" ;
	count_--;
}

template <typename T>
void stack<T>::print() const
{
	for (int i = 0; i < array_size_; i++)
		cout << array_[i];
}

template<typename T>
stack<T>& stack<T>::operator=(stack<T> & other)
{
	std::lock_guard<std::mutex> lock(obj.mutex_);
	if (this != &other)
	{
		stack<T> tmp(other);
		tmp.swap(*this);
	}
	return *this;
}
<commit_msg>Update stack.hpp<commit_after>#include <iostream>
#include <mutex>
#include <thread>
#include <memory>

using namespace std;

template <typename T>
class stack
{
public:
	stack();/*noexept*/
	stack(const stack<T> &);/*strong*/
	size_t count() const; /*noexcept*/
	void print()const;/*noexcept*/
	void push(T const &); /*strong*/
	void swap(stack<T>&); /*noexcept*/
	auto pop()->std::shared_ptr<T>; /*strong*/
	T top(); /*strong*/
	bool empty() const; /*noexcept*/
	stack<T>& operator=(stack<T> &); /*noexcept*/
	~stack();/*noexcept*/
private:
	T * array_;
	mutable std::mutex mutex_;
	size_t array_size_;
	size_t count_;
};

template <typename T>
stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr }
{}

template<class T>
stack<T>::~stack()
{
	count_ = 0;
	array_size_ = 0;
	delete[] array_;
}

template <typename T>
stack<T>::stack(const stack<T>& copy)
{
	std::lock_guard<std::mutex> lock(mutex_);
	T *tmp = new T[copy.array_size_];
	count_ = copy.count_;
	array_size_ = copy.array_size_;
	array_ = tmp;
	if(array_ == nullptr){
		throw "error";
		delete[] array_;
	}
	std::copy(copy.array_, copy.array_ + count_, array_);
}

template<class T>
size_t stack<T>::count() const
{
	std::lock_guard<std::mutex> lock(mutex_);
	return count_;
}

template <typename T>
bool stack<T>::empty() const
{
	return (count_ == 0);
}

template<typename T>
void stack<T>::swap(stack& x)
{
	other.mutex_.lock();
	std::swap(x.array_size_, array_size_);
	std::swap(count_, x.count_);
	std::swap(x.array_, array_);
	other.mutex_.unlock();
}

template <typename T>
T stack<T>::top()
{
	if (empty())
	{
		throw "Stack is empty!";
	}
	return array_[count_ - 1];
}

template <typename T>
void stack<T>::push(T const &value)
{
	mutex_.lock();
	if (array_size_ == count_)
	{
		array_size_ *= 2;
		stack<T> temp(*this);
		swap(temp);
	}
	array_[count_] = value;
	++count_;
	mutex_.unlock();
}

template <typename T>
auto stack<T>::pop() -> std::shared_ptr<T>
{
	std::lock_guard<std::mutex> lock(mutex_);
	if (empty())
		throw "Stack is empty" ;
	count_--;
}

template <typename T>
void stack<T>::print() const
{
	for (int i = 0; i < array_size_; i++)
		cout << array_[i];
}

template<typename T>
stack<T>& stack<T>::operator=(stack<T> & other)
{
	std::lock_guard<std::mutex> lock(obj.mutex_);
	if (this != &other)
	{
		stack<T> tmp(other);
		tmp.swap(*this);
	}
	return *this;
}
<|endoftext|>


<commit_before>#include <Pixel.h>

#define PIXEL WalrusRPG::Graphics::Pixel
#define GRAPHICS WalrusRPG::Graphics

PIXEL::Pixel(std::uint16_t color) : value(color) {

}

PIXEL::Pixel(Pixel &pix) : value((std::uint8_t)pix) {

}

PIXEL::Pixel(std::uint8_t red, std::uint8_t green, std::uint8_t blue) : r(red>>3), g(green>>2), b(blue>>3) {

}

PIXEL::operator std::uint16_t() const {
  return value;
}

PIXEL& PIXEL::operator=(unsigned value) {
  this->value = value;
	return *this;
}

const PIXEL GRAPHICS::Black(0, 0, 0);
const PIXEL GRAPHICS::White(255, 255, 255);
const PIXEL GRAPHICS::Red(255, 0, 0);
const PIXEL GRAPHICS::Green(0, 255, 0);
const PIXEL GRAPHICS::Blue(0, 0, 255);
<commit_msg>X-macro based palette definition<commit_after>#include <Pixel.h>

#define PIXEL WalrusRPG::Graphics::Pixel

PIXEL::Pixel(std::uint16_t color) : value(color) {

}

PIXEL::Pixel(Pixel &pix) : value((std::uint8_t)pix) {

}

PIXEL::Pixel(std::uint8_t red, std::uint8_t green, std::uint8_t blue) : r(red>>3), g(green>>2), b(blue>>3) {

}

PIXEL::operator std::uint16_t() const {
  return value;
}

PIXEL& PIXEL::operator=(unsigned value) {
  this->value = value;
	return *this;
}

#define CONST_COLOR(color, r, g, b) const WalrusRPG::Graphics::Pixel WalrusRPG::Graphics::color(r, g, b)
CONST_COLOR(Black, 0, 0, 0);
CONST_COLOR(White, 255, 255, 255);
CONST_COLOR(Red, 255, 0, 0);
CONST_COLOR(Green, 0, 255, 0);
CONST_COLOR(Blue, 0, 0, 255);
#undef CONST_COLOR
<|endoftext|>


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

  Program:   Visualization Library
  Module:    PtLoad.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "PtLoad.hh"
#include "vtkMath.hh"
#include "FTensors.hh"

// Description:
// Construct with ModelBounds=(-1,1,-1,1,-1,1), SampleDimensions=(50,50,50),
// and LoadValue = 1.
vtkPointLoad::vtkPointLoad()
{
 this->LoadValue = 1.0;

  this->ModelBounds[0] = -1.0;
  this->ModelBounds[1] = 1.0;
  this->ModelBounds[2] = -1.0;
  this->ModelBounds[3] = 1.0;
  this->ModelBounds[4] = -1.0;
  this->ModelBounds[5] = 1.0;

  this->SampleDimensions[0] = 50;
  this->SampleDimensions[1] = 50;
  this->SampleDimensions[2] = 50;
}

// Description:
// Specify the dimensions of the volume. A stress tensor will be computed for
// each point in the volume.
void vtkPointLoad::SetSampleDimensions(int i, int j, int k)
{
  int dim[3];

  dim[0] = i;
  dim[1] = j;
  dim[2] = k;

  this->SetSampleDimensions(dim);
}

// Description:
// Specify the dimensions of the volume. A stress tensor will be computed for
// each point in the volume.
void vtkPointLoad::SetSampleDimensions(int dim[3])
{
  vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")");

  if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] ||
  dim[2] != SampleDimensions[2] )
    {
    for ( int i=0; i<3; i++)
      this->SampleDimensions[i] = (dim[i] > 0 ? dim[i] : 1);
    this->Modified();
    }
}

// Description:
// Specify the region in space over which the tensors are computed. The point
// load is assumed to be applied at top center of the volume.
void vtkPointLoad::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)
{
  if (this->ModelBounds[0] != xmin || this->ModelBounds[1] != xmax ||
  this->ModelBounds[2] != ymin || this->ModelBounds[3] != ymax ||
  this->ModelBounds[4] != zmin || this->ModelBounds[5] != zmax )
    {
    this->Modified();
    this->ModelBounds[0] = xmin;
    this->ModelBounds[1] = xmax;
    this->ModelBounds[2] = ymin;
    this->ModelBounds[3] = ymax;
    this->ModelBounds[4] = zmin;
    this->ModelBounds[5] = zmax;
    }
}

// Description:
// Specify the region in space over which the tensors are computed. The point
// load is assumed to be applied at top center of the volume.
void vtkPointLoad::SetModelBounds(float *bounds)
{
  vtkPointLoad::SetModelBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);
}

void vtkPointLoad::Execute()
{
  int ptId, i, j, k;
  vtkFloatTensors *newTensors;
  vtkTensor tensor;
  int numPts;
  vtkMath math;
  float P, pi, twoPi, xP[3], rho, rho2, rho3, rho5, nu;
  float x, x2, y, y2, z, z2, z3, rhoPlusz2, zPlus2rho, txy, txz, tyz;

  vtkDebugMacro(<< "Computing point load stress tensors");
//
// Initialize self; create output objects
//
  this->Initialize();

  numPts = this->SampleDimensions[0] * this->SampleDimensions[1]
           * this->SampleDimensions[2];
  newTensors = new vtkFloatTensors(numPts);

  // Compute origin and aspect ratio
  this->SetDimensions(this->GetSampleDimensions());
  for (i=0; i < 3; i++)
    {
    this->Origin[i] = this->ModelBounds[2*i];
    this->AspectRatio[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i])
                           / (this->SampleDimensions[i] - 1);
    }
//
// Compute the location of the load
//
  xP[0] = (this->ModelBounds[0] + this->ModelBounds[1]) / 2.0; //in center
  xP[1] = (this->ModelBounds[2] + this->ModelBounds[3]) / 2.0;
  xP[2] = this->ModelBounds[5]; // at top of box
//
// Traverse all points evaluating implicit function at each point
//
  twoPi = 2.0*math.Pi();
  P = -this->LoadValue;

  for (k=0; k<this->Dimensions[2]; k++)
    {
    z = this->Origin[2] + k*this->AspectRatio[2];
    for (j=0; j<this->Dimensions[1]; j++)
      {
      y = this->Origin[1] + k*this->AspectRatio[1];
      for (i=0; i<this->Dimensions[0]; i++)
        {
        x = this->Origin[0] + k*this->AspectRatio[0];
        rho = sqrt((x-xP[0])*(x-xP[0]) + (y-xP[1])*(y-xP[1]) +
                   (z-xP[2])*(z-xP[2]));
        if ( rho < 1.0e-10 )
          {
          vtkWarningMacro(<<"Attempting to set singularity, resetting");
          tensor.SetComponent(0,0,LARGE_FLOAT);
          tensor.SetComponent(1,1,LARGE_FLOAT);
          tensor.SetComponent(2,2,LARGE_FLOAT);
          tensor.SetComponent(0,1,0.0);
          tensor.SetComponent(0,2,0.0);
          tensor.SetComponent(1,0,0.0);
          tensor.SetComponent(1,2,0.0);
          tensor.SetComponent(2,0,0.0);
          tensor.SetComponent(2,1,0.0);
          newTensors->InsertNextTensor(tensor);
          continue;
          }

        rho2 = rho*rho;
        rho3 = rho2*rho;
        rho5 = rho2*rho3;
        nu = (1.0 - 2.0*this->PoissonsRatio);
        x2 = x*x;
        y2 = y*y;
        rhoPlusz2 = (rho + z) * (rho + z);
        zPlus2rho = (2.0*rho + z);

        // normal stresses
        tensor.SetComponent(0,0, P/(twoPi*rho2) * (3.0*z*x2/rho3 -
                     nu*(z/rho - rho/(rho+z) + x2*(zPlus2rho)/(rho*rhoPlusz2))));
        tensor.SetComponent(1,1, P/(twoPi*rho2) * (3.0*z*y2/rho3 -
                     nu*(z/rho - rho/(rho+z) + y2*(zPlus2rho)/(rho*rhoPlusz2))));
        tensor.SetComponent(2,2, 3.0*P*z3/(twoPi*rho5));

        //shear stresses
        txy = P/(twoPi*rho2) * (3.0*x*y*z/rho3 -
                                nu*x*y*(zPlus2rho)/(rho*rhoPlusz2));

        tensor.SetComponent(0,1,txy);
        tensor.SetComponent(1,0,txy);

        txz = 3.0*P*x*z2/(twoPi*rho5);
        tensor.SetComponent(0,2,txz);
        tensor.SetComponent(2,0,txz);

        tyz = 3.0*P*y*z2/(twoPi*rho5);
        tensor.SetComponent(1,2,tyz);
        tensor.SetComponent(2,1,tyz);

        newTensors->InsertNextTensor(tensor);
        }
      }
    }
//
// Update self
//
  this->PointData.SetTensors(newTensors);
}

void vtkPointLoad::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkStructuredPointsSource::PrintSelf(os,indent);

  os << indent << "Load Value: " << this->LoadValue << "\n";
  os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", "
               << this->SampleDimensions[1] << ", "
               << this->SampleDimensions[2] << ")\n";
  os << indent << "ModelBounds: \n";
  os << indent << "  Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n";
  os << indent << "  Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n";
  os << indent << "  Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n";
  os << indent << "Poisson's Ratio: " << this->PoissonsRatio << "\n";

}

<commit_msg>*** empty log message ***<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    PtLoad.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "PtLoad.hh"
#include "vtkMath.hh"
#include "FTensors.hh"

// Description:
// Construct with ModelBounds=(-1,1,-1,1,-1,1), SampleDimensions=(50,50,50),
// and LoadValue = 1.
vtkPointLoad::vtkPointLoad()
{
 this->LoadValue = 1.0;

  this->ModelBounds[0] = -1.0;
  this->ModelBounds[1] = 1.0;
  this->ModelBounds[2] = -1.0;
  this->ModelBounds[3] = 1.0;
  this->ModelBounds[4] = -1.0;
  this->ModelBounds[5] = 1.0;

  this->SampleDimensions[0] = 50;
  this->SampleDimensions[1] = 50;
  this->SampleDimensions[2] = 50;
}

// Description:
// Specify the dimensions of the volume. A stress tensor will be computed for
// each point in the volume.
void vtkPointLoad::SetSampleDimensions(int i, int j, int k)
{
  int dim[3];

  dim[0] = i;
  dim[1] = j;
  dim[2] = k;

  this->SetSampleDimensions(dim);
}

// Description:
// Specify the dimensions of the volume. A stress tensor will be computed for
// each point in the volume.
void vtkPointLoad::SetSampleDimensions(int dim[3])
{
  vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")");

  if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] ||
  dim[2] != SampleDimensions[2] )
    {
    for ( int i=0; i<3; i++)
      this->SampleDimensions[i] = (dim[i] > 0 ? dim[i] : 1);
    this->Modified();
    }
}

// Description:
// Specify the region in space over which the tensors are computed. The point
// load is assumed to be applied at top center of the volume.
void vtkPointLoad::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)
{
  if (this->ModelBounds[0] != xmin || this->ModelBounds[1] != xmax ||
  this->ModelBounds[2] != ymin || this->ModelBounds[3] != ymax ||
  this->ModelBounds[4] != zmin || this->ModelBounds[5] != zmax )
    {
    this->Modified();
    this->ModelBounds[0] = xmin;
    this->ModelBounds[1] = xmax;
    this->ModelBounds[2] = ymin;
    this->ModelBounds[3] = ymax;
    this->ModelBounds[4] = zmin;
    this->ModelBounds[5] = zmax;
    }
}

// Description:
// Specify the region in space over which the tensors are computed. The point
// load is assumed to be applied at top center of the volume.
void vtkPointLoad::SetModelBounds(float *bounds)
{
  vtkPointLoad::SetModelBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);
}

void vtkPointLoad::Execute()
{
  int ptId, i, j, k;
  vtkFloatTensors *newTensors;
  vtkTensor tensor;
  int numPts;
  vtkMath math;
  float P, pi, twoPi, xP[3], rho, rho2, rho3, rho5, nu;
  float x, x2, y, y2, z, z2, z3, rhoPlusz2, zPlus2rho, txy, txz, tyz;

  vtkDebugMacro(<< "Computing point load stress tensors");
//
// Initialize self; create output objects
//
  this->Initialize();

  numPts = this->SampleDimensions[0] * this->SampleDimensions[1]
           * this->SampleDimensions[2];
  newTensors = new vtkFloatTensors(numPts);

  // Compute origin and aspect ratio
  this->SetDimensions(this->GetSampleDimensions());
  for (i=0; i < 3; i++)
    {
    this->Origin[i] = this->ModelBounds[2*i];
    this->AspectRatio[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i])
                           / (this->SampleDimensions[i] - 1);
    }
//
// Compute the location of the load
//
  xP[0] = (this->ModelBounds[0] + this->ModelBounds[1]) / 2.0; //in center
  xP[1] = (this->ModelBounds[2] + this->ModelBounds[3]) / 2.0;
  xP[2] = this->ModelBounds[5]; // at top of box
//
// Traverse all points evaluating implicit function at each point
//
  twoPi = 2.0*math.Pi();
  P = -this->LoadValue;

  for (k=0; k<this->Dimensions[2]; k++)
    {
    z = this->Origin[2] + k*this->AspectRatio[2];
    for (j=0; j<this->Dimensions[1]; j++)
      {
      y = this->Origin[1] + j*this->AspectRatio[1];
      for (i=0; i<this->Dimensions[0]; i++)
        {
        x = this->Origin[0] + i*this->AspectRatio[0];
        rho = sqrt((x-xP[0])*(x-xP[0]) + (y-xP[1])*(y-xP[1]) +
                   (z-xP[2])*(z-xP[2]));
        if ( rho < 1.0e-10 )
          {
          vtkWarningMacro(<<"Attempting to set singularity, resetting");
          tensor.SetComponent(0,0,LARGE_FLOAT);
          tensor.SetComponent(1,1,LARGE_FLOAT);
          tensor.SetComponent(2,2,LARGE_FLOAT);
          tensor.SetComponent(0,1,0.0);
          tensor.SetComponent(0,2,0.0);
          tensor.SetComponent(1,0,0.0);
          tensor.SetComponent(1,2,0.0);
          tensor.SetComponent(2,0,0.0);
          tensor.SetComponent(2,1,0.0);
          newTensors->InsertNextTensor(tensor);
          continue;
          }

        rho2 = rho*rho;
        rho3 = rho2*rho;
        rho5 = rho2*rho3;
        nu = (1.0 - 2.0*this->PoissonsRatio);
        x2 = x*x;
        y2 = y*y;
        rhoPlusz2 = (rho + z) * (rho + z);
        zPlus2rho = (2.0*rho + z);

        // normal stresses
        tensor.SetComponent(0,0, P/(twoPi*rho2) * (3.0*z*x2/rho3 -
                     nu*(z/rho - rho/(rho+z) + x2*(zPlus2rho)/(rho*rhoPlusz2))));
        tensor.SetComponent(1,1, P/(twoPi*rho2) * (3.0*z*y2/rho3 -
                     nu*(z/rho - rho/(rho+z) + y2*(zPlus2rho)/(rho*rhoPlusz2))));
        tensor.SetComponent(2,2, 3.0*P*z3/(twoPi*rho5));

        //shear stresses
        txy = P/(twoPi*rho2) * (3.0*x*y*z/rho3 -
                                nu*x*y*(zPlus2rho)/(rho*rhoPlusz2));

        tensor.SetComponent(0,1,txy);
        tensor.SetComponent(1,0,txy);

        txz = 3.0*P*x*z2/(twoPi*rho5);
        tensor.SetComponent(0,2,txz);
        tensor.SetComponent(2,0,txz);

        tyz = 3.0*P*y*z2/(twoPi*rho5);
        tensor.SetComponent(1,2,tyz);
        tensor.SetComponent(2,1,tyz);

        newTensors->InsertNextTensor(tensor);
        }
      }
    }
//
// Update self
//
  this->PointData.SetTensors(newTensors);
}

void vtkPointLoad::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkStructuredPointsSource::PrintSelf(os,indent);

  os << indent << "Load Value: " << this->LoadValue << "\n";
  os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", "
               << this->SampleDimensions[1] << ", "
               << this->SampleDimensions[2] << ")\n";
  os << indent << "ModelBounds: \n";
  os << indent << "  Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n";
  os << indent << "  Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n";
  os << indent << "  Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n";
  os << indent << "Poisson's Ratio: " << this->PoissonsRatio << "\n";

}

<|endoftext|>


<commit_before>#include <phpcpp.h>
#include <stdlib.h>
#include <stdio.h>
#include "Rsync.hpp"

extern "C" {
#include <librsync.h>
}

/**
 * rs_result rs_sig_file (FILE *old_file, FILE *sig_file, size_t block_len, size_t strong_len, rs_stats_t *)
 */
void php_sig_file(Php::Parameters & params) {
    int32_t block_len = 1;
    int32_t strong_len = 2;

    /* TODO
    if (params[2] != nullptr) {
        block_len = params[2];
    }

    if (params[3] != nullptr) {
        strong_len = params[3];
    }
    */

    FILE *old_file;
    old_file = fopen(params[0], "r");

    FILE *sig_file;
    sig_file = fopen(params[1], "w+");

    rs_result res = rs_sig_file(old_file, sig_file, block_len, strong_len, NULL);

    fclose(old_file);
    fclose(sig_file);

    if (res != 0) {
        throw Php::Exception(rs_strerror(res), res);
    }
}

/**
 * rs_result rs_loadsig_file (FILE *sig_file, rs_signature_t **, rs_stats_t *)
 * rs_result rs_delta_file (rs_signature_t *, FILE *new_file, FILE *delta_file, rs_stats_t *)
*/
void php_delta_file(Php::Parameters & params) {
    rs_signature_t *signature;
    rs_result res;

    FILE *sig_file;
    sig_file = fopen(params[0], "r");

    res = rs_loadsig_file(sig_file, &signature, NULL);

    if (res != 0) {
        fclose(sig_file);
        throw Php::Exception(rs_strerror(res), res);
    }

    FILE *new_file;
    new_file = fopen(params[1], "r");

    FILE *delta_file;
    delta_file = fopen(params[2], "w+");

    rs_build_hash_table(signature);
    res = rs_delta_file(signature, new_file, delta_file, NULL);

    fclose(new_file);
    fclose(sig_file);
    fclose(delta_file);

    if (res != 0) {
        throw Php::Exception(rs_strerror(res), res);
    }
}

/**
 * rs_result rs_patch_file (FILE *basis_file, FILE *delta_file, FILE *new_file, rs_stats_t *)
 */
void php_patch_file(Php::Parameters & params) {
    FILE *basis_file;
    basis_file = fopen(params[0], "r");

    FILE *delta_file;
    delta_file = fopen(params[1], "r");

    FILE *new_file;
    new_file = fopen(params[2], "w+");

    rs_result res = rs_patch_file(basis_file, delta_file, new_file, NULL);

    fclose(basis_file);
    fclose(new_file);
    fclose(delta_file);

    if (res != 0) {
        throw Php::Exception(rs_strerror(res), res);
    }
}
<commit_msg>changed default values<commit_after>#include <phpcpp.h>
#include <stdlib.h>
#include <stdio.h>
#include "Rsync.hpp"

extern "C" {
#include <librsync.h>
}

/**
 * rs_result rs_sig_file (FILE *old_file, FILE *sig_file, size_t block_len, size_t strong_len, rs_stats_t *)
 */
void php_sig_file(Php::Parameters & params) {
    // TODO load from ini file

    int32_t block_len = 1024;
    int32_t strong_len = 8;

    FILE *old_file;
    old_file = fopen(params[0], "r");

    FILE *sig_file;
    sig_file = fopen(params[1], "w+");

    rs_result res = rs_sig_file(old_file, sig_file, block_len, strong_len, NULL);

    fclose(old_file);
    fclose(sig_file);

    if (res != 0) {
        throw Php::Exception(rs_strerror(res), res);
    }
}

/**
 * rs_result rs_loadsig_file (FILE *sig_file, rs_signature_t **, rs_stats_t *)
 * rs_result rs_delta_file (rs_signature_t *, FILE *new_file, FILE *delta_file, rs_stats_t *)
*/
void php_delta_file(Php::Parameters & params) {
    rs_signature_t *signature;
    rs_result res;

    FILE *sig_file;
    sig_file = fopen(params[0], "r");

    res = rs_loadsig_file(sig_file, &signature, NULL);

    if (res != 0) {
        fclose(sig_file);
        throw Php::Exception(rs_strerror(res), res);
    }

    FILE *new_file;
    new_file = fopen(params[1], "r");

    FILE *delta_file;
    delta_file = fopen(params[2], "w+");

    rs_build_hash_table(signature);
    res = rs_delta_file(signature, new_file, delta_file, NULL);

    fclose(new_file);
    fclose(sig_file);
    fclose(delta_file);

    if (res != 0) {
        throw Php::Exception(rs_strerror(res), res);
    }
}

/**
 * rs_result rs_patch_file (FILE *basis_file, FILE *delta_file, FILE *new_file, rs_stats_t *)
 */
void php_patch_file(Php::Parameters & params) {
    FILE *basis_file;
    basis_file = fopen(params[0], "r");

    FILE *delta_file;
    delta_file = fopen(params[1], "r");

    FILE *new_file;
    new_file = fopen(params[2], "w+");

    rs_result res = rs_patch_file(basis_file, delta_file, new_file, NULL);

    fclose(basis_file);
    fclose(new_file);
    fclose(delta_file);

    if (res != 0) {
        throw Php::Exception(rs_strerror(res), res);
    }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2015 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "BindTransport.h"
#include "Server.h"
#include "ShortMacros.h"
#include "WorkerManager.h"

namespace RAMCloud {
/**
 * Constructor for Server: binds a configuration to a Server, but doesn't
 * start anything up yet.
 *
 * \param context
 *      Overall information about the RAMCloud server.  Note: if caller
 *      has not provided a serverList here, then we will.  This method
 *      will store information about the master and backup services in
 *      this context.
 * \param config
 *      Specifies which services and their configuration details for
 *      when the Server is run.
 */
Server::Server(Context* context, const ServerConfig* config)
    : context(context)
    , config(*config)
    , backupReadSpeed()
    , serverId()
    , serverList(NULL)
    , failureDetector()
    , master()
    , backup()
    , membership()
    , ping()
    , enlistTimer()
{
    context->coordinatorSession->setLocation(
            config->coordinatorLocator.c_str(), config->clusterName.c_str());
    context->workerManager = new WorkerManager(context, config->maxCores-1);
}

/**
 * Destructor for Server.
 */
Server::~Server()
{
    delete serverList;
}

/**
 * Create services according to #config, enlist with the coordinator and
 * then return. This method should almost exclusively be used by MockCluster
 * and is only useful for unit testing.  Production code should always use
 * run() instead.
 *
 * \param bindTransport
 *      The BindTransport to register on to listen for rpcs during unit
 *      testing.
 */
void
Server::startForTesting(BindTransport& bindTransport)
{
    ServerId formerServerId = createAndRegisterServices();
    bindTransport.registerServer(context, config.localLocator);
    enlist(formerServerId);
}

/**
 * Create services according to #config and enlist with the coordinator.
 * Either call this method or startForTesting(), not both.  Loops
 * forever calling Dispatch::poll() to serve requests.
 */
void
Server::run()
{
    LOG(NOTICE, "Starting services");
    ServerId formerServerId = createAndRegisterServices();
    LOG(NOTICE, "Services started");

    // Only pin down memory _after_ users of LargeBlockOfMemory have
    // obtained their allocations (since LBOM probes are much slower if
    // the memory needs to be pinned during mmap).
    LOG(NOTICE, "Pinning memory");
    pinAllMemory();
    LOG(NOTICE, "Memory pinned");

    // The following statement suppresses a "long gap" message that would
    // otherwise be generated by the next call to dispatch.poll (the
    // warning is benign, and is caused by the time to benchmark secondary
    // storage above.
    Dispatch& dispatch = *context->dispatch;
    dispatch.currentTime = Cycles::rdtsc();

    // Enlist only once all expensive initialization has been done.
    // In particular, we must not enlist until we have mmapped all of the
    // log and hash table memory and have registered any regions with the NIC
    // (if appropriate). These large virtual memory operations can block
    // the entire process for seconds at a time, so we must not be expected
    // to handle RPCs until we're confident such hiccups won't occur.
    // Even so, some of the work that has to be done after enlistment takes
    // significant amounts of time, so execute the enlistment in a worker
    // thread. That way, this thread can enter the dispatcher and start
    // servicing requests.
    enlistTimer.construct(this, formerServerId);

    dispatch.run();
}

// - private -

/**
 * Create each of the services which are marked as active in config.services,
 * configure them according to #config, and register them.
 *
 * \return
 *      If this server is rejoining a cluster its former server id is returned,
 *      otherwise an invalid server is returned.  "Rejoining" means the backup
 *      service on this server may have segment replicas stored that were
 *      created by masters in the cluster.  In this case, the coordinator must
 *      be told of the former server id under which these replicas were
 *      created to ensure correct garbage collection of the stored replicas.
 */
ServerId
Server::createAndRegisterServices()
{
    ServerId formerServerId;

    if (config.services.has(WireFormat::COORDINATOR_SERVICE)) {
        DIE("Server class is not capable of running the CoordinatorService "
            "(yet).");
    }

    // If a serverList was already provided in the context, then use it;
    // otherwise, create a new one.
    if (context->serverList == NULL) {
        serverList = new ServerList(context);
    }

    if (config.services.has(WireFormat::MASTER_SERVICE)) {
        LOG(NOTICE, "Master is using %u backups", config.master.numReplicas);
        master.construct(context, &config);
    }

    if (config.services.has(WireFormat::BACKUP_SERVICE)) {
        LOG(NOTICE, "Starting backup service");
        backup.construct(context, &config);
        formerServerId = backup->getFormerServerId();
        backupReadSpeed = backup->getReadSpeed();
        LOG(NOTICE, "Backup service started");
    }

    if (config.services.has(WireFormat::MEMBERSHIP_SERVICE)) {
        membership.construct(context,
                             static_cast<ServerList*>(context->serverList),
                             &config);
    }

    if (config.services.has(WireFormat::PING_SERVICE)) {
        ping.construct(context);
    }

    return formerServerId;
}

/**
 * Enlist the Server with the coordinator, notify all services of the ServerId
 * assigned by the coordinator, and start the failure detector if it is enabled
 * in #config.
 *
 * \param replacingId
 *      If this server has found replicas on storage written by a now-defunct
 *      server then the backup must report the server id that formerly owned
 *      those replicas upon enlistment. This is used to ensure that all
 *      servers in the cluster know of the crash of the old server which
 *      created the replicas before a new server enters the cluster
 *      attempting to reuse those replicas.  This property is used as part
 *      of the backup's replica garbage collection routines.
 */
void
Server::enlist(ServerId replacingId)
{
    // Enlist with the coordinator just before dedicating this thread
    // to rpc dispatch. This reduces the window of being unavailable to
    // service rpcs after enlisting with the coordinator (which can
    // lead to session open timeouts).
    LOG(NOTICE, "Enlisting with cooordinator");
    serverId = CoordinatorClient::enlistServer(context,
                                               config.preferredIndex,
                                               replacingId,
                                               config.services,
                                               config.localLocator,
                                               backupReadSpeed);
    LOG(NOTICE, "Enlisted; serverId %s", serverId.toString().c_str());

    if (master)
        master->setServerId(serverId);
    if (backup)
        backup->setServerId(serverId);
    if (membership)
        membership->setServerId(serverId);
    if (ping)
        ping->setServerId(serverId);

    if (config.detectFailures) {
        failureDetector.construct(context, serverId);
        failureDetector->start();
    }
}

} // namespace RAMCloud
<commit_msg>Perform post-initialization work on PingService first<commit_after>/* Copyright (c) 2012-2015 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "BindTransport.h"
#include "Server.h"
#include "ShortMacros.h"
#include "WorkerManager.h"

namespace RAMCloud {
/**
 * Constructor for Server: binds a configuration to a Server, but doesn't
 * start anything up yet.
 *
 * \param context
 *      Overall information about the RAMCloud server.  Note: if caller
 *      has not provided a serverList here, then we will.  This method
 *      will store information about the master and backup services in
 *      this context.
 * \param config
 *      Specifies which services and their configuration details for
 *      when the Server is run.
 */
Server::Server(Context* context, const ServerConfig* config)
    : context(context)
    , config(*config)
    , backupReadSpeed()
    , serverId()
    , serverList(NULL)
    , failureDetector()
    , master()
    , backup()
    , membership()
    , ping()
    , enlistTimer()
{
    context->coordinatorSession->setLocation(
            config->coordinatorLocator.c_str(), config->clusterName.c_str());
    context->workerManager = new WorkerManager(context, config->maxCores-1);
}

/**
 * Destructor for Server.
 */
Server::~Server()
{
    delete serverList;
}

/**
 * Create services according to #config, enlist with the coordinator and
 * then return. This method should almost exclusively be used by MockCluster
 * and is only useful for unit testing.  Production code should always use
 * run() instead.
 *
 * \param bindTransport
 *      The BindTransport to register on to listen for rpcs during unit
 *      testing.
 */
void
Server::startForTesting(BindTransport& bindTransport)
{
    ServerId formerServerId = createAndRegisterServices();
    bindTransport.registerServer(context, config.localLocator);
    enlist(formerServerId);
}

/**
 * Create services according to #config and enlist with the coordinator.
 * Either call this method or startForTesting(), not both.  Loops
 * forever calling Dispatch::poll() to serve requests.
 */
void
Server::run()
{
    LOG(NOTICE, "Starting services");
    ServerId formerServerId = createAndRegisterServices();
    LOG(NOTICE, "Services started");

    // Only pin down memory _after_ users of LargeBlockOfMemory have
    // obtained their allocations (since LBOM probes are much slower if
    // the memory needs to be pinned during mmap).
    LOG(NOTICE, "Pinning memory");
    pinAllMemory();
    LOG(NOTICE, "Memory pinned");

    // The following statement suppresses a "long gap" message that would
    // otherwise be generated by the next call to dispatch.poll (the
    // warning is benign, and is caused by the time to benchmark secondary
    // storage above.
    Dispatch& dispatch = *context->dispatch;
    dispatch.currentTime = Cycles::rdtsc();

    // Enlist only once all expensive initialization has been done.
    // In particular, we must not enlist until we have mmapped all of the
    // log and hash table memory and have registered any regions with the NIC
    // (if appropriate). These large virtual memory operations can block
    // the entire process for seconds at a time, so we must not be expected
    // to handle RPCs until we're confident such hiccups won't occur.
    // Even so, some of the work that has to be done after enlistment takes
    // significant amounts of time, so execute the enlistment in a worker
    // thread. That way, this thread can enter the dispatcher and start
    // servicing requests.
    enlistTimer.construct(this, formerServerId);

    dispatch.run();
}

// - private -

/**
 * Create each of the services which are marked as active in config.services,
 * configure them according to #config, and register them.
 *
 * \return
 *      If this server is rejoining a cluster its former server id is returned,
 *      otherwise an invalid server is returned.  "Rejoining" means the backup
 *      service on this server may have segment replicas stored that were
 *      created by masters in the cluster.  In this case, the coordinator must
 *      be told of the former server id under which these replicas were
 *      created to ensure correct garbage collection of the stored replicas.
 */
ServerId
Server::createAndRegisterServices()
{
    ServerId formerServerId;

    if (config.services.has(WireFormat::COORDINATOR_SERVICE)) {
        DIE("Server class is not capable of running the CoordinatorService "
            "(yet).");
    }

    // If a serverList was already provided in the context, then use it;
    // otherwise, create a new one.
    if (context->serverList == NULL) {
        serverList = new ServerList(context);
    }

    if (config.services.has(WireFormat::MASTER_SERVICE)) {
        LOG(NOTICE, "Master is using %u backups", config.master.numReplicas);
        master.construct(context, &config);
    }

    if (config.services.has(WireFormat::BACKUP_SERVICE)) {
        LOG(NOTICE, "Starting backup service");
        backup.construct(context, &config);
        formerServerId = backup->getFormerServerId();
        backupReadSpeed = backup->getReadSpeed();
        LOG(NOTICE, "Backup service started");
    }

    if (config.services.has(WireFormat::MEMBERSHIP_SERVICE)) {
        membership.construct(context,
                             static_cast<ServerList*>(context->serverList),
                             &config);
    }

    if (config.services.has(WireFormat::PING_SERVICE)) {
        ping.construct(context);
    }

    return formerServerId;
}

/**
 * Enlist the Server with the coordinator, notify all services of the ServerId
 * assigned by the coordinator, and start the failure detector if it is enabled
 * in #config.
 *
 * \param replacingId
 *      If this server has found replicas on storage written by a now-defunct
 *      server then the backup must report the server id that formerly owned
 *      those replicas upon enlistment. This is used to ensure that all
 *      servers in the cluster know of the crash of the old server which
 *      created the replicas before a new server enters the cluster
 *      attempting to reuse those replicas.  This property is used as part
 *      of the backup's replica garbage collection routines.
 */
void
Server::enlist(ServerId replacingId)
{
    // Enlist with the coordinator just before dedicating this thread
    // to rpc dispatch. This reduces the window of being unavailable to
    // service rpcs after enlisting with the coordinator (which can
    // lead to session open timeouts).
    LOG(NOTICE, "Enlisting with cooordinator");
    serverId = CoordinatorClient::enlistServer(context,
                                               config.preferredIndex,
                                               replacingId,
                                               config.services,
                                               config.localLocator,
                                               backupReadSpeed);
    LOG(NOTICE, "Enlisted; serverId %s", serverId.toString().c_str());

    // Finish PingService initialization first, so that the getServerId
    // RPC will work; otherwise, no one can open connections to us.
    if (ping)
        ping->setServerId(serverId);
    if (master)
        master->setServerId(serverId);
    if (backup)
        backup->setServerId(serverId);
    if (membership)
        membership->setServerId(serverId);

    if (config.detectFailures) {
        failureDetector.construct(context, serverId);
        failureDetector->start();
    }
}

} // namespace RAMCloud
<|endoftext|>


<commit_before>/*
 * Store.cpp
 *
 *  Created on: 24 de may. de 2015
 *      Author: carlos
 */

#include "Store.h"
#include <sstream>
#include <cassert>
#include <iomanip>

namespace event {

using grpc::ServerContext;
using grpc::Status;
using grpc::ServerWriter;

using namespace std;
using namespace common;

Store::Store() : m_context(redisConnect("127.0.0.1", 6379)){
	assert(m_context != nullptr);
	assert(!m_context->err);
}

Store::~Store(){
	redisFree(m_context);
}

void Store::on_receive(const char * msg) {
	Event event{};
	if (event.ParseFromString(string{msg})){
		event.aggregate_id();
		event.serialized_data();
	}
}

Status Store::get_events(ServerContext* context, const Uuid* request, ServerWriter<Event>* writer)
{
	return Status::OK;
}

void Store::add_event(Event & evt)
{
	redisCommand(m_context, "SET key:%s %s", to_str(evt.aggregate_id()).c_str(), evt.serialized_data().c_str());

}

auto convert_to_hex = [] (stringstream & stream, int64_t l) { stream << setfill('0') << setw(16) << hex << l; };

string Store::to_str(const Uuid & uuid)
{
	// 8-4-4-4-12
	stringstream stream;
	convert_to_hex(stream, uuid.most_significant_bits());
	convert_to_hex(stream, uuid.least_significant_bits());
	string result( stream.str() );
	for (int i=0; i<4; i++)
	{
		result.insert(8 + (i * 4) + i, 1, '-');
	}
	return result;
}

}
<commit_msg>storing events in a list per key aggregate<commit_after>/*
 * Store.cpp
 *
 *  Created on: 24 de may. de 2015
 *      Author: carlos
 */

#include "Store.h"
#include <sstream>
#include <cassert>
#include <iomanip>

namespace event {

using grpc::ServerContext;
using grpc::Status;
using grpc::ServerWriter;

using namespace std;
using namespace common;

Store::Store() : m_context(redisConnect("127.0.0.1", 6379)){
	assert(m_context != nullptr);
	assert(!m_context->err);
}

Store::~Store(){
	redisFree(m_context);
}

void Store::on_receive(const char * msg) {
	Event event{};
	if (event.ParseFromString(string{msg})){
		event.aggregate_id();
		event.serialized_data();
	}
}

Status Store::get_events(ServerContext* context, const Uuid* request, ServerWriter<Event>* writer)
{
	return Status::OK;
}

void Store::add_event(Event & evt)
{
	//redisReply * reply = redisCommand(m_context, "SET key:%s %s", to_str(evt.aggregate_id()).c_str(), evt.serialized_data().c_str());

	redisReply * reply = redisCommand(m_context, "RPUSH key:%s %s", to_str(evt.aggregate_id()).c_str(), evt.serialized_data().c_str());

	cout << reply->str << endl;
    freeReplyObject(reply);

}

auto convert_to_hex = [] (stringstream & stream, int64_t l) { stream << setfill('0') << setw(16) << hex << l; };

string Store::to_str(const Uuid & uuid)
{
	// 8-4-4-4-12
	stringstream stream;
	convert_to_hex(stream, uuid.most_significant_bits());
	convert_to_hex(stream, uuid.least_significant_bits());
	string result( stream.str() );
	for (int i=0; i<4; i++)
	{
		result.insert(8 + (i * 4) + i, 1, '-');
	}
	return result;
}

}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <sstream>

template<typename T>
std::string to_s(const T& t)
{
    std::ostringstream ss;
    ss << t;
    return ss.str();
}

// Based upon http://stackoverflow.com/a/10168511
template<>
std::string to_s<cv::Mat>(const cv::Mat& m)
{
    std::ostringstream ss("Matrix: ");

    int type = m.type();

    // Channel type
    switch(type & CV_MAT_DEPTH_MASK) {
        case CV_8U:  ss << "8U"; break;
        case CV_8S:  ss << "8S"; break;
        case CV_16U: ss << "16U"; break;
        case CV_16S: ss << "16S"; break;
        case CV_32S: ss << "32S"; break;
        case CV_32F: ss << "32F"; break;
        case CV_64F: ss << "64F"; break;
        default:     ss << "User"; break;
    }

    // Channel count
    ss << "C" << 1 + (type >> CV_CN_SHIFT);

    // Size
    ss << " " << m.cols << "x" << m.rows;

    // Min/Max
    double min, max;
    minMaxIdx(m, &min, &max);
    ss << " values in [" << min << ".." << max << "]";

    return ss.str();
}

<commit_msg>Fixed a linking error.<commit_after>#pragma once

#include <string>
#include <sstream>

template<typename T>
std::string to_s(const T& t)
{
    std::ostringstream ss;
    ss << t;
    return ss.str();
}

// Based upon http://stackoverflow.com/a/10168511
template<>
inline std::string to_s<cv::Mat>(const cv::Mat& m)
{
    std::ostringstream ss("Matrix: ");

    int type = m.type();

    // Channel type
    switch(type & CV_MAT_DEPTH_MASK) {
        case CV_8U:  ss << "8U"; break;
        case CV_8S:  ss << "8S"; break;
        case CV_16U: ss << "16U"; break;
        case CV_16S: ss << "16S"; break;
        case CV_32S: ss << "32S"; break;
        case CV_32F: ss << "32F"; break;
        case CV_64F: ss << "64F"; break;
        default:     ss << "User"; break;
    }

    // Channel count
    ss << "C" << 1 + (type >> CV_CN_SHIFT);

    // Size
    ss << " " << m.cols << "x" << m.rows;

    // Min/Max
    double min, max;
    minMaxIdx(m, &min, &max);
    ss << " values in [" << min << ".." << max << "]";

    return ss.str();
}

<|endoftext|>


<commit_before>/*-------------FDTD.cpp-------------------------------------------------------//
*
*              Finite Difference Time Domain
*
* Purpose: To replicate the results of our invisible lense raytracer with
*          FDTD. Woo!
*
*   Notes: Most of this is coming from the following link:
*             http://www.eecs.wsu.edu/~schneidj/ufdtd/chap3.pdf
*
*-----------------------------------------------------------------------------*/

#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>

static const size_t space = 200;

struct Loss{
    std::vector <double> EzH = std::vector<double>(space * space, 0),
                         EzE = std::vector<double>(space * space, 0),
                         HyE = std::vector<double>(space * space, 0),
                         HyH = std::vector<double>(space * space, 0),
                         HxE = std::vector<double>(space * space, 0),
                         HxH = std::vector<double>(space * space, 0);
};

struct Field{
    std::vector <double> Hx = std::vector<double>(space * space, 0),
                         Hy = std::vector<double>(space * space, 0),
                         Ez = std::vector<double>(space * space, 0);
};

#define EzH(i, j) EzH[(i) + (j) *  space]
#define EzE(i, j) EzE[(i) + (j) *  space]
#define HyH(i, j) HyH[(i) + (j) *  space]
#define HyE(i, j) HyE[(i) + (j) *  space]
#define HxH(i, j) HxH[(i) + (j) *  space]
#define HxE(i, j) HxE[(i) + (j) *  space]
#define Hx(i, j) Hx[(i) + (j) *  space]
#define Hy(i, j) Hy[(i) + (j) *  space]
#define Ez(i, j) Ez[(i) + (j) *  space]

void FDTD(Field EM,
          const int final_time, const double eps, const int space, Loss lass,
          std::ofstream& output);

/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/

int main(){

    // defines output
    std::ofstream output("FDTD.dat", std::ofstream::out);

    int space = 200, final_time = 500;
    double eps = 377.0;

    Loss lass;

    // define initial E and H fields
    // std::vector<double> Ez(space, 0.0), Hy(space, 0.0);
    Field EM;

    FDTD(EM, final_time, eps, space, lass, output);

}

/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/

// This is the function we writs the bulk of the code in
void FDTD(Field EM,
          const int final_time, const double eps, const int space, Loss lass,
          std::ofstream& output){

    // For magnetic field:
    // double offset = 0.00005;

    // for electric field:
    double offset = 0.05;
    double loss = 0.0;

    // Relative permittivity
    for (int dx = 0; dx < space; dx++){
        for (int dy = 0; dy < space; dy++){
            if (dx > 100 && dx < 150){
                lass.EzH(dx, dy) =  eps / 9.0 /(1.0 - loss);
                lass.EzE(dx, dy) = (1.0 - loss) / (1.0 + loss);
                lass.HyH(dx, dy) = (1.0 - loss) / (1.0 + loss);
                lass.HyE(dx, dy) = (1.0 / eps) / (1.0 + loss);
                lass.HxE(dx, dy) = (1.0 / eps) / (1.0 + loss);
                lass.HxH(dx, dy) = (1.0 - loss) / (1.0 + loss);
            }
            else{
                lass.EzH(dx, dy) =  eps;
                lass.EzE(dx, dy) = 1.0;
                lass.HyH(dx, dy) = 1.0;
                lass.HyE(dx, dy) = (1.0 / eps);
                lass.HxE(dx, dy) = (1.0 / eps);
                lass.HxH(dx, dy) = 1.0;
            }
        }
    }

    // Time looping
    for (int t = 0; t < final_time; t++){

        // Linking the final two elements for an ABC
        // Hy[space - 1] = Hy[space - 2];

        // update magnetic field, y direction
        for (int dx = 0; dx < space - 1; dx++){
            for (int dy = 0; dy < space; dy++){
               EM.Hy(dx,dy) = lass.HyH(dx,dy) * EM.Hy(dx,dy)
                           + lass.HyE(dx,dy) * (EM.Ez(dx + 1,dy)
                                                - EM.Ez(dx,dy));
            }
        }

        // update magnetic field, x direction
        for (int dx = 0; dx < space; dx++){
            for (int dy = 0; dy < space - 1; dy++){
               EM.Hx(dx,dy) = lass.HxH(dx,dy) * EM.Hx(dx, dy)
                           + lass.HxE(dx,dy) * (EM.Ez(dx + 1,dy)
                                                - EM.Ez(dx,dy));
            }
        }

        // Correction to the H field for the TFSF boundary
        // Hy[49] -= exp(-(t - 40.) * (t - 40.)/100.0) / eps;
        // Hy[49] -= sin((t-10.0)*0.2)*0.0005;

        // Linking the first two elements in the electric field
        EM.Ez[0] = EM.Ez[1];
        // Ez[space - 1] = Ez[space - 2];

        // update electric field
        for (int dx = 0; dx < space - 1; dx++){
            for (int dy = 0; dy < space - 1; dy++){
               EM.Ez(dx,dy) = lass.EzE(dx,dy) * EM.Ez(dx,dy)
                           + lass.EzH[dx] * (EM.Hy(dx, dy)
                                             - EM.Hy(dx-1, dy)
                                             - EM.Hx(dx,dy)
                                             - EM.Hx(dx, dy - 1));
            }
        }

        // set src for next step
        EM.Ez[0] += exp(-((t + 1 - 40.) * (t + 1 - 40.))/100.0);

        // Ez[50] += sin((t - 10.0 + 1)*0.2)*0.0005;
/*
        if (t > 0){
            Ez[50] = sin(0.1 * t) / (0.1 * t);
        }
        else{
            Ez[50] = 1;
        }
*/
        if (t % 10 == 0){
            for (int dx = 0; dx < space; dx++){
                for (int dy = 0; dy < space; dy++){
                    output << t << EM.Ez(dx, dy) << '\n';
                    //output << Ez(dx,dy) + (t * offset) << '\n';
                    //output << Hy[dx] + (t * offset) << '\n';
                }
            }

            output << '\n' << '\n';
        }

    }
}
<commit_msg>Still not outputting data correctly, but it is running in the 2d case! woo!<commit_after>/*-------------FDTD.cpp-------------------------------------------------------//
*
*              Finite Difference Time Domain
*
* Purpose: To replicate the results of our invisible lense raytracer with
*          FDTD. Woo!
*
*   Notes: Most of this is coming from the following link:
*             http://www.eecs.wsu.edu/~schneidj/ufdtd/chap3.pdf
*
*-----------------------------------------------------------------------------*/

#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>

static const size_t space = 200;

struct Loss{
    std::vector <double> EzH = std::vector<double>(space * space, 0),
                         EzE = std::vector<double>(space * space, 0),
                         HyE = std::vector<double>(space * space, 0),
                         HyH = std::vector<double>(space * space, 0),
                         HxE = std::vector<double>(space * space, 0),
                         HxH = std::vector<double>(space * space, 0);
};

struct Field{
    std::vector <double> Hx = std::vector<double>(space * space, 0),
                         Hy = std::vector<double>(space * space, 0),
                         Ez = std::vector<double>(space * space, 0);
};

#define EzH(i, j) EzH[(i) + (j) *  space]
#define EzE(i, j) EzE[(i) + (j) *  space]
#define HyH(i, j) HyH[(i) + (j) *  space]
#define HyE(i, j) HyE[(i) + (j) *  space]
#define HxH(i, j) HxH[(i) + (j) *  space]
#define HxE(i, j) HxE[(i) + (j) *  space]
#define Hx(i, j) Hx[(i) + (j) *  space]
#define Hy(i, j) Hy[(i) + (j) *  space]
#define Ez(i, j) Ez[(i) + (j) *  space]

void FDTD(Field EM,
          const int final_time, const double eps, const int space, Loss lass,
          std::ofstream& output);

/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/

int main(){

    // defines output
    std::ofstream output("FDTD.dat", std::ofstream::out);

    int space = 200, final_time = 500;
    double eps = 377.0;

    Loss lass;

    // define initial E and H fields
    // std::vector<double> Ez(space, 0.0), Hy(space, 0.0);
    Field EM;

    FDTD(EM, final_time, eps, space, lass, output);

}

/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/

// This is the function we writs the bulk of the code in
void FDTD(Field EM,
          const int final_time, const double eps, const int space, Loss lass,
          std::ofstream& output){

    // For magnetic field:
    // double offset = 0.00005;

    // for electric field:
    double offset = 0.05;
    double loss = 0.0;

    // Relative permittivity
    for (int dx = 0; dx < space; dx++){
        for (int dy = 0; dy < space; dy++){
            if (dx > 100 && dx < 150){
                lass.EzH(dx, dy) =  eps / 9.0 /(1.0 - loss);
                lass.EzE(dx, dy) = (1.0 - loss) / (1.0 + loss);
                lass.HyH(dx, dy) = (1.0 - loss) / (1.0 + loss);
                lass.HyE(dx, dy) = (1.0 / eps) / (1.0 + loss);
                lass.HxE(dx, dy) = (1.0 / eps) / (1.0 + loss);
                lass.HxH(dx, dy) = (1.0 - loss) / (1.0 + loss);
            }
            else{
                lass.EzH(dx, dy) =  eps;
                lass.EzE(dx, dy) = 1.0;
                lass.HyH(dx, dy) = 1.0;
                lass.HyE(dx, dy) = (1.0 / eps);
                lass.HxE(dx, dy) = (1.0 / eps);
                lass.HxH(dx, dy) = 1.0;
            }
        }
    }

    // Time looping
    for (int t = 0; t < final_time; t++){

        // Linking the final two elements for an ABC
        // Hy[space - 1] = Hy[space - 2];

        // update magnetic field, y direction
        for (int dx = 0; dx < space - 1; dx++){
            for (int dy = 0; dy < space; dy++){
               EM.Hy(dx,dy) = lass.HyH(dx,dy) * EM.Hy(dx,dy)
                           + lass.HyE(dx,dy) * (EM.Ez(dx + 1,dy)
                                                - EM.Ez(dx,dy));
            }
        }

        // update magnetic field, x direction
        for (int dx = 0; dx < space; dx++){
            for (int dy = 0; dy < space - 1; dy++){
               EM.Hx(dx,dy) = lass.HxH(dx,dy) * EM.Hx(dx, dy)
                           + lass.HxE(dx,dy) * (EM.Ez(dx,dy + 1)
                                                - EM.Ez(dx,dy));
            }
        }

        // Correction to the H field for the TFSF boundary
        // Hy[49] -= exp(-(t - 40.) * (t - 40.)/100.0) / eps;
        // Hy[49] -= sin((t-10.0)*0.2)*0.0005;

        // Linking the first two elements in the electric field
        EM.Ez[0] = EM.Ez[1];
        // Ez[space - 1] = Ez[space - 2];

        // update electric field
        for (int dx = 1; dx < space - 1; dx++){
            for (int dy = 1; dy < space - 1; dy++){
               EM.Ez(dx,dy) = lass.EzE(dx,dy) * EM.Ez(dx,dy)
                           + lass.EzH[dx] * (EM.Hy(dx, dy)
                                             - EM.Hy(dx - 1, dy)
                                             - EM.Hx(dx,dy)
                                             - EM.Hx(dx, dy - 1));
            }
        }

        // set src for next step
        EM.Ez[0] += exp(-((t + 1 - 40.) * (t + 1 - 40.))/100.0);
        // EM.Ez[0] = 0;

        // Ez[50] += sin((t - 10.0 + 1)*0.2)*0.0005;
/*
        if (t > 0){
            Ez[50] = sin(0.1 * t) / (0.1 * t);
        }
        else{
            Ez[50] = 1;
        }
*/
        if (t % 50 == 0){
            for (int dx = 0; dx < space; dx = dx + 5){
                for (int dy = 0; dy < space; dy = dy + 5){
                    output << t << '\t' << dx <<'\t' << dy
                           << EM.Ez(dx, dy) << '\n';
                    //output << Ez(dx,dy) + (t * offset) << '\n';
                    //output << Hy[dx] + (t * offset) << '\n';
                }
            }

            output << '\n' << '\n';
        }

    }
}
<|endoftext|>