<commit_before>//      page.cpp
//
//      Copyright 2011 Florian Weber <florian.weber@sfz-bw.de>
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU Affero General Public License as published by
//      the Free Software Foundation; either version 3 of the License, or
//      (at your option) any later version.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU Affero General Public License for more details.
//
//      You should have received a copy of the GNU Affero General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.
//
//

#include <iostream>
#include <list>
using namespace std;

#include "page.hpp"
#include "lines.hpp"
#include "files.hpp"

const string TEMPLATE_FILE_PUT_POSTINGS=string("<<POSTINGS>>");
const string TEMPLATE_FILE_PUT_TITLE=string("<<TITLE>>");
const string TEMPLATE_FILE_PUT_TOC=string("<<TOC>>");
const string TEMPLATE_FILE_PUT_MAINPAGE_TOC=string("<<MAINPAGE_TOC>>");///will only be shown on mainpage
const string TEMPLATE_FILE_PUT_TAGS="<<TAGS>>";

int write_page(blogentry *entry, settings &S,string filename,bool comments){
	list<blogentry*> entries;
	entries.push_back(entry);
	list<string> data, temp_lines=read_file_to_list(S.template_file);
	for(list<string>::iterator it=temp_lines.begin();it!=temp_lines.end();++it){
		*it=replace(*it,TEMPLATE_FILE_PUT_TITLE,S.name+" - "+entry->get_heading());
		if(*it==TEMPLATE_FILE_PUT_POSTINGS){
			data+=get_postings(entries,S,comments);
		}
		else if(*it==TEMPLATE_FILE_PUT_TOC){
			if(S.toc_in_singleentries){
				data+=get_TOC(S);
			}
		}
		else if(*it==TEMPLATE_FILE_PUT_MAINPAGE_TOC){
			continue;
		}
		else{
			data.push_back(*it);
		}
	}
	return write_file(filename,data);
}

int write_page(list<blogentry*> &entries, settings &S, string filename,bool comments){
	list<string> data, temp_lines=read_file_to_list(S.template_file);
	for(list<string>::iterator it=temp_lines.begin();it!=temp_lines.end();++it){
		*it=replace(*it,TEMPLATE_FILE_PUT_TITLE,S.name);
		if(*it==TEMPLATE_FILE_PUT_POSTINGS){
			data+=get_postings(entries,S,comments);
		}
		else if(*it==TEMPLATE_FILE_PUT_TOC){
			data+=get_TOC(S);
		}
		else if(*it==TEMPLATE_FILE_PUT_MAINPAGE_TOC){
			data+=get_mainpage_TOC(entries,S);
		}
		else{
			data.push_back(*it);
		}
	}
	return write_file(filename,data);
}

