<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>

#define CYGWIN_PATH "c:\\cygwin\\bin\\"
#define GIT_PATH "git.exe"
#define WC_PATH  "wc.exe"

using namespace std;

#include "crc.h"

int GetGitRevisionNumber ( const char *_rootPath );

int main ( int argc, char **argv )
{
	char currentPath[2048];
	char buildNumberPath[2048];
	char fileBuffer[8192];
	char temp[256];

	if ( argc < 2 )
	{
		fprintf ( stderr, "Not enough parameters!\n" );
		return 1;
	}

	memset ( currentPath, 0, sizeof(currentPath) );

	for ( int i = 1; i < argc; i++ )
	{
		strcat ( currentPath, argv[i] );
		if ( i < argc - 1 )
			strcat ( currentPath, " " );
	}

	sprintf ( buildNumberPath, "%s/build_number.h", currentPath );

	sprintf ( fileBuffer, "#ifndef __included_build_number_h\n" );

	sprintf ( temp, "#define __included_build_number_h\n" );
	strcat ( fileBuffer, temp );

	sprintf ( temp, "\n#define BUILD_NUMBER %d\n\n",
		GetGitRevisionNumber ( currentPath ) );
	strcat ( fileBuffer, temp );

	sprintf ( temp, "#endif\n" );
	strcat ( fileBuffer, temp );

	CRC crcTemp, crcFinal;
	crcTemp.Process ( fileBuffer, strlen(fileBuffer) );
	crcFinal.ProcessFile ( buildNumberPath );

	fprintf ( stderr, "File CRC: %08x, Data CRC: %08x\n", crcTemp.GetCRC(), crcFinal.GetCRC() );

	if ( crcTemp.GetCRC() != crcFinal.GetCRC() ) {
		FILE *outfile = fopen ( buildNumberPath, "w" );
		if ( !outfile )
		{
			fprintf ( stderr, "Output file '%s' couldn't be opened!\n", buildNumberPath );
			return 1;
		}
		fprintf ( outfile, "%s", fileBuffer );
		fclose ( outfile );
	} else {
		fprintf ( stderr, "build_number.h is already up to date.\n" );
	}

	return 0;
}

int GetGitRevisionNumber ( const char *_rootPath )
{
	char command[2048];
	sprintf ( command, "%s rev-list --all | %s -l > .rev-temp",
		CYGWIN_PATH GIT_PATH, CYGWIN_PATH WC_PATH );
	int ret = system ( command );
	if ( ret != 0 )
	{
		printf ( "Command didn't work.\n" );
		return 0;
	}
	FILE *rev = fopen ( ".rev-temp", "r" );
	if ( !rev )
	{
		printf ( "Output didn't show up as expected.\n" );
		return 0;
	}
	char buffer[64];
	fgets ( buffer, 63, rev );
	fclose ( rev );
	remove ( ".rev-temp" );
	return atoi(buffer);
}
<commit_msg>Fixed build number generation on Mac and Linux.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <iostream>
#include <fstream>
#include <string>

#ifdef _MSC_VER
# define CYGWIN_PATH "c:\\cygwin\\bin\\"
# define GIT_PATH "git.exe"
# define WC_PATH "wc.exe"
#elif defined __MACH__
# define CYGWIN_PATH ""
# define GIT_PATH "/opt/local/bin/git"
# define WC_PATH  "/usr/bin/wc"
#else
# define CYGWIN_PATH ""
# define GIT_PATH "/usr/bin/git"
# define WC_PATH  "/usr/bin/wc"
#endif

using namespace std;

#include "crc.h"

int GetGitRevisionNumber ( const char *_rootPath );

int main ( int argc, char **argv )
{
	char currentPath[2048];
	char buildNumberPath[2048];
	char fileBuffer[8192];
	char temp[256];

	if ( argc < 2 )
	{
		fprintf ( stderr, "Not enough parameters!\n" );
		return 1;
	}

	memset ( currentPath, 0, sizeof(currentPath) );

	for ( int i = 1; i < argc; i++ )
	{
		strcat ( currentPath, argv[i] );
		if ( i < argc - 1 )
			strcat ( currentPath, " " );
	}

	sprintf ( buildNumberPath, "%s/build_number.h", currentPath );

	sprintf ( fileBuffer, "#ifndef __included_build_number_h\n" );

	sprintf ( temp, "#define __included_build_number_h\n" );
	strcat ( fileBuffer, temp );

	sprintf ( temp, "\n#define BUILD_NUMBER %d\n\n",
		GetGitRevisionNumber ( currentPath ) );
	strcat ( fileBuffer, temp );

	sprintf ( temp, "#endif\n" );
	strcat ( fileBuffer, temp );

	CRC crcTemp, crcFinal;
	crcTemp.Process ( fileBuffer, strlen(fileBuffer) );
	crcFinal.ProcessFile ( buildNumberPath );

	fprintf ( stderr, "File CRC: %08x, Data CRC: %08x\n", crcTemp.GetCRC(), crcFinal.GetCRC() );

	if ( crcTemp.GetCRC() != crcFinal.GetCRC() ) {
		FILE *outfile = fopen ( buildNumberPath, "w" );
		if ( !outfile )
		{
			fprintf ( stderr, "Output file '%s' couldn't be opened!\n", buildNumberPath );
			return 1;
		}
		fprintf ( outfile, "%s", fileBuffer );
		fclose ( outfile );
	} else {
		fprintf ( stderr, "build_number.h is already up to date.\n" );
	}

	return 0;
}

int GetGitRevisionNumber ( const char *_rootPath )
{
	char command[2048];
	sprintf ( command, "%s rev-list --all | %s -l > .rev-temp",
		CYGWIN_PATH GIT_PATH, CYGWIN_PATH WC_PATH );
	int ret = system ( command );
	if ( ret != 0 )
	{
		printf ( "Command didn't work.\n" );
		return 0;
	}
	FILE *rev = fopen ( ".rev-temp", "r" );
	if ( !rev )
	{
		printf ( "Output didn't show up as expected.\n" );
		return 0;
	}
	char buffer[64];
	fgets ( buffer, 63, rev );
	fclose ( rev );
	remove ( ".rev-temp" );
	return atoi(buffer);
}
<|endoftext|>


<commit_before>#ifndef MYVECTOR_HPP
#define MYVECTOR_HPP 1

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <memory>

namespace sandsnip3r {
	template<typename Type>
	class MyVectorIterator {
	private:
	};

	template<typename Type>
	class MyVector {
	public:
		using value_type = Type;
		using allocator_type = std::allocator<value_type>;
		using size_type = size_t;
		using difference_type = ptrdiff_t;
		using reference = Type&;
		using const_reference = const Type&;
		using pointer = Type*;
		using const_pointer = const Type*;
		//iterator
		//const_iterator
		//reverse_iterator
		//const_reverse_iterator
	private:
		std::allocator<value_type> vectorAllocator;
		std::unique_ptr<value_type[], std::function<void(value_type*)>> vectorData;
		size_t vectorSize{0};
		size_t vectorCapacity{0};

		void reallocateIfNecessary() {
			//Arguments state the the golden ratio is the most appropriate growth factor
			const auto GROWTH_FACTOR = 1.618;
			if (this->size() == this->capacity()) {
				//Need to reallocate to make space
				size_type newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * GROWTH_FACTOR);
				reallocate(newCapacity);
			}
		}

		void reallocate(size_type newCapacity) {
			//Allocate memory for the new data
			if (newCapacity > this->max_size()) {
				throw std::length_error("MyVector::reallocate() newCapacity (which is "+std::to_string(newCapacity)+") > max_size (which is "+std::to_string(this->max_size())+")");
			}
			//	store it in a unique_ptr
			std::unique_ptr<value_type[], std::function<void(value_type*)>> newData(vectorAllocator.allocate(newCapacity), [this, newCapacity](value_type *ptr){
				vectorAllocator.deallocate(ptr, newCapacity);
			});
			//Move the old data into out new storage chunk
			const auto &dataBegin = vectorData.get();
			std::move(dataBegin, std::next(dataBegin, vectorSize), newData.get());
			//Assign the new data to be the current
			vectorData = std::move(newData);
			//Update the capacity
			vectorCapacity = newCapacity;
		}

		reference elementAt(size_type pos) {
			return vectorData[pos];
		}

		const_reference elementAt(size_type pos) const {
			return vectorData[pos];
		}

		void throwIfOutOfBounds(size_type pos, const std::string &methodName) const {
			if (!(pos < this->size())) {
				throw std::out_of_range("MyVector::"+methodName+"() pos (which is "+std::to_string(pos)+") >= size (which is "+std::to_string(this->size())+")");
			}
		}

		void throwIfEmpty(const std::string &methodName) const {
			if (this->empty()) {
				throw std::out_of_range("MyVector::"+methodName+"() is empty");
			}
		}
	public:
		//constructor

		~MyVector() {
			this->clear();
		}

		//operator=
		//assign

		allocator_type get_allocator() const {
			return vectorAllocator;
		}

		reference at(size_type pos) {
			throwIfOutOfBounds(pos, "at");
			return elementAt(pos);
		}

		const_reference at(size_type pos) const {
			throwIfOutOfBounds(pos, "at");
			return elementAt(pos);
		}

		reference operator[](size_type pos) {
			return elementAt(pos);
		}

		const_reference operator[](size_type pos) const {
			return elementAt(pos);
		}

		reference front() {
			throwIfEmpty("front");
			return elementAt(0);
		}

		const_reference front() const {
			throwIfEmpty("front");
			return elementAt(0);
		}

		reference back() {
			throwIfEmpty("back");
			return elementAt(this->size()-1);
		}

		const_reference back() const {
			throwIfEmpty("back");
			return elementAt(this->size()-1);
		}

		pointer data() {
			return vectorData.get();
		}

		const_pointer data() const {
			return vectorData.get();
		}

		//begin, cbegin
		//end, cend
		//rbegin, crbegin
		//rend, crend

		bool empty() const {
			return (this->size() == 0);
		}

		size_type size() const {
			return vectorSize;
		}

		//max_size
		size_type max_size() const {
			return std::numeric_limits<decltype(vectorSize)>::max();
		}

		void reserve(size_type newCapacity) {
			if (this->capacity() < newCapacity) {
				reallocate(newCapacity);
			}
		}

		size_type capacity() const {
			return vectorCapacity;
		}

		void shrink_to_fit() {
			if (this->size() < this->capacity()) {
				reallocate(vectorSize);
			}
		}

		void clear() {
			for (size_type i=0; i<this->size(); ++i) {
				vectorData[i].~value_type();
			}
			vectorSize = 0;
		}

		//insert
		//emplace
		//erase

		void push_back(const value_type &obj) {
			reallocateIfNecessary();
			new(vectorData.get()+vectorSize) value_type{obj};
			++vectorSize;
		}

		void push_back(value_type &&obj) {
			reallocateIfNecessary();
			new(vectorData.get()+vectorSize) value_type{std::move(obj)};
			++vectorSize;
		}

		template<class... Args>
		void emplace_back(Args&&... args) {
			reallocateIfNecessary();
			new(vectorData.get()+vectorSize) value_type{std::forward<Args>(args)...};
			++vectorSize;
		}

		void pop_back() {
			if (!this->empty()) {
				vectorData[this->size()-1].~value_type();
				--vectorSize;
			}
		}

		void resize(size_type count) {
			if (this->size() < count) {
				if (this->capacity() < count) {
					//need to allocate more
					reallocate(count);
				}
				while (vectorSize < count) {
					//Fill with default constructed elements
					new(vectorData.get()+vectorSize) value_type{};
					++vectorSize;
				}
			} else if (this->size() > count) {
				for (size_type i=this->size()-1; i>=count; --i) {
					vectorData[i].~value_type();
					--vectorSize;
				}
			}
		}

		void resize(size_type count, const value_type &value) {
			if (this->size() < count) {
				if (this->capacity() < count) {
					//need to allocate more
					reallocate(count);
				}
				while (vectorSize < count) {
					//Fill with default constructed elements
					new(vectorData.get()+vectorSize) value_type{value};
					++vectorSize;
				}
			} else if (this->size() > count) {
				for (size_type i=this->size()-1; i>=count; --i) {
					vectorData[i].~value_type();
					--vectorSize;
				}
			}
		}

		//swap

		//operators:
		//	==
		//	!=
		//	<
		//	<=
		//	>
		//	>=

		//std::swap
	};
}

#endif //MYVECTOR_HPP<commit_msg>implemented another common reallocateIfNecessary<commit_after>#ifndef MYVECTOR_HPP
#define MYVECTOR_HPP 1

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <memory>

namespace sandsnip3r {
	template<typename Type>
	class MyVectorIterator {
	private:
	};

	template<typename Type>
	class MyVector {
	public:
		using value_type = Type;
		using allocator_type = std::allocator<value_type>;
		using size_type = size_t;
		using difference_type = ptrdiff_t;
		using reference = Type&;
		using const_reference = const Type&;
		using pointer = Type*;
		using const_pointer = const Type*;
		//iterator
		//const_iterator
		//reverse_iterator
		//const_reverse_iterator
	private:
		std::allocator<value_type> vectorAllocator;
		std::unique_ptr<value_type[], std::function<void(value_type*)>> vectorData;
		size_t vectorSize{0};
		size_t vectorCapacity{0};

		void reallocateIfNecessary() {
			//Arguments state the the golden ratio is the most appropriate growth factor
			const auto GROWTH_FACTOR = 1.618;
			if (this->size() == this->capacity()) {
				//Need to reallocate to make space
				size_type newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * GROWTH_FACTOR);
				reallocate(newCapacity);
			}
		}

		void reallocateIfNecessary(size_type newCapacity) {
			if (this->capacity() < newCapacity) {
				reallocate(newCapacity);
			}
		}

		void reallocate(size_type newCapacity) {
			//Allocate memory for the new data
			if (newCapacity > this->max_size()) {
				throw std::length_error("MyVector::reallocate() newCapacity (which is "+std::to_string(newCapacity)+") > max_size (which is "+std::to_string(this->max_size())+")");
			}
			//	store it in a unique_ptr
			std::unique_ptr<value_type[], std::function<void(value_type*)>> newData(vectorAllocator.allocate(newCapacity), [this, newCapacity](value_type *ptr){
				vectorAllocator.deallocate(ptr, newCapacity);
			});
			//Move the old data into out new storage chunk
			const auto &dataBegin = vectorData.get();
			std::move(dataBegin, std::next(dataBegin, vectorSize), newData.get());
			//Assign the new data to be the current
			vectorData = std::move(newData);
			//Update the capacity
			vectorCapacity = newCapacity;
		}

		reference elementAt(size_type pos) {
			return vectorData[pos];
		}

		const_reference elementAt(size_type pos) const {
			return vectorData[pos];
		}

		void throwIfOutOfBounds(size_type pos, const std::string &methodName) const {
			if (!(pos < this->size())) {
				throw std::out_of_range("MyVector::"+methodName+"() pos (which is "+std::to_string(pos)+") >= size (which is "+std::to_string(this->size())+")");
			}
		}

		void throwIfEmpty(const std::string &methodName) const {
			if (this->empty()) {
				throw std::out_of_range("MyVector::"+methodName+"() is empty");
			}
		}
	public:
		//constructor

		~MyVector() {
			this->clear();
		}

		//operator=
		//assign

		allocator_type get_allocator() const {
			return vectorAllocator;
		}

		reference at(size_type pos) {
			throwIfOutOfBounds(pos, "at");
			return elementAt(pos);
		}

		const_reference at(size_type pos) const {
			throwIfOutOfBounds(pos, "at");
			return elementAt(pos);
		}

		reference operator[](size_type pos) {
			return elementAt(pos);
		}

		const_reference operator[](size_type pos) const {
			return elementAt(pos);
		}

		reference front() {
			throwIfEmpty("front");
			return elementAt(0);
		}

		const_reference front() const {
			throwIfEmpty("front");
			return elementAt(0);
		}

		reference back() {
			throwIfEmpty("back");
			return elementAt(this->size()-1);
		}

		const_reference back() const {
			throwIfEmpty("back");
			return elementAt(this->size()-1);
		}

		pointer data() {
			return vectorData.get();
		}

		const_pointer data() const {
			return vectorData.get();
		}

		//begin, cbegin
		//end, cend
		//rbegin, crbegin
		//rend, crend

		bool empty() const {
			return (this->size() == 0);
		}

		size_type size() const {
			return vectorSize;
		}

		size_type max_size() const {
			//TODO: Implement this using allocator_traits
			return std::numeric_limits<decltype(vectorSize)>::max();
		}

		void reserve(size_type newCapacity) {
			reallocateIfNecessary(newCapacity);
		}

		size_type capacity() const {
			return vectorCapacity;
		}

		void shrink_to_fit() {
			if (this->size() < this->capacity()) {
				reallocate(vectorSize);
			}
		}

		void clear() {
			for (size_type i=0; i<this->size(); ++i) {
				vectorData[i].~value_type();
			}
			vectorSize = 0;
		}

		//insert
		//emplace
		//erase

		void push_back(const value_type &obj) {
			reallocateIfNecessary();
			new(vectorData.get()+vectorSize) value_type{obj};
			++vectorSize;
		}

		void push_back(value_type &&obj) {
			reallocateIfNecessary();
			new(vectorData.get()+vectorSize) value_type{std::move(obj)};
			++vectorSize;
		}

		template<class... Args>
		void emplace_back(Args&&... args) {
			reallocateIfNecessary();
			new(vectorData.get()+vectorSize) value_type{std::forward<Args>(args)...};
			++vectorSize;
		}

		void pop_back() {
			if (!this->empty()) {
				vectorData[this->size()-1].~value_type();
				--vectorSize;
			}
		}

		void resize(size_type count) {
			if (this->size() < count) {
				reallocateIfNecessary(count);
				while (vectorSize < count) {
					//Fill with default constructed elements
					new(vectorData.get()+vectorSize) value_type{};
					++vectorSize;
				}
			} else if (this->size() > count) {
				for (size_type i=this->size()-1; i>=count; --i) {
					vectorData[i].~value_type();
					--vectorSize;
				}
			}
		}

		void resize(size_type count, const value_type &value) {
			if (this->size() < count) {
				reallocateIfNecessary(count);
				while (vectorSize < count) {
					//Fill with default constructed elements
					new(vectorData.get()+vectorSize) value_type{value};
					++vectorSize;
				}
			} else if (this->size() > count) {
				for (size_type i=this->size()-1; i>=count; --i) {
					vectorData[i].~value_type();
					--vectorSize;
				}
			}
		}

		//swap

		//operators:
		//	==
		//	!=
		//	<
		//	<=
		//	>
		//	>=

		//std::swap
	};
}

#endif //MYVECTOR_HPP<|endoftext|>


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

#include "desktop/mouse_cursor_cache.h"

#include "base/logging.h"

namespace desktop {

namespace {

constexpr size_t kMinCacheSize = 2;
constexpr size_t kMaxCacheSize = 31;

} // namespace

MouseCursorCache::MouseCursorCache(size_t cache_size)
    : cache_size_(cache_size)
{
    // Nothing
}

size_t MouseCursorCache::find(const MouseCursor* mouse_cursor)
{
    DCHECK(mouse_cursor);

    size_t size = cache_.size();

    for (size_t index = 0; index < size; ++index)
    {
        // If the cursor is found in the cache.
        if (cache_.at(index)->equals(*mouse_cursor))
        {
            // Return its index.
            return index;
        }
    }

    return kInvalidIndex;
}

size_t MouseCursorCache::add(std::shared_ptr<MouseCursor> mouse_cursor)
{
    DCHECK(mouse_cursor);

    // Add the cursor to the end of the list.
    cache_.emplace_back(std::move(mouse_cursor));

    // If the current cache size exceeds the maximum cache size.
    if (cache_.size() > cache_size_)
    {
        // Delete the first element in the cache (the oldest one).
        cache_.pop_front();
    }

    return cache_.size() - 1;
}

std::shared_ptr<MouseCursor> MouseCursorCache::get(size_t index)
{
    if (index > kMaxCacheSize)
    {
        LOG(LS_WARNING) << "Invalid cache index: " << index;
        return nullptr;
    }

    return cache_.at(index);
}

bool MouseCursorCache::isEmpty() const
{
    return cache_.empty();
}

void MouseCursorCache::clear()
{
    cache_.clear();
}

// static
bool MouseCursorCache::isValidCacheSize(size_t size)
{
    if (size < kMinCacheSize || size > kMaxCacheSize)
        return false;

    return true;
}

} // namespace desktop
<commit_msg>Fixed index check.<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//

#include "desktop/mouse_cursor_cache.h"

#include "base/logging.h"

namespace desktop {

namespace {

constexpr size_t kMinCacheSize = 2;
constexpr size_t kMaxCacheSize = 31;

} // namespace

MouseCursorCache::MouseCursorCache(size_t cache_size)
    : cache_size_(cache_size)
{
    // Nothing
}

size_t MouseCursorCache::find(const MouseCursor* mouse_cursor)
{
    DCHECK(mouse_cursor);

    size_t size = cache_.size();

    for (size_t index = 0; index < size; ++index)
    {
        // If the cursor is found in the cache.
        if (cache_.at(index)->equals(*mouse_cursor))
        {
            // Return its index.
            return index;
        }
    }

    return kInvalidIndex;
}

size_t MouseCursorCache::add(std::shared_ptr<MouseCursor> mouse_cursor)
{
    DCHECK(mouse_cursor);

    // Add the cursor to the end of the list.
    cache_.emplace_back(std::move(mouse_cursor));

    // If the current cache size exceeds the maximum cache size.
    if (cache_.size() > cache_size_)
    {
        // Delete the first element in the cache (the oldest one).
        cache_.pop_front();
    }

    return cache_.size() - 1;
}

std::shared_ptr<MouseCursor> MouseCursorCache::get(size_t index)
{
    if (index >= cache_size_)
    {
        LOG(LS_WARNING) << "Invalid cache index: " << index;
        return nullptr;
    }

    return cache_.at(index);
}

bool MouseCursorCache::isEmpty() const
{
    return cache_.empty();
}

void MouseCursorCache::clear()
{
    cache_.clear();
}

// static
bool MouseCursorCache::isValidCacheSize(size_t size)
{
    if (size < kMinCacheSize || size > kMaxCacheSize)
        return false;

    return true;
}

} // namespace desktop
<|endoftext|>


<commit_before>/* =======================================================================
   Copyright (c) 2011-2013, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#ifdef _MSC_VER
  #pragma warning( disable : 4503 )     //truncated name decoration
#endif

#include "viennagrid/forwards.hpp"
#include "viennagrid/config/default_configs.hpp"
#include "viennagrid/io/netgen_reader.hpp"
#include "viennagrid/io/vtk_reader.hpp"
#include "viennagrid/io/vmesh_writer.hpp"
#include <boost/concept_check.hpp>

template<typename MeshT, typename ReaderT>
bool dump_information(std::string const & filename, std::string const & outputfile)
{
  // defining and creating a mesh and a segmentation
  typedef typename viennagrid::result_of::segmentation<MeshT>::type SegmentationType;
  MeshT mesh;
  SegmentationType segmentation(mesh);

  // trying to read the file
  try
  {
    ReaderT reader;
    reader(mesh, segmentation, filename);
  }
  catch (std::exception & e)
  {
    std::cout << "Error reading mesh file: " << filename << std::endl;
    std::cout << e.what() << std::endl;
    return false;
  }

  viennagrid::io::vmesh_writer<MeshT> writer;
  writer(mesh, segmentation, filename, outputfile);

  return true;
}

int main(int argc, char *argv[])
{
  // checking number of arguments
  if (argc != 4)
  {
    std::cout << "Usage: " << argv[0] << " <CELL_TYPE> <INPUT_FILE> <OUTPUT_FILE>" << std::endl;
    std::cout << "  Supported cell types: tet3d, tri2d, tri3d" << std::endl;
    std::cout << "  Supported file format: .mesh (Netgen), .pvd and .vtu (VTK)" << std::endl;
    std::cout << std::endl;
    std::cout << "Example: " << argv[0] << " tet3d test.mesh test.vmesh" << std::endl;
    return EXIT_FAILURE;
  }

  // querying arguments: cell type and filename
  std::string type = argv[1];
  std::string filename = argv[2];
  std::string outputfile = argv[3];
  std::string extension = filename.substr( filename.rfind(".")+1 );

  // check if cell type is supported
  if ((type != "tet3d") && (type != "tri2d") && (type != "tri3d"))
  {
    std::cout << "Cell type not supported: " << extension << std::endl;
    std::cout << "  Supported cell types: tet3d, tri2d, tri3d" << std::endl;
    return EXIT_FAILURE;
  }

  // check if file format is supported
  if ((extension != "mesh") && (extension != "pvd") && (extension != "vtk"))
  {
    std::cout << "File format not supported: " << extension << std::endl;
    std::cout << "  Supported file format: .mesh (Netgen), .pvd and .vtu (VTK)" << std::endl;
    return EXIT_FAILURE;
  }

  // call the corresponding dump_info method using the correct mesh type and reader class
  if (type == "tet3d")
  {
    typedef viennagrid::tetrahedral_3d_mesh MeshType;

    if (extension == "mesh")
      return dump_information<MeshType, viennagrid::io::netgen_reader>(filename, outputfile);
    else if ((extension == "pvd") || (extension == "vtk"))
      return dump_information<MeshType, viennagrid::io::vtk_reader<MeshType> >(filename, outputfile);
  }
  else if(type == "tri2d")
  {
    typedef viennagrid::triangular_2d_mesh MeshType;

    if (extension == "mesh")
      return dump_information<MeshType, viennagrid::io::netgen_reader>(filename, outputfile);
    else if ((extension == "pvd") || (extension == "vtk"))
      return dump_information<MeshType, viennagrid::io::vtk_reader<MeshType> >(filename, outputfile);
  }
  else if(type == "tri3d")
  {
    typedef viennagrid::triangular_3d_mesh MeshType;

    if (extension == "mesh")
      return dump_information<MeshType, viennagrid::io::netgen_reader>(filename, outputfile);
    else if ((extension == "pvd") || (extension == "vtk"))
      return dump_information<MeshType, viennagrid::io::vtk_reader<MeshType> >(filename, outputfile);
  }

  return EXIT_SUCCESS;
}

<commit_msg>vmesh_creator: Removed spurious #include <boost/concept_check.hpp><commit_after>/* =======================================================================
   Copyright (c) 2011-2013, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#ifdef _MSC_VER
  #pragma warning( disable : 4503 )     //truncated name decoration
#endif

#include "viennagrid/forwards.hpp"
#include "viennagrid/config/default_configs.hpp"
#include "viennagrid/io/netgen_reader.hpp"
#include "viennagrid/io/vtk_reader.hpp"
#include "viennagrid/io/vmesh_writer.hpp"

template<typename MeshT, typename ReaderT>
bool dump_information(std::string const & filename, std::string const & outputfile)
{
  // defining and creating a mesh and a segmentation
  typedef typename viennagrid::result_of::segmentation<MeshT>::type SegmentationType;
  MeshT mesh;
  SegmentationType segmentation(mesh);

  // trying to read the file
  try
  {
    ReaderT reader;
    reader(mesh, segmentation, filename);
  }
  catch (std::exception & e)
  {
    std::cout << "Error reading mesh file: " << filename << std::endl;
    std::cout << e.what() << std::endl;
    return false;
  }

  viennagrid::io::vmesh_writer<MeshT> writer;
  writer(mesh, segmentation, filename, outputfile);

  return true;
}

int main(int argc, char *argv[])
{
  // checking number of arguments
  if (argc != 4)
  {
    std::cout << "Usage: " << argv[0] << " <CELL_TYPE> <INPUT_FILE> <OUTPUT_FILE>" << std::endl;
    std::cout << "  Supported cell types: tet3d, tri2d, tri3d" << std::endl;
    std::cout << "  Supported file format: .mesh (Netgen), .pvd and .vtu (VTK)" << std::endl;
    std::cout << std::endl;
    std::cout << "Example: " << argv[0] << " tet3d test.mesh test.vmesh" << std::endl;
    return EXIT_FAILURE;
  }

  // querying arguments: cell type and filename
  std::string type = argv[1];
  std::string filename = argv[2];
  std::string outputfile = argv[3];
  std::string extension = filename.substr( filename.rfind(".")+1 );

  // check if cell type is supported
  if ((type != "tet3d") && (type != "tri2d") && (type != "tri3d"))
  {
    std::cout << "Cell type not supported: " << extension << std::endl;
    std::cout << "  Supported cell types: tet3d, tri2d, tri3d" << std::endl;
    return EXIT_FAILURE;
  }

  // check if file format is supported
  if ((extension != "mesh") && (extension != "pvd") && (extension != "vtk"))
  {
    std::cout << "File format not supported: " << extension << std::endl;
    std::cout << "  Supported file format: .mesh (Netgen), .pvd and .vtu (VTK)" << std::endl;
    return EXIT_FAILURE;
  }

  // call the corresponding dump_info method using the correct mesh type and reader class
  if (type == "tet3d")
  {
    typedef viennagrid::tetrahedral_3d_mesh MeshType;

    if (extension == "mesh")
      return dump_information<MeshType, viennagrid::io::netgen_reader>(filename, outputfile);
    else if ((extension == "pvd") || (extension == "vtk"))
      return dump_information<MeshType, viennagrid::io::vtk_reader<MeshType> >(filename, outputfile);
  }
  else if(type == "tri2d")
  {
    typedef viennagrid::triangular_2d_mesh MeshType;

    if (extension == "mesh")
      return dump_information<MeshType, viennagrid::io::netgen_reader>(filename, outputfile);
    else if ((extension == "pvd") || (extension == "vtk"))
      return dump_information<MeshType, viennagrid::io::vtk_reader<MeshType> >(filename, outputfile);
  }
  else if(type == "tri3d")
  {
    typedef viennagrid::triangular_3d_mesh MeshType;

    if (extension == "mesh")
      return dump_information<MeshType, viennagrid::io::netgen_reader>(filename, outputfile);
    else if ((extension == "pvd") || (extension == "vtk"))
      return dump_information<MeshType, viennagrid::io::vtk_reader<MeshType> >(filename, outputfile);
  }

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>
#include <QNetworkProxyFactory>
#include "googlechat.h"

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

    QNetworkProxyFactory::setUseSystemConfigurationEnabled(true);

    GoogleChat *chat = new GoogleChat;
    chat->show();
    return app.exec();
}
<commit_msg>Google Chat example: state that SSL is required<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>
#include <QNetworkProxyFactory>
#include "googlechat.h"

#ifndef QT_NO_OPENSSL
#include <QSslSocket>
#endif

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

#ifndef QT_NO_OPENSSL
    if (!QSslSocket::supportsSsl()) {
#endif
        QMessageBox::information(0, "Google Talk client",
                                 "Your system does not support SSL, "
                                 "which is required to run this example.");
        return -1;
#ifndef QT_NO_OPENSSL
    }
#endif

    QNetworkProxyFactory::setUseSystemConfigurationEnabled(true);

    GoogleChat *chat = new GoogleChat;
    chat->show();
    return app.exec();
}
<|endoftext|>


<commit_before>#include <qapplication.h>
#include "QtGlSliceView.h"
#include "QtSlicer.h"
#include <qfiledialog.h>
#include <qslider.h>

#include "itkImageFileReader.h"
#include "itkImage.h"
#include "itkMetaImageIOFactory.h"
#include "itkImageRegionIteratorWithIndex.h"

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

  QtSlicer myGUI( 0, 0, TRUE );

  typedef double                            PixelType;
  typedef itk::Image<PixelType, 3>          ImageType;
  typedef itk::ImageFileReader<ImageType>   ReaderType;

  ReaderType::Pointer reader = ReaderType::New();

  QString caption = "Chose an image filename";
  QString directory = ".";
  QString filter = "Images (*.*)";

  QString filename = QFileDialog::getOpenFileName( 0, caption, directory, filter );

  reader->SetFileName( filename.toLatin1() );

  try
    {
    reader->Update();
    }
  catch (itk::ExceptionObject & e)
    {
    std::cerr << "Exception in file reader " << std::endl;
    std::cerr << e << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Done!" << std::endl;
  myGUI.SetInputImage( reader->GetOutput() );

  try
    {
    myGUI.show();
    myApp.exec();
    }
  catch (itk::ExceptionObject & e)
    {
    std::cerr << "Exception during GUI execution" << std::endl;
    std::cerr << e << std::endl;
    return EXIT_FAILURE;
    }

  return 0;

}

<commit_msg>BUG: Fixed typo in file open dialog.<commit_after>#include <qapplication.h>
#include "QtGlSliceView.h"
#include "QtSlicer.h"
#include <qfiledialog.h>
#include <qslider.h>

#include "itkImageFileReader.h"
#include "itkImage.h"
#include "itkMetaImageIOFactory.h"
#include "itkImageRegionIteratorWithIndex.h"

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

  QtSlicer myGUI( 0, 0, TRUE );

  typedef double                            PixelType;
  typedef itk::Image<PixelType, 3>          ImageType;
  typedef itk::ImageFileReader<ImageType>   ReaderType;

  ReaderType::Pointer reader = ReaderType::New();

  QString caption = "Open";
  QString directory = ".";
  QString filter = "Images (*.*)";

  QString filename = QFileDialog::getOpenFileName( 0, caption, directory, filter );

  reader->SetFileName( filename.toLatin1() );

  try
    {
    reader->Update();
    }
  catch (itk::ExceptionObject & e)
    {
    std::cerr << "Exception in file reader " << std::endl;
    std::cerr << e << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Done!" << std::endl;
  myGUI.SetInputImage( reader->GetOutput() );

  try
    {
    myGUI.show();
    myApp.exec();
    }
  catch (itk::ExceptionObject & e)
    {
    std::cerr << "Exception during GUI execution" << std::endl;
    std::cerr << e << std::endl;
    return EXIT_FAILURE;
    }

  return 0;

}

<|endoftext|>


<commit_before>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/* HANDLER ... commands - direct access to ISAM */

#include "mysql_priv.h"
#include "sql_select.h"
#include <assert.h>

/* TODO:
  HANDLER blabla OPEN [ AS foobar ] [ (column-list) ]

  the most natural (easiest, fastest) way to do it is to
  compute List<Item> field_list not in mysql_ha_read
  but in mysql_ha_open, and then store it in TABLE structure.

  The problem here is that mysql_parse calls free_item to free all the
  items allocated at the end of every query. The workaround would to
  keep two item lists per THD - normal free_list and handler_items.
  The second is to be freeed only on thread end. mysql_ha_open should
  then do { handler_items=concat(handler_items, free_list); free_list=0; }

  But !!! do_cammand calls free_root at the end of every query and frees up
  all the sql_alloc'ed memory. It's harder to work around...
 */

#define HANDLER_TABLES_HACK(thd) {      \
  TABLE *tmp=thd->open_tables;          \
  thd->open_tables=thd->handler_tables; \
  thd->handler_tables=tmp; }

static TABLE **find_table_ptr_by_name(THD *thd,const char *db,
				      const char *table_name, bool is_alias);

int mysql_ha_open(THD *thd, TABLE_LIST *tables)
{
  HANDLER_TABLES_HACK(thd);
  int err=open_tables(thd,tables);
  HANDLER_TABLES_HACK(thd);
  if (err)
    return -1;

  // there can be only one table in *tables
  if (!(tables->table->file->table_flags() & HA_CAN_SQL_HANDLER))
  {
    my_printf_error(ER_ILLEGAL_HA,ER(ER_ILLEGAL_HA),MYF(0), tables->alias);
    mysql_ha_close(thd, tables,1);
    return -1;
  }

  send_ok(&thd->net);
  return 0;
}

int mysql_ha_close(THD *thd, TABLE_LIST *tables, bool dont_send_ok)
{
  TABLE **ptr=find_table_ptr_by_name(thd, tables->db, tables->alias, 1);

  if (*ptr)
  {
    VOID(pthread_mutex_lock(&LOCK_open));
    close_thread_table(thd, ptr);
    VOID(pthread_mutex_unlock(&LOCK_open));
  }
  else
  {
    my_printf_error(ER_UNKNOWN_TABLE,ER(ER_UNKNOWN_TABLE),MYF(0),
		    tables->alias, "HANDLER");
    return -1;
  }
  if (!dont_send_ok)
    send_ok(&thd->net);
  return 0;
}

int mysql_ha_closeall(THD *thd, TABLE_LIST *tables)
{
  TABLE **ptr=find_table_ptr_by_name(thd, tables->db, tables->real_name, 0);
  if (*ptr)
    close_thread_table(thd, ptr);
  return 0;
}

static enum enum_ha_read_modes rkey_to_rnext[]=
    { RNEXT, RNEXT, RPREV, RNEXT, RPREV, RNEXT, RPREV };

int mysql_ha_read(THD *thd, TABLE_LIST *tables,
    enum enum_ha_read_modes mode, char *keyname, List<Item> *key_expr,
    enum ha_rkey_function ha_rkey_mode, Item *cond,
    ha_rows select_limit,ha_rows offset_limit)
{
  int err, keyno=-1;
  TABLE *table=*find_table_ptr_by_name(thd, tables->db, tables->alias, 1);
  if (!table)
  {
    my_printf_error(ER_UNKNOWN_TABLE,ER(ER_UNKNOWN_TABLE),MYF(0),
		    tables->alias,"HANDLER");
    return -1;
  }
  tables->table=table;

  if (cond && cond->fix_fields(thd,tables))
    return -1;

  table->file->init_table_handle_for_HANDLER(); // Only InnoDB requires it

  if (keyname)
  {
    if ((keyno=find_type(keyname, &table->keynames, 1+2)-1)<0)
    {
      my_printf_error(ER_KEY_DOES_NOT_EXITS,ER(ER_KEY_DOES_NOT_EXITS),MYF(0),
          keyname,tables->alias);
      return -1;
    }
    table->file->index_init(keyno);
  }

  List<Item> list;
  list.push_front(new Item_field(NULL,NULL,"*"));
  List_iterator<Item> it(list);
  uint num_rows;
  it++;

  insert_fields(thd,tables,tables->db,tables->alias,&it);

  select_limit+=offset_limit;
  send_fields(thd,list,1);

  HANDLER_TABLES_HACK(thd);
  MYSQL_LOCK *lock=mysql_lock_tables(thd,&tables->table,1);
  HANDLER_TABLES_HACK(thd);
  if (!lock)
     goto err0; // mysql_lock_tables() printed error message already

  table->file->init_table_handle_for_HANDLER(); // Only InnoDB requires it

  for (num_rows=0; num_rows < select_limit; )
  {
    switch(mode) {
    case RFIRST:
      if (keyname)
        err=table->file->index_first(table->record[0]);
      else
      {
	if (!(err=table->file->rnd_init(1)))
          err=table->file->rnd_next(table->record[0]);
      }
      mode=RNEXT;
      break;
    case RLAST:
      DBUG_ASSERT(keyname != 0);
      err=table->file->index_last(table->record[0]);
      mode=RPREV;
      break;
    case RNEXT:
      err=keyname ?
	table->file->index_next(table->record[0]) :
	table->file->rnd_next(table->record[0]);
      break;
    case RPREV:
      DBUG_ASSERT(keyname != 0);
      err=table->file->index_prev(table->record[0]);
      break;
    case RKEY:
    {
      DBUG_ASSERT(keyname != 0);
      KEY *keyinfo=table->key_info+keyno;
      KEY_PART_INFO *key_part=keyinfo->key_part;
      uint key_len;
      byte *key;
      if (key_expr->elements > keyinfo->key_parts)
      {
	my_printf_error(ER_TOO_MANY_KEY_PARTS,ER(ER_TOO_MANY_KEY_PARTS),
			MYF(0),keyinfo->key_parts);
	goto err;
      }
      List_iterator_fast<Item> it_ke(*key_expr);
      Item *item;
      for (key_len=0 ; (item=it_ke++) ; key_part++)
      {
	if (item->fix_fields(thd, tables))
	    return -1;
	item->save_in_field(key_part->field, 1);
	key_len+=key_part->store_length;
      }
      if (!(key= (byte*) thd->calloc(ALIGN_SIZE(key_len))))
      {
	send_error(&thd->net,ER_OUTOFMEMORY);
	goto err;
      }
      key_copy(key, table, keyno, key_len);
      err=table->file->index_read(table->record[0],
				  key,key_len,ha_rkey_mode);
      mode=rkey_to_rnext[(int)ha_rkey_mode];
      break;
    }
    default:
      send_error(&thd->net,ER_ILLEGAL_HA);
      goto err;
    }

    if (err)
    {
      if (err != HA_ERR_KEY_NOT_FOUND && err != HA_ERR_END_OF_FILE)
      {
        sql_print_error("mysql_ha_read: Got error %d when reading table",
                        err);
        table->file->print_error(err,MYF(0));
        goto err;
      }
      goto ok;
    }
    if (cond)
    {
      err=err;
      if (!cond->val_int())
        continue;
    }
    if (num_rows>=offset_limit)
    {
      if (!err)
      {
        String *packet = &thd->packet;
        Item *item;
        packet->length(0);
        it.rewind();
        while ((item=it++))
        {
          if (item->send(thd,packet))
          {
            packet->free();                             // Free used
            my_error(ER_OUT_OF_RESOURCES,MYF(0));
            goto err;
          }
        }
        my_net_write(&thd->net, (char*)packet->ptr(), packet->length());
      }
    }
    num_rows++;
  }
ok:
  mysql_unlock_tables(thd,lock);
  send_eof(&thd->net);
  return 0;
err:
  mysql_unlock_tables(thd,lock);
err0:
  return -1;
}

static TABLE **find_table_ptr_by_name(THD *thd, const char *db,
				      const char *table_name, bool is_alias)
{
  int dblen;
  TABLE **ptr;

  if (!db || ! *db)
    db= thd->db ? thd->db : "";
  dblen=strlen(db)+1;
  ptr=&(thd->handler_tables);

  for (TABLE *table=*ptr; table ; table=*ptr)
  {
    if (!memcmp(table->table_cache_key, db, dblen) &&
        !my_strcasecmp((is_alias ? table->table_name : table->real_name),table_name))
      break;
    ptr=&(table->next);
  }
  return ptr;
}

<commit_msg>Fixed memory/lock leak from bug fix<commit_after>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/* HANDLER ... commands - direct access to ISAM */

#include "mysql_priv.h"
#include "sql_select.h"
#include <assert.h>

/* TODO:
  HANDLER blabla OPEN [ AS foobar ] [ (column-list) ]

  the most natural (easiest, fastest) way to do it is to
  compute List<Item> field_list not in mysql_ha_read
  but in mysql_ha_open, and then store it in TABLE structure.

  The problem here is that mysql_parse calls free_item to free all the
  items allocated at the end of every query. The workaround would to
  keep two item lists per THD - normal free_list and handler_items.
  The second is to be freeed only on thread end. mysql_ha_open should
  then do { handler_items=concat(handler_items, free_list); free_list=0; }

  But !!! do_cammand calls free_root at the end of every query and frees up
  all the sql_alloc'ed memory. It's harder to work around...
 */

#define HANDLER_TABLES_HACK(thd) {      \
  TABLE *tmp=thd->open_tables;          \
  thd->open_tables=thd->handler_tables; \
  thd->handler_tables=tmp; }

static TABLE **find_table_ptr_by_name(THD *thd,const char *db,
				      const char *table_name, bool is_alias);

int mysql_ha_open(THD *thd, TABLE_LIST *tables)
{
  HANDLER_TABLES_HACK(thd);
  int err=open_tables(thd,tables);
  HANDLER_TABLES_HACK(thd);
  if (err)
    return -1;

  // there can be only one table in *tables
  if (!(tables->table->file->table_flags() & HA_CAN_SQL_HANDLER))
  {
    my_printf_error(ER_ILLEGAL_HA,ER(ER_ILLEGAL_HA),MYF(0), tables->alias);
    mysql_ha_close(thd, tables,1);
    return -1;
  }

  send_ok(&thd->net);
  return 0;
}

int mysql_ha_close(THD *thd, TABLE_LIST *tables, bool dont_send_ok)
{
  TABLE **ptr=find_table_ptr_by_name(thd, tables->db, tables->alias, 1);

  if (*ptr)
  {
    VOID(pthread_mutex_lock(&LOCK_open));
    close_thread_table(thd, ptr);
    VOID(pthread_mutex_unlock(&LOCK_open));
  }
  else
  {
    my_printf_error(ER_UNKNOWN_TABLE,ER(ER_UNKNOWN_TABLE),MYF(0),
		    tables->alias, "HANDLER");
    return -1;
  }
  if (!dont_send_ok)
    send_ok(&thd->net);
  return 0;
}

int mysql_ha_closeall(THD *thd, TABLE_LIST *tables)
{
  TABLE **ptr=find_table_ptr_by_name(thd, tables->db, tables->real_name, 0);
  if (*ptr)
    close_thread_table(thd, ptr);
  return 0;
}

static enum enum_ha_read_modes rkey_to_rnext[]=
    { RNEXT, RNEXT, RPREV, RNEXT, RPREV, RNEXT, RPREV };

int mysql_ha_read(THD *thd, TABLE_LIST *tables,
    enum enum_ha_read_modes mode, char *keyname, List<Item> *key_expr,
    enum ha_rkey_function ha_rkey_mode, Item *cond,
    ha_rows select_limit,ha_rows offset_limit)
{
  int err, keyno=-1;
  TABLE *table=*find_table_ptr_by_name(thd, tables->db, tables->alias, 1);
  if (!table)
  {
    my_printf_error(ER_UNKNOWN_TABLE,ER(ER_UNKNOWN_TABLE),MYF(0),
		    tables->alias,"HANDLER");
    return -1;
  }
  tables->table=table;

  if (cond && cond->fix_fields(thd,tables))
    return -1;

  table->file->init_table_handle_for_HANDLER(); // Only InnoDB requires it

  if (keyname)
  {
    if ((keyno=find_type(keyname, &table->keynames, 1+2)-1)<0)
    {
      my_printf_error(ER_KEY_DOES_NOT_EXITS,ER(ER_KEY_DOES_NOT_EXITS),MYF(0),
          keyname,tables->alias);
      return -1;
    }
    table->file->index_init(keyno);
  }

  List<Item> list;
  list.push_front(new Item_field(NULL,NULL,"*"));
  List_iterator<Item> it(list);
  uint num_rows;
  it++;

  insert_fields(thd,tables,tables->db,tables->alias,&it);

  select_limit+=offset_limit;
  send_fields(thd,list,1);

  HANDLER_TABLES_HACK(thd);
  MYSQL_LOCK *lock=mysql_lock_tables(thd,&tables->table,1);
  HANDLER_TABLES_HACK(thd);
  if (!lock)
     goto err0; // mysql_lock_tables() printed error message already

  table->file->init_table_handle_for_HANDLER(); // Only InnoDB requires it

  for (num_rows=0; num_rows < select_limit; )
  {
    switch(mode) {
    case RFIRST:
      if (keyname)
        err=table->file->index_first(table->record[0]);
      else
      {
	if (!(err=table->file->rnd_init(1)))
          err=table->file->rnd_next(table->record[0]);
      }
      mode=RNEXT;
      break;
    case RLAST:
      DBUG_ASSERT(keyname != 0);
      err=table->file->index_last(table->record[0]);
      mode=RPREV;
      break;
    case RNEXT:
      err=keyname ?
	table->file->index_next(table->record[0]) :
	table->file->rnd_next(table->record[0]);
      break;
    case RPREV:
      DBUG_ASSERT(keyname != 0);
      err=table->file->index_prev(table->record[0]);
      break;
    case RKEY:
    {
      DBUG_ASSERT(keyname != 0);
      KEY *keyinfo=table->key_info+keyno;
      KEY_PART_INFO *key_part=keyinfo->key_part;
      uint key_len;
      byte *key;
      if (key_expr->elements > keyinfo->key_parts)
      {
	my_printf_error(ER_TOO_MANY_KEY_PARTS,ER(ER_TOO_MANY_KEY_PARTS),
			MYF(0),keyinfo->key_parts);
	goto err;
      }
      List_iterator_fast<Item> it_ke(*key_expr);
      Item *item;
      for (key_len=0 ; (item=it_ke++) ; key_part++)
      {
	if (item->fix_fields(thd, tables))
	  goto err;
	item->save_in_field(key_part->field, 1);
	key_len+=key_part->store_length;
      }
      if (!(key= (byte*) thd->calloc(ALIGN_SIZE(key_len))))
      {
	send_error(&thd->net,ER_OUTOFMEMORY);
	goto err;
      }
      key_copy(key, table, keyno, key_len);
      err=table->file->index_read(table->record[0],
				  key,key_len,ha_rkey_mode);
      mode=rkey_to_rnext[(int)ha_rkey_mode];
      break;
    }
    default:
      send_error(&thd->net,ER_ILLEGAL_HA);
      goto err;
    }

    if (err)
    {
      if (err != HA_ERR_KEY_NOT_FOUND && err != HA_ERR_END_OF_FILE)
      {
        sql_print_error("mysql_ha_read: Got error %d when reading table",
                        err);
        table->file->print_error(err,MYF(0));
        goto err;
      }
      goto ok;
    }
    if (cond)
    {
      err=err;
      if (!cond->val_int())
        continue;
    }
    if (num_rows>=offset_limit)
    {
      if (!err)
      {
        String *packet = &thd->packet;
        Item *item;
        packet->length(0);
        it.rewind();
        while ((item=it++))
        {
          if (item->send(thd,packet))
          {
            packet->free();                             // Free used
            my_error(ER_OUT_OF_RESOURCES,MYF(0));
            goto err;
          }
        }
        my_net_write(&thd->net, (char*)packet->ptr(), packet->length());
      }
    }
    num_rows++;
  }
ok:
  mysql_unlock_tables(thd,lock);
  send_eof(&thd->net);
  return 0;
err:
  mysql_unlock_tables(thd,lock);
err0:
  return -1;
}

static TABLE **find_table_ptr_by_name(THD *thd, const char *db,
				      const char *table_name, bool is_alias)
{
  int dblen;
  TABLE **ptr;

  if (!db || ! *db)
    db= thd->db ? thd->db : "";
  dblen=strlen(db)+1;
  ptr=&(thd->handler_tables);

  for (TABLE *table=*ptr; table ; table=*ptr)
  {
    if (!memcmp(table->table_cache_key, db, dblen) &&
        !my_strcasecmp((is_alias ? table->table_name : table->real_name),table_name))
      break;
    ptr=&(table->next);
  }
  return ptr;
}

<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	GUI widget スピン・ボックス・クラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/glfw_app/blob/master/LICENSE
*/
//=====================================================================//
#include "widgets/widget_director.hpp"
#include "widgets/widget_utils.hpp"

namespace gui {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	GUI widget_spinbox クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	struct widget_spinbox : public widget {

		typedef widget_spinbox value_type;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief	widget_spinbox ステート
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class state {
			initial,///< 初期化
			inc,	///< インクリメント
			select,	///< セレクト
			dec,	///< デクリメント
			none	///< 何もしない
		};

		typedef std::function< std::string (state st, int before, int newpos) > select_func_type;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief	widget_spinbox パラメーター
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		struct param {
			plate_param		plate_param_;
			color_param		color_param_;	///< 頂点カラーで変調する場合のパラメーター
			text_param		text_param_;	///< テキスト描画のパラメータ
			const img::i_img*	image_;		///< 画像を使う場合
			gl::mobj::handle	handle_;	///< モーションオブジェクトを使う場合
			uint32_t			id_;		///< セレクト ID （押された回数）

			select_func_type	select_func_;	///< 選択関数

			int					min_pos_;	///< 最低位置
			int					sel_pos_;	///< 選択位置
			int					max_pos_;	///< 最大位置

			bool				scroll_ctrl_;	///< スクロール・コントロール（マウスのダイアル）

			param(int min = 0, int sel = 0, int max = 0) :
				plate_param_(), color_param_(widget_director::default_spinbox_color_),
				text_param_("", img::rgba8(255, 255), img::rgba8(0, 255)),
				image_(0), handle_(0), id_(0),
				select_func_(),
				min_pos_(min), sel_pos_(sel), max_pos_(max),
				scroll_ctrl_(true)
				{ }
		};

	private:
		widget_director&	wd_;

		param				param_;

		gl::mobj::handle	objh_;
		gl::mobj::handle	up_objh_;
		gl::mobj::handle	dn_objh_;

		bool	initial_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		widget_spinbox(widget_director& wd, const widget::param& bp, const param& p) :
			widget(bp), wd_(wd), param_(p), objh_(0), up_objh_(0), dn_objh_(0),
		    initial_(false) { }

		//-----------------------------------------------------------------//
		/*!
			@brief	デストラクター
		*/
		//-----------------------------------------------------------------//
		virtual ~widget_spinbox() { }

		//-----------------------------------------------------------------//
		/*!
			@brief	型を取得
		*/
		//-----------------------------------------------------------------//
		type_id type() const override { return get_type_id<value_type>(); }

		//-----------------------------------------------------------------//
		/*!
			@brief	widget 型の基本名称を取得
			@return widget 型の基本名称
		*/
		//-----------------------------------------------------------------//
		const char* type_name() const override { return "spinbox"; }

		//-----------------------------------------------------------------//
		/*!
			@brief	ハイブリッド・ウィジェットのサイン
			@return ハイブリッド・ウィジェットの場合「true」を返す。
		*/
		//-----------------------------------------------------------------//
		bool hybrid() const override { return true; }

		//-----------------------------------------------------------------//
		/*!
			@brief	個別パラメーターへの取得(ro)
			@return 個別パラメーター
		*/
		//-----------------------------------------------------------------//
		const param& get_local_param() const { return param_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	個別パラメーターへの取得
			@return 個別パラメーター
		*/
		//-----------------------------------------------------------------//
		param& at_local_param() { return param_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	選択テキストの取得
			@return 選択テキスト
		*/
		//-----------------------------------------------------------------//
		std::string get_select_text() const { return param_.text_param_.get_text(); }

		//-----------------------------------------------------------------//
		/*!
			@brief	選択位置の取得
			@return 選択位置
		*/
		//-----------------------------------------------------------------//
		uint32_t get_select_pos() const { return param_.sel_pos_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	初期化
		*/
		//-----------------------------------------------------------------//
		void initialize() override
		{
			// ボタンは標準的に固定、サイズ固定、選択時拡大
			at_param().state_.set(widget::state::SERVICE);
			at_param().state_.set(widget::state::POSITION_LOCK);
			at_param().state_.set(widget::state::SIZE_LOCK);
			at_param().state_.set(widget::state::MOVE_STALL);
			at_param().action_.set(widget::action::SELECT_SCALE);

			using namespace img;

			if(param_.handle_) {
				at_rect().size = wd_.at_mobj().get_size(param_.handle_);
				objh_ = param_.handle_;
			} else if(param_.image_) {
				paint pa;
				const vtx::spos& size = get_rect().size;
				create_image_base(param_.image_, size, pa);
				at_rect().size = pa.get_size();
				objh_ = wd_.at_mobj().install(&pa);
			} else {
				vtx::spos size;
				if(param_.plate_param_.resizeble_) {
					vtx::spos rsz = param_.plate_param_.grid_ * 3;
					if(get_param().rect_.size.x >= rsz.x) size.x = rsz.x;
					else size.x = get_param().rect_.size.x;
					if(get_param().rect_.size.y >= rsz.y) size.y = rsz.y;
					else size.y = get_param().rect_.size.y;
				} else {
					size = get_param().rect_.size;
				}
				share_t t;
				t.size_ = size;
				t.color_param_ = param_.color_param_;
				t.plate_param_ = param_.plate_param_;
				objh_ = wd_.share_add(t);
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	アップデート
		*/
		//-----------------------------------------------------------------//
		void update() override
		{
			if(!initial_ && param_.select_func_ != nullptr) {
				initial_ = true;
				auto t = param_.select_func_(state::initial, param_.sel_pos_, param_.sel_pos_);
				if(!t.empty()) {
					param_.text_param_.set_text(t);
				}
			}

			state st = state::none;
			int d = 0;
			if(get_selected()) {
				auto x = get_param().in_point_.x;
				auto xs = get_rect().size.x;
				if(x < (xs / 3)) {  // inc
					d = 1;
					st = state::inc;
				} else if(x >= (xs * 2 / 3)) {  // dec
					d = -1;
					st = state::dec;
				} else {
					st = state::select;
				}
			} else if(get_focus() && param_.scroll_ctrl_) {
				const vtx::spos& scr = wd_.get_scroll();
				if(scr.y != 0) {
					d = -scr.y;
					if(d > 0) st = state::inc;
					else if(d < 0) st = state::dec;
				}
			}

			if(st != state::none) {
				int before = param_.sel_pos_;
				++param_.id_;
				if(d > 0) {
					param_.sel_pos_ += d;
					if(param_.sel_pos_ > param_.max_pos_) param_.sel_pos_ = param_.max_pos_;
					st = state::inc;
				} else if(d < 0) {
					param_.sel_pos_ += d;
					if(param_.sel_pos_ < param_.min_pos_) param_.sel_pos_ = param_.min_pos_;
					st = state::dec;
				}
				if(param_.select_func_ != nullptr) {
					auto t = param_.select_func_(st, before, param_.sel_pos_);
					if(!t.empty()) {
						param_.text_param_.set_text(t);
					}
				}
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	サービス
		*/
		//-----------------------------------------------------------------//
		void service() override { }

		//-----------------------------------------------------------------//
		/*!
			@brief	レンダリング
		*/
		//-----------------------------------------------------------------//
		void render() override
		{
			if(objh_ == 0) return;

			using namespace gl;

			core& core = core::get_instance();
			const vtx::spos& siz = core.get_rect().size;

			if(param_.plate_param_.resizeble_) {
				wd_.at_mobj().resize(objh_, get_param().rect_.size);
			}

			render_text(wd_, objh_, get_param(), param_.text_param_, param_.plate_param_);

			// チップの描画
			wd_.at_mobj().setup_matrix(siz.x, siz.y);
			wd_.set_TSC();

			gl::mobj::handle uph = wd_.get_share_image().up_box_;
			gl::mobj::handle dnh = wd_.get_share_image().down_box_;
			const vtx::spos& bs = wd_.at_mobj().get_size(uph);
			const vtx::spos& size = get_rect().size;
			short wf = param_.plate_param_.frame_width_;
			short space = 2;
			vtx::spos pos(size.x - bs.x - wf - space, (size.y - bs.y) / 2);
			wd_.at_mobj().draw(dnh, gl::mobj::attribute::normal, pos);
			pos.x = wf + space;
			wd_.at_mobj().draw(uph, gl::mobj::attribute::normal, pos);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	状態のセーブ
			@param[in]	pre	プリファレンス参照
			@return エラーが無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool save(sys::preference& pre) override {
			std::string path;
			path += '/';
			path += wd_.create_widget_name(this);

			int err = 0;
			if(!pre.put_integer(path + "/selector", param_.sel_pos_)) ++err;
			return err == 0;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	状態のロード
			@param[in]	pre	プリファレンス参照
			@return エラーが無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool load(const sys::preference& pre) override {
			std::string path;
			path += '/';
			path += wd_.create_widget_name(this);

			int err = 0;
			if(!pre.get_integer(path + "/selector", param_.sel_pos_)) ++err;
			return err == 0;
		}
	};

}
<commit_msg>update: accel button (repeat)<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	GUI widget スピン・ボックス・クラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/glfw_app/blob/master/LICENSE
*/
//=====================================================================//
#include "widgets/widget_director.hpp"
#include "widgets/widget_utils.hpp"

namespace gui {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	GUI widget_spinbox クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	struct widget_spinbox : public widget {

		typedef widget_spinbox value_type;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief	widget_spinbox ステート
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class state {
			initial,///< 初期化
			inc,	///< インクリメント
			select,	///< セレクト
			dec,	///< デクリメント
			none	///< 何もしない
		};

		typedef std::function< std::string (state st, int before, int newpos) > select_func_type;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief	widget_spinbox パラメーター
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		struct param {
			plate_param		plate_param_;
			color_param		color_param_;	///< 頂点カラーで変調する場合のパラメーター
			text_param		text_param_;	///< テキスト描画のパラメータ
			const img::i_img*	image_;		///< 画像を使う場合
			gl::mobj::handle	handle_;	///< モーションオブジェクトを使う場合
			uint32_t			id_;		///< セレクト ID （押された回数）

			select_func_type	select_func_;	///< 選択関数

			int					min_pos_;	///< 最低位置
			int					sel_pos_;	///< 選択位置
			int					max_pos_;	///< 最大位置

			bool				scroll_ctrl_;	///< スクロール・コントロール（マウスのダイアル）
			bool				accel_;			///< ボタンのアクセル・コントロール
			uint16_t			accel_delay_;	///< アクセルが利くまでの遅延
			uint16_t			accel_inter_;	///< アクセル時のインターバル（速度）

			param(int min = 0, int sel = 0, int max = 0) :
				plate_param_(), color_param_(widget_director::default_spinbox_color_),
				text_param_("", img::rgba8(255, 255), img::rgba8(0, 255)),
				image_(0), handle_(0), id_(0),
				select_func_(),
				min_pos_(min), sel_pos_(sel), max_pos_(max),
				scroll_ctrl_(true),
				accel_(true), accel_delay_(35), accel_inter_(10)
				{ }
		};

	private:
		widget_director&	wd_;

		param				param_;

		gl::mobj::handle	objh_;
		gl::mobj::handle	up_objh_;
		gl::mobj::handle	dn_objh_;

		bool	initial_;

		uint16_t	delay_cnt_;

		state get_button_state_(int& d) const
		{
			state st = state::none;
			auto x = get_param().in_point_.x;
			auto xs = get_rect().size.x;
			if(x < (xs / 3)) {  // inc
				d = 1;
				st = state::inc;
			} else if(x >= (xs * 2 / 3)) {  // dec
				d = -1;
				st = state::dec;
			} else {
				st = state::select;
			}
			return st;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		widget_spinbox(widget_director& wd, const widget::param& bp, const param& p) :
			widget(bp), wd_(wd), param_(p), objh_(0), up_objh_(0), dn_objh_(0),
		    initial_(false), delay_cnt_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief	デストラクター
		*/
		//-----------------------------------------------------------------//
		virtual ~widget_spinbox() { }

		//-----------------------------------------------------------------//
		/*!
			@brief	型を取得
		*/
		//-----------------------------------------------------------------//
		type_id type() const override { return get_type_id<value_type>(); }

		//-----------------------------------------------------------------//
		/*!
			@brief	widget 型の基本名称を取得
			@return widget 型の基本名称
		*/
		//-----------------------------------------------------------------//
		const char* type_name() const override { return "spinbox"; }

		//-----------------------------------------------------------------//
		/*!
			@brief	ハイブリッド・ウィジェットのサイン
			@return ハイブリッド・ウィジェットの場合「true」を返す。
		*/
		//-----------------------------------------------------------------//
		bool hybrid() const override { return true; }

		//-----------------------------------------------------------------//
		/*!
			@brief	個別パラメーターへの取得(ro)
			@return 個別パラメーター
		*/
		//-----------------------------------------------------------------//
		const param& get_local_param() const { return param_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	個別パラメーターへの取得
			@return 個別パラメーター
		*/
		//-----------------------------------------------------------------//
		param& at_local_param() { return param_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	選択テキストの取得
			@return 選択テキスト
		*/
		//-----------------------------------------------------------------//
		std::string get_select_text() const { return param_.text_param_.get_text(); }

		//-----------------------------------------------------------------//
		/*!
			@brief	選択位置の取得
			@return 選択位置
		*/
		//-----------------------------------------------------------------//
		uint32_t get_select_pos() const { return param_.sel_pos_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	初期化
		*/
		//-----------------------------------------------------------------//
		void initialize() override
		{
			// ボタンは標準的に固定、サイズ固定、選択時拡大
			at_param().state_.set(widget::state::SERVICE);
			at_param().state_.set(widget::state::POSITION_LOCK);
			at_param().state_.set(widget::state::SIZE_LOCK);
			at_param().state_.set(widget::state::MOVE_STALL);
			at_param().action_.set(widget::action::SELECT_SCALE);

			using namespace img;

			if(param_.handle_) {
				at_rect().size = wd_.at_mobj().get_size(param_.handle_);
				objh_ = param_.handle_;
			} else if(param_.image_) {
				paint pa;
				const vtx::spos& size = get_rect().size;
				create_image_base(param_.image_, size, pa);
				at_rect().size = pa.get_size();
				objh_ = wd_.at_mobj().install(&pa);
			} else {
				vtx::spos size;
				if(param_.plate_param_.resizeble_) {
					vtx::spos rsz = param_.plate_param_.grid_ * 3;
					if(get_param().rect_.size.x >= rsz.x) size.x = rsz.x;
					else size.x = get_param().rect_.size.x;
					if(get_param().rect_.size.y >= rsz.y) size.y = rsz.y;
					else size.y = get_param().rect_.size.y;
				} else {
					size = get_param().rect_.size;
				}
				share_t t;
				t.size_ = size;
				t.color_param_ = param_.color_param_;
				t.plate_param_ = param_.plate_param_;
				objh_ = wd_.share_add(t);
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	アップデート
		*/
		//-----------------------------------------------------------------//
		void update() override
		{
			if(!initial_ && param_.select_func_ != nullptr) {
				initial_ = true;
				auto t = param_.select_func_(state::initial, param_.sel_pos_, param_.sel_pos_);
				if(!t.empty()) {
					param_.text_param_.set_text(t);
				}
			}

			state st = state::none;
			int d = 0;
			if(get_selected()) {
				st = get_button_state_(d);
				delay_cnt_ = 0;
			} else if(get_focus() && param_.scroll_ctrl_) {
				if(get_select()) {
					st = get_button_state_(d);
					if(st == state::inc || st == state::dec) {
						++delay_cnt_;
						if(delay_cnt_ >= param_.accel_delay_) {
							if(delay_cnt_ > param_.accel_inter_) {
								delay_cnt_ -= param_.accel_inter_;
							} else {
								delay_cnt_ = 0;
							}
						} else {
							st = state::none;
						}
					}
				} else {
					delay_cnt_ = 0;
					const vtx::spos& scr = wd_.get_scroll();
					if(scr.y != 0) {
						d = -scr.y;
						if(d > 0) st = state::inc;
						else if(d < 0) st = state::dec;
					}
				}
			}

			if(st != state::none) {
				int before = param_.sel_pos_;
				++param_.id_;
				if(d > 0) {
					param_.sel_pos_ += d;
					if(param_.sel_pos_ > param_.max_pos_) param_.sel_pos_ = param_.max_pos_;
					st = state::inc;
				} else if(d < 0) {
					param_.sel_pos_ += d;
					if(param_.sel_pos_ < param_.min_pos_) param_.sel_pos_ = param_.min_pos_;
					st = state::dec;
				}
				if(param_.select_func_ != nullptr) {
					auto t = param_.select_func_(st, before, param_.sel_pos_);
					if(!t.empty()) {
						param_.text_param_.set_text(t);
					}
				}
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	サービス
		*/
		//-----------------------------------------------------------------//
		void service() override { }

		//-----------------------------------------------------------------//
		/*!
			@brief	レンダリング
		*/
		//-----------------------------------------------------------------//
		void render() override
		{
			if(objh_ == 0) return;

			using namespace gl;

			core& core = core::get_instance();
			const vtx::spos& siz = core.get_rect().size;

			if(param_.plate_param_.resizeble_) {
				wd_.at_mobj().resize(objh_, get_param().rect_.size);
			}

			render_text(wd_, objh_, get_param(), param_.text_param_, param_.plate_param_);

			// チップの描画
			wd_.at_mobj().setup_matrix(siz.x, siz.y);
			wd_.set_TSC();

			gl::mobj::handle uph = wd_.get_share_image().up_box_;
			gl::mobj::handle dnh = wd_.get_share_image().down_box_;
			const vtx::spos& bs = wd_.at_mobj().get_size(uph);
			const vtx::spos& size = get_rect().size;
			short wf = param_.plate_param_.frame_width_;
			short space = 2;
			vtx::spos pos(size.x - bs.x - wf - space, (size.y - bs.y) / 2);
			wd_.at_mobj().draw(dnh, gl::mobj::attribute::normal, pos);
			pos.x = wf + space;
			wd_.at_mobj().draw(uph, gl::mobj::attribute::normal, pos);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	状態のセーブ
			@param[in]	pre	プリファレンス参照
			@return エラーが無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool save(sys::preference& pre) override {
			std::string path;
			path += '/';
			path += wd_.create_widget_name(this);

			int err = 0;
			if(!pre.put_integer(path + "/selector", param_.sel_pos_)) ++err;
			return err == 0;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	状態のロード
			@param[in]	pre	プリファレンス参照
			@return エラーが無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool load(const sys::preference& pre) override {
			std::string path;
			path += '/';
			path += wd_.create_widget_name(this);

			int err = 0;
			if(!pre.get_integer(path + "/selector", param_.sel_pos_)) ++err;
			return err == 0;
		}
	};

}
<|endoftext|>


<commit_before>/******************************************************************************
 *  Copyright (c) 2015 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project:
 *  Filename: libssh_wrapper.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hoojamis@gmail.com
 *  Date: Jun  4, 2015
 *  Time: 22:48:53
 *  Description: wapper of libssh functions
 *****************************************************************************/

#include "libssh_wrapper.h"
#include <libssh/libssh.h>
#include <libssh/sftp.h>
#include <sys/stat.h>
#include <fcntl.h>

intmax_t SSHSession::read(const std::string& path, const size_t offset, const size_t size, char* buff) {
    ssh_session ssh_session;
    sftp_session sftp_session;
    sftp_file file_handle;

    bool rtv =
               // alloc ssh session
               bool(ssh_session = ssh_new()) &&
               // set host
               ssh_options_set(ssh_session, SSH_OPTIONS_HOST, _address.c_str()) == 0 &&
               // set port
               ssh_options_set(ssh_session, SSH_OPTIONS_PORT, &_port) == 0 &&
               // connect ssh
               ssh_connect(ssh_session) == SSH_OK &&
               // ssh authentication
               ssh_userauth_publickey_auto(ssh_session, 0, 0) == SSH_AUTH_SUCCESS &&
               // create sftp session
               bool(sftp_session = sftp_new(ssh_session)) &&
               // sftp init
               sftp_init(sftp_session) == SSH_OK &&
               // open file
               bool(file_handle = sftp_open(sftp_session, path.c_str(), O_RDONLY, 0)) &&
               // seek
               sftp_seek64(file_handle, offset) == 0;

    intmax_t bytes_read = -1;

    if (rtv)
        bytes_read = sftp_read(file_handle, buff, size);

    if (file_handle) sftp_close(file_handle);
    file_handle = nullptr;
    if (sftp_session) sftp_free(sftp_session);
    sftp_session = nullptr;
    ssh_disconnect(ssh_session);
    ssh_free(ssh_session);

    return bytes_read;
}

<commit_msg>add cerr<commit_after>/******************************************************************************
 *  Copyright (c) 2015 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project:
 *  Filename: libssh_wrapper.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hoojamis@gmail.com
 *  Date: Jun  4, 2015
 *  Time: 22:48:53
 *  Description: wapper of libssh functions
 *****************************************************************************/

#include "libssh_wrapper.h"
#include <libssh/libssh.h>
#include <libssh/sftp.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>

intmax_t SSHSession::read(const std::string& path, const size_t offset, const size_t size, char* buff) {
    ssh_session ssh_session;
    sftp_session sftp_session;
    sftp_file file_handle;

    bool rtv =
               // alloc ssh session
               bool(ssh_session = ssh_new()) &&
               // set host
               ssh_options_set(ssh_session, SSH_OPTIONS_HOST, _address.c_str()) == 0 &&
               // set port
               ssh_options_set(ssh_session, SSH_OPTIONS_PORT, &_port) == 0 &&
               // connect ssh
               ssh_connect(ssh_session) == SSH_OK &&
               // ssh authentication
               ssh_userauth_publickey_auto(ssh_session, 0, 0) == SSH_AUTH_SUCCESS &&
               // create sftp session
               bool(sftp_session = sftp_new(ssh_session)) &&
               // sftp init
               sftp_init(sftp_session) == SSH_OK &&
               // open file
               bool(file_handle = sftp_open(sftp_session, path.c_str(), O_RDONLY, 0)) &&
               // seek
               sftp_seek64(file_handle, offset) == 0;

    intmax_t bytes_read = -1;

    if (rtv)
        bytes_read = sftp_read(file_handle, buff, size);
    else
        std::cerr << "SSH connection failed. " << std::endl;

    if (file_handle) sftp_close(file_handle);
    file_handle = nullptr;
    if (sftp_session) sftp_free(sftp_session);
    sftp_session = nullptr;
    ssh_disconnect(ssh_session);
    ssh_free(ssh_session);

    return bytes_read;
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "testwizard.h"
#include "testwizarddialog.h"

#include <cpptools/abstracteditorsupport.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <qtsupport/qtsupportconstants.h>

#include <utils/qtcassert.h>

#include <QCoreApplication>
#include <QTextStream>
#include <QFileInfo>

namespace QmakeProjectManager {
namespace Internal {

TestWizard::TestWizard()
{
    setId(QLatin1String("L.Qt4Test"));
    setCategory(QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY));
    setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
             ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY));
    setDisplayName(tr("Qt Unit Test"));
    setDescription(tr("Creates a QTestLib-based unit test for a feature or a class. "
                "Unit tests allow you to verify that the code is fit for use "
                "and that there are no regressions."));
    setIcon(QIcon(QLatin1String(":/wizards/images/console.png")));
    setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT_CONSOLE) |
            Core::Feature(QtSupport::Constants::FEATURE_QT));
}

Core::BaseFileWizard *TestWizard::create(QWidget *parent, const Core::WizardDialogParameters &parameters) const
{
    TestWizardDialog *dialog = new TestWizardDialog(displayName(), icon(), parent, parameters);
    dialog->setProjectName(TestWizardDialog::uniqueProjectName(parameters.defaultPath()));
    return dialog;
}

// ---------------- code generation helpers
static const char initTestCaseC[] = "initTestCase";
static const char cleanupTestCaseC[] = "cleanupTestCase";
static const char closeFunctionC[] = "}\n\n";
static const char testDataTypeC[] = "QString";

static inline void writeVoidMemberDeclaration(QTextStream &str,
                                              const QString &indent,
                                              const QString &methodName)
{
    str << indent << "void " << methodName << "();\n";
}

static inline void writeVoidMemberBody(QTextStream &str,
                                       const QString &className,
                                       const QString &methodName,
                                       bool close = true)
{
    str << "void " << className << "::" << methodName << "()\n{\n";
    if (close)
        str << closeFunctionC;
}

static QString generateTestCode(const TestWizardParameters &testParams,
                                const QString &sourceBaseName)
{
    QString rc;
    const QString indent = QString(4, QLatin1Char(' '));
    QTextStream str(&rc);
    // Includes
    str << CppTools::AbstractEditorSupport::licenseTemplate(testParams.fileName, testParams.className)
        << "#include <QString>\n#include <QtTest>\n";
    if (testParams.requiresQApplication)
        str << "#include <QCoreApplication>\n";
    // Class declaration
    str  << "\nclass " << testParams.className << " : public QObject\n"
        "{\n" << indent << "Q_OBJECT\n\npublic:\n"
        << indent << testParams.className << "();\n\nprivate Q_SLOTS:\n";
    if (testParams.initializationCode) {
        writeVoidMemberDeclaration(str, indent, QLatin1String(initTestCaseC));
        writeVoidMemberDeclaration(str, indent, QLatin1String(cleanupTestCaseC));
    }
    const QString dataSlot = testParams.testSlot + QLatin1String("_data");
    writeVoidMemberDeclaration(str, indent, testParams.testSlot);
    if (testParams.useDataSet)
        writeVoidMemberDeclaration(str, indent, dataSlot);
    str << "};\n\n";
    // Code: Constructor
    str << testParams.className << "::" << testParams.className << "()\n{\n}\n\n";
    // Code: Initialization slots
    if (testParams.initializationCode) {
        writeVoidMemberBody(str, testParams.className, QLatin1String(initTestCaseC));
        writeVoidMemberBody(str, testParams.className, QLatin1String(cleanupTestCaseC));
    }
    // Test slot with data or dummy
    writeVoidMemberBody(str, testParams.className, testParams.testSlot, false);
    if (testParams.useDataSet)
        str << indent << "QFETCH(" << testDataTypeC << ", data);\n";
    switch (testParams.type) {
    case TestWizardParameters::Test:
        str << indent << "QVERIFY2(true, \"Failure\");\n";
        break;
    case TestWizardParameters::Benchmark:
        str << indent << "QBENCHMARK {\n" << indent << "}\n";
        break;
    }
    str << closeFunctionC;
    // test data generation slot
    if (testParams.useDataSet) {
        writeVoidMemberBody(str, testParams.className, dataSlot, false);
        str << indent << "QTest::addColumn<" << testDataTypeC << ">(\"data\");\n"
            << indent << "QTest::newRow(\"0\") << " << testDataTypeC << "();\n"
            << closeFunctionC;
    }
    // Main & moc include
    str << (testParams.requiresQApplication ? "QTEST_MAIN" : "QTEST_APPLESS_MAIN")
        << '(' << testParams.className << ")\n\n"
        << "#include \"" << sourceBaseName << ".moc\"\n";
    return rc;
}

Core::GeneratedFiles TestWizard::generateFiles(const QWizard *w, QString *errorMessage) const
{
    Q_UNUSED(errorMessage)

    const TestWizardDialog *wizardDialog = qobject_cast<const TestWizardDialog *>(w);
    QTC_ASSERT(wizardDialog, return Core::GeneratedFiles());

    const QtProjectParameters projectParams = wizardDialog->projectParameters();
    const TestWizardParameters testParams = wizardDialog->testParameters();
    const QString projectPath = projectParams.projectPath();

    // Create files: Source
    const QString sourceFilePath = Core::BaseFileWizardFactory::buildFileName(projectPath, testParams.fileName, sourceSuffix());
    const QFileInfo sourceFileInfo(sourceFilePath);

    Core::GeneratedFile source(sourceFilePath);
    source.setAttributes(Core::GeneratedFile::OpenEditorAttribute);
    source.setContents(generateTestCode(testParams, sourceFileInfo.baseName()));

    // Create profile with define for base dir to find test data
    const QString profileName = Core::BaseFileWizardFactory::buildFileName(projectPath, projectParams.fileName, profileSuffix());
    Core::GeneratedFile profile(profileName);
    profile.setAttributes(Core::GeneratedFile::OpenProjectAttribute);
    QString contents;
    {
        QTextStream proStr(&contents);
        QtProjectParameters::writeProFileHeader(proStr);
        projectParams.writeProFile(proStr);
        proStr << "\n\nSOURCES += " << QFileInfo(sourceFilePath).fileName() << '\n'
               << "DEFINES += SRCDIR=\\\\\\\"$$PWD/\\\\\\\"\n";
    }
    profile.setContents(contents);

    return Core::GeneratedFiles() <<  source << profile;
}

} // namespace Internal
} // namespace QmakeProjectManager
<commit_msg>testwizard: put _data function before test function.<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "testwizard.h"
#include "testwizarddialog.h"

#include <cpptools/abstracteditorsupport.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <qtsupport/qtsupportconstants.h>

#include <utils/qtcassert.h>

#include <QCoreApplication>
#include <QTextStream>
#include <QFileInfo>

namespace QmakeProjectManager {
namespace Internal {

TestWizard::TestWizard()
{
    setId(QLatin1String("L.Qt4Test"));
    setCategory(QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY));
    setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
             ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY));
    setDisplayName(tr("Qt Unit Test"));
    setDescription(tr("Creates a QTestLib-based unit test for a feature or a class. "
                "Unit tests allow you to verify that the code is fit for use "
                "and that there are no regressions."));
    setIcon(QIcon(QLatin1String(":/wizards/images/console.png")));
    setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT_CONSOLE) |
            Core::Feature(QtSupport::Constants::FEATURE_QT));
}

Core::BaseFileWizard *TestWizard::create(QWidget *parent, const Core::WizardDialogParameters &parameters) const
{
    TestWizardDialog *dialog = new TestWizardDialog(displayName(), icon(), parent, parameters);
    dialog->setProjectName(TestWizardDialog::uniqueProjectName(parameters.defaultPath()));
    return dialog;
}

// ---------------- code generation helpers
static const char initTestCaseC[] = "initTestCase";
static const char cleanupTestCaseC[] = "cleanupTestCase";
static const char closeFunctionC[] = "}\n\n";
static const char testDataTypeC[] = "QString";

static inline void writeVoidMemberDeclaration(QTextStream &str,
                                              const QString &indent,
                                              const QString &methodName)
{
    str << indent << "void " << methodName << "();\n";
}

static inline void writeVoidMemberBody(QTextStream &str,
                                       const QString &className,
                                       const QString &methodName,
                                       bool close = true)
{
    str << "void " << className << "::" << methodName << "()\n{\n";
    if (close)
        str << closeFunctionC;
}

static QString generateTestCode(const TestWizardParameters &testParams,
                                const QString &sourceBaseName)
{
    QString rc;
    const QString indent = QString(4, QLatin1Char(' '));
    QTextStream str(&rc);
    // Includes
    str << CppTools::AbstractEditorSupport::licenseTemplate(testParams.fileName, testParams.className)
        << "#include <QString>\n#include <QtTest>\n";
    if (testParams.requiresQApplication)
        str << "#include <QCoreApplication>\n";
    // Class declaration
    str  << "\nclass " << testParams.className << " : public QObject\n"
        "{\n" << indent << "Q_OBJECT\n\npublic:\n"
        << indent << testParams.className << "();\n\nprivate Q_SLOTS:\n";
    if (testParams.initializationCode) {
        writeVoidMemberDeclaration(str, indent, QLatin1String(initTestCaseC));
        writeVoidMemberDeclaration(str, indent, QLatin1String(cleanupTestCaseC));
    }
    const QString dataSlot = testParams.testSlot + QLatin1String("_data");
    if (testParams.useDataSet)
        writeVoidMemberDeclaration(str, indent, dataSlot);
    writeVoidMemberDeclaration(str, indent, testParams.testSlot);
    str << "};\n\n";
    // Code: Constructor
    str << testParams.className << "::" << testParams.className << "()\n{\n}\n\n";
    // Code: Initialization slots
    if (testParams.initializationCode) {
        writeVoidMemberBody(str, testParams.className, QLatin1String(initTestCaseC));
        writeVoidMemberBody(str, testParams.className, QLatin1String(cleanupTestCaseC));
    }
    // test data generation slot
    if (testParams.useDataSet) {
        writeVoidMemberBody(str, testParams.className, dataSlot, false);
        str << indent << "QTest::addColumn<" << testDataTypeC << ">(\"data\");\n"
            << indent << "QTest::newRow(\"0\") << " << testDataTypeC << "();\n"
            << closeFunctionC;
    }
    // Test slot with data or dummy
    writeVoidMemberBody(str, testParams.className, testParams.testSlot, false);
    if (testParams.useDataSet)
        str << indent << "QFETCH(" << testDataTypeC << ", data);\n";
    switch (testParams.type) {
    case TestWizardParameters::Test:
        str << indent << "QVERIFY2(true, \"Failure\");\n";
        break;
    case TestWizardParameters::Benchmark:
        str << indent << "QBENCHMARK {\n" << indent << "}\n";
        break;
    }
    str << closeFunctionC;
    // Main & moc include
    str << (testParams.requiresQApplication ? "QTEST_MAIN" : "QTEST_APPLESS_MAIN")
        << '(' << testParams.className << ")\n\n"
        << "#include \"" << sourceBaseName << ".moc\"\n";
    return rc;
}

Core::GeneratedFiles TestWizard::generateFiles(const QWizard *w, QString *errorMessage) const
{
    Q_UNUSED(errorMessage)

    const TestWizardDialog *wizardDialog = qobject_cast<const TestWizardDialog *>(w);
    QTC_ASSERT(wizardDialog, return Core::GeneratedFiles());

    const QtProjectParameters projectParams = wizardDialog->projectParameters();
    const TestWizardParameters testParams = wizardDialog->testParameters();
    const QString projectPath = projectParams.projectPath();

    // Create files: Source
    const QString sourceFilePath = Core::BaseFileWizardFactory::buildFileName(projectPath, testParams.fileName, sourceSuffix());
    const QFileInfo sourceFileInfo(sourceFilePath);

    Core::GeneratedFile source(sourceFilePath);
    source.setAttributes(Core::GeneratedFile::OpenEditorAttribute);
    source.setContents(generateTestCode(testParams, sourceFileInfo.baseName()));

    // Create profile with define for base dir to find test data
    const QString profileName = Core::BaseFileWizardFactory::buildFileName(projectPath, projectParams.fileName, profileSuffix());
    Core::GeneratedFile profile(profileName);
    profile.setAttributes(Core::GeneratedFile::OpenProjectAttribute);
    QString contents;
    {
        QTextStream proStr(&contents);
        QtProjectParameters::writeProFileHeader(proStr);
        projectParams.writeProFile(proStr);
        proStr << "\n\nSOURCES += " << QFileInfo(sourceFilePath).fileName() << '\n'
               << "DEFINES += SRCDIR=\\\\\\\"$$PWD/\\\\\\\"\n";
    }
    profile.setContents(contents);

    return Core::GeneratedFiles() <<  source << profile;
}

} // namespace Internal
} // namespace QmakeProjectManager
<|endoftext|>


<commit_before>#include <cctbx/boost_python/flex_fwd.h>
#include <yamtbx/dataproc/crystfel/merge_equivalents.h>

#include <boost/python/class.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/return_by_value.hpp>

namespace yamtbx { namespace dataproc { namespace crystfel { namespace boost_python {

namespace {

  struct merge_equivalents_crystfel_wrappers
  {
    typedef merge_equivalents_crystfel<> w_t;

    static void
    wrap()
    {
      using namespace boost::python;
      typedef return_value_policy<return_by_value> rbv;
      class_<w_t>("merge_equivalents_crystfel")
	.def("add_observations", (void(w_t::*)(af::const_ref<cctbx::miller::index<> > const&,
					       af::const_ref<double> const&))&w_t::add_observations,
	     (arg("unmerged_indices"), arg("unmerged_data")))
	.def("add_observations", (void(w_t::*)(af::const_ref<cctbx::miller::index<> > const&,
					       af::const_ref<double> const&,
					       af::const_ref<double> const&))&w_t::add_observations,
	     (arg("unmerged_indices"), arg("unmerged_data"), arg("unmerged_sigmas")))
	.def("merge", &w_t::merge, arg("sigma")="population sigma")
        .add_property("indices", make_getter(&w_t::indices, rbv()))
        .add_property("data", make_getter(&w_t::data, rbv()))
        .add_property("sigmas", make_getter(&w_t::sigmas, rbv()))
        .add_property("redundancies", make_getter(&w_t::redundancies, rbv()))
      ;
    }
  };
} // namespace <anoymous>

  void wrap_merge_equivalents()
  {
    merge_equivalents_crystfel_wrappers::wrap();
  }

}}}} // namespace yamtbx::dataproc::crystfel::boost_python
<commit_msg>relative path to header for easy compiling Commit 7aaa7871<commit_after>#include <cctbx/boost_python/flex_fwd.h>
#include "../merge_equivalents.h"

#include <boost/python/class.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/return_by_value.hpp>

namespace yamtbx { namespace dataproc { namespace crystfel { namespace boost_python {

namespace {

  struct merge_equivalents_crystfel_wrappers
  {
    typedef merge_equivalents_crystfel<> w_t;

    static void
    wrap()
    {
      using namespace boost::python;
      typedef return_value_policy<return_by_value> rbv;
      class_<w_t>("merge_equivalents_crystfel")
	.def("add_observations", (void(w_t::*)(af::const_ref<cctbx::miller::index<> > const&,
					       af::const_ref<double> const&))&w_t::add_observations,
	     (arg("unmerged_indices"), arg("unmerged_data")))
	.def("add_observations", (void(w_t::*)(af::const_ref<cctbx::miller::index<> > const&,
					       af::const_ref<double> const&,
					       af::const_ref<double> const&))&w_t::add_observations,
	     (arg("unmerged_indices"), arg("unmerged_data"), arg("unmerged_sigmas")))
	.def("merge", &w_t::merge, arg("sigma")="population sigma")
        .add_property("indices", make_getter(&w_t::indices, rbv()))
        .add_property("data", make_getter(&w_t::data, rbv()))
        .add_property("sigmas", make_getter(&w_t::sigmas, rbv()))
        .add_property("redundancies", make_getter(&w_t::redundancies, rbv()))
      ;
    }
  };
} // namespace <anoymous>

  void wrap_merge_equivalents()
  {
    merge_equivalents_crystfel_wrappers::wrap();
  }

}}}} // namespace yamtbx::dataproc::crystfel::boost_python
<|endoftext|>