<commit_before>// Copyright © 2013 Lénaïc Bagnères, hnc@singularity.fr

// 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.

#ifndef HNC_VALUE_PTR_HPP
#define HNC_VALUE_PTR_HPP

#include "copy_ptr.hpp"

namespace hnc
{
	/**
	 * @brief hnc::value_ptr of T is like a T with inclusion polymorphism
	 *
	 * @code
	 * #include <hnc/value_ptr.hpp>
	 * @endcode
	 *
	 * hnc::value_ptr performs a deep copy; it uses hnc::clone function which uses [virtual] .clone() method if it exists @n
	 * So, copy a hnc::value_ptr of base class which olds a derived class object works and does what you think
	 *
	 * Example:
	 * @code
	 * #include <iostream>
	 *
	 * #include <hnc/value_ptr.hpp>
	 *
	 * class A
	 * {
	 * public:
	 *
	 * 	virtual ~A() { }
	 *
	 * 	hnc_generate_clone_method(A, A)
	 *
	 * 	virtual void display(std::ostream & o) const { o << "one_A"; }
	 * };
	 *
	 * class B : public A
	 * {
	 * public:
	 *
	 * 	virtual ~B() { }
	 *
	 * 	hnc_generate_clone_method(A, B)
	 *
	 * 	virtual void display(std::ostream & o) const override { o << "one_B"; }
	 * };
	 *
	 * std::ostream & operator<<(std::ostream & o, A const & v) { v.display(o); return o; }
	 *
	 * int main()
	 * {
	 * 	// Create a A
	 * 	hnc::value_ptr<A> a = A();
	 * 	std::cout << a << std::endl; // one_A
	 *
	 * 	// Create a B
	 * 	hnc::value_ptr<A> b = B();
	 * 	std::cout << b << std::endl; // one_B
	 *
	 * 	// Copy
	 * 	hnc::value_ptr<A> c = b;
	 * 	std::cout << c << std::endl; // one_B
	 *
	 * 	return 0;
	 * }
	 * @endcode
	 */
	template <class T>
	class value_ptr : private hnc::copy_ptr<T>
	{
	public:

		/// @brief Default constructor
		value_ptr() : hnc::copy_ptr<T>(hnc::make_copy_ptr<T>())
		{ }

		/// @brief Constrcutor
		/// @param[in] value Value
		value_ptr(T const & value) : hnc::copy_ptr<T>(hnc::clone_to_unique_ptr(value).release())
		{ }

		/// @brief Copy constrcutor
		/// @param[in] value Value
		template <class U>
		value_ptr(hnc::value_ptr<U> const & value) : hnc::copy_ptr<T>(hnc::clone_to_unique_ptr(*value).release())
		{ }

		/// @brief Return the stored pointer
		/// @return the stored pointer
		using hnc::copy_ptr<T>::get;

		/// @brief Exchange the objects stored
		using hnc::copy_ptr<T>::swap;

		/// @brief Return a reference to the stored object
		/// @return a reference to the stored object
		using hnc::copy_ptr<T>::operator*;

		/// @brief Return a reference to the stored object to access of its members
		/// @return a reference to the stored object to access of its members
		using hnc::copy_ptr<T>::operator->;
	};
}

/// @brief std::swap between two hnc::value_ptr
hnc_overload_std_swap_with_swap_method_for_template_class(hnc::value_ptr<T>, class T)

/**
 * @brief Display a hnc::value_ptr of T
 *
 * @param[in,out] o     Out stream
 * @param[in]     value A hnc::value_ptr of T
 *
 * @return the out stream
 */
template <class T>
std::ostream & operator<<(std::ostream & o, hnc::value_ptr<T> const & value)
{
	o << *value;
	return o;
}

#endif
<commit_msg>Add equality operator between two hnc::value_ptr<T><commit_after>// Copyright © 2013, 2014 Lénaïc Bagnères, hnc@singularity.fr

// 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.

#ifndef HNC_VALUE_PTR_HPP
#define HNC_VALUE_PTR_HPP

#include "copy_ptr.hpp"

namespace hnc
{
	/**
	 * @brief hnc::value_ptr<T> is like a T with inclusion polymorphism
	 *
	 * @code
	 * #include <hnc/value_ptr.hpp>
	 * @endcode
	 *
	 * hnc::value_ptr performs a deep copy; it uses hnc::clone function which uses [virtual] .clone() method if it exists @n
	 * So, copy a hnc::value_ptr of base class which olds a derived class object works and does what you think
	 *
	 * Example:
	 * @code
	 * #include <iostream>
	 *
	 * #include <hnc/value_ptr.hpp>
	 *
	 * class A
	 * {
	 * public:
	 *
	 * 	virtual ~A() { }
	 *
	 * 	hnc_generate_clone_method(A, A)
	 *
	 * 	virtual void display(std::ostream & o) const { o << "one_A"; }
	 * };
	 *
	 * class B : public A
	 * {
	 * public:
	 *
	 * 	virtual ~B() { }
	 *
	 * 	hnc_generate_clone_method(A, B)
	 *
	 * 	virtual void display(std::ostream & o) const override { o << "one_B"; }
	 * };
	 *
	 * std::ostream & operator<<(std::ostream & o, A const & v) { v.display(o); return o; }
	 *
	 * int main()
	 * {
	 * 	// Create a A
	 * 	hnc::value_ptr<A> a = A();
	 * 	std::cout << a << std::endl; // one_A
	 *
	 * 	// Create a B
	 * 	hnc::value_ptr<A> b = B();
	 * 	std::cout << b << std::endl; // one_B
	 *
	 * 	// Copy
	 * 	hnc::value_ptr<A> c = b;
	 * 	std::cout << c << std::endl; // one_B
	 *
	 * 	return 0;
	 * }
	 * @endcode
	 */
	template <class T>
	class value_ptr : private hnc::copy_ptr<T>
	{
	public:

		/// @brief Default constructor
		value_ptr() : hnc::copy_ptr<T>(hnc::make_copy_ptr<T>())
		{ }

		/// @brief Constructor
		/// @param[in] value Value
		value_ptr(T const & value) : hnc::copy_ptr<T>(hnc::clone_to_unique_ptr(value).release())
		{ }

		/// @brief Copy constrcutor
		/// @param[in] value Value
		template <class U>
		value_ptr(hnc::value_ptr<U> const & value) : hnc::copy_ptr<T>(hnc::clone_to_unique_ptr(*value).release())
		{ }

		/// @brief Return the stored pointer
		/// @return the stored pointer
		using hnc::copy_ptr<T>::get;

		/// @brief Exchange the objects stored
		using hnc::copy_ptr<T>::swap;

		/// @brief Return a reference to the stored object
		/// @return a reference to the stored object
		using hnc::copy_ptr<T>::operator*;

		/// @brief Return a reference to the stored object to access of its members
		/// @return a reference to the stored object to access of its members
		using hnc::copy_ptr<T>::operator->;
	};

	/**
	 * @brief Equality operator between two hnc::value_ptr<T>
	 *
	 * @param[in] v0 An hnc::value_ptr<T>
	 * @param[in] v1 An hnc::value_ptr<T>
	 *
	 * @return true if hnc::value_ptr<T> are equals, false otherwise
	 */
	template <class T>
	bool operator==(hnc::value_ptr<T> const & v0, hnc::value_ptr<T> const & v1)
	{
		if (&v0 == &v1) { return true; }
		else { return (*v0 == *v1); }
	}

	/**
	 * @brief Inequality operator between two hnc::value_ptr<T>
	 *
	 * @param[in] v0 An hnc::value_ptr<T>
	 * @param[in] v1 An hnc::value_ptr<T>
	 *
	 * @return true if hnc::value_ptr<T> are not equals, false otherwise
	 */
	template <class T>
	bool operator!=(hnc::value_ptr<T> const & v0, hnc::value_ptr<T> const & v1)
	{
		return (!(v0 == v1));
	}
}

/// @brief std::swap between two hnc::value_ptr
hnc_overload_std_swap_with_swap_method_for_template_class(hnc::value_ptr<T>, class T)

/**
 * @brief Display a hnc::value_ptr<T>
 *
 * @param[in,out] o     Out stream
 * @param[in]     value A hnc::value_ptr<T>
 *
 * @return the out stream
 */
template <class T>
std::ostream & operator<<(std::ostream & o, hnc::value_ptr<T> const & value)
{
	o << *value;
	return o;
}

#endif
<|endoftext|>


<commit_before>//
//  benchmark.cpp
//
//
//  Created by Julian Karch on 17/09/15.
//
//

#include "benchmark.h"

std::stack<clock_t> tictoc_stack;

void tic() {
    tictoc_stack.push(clock());
}

double toc() {
    clock_t tmp=tictoc_stack.top();
    tictoc_stack.pop();
    return(((double)(clock() - tmp)) / CLOCKS_PER_SEC);
}<commit_msg>changes by michael krause<commit_after>//
//  benchmark.cpp
//
//
//  Created by Julian Karch on 17/09/15.
//
//

#include "benchmark.h"

std::stack<clock_t> tictoc_stack;

void tic() {
    #pragma omp critical
    {
    tictoc_stack.push(clock());
    }
}

double toc() {
    clock_t tmp;
    #pragma omp critical
    {
    tmp = tictoc_stack.top();
    tictoc_stack.pop();
    }
    return(((double)(clock() - tmp)) / CLOCKS_PER_SEC);
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#ifndef _OCTREE_HPP_
#define _OCTREE_HPP_

#include <boost/format.hpp>
#include <boost/utility.hpp>
#include <vector>
#include <iostream>
#include <deque>

namespace mapnik {

   typedef uint8_t byte ;
   struct rgb
   {
         byte r;
         byte g;
         byte b;
         rgb(byte r_, byte b_, byte g_)
            : r(r_), g(g_), b(b_) {}
   };

   struct RGBPolicy
   {
         const static unsigned MAX_LEVELS = 6;
         inline static unsigned index_from_level(unsigned level, rgb const& c)
         {
            unsigned shift = (MAX_LEVELS + 1) - level;
            return (((c.r >> shift) & 1) << 2)
               | (((c.g >> shift) & 1) << 1)
               | ((c.b >> shift) & 1);
         }
   };

   template <typename T, typename InsertPolicy = RGBPolicy >
   class octree : private boost::noncopyable
   {
         struct node
         {
               node ()
                  :  reds(0),
                     greens(0),
                     blues(0),
                     count(0),
                     index(0)
               {
                  memset(&children_[0],0,sizeof(children_));
               }

               ~node ()
               {
                  for (unsigned i = 0;i < 8; ++i) {
                     if (children_[i] != 0) delete children_[i],children_[i]=0;
                  }
               }

               bool is_leaf() const { return count == 0; }
               node * children_[8];
               unsigned reds;
               unsigned greens;
               unsigned blues;
               unsigned count;
               uint8_t  index;
         };
         struct node_cmp
         {
               bool operator() ( const node * lhs,const node* rhs) const
               {
                  unsigned left_total=0;
                  unsigned right_total=0;
                  for (unsigned i=0; i<8;++i)
                  {
                     if (lhs->children_[i]) left_total+=lhs->children_[i]->count;
                     if (rhs->children_[i]) right_total+=rhs->children_[i]->count;
                  }
                  return left_total > right_total;
               }
         };

         std::deque<node*> reducible_[InsertPolicy::MAX_LEVELS];
         unsigned max_colors_;
         unsigned colors_;
         unsigned leaf_level_;

      public:
         explicit octree(unsigned max_colors=256)
            : max_colors_(max_colors),
              colors_(0),
              leaf_level_(InsertPolicy::MAX_LEVELS),
              root_(new node())
         {}

         ~octree() { delete root_;}

         void insert(T const& data)
         {
            unsigned level = 0;
            node * cur_node = root_;
            while (true) {

               if ( cur_node->count > 0 || level == leaf_level_)
               {
                  cur_node->reds   += data.r;
                  cur_node->greens += data.g;
                  cur_node->blues  += data.b;
                  cur_node->count  += 1;
                  if (cur_node->count == 1) ++colors_;
                  //if (colors_ >= max_colors_ - 1)
                  //reduce();
                  break;
               }

               unsigned idx = InsertPolicy::index_from_level(level,data);
               if (cur_node->children_[idx] == 0) {
                  cur_node->children_[idx] = new node();
                  if (level < leaf_level_-1)
                  {
                     reducible_[level+1].push_back(cur_node->children_[idx]);
                  }
               }
               cur_node = cur_node->children_[idx];
               ++level;
            }
         }

         int quantize(rgb const& c) const
         {
            unsigned level = 0;
            node * cur_node = root_;
            while (cur_node)
            {
               if (cur_node->count != 0) return cur_node->index;
               unsigned idx = InsertPolicy::index_from_level(level,c);
               cur_node = cur_node->children_[idx];
               ++level;
            }
            return -1;
         }

         void create_palette(std::vector<rgb> & palette)
         {
            reduce();
            palette.reserve(colors_);
            create_palette(palette, root_);
         }

         void reduce()
         {
            // sort reducible
            for (unsigned i=0;i<InsertPolicy::MAX_LEVELS;++i)
            {
               std::sort(reducible_[i].begin(), reducible_[i].end(),node_cmp());
            }

            while ( colors_ >= max_colors_ - 1)
            {
               while (leaf_level_ >0  && reducible_[leaf_level_-1].size() == 0)
               {
                  --leaf_level_;
               }

               if (leaf_level_ < 1) continue;

               if ( reducible_[leaf_level_-1].size() == 0) return;

               typename std::deque<node*>::iterator pos = reducible_[leaf_level_-1].begin();
               node * cur_node = *pos;
               unsigned num_children = 0;
               for (unsigned idx=0; idx < 8; ++idx)
               {
                  if (cur_node->children_[idx] != 0)
                  {
                     ++num_children;
                     cur_node->reds   += cur_node->children_[idx]->reds;
                     cur_node->greens += cur_node->children_[idx]->greens;
                     cur_node->blues  += cur_node->children_[idx]->blues;
                     cur_node->count  += cur_node->children_[idx]->count;
                     delete cur_node->children_[idx], cur_node->children_[idx]=0;
                  }
               }

               reducible_[leaf_level_-1].erase(pos);
               if (num_children > 0 )
               {
                  colors_ -= (num_children - 1);
               }
            }
         }

         void create_palette(std::vector<rgb> & palette, node * itr) const
         {
            if (itr->count != 0)
            {
               unsigned count = itr->count;
               palette.push_back(rgb(uint8_t(itr->reds/float(count)),
                                     uint8_t(itr->greens/float(count)),
                                     uint8_t(itr->blues/float(count))));
               itr->index = palette.size() - 1;
            }
            for (unsigned i=0; i < 8 ;++i)
            {
               if (itr->children_[i] != 0)
                  create_palette(palette, itr->children_[i]);
            }
         }
      private:
         node * root_;
   };
} // namespace mapnik

#endif /* _OCTREE_HPP_ */
<commit_msg>corrected sorting criteria<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#ifndef _OCTREE_HPP_
#define _OCTREE_HPP_

#include <boost/format.hpp>
#include <boost/utility.hpp>
#include <vector>
#include <iostream>
#include <deque>

namespace mapnik {

   typedef uint8_t byte ;
   struct rgb
   {
         byte r;
         byte g;
         byte b;
         rgb(byte r_, byte b_, byte g_)
            : r(r_), g(g_), b(b_) {}
   };

   struct RGBPolicy
   {
         const static unsigned MAX_LEVELS = 6;
         inline static unsigned index_from_level(unsigned level, rgb const& c)
         {
            unsigned shift = (MAX_LEVELS + 1) - level;
            return (((c.r >> shift) & 1) << 2)
               | (((c.g >> shift) & 1) << 1)
               | ((c.b >> shift) & 1);
         }
   };

   template <typename T, typename InsertPolicy = RGBPolicy >
   class octree : private boost::noncopyable
   {
         struct node
         {
               node ()
                  :  reds(0),
                     greens(0),
                     blues(0),
                     count(0),
                     index(0)
               {
                  memset(&children_[0],0,sizeof(children_));
               }

               ~node ()
               {
                  for (unsigned i = 0;i < 8; ++i) {
                     if (children_[i] != 0) delete children_[i],children_[i]=0;
                  }
               }

               bool is_leaf() const { return count == 0; }
               node * children_[8];
               unsigned reds;
               unsigned greens;
               unsigned blues;
               unsigned count;
               uint8_t  index;
         };
         struct node_cmp
         {
               bool operator() ( const node * lhs,const node* rhs) const
               {
                  unsigned left_total=0;
                  unsigned right_total=0;
                  for (unsigned i=0; i<8;++i)
                  {
                     if (lhs->children_[i]) left_total+=lhs->children_[i]->count;
                     if (rhs->children_[i]) right_total+=rhs->children_[i]->count;
                  }
                  return left_total < right_total;
               }
         };

         std::deque<node*> reducible_[InsertPolicy::MAX_LEVELS];
         unsigned max_colors_;
         unsigned colors_;
         unsigned leaf_level_;

      public:
         explicit octree(unsigned max_colors=256)
            : max_colors_(max_colors),
              colors_(0),
              leaf_level_(InsertPolicy::MAX_LEVELS),
              root_(new node())
         {}

         ~octree() { delete root_;}

         void insert(T const& data)
         {
            unsigned level = 0;
            node * cur_node = root_;
            while (true) {

               if ( cur_node->count > 0 || level == leaf_level_)
               {
                  cur_node->reds   += data.r;
                  cur_node->greens += data.g;
                  cur_node->blues  += data.b;
                  cur_node->count  += 1;
                  if (cur_node->count == 1) ++colors_;
                  //if (colors_ >= max_colors_ - 1)
                  //reduce();
                  break;
               }

               unsigned idx = InsertPolicy::index_from_level(level,data);
               if (cur_node->children_[idx] == 0) {
                  cur_node->children_[idx] = new node();
                  if (level < leaf_level_-1)
                  {
                     reducible_[level+1].push_back(cur_node->children_[idx]);
                  }
               }
               cur_node = cur_node->children_[idx];
               ++level;
            }
         }

         int quantize(rgb const& c) const
         {
            unsigned level = 0;
            node * cur_node = root_;
            while (cur_node)
            {
               if (cur_node->count != 0) return cur_node->index;
               unsigned idx = InsertPolicy::index_from_level(level,c);
               cur_node = cur_node->children_[idx];
               ++level;
            }
            return -1;
         }

         void create_palette(std::vector<rgb> & palette)
         {
            reduce();
            palette.reserve(colors_);
            create_palette(palette, root_);
         }

         void reduce()
         {
            // sort reducible
            for (unsigned i=0;i<InsertPolicy::MAX_LEVELS;++i)
            {
               std::sort(reducible_[i].begin(), reducible_[i].end(),node_cmp());
            }

            while ( colors_ >= max_colors_ - 1)
            {
               while (leaf_level_ >0  && reducible_[leaf_level_-1].size() == 0)
               {
                  --leaf_level_;
               }

               if (leaf_level_ < 1) continue;

               if ( reducible_[leaf_level_-1].size() == 0) return;

               typename std::deque<node*>::iterator pos = reducible_[leaf_level_-1].begin();
               node * cur_node = *pos;
               unsigned num_children = 0;
               for (unsigned idx=0; idx < 8; ++idx)
               {
                  if (cur_node->children_[idx] != 0)
                  {
                     ++num_children;
                     cur_node->reds   += cur_node->children_[idx]->reds;
                     cur_node->greens += cur_node->children_[idx]->greens;
                     cur_node->blues  += cur_node->children_[idx]->blues;
                     cur_node->count  += cur_node->children_[idx]->count;
                     delete cur_node->children_[idx], cur_node->children_[idx]=0;
                  }
               }

               reducible_[leaf_level_-1].erase(pos);
               if (num_children > 0 )
               {
                  colors_ -= (num_children - 1);
               }
            }
         }

         void create_palette(std::vector<rgb> & palette, node * itr) const
         {
            if (itr->count != 0)
            {
               unsigned count = itr->count;
               palette.push_back(rgb(uint8_t(itr->reds/float(count)),
                                     uint8_t(itr->greens/float(count)),
                                     uint8_t(itr->blues/float(count))));
               itr->index = palette.size() - 1;
            }
            for (unsigned i=0; i < 8 ;++i)
            {
               if (itr->children_[i] != 0)
                  create_palette(palette, itr->children_[i]);
            }
         }
      private:
         node * root_;
   };
} // namespace mapnik

#endif /* _OCTREE_HPP_ */
<|endoftext|>


<commit_before>//--------------------------------------------------------------------------------------------------
//
///	@PROJECT	gtest-gui
/// @BRIEF		main file for gtest-gui
///	@DETAILS
//
//--------------------------------------------------------------------------------------------------
//
// The MIT License (MIT)
//
// 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.
//
//--------------------------------------------------------------------------------------------------
//
// ATTRIBUTION:
// Parts of this work have been adapted from:
//
//--------------------------------------------------------------------------------------------------
//
// Copyright (c) 2016 Nic Holthaus
//
//--------------------------------------------------------------------------------------------------

//------------------------------
//	INCLUDE
//------------------------------

// Qt
#include <QApplication>

// gtest-gui
#include "appinfo.h"
#include "mainwindow.h"

int main(int argc, char *argv[])
{
//	Q_INIT_RESOURCE(application);

	QApplication app(argc, argv);
	app.setOrganizationName(APPINFO::organization);
	app.setOrganizationDomain(APPINFO::oranizationDomain);
	app.setApplicationName(APPINFO::name);
	app.setApplicationVersion(APPINFO::version);
	MainWindow mainWin;
	mainWin.show();
	return app.exec();
}<commit_msg>fixed issue with improper scaling for high-DPI monitors.<commit_after>//--------------------------------------------------------------------------------------------------
//
///	@PROJECT	gtest-gui
/// @BRIEF		main file for gtest-gui
///	@DETAILS
//
//--------------------------------------------------------------------------------------------------
//
// The MIT License (MIT)
//
// 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.
//
//--------------------------------------------------------------------------------------------------
//
// ATTRIBUTION:
// Parts of this work have been adapted from:
//
//--------------------------------------------------------------------------------------------------
//
// Copyright (c) 2016 Nic Holthaus
//
//--------------------------------------------------------------------------------------------------

//------------------------------
//	INCLUDE
//------------------------------

// Qt
#include <QApplication>

// gtest-gui
#include "appinfo.h"
#include "mainwindow.h"

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

	QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

	QApplication app(argc, argv);
	app.setOrganizationName(APPINFO::organization);
	app.setOrganizationDomain(APPINFO::oranizationDomain);
	app.setApplicationName(APPINFO::name);
	app.setApplicationVersion(APPINFO::version);
	MainWindow mainWin;
	mainWin.show();
	return app.exec();
}<|endoftext|>


<commit_before>#include "Stdafx.h"

#define PROG_NAME "shootergameserver.exe"

std::string pName;

#pragma region VersionWrapper
HINSTANCE hmMain = 0;
HINSTANCE hmVersion = 0;
extern "C" FARPROC versionFunctions[17] = { 0 };
#pragma endregion

void threadMain();

bool APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved)
{
	switch (reason)
	{
	case DLL_PROCESS_ATTACH:
	{
		DWORD pID = GetCurrentProcessId();
		TCHAR buffer[MAX_PATH] = { 0 };
		TCHAR* out;
		DWORD bufSize = sizeof(buffer) / sizeof(*buffer);
		GetModuleFileName(NULL, buffer, bufSize);
		out = PathFindFileName(buffer);
		std::string pName = out;
		std::transform(pName.begin(), pName.end(), pName.begin(), tolower);
		if (pName == PROG_NAME)
		{
			hmMain = hModule;
			char infoBuf[MAX_PATH];
			strcpy_s(infoBuf, MAX_PATH, "c:\\windows\\system32\\version.dll");
			hmVersion = LoadLibrary(infoBuf);
			if (!hmVersion)
			{
				MessageBox(NULL, "The original version.dll could not be found.", "MetaArkInjector", MB_OK | MB_ICONERROR);
				return false;
			}
			versionFunctions[0] = GetProcAddress(hmVersion, "GetFileVersionInfoA");
			versionFunctions[1] = GetProcAddress(hmVersion, "GetFileVersionInfoByHandle");
			versionFunctions[2] = GetProcAddress(hmVersion, "GetFileVersionInfoExA");
			versionFunctions[3] = GetProcAddress(hmVersion, "GetFileVersionInfoExW");
			versionFunctions[4] = GetProcAddress(hmVersion, "GetFileVersionInfoSizeA");
			versionFunctions[5] = GetProcAddress(hmVersion, "GetFileVersionInfoSizeExA");
			versionFunctions[6] = GetProcAddress(hmVersion, "GetFileVersionInfoSizeExW");
			versionFunctions[7] = GetProcAddress(hmVersion, "GetFileVersionInfoSizeW");
			versionFunctions[8] = GetProcAddress(hmVersion, "GetFileVersionInfoW");
			versionFunctions[9] = GetProcAddress(hmVersion, "VerFindFileA");
			versionFunctions[10] = GetProcAddress(hmVersion, "VerFindFileW");
			versionFunctions[11] = GetProcAddress(hmVersion, "VerInstallFileA");
			versionFunctions[12] = GetProcAddress(hmVersion, "VerInstallFileW");
			versionFunctions[13] = GetProcAddress(hmVersion, "VerLanguageNameA");
			versionFunctions[14] = GetProcAddress(hmVersion, "VerLanguageNameW");
			versionFunctions[15] = GetProcAddress(hmVersion, "VerQueryValueA");
			versionFunctions[16] = GetProcAddress(hmVersion, "VerQueryValueW");
			CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)threadMain, NULL, NULL, NULL);
		}
		break;
	}
	case DLL_PROCESS_DETACH:
	{
		if (pName == PROG_NAME)
			FreeLibrary(hmVersion);
		break;
	}
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
		break;
	}
	return true;
}<commit_msg>Remove unnecessary code.<commit_after>#include "Stdafx.h"

#define PROG_NAME "ShooterGameServer.exe"

std::string pName;

#pragma region VersionWrapper
HINSTANCE hmMain = 0;
HINSTANCE hmVersion = 0;
extern "C" FARPROC versionFunctions[17] = { 0 };
#pragma endregion

void threadMain();

#pragma unmanaged
bool APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved)
{
	switch (reason)
	{
	case DLL_PROCESS_ATTACH:
	{
		DWORD pID = GetCurrentProcessId();
		TCHAR buffer[MAX_PATH] = { 0 };
		DWORD bufSize = sizeof(buffer) / sizeof(*buffer);
		GetModuleFileName(NULL, buffer, bufSize);
		pName = PathFindFileName(buffer);

		if (pName == PROG_NAME)
		{
			hmMain = hModule;
			char infoBuf[MAX_PATH];
			strcpy_s(infoBuf, MAX_PATH, "c:\\windows\\system32\\version.dll");
			hmVersion = LoadLibrary(infoBuf);
			if (!hmVersion)
			{
				MessageBox(NULL, "The original version.dll could not be found.", "MetaArkInjector", MB_OK | MB_ICONERROR);
				return false;
			}
			versionFunctions[0] = GetProcAddress(hmVersion, "GetFileVersionInfoA");
			versionFunctions[1] = GetProcAddress(hmVersion, "GetFileVersionInfoByHandle");
			versionFunctions[2] = GetProcAddress(hmVersion, "GetFileVersionInfoExA");
			versionFunctions[3] = GetProcAddress(hmVersion, "GetFileVersionInfoExW");
			versionFunctions[4] = GetProcAddress(hmVersion, "GetFileVersionInfoSizeA");
			versionFunctions[5] = GetProcAddress(hmVersion, "GetFileVersionInfoSizeExA");
			versionFunctions[6] = GetProcAddress(hmVersion, "GetFileVersionInfoSizeExW");
			versionFunctions[7] = GetProcAddress(hmVersion, "GetFileVersionInfoSizeW");
			versionFunctions[8] = GetProcAddress(hmVersion, "GetFileVersionInfoW");
			versionFunctions[9] = GetProcAddress(hmVersion, "VerFindFileA");
			versionFunctions[10] = GetProcAddress(hmVersion, "VerFindFileW");
			versionFunctions[11] = GetProcAddress(hmVersion, "VerInstallFileA");
			versionFunctions[12] = GetProcAddress(hmVersion, "VerInstallFileW");
			versionFunctions[13] = GetProcAddress(hmVersion, "VerLanguageNameA");
			versionFunctions[14] = GetProcAddress(hmVersion, "VerLanguageNameW");
			versionFunctions[15] = GetProcAddress(hmVersion, "VerQueryValueA");
			versionFunctions[16] = GetProcAddress(hmVersion, "VerQueryValueW");
			CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)threadMain, NULL, NULL, NULL);
		}
		break;
	}
	case DLL_PROCESS_DETACH:
	{
		if (pName == PROG_NAME)
			FreeLibrary(hmVersion);
		break;
	}
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
		break;
	}
	return true;
}<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: raster.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef RASTER_HPP
#define RASTER_HPP

#include <mapnik/graphics.hpp>

namespace mapnik {
    struct raster
    {
        Envelope<double> ext_;
        ImageData32 data_;
        raster(Envelope<double> const ext,ImageData32& data)
            : ext_(ext),
              data_(data) {}
    };
}

#endif //RASTER_HPP

<commit_msg>+ pass parameter by const ref<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: raster.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef RASTER_HPP
#define RASTER_HPP

#include <mapnik/graphics.hpp>

namespace mapnik {
    struct raster
    {
        Envelope<double> ext_;
        ImageData32 data_;
        raster(Envelope<double> const& ext,ImageData32& data)
            : ext_(ext),
              data_(data) {}
    };
}

#endif //RASTER_HPP

<|endoftext|>


<commit_before>#include <iostream>
#include <queue>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "Shell.h"
#include "Input.h"

using namespace std;

int main() {
    Input in;
    queue<string> tasks;

    // to exit while loop, user must type exit
    while(1) {

        in.getInput();
        // bool test = in.isTest();
        // cout << "test: " << test << endl;
        // exit(0);
        tasks = in.Parse();

        cout << "size: " << tasks.size() << endl;

        // while (tasks.size() != 0) {
        //     cout << tasks.front() << endl;
        //     tasks.pop();
        // }

        // exit(0);

        // bool determines whether command was successful
        bool comp_status = true;
        char** c;
        Execute ex;

        // TEST STUFF
        Test test;

        while (tasks.size() != 0) {

            // if at any point the user has exit
            if (tasks.front() == "exit") {
                cout << "You have exited shell." << endl;
                exit(0);
            }

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

            else if (tasks.front() == "&&") {
	            tasks.pop(); //gets rid of the &&
                // if the command before this one does returns F,then dont do
                // //the next command
	            if(comp_status == false) {
		        // so the && connector should have already been deleted,
                // this is a while loop to
                // delete the next commands so that they wont run if
                // the command before fails
		            if(tasks.size() != 0) {
			            if(tasks.front() != "&&" || tasks.front() != "||" ||
                                tasks.front() != ";") {
				            tasks.pop();
			            }
		            }
	            }
            }
            //------------------------------------------------------------------

            else if (tasks.front() == "||") {
		        tasks.pop();  // gets rid of the ||
		        if(comp_status == true) {
			        if(tasks.size() != 0) {
                        if (tasks.front() == "test") {
                            // delete all of test
                        }
                        else if (tasks.front() != "&&" || tasks.front() != "||" ||
                                tasks.front() != ";") {
				 	        tasks.pop();
			  	        }
		  	        }
		        }
	        }

            // simply pop the semicolon and continue looping
	        else if (tasks.front() == ";") {
                tasks.pop();
	        }

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

            // the user wants to test
            else if (tasks.front() == "test") {
                // pops "test"
                tasks.pop();
                test.run(tasks);
            }

            // task was not a connector, and therefore a command
            else {
                c = in.toChar(tasks.front());
                ex.execute(c, comp_status);
	            tasks.pop();
	        }

        }
    cout << flush;

    }

    return 0;
}
<commit_msg>cleaned a little<commit_after>#include <iostream>
#include <queue>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "Shell.h"
#include "Input.h"

using namespace std;

int main() {
    Input in;
    queue<string> tasks;

    // to exit while loop, user must type exit
    while(1) {

        in.getInput();
        // bool test = in.isTest();
        // cout << "test: " << test << endl;
        // exit(0);
        tasks = in.Parse();

        cout << "size: " << tasks.size() << endl;

        // while (tasks.size() != 0) {
        //     cout << tasks.front() << endl;
        //     tasks.pop();
        // }

        // exit(0);

        // bool determines whether command was successful
        bool comp_status = true;
        char** c;
        Execute ex;

        // TEST STUFF
        Test test;

        while (tasks.size() != 0) {

            // if at any point the user has exit
            if (tasks.front() == "exit") {
                cout << "You have exited shell." << endl;
                exit(0);
            }

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

            else if (tasks.front() == "&&") {
	            tasks.pop(); //gets rid of the &&
                // if the command before this one does returns F,then dont do
                // //the next command
	            if(comp_status == false) {
		        // so the && connector should have already been deleted,
                // this is a while loop to
                // delete the next commands so that they wont run if
                // the command before fails
		            if(tasks.size() != 0) {
			            if(tasks.front() != "&&" || tasks.front() != "||" ||
                                tasks.front() != ";") {
				            tasks.pop();
			            }
		            }
	            }
            }
            //------------------------------------------------------------------

            else if (tasks.front() == "||") {
		        tasks.pop();  // gets rid of the ||
		        if(comp_status == true) {
			        if(tasks.size() != 0) {
                        if (tasks.front() == "test") {
                            // delete all of test
                        }
                        else if (tasks.front() != "&&" || tasks.front() != "||"
                                || tasks.front() != ";") {
				 	        tasks.pop();
			  	        }
		  	        }
		        }
	        }

            // simply pop the semicolon and continue looping
	        else if (tasks.front() == ";") {
                tasks.pop();
	        }

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

            // the user wants to test
            else if (tasks.front() == "test") {
                // pops "test"
                tasks.pop();
                test.run(tasks);
            }

            // task was not a connector, and therefore a command
            else {
                c = in.toChar(tasks.front());
                ex.execute(c, comp_status);
	            tasks.pop();
	        }

        }
    cout << flush;

    }

    return 0;
}
<|endoftext|>


<commit_before>#include <node.h>
#include <v8.h>
#include <nan.h>

extern "C"{
  #include "ABE_IoPi.h"
}

using namespace v8;

void initIOPI(const Nan::FunctionCallbackInfo<Value>& args){
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  char address = args[0]->NumberValue();
  IOPi_init(address);
  // Local<Number> num = Nan::New(address);
  // args.GetReturnValue().Set(num);
}

void setPortDirection(const Nan::FunctionCallbackInfo<Value>& args){
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  char address = args[0]->NumberValue();
  char port = args[1]->NumberValue();
  char direction = args[2]->NumberValue();
  set_port_direction(address, port, direction);
}

void setPinDirection(const Nan::FunctionCallbackInfo<Value>& args){
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  char address = args[0]->NumberValue();
  char pin = args[1]->NumberValue();
  char direction = args[2]->NumberValue();
  set_pin_direction(address, pin, direction);
}

void writePort(const Nan::FunctionCallbackInfo<Value>& args){
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  char address = args[0]->NumberValue();
  char port = args[1]->NumberValue();
  char value = args[2]->NumberValue();
  write_port(address, port, value);
}

void writePin(const Nan::FunctionCallbackInfo<Value>& args){
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  char address = args[0]->NumberValue();
  char pin = args[1]->NumberValue();
  char value = args[2]->NumberValue();
  write_pin(address, pin, value);
}

void setup(Handle<Object> exports) {
  exports->Set(Nan::New("init").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(initIOPI)->GetFunction());
  exports->Set(Nan::New("setPortDirection").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(setPortDirection)->GetFunction());
  exports->Set(Nan::New("setPinDirection").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(setPinDirection)->GetFunction());
  exports->Set(Nan::New("writePort").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(writePort)->GetFunction());
  exports->Set(Nan::New("writePin").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(writePin)->GetFunction());
}

NODE_MODULE(iopi, setup)
<commit_msg>Cleanup<commit_after>#include <node.h>
#include <v8.h>
#include <nan.h>

extern "C"{
  #include "ABE_IoPi.h"
}

using namespace v8;

void initIOPI(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  IOPi_init(address);
}

void setPortDirection(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char port = args[1]->NumberValue();
  char direction = args[2]->NumberValue();
  set_port_direction(address, port, direction);
}

void setPinDirection(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char pin = args[1]->NumberValue();
  char direction = args[2]->NumberValue();
  set_pin_direction(address, pin, direction);
}

void writePort(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char port = args[1]->NumberValue();
  char value = args[2]->NumberValue();
  write_port(address, port, value);
}

void writePin(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char pin = args[1]->NumberValue();
  char value = args[2]->NumberValue();
  write_pin(address, pin, value);
}

void setup(Handle<Object> exports) {
  exports->Set(Nan::New("init").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(initIOPI)->GetFunction());
  exports->Set(Nan::New("setPortDirection").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(setPortDirection)->GetFunction());
  exports->Set(Nan::New("setPinDirection").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(setPinDirection)->GetFunction());
  exports->Set(Nan::New("writePort").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(writePort)->GetFunction());
  exports->Set(Nan::New("writePin").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(writePin)->GetFunction());
}

NODE_MODULE(iopi, setup)
<|endoftext|>


<commit_before>/*
 *  Author:
 *     Guido Tack <guido.tack@monash.edu>
 *
 *  Copyright:
 *     NICTA 2013
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <QDebug>

#include "highlighter.h"

Highlighter::Highlighter(QFont& font, bool dm, QTextDocument *parent)
    : QSyntaxHighlighter(parent)
{
    Rule rule;

    quoteFormat.setForeground(Qt::darkRed);
    rule.pattern = QRegExp("\"([^\"\\\\]|\\\\.)*\"");
    rule.format = quoteFormat;
    rules.append(rule);

    commentFormat.setForeground(Qt::red);
    rule.pattern = QRegExp("%[^\n]*");
    rule.format = commentFormat;
    rules.append(rule);

    QStringList patterns;
    patterns << "\\bann\\b" << "\\bannotation\\b" << "\\bany\\b"
             << "\\barray\\b" << "\\bbool\\b" << "\\bcase\\b"
             << "\\bconstraint\\b" << "\\bdefault\\b" << "\\bdiv\\b"
             << "\\bdiff\\b" << "\\belse\\b" << "\\belseif\\b"
             << "\\bendif\\b" << "\\benum\\b" << "\\bfloat\\b"
             << "\\bfunction\\b" << "\\bif\\b" << "\\binclude\\b"
             << "\\bintersect\\b" << "\\bin\\b" << "\\bint\\b"
             << "\\blet\\b" << "\\bmaximize\\b" << "\\bminimize\\b"
             << "\\bmod\\b" << "\\bnot\\b" << "\\bof\\b" << "\\boutput\\b"
             << "\\bopt\\b" << "\\bpar\\b" << "\\bpredicate\\b"
             << "\\brecord\\b" << "\\bsatisfy\\b" << "\\bset\\b"
             << "\\bsolve\\b" << "\\bstring\\b" << "\\bsubset\\b"
             << "\\bsuperset\\b" << "\\bsymdiff\\b" << "\\btest\\b"
             << "\\bthen\\b" << "\\btuple\\b" << "\\btype\\b"
             << "\\bunion\\b" << "\\bvar\\b" << "\\bvariant_record\\b"
             << "\\bwhere\\b" << "\\bxor\\b";
    QTextCharFormat format;

    format.setFontWeight(QFont::Bold);
    for (int i=0; i<patterns.size(); i++) {
        rule.pattern = QRegExp(patterns[i]);
        rule.format = format;
        rules.append(rule);
    }

    format = QTextCharFormat();
    format.setFontItalic(true);
    format.setForeground(Qt::blue);
    rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\s*\\()");
    rule.format = format;
    rules.append(rule);

    setEditorFont(font);

    commentStartExp = QRegExp("/\\*");
    commentEndExp = QRegExp("\\*/");

    setDarkMode(dm);

}

void Highlighter::setEditorFont(QFont& font)
{
    quoteFormat.setFont(font);
    commentFormat.setFont(font);
    for (int i=0; i<rules.size(); i++) {
        rules[i].format.setFont(font);
    }
}

bool fg_contains(const FixedBg& a, const FixedBg& b) {
  return (a.sl < b.sl || (a.sl == b.sl && a.sc <= b.sc))
      && (a.el > b.el || (a.el == b.el && a.ec >= b.ec));
}

void Highlighter::addFixedBg(
    unsigned int sl, unsigned int sc, unsigned int el, unsigned ec,
    QColor colour, QString tip) {

  FixedBg ifb {sl, sc, el, ec};

  for(BgMap::iterator it = fixedBg.begin();
      it != fixedBg.end();) {
    const FixedBg& fb = it.key();

    if (fg_contains(fb, ifb)) {
      it = fixedBg.erase(it);
    } else {
      ++it;
    }
  }
  fixedBg.insert(ifb, QPair<QColor, QString>(colour, tip));

}

void Highlighter::clearFixedBg() {
    fixedBg.clear();
}

void Highlighter::highlightBlock(const QString &text)
{
    QTextBlock block = currentBlock();
    for (int i=0; i<rules.size(); i++) {
        const Rule& rule = rules[i];
        QRegExp expression(rule.pattern);
        int index = expression.indexIn(text);
        while (index >= 0) {
            int length = expression.matchedLength();
            if (format(index)!=quoteFormat && format(index)!=commentFormat) {
                setFormat(index, length, rule.format);
            }
            index = expression.indexIn(text, index + length);
        }
    }

    for(QMap<FixedBg, QPair<QColor, QString> >::iterator it = fixedBg.begin();
        it != fixedBg.end(); ++it) {
      const FixedBg& fb = it.key();
      QPair<QColor, QString> val = it.value();
      QColor colour = val.first;
      QString tip = val.second;

      unsigned int blockNumber = block.blockNumber() + 1;
      if(fb.sl <= blockNumber && fb.el >= blockNumber) {
        int index = 0;
        int length = block.length();
        int endpos = index + length;

        if(fb.sl == blockNumber) {
          index = fb.sc - 1;
          if(fb.sl == fb.el) {
            length = fb.ec - index;
          }
        } else if(fb.el == blockNumber) {
          length = fb.ec;
        }

        foreach(const QTextLayout::FormatRange& fr, block.textFormats()) {
          //if(index >= fr.start && index <= fr.start + length) {
            int local_index = fr.start < index ? index : fr.start;
            int fr_endpos = fr.start + fr.length;
            int local_len = (fr_endpos < endpos ? fr_endpos : endpos) - local_index;
            QTextCharFormat fmt = fr.format;
            fmt.setBackground(colour);
            fmt.setToolTip(tip);
            setFormat(local_index, local_len, fmt);
          //}
        }
      }
    }

    BracketData* bd = new BracketData;
    QRegExp re("\\(|\\)|\\{|\\}|\\[|\\]");
    int pos = text.indexOf(re);
    while (pos != -1) {
        if (format(pos)!=quoteFormat && format(pos)!=commentFormat) {
            Bracket b;
            b.b = text.at(pos);
            b.pos = pos;
            bd->brackets.append(b);
        }
        pos = text.indexOf(re, pos+1);
    }
    setCurrentBlockUserData(bd);
    setCurrentBlockState(0);

    int commentStartIndex = 0;
    if (previousBlockState() != 1) {
        commentStartIndex = commentStartExp.indexIn(text);
    }
    while (commentStartIndex >= 0) {
        int commentEndIndex = commentEndExp.indexIn(text, commentStartIndex);
        int commentLength;
        if (commentEndIndex == -1) {
            setCurrentBlockState(1);
            commentLength = text.length() - commentStartIndex;
        } else {
            commentLength = commentEndIndex - commentStartIndex + commentEndExp.matchedLength();
        }
        setFormat(commentStartIndex, commentLength, commentFormat);
        commentStartIndex = commentStartExp.indexIn(text, commentStartIndex + commentLength);
    }
}

#include <QTextCursor>
#include <QTextDocumentFragment>
#include <QTextLayout>
#include <QTextEdit>
#include <QApplication>
#include <QClipboard>
#include <QMimeData>

class MyMimeDataExporter : public QTextEdit {
public:
    QMimeData* md(void) const {
        QMimeData* mymd = createMimeDataFromSelection();
        mymd->removeFormat("text/plain");
        return mymd;
    }
};

void Highlighter::copyHighlightedToClipboard(QTextCursor cursor)
{
    QTextDocument* tempDocument(new QTextDocument);
    Q_ASSERT(tempDocument);
    QTextCursor tempCursor(tempDocument);

    tempCursor.insertFragment(cursor.selection());
    tempCursor.select(QTextCursor::Document);

    QTextCharFormat textfmt = cursor.charFormat();
    textfmt.setFont(quoteFormat.font());
    tempCursor.setCharFormat(textfmt);

    QTextBlock start = document()->findBlock(cursor.selectionStart());
    QTextBlock end = document()->findBlock(cursor.selectionEnd());
    end = end.next();
    const int selectionStart = cursor.selectionStart();
    const int endOfDocument = tempDocument->characterCount() - 1;
    for(QTextBlock current = start; current.isValid() && current != end; current = current.next()) {
        const QTextLayout* layout(current.layout());

        foreach(const QTextLayout::FormatRange &range, layout->additionalFormats()) {
            const int start = current.position() + range.start - selectionStart;
            const int end = start + range.length;
            if(end <= 0 || start >= endOfDocument)
                continue;
            tempCursor.setPosition(qMax(start, 0));
            tempCursor.setPosition(qMin(end, endOfDocument), QTextCursor::KeepAnchor);
            tempCursor.setCharFormat(range.format);
        }
    }

    for(QTextBlock block = tempDocument->begin(); block.isValid(); block = block.next())
        block.setUserState(-1);

    tempCursor.select(QTextCursor::Document);
    QTextBlockFormat blockFormat = cursor.blockFormat();
    blockFormat.setNonBreakableLines(true);
    tempCursor.setBlockFormat(blockFormat);

    MyMimeDataExporter te;
    te.setDocument(tempDocument);
    te.selectAll();
    QMimeData* mimeData = te.md();
    QApplication::clipboard()->setMimeData(mimeData);
    delete tempDocument;
}

void Highlighter::setDarkMode(bool enable)
{
    darkMode = enable;
    if (darkMode) {
        rules[0].format.setForeground(QColor(143,157,106));
        commentFormat.setForeground(QColor(90,90,90));
        rules[1].format.setForeground(QColor(90,90,90));
        for (int i=2; i<rules.size()-1; i++) {
            rules[i].format.setForeground(QColor(218,208,133));
        }
        rules[rules.size()-1].format.setForeground(QColor(155,112,63));
    } else {
        rules[0].format.setForeground(Qt::darkRed);
        rules[1].format.setForeground(Qt::red);
        commentFormat.setForeground(Qt::red);
        for (int i=2; i<rules.size()-1; i++) {
            rules[i].format.setForeground(Qt::darkGreen);
        }
        rules[rules.size()-1].format.setForeground(Qt::blue);
    }
}
<commit_msg>Fixed highlighing bug. (all highlighting went to end of line)<commit_after>/*
 *  Author:
 *     Guido Tack <guido.tack@monash.edu>
 *
 *  Copyright:
 *     NICTA 2013
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <QDebug>

#include "highlighter.h"

Highlighter::Highlighter(QFont& font, bool dm, QTextDocument *parent)
    : QSyntaxHighlighter(parent)
{
    Rule rule;

    quoteFormat.setForeground(Qt::darkRed);
    rule.pattern = QRegExp("\"([^\"\\\\]|\\\\.)*\"");
    rule.format = quoteFormat;
    rules.append(rule);

    commentFormat.setForeground(Qt::red);
    rule.pattern = QRegExp("%[^\n]*");
    rule.format = commentFormat;
    rules.append(rule);

    QStringList patterns;
    patterns << "\\bann\\b" << "\\bannotation\\b" << "\\bany\\b"
             << "\\barray\\b" << "\\bbool\\b" << "\\bcase\\b"
             << "\\bconstraint\\b" << "\\bdefault\\b" << "\\bdiv\\b"
             << "\\bdiff\\b" << "\\belse\\b" << "\\belseif\\b"
             << "\\bendif\\b" << "\\benum\\b" << "\\bfloat\\b"
             << "\\bfunction\\b" << "\\bif\\b" << "\\binclude\\b"
             << "\\bintersect\\b" << "\\bin\\b" << "\\bint\\b"
             << "\\blet\\b" << "\\bmaximize\\b" << "\\bminimize\\b"
             << "\\bmod\\b" << "\\bnot\\b" << "\\bof\\b" << "\\boutput\\b"
             << "\\bopt\\b" << "\\bpar\\b" << "\\bpredicate\\b"
             << "\\brecord\\b" << "\\bsatisfy\\b" << "\\bset\\b"
             << "\\bsolve\\b" << "\\bstring\\b" << "\\bsubset\\b"
             << "\\bsuperset\\b" << "\\bsymdiff\\b" << "\\btest\\b"
             << "\\bthen\\b" << "\\btuple\\b" << "\\btype\\b"
             << "\\bunion\\b" << "\\bvar\\b" << "\\bvariant_record\\b"
             << "\\bwhere\\b" << "\\bxor\\b";
    QTextCharFormat format;

    format.setFontWeight(QFont::Bold);
    for (int i=0; i<patterns.size(); i++) {
        rule.pattern = QRegExp(patterns[i]);
        rule.format = format;
        rules.append(rule);
    }

    format = QTextCharFormat();
    format.setFontItalic(true);
    format.setForeground(Qt::blue);
    rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\s*\\()");
    rule.format = format;
    rules.append(rule);

    setEditorFont(font);

    commentStartExp = QRegExp("/\\*");
    commentEndExp = QRegExp("\\*/");

    setDarkMode(dm);

}

void Highlighter::setEditorFont(QFont& font)
{
    quoteFormat.setFont(font);
    commentFormat.setFont(font);
    for (int i=0; i<rules.size(); i++) {
        rules[i].format.setFont(font);
    }
}

bool fg_contains(const FixedBg& a, const FixedBg& b) {
  return (a.sl < b.sl || (a.sl == b.sl && a.sc <= b.sc))
      && (a.el > b.el || (a.el == b.el && a.ec >= b.ec));
}

void Highlighter::addFixedBg(
    unsigned int sl, unsigned int sc, unsigned int el, unsigned ec,
    QColor colour, QString tip) {

  FixedBg ifb {sl, sc, el, ec};

  for(BgMap::iterator it = fixedBg.begin();
      it != fixedBg.end();) {
    const FixedBg& fb = it.key();

    if (fg_contains(fb, ifb)) {
      it = fixedBg.erase(it);
    } else {
      ++it;
    }
  }
  fixedBg.insert(ifb, QPair<QColor, QString>(colour, tip));

}

void Highlighter::clearFixedBg() {
    fixedBg.clear();
}

void Highlighter::highlightBlock(const QString &text)
{
    QTextBlock block = currentBlock();
    for (int i=0; i<rules.size(); i++) {
        const Rule& rule = rules[i];
        QRegExp expression(rule.pattern);
        int index = expression.indexIn(text);
        while (index >= 0) {
            int length = expression.matchedLength();
            if (format(index)!=quoteFormat && format(index)!=commentFormat) {
                setFormat(index, length, rule.format);
            }
            index = expression.indexIn(text, index + length);
        }
    }

    for(QMap<FixedBg, QPair<QColor, QString> >::iterator it = fixedBg.begin();
        it != fixedBg.end(); ++it) {
      const FixedBg& fb = it.key();
      QPair<QColor, QString> val = it.value();
      QColor colour = val.first;
      QString tip = val.second;

      unsigned int blockNumber = block.blockNumber() + 1;
      if(fb.sl <= blockNumber && fb.el >= blockNumber) {
        int index = 0;
        int length = block.length();

        if(fb.sl == blockNumber) {
          index = fb.sc - 1;
          if(fb.sl == fb.el) {
            length = fb.ec - index;
          }
        } else if(fb.el == blockNumber) {
          length = fb.ec;
        }

        int endpos = index + length;
        foreach(const QTextLayout::FormatRange& fr, block.textFormats()) {
          //if(index >= fr.start && index <= fr.start + length) {
            int local_index = fr.start < index ? index : fr.start;
            int fr_endpos = fr.start + fr.length;
            int local_len = (fr_endpos < endpos ? fr_endpos : endpos) - local_index;
            QTextCharFormat fmt = fr.format;
            fmt.setBackground(colour);
            fmt.setToolTip(tip);
            setFormat(local_index, local_len, fmt);
          //}
        }
      }
    }

    BracketData* bd = new BracketData;
    QRegExp re("\\(|\\)|\\{|\\}|\\[|\\]");
    int pos = text.indexOf(re);
    while (pos != -1) {
        if (format(pos)!=quoteFormat && format(pos)!=commentFormat) {
            Bracket b;
            b.b = text.at(pos);
            b.pos = pos;
            bd->brackets.append(b);
        }
        pos = text.indexOf(re, pos+1);
    }
    setCurrentBlockUserData(bd);
    setCurrentBlockState(0);

    int commentStartIndex = 0;
    if (previousBlockState() != 1) {
        commentStartIndex = commentStartExp.indexIn(text);
    }
    while (commentStartIndex >= 0) {
        int commentEndIndex = commentEndExp.indexIn(text, commentStartIndex);
        int commentLength;
        if (commentEndIndex == -1) {
            setCurrentBlockState(1);
            commentLength = text.length() - commentStartIndex;
        } else {
            commentLength = commentEndIndex - commentStartIndex + commentEndExp.matchedLength();
        }
        setFormat(commentStartIndex, commentLength, commentFormat);
        commentStartIndex = commentStartExp.indexIn(text, commentStartIndex + commentLength);
    }
}

#include <QTextCursor>
#include <QTextDocumentFragment>
#include <QTextLayout>
#include <QTextEdit>
#include <QApplication>
#include <QClipboard>
#include <QMimeData>

class MyMimeDataExporter : public QTextEdit {
public:
    QMimeData* md(void) const {
        QMimeData* mymd = createMimeDataFromSelection();
        mymd->removeFormat("text/plain");
        return mymd;
    }
};

void Highlighter::copyHighlightedToClipboard(QTextCursor cursor)
{
    QTextDocument* tempDocument(new QTextDocument);
    Q_ASSERT(tempDocument);
    QTextCursor tempCursor(tempDocument);

    tempCursor.insertFragment(cursor.selection());
    tempCursor.select(QTextCursor::Document);

    QTextCharFormat textfmt = cursor.charFormat();
    textfmt.setFont(quoteFormat.font());
    tempCursor.setCharFormat(textfmt);

    QTextBlock start = document()->findBlock(cursor.selectionStart());
    QTextBlock end = document()->findBlock(cursor.selectionEnd());
    end = end.next();
    const int selectionStart = cursor.selectionStart();
    const int endOfDocument = tempDocument->characterCount() - 1;
    for(QTextBlock current = start; current.isValid() && current != end; current = current.next()) {
        const QTextLayout* layout(current.layout());

        foreach(const QTextLayout::FormatRange &range, layout->additionalFormats()) {
            const int start = current.position() + range.start - selectionStart;
            const int end = start + range.length;
            if(end <= 0 || start >= endOfDocument)
                continue;
            tempCursor.setPosition(qMax(start, 0));
            tempCursor.setPosition(qMin(end, endOfDocument), QTextCursor::KeepAnchor);
            tempCursor.setCharFormat(range.format);
        }
    }

    for(QTextBlock block = tempDocument->begin(); block.isValid(); block = block.next())
        block.setUserState(-1);

    tempCursor.select(QTextCursor::Document);
    QTextBlockFormat blockFormat = cursor.blockFormat();
    blockFormat.setNonBreakableLines(true);
    tempCursor.setBlockFormat(blockFormat);

    MyMimeDataExporter te;
    te.setDocument(tempDocument);
    te.selectAll();
    QMimeData* mimeData = te.md();
    QApplication::clipboard()->setMimeData(mimeData);
    delete tempDocument;
}

void Highlighter::setDarkMode(bool enable)
{
    darkMode = enable;
    if (darkMode) {
        rules[0].format.setForeground(QColor(143,157,106));
        commentFormat.setForeground(QColor(90,90,90));
        rules[1].format.setForeground(QColor(90,90,90));
        for (int i=2; i<rules.size()-1; i++) {
            rules[i].format.setForeground(QColor(218,208,133));
        }
        rules[rules.size()-1].format.setForeground(QColor(155,112,63));
    } else {
        rules[0].format.setForeground(Qt::darkRed);
        rules[1].format.setForeground(Qt::red);
        commentFormat.setForeground(Qt::red);
        for (int i=2; i<rules.size()-1; i++) {
            rules[i].format.setForeground(Qt::darkGreen);
        }
        rules[rules.size()-1].format.setForeground(Qt::blue);
    }
}
<|endoftext|>


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

#include <boost/filesystem.hpp>

#include "csv_parser.hpp"

int main(int argc, char** argv)
{
	using namespace vakkenranking;
	using namespace boost::filesystem;

	path p("data/");

	const directory_iterator it_end;
	for(directory_iterator it(p); it != it_end; ++it)
	{
		const std::string filename(it->path().string());
		csv_parser parser(filename);

		std::vector<std::string> line;
		while(parser.read(line))
			std::copy(
				line.begin(),
				line.end(),
				std::ostream_iterator<std::string>(std::cout, "|")
			);
	}

	return 0;
}
<commit_msg>Added calculation of data<commit_after>#include <iostream>
#include <algorithm>
#include <sstream>
#include <map>

#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>

#include "csv_parser.hpp"

bool check_rating_row(const std::vector<std::string>& line, size_t& rating)
{
	if(line.size() != 3)
		return false;

	for(size_t i = 1; i <= 10; i++)
	{
		std::stringstream cmp_str;
		cmp_str << i << " (";

		if(i < 10)
			cmp_str << '0';

		cmp_str << i << ")";

		if(cmp_str.str() != line[0])
			continue;

		rating = i;
		return true;
	}

	return false;
}

double round(double x, size_t digits)
{
	double multiplier = std::pow(10, digits);
	return std::round(x * multiplier) / multiplier;
}

int main(int argc, char** argv)
{
	using namespace vakkenranking;
	using namespace boost::filesystem;

	path p("data/");

	const directory_iterator it_end;
	for(directory_iterator it(p); it != it_end; ++it)
	{
		const std::string filename(it->path().string());
		csv_parser parser(filename);

		std::map<double, double> rating_map;
		std::vector<std::string> line;
		while(parser.read(line))
		{
			size_t rating;
			if(!check_rating_row(line, rating))
				continue;

			rating_map[(double)rating] = boost::lexical_cast<double>(line[1]);
		}

		double count = 0;
		for(std::pair<double, double> rating : rating_map)
			count += rating.second;

		double avg = 0;
		for(std::pair<double, double> rating : rating_map)
			avg += (rating.first / count) * rating.second;

		double stddev = 0;
		for(std::pair<double, double> rating : rating_map)
			stddev += std::pow(rating.first - avg, 2) * rating.second;

		stddev = std::sqrt(stddev / count);

		std::cout
			<< filename << '\n'
			<< "\tcount: " << count
			<< " avg: " << round(avg, 1)
			<< " stddev: " << round(stddev, 2)
			<< std::endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>
#ifndef PAN_GROUP_H_INCLUDE
#define PAN_GROUP_H_INCLUDE

#include <string>
#include <H5Cpp.h>

#include "Charon.hpp"

namespace pandora {

class Group {

private:

  H5::Group h5group;

public:

  Group();

  Group(H5::Group h5group);

  Group(const Group &group);

  void operator=(const Group &group);

  bool hasAttr(std::string name) const;
  void removeAttr(std::string name) const;

  template <typename T>
  void setAttr(std::string name, const T &value) const;

  template <typename T>
  bool getAttr(std::string name, T &value) const;

  bool hasObject(std::string path) const;
  size_t objectCount() const;
  std::string objectName(size_t index) const;

  bool hasData(std::string name) const;
  H5::DataSet openData(std::string name) const;
  void removeData(std::string name);

  bool hasGroup(std::string name) const;
  Group openGroup(std::string name, bool create = true) const;
  void removeGroup(std::string name);

  bool operator==(const Group &group) const;
  bool operator!=(const Group &group) const;

  H5::Group h5Group() const;
  virtual ~Group();
}; // group Group

  //template functions

template<typename T> void Group::setAttr(std::string name, const T &value) const
{
  Charon<const T> charon(value);
  H5::Attribute attr;

  if (hasAttr(name)) {
    attr = h5group.openAttribute(name);
  } else {
    H5::DataType fileType = charon.getFileType();
    H5::DataSpace fileSpace = charon.createDataSpace(true);
    attr = h5group.createAttribute(name, fileType, fileSpace);
  }

  typedef typename Charon<const T>::dbox_type dbox_type;
  dbox_type data = charon.get_data();
  attr.write(charon.getMemType(), *data);
  data.finish();
}

template<typename T> bool Group::getAttr(std::string name, T &value) const
{

  if (!hasAttr(name)) {
    return false;
  }

  Charon<T> charon(value);
  H5::Attribute attr;
  H5::DataSpace space;

  attr = h5group.openAttribute(name);

  space = attr.getSpace();
  size_t rank = (size_t) space.getSimpleExtentNdims();
  hsize_t *dims = new hsize_t[rank];
  space.getSimpleExtentDims (dims, nullptr);
  charon.resize(rank, dims);
  delete[] dims;

  typedef typename Charon<T>::dbox_type dbox_type;
  dbox_type data = charon.get_data();
  attr.read(charon.getMemType(), *data);
  data.finish(&space);

  return true;
}

}  // namespace pandora

#endif /* PAN_GROUP_H_INCLUDE */
<commit_msg>Group::setAttr: Don't create unlimited datasets<commit_after>
#ifndef PAN_GROUP_H_INCLUDE
#define PAN_GROUP_H_INCLUDE

#include <string>
#include <H5Cpp.h>

#include "Charon.hpp"

namespace pandora {

class Group {

private:

  H5::Group h5group;

public:

  Group();

  Group(H5::Group h5group);

  Group(const Group &group);

  void operator=(const Group &group);

  bool hasAttr(std::string name) const;
  void removeAttr(std::string name) const;

  template <typename T>
  void setAttr(std::string name, const T &value) const;

  template <typename T>
  bool getAttr(std::string name, T &value) const;

  bool hasObject(std::string path) const;
  size_t objectCount() const;
  std::string objectName(size_t index) const;

  bool hasData(std::string name) const;
  H5::DataSet openData(std::string name) const;
  void removeData(std::string name);

  bool hasGroup(std::string name) const;
  Group openGroup(std::string name, bool create = true) const;
  void removeGroup(std::string name);

  bool operator==(const Group &group) const;
  bool operator!=(const Group &group) const;

  H5::Group h5Group() const;
  virtual ~Group();
}; // group Group

  //template functions

template<typename T> void Group::setAttr(std::string name, const T &value) const
{
  Charon<const T> charon(value);
  H5::Attribute attr;

  if (hasAttr(name)) {
    attr = h5group.openAttribute(name);
  } else {
    H5::DataType fileType = charon.getFileType();
    H5::DataSpace fileSpace = charon.createDataSpace(false);
    attr = h5group.createAttribute(name, fileType, fileSpace);
  }

  typedef typename Charon<const T>::dbox_type dbox_type;
  dbox_type data = charon.get_data();
  attr.write(charon.getMemType(), *data);
  data.finish();
}

template<typename T> bool Group::getAttr(std::string name, T &value) const
{

  if (!hasAttr(name)) {
    return false;
  }

  Charon<T> charon(value);
  H5::Attribute attr;
  H5::DataSpace space;

  attr = h5group.openAttribute(name);

  space = attr.getSpace();
  size_t rank = (size_t) space.getSimpleExtentNdims();
  hsize_t *dims = new hsize_t[rank];
  space.getSimpleExtentDims (dims, nullptr);
  charon.resize(rank, dims);
  delete[] dims;

  typedef typename Charon<T>::dbox_type dbox_type;
  dbox_type data = charon.get_data();
  attr.read(charon.getMemType(), *data);
  data.finish(&space);

  return true;
}

}  // namespace pandora

#endif /* PAN_GROUP_H_INCLUDE */
<|endoftext|>


<commit_before>#include "func-overload-match.h"
#include "details/atom/atom.h"
#include "details/atom/vardef.h"
#include "details/atom/classdef-table-view.h"
#include "details/reporting/report.h"
#include "libnany-config.h"

using namespace Yuni;

namespace Nany
{

	FuncOverloadMatch::FuncOverloadMatch(Logs::Report report, const ClassdefTableView& table)
		: report(std::ref(report))
		, table(table)
	{
		input.rettype.reserve(1); // currently, only 1 return value is allowed
		input.params.indexed.reserve(Config::maxPushedParameters);
		input.params.named.reserve(Config::maxPushedParameters);
		result.params.reserve(Config::maxPushedParameters);
	}

	void FuncOverloadMatch::clear()
	{
		input.rettype.clear();
		input.params.indexed.clear();
		input.params.named.clear();
		input.tmplparams.indexed.clear();
		input.tmplparams.named.clear();

		result.params.clear();
		result.tmplparams.clear();
		result.funcToCall = nullptr;
	}

	void FuncOverloadMatch::printInputParameters(String& out) const
	{
		if (not input.params.indexed.empty())
		{
			table.classdef(input.params.indexed.front()).print(out, table, false);

			for (auto it = input.params.indexed.begin() + 1; it != input.params.indexed.end(); ++it)
			{
				out.write(", ", 2);
				table.classdef(*it).print(out, table, false);
			}
		}

		if (not input.params.named.empty())
		{
			if (not input.params.indexed.empty())
				out.write(", ", 2);

			(out << input.params.named.front().first).write(": ", 2);
			table.classdef(input.params.named.front().second).print(out, table, false);

			for (auto it = input.params.named.begin() + 1; it != input.params.named.end(); ++it)
			{
				out.write(", ", 2);
				(out << it->first).write(": ", 2);
				table.classdef(it->second).print(out, table, false);
			}
		}
	}

	void FuncOverloadMatch::complainParamTypeMismatch(bool isGenType, const Classdef& cdef, const Atom& atom, uint32_t i, const Classdef& paramdef)
	{
		report.get().trace() << "failed to push"
			<< (isGenType ? " generic value " : " value ")
			<< cdef.clid << " to "
			<< (CLID{atom.atomid,0})
			<< ":'" << atom.name << "' parameter index " << i;

		auto hint = report.get().hint();
		switch (i)
		{
			case 0:  hint << "1st"; break;
			case 1:  hint << "2nd"; break;
			case 2:  hint << "3rd"; break;
			default: hint << (i + 1) << "th";
		}
		if (isGenType)
			hint << " generic";
		hint << " parameter, got '";
		cdef.print(hint.message.message, table, false);
		if (debugmode)
			hint << ' ' << cdef.clid;

		hint << "', expected '";
		paramdef.print(hint.message.message, table, false);
		if (debugmode)
			hint << ' ' << paramdef.clid;
		hint << '\'';
	}

	template<bool isTmpl>
	inline TypeCheck::Match FuncOverloadMatch::pushParameter(Atom& atom, uint32_t index, const CLID& clid)
	{
		// force reset
		auto& cdef = table.classdef(clid);
		auto& resultinfo = (not isTmpl) ? result.params[index] : result.tmplparams[index];
		resultinfo.clid = clid;
		resultinfo.cdef = &cdef;

		// type checking
		auto& paramdef = (not isTmpl)
			? table.classdef(atom.parameters.vardef(index).clid)
			: table.classdef(atom.tmplparams.vardef(index).clid);

		// checking the parameter type
		resultinfo.strategy = TypeCheck::isSimilarTo(table, nullptr, cdef, paramdef, pAllowImplicit);

		if (resultinfo.strategy == TypeCheck::Match::none)
		{
			if (unlikely(canGenerateReport))
				complainParamTypeMismatch(isTmpl, cdef, atom, index, paramdef);
		}
		return resultinfo.strategy;
	}

	TypeCheck::Match FuncOverloadMatch::validate(Atom& atom, bool allowImplicit)
	{
		assert(atom.isFunction() or atom.isClass());

		// some reset
		result.params.clear();
		result.tmplparams.clear();
		result.funcToCall = &atom;

		// trivial check, too many parameters for this overload
		if (atom.parameters.size() < (uint32_t) input.params.indexed.size())
		{
			if (unlikely(canGenerateReport))
			{
				// do not take into consideration the 'self' parameter for error reporting
				uint32_t selfidx = static_cast<uint32_t>(atom.isClassMember() and atom.isFunction());
				report.get().hint() << "too many parameters. Got "
					<< (input.params.indexed.size() - selfidx)
					<< ", expected: " << (atom.parameters.size() - selfidx);
			}
			return TypeCheck::Match::none;
		}
		// trivial check, too many template parameters for this overload
		if (atom.tmplparams.size() < (uint32_t) input.tmplparams.indexed.size())
		{
			if (unlikely(canGenerateReport))
			{
				report.get().hint() << "too many generic type parameters. Got "
					<< input.tmplparams.indexed.size()
					<< ", expected: " << atom.tmplparams.size();
			}
			return TypeCheck::Match::none;
		}

		pAllowImplicit = allowImplicit;
		bool perfectMatch /*= false*/;

		// checking input.params
		{
			perfectMatch = true;
			result.params.resize(atom.parameters.size());
			result.tmplparams.resize(atom.tmplparams.size());

			// trying to resolve indexed template parameters
			for (uint32_t i = 0; i != (uint32_t) input.tmplparams.indexed.size(); ++i)
			{
				switch (pushParameter<true>(atom, i, input.tmplparams.indexed[i]))
				{
					case TypeCheck::Match::equal:       perfectMatch = false; break;
					case TypeCheck::Match::strictEqual: break;
					case TypeCheck::Match::none:        return TypeCheck::Match::none;
				}
			}

			if (not input.tmplparams.named.empty())
			{
				if (unlikely(canGenerateReport))
					report.get().error() << "named generic type parameters not implemented yet";
				return TypeCheck::Match::none;
			}

			// trying to resolve indexed parameters (if they match)
			for (uint32_t i = 0; i != (uint32_t) input.params.indexed.size(); ++i)
			{
				switch (pushParameter<false>(atom, i, input.params.indexed[i]))
				{
					case TypeCheck::Match::equal:       perfectMatch = false; break;
					case TypeCheck::Match::strictEqual: break;
					case TypeCheck::Match::none:        return TypeCheck::Match::none;
				}
			}

			// try to resolve named-parameters
			if (not input.params.named.empty())
			{
				uint32_t offset = (uint32_t) input.params.indexed.size();
				for (auto& pair: input.params.named)
				{
					uint32_t index = atom.parameters.findByName(pair.first, offset);
					// the named parameter is not present after indexed parameters
					if (index == static_cast<uint32_t>(-1))
					{
						//report.trace() << "named parameter '" << pair.first
						//	<< "' not found after started from index " << offset << " in " << (CLID{atom.atomid,0});
						if (unlikely(canGenerateReport))
							report.get().hint() << "named parameter '" << pair.first << "' not found after indexed parameters";
						return TypeCheck::Match::none;
					}

					switch (pushParameter<false>(atom, index, pair.second))
					{
						case TypeCheck::Match::equal:       perfectMatch = false; break;
						case TypeCheck::Match::strictEqual: break;
						case TypeCheck::Match::none:        return TypeCheck::Match::none;
					}
				}
			}

			// check for missing default values for generic types
			for (size_t i = input.tmplparams.indexed.size(); i < result.tmplparams.size(); ++i)
			{
				if (not result.tmplparams[i].cdef or result.tmplparams[i].cdef->clid.isVoid()) // undefined - TODO: default values
				{
					if (unlikely(canGenerateReport))
					{
						auto ix = i;
						if (not atom.isClassMember())
							++ix;
						auto hint = (report.get().hint());
						hint << atom.caption(table);
						hint << ": no type provided for the generic type parameter '";
						hint << atom.tmplparams.name((uint32_t) i) << '\'';
					}
					return TypeCheck::Match::none;
				}
			}

			// check for missing default values
			for (size_t i = input.params.indexed.size(); i < result.params.size(); ++i)
			{
				if (not result.params[i].cdef or result.params[i].cdef->clid.isVoid()) // undefined - TODO: default values
				{
					if (unlikely(canGenerateReport))
					{
						auto ix = i;
						if (not atom.isClassMember())
							++ix;
						auto hint = (report.get().hint());
						hint << atom.caption(table) << ": no value provided for the parameter '";
						hint << atom.parameters.name((uint32_t) i) << '\'';
					}
					return TypeCheck::Match::none;
				}
			}
		}

		// checking return type
		switch (input.rettype.size())
		{
			case 1:
			{
				auto& wantedRettype = table.classdef(input.rettype[0]);
				// the value is really used, let's continue
				if (wantedRettype.isBuiltinOrVoid() or wantedRettype.hasConstraints())
				{
					auto& atomRettype = table.classdef(atom.returnType.clid);
					if (TypeCheck::Match::none == TypeCheck::isSimilarTo(table, nullptr, wantedRettype, atomRettype, pAllowImplicit))
					{
						if (unlikely(canGenerateReport))
						{
							auto err = report.get().hint() << "returned type does not match, got '";
							if (debugmode)
								err << atomRettype.clid;
							atomRettype.print(err.message.message, table, false);
							err << "', expected '";

							if (debugmode)
								err << wantedRettype.clid;
							wantedRettype.print(err.message.message, table, false);
							err << '\'';
						}
						return TypeCheck::Match::none;
					}
				}
				break;
			}
			case 0:
			{
				// no return value, the return type MUST be void
				if (not atom.returnType.clid.isVoid())
				{
					auto& atomRettype = table.classdef(atom.returnType.clid);
					if (atomRettype.isVoid())
						break;

					// The returned type can be any, which can be void then
					if (atomRettype.kind == nyt_any and !table.findClassdefAtom(atomRettype))
						break;

					if (unlikely(canGenerateReport))
					{
						auto err = report.get().hint() << "returned type does not match, got '";
						if (debugmode)
							err << atomRettype.clid;
						atomRettype.print(err.message.message, table, false);
						err << "', expected 'void'";
					}
					return TypeCheck::Match::none;
				}
				break;
			}
			default:
			{
				assert(false and "not implemented");
				return TypeCheck::Match::none;
			}
		}
		return perfectMatch ? TypeCheck::Match::strictEqual : TypeCheck::Match::equal;
	}

} // namespace Nany
<commit_msg>improved debug diagnostic when failed to call func<commit_after>#include "func-overload-match.h"
#include "details/atom/atom.h"
#include "details/atom/vardef.h"
#include "details/atom/classdef-table-view.h"
#include "details/reporting/report.h"
#include "libnany-config.h"

using namespace Yuni;

namespace Nany
{

	FuncOverloadMatch::FuncOverloadMatch(Logs::Report report, const ClassdefTableView& table)
		: report(std::ref(report))
		, table(table)
	{
		input.rettype.reserve(1); // currently, only 1 return value is allowed
		input.params.indexed.reserve(Config::maxPushedParameters);
		input.params.named.reserve(Config::maxPushedParameters);
		result.params.reserve(Config::maxPushedParameters);
	}

	void FuncOverloadMatch::clear()
	{
		input.rettype.clear();
		input.params.indexed.clear();
		input.params.named.clear();
		input.tmplparams.indexed.clear();
		input.tmplparams.named.clear();

		result.params.clear();
		result.tmplparams.clear();
		result.funcToCall = nullptr;
	}

	void FuncOverloadMatch::printInputParameters(String& out) const
	{
		auto paramprinter = [&](const auto& paramlist)
		{
			if (not paramlist.indexed.empty())
			{
				table.classdef(paramlist.indexed.front()).print(out, table, false);

				for (auto it = paramlist.indexed.begin() + 1; it != paramlist.indexed.end(); ++it)
				{
					out.write(", ", 2);
					table.classdef(*it).print(out, table, false);
				}
			}

			if (not paramlist.named.empty())
			{
				if (not paramlist.indexed.empty())
					out.write(", ", 2);

				(out << paramlist.named.front().first).write(": ", 2);
				table.classdef(paramlist.named.front().second).print(out, table, false);

				for (auto it = paramlist.named.begin() + 1; it != paramlist.named.end(); ++it)
				{
					out.write(", ", 2);
					(out << it->first).write(": ", 2);
					table.classdef(it->second).print(out, table, false);
				}
			}
		};

		if (not input.tmplparams.indexed.empty() or not input.tmplparams.named.empty())
		{
			out << "<:";
			paramprinter(input.tmplparams);
			out << ":>";
		}

		out << '(';
		paramprinter(input.params);
		out << ')';
	}

	void FuncOverloadMatch::complainParamTypeMismatch(bool isGenType, const Classdef& cdef, const Atom& atom, uint32_t i, const Classdef& paramdef)
	{

		auto hint = report.get().hint();
		switch (i)
		{
			case 0:  hint << "1st"; break;
			case 1:  hint << "2nd"; break;
			case 2:  hint << "3rd"; break;
			default: hint << (i + 1) << "th";
		}
		if (isGenType)
			hint << " generic";
		hint << " parameter, got '";
		cdef.print(hint.message.message, table, false);
		if (debugmode)
			hint << ' ' << cdef.clid;

		hint << "', expected '";
		paramdef.print(hint.message.message, table, false);
		if (debugmode)
			hint << ' ' << paramdef.clid;
		hint << '\'';

		if (debugmode)
		{
			hint.hint() << "failed to push"
				<< (isGenType ? " generic value " : " value ")
				<< cdef.clid << " to " << (CLID{atom.atomid,0})
				<< ":'" << atom.name << "' parameter index " << (i + 1);

			String inputs;
			printInputParameters(inputs);
			hint.hint() << ">> <call> " << inputs;
		}
	}

	template<bool isTmpl>
	inline TypeCheck::Match FuncOverloadMatch::pushParameter(Atom& atom, uint32_t index, const CLID& clid)
	{
		// force reset
		auto& cdef = table.classdef(clid);
		auto& resultinfo = (not isTmpl) ? result.params[index] : result.tmplparams[index];
		resultinfo.clid = clid;
		resultinfo.cdef = &cdef;

		// type checking
		auto& paramdef = (not isTmpl)
			? table.classdef(atom.parameters.vardef(index).clid)
			: table.classdef(atom.tmplparams.vardef(index).clid);

		// checking the parameter type
		resultinfo.strategy = TypeCheck::isSimilarTo(table, nullptr, cdef, paramdef, pAllowImplicit);

		if (resultinfo.strategy == TypeCheck::Match::none)
		{
			if (unlikely(canGenerateReport))
				complainParamTypeMismatch(isTmpl, cdef, atom, index, paramdef);
		}
		return resultinfo.strategy;
	}

	TypeCheck::Match FuncOverloadMatch::validate(Atom& atom, bool allowImplicit)
	{
		assert(atom.isFunction() or atom.isClass());

		// some reset
		result.params.clear();
		result.tmplparams.clear();
		result.funcToCall = &atom;

		// trivial check, too many parameters for this overload
		if (atom.parameters.size() < (uint32_t) input.params.indexed.size())
		{
			if (unlikely(canGenerateReport))
			{
				// do not take into consideration the 'self' parameter for error reporting
				uint32_t selfidx = static_cast<uint32_t>(atom.isClassMember() and atom.isFunction());
				report.get().hint() << "too many parameters. Got "
					<< (input.params.indexed.size() - selfidx)
					<< ", expected: " << (atom.parameters.size() - selfidx);
			}
			return TypeCheck::Match::none;
		}
		// trivial check, too many template parameters for this overload
		if (atom.tmplparams.size() < (uint32_t) input.tmplparams.indexed.size())
		{
			if (unlikely(canGenerateReport))
			{
				report.get().hint() << "too many generic type parameters. Got "
					<< input.tmplparams.indexed.size()
					<< ", expected: " << atom.tmplparams.size();
			}
			return TypeCheck::Match::none;
		}

		pAllowImplicit = allowImplicit;
		bool perfectMatch /*= false*/;

		// checking input.params
		{
			perfectMatch = true;
			result.params.resize(atom.parameters.size());
			result.tmplparams.resize(atom.tmplparams.size());

			// trying to resolve indexed template parameters
			for (uint32_t i = 0; i != (uint32_t) input.tmplparams.indexed.size(); ++i)
			{
				switch (pushParameter<true>(atom, i, input.tmplparams.indexed[i]))
				{
					case TypeCheck::Match::equal:       perfectMatch = false; break;
					case TypeCheck::Match::strictEqual: break;
					case TypeCheck::Match::none:        return TypeCheck::Match::none;
				}
			}

			if (not input.tmplparams.named.empty())
			{
				if (unlikely(canGenerateReport))
					report.get().error() << "named generic type parameters not implemented yet";
				return TypeCheck::Match::none;
			}

			// trying to resolve indexed parameters (if they match)
			for (uint32_t i = 0; i != (uint32_t) input.params.indexed.size(); ++i)
			{
				switch (pushParameter<false>(atom, i, input.params.indexed[i]))
				{
					case TypeCheck::Match::equal:       perfectMatch = false; break;
					case TypeCheck::Match::strictEqual: break;
					case TypeCheck::Match::none:        return TypeCheck::Match::none;
				}
			}

			// try to resolve named-parameters
			if (not input.params.named.empty())
			{
				uint32_t offset = (uint32_t) input.params.indexed.size();
				for (auto& pair: input.params.named)
				{
					uint32_t index = atom.parameters.findByName(pair.first, offset);
					// the named parameter is not present after indexed parameters
					if (index == static_cast<uint32_t>(-1))
					{
						//report.trace() << "named parameter '" << pair.first
						//	<< "' not found after started from index " << offset << " in " << (CLID{atom.atomid,0});
						if (unlikely(canGenerateReport))
							report.get().hint() << "named parameter '" << pair.first << "' not found after indexed parameters";
						return TypeCheck::Match::none;
					}

					switch (pushParameter<false>(atom, index, pair.second))
					{
						case TypeCheck::Match::equal:       perfectMatch = false; break;
						case TypeCheck::Match::strictEqual: break;
						case TypeCheck::Match::none:        return TypeCheck::Match::none;
					}
				}
			}

			// check for missing default values for generic types
			for (size_t i = input.tmplparams.indexed.size(); i < result.tmplparams.size(); ++i)
			{
				if (not result.tmplparams[i].cdef or result.tmplparams[i].cdef->clid.isVoid()) // undefined - TODO: default values
				{
					if (unlikely(canGenerateReport))
					{
						auto ix = i;
						if (not atom.isClassMember())
							++ix;
						auto hint = (report.get().hint());
						hint << atom.caption(table);
						hint << ": no type provided for the generic type parameter '";
						hint << atom.tmplparams.name((uint32_t) i) << '\'';
					}
					return TypeCheck::Match::none;
				}
			}

			// check for missing default values
			for (size_t i = input.params.indexed.size(); i < result.params.size(); ++i)
			{
				if (not result.params[i].cdef or result.params[i].cdef->clid.isVoid()) // undefined - TODO: default values
				{
					if (unlikely(canGenerateReport))
					{
						auto ix = i;
						if (not atom.isClassMember())
							++ix;
						auto hint = (report.get().hint());
						hint << atom.caption(table) << ": no value provided for the parameter '";
						hint << atom.parameters.name((uint32_t) i) << '\'';
					}
					return TypeCheck::Match::none;
				}
			}
		}

		// checking return type
		switch (input.rettype.size())
		{
			case 1:
			{
				auto& wantedRettype = table.classdef(input.rettype[0]);
				// the value is really used, let's continue
				if (wantedRettype.isBuiltinOrVoid() or wantedRettype.hasConstraints())
				{
					auto& atomRettype = table.classdef(atom.returnType.clid);
					if (TypeCheck::Match::none == TypeCheck::isSimilarTo(table, nullptr, wantedRettype, atomRettype, pAllowImplicit))
					{
						if (unlikely(canGenerateReport))
						{
							auto err = report.get().hint() << "returned type does not match, got '";
							if (debugmode)
								err << atomRettype.clid;
							atomRettype.print(err.message.message, table, false);
							err << "', expected '";

							if (debugmode)
								err << wantedRettype.clid;
							wantedRettype.print(err.message.message, table, false);
							err << '\'';
						}
						return TypeCheck::Match::none;
					}
				}
				break;
			}
			case 0:
			{
				// no return value, the return type MUST be void
				if (not atom.returnType.clid.isVoid())
				{
					auto& atomRettype = table.classdef(atom.returnType.clid);
					if (atomRettype.isVoid())
						break;

					// The returned type can be any, which can be void then
					if (atomRettype.kind == nyt_any and !table.findClassdefAtom(atomRettype))
						break;

					if (unlikely(canGenerateReport))
					{
						auto err = report.get().hint() << "returned type does not match, got '";
						if (debugmode)
							err << atomRettype.clid;
						atomRettype.print(err.message.message, table, false);
						err << "', expected 'void'";
					}
					return TypeCheck::Match::none;
				}
				break;
			}
			default:
			{
				assert(false and "not implemented");
				return TypeCheck::Match::none;
			}
		}
		return perfectMatch ? TypeCheck::Match::strictEqual : TypeCheck::Match::equal;
	}

} // namespace Nany
<|endoftext|>