list<string> get_postings(list<blogentry*> &entries, settings &S,bool comments){
	if(!S.enable_comments){
		comments=false;
	}
	list<string> tmp,data;
	string lastdate="";
	bool first_post=true;
	if(S.sorting_by_date){
		for(list<blogentry*>::iterator it=entries.begin();it!=entries.end();++it){
			if(lastdate!=(*it)->get_display_date()){
				if(first_post){
					first_post=false;
				}
				else{
					data.push_back(string("
\n
"));

				}
				data.push_back(string("
\n
")+(*it)->get_display_date()+string("
\n
"));
				lastdate=(*it)->get_display_date();
			}
			data.push_back("
get_id()+"\" class=\"blogentry\">");
			data.push_back("
get_id()+".html\" >"+(*it)->get_heading()+"
");
			data+=(*it)->content();
			if(comments){
				tmp.clear();
				tmp+=(*it)->comments();
				if(tmp.empty()){
					data.push_back(string("
\n")+"get_id()+"\">"+S.comment_name+"");
				}
				else{
					data.push_back("

"+S.comment_section_heading+"
\n
");
					data+=tmp;
					data.push_back("
");
					data.push_back("get_id()+"\">"+S.comment_name+"");
				}
			}
			data.push_back("
");
		}
	data.push_back(string("
\n
"));
	}
	else{
		for(list<blogentry*>::iterator it=entries.begin();it!=entries.end();++it){
			data.push_back("
");
			data.push_back("
");
			data.push_back("
get_id()+"\" href=\""+S.single_entries_dir_rel+(*it)->get_id()+".html\" >"+(*it)->get_heading()+"
\n");
			data.push_back(""+(*it)->get_display_date()+"\n");
			data+=(*it)->content();
			data.push_back("
");
			if(S.enable_tag_file){
				deque<string> tags=(*it)->get_tags();
				if(!tags.empty()){
					data.push_back(""+S.tags_title+"");
					data.push_back("
");
					for(deque<string>::iterator it=tags.begin();it!=tags.end();++it){
						data.push_back("
"+*it+"
");
					}
					data.push_back("
");
				}
			}
			if(comments){
				tmp.clear();
				tmp+=(*it)->comments();
				if(tmp.empty()){
					data.push_back(string("
\n")+"get_id()+"\">"+S.comment_name+"");
				}
				else{
					data.push_back("

"+S.comment_section_heading+"
\n
");
					data+=tmp;
					data.push_back("
");
					data.push_back("get_id()+"\">"+S.comment_name+"");
				}
			}
			data.push_back("
");
		}
	}

	return data;
}

list<string> get_TOC(settings &S){
	list<string> data;
	if(S.blogentries.empty()){
		read_entries(S,true);
	}
	if(!S.toc_pre.empty()){
		data.push_back(S.toc_pre);
	}
	if(!S.toc_title.empty()){
		data.push_back("
"+S.toc_title+"
");
	}
	data.push_back("
");
	for(list<blogentry*>::iterator it=S.blogentries.begin();it!=S.blogentries.end();++it){
		data.push_back("
get_id()+".html\" class=\"toclink\">"+(*it)->get_heading()+"
");
	}
	data.push_back("
");
	if(!S.toc_post.empty()){
		data.push_back(S.toc_post);
	}
	return data;
}

list<string> get_mainpage_TOC(list<blogentry*> &entries, settings &S){
	list<string> data;
	if(!S.mainpage_toc_pre.empty()){
		data.push_back(S.mainpage_toc_pre);
	}
	if(!S.mainpage_toc_title.empty()){
		data.push_back("
"+S.mainpage_toc_title+"
");
	}
	data.push_back("
");
	for(list<blogentry*>::iterator it=entries.begin();it!=entries.end();++it){
		data.push_back("
get_id()+"\" >"+(*it)->get_heading()+"
");
	}
	data.push_back("
");
	if(!S.mainpage_toc_post.empty()){
		data.push_back(S.mainpage_toc_post);
	}
	return data;
}

int create_tags_page(settings &S){
	if(!S.enable_tag_file){
		return 1;
	}
	list<string> data, temp_lines=read_file_to_list(S.template_file);

	for(list<string>::iterator it=temp_lines.begin();it!=temp_lines.end();++it){
		if(it->find("<<")==string::npos){
			data.push_back(*it);
		}
		else{
			if(*it==TEMPLATE_FILE_PUT_TAGS){
				data+=get_tag_list(S);
			}
			else{
				cerr<<"WARNING: Unknown template used"<<endl;
			}
		}
	}

	return write_file(S.tag_file,data);
}

list<string> get_tag_list(settings &S){
	list<string> lines;
	lines.push_back("
");
	for(map<string,list<blogentry*> >::iterator it=S.tags.begin();it!=S.tags.end();++it){
		lines.push_back("
first," ","_")+"\">"+it->first+"
");
		for(list<blogentry*>::iterator inner_it=it->second.begin();inner_it!=it->second.end();++inner_it){
			lines.push_back("
get_url(S)+"\" >"+(*inner_it)->get_heading()+"
");
		}
	}
	lines.push_back("
");
	return lines;
}<commit_msg>bugfix<commit_after>//      page.cpp
//
//      Copyright 2011 Florian Weber <florian.weber@sfz-bw.de>
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU Affero General Public License as published by
//      the Free Software Foundation; either version 3 of the License, or
//      (at your option) any later version.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU Affero General Public License for more details.
//
//      You should have received a copy of the GNU Affero General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.
//
//

#include <iostream>
#include <list>
using namespace std;

#include "page.hpp"
#include "lines.hpp"
#include "files.hpp"

const string TEMPLATE_FILE_PUT_POSTINGS=string("<<POSTINGS>>");
const string TEMPLATE_FILE_PUT_TITLE=string("<<TITLE>>");
const string TEMPLATE_FILE_PUT_TOC=string("<<TOC>>");
const string TEMPLATE_FILE_PUT_MAINPAGE_TOC=string("<<MAINPAGE_TOC>>");///will only be shown on mainpage
const string TEMPLATE_FILE_PUT_TAGS="<<TAGS>>";

int write_page(blogentry *entry, settings &S,string filename,bool comments){
	list<blogentry*> entries;
	entries.push_back(entry);
	list<string> data, temp_lines=read_file_to_list(S.template_file);
	for(list<string>::iterator it=temp_lines.begin();it!=temp_lines.end();++it){
		*it=replace(*it,TEMPLATE_FILE_PUT_TITLE,S.name+" - "+entry->get_heading());
		if(*it==TEMPLATE_FILE_PUT_POSTINGS){
			data+=get_postings(entries,S,comments);
		}
		else if(*it==TEMPLATE_FILE_PUT_TOC){
			if(S.toc_in_singleentries){
				data+=get_TOC(S);
			}
		}
		else if(*it==TEMPLATE_FILE_PUT_MAINPAGE_TOC){
			continue;
		}
		else{
			data.push_back(*it);
		}
	}
	return write_file(filename,data);
}

int write_page(list<blogentry*> &entries, settings &S, string filename,bool comments){
	list<string> data, temp_lines=read_file_to_list(S.template_file);
	for(list<string>::iterator it=temp_lines.begin();it!=temp_lines.end();++it){
		*it=replace(*it,TEMPLATE_FILE_PUT_TITLE,S.name);
		if(*it==TEMPLATE_FILE_PUT_POSTINGS){
			data+=get_postings(entries,S,comments);
		}
		else if(*it==TEMPLATE_FILE_PUT_TOC){
			data+=get_TOC(S);
		}
		else if(*it==TEMPLATE_FILE_PUT_MAINPAGE_TOC){
			data+=get_mainpage_TOC(entries,S);
		}
		else{
			data.push_back(*it);
		}
	}
	return write_file(filename,data);
}

list<string> get_postings(list<blogentry*> &entries, settings &S,bool comments){
	if(!S.enable_comments){
		comments=false;
	}
	list<string> tmp,data;
	string lastdate="";
	bool first_post=true;
	if(S.sorting_by_date){
		for(list<blogentry*>::iterator it=entries.begin();it!=entries.end();++it){
			if(lastdate!=(*it)->get_display_date()){
				if(first_post){
					first_post=false;
				}
				else{
					data.push_back(string("
\n
"));

				}
				data.push_back(string("
\n
")+(*it)->get_display_date()+string("
\n
"));
				lastdate=(*it)->get_display_date();
			}
			data.push_back("
get_id()+"\" class=\"blogentry\">");
			data.push_back("
get_id()+".html\" >"+(*it)->get_heading()+"
");
			data+=(*it)->content();
			if(comments){
				tmp.clear();
				tmp+=(*it)->comments();
				if(tmp.empty()){
					data.push_back(string("
\n")+"get_id()+"\">"+S.comment_name+"");
				}
				else{
					data.push_back("

"+S.comment_section_heading+"
\n
");
					data+=tmp;
					data.push_back("
");
					data.push_back("get_id()+"\">"+S.comment_name+"");
				}
			}
			data.push_back("
");
		}
	data.push_back(string("
\n
"));
	}
	else{
		for(list<blogentry*>::iterator it=entries.begin();it!=entries.end();++it){
			data.push_back("
");
			data.push_back("
");
			data.push_back("
get_id()+"\" href=\""+S.single_entries_dir_rel+(*it)->get_id()+".html\" >"+(*it)->get_heading()+"
\n");
			data.push_back(""+(*it)->get_display_date()+"\n");
			data+=(*it)->content();
			data.push_back("
");
			if(S.enable_tag_file){
				deque<string> tags=(*it)->get_tags();
				if(!tags.empty()){
					data.push_back(""+S.tags_title+"");
					data.push_back("
");
					for(deque<string>::iterator it=tags.begin();it!=tags.end();++it){
						data.push_back("
"+*it+"
");
					}
					data.push_back("
");
				}
			}
			if(comments){
				tmp.clear();
				tmp+=(*it)->comments();
				if(tmp.empty()){
					data.push_back(string("
\n")+"get_id()+"\">"+S.comment_name+"");
				}
				else{
					data.push_back("

"+S.comment_section_heading+"
\n
");
					data+=tmp;
					data.push_back("
");
					data.push_back("get_id()+"\">"+S.comment_name+"");
				}
			}
			data.push_back("
");
		}
	}

	return data;
}

list<string> get_TOC(settings &S){
	list<string> data;
	if(S.blogentries.empty()){
		read_entries(S,true);
	}
	if(!S.toc_pre.empty()){
		data.push_back(S.toc_pre);
	}
	if(!S.toc_title.empty()){
		data.push_back("
"+S.toc_title+"
");
	}
	data.push_back("
");
	for(list<blogentry*>::iterator it=S.blogentries.begin();it!=S.blogentries.end();++it){
		data.push_back("
get_id()+".html\" class=\"toclink\">"+(*it)->get_heading()+"
");
	}
	data.push_back("
");
	if(!S.toc_post.empty()){
		data.push_back(S.toc_post);
	}
	return data;
}

list<string> get_mainpage_TOC(list<blogentry*> &entries, settings &S){
	list<string> data;
	if(!S.mainpage_toc_pre.empty()){
		data.push_back(S.mainpage_toc_pre);
	}
	if(!S.mainpage_toc_title.empty()){
		data.push_back("
"+S.mainpage_toc_title+"
");
	}
	data.push_back("
");
	for(list<blogentry*>::iterator it=entries.begin();it!=entries.end();++it){
		data.push_back("
get_id()+"\" >"+(*it)->get_heading()+"
");
	}
	data.push_back("
");
	if(!S.mainpage_toc_post.empty()){
		data.push_back(S.mainpage_toc_post);
	}
	return data;
}

int create_tags_page(settings &S){
	if(!S.enable_tag_file){
		return 1;
	}
	list<string> data, temp_lines=read_file_to_list(S.tag_file_template);

	for(list<string>::iterator it=temp_lines.begin();it!=temp_lines.end();++it){
		if(it->find("<<")==string::npos){
			data.push_back(*it);
		}
		else{
			if(*it==TEMPLATE_FILE_PUT_TAGS){
				data+=get_tag_list(S);
			}
			else{
				cerr<<"WARNING: Unknown template used"<<endl;
			}
		}
	}

	return write_file(S.tag_file,data);
}

list<string> get_tag_list(settings &S){
	list<string> lines;
	lines.push_back("
");
	for(map<string,list<blogentry*> >::iterator it=S.tags.begin();it!=S.tags.end();++it){
		lines.push_back("
first," ","_")+"\">"+it->first+"
");
		for(list<blogentry*>::iterator inner_it=it->second.begin();inner_it!=it->second.end();++inner_it){
			lines.push_back("
get_url(S)+"\" >"+(*inner_it)->get_heading()+"
");
		}
	}
	lines.push_back("
");
	return lines;
}<|endoftext|>


<commit_before>/*
 * Copyright 2009 Bjorn Fahller <bjorn@fahller.se>
 * All rights reserved

 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef POLL_HPP
#define POLL_HPP

#include <cassert>

#ifdef HAVE_EPOLL
extern "C"
{
#include <sys/epoll.h>
}
template <size_t N>
struct polldata
{
  int epoll_fd;
};
#else

extern "C"
{
#include <sys/select.h>
}

template <size_t N>
struct polldata

{
  polldata()
    : num_subscribers(0U),
      pending_fds(0U)
  {
    FD_ZERO(&rset);
    FD_ZERO(&xset);
  }
  std::pair<int, void*> access[N];
  size_t num_subscribers;
  size_t pending_fds;
  fd_set rset;
  fd_set xset;

  static const int readbit = 1;
  static const int hupbit = 2;
};
#endif

template <typename T, size_t N>
class poll
{
public:
  class descriptor
  {
  public:
    T* operator->() const { return data; }
    T* get() const { return data; }
    bool read() const;
    bool hup() const;
    bool timeout() const { return mode == 0; }
  private:
    descriptor(T* t, int m) : data(t), mode(m) {}

    T* data;
    int mode;

    friend class poll<T, N>;
  };
  poll();
  ~poll();
  void add_fd(int fd, T* data);
  void del_fd(int fd);
  descriptor wait(int timeout_ms = -1);
private:
  polldata<N> data;
};

#ifdef HAVE_EPOLL

template <typename T, size_t N>
inline bool poll<T, N>::descriptor::read() const
{
  return mode & EPOLLIN;
}
template <typename T, size_t N>
inline bool poll<T, N>::descriptor::hup() const
{
  return mode & EPOLLHUP;
}

template <typename T, size_t N>
inline poll<T, N>::poll()
{
  data.epoll_fd = epoll_create(N);
  assert(data.epoll_fd != -1);
}
template <typename T, size_t N>
inline poll<T, N>::~poll()
{
  ::close(data.epoll_fd);
}
template <typename T, size_t N>
inline void poll<T, N>::add_fd(int fd, T* data)
{
  epoll_event ev;
  ev.events = EPOLLIN | EPOLLHUP;
  ev.data.ptr = data;
  int rv = epoll_ctl(this->data.epoll_fd, EPOLL_CTL_ADD, fd, &ev);
  assert(rv == 0);
  (void)rv; // silence warning
}

template <typename T, size_t N>
inline void poll<T, N>::del_fd(int fd)
{
  int rv = epoll_ctl(data.epoll_fd, EPOLL_CTL_DEL, fd, 0);
  assert(rv == 0);
  (void)rv; // silence warning
}

template <typename T, size_t N>
inline typename poll<T, N>::descriptor poll<T, N>::wait(int timeout_ms)
{
  epoll_event ev;
  for (;;)
    {
      int rv = epoll_wait(data.epoll_fd, &ev, 1, timeout_ms);
      if (rv == 0)
        {
          return descriptor(0,0); // timeout
        }
      if (rv == 1)
        {
          return descriptor(static_cast<T*>(ev.data.ptr), ev.events);
        }
    }
}

#else

template <typename T, size_t N>
inline bool poll<T, N>::descriptor::read() const
{
  return mode & polldata<N>::readbit;
}
template <typename T, size_t N>
inline bool poll<T, N>::descriptor::hup() const
{
  return mode & polldata<N>::hupbit;
}
template <typename T, size_t N>
inline poll<T, N>::poll()
{
}
template <typename T, size_t N>
inline poll<T, N>::~poll()
{
}

template <typename T, size_t N>
inline void poll<T, N>::add_fd(int fd, T* data)
{
  this->data.access[this->data.num_subscribers++] = std::make_pair(fd, data);
}
template <typename T, size_t N>
inline void poll<T, N>::del_fd(int fd)
{
  for (size_t i = 0; i < data.num_subscribers; ++i)
    {
      if (data.access[i].first == fd)
        {
          data.access[i] = data.access[--data.num_subscribers];
          if (FD_ISSET(fd, &data.rset) || FD_ISSET(fd, &data.xset))
            {
              FD_CLR(fd, &data.rset);
              FD_CLR(fd, &data.xset);
              --data.pending_fds;
            }
          return;
        }
    }
  assert("fd not found" == 0);
}
template <typename T, size_t N>
inline typename poll<T, N>::descriptor poll<T, N>::wait(int timeout_ms)
{
  if (data.pending_fds == 0)
    {
      int maxfd = 0;
      for (size_t i = 0; i < data.num_subscribers; ++i)
        {
          int fd = data.access[i].first;
          if (fd > maxfd) maxfd = fd;
          FD_SET(fd, &data.rset);
          FD_SET(fd, &data.xset);
        }
      struct timeval tv = { timeout_ms / 1000, (timeout_ms % 1000) * 1000 };
      for (;;)
        {
          int rv = select(maxfd + 1,
                          &data.rset,
                          0,
                          &data.xset,
                          timeout_ms == -1 ? 0 : &tv);
          if (rv == -1 && errno == EINTR) continue;
          assert(rv != -1);
          if (rv == 0) return descriptor(0,0); // timeout
          data.pending_fds = rv;
          break;
        }
    }
  for (size_t j = 0; j < data.num_subscribers; ++j)
    {
      int fd = data.access[j].first;
      int mode = 0;
      if (FD_ISSET(fd, &data.rset))
        {
          mode|= polldata<N>::readbit;
          FD_CLR(fd, &data.rset);
        }
      if (FD_ISSET(fd, &data.xset))
        {
          mode|= polldata<N>::hupbit;
          FD_CLR(fd, &data.xset);
        }
      if (mode)
        {
          --data.pending_fds;
          return descriptor(static_cast<T*>(data.access[j].second),
                            mode);
        }
    }
  assert("no matching fd" == 0);
}
#endif

#endif // POLL_HPP
<commit_msg>Silence uninit-mem warning from valgrind when using epoll<commit_after>/*
 * Copyright 2009 Bjorn Fahller <bjorn@fahller.se>
 * All rights reserved

 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef POLL_HPP
#define POLL_HPP

#include <cassert>

#ifdef HAVE_EPOLL
extern "C"
{
#include <sys/epoll.h>
}
template <size_t N>
struct polldata
{
  int epoll_fd;
};
#else

extern "C"
{
#include <sys/select.h>
}

template <size_t N>
struct polldata

{
  polldata()
    : num_subscribers(0U),
      pending_fds(0U)
  {
    FD_ZERO(&rset);
    FD_ZERO(&xset);
  }
  std::pair<int, void*> access[N];
  size_t num_subscribers;
  size_t pending_fds;
  fd_set rset;
  fd_set xset;

  static const int readbit = 1;
  static const int hupbit = 2;
};
#endif

template <typename T, size_t N>
class poll
{
public:
  class descriptor
  {
  public:
    T* operator->() const { return data; }
    T* get() const { return data; }
    bool read() const;
    bool hup() const;
    bool timeout() const { return mode == 0; }
  private:
    descriptor(T* t, int m) : data(t), mode(m) {}

    T* data;
    int mode;

    friend class poll<T, N>;
  };
  poll();
  ~poll();
  void add_fd(int fd, T* data);
  void del_fd(int fd);
  descriptor wait(int timeout_ms = -1);
private:
  polldata<N> data;
};

#ifdef HAVE_EPOLL

template <typename T, size_t N>
inline bool poll<T, N>::descriptor::read() const
{
  return mode & EPOLLIN;
}
template <typename T, size_t N>
inline bool poll<T, N>::descriptor::hup() const
{
  return mode & EPOLLHUP;
}

template <typename T, size_t N>
inline poll<T, N>::poll()
{
  data.epoll_fd = epoll_create(N);
  assert(data.epoll_fd != -1);
}
template <typename T, size_t N>
inline poll<T, N>::~poll()
{
  ::close(data.epoll_fd);
}
template <typename T, size_t N>
inline void poll<T, N>::add_fd(int fd, T* data)
{
  epoll_event ev;
  ev.events = EPOLLIN | EPOLLHUP;
  ev.data.u64 = 0; // Unnecessary, but silences valgrind msg about uninit mem
  ev.data.ptr = data;
  int rv = epoll_ctl(this->data.epoll_fd, EPOLL_CTL_ADD, fd, &ev);
  assert(rv == 0);
  (void)rv; // silence warning
}

template <typename T, size_t N>
inline void poll<T, N>::del_fd(int fd)
{
  int rv = epoll_ctl(data.epoll_fd, EPOLL_CTL_DEL, fd, 0);
  assert(rv == 0);
  (void)rv; // silence warning
}

template <typename T, size_t N>
inline typename poll<T, N>::descriptor poll<T, N>::wait(int timeout_ms)
{
  epoll_event ev;
  for (;;)
    {
      int rv = epoll_wait(data.epoll_fd, &ev, 1, timeout_ms);
      if (rv == 0)
        {
          return descriptor(0,0); // timeout
        }
      if (rv == 1)
        {
          return descriptor(static_cast<T*>(ev.data.ptr), ev.events);
        }
    }
}

#else

template <typename T, size_t N>
inline bool poll<T, N>::descriptor::read() const
{
  return mode & polldata<N>::readbit;
}
template <typename T, size_t N>
inline bool poll<T, N>::descriptor::hup() const
{
  return mode & polldata<N>::hupbit;
}
template <typename T, size_t N>
inline poll<T, N>::poll()
{
}
template <typename T, size_t N>
inline poll<T, N>::~poll()
{
}

template <typename T, size_t N>
inline void poll<T, N>::add_fd(int fd, T* data)
{
  this->data.access[this->data.num_subscribers++] = std::make_pair(fd, data);
}
template <typename T, size_t N>
inline void poll<T, N>::del_fd(int fd)
{
  for (size_t i = 0; i < data.num_subscribers; ++i)
    {
      if (data.access[i].first == fd)
        {
          data.access[i] = data.access[--data.num_subscribers];
          if (FD_ISSET(fd, &data.rset) || FD_ISSET(fd, &data.xset))
            {
              FD_CLR(fd, &data.rset);
              FD_CLR(fd, &data.xset);
              --data.pending_fds;
            }
          return;
        }
    }
  assert("fd not found" == 0);
}
template <typename T, size_t N>
inline typename poll<T, N>::descriptor poll<T, N>::wait(int timeout_ms)
{
  if (data.pending_fds == 0)
    {
      int maxfd = 0;
      for (size_t i = 0; i < data.num_subscribers; ++i)
        {
          int fd = data.access[i].first;
          if (fd > maxfd) maxfd = fd;
          FD_SET(fd, &data.rset);
          FD_SET(fd, &data.xset);
        }
      struct timeval tv = { timeout_ms / 1000, (timeout_ms % 1000) * 1000 };
      for (;;)
        {
          int rv = select(maxfd + 1,
                          &data.rset,
                          0,
                          &data.xset,
                          timeout_ms == -1 ? 0 : &tv);
          if (rv == -1 && errno == EINTR) continue;
          assert(rv != -1);
          if (rv == 0) return descriptor(0,0); // timeout
          data.pending_fds = rv;
          break;
        }
    }
  for (size_t j = 0; j < data.num_subscribers; ++j)
    {
      int fd = data.access[j].first;
      int mode = 0;
      if (FD_ISSET(fd, &data.rset))
        {
          mode|= polldata<N>::readbit;
          FD_CLR(fd, &data.rset);
        }
      if (FD_ISSET(fd, &data.xset))
        {
          mode|= polldata<N>::hupbit;
          FD_CLR(fd, &data.xset);
        }
      if (mode)
        {
          --data.pending_fds;
          return descriptor(static_cast<T*>(data.access[j].second),
                            mode);
        }
    }
  assert("no matching fd" == 0);
}
#endif

#endif // POLL_HPP
<|endoftext|>


<commit_before>#include <re2/re2.h>
#include <iostream>

int extract(const re2::StringPiece &text,
            const re2::RE2& pattern,
            const re2::StringPiece &rewrite,
            std::string *out,
            bool global){
  return global?RE2::GlobalExtract(text,pattern,rewrite,out):
    RE2::Extract(text,pattern,rewrite,out)?1:0;
}

int replace(std::string *text,
            const re2::RE2& pattern,
            const re2::StringPiece &rewrite,
            bool global){
  return global?RE2::GlobalReplace(text,pattern,rewrite):
    RE2::Replace(text,pattern,rewrite)?1:0;
}

int main(int argc,char** argv){
  int o_global=0,
    o_usage=0,
    o_print_match=0,
    o_also_print_unreplaced=0,
    o_negate_match=0;

  if(argc>1){
    if(argv[1][0] == '-'){
      if ( argv[1][1] == '-'){
        //ignore standalone '--' as argv[1];
      } else {
        // we have flags
        char* fs=argv[1]+1;
        char c;
        while((c=*fs++)){
          switch (c) {
          case 'g':
            o_global = 1;
            break;
          case 'o':
            o_print_match = 1;
            break;
          case 'p':
            o_also_print_unreplaced = 1;
            break;
          case 'v':
            o_negate_match = 1;
            break;
          default:
            o_usage = 1;
          }
        }
      }
      argv[1] = argv[0];
      argv++;
      argc--;
    }
  }

  if(o_usage){
    std::cout << argv[0] << " [-flags] text pattern [replacement]" << std::endl
              << std:: endl
              << "TEXT text to search" << std::endl
              << "PATTERN re2 expression to apply" << std::endl
              << "REPLACEMENT optional replacement string, supports \\0 .. \\9 references"  << std::endl
              << "FLAGS modifiers to operation"  << std::endl
              << std::endl
              << "   h: display help"  << std::endl
              << "   v: invert match"  << std::endl
              << "   o: only print matching portion"  << std::endl
              << "   g: global search/replace, default is one per line"  << std::endl
              << "   p: (when replacing) print lines where no replacement was made"  << std::endl
              << std::endl;
    return 0;
  }

  /*
  std::cout << "g:" << o_global << std::endl <<
    "u:" << o_usage << std::endl <<
    "p:" << o_print_match << std::endl <<
    "u:" << o_also_print_unreplaced << std::endl <<
    "n:" << o_negate_match << std::endl;*/

  std::string in = std::string(argv[1]);
  std::string out;
  std::string *to_print = NULL;
  RE2::RE2 pat(argv[2]);

  //rationalize flags
  if(o_negate_match && o_print_match){
    o_print_match = 0;
  }

  bool matched;
  bool print;
  if(argc==3){
    // re2g str pat
    if(o_print_match){
      matched = extract(in,pat,"\\0",&out,o_global)>0;
      to_print=&out;
    } else {
      matched = RE2::PartialMatch(in,pat);
      to_print= ∈
    }
    to_print=(matched^o_negate_match)?to_print:NULL;
  } else if(argc==4) {
    // re2g str pat rep
    std::string rep = std::string(argv[3]);

    // need to pick: (-o) Extract, (default)Replace, (-g)GlobalReplace
    // also, print non matching lines? (-p)
    if(o_print_match){
      matched = extract(in,pat,rep,&out,o_global)>0;
      to_print=&out;
    } else {
      matched = replace(&in,pat,rep,o_global)>0;
      to_print=∈
    }
    to_print=(matched ^ o_negate_match)?to_print:NULL;

    if(o_also_print_unreplaced && !to_print){
      out = std::string(argv[1]);
      to_print = & out;
    }
  } else {
    std::cout << RE2::PartialMatch("f", "f") << std::endl;
    std::cout << RE2::PartialMatch("fred", "z") << std::endl;
    std::cout << RE2::PartialMatch("fred", "[fz]") << std::endl;
  }
  if(to_print){
    std::cout << *to_print << std::endl;
  } else {
    std::cout << std::endl;
  }
}

<commit_msg>spacing cleanup<commit_after>#include <re2/re2.h>
#include <iostream>

int extract(const re2::StringPiece &text,
            const re2::RE2& pattern,
            const re2::StringPiece &rewrite,
            std::string *out,
            bool global){
  return global?RE2::GlobalExtract(text, pattern, rewrite, out):
    RE2::Extract(text, pattern, rewrite, out)?1:0;
}

int replace(std::string *text,
            const re2::RE2& pattern,
            const re2::StringPiece &rewrite,
            bool global){
  return global?RE2::GlobalReplace(text, pattern, rewrite):
    RE2::Replace(text, pattern, rewrite)?1:0;
}

int main(int argc, char** argv){
  int o_global=0,
    o_usage=0,
    o_print_match=0,
    o_also_print_unreplaced=0,
    o_negate_match=0;

  if(argc>1){
    if(argv[1][0] == '-'){
      if ( argv[1][1] == '-'){
        //ignore standalone '--' as argv[1];
      } else {
        // we have flags
        char* fs=argv[1]+1;
        char c;
        while((c=*fs++)){
          switch (c) {
          case 'g':
            o_global = 1;
            break;
          case 'o':
            o_print_match = 1;
            break;
          case 'p':
            o_also_print_unreplaced = 1;
            break;
          case 'v':
            o_negate_match = 1;
            break;
          default:
            o_usage = 1;
          }
        }
      }
      argv[1] = argv[0];
      argv++;
      argc--;
    }
  }

  if(o_usage){
    std::cout << argv[0] << " [-flags] text pattern [replacement]" << std::endl
              << std:: endl
              << "TEXT text to search" << std::endl
              << "PATTERN re2 expression to apply" << std::endl
              << "REPLACEMENT optional replacement string, supports \\0 .. \\9 references"  << std::endl
              << "FLAGS modifiers to operation"  << std::endl
              << std::endl
              << "   h: display help"  << std::endl
              << "   v: invert match"  << std::endl
              << "   o: only print matching portion"  << std::endl
              << "   g: global search/replace, default is one per line"  << std::endl
              << "   p: (when replacing) print lines where no replacement was made"  << std::endl
              << std::endl;
    return 0;
  }

  /*
  std::cout << "g:" << o_global << std::endl <<
    "u:" << o_usage << std::endl <<
    "p:" << o_print_match << std::endl <<
    "u:" << o_also_print_unreplaced << std::endl <<
    "n:" << o_negate_match << std::endl;*/

  std::string in = std::string(argv[1]);
  std::string out;
  std::string *to_print = NULL;
  RE2::RE2 pat(argv[2]);

  //rationalize flags
  if(o_negate_match && o_print_match){
    o_print_match = 0;
  }

  bool matched;
  bool print;
  if(argc==3){
    // re2g str pat
    if(o_print_match){
      matched = extract(in, pat, "\\0", &out, o_global) > 0;
      to_print = &out;
    } else {
      matched = RE2::PartialMatch(in, pat);
      to_print = ∈
    }
    to_print=(matched ^ o_negate_match)?to_print:NULL;
  } else if(argc==4) {
    // re2g str pat rep
    std::string rep = std::string(argv[3]);

    // need to pick: (-o) Extract, (default)Replace, (-g)GlobalReplace
    // also, print non matching lines? (-p)
    if(o_print_match){
      matched = extract(in, pat, rep, &out, o_global) > 0;
      to_print = &out;
    } else {
      matched = replace(&in, pat, rep, o_global) > 0;
      to_print = ∈
    }
    to_print=(matched ^ o_negate_match)?to_print:NULL;

    if(o_also_print_unreplaced && !to_print){
      out = std::string(argv[1]);
      to_print = & out;
    }
  } else {
    std::cout << RE2::PartialMatch("f", "f") << std::endl;
    std::cout << RE2::PartialMatch("fred", "z") << std::endl;
    std::cout << RE2::PartialMatch("fred", "[fz]") << std::endl;
  }
  if(to_print){
    std::cout << *to_print << std::endl;
  } else {
    std::cout << std::endl;
  }
}

<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <math.h>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <fstream>
#include <votca/csg/csgapplication.h>
#include <votca/csg/trajectorywriter.h>

using namespace std;
using namespace votca::csg;

class CsgMapApp
    : public CsgApplication
{
public:
    string ProgramName() { return "csg_map"; }
    void HelpText(ostream &out) {
        out << "Map a reference trajectory to a coarse-grained trajectory.\n"
            "This program can be used to map a whole trajectory or to\n"
            "create an initial configuration for a coarse-grained run only.";
    }

    bool DoTrajectory() { return true;}
    bool DoMapping() { return true;}

    void Initialize() {
        CsgApplication::Initialize();
        AddProgramOptions()
            ("out", boost::program_options::value<string>(),
                "  output file for coarse-grained trajectory")
                ("hybrid", boost::program_options::value<string>(&_hybrid_string)->default_value(""),
                " [yes/no] Create hybrid topology containing both atomistic and coarse-grained");
    }

    bool EvaluateOptions() {
        CsgApplication::EvaluateOptions();
        CheckRequired("trj", "no trajectory file specified");
        CheckRequired("out", "need to specify output trajectory");
        return true;
    }

    void BeginEvaluate(Topology *top, Topology *top_ref);
void EvalConfiguration(Topology *top, Topology *top_ref) {
        if (!_do_hybrid) {
            // simply write the topology mapped by csgapplication classe
            _writer->Write(top);
        } else {
            // we want to combinge atomistic and coarse-grained into one topology
            Topology *hybtol = new Topology();

            BeadContainer::iterator it_bead;
            ResidueContainer::iterator it_res;
            MoleculeContainer::iterator it_mol;
            InteractionContainer::iterator it_ia;

            hybtol->setBox(top->getBox());
            hybtol->setTime(top->getTime());
            hybtol->setStep(top->getStep());

            // copy all residues from both
            for (it_res = top_ref->Residues().begin(); it_res != top_ref->Residues().end(); ++it_res) {
                hybtol->CreateResidue((*it_res)->getName());
            }
            for (it_res = top->Residues().begin(); it_res != top->Residues().end(); ++it_res) {
                hybtol->CreateResidue((*it_res)->getName());
            }

            // copy all molecules and beads

            for(it_mol=top_ref->Molecules().begin();it_mol!=top_ref->Molecules().end(); ++it_mol) {
                Molecule *mi = hybtol->CreateMolecule((*it_mol)->getName());
                for (int i = 0; i < (*it_mol)->BeadCount(); i++) {
                    // copy atomistic beads of molecule
                    int beadid = (*it_mol)->getBead(i)->getId();

                    Bead *bi = (*it_mol)->getBead(i);
                    BeadType *type = hybtol->GetOrCreateBeadType(bi->getType()->getName());
                    Bead *bn = hybtol->CreateBead(bi->getSymmetry(), bi->getName(), type, bi->getResnr(), bi->getM(), bi->getQ());
                    bn->setOptions(bi->Options());
                    bn->setPos(bi->getPos());
                    if (bi->HasVel()) bn->setVel(bi->getVel());

                    mi->AddBead(hybtol->Beads()[beadid], (*it_mol)->getBeadName(i));

                }

                if (mi->getId() < top->MoleculeCount()) {
                    // copy cg beads of molecule
                    Molecule *cgmol = top->Molecules()[mi->getId()];
                    for (int i = 0; i < cgmol->BeadCount(); i++) {
                        Bead *bi = cgmol->getBead(i);
                        // todo: this is a bit dirty as a cg bead will always have the resid of its first parent
                        Bead *bparent = (*it_mol)->getBead(0);
                        BeadType *type = hybtol->GetOrCreateBeadType(bi->getType()->getName());
                        Bead *bn = hybtol->CreateBead(bi->getSymmetry(), bi->getName(), type, bparent->getResnr(), bi->getM(), bi->getQ());
                        bn->setOptions(bi->Options());
                        bn->setPos(bi->getPos());
                        if (bi->HasVel()) bn->setVel(bi->getVel());
                        int mid = bparent->getMolecule()->getId();
                        mi->AddBead(bi, bi->getName());
                    }
                }

            }
           hybtol->setBox(top_ref->getBox());

            _writer->Write(hybtol);
        }
    }

    void EndEvaluate() {
        _writer->Close();
        delete _writer;
    }

protected:
    TrajectoryWriter *_writer;
    bool _do_hybrid;
    string _hybrid_string;

};

void CsgMapApp::BeginEvaluate(Topology *top, Topology *top_atom) {
    string out = OptionsMap()["out"].as<string > ();
    string hybrid = OptionsMap()["hybrid"].as<string > ();
    cout << "writing coarse-grained trajectory to " << out << endl;
    _writer = TrjWriterFactory().Create(out);
    if (_writer == NULL)
        throw runtime_error("output format not supported: " + out);

    _do_hybrid = false;
    if (hybrid == "yes") {
        if (!_do_mapping)
            throw runtime_error("options hybrid and no-map not compatible");
        cout << "Doing hybrid mapping..." << endl;
        _do_hybrid = true;
    }

    _writer->Open(out);
};

int main(int argc, char **argv)
{
    CsgMapApp app;
    return app.Exec(argc, argv);
}

<commit_msg>csg_map: make --hybrid a bool options<commit_after>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <math.h>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <fstream>
#include <votca/csg/csgapplication.h>
#include <votca/csg/trajectorywriter.h>

using namespace std;
using namespace votca::csg;

class CsgMapApp
    : public CsgApplication
{
public:
    string ProgramName() { return "csg_map"; }
    void HelpText(ostream &out) {
        out << "Map a reference trajectory to a coarse-grained trajectory.\n"
            "This program can be used to map a whole trajectory or to\n"
            "create an initial configuration for a coarse-grained run only.";
    }

    bool DoTrajectory() { return true;}
    bool DoMapping() { return true;}

    void Initialize() {
        CsgApplication::Initialize();
        AddProgramOptions()
            ("out", boost::program_options::value<string>(),
                "  output file for coarse-grained trajectory")
                ("hybrid", "Create hybrid trajectory containing both atomistic and coarse-grained");
    }

    bool EvaluateOptions() {
        CsgApplication::EvaluateOptions();
        CheckRequired("trj", "no trajectory file specified");
        CheckRequired("out", "need to specify output trajectory");
        return true;
    }

    void BeginEvaluate(Topology *top, Topology *top_ref);
void EvalConfiguration(Topology *top, Topology *top_ref) {
        if (!_do_hybrid) {
            // simply write the topology mapped by csgapplication classe
            _writer->Write(top);
        } else {
            // we want to combinge atomistic and coarse-grained into one topology
            Topology *hybtol = new Topology();

            BeadContainer::iterator it_bead;
            ResidueContainer::iterator it_res;
            MoleculeContainer::iterator it_mol;
            InteractionContainer::iterator it_ia;

            hybtol->setBox(top->getBox());
            hybtol->setTime(top->getTime());
            hybtol->setStep(top->getStep());

            // copy all residues from both
            for (it_res = top_ref->Residues().begin(); it_res != top_ref->Residues().end(); ++it_res) {
                hybtol->CreateResidue((*it_res)->getName());
            }
            for (it_res = top->Residues().begin(); it_res != top->Residues().end(); ++it_res) {
                hybtol->CreateResidue((*it_res)->getName());
            }

            // copy all molecules and beads

            for(it_mol=top_ref->Molecules().begin();it_mol!=top_ref->Molecules().end(); ++it_mol) {
                Molecule *mi = hybtol->CreateMolecule((*it_mol)->getName());
                for (int i = 0; i < (*it_mol)->BeadCount(); i++) {
                    // copy atomistic beads of molecule
                    int beadid = (*it_mol)->getBead(i)->getId();

                    Bead *bi = (*it_mol)->getBead(i);
                    BeadType *type = hybtol->GetOrCreateBeadType(bi->getType()->getName());
                    Bead *bn = hybtol->CreateBead(bi->getSymmetry(), bi->getName(), type, bi->getResnr(), bi->getM(), bi->getQ());
                    bn->setOptions(bi->Options());
                    bn->setPos(bi->getPos());
                    if (bi->HasVel()) bn->setVel(bi->getVel());

                    mi->AddBead(hybtol->Beads()[beadid], (*it_mol)->getBeadName(i));

                }

                if (mi->getId() < top->MoleculeCount()) {
                    // copy cg beads of molecule
                    Molecule *cgmol = top->Molecules()[mi->getId()];
                    for (int i = 0; i < cgmol->BeadCount(); i++) {
                        Bead *bi = cgmol->getBead(i);
                        // todo: this is a bit dirty as a cg bead will always have the resid of its first parent
                        Bead *bparent = (*it_mol)->getBead(0);
                        BeadType *type = hybtol->GetOrCreateBeadType(bi->getType()->getName());
                        Bead *bn = hybtol->CreateBead(bi->getSymmetry(), bi->getName(), type, bparent->getResnr(), bi->getM(), bi->getQ());
                        bn->setOptions(bi->Options());
                        bn->setPos(bi->getPos());
                        if (bi->HasVel()) bn->setVel(bi->getVel());
                        int mid = bparent->getMolecule()->getId();
                        mi->AddBead(bi, bi->getName());
                    }
                }

            }
           hybtol->setBox(top_ref->getBox());

            _writer->Write(hybtol);
        }
    }

    void EndEvaluate() {
        _writer->Close();
        delete _writer;
    }

protected:
    TrajectoryWriter *_writer;
    bool _do_hybrid;
    string _hybrid_string;

};

void CsgMapApp::BeginEvaluate(Topology *top, Topology *top_atom) {
    string out = OptionsMap()["out"].as<string > ();
    string hybrid = OptionsMap()["hybrid"].as<string > ();
    cout << "writing coarse-grained trajectory to " << out << endl;
    _writer = TrjWriterFactory().Create(out);
    if (_writer == NULL)
        throw runtime_error("output format not supported: " + out);

    _do_hybrid = false;
    if(OptionsMap().count("hybrid")){
        if (!_do_mapping)
            throw runtime_error("options hybrid and no-map not compatible");
        cout << "Doing hybrid mapping..." << endl;
        _do_hybrid = true;
    }

    _writer->Open(out);
};

int main(int argc, char **argv)
{
    CsgMapApp app;
    return app.Exec(argc, argv);
}

<|endoftext|>


<commit_before>// Test.cpp
// Sean Jones

#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#include <chrono>
#include <glm/glm.hpp>
#include <glm/gtx/constants.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>

using namespace std::chrono;

GLFWwindow* window;

bool running = true;

// Value to keep track of current orientation on axis
vec3 position(0.0f, 0.0f, 0.0f);

bool initialise()
{
  // Set Color to cyan
  glClearColor(0.0f, 1.0f, 1.0f, 1.0f);

  return true;
} // initialise

//updates the application
void update(double deltaTime)
{
  // Check if escape pressed or window is closed
  running = !glfwGetKey(window, GLFW_KEY_ESCAPE) &&
    !glfwWindowShouldClose(window);

  // Rotate at half a rotation (pi radians) per second
  orientation += (deltaTime * glm::pi<float>());

} // update

//renders the application
void render()
{
  // Create rotation transform. Use Z-axis
  glm::mat4 model = glm::rotate(glm::mat4(10.f),
                                glm::degrees(orientation),
                                glm::vec3(0.0f, 0.0f, 1.0f));

  // Now scale the triangle
  model *= glm::scale(1.0f/orientation, 1.0f/orientation, 1.0f/orientation);

  // Set the matrix we are using
  glMatrixMode(GL_MODELVIEW);
  // Load the matrix (use it)
  glLoadMatrixf(glm::value_ptr(model));

  // Clear the screen
  glClear(GL_COLOR_BUFFER_BIT);

  //Set the colour
  glColor4f(1.0f, 0.0f, 0.0f, 1.0f);

  //Render a Triangel
  glBegin(GL_TRIANGLES);

    glColor3f(1.0f, 0.0f, 0.0f);
    glVertex3f(0.0f, 0.5f, 0.0f);
    glColor3f(0.0f, 1.0f, 0.0f);
    glVertex3f(-0.5f, -0.5f, 0.0f);
    glColor3f(0.0f, 0.0f, 1.0f);
    glVertex3f(0.5f, -0.5f, 0.0f);

  glEnd();

  // Swap front and back buffers
  glfwSwapBuffers(window);
  // Load the identity matrix (ensures transformation is reset)
  glLoadIdentity();
} // render

int main(void)
{
    /* Initialize the library */
    if (!glfwInit())
    {
        return -1;
    }

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    //initialise the window
    if (!initialise())
    {
      glfwTerminate();
      return -1;
    }

    // Monitor the elapsed time per frame
    auto currentTimeStamp = system_clock::now();
    auto prevTimeStamp = system_clock::now();

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        // Get current time
        currentTimeStamp = system_clock::now();
        // Calculate elapsed time
        auto elapsed = duration_cast<milliseconds>(currentTimeStamp
            - prevTimeStamp);
        //Convert to fractions of a second
        auto seconds = double(elapsed.count()) / 1000.0;

        // Update Application
        update(seconds);
        //Render scene
        render();

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();

        // set the previous time stamp to current time stamp
        prevTimeStamp = currentTimeStamp;
    } // Main Loop

    glfwTerminate();
    return 0;
} // main
<commit_msg>Added key interaction code<commit_after>// Test.cpp
// Sean Jones

#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#include <chrono>
#include <glm/glm.hpp>
#include <glm/gtx/constants.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>

using namespace std::chrono;

GLFWwindow* window;

bool running = true;

// Value to keep track of current orientation on axis
vec3 position(0.0f, 0.0f, 0.0f);

bool initialise()
{
  // Set Color to cyan
  glClearColor(0.0f, 1.0f, 1.0f, 1.0f);

  return true;
} // initialise

//updates the application
void update(double deltaTime)
{
  // Check if escape pressed or window is closed
  running = !glfwGetKey(window, GLFW_KEY_ESCAPE) &&
    !glfwWindowShouldClose(window);

  // Move the quad when arrow keys are pressed
  if (glfwGetKey(window, GLFW_KET_RIGHT)){
    position += vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
  }
  if (glfwGetKey(window, GLFW_KET_LEFT)){
    position -= vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
  }
  if (glfwGetKey(window, GLFW_KET_UP)){
    position += vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
  }
  if (glfwGetKey(window, GLFW_KET_DOWN)){
    position -= vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
  }
} // update

//renders the application
void render()
{
  // Create rotation transform. Use Z-axis
  glm::mat4 model = glm::rotate(glm::mat4(10.f),
                                glm::degrees(orientation),
                                glm::vec3(0.0f, 0.0f, 1.0f));

  // Now scale the triangle
  model *= glm::scale(1.0f/orientation, 1.0f/orientation, 1.0f/orientation);

  // Set the matrix we are using
  glMatrixMode(GL_MODELVIEW);
  // Load the matrix (use it)
  glLoadMatrixf(glm::value_ptr(model));

  // Clear the screen
  glClear(GL_COLOR_BUFFER_BIT);

  //Set the colour
  glColor4f(1.0f, 0.0f, 0.0f, 1.0f);

  //Render a Triangel
  glBegin(GL_TRIANGLES);

    glColor3f(1.0f, 0.0f, 0.0f);
    glVertex3f(0.0f, 0.5f, 0.0f);
    glColor3f(0.0f, 1.0f, 0.0f);
    glVertex3f(-0.5f, -0.5f, 0.0f);
    glColor3f(0.0f, 0.0f, 1.0f);
    glVertex3f(0.5f, -0.5f, 0.0f);

  glEnd();

  // Swap front and back buffers
  glfwSwapBuffers(window);
  // Load the identity matrix (ensures transformation is reset)
  glLoadIdentity();
} // render

int main(void)
{
    /* Initialize the library */
    if (!glfwInit())
    {
        return -1;
    }

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    //initialise the window
    if (!initialise())
    {
      glfwTerminate();
      return -1;
    }

    // Monitor the elapsed time per frame
    auto currentTimeStamp = system_clock::now();
    auto prevTimeStamp = system_clock::now();

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        // Get current time
        currentTimeStamp = system_clock::now();
        // Calculate elapsed time
        auto elapsed = duration_cast<milliseconds>(currentTimeStamp
            - prevTimeStamp);
        //Convert to fractions of a second
        auto seconds = double(elapsed.count()) / 1000.0;

        // Update Application
        update(seconds);
        //Render scene
        render();

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();

        // set the previous time stamp to current time stamp
        prevTimeStamp = currentTimeStamp;
    } // Main Loop

    glfwTerminate();
    return 0;
} // main
<|endoftext|>


<commit_before>// Lesson 13.cpp : Defines the entry point for the console application.

#include <render_framework\render_framework.h>
#include <chrono>
#pragma comment (lib , "Render Framework" )

using namespace std;
using namespace glm;
using namespace render_framework;
using namespace chrono;

#define OBJECTS 1

// Global scope box
shared_ptr<mesh> object[1];
shared_ptr<target_camera> cam;

/*
 * Update routine
 *
 * Updates the application state
 */
void update(float deltaTime) {

	cam->update(deltaTime);

} // update()

bool load_content() {

	int i = 0;
	for (i=0;i<OBJECTS;i++) {
		// Create box
		object[i] = make_shared<mesh>();
		object[i]->geom = geometry_builder::create_box();

		// Load in effect.  Start with shaders
		auto eff = make_shared<effect>();
		eff->add_shader("shader.vert", GL_VERTEX_SHADER);
		eff->add_shader("shader.frag", GL_FRAGMENT_SHADER);
		if (!effect_loader::build_effect(eff)) {
			return false;
		}

		// Create material for box
		object[i]->mat = make_shared<material>();
		object[i]->mat->effect = eff;
		object[i]->mat->set_texture("tex", texture_loader::load("Checkered.png"));

		object[i]->trans.translate(vec3(0.0, (float) i*2+1, 0.0));
	}

	return true;

} // load_content()

bool load_camera() {
	// Initialize the camera
	cam = make_shared<target_camera>();

	/* Set the projection matrix */
	// First get the aspect ratio (width/height)
	float aspect = (float)renderer::get_instance().get_screen_width() /
					(float)renderer::get_instance().get_screen_width();
	// Use this to set the camera projection matrix
	cam->set_projection(
						degrees(quarter_pi<float>()),	// FOV
						aspect,							// Aspect ratio
						2.414f,							// Near plane
						10000.0f);						// Far plane
	// Set the camera properties
	cam->set_position(vec3(10.0, 10.0, 10.0));
	cam->set_target(vec3(0.0, 0.0, 0.0));
	cam->set_up(vec3(0.0, 1.0, 0.0));

	// Attach camera to renderer
	renderer::get_instance().set_camera(cam);

	// Set the view matrix
	auto view = lookAt(
					vec3(20.0f, 20.0f, 20.0f),	// Camera position
					vec3(0.0f, 0.0f, 0.0f),		// Target
					vec3(0.0f, 1.0f, 0.0f));	// Up vector
	renderer::get_instance().set_view(view);

	return true;
} // load_camera

int main()
{
	// Initialize the renderer
	if (!renderer::get_instance().initialise()) return -1;

	// Set the clear colour to cyan
	glClearColor(0.0f, 1.0f, 1.0f, 1.0f);

	if (!load_content()) {
		return -1;
	}

	if (!load_camera()) {
		return -1;
	}

	// Monitor the elapsed time per frame
	auto currentTimeStamp = system_clock::now();
	auto prevTimeStamp = system_clock::now();

	// Main render loop
	while (renderer::get_instance().is_running())
	{
		// Get current time
		currentTimeStamp = system_clock::now();
		// Calculate elapsed time
		auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp);
		// Convert to fractions of a second
		auto seconds = float(elapsed.count()) / 1000.0;

		// Update Scene
		update(seconds);

		// Check if running
		if (renderer::get_instance().begin_render())
		{
			// Render Cube
			int i = 0;
			for (i = 0; i <OBJECTS; i++) {
				renderer::get_instance().render(object[i]);
			}

			// End the render
			renderer::get_instance().end_render();
		}

		prevTimeStamp = currentTimeStamp;

	} // Main render loop
}
<commit_msg>Changed camera to free camera<commit_after>// Lesson 13.cpp : Defines the entry point for the console application.

#include <render_framework\render_framework.h>
#include <chrono>
#pragma comment (lib , "Render Framework" )

using namespace std;
using namespace glm;
using namespace render_framework;
using namespace chrono;

#define OBJECTS 1

// Global scope box
shared_ptr<mesh> object[1];
shared_ptr<free_camera> cam;

/*
 * Update routine
 *
 * Updates the application state
 */
void update(float deltaTime) {

	cam->update(deltaTime);

} // update()

bool load_content() {

	int i = 0;
	for (i=0;i<OBJECTS;i++) {
		// Create box
		object[i] = make_shared<mesh>();
		object[i]->geom = geometry_builder::create_box();

		// Load in effect.  Start with shaders
		auto eff = make_shared<effect>();
		eff->add_shader("shader.vert", GL_VERTEX_SHADER);
		eff->add_shader("shader.frag", GL_FRAGMENT_SHADER);
		if (!effect_loader::build_effect(eff)) {
			return false;
		}

		// Create material for box
		object[i]->mat = make_shared<material>();
		object[i]->mat->effect = eff;
		object[i]->mat->set_texture("tex", texture_loader::load("Checkered.png"));

		object[i]->trans.translate(vec3(0.0, (float) i*2+1, 0.0));
	}

	return true;

} // load_content()

bool load_camera() {
	// Initialize the camera
	cam = make_shared<free_camera>();

	/* Set the projection matrix */
	// First get the aspect ratio (width/height)
	float aspect = (float)renderer::get_instance().get_screen_width() /
					(float)renderer::get_instance().get_screen_width();
	// Use this to set the camera projection matrix
	cam->set_projection(
						quarter_pi<float>(),			// FOV
						aspect,							// Aspect ratio
						2.414f,							// Near plane
						10000.0f);						// Far plane
	// Set the camera properties
	cam->set_position(vec3(10.0, 10.0, 10.0));

	// Attach camera to renderer
	renderer::get_instance().set_camera(cam);

	// Set the view matrix
	auto view = lookAt(
					vec3(20.0f, 20.0f, 20.0f),	// Camera position
					vec3(0.0f, 0.0f, 0.0f),		// Target
					vec3(0.0f, 1.0f, 0.0f));	// Up vector
	renderer::get_instance().set_view(view);

	return true;
} // load_camera

int main()
{
	// Initialize the renderer
	if (!renderer::get_instance().initialise()) return -1;

	// Set the clear colour to cyan
	glClearColor(0.0f, 1.0f, 1.0f, 1.0f);

	if (!load_content()) {
		return -1;
	}

	if (!load_camera()) {
		return -1;
	}

	// Monitor the elapsed time per frame
	auto currentTimeStamp = system_clock::now();
	auto prevTimeStamp = system_clock::now();

	// Main render loop
	while (renderer::get_instance().is_running())
	{
		// Get current time
		currentTimeStamp = system_clock::now();
		// Calculate elapsed time
		auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp);
		// Convert to fractions of a second
		auto seconds = float(elapsed.count()) / 1000.0;

		// Update Scene
		update(seconds);

		// Check if running
		if (renderer::get_instance().begin_render())
		{
			// Render Cube
			int i = 0;
			for (i = 0; i <OBJECTS; i++) {
				renderer::get_instance().render(object[i]);
			}

			// End the render
			renderer::get_instance().end_render();
		}

		prevTimeStamp = currentTimeStamp;

	} // Main render loop
}
<|endoftext|>


<commit_before>
/*
 *  client.cpp
 *
 *  Handles the client env.
 *
 *  Created by Ryan Faulkner on 2014-06-08
 *  Copyright (c) 2014. All rights reserved.
 */

#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>

#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"

#define REDISHOST "127.0.0.1"
#define REDISPORT 6379

using namespace std;

/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
    RedisHandler r;
    r.connect();
    r.write("foo", "bar");
}

/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
    RedisHandler r;
    r.connect();
    cout << endl << "VALUE FOR KEY foo" << endl;
    cout << r.read("foo") << endl << endl;
}

/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
    RedisHandler r;
    std::vector<std::string> vec;

    r.connect();
    vec = r.keys("*");
    cout << "KEY LIST FOR *" << endl;
    for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
        cout << *it << endl;
    }
    cout << endl;
}

/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
    RedisHandler r;
    std::vector<string>* vec;
    std::string outTrue, outFalse = "";

    r.connect();
    r.write("test_key", "test value");
    outTrue = r.read("test_key");
    assert(std::strcmp(outTrue.c_str(), "test value") == 0);
    r.deleteKey("test_key");
    assert(!r.exists("test_key"));
}

/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
    cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}

/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
    IntegerColumn ic;
    FloatColumn fc;
    assert(ic.validate("1981"));
    assert(fc.validate("5.2"));
    cout << "Passed regex tests." << endl;
}

/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
    IndexHandler ih;
    assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
    cout << "Passed orderPairAlphaNumeric tests." << endl;
}

/**
 * Test to ensure that relation entities are encoded properly
 */
void testJSONEntityEncoding() {

    IndexHandler ih;
    Json::Value json;
    std::vector<std::pair<ColumnBase*, std::string>>* fields_ent = new vector<std::pair<ColumnBase*, std::string>>;

    fields_ent->push_back(std::make_pair(getColumnType("integer"), "a"));   // Create fields
    ih.writeEntity("test", fields_ent);     // Create the entity
    ih.fetchEntity("test", json);           // Fetch the entity representation
    cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;

    // Assert that entity as read matches definition
    assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
            std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
            json["fields"]["fields_count"].asInt() == 1
    );
    ih.removeEntity("test");                // Remove the entity
}

/**
 * Test to ensure that relation fields are encoded properly
 */
void testJSONRelationEncoding() {
    IndexHandler ih;
    std::vector<Json::Value> ret;
    std::vector<std::pair<ColumnBase*, std::string>>* fields_ent_1 = new vector<std::pair<ColumnBase*, std::string>>;
    std::vector<std::pair<ColumnBase*, std::string>>* fields_ent_2 = new vector<std::pair<ColumnBase*, std::string>>;
    std::vector<std::pair<std::string, std::string>>* fields_rel_1 = new vector<std::pair<std::string, std::string>>;
    std::vector<std::pair<std::string, std::string>>* fields_rel_2 = new vector<std::pair<std::string, std::string>>;

    // Popualate fields
    fields_ent_1->push_back(std::make_pair(getColumnType("integer"), "a"));
    fields_ent_2->push_back(std::make_pair(getColumnType("string"), "b"));
    fields_rel_1->push_back(std::make_pair("a", "1"));
    fields_rel_2->push_back(std::make_pair("b", "hello"));

    // Create entities
    ih.writeEntity("test_1", fields_ent_1);
    ih.writeEntity("test_2", fields_ent_1);

    // Create relation in redis
    ih.writeRelation("test_1", "test_2", fields_rel_1, fields_rel_2);

    // Fetch the entity representation
    ret = ih.fetchRelationPrefix("test_1", "test_2");
    for (std::vector<Json::Value>::iterator it = ret.begin(); it != ret.end(); ++it)
        cout << (*it).toStyledString() << endl;

    // assert
}

int main() {
    cout << "-- TESTS BEGIN --" << endl << endl;

//    testRedisSet();
//    testRedisGet();
//    testRedisKeys();
//    md5Hashing();
//    testRedisIO();
//    testRegexForTypes();
//    testOrderPairAlphaNumeric();
    testJSONEntityEncoding();

    cout << endl << "-- TESTS END --" << endl;

    return 0;
}
<commit_msg>flesh out test for relation encoding<commit_after>
/*
 *  client.cpp
 *
 *  Handles the client env.
 *
 *  Created by Ryan Faulkner on 2014-06-08
 *  Copyright (c) 2014. All rights reserved.
 */

#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>

#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"

#define REDISHOST "127.0.0.1"
#define REDISPORT 6379

using namespace std;

/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
    RedisHandler r;
    r.connect();
    r.write("foo", "bar");
}

/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
    RedisHandler r;
    r.connect();
    cout << endl << "VALUE FOR KEY foo" << endl;
    cout << r.read("foo") << endl << endl;
}

/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
    RedisHandler r;
    std::vector<std::string> vec;

    r.connect();
    vec = r.keys("*");
    cout << "KEY LIST FOR *" << endl;
    for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
        cout << *it << endl;
    }
    cout << endl;
}

/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
    RedisHandler r;
    std::vector<string>* vec;
    std::string outTrue, outFalse = "";

    r.connect();
    r.write("test_key", "test value");
    outTrue = r.read("test_key");
    assert(std::strcmp(outTrue.c_str(), "test value") == 0);
    r.deleteKey("test_key");
    assert(!r.exists("test_key"));
}

/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
    cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}

/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
    IntegerColumn ic;
    FloatColumn fc;
    assert(ic.validate("1981"));
    assert(fc.validate("5.2"));
    cout << "Passed regex tests." << endl;
}

/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
    IndexHandler ih;
    assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
    cout << "Passed orderPairAlphaNumeric tests." << endl;
}

/**
 * Test to ensure that relation entities are encoded properly
 */
void testJSONEntityEncoding() {

    IndexHandler ih;
    Json::Value json;
    std::vector<std::pair<ColumnBase*, std::string>>* fields_ent = new vector<std::pair<ColumnBase*, std::string>>;

    fields_ent->push_back(std::make_pair(getColumnType("integer"), "a"));   // Create fields
    ih.writeEntity("test", fields_ent);     // Create the entity
    ih.fetchEntity("test", json);           // Fetch the entity representation
    cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;

    // Assert that entity as read matches definition
    assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
            std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
            json["fields"]["fields_count"].asInt() == 1
    );
    ih.removeEntity("test");                // Remove the entity
}

/**
 * Test to ensure that relation fields are encoded properly
 */
void testJSONRelationEncoding() {
    IndexHandler ih;
    std::vector<Json::Value> ret;
    std::vector<std::pair<ColumnBase*, std::string>>* fields_ent_1 = new vector<std::pair<ColumnBase*, std::string>>;
    std::vector<std::pair<ColumnBase*, std::string>>* fields_ent_2 = new vector<std::pair<ColumnBase*, std::string>>;
    std::vector<std::pair<std::string, std::string>>* fields_rel_1 = new vector<std::pair<std::string, std::string>>;
    std::vector<std::pair<std::string, std::string>>* fields_rel_2 = new vector<std::pair<std::string, std::string>>;

    // Popualate fields
    fields_ent_1->push_back(std::make_pair(getColumnType("integer"), "a"));
    fields_ent_2->push_back(std::make_pair(getColumnType("string"), "b"));
    fields_rel_1->push_back(std::make_pair("a", "1"));
    fields_rel_2->push_back(std::make_pair("b", "hello"));

    // Create entities
    ih.writeEntity("test_1", fields_ent_1);
    ih.writeEntity("test_2", fields_ent_1);

    // Create relation in redis
    ih.writeRelation("test_1", "test_2", fields_rel_1, fields_rel_2);

    // Fetch the entity representation
    ret = ih.fetchRelationPrefix("test_1", "test_2");
    cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl;

    // Assert that entity as read matches definition
    assert(
        std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 &&
        std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 &&
        std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 &&
        std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 &&
        ret[0]["fields_left"]["fields_count"].asInt() == 1 &&
        ret[0]["fields_right"]["fields_count"].asInt() == 1
    );
    ih.removeEntity("test_1");                // Remove the entity
    ih.removeEntity("test_2");                // Remove the entity
    ih.removeRelation("test_1", "test_2", fields_rel_1, fields_rel_2);    // Remove the relation
}

int main() {
    cout << "-- TESTS BEGIN --" << endl << endl;

//    testRedisSet();
//    testRedisGet();
//    testRedisKeys();
//    md5Hashing();
//    testRedisIO();
//    testRegexForTypes();
//    testOrderPairAlphaNumeric();

    testJSONEntityEncoding();
    testJSONRelationEncoding();

    cout << endl << "-- TESTS END --" << endl;

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <ctime>

#include "marian.h"

marian::Var layer(size_t max) {

    using namespace marian;

    Var x0 = 1, x1 = 2, x2 = 3;
    Var y = 0.0;
    for(int i = 0; i < max; i++) {
        Var xi = i;
        y = y + x0 + log(x2) + x1;
        for(int j = 0; j < i; ++j) {
            y = y + xi;
        }
    }

    return y;
}

int main(int argc, char** argv) {
    srand(time(NULL));

    using namespace marian;

    Var y1 = layer(10);
    Var y2 = layer(rand() % 20 + 1);

    Var y = y1 + log(y2);

    set_zero_all_adjoints();
    y.calc_gradients();

    std::cerr << "y1 = " << y1.val() << std::endl;
    std::cerr << "y2 = " << y2.val() << std::endl;
    std::cerr << "y = " << y.val() << std::endl;

    std::cerr << "dy/dy1 = " << y1.grad() << std::endl;
    std::cerr << "dy/dy2 = " << y2.grad() << std::endl;

}<commit_msg>more loops<commit_after>#include <iostream>
#include <ctime>

#include "marian.h"

using namespace marian;

Var layer(size_t max, std::vector<Var>& x) {
    Var x0 = 1, x1 = 2, x2 = 3;
    x = { x0, x1, x2 };

    Var y = 0.0;
    for(int i = 0; i < max; i++) {
        Var xi = i;
        x.push_back(xi);
        y = y + x0 + log(x2) + x1;
        for(int j = 0; j < i; ++j) {
            y = y + xi;
        }
    }

    return y;
}

int main(int argc, char** argv) {
    srand(time(NULL));

    std::vector<Var> x1, x2;
    Var y1 = layer(10, x1);
    Var y2 = layer(rand() % 20 + 1, x2);

    Var y = y1 + log(y2);

    set_zero_all_adjoints();
    y.calc_gradients();

    std::cerr << "y1 = " << y1.val() << std::endl;
    std::cerr << "y2 = " << y2.val() << std::endl;
    std::cerr << "y = " << y.val() << std::endl;

    std::cerr << "dy/dy1 = " << y1.grad() << std::endl;
    std::cerr << "dy/dy2 = " << y2.grad() << std::endl;

    for(size_t i = 0; i < x1.size(); ++i)
        std::cerr << "dy/dx1_" << i << " = " << x1[i].grad() << std::endl;
    for(size_t i = 0; i < x2.size(); ++i)
        std::cerr << "dy/dx2_" << i << " = " << x2[i].grad() << std::endl;

}<|endoftext|>


<commit_before>#include "info_entry.hh"
#include <iostream>
using namespace std;

bool InfoEntry::validate(const string& s)
{
	if (_validator) return _validator(s);
	return true;
}

void InfoEntry::theme(const string& name)
{
	get_style_context()->add_class(name);
}

InfoEntry::InfoEntry(const string& placeholder)
{
	set_placeholder_text(placeholder);
	reset();

	signal_changed().connect([&]() {
		validate();
	});
}

bool InfoEntry::validate()
{
	if (validate(get_text())) {
		theme("info");
		return true;
	}

	theme("error");
	return false;
}

void InfoEntry::reset()
{
	set_text("");
	theme("info");
}

bool InfoEntry::on_key_press_event(GdkEventKey* ev)
{
	if (ev->keyval == GDK_KEY_Escape) {
		_signal_cancel.emit();
		return true;
	}
	return Entry::on_key_press_event(ev);
}

<commit_msg>bugfix: recover color<commit_after>#include "info_entry.hh"
#include <iostream>
using namespace std;

bool InfoEntry::validate(const string& s)
{
	if (_validator) return _validator(s);
	return true;
}

void InfoEntry::theme(const string& name)
{
	static string last_name;
	auto context = get_style_context();
	context->remove_class(last_name);
	context->add_class(name);
	last_name = name;
}

InfoEntry::InfoEntry(const string& placeholder)
{
	set_placeholder_text(placeholder);
	reset();

	signal_changed().connect([&]() {
		validate();
	});
}

bool InfoEntry::validate()
{
	if (validate(get_text())) {
		theme("info");
		return true;
	}

	theme("error");
	return false;
}

void InfoEntry::reset()
{
	set_text("");
	theme("info");
}

bool InfoEntry::on_key_press_event(GdkEventKey* ev)
{
	if (ev->keyval == GDK_KEY_Escape) {
		_signal_cancel.emit();
		return true;
	}
	return Entry::on_key_press_event(ev);
}

<|endoftext|>


<commit_before>// ---------------------------------------------------------------------------
//
// This file is part of the <kortex> library suite
//
// Copyright (C) 2014 Engin Tola
//
// See LICENSE file for license information.
//
// author: Engin Tola
// e-mail: engintola@gmail.com
// web   : http://www.engintola.com
//
// ---------------------------------------------------------------------------

#include <kortex/timer.h>

namespace kortex {

    Timer::Timer() {
        st = std::chrono::high_resolution_clock::now();
        el = st;
    }
    double Timer::elapsed() {
        en = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> elapsed_seconds = en-el;
        el = en;
        return elapsed_seconds.count();
    }
    double Timer::end() {
        en = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> elapsed_seconds = en-st;
        st = en;
        el = en;
        return elapsed_seconds.count();
    }
    double Timer::duration() {
        en = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> elapsed_seconds = en-st;
        return elapsed_seconds.count();
    }

    void Timer::reset() {
        st = std::chrono::high_resolution_clock::now();
    }

}
<commit_msg>timer: bugfix - reset function resets elapsed beginning as well<commit_after>// ---------------------------------------------------------------------------
//
// This file is part of the <kortex> library suite
//
// Copyright (C) 2014 Engin Tola
//
// See LICENSE file for license information.
//
// author: Engin Tola
// e-mail: engintola@gmail.com
// web   : http://www.engintola.com
//
// ---------------------------------------------------------------------------

#include <kortex/timer.h>

namespace kortex {

    Timer::Timer() {
        reset();
    }
    double Timer::elapsed() {
        en = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> elapsed_seconds = en-el;
        el = en;
        return elapsed_seconds.count();
    }
    double Timer::end() {
        en = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> elapsed_seconds = en-st;
        st = en;
        el = en;
        return elapsed_seconds.count();
    }
    double Timer::duration() {
        en = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> elapsed_seconds = en-st;
        return elapsed_seconds.count();
    }

    void Timer::reset() {
        st = std::chrono::high_resolution_clock::now();
        el = st;
    }

}
<|endoftext|>


<commit_before>#include "model.h"
#include "octree_internal.h"
#include "helper.h"
#include <vector>
#include <GL/gl.h>
#include <iostream>
#include <memory>
#include <random>

//Implementação da classe tree!

using namespace tnw::octree;
using tnw::owner_ptr;
using std::make_unique;

tnw::octree::Tree::Tree(Tree* parent) {
	color = Color::black;
	this->parent = parent;

	std::random_device r;
	std::default_random_engine gen(r());

	std::uniform_real_distribution<> dis(0,1);

	for (int i = 0; i < 3; ++i)
	{
		drawColor[i] = dis(gen);
	}

}

tnw::octree::Tree::Tree(array<unique_ptr<Tree>,8>&& children, Tree* parent) {
	this->children = std::move(children);
	for (auto&& child : children) {
		if (child) {
			child->parent = this;
		}
	}
	color = Color::gray;
	this->parent = parent;

	std::random_device r;
	std::default_random_engine gen(r());

	std::uniform_real_distribution<> dis(0,1);

	for (int i = 0; i < 3; ++i) {
		drawColor[i] = dis(gen);
	}

}

tnw::octree::Tree::Tree(const Tree& o) {
	parent = nullptr;
	color = o.color;
	for (size_t i = 0; i < 3; ++i) {
		drawColor[i] = o.drawColor[i];
	}
	for (size_t i = 0; i < 8; ++i) {
		if (o.children[i]) {
			children[i] = make_unique<Tree>(*o.children[i]);
			children[i]->parent = this;
		}
	}
}

void tnw::octree::Tree::set(size_t i, unique_ptr<Tree>&& t) {
	children[i] = std::move(t);
}

Tree* tnw::octree::Tree::get(size_t i) {
	return children[i].get();
}

tnw::owner_ptr<Tree> tnw::octree::tree_and(Tree* t1, Tree* t2) {
	if (!t1 || !t2) return nullptr;
	if (t1->color == Color::black) return new Tree(*t2);
	if (t2->color == Color::black) return new Tree(*t1);

	owner_ptr<Tree> r = new Tree();
	r->color = Color::gray;
	size_t whiteCounter = 0;

	for (size_t i = 0; i < 8; ++i) {
		r->children[i] = unique_ptr<Tree>(tree_and(t1->get(i),t2->get(i)));
		if (!r->children[i]) whiteCounter++;
	}

	if (whiteCounter == 8) return nullptr;

	return r;
}

tnw::owner_ptr<Tree> tnw::octree::tree_or(Tree* t1, Tree* t2) {
	if (!t1 && !t2) return nullptr;
	if (!t1) return new Tree(*t2);
	if (!t2) return new Tree(*t1);
	if (t1->color == Color::black) return new Tree();
	if (t2->color == Color::black) return new Tree();

	owner_ptr<Tree> r = new Tree();
	r->color = Color::gray;
	size_t blackCounter = 0;

	for (size_t i = 0; i < 8; ++i) {
		r->children[i] = unique_ptr<Tree>(tree_or(t1->get(i),t2->get(i)));
		if (r->children[i] && r->children[i]->color == Color::black) blackCounter++;
	}

	if (blackCounter == 8) return new Tree();

	return r;
}

tnw::owner_ptr<Tree> tnw::octree::make_from_file(FILE* f) {
	char c;
	std::vector<int> counter{0};

	switch(fgetc(f)) {
		case 'b':
			return new Tree();
		case 'w':
			return nullptr;
	}

	owner_ptr<Tree> root = new Tree();
	root->color = Color::gray;

	Tree* cursor = root;
	while (((c = fgetc(f)) != '\n') && (c != EOF)) {
		switch(c) {
			case '(': {
				Tree* aux = cursor;
				cursor = new Tree(cursor);
				aux->set(counter.back(),unique_ptr<Tree>(cursor));
				cursor->color = Color::gray;
				counter.back()++;
				counter.push_back(0);
				break;
			}
			case 'b': {
				cursor->set(counter.back()++,make_unique<Tree>(cursor));
				break;
			}
			case 'w': {
				cursor->set(counter.back()++,nullptr);
				break;
			}
		}

		while (counter.back() == 8) {
			counter.pop_back();
			cursor = cursor->parent;
		}
	}

	return root;
}

// Todo - Make recursive version using std::vector
std::string tnw::octree::serialize(Tree* t) {
	if(!t) return "w";

	std::string o;
	if (t->color == Color::gray) {
		o += "(";
		for (auto&& c : t->children)
			o += serialize(c.get());
	}
	if (t->color == Color::black) {
		o += "b";
	}

	return o;
}

// Todo - Make recursive version using std::vector
owner_ptr<Tree> tnw::octree::classify(Classifier c, BoundingBox bb, unsigned int maxDepth, unsigned int currDepth){
	if (currDepth >= maxDepth) return nullptr;

	switch (c(bb)) {
		case Color::white:
			return nullptr;
		case Color::black:
			return new Tree();
		case Color::gray: break;
	}

	owner_ptr<Tree> r = new Tree();
	r->color = Color::gray;
	size_t countB = 0;
	size_t countW = 0;

	for (size_t i = 0; i < 8; ++i) {
		r->children[i].reset(classify(c, bb[i], maxDepth, currDepth+1));
		if(r->children[i] && r->children[i]->color == Color::black) countB++;
		if(!r->children[i]) countW++;
	}

	if (countB == 8) return new Tree();
	if (countW == 8) return nullptr;

	return r;
}

/* Recebe a própria bounding box do pai, e dependendo da sua cor faz o seguinte
 * Cinza - Chama o draw nos filhos, e desenha a própria bounding box como  wireframe
 * Preto - Desenha a própria bounding box como preenchida
 */
void tnw::octree::Tree::draw(const BoundingBox& bb){
	switch (color) {
		case Color::white: {
			//Não é pra acontecer!
			break;
		}

		case Color::gray: {
			for (int i = 0; i < 8; ++i) {
				if (children[i]) {
					children[i]->draw(bb[i]);
				}
			}
			break;
		}

		case Color::black: {
			// Desenha sólido em Cor aleatória
			glColor3f(drawColor[0], drawColor[1], drawColor[2]);
			// glColor3f(0,0,0.8);
			bb.draw();

			//Desenha wireframe cinza
			// glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
			// glColor3f(.5,.5,.5);
			// glLineWidth(0.5);
			// bb.draw();
			// glLineWidth(1.0);
			// glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );

			break;
		}

	}
}

void tnw::octree::Tree::setColor(float c[3]) {
	drawColor[0] = c[0];
	drawColor[1] = c[1];
	drawColor[2] = c[2];
	if (color == Color::gray) {
		for (auto&& child : children) {
			if (child) child->setColor(c);
		}
	}
}

double tnw::octree::Tree::volume() const {
	switch (color) {
		case Color::black : {
			return 1;
			break;
		}
		case Color::gray : {
			double volume_sum = 0;
			for (auto&& child : children) {
				if (child) volume_sum += child->volume();
			}
			return volume_sum/8.;
		}
		case Color::white: break;
	}
	return 0;
}
<commit_msg>Voltando a mostrar outline<commit_after>#include "model.h"
#include "octree_internal.h"
#include "helper.h"
#include <vector>
#include <GL/gl.h>
#include <iostream>
#include <memory>
#include <random>

//Implementação da classe tree!

using namespace tnw::octree;
using tnw::owner_ptr;
using std::make_unique;

tnw::octree::Tree::Tree(Tree* parent) {
	color = Color::black;
	this->parent = parent;

	std::random_device r;
	std::default_random_engine gen(r());

	std::uniform_real_distribution<> dis(0,1);

	for (int i = 0; i < 3; ++i)
	{
		drawColor[i] = dis(gen);
	}

}

tnw::octree::Tree::Tree(array<unique_ptr<Tree>,8>&& children, Tree* parent) {
	this->children = std::move(children);
	for (auto&& child : children) {
		if (child) {
			child->parent = this;
		}
	}
	color = Color::gray;
	this->parent = parent;

	std::random_device r;
	std::default_random_engine gen(r());

	std::uniform_real_distribution<> dis(0,1);

	for (int i = 0; i < 3; ++i) {
		drawColor[i] = dis(gen);
	}

}

tnw::octree::Tree::Tree(const Tree& o) {
	parent = nullptr;
	color = o.color;
	for (size_t i = 0; i < 3; ++i) {
		drawColor[i] = o.drawColor[i];
	}
	for (size_t i = 0; i < 8; ++i) {
		if (o.children[i]) {
			children[i] = make_unique<Tree>(*o.children[i]);
			children[i]->parent = this;
		}
	}
}

void tnw::octree::Tree::set(size_t i, unique_ptr<Tree>&& t) {
	children[i] = std::move(t);
}

Tree* tnw::octree::Tree::get(size_t i) {
	return children[i].get();
}

tnw::owner_ptr<Tree> tnw::octree::tree_and(Tree* t1, Tree* t2) {
	if (!t1 || !t2) return nullptr;
	if (t1->color == Color::black) return new Tree(*t2);
	if (t2->color == Color::black) return new Tree(*t1);

	owner_ptr<Tree> r = new Tree();
	r->color = Color::gray;
	size_t whiteCounter = 0;

	for (size_t i = 0; i < 8; ++i) {
		r->children[i] = unique_ptr<Tree>(tree_and(t1->get(i),t2->get(i)));
		if (!r->children[i]) whiteCounter++;
	}

	if (whiteCounter == 8) return nullptr;

	return r;
}

tnw::owner_ptr<Tree> tnw::octree::tree_or(Tree* t1, Tree* t2) {
	if (!t1 && !t2) return nullptr;
	if (!t1) return new Tree(*t2);
	if (!t2) return new Tree(*t1);
	if (t1->color == Color::black) return new Tree();
	if (t2->color == Color::black) return new Tree();

	owner_ptr<Tree> r = new Tree();
	r->color = Color::gray;
	size_t blackCounter = 0;

	for (size_t i = 0; i < 8; ++i) {
		r->children[i] = unique_ptr<Tree>(tree_or(t1->get(i),t2->get(i)));
		if (r->children[i] && r->children[i]->color == Color::black) blackCounter++;
	}

	if (blackCounter == 8) return new Tree();

	return r;
}

tnw::owner_ptr<Tree> tnw::octree::make_from_file(FILE* f) {
	char c;
	std::vector<int> counter{0};

	switch(fgetc(f)) {
		case 'b':
			return new Tree();
		case 'w':
			return nullptr;
	}

	owner_ptr<Tree> root = new Tree();
	root->color = Color::gray;

	Tree* cursor = root;
	while (((c = fgetc(f)) != '\n') && (c != EOF)) {
		switch(c) {
			case '(': {
				Tree* aux = cursor;
				cursor = new Tree(cursor);
				aux->set(counter.back(),unique_ptr<Tree>(cursor));
				cursor->color = Color::gray;
				counter.back()++;
				counter.push_back(0);
				break;
			}
			case 'b': {
				cursor->set(counter.back()++,make_unique<Tree>(cursor));
				break;
			}
			case 'w': {
				cursor->set(counter.back()++,nullptr);
				break;
			}
		}

		while (counter.back() == 8) {
			counter.pop_back();
			cursor = cursor->parent;
		}
	}

	return root;
}

// Todo - Make recursive version using std::vector
std::string tnw::octree::serialize(Tree* t) {
	if(!t) return "w";

	std::string o;
	if (t->color == Color::gray) {
		o += "(";
		for (auto&& c : t->children)
			o += serialize(c.get());
	}
	if (t->color == Color::black) {
		o += "b";
	}

	return o;
}

// Todo - Make recursive version using std::vector
owner_ptr<Tree> tnw::octree::classify(Classifier c, BoundingBox bb, unsigned int maxDepth, unsigned int currDepth){
	if (currDepth >= maxDepth) return nullptr;

	switch (c(bb)) {
		case Color::white:
			return nullptr;
		case Color::black:
			return new Tree();
		case Color::gray: break;
	}

	owner_ptr<Tree> r = new Tree();
	r->color = Color::gray;
	size_t countB = 0;
	size_t countW = 0;

	for (size_t i = 0; i < 8; ++i) {
		r->children[i].reset(classify(c, bb[i], maxDepth, currDepth+1));
		if(r->children[i] && r->children[i]->color == Color::black) countB++;
		if(!r->children[i]) countW++;
	}

	if (countB == 8) return new Tree();
	if (countW == 8) return nullptr;

	return r;
}

/* Recebe a própria bounding box do pai, e dependendo da sua cor faz o seguinte
 * Cinza - Chama o draw nos filhos, e desenha a própria bounding box como  wireframe
 * Preto - Desenha a própria bounding box como preenchida
 */
void tnw::octree::Tree::draw(const BoundingBox& bb){
	switch (color) {
		case Color::white: {
			//Não é pra acontecer!
			break;
		}

		case Color::gray: {
			for (int i = 0; i < 8; ++i) {
				if (children[i]) {
					children[i]->draw(bb[i]);
				}
			}
			break;
		}

		case Color::black: {
			// Desenha sólido em Cor aleatória
			glColor3f(drawColor[0], drawColor[1], drawColor[2]);
			// glColor3f(0,0,0.8);
			bb.draw();

			//Desenha wireframe cinza
			glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
			glColor3f(.5,.5,.5);
			glLineWidth(0.5);
			bb.draw();
			glLineWidth(1.0);
			glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );

			break;
		}

	}
}

void tnw::octree::Tree::setColor(float c[3]) {
	drawColor[0] = c[0];
	drawColor[1] = c[1];
	drawColor[2] = c[2];
	if (color == Color::gray) {
		for (auto&& child : children) {
			if (child) child->setColor(c);
		}
	}
}

double tnw::octree::Tree::volume() const {
	switch (color) {
		case Color::black : {
			return 1;
			break;
		}
		case Color::gray : {
			double volume_sum = 0;
			for (auto&& child : children) {
				if (child) volume_sum += child->volume();
			}
			return volume_sum/8.;
		}
		case Color::white: break;
	}
	return 0;
}
<|endoftext|>