<commit_before>/*
  This file is part of the Ofi Labs X2 project.

  Copyright (C) 2010 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "kineticmodel.h"

#include <QtCore/QTimer>
#include <QtCore/QDateTime>

static const int KineticModelDefaultUpdateInterval = 15; // ms

class KineticModelPrivate
{
public:
    QTimer ticker;

    int duration;
    QPointF position;
    QPointF velocity;
    QPointF deacceleration;

    QTime timestamp;
    QPointF lastPosition;

    KineticModelPrivate();
};

KineticModelPrivate::KineticModelPrivate()
    : duration(1403)
    , position(0, 0)
    , velocity(0, 0)
    , deacceleration(0, 0)
    , lastPosition(0, 0)
{

}

KineticModel::KineticModel(QObject *parent)
    : QObject(parent)
    , d_ptr(new KineticModelPrivate)
{
    connect(&d_ptr->ticker, SIGNAL(timeout()), SLOT(update()));
    d_ptr->ticker.setInterval(KineticModelDefaultUpdateInterval);
}

KineticModel::~KineticModel()
{

}

int KineticModel::duration() const
{
    return d_ptr->duration;
}

void KineticModel::setDuration(int ms)
{
    d_ptr->duration = ms;
}

QPointF KineticModel::position() const
{
    return d_ptr->position;
}

void KineticModel::setPosition(QPointF position)
{
    setPosition( position.x(), position.y() );
}

void KineticModel::setPosition(qreal posX, qreal posY)
{
    d_ptr->position.setX( posX );
    d_ptr->position.setY( posY );

    int elapsed = d_ptr->timestamp.elapsed();

    // too fast gives less accuracy
    if (elapsed < d_ptr->ticker.interval() / 2) {
        return;
    }

    qreal delta = static_cast<qreal>( elapsed ) / 1000.0;

    QPointF lastSpeed = d_ptr->velocity;
    QPointF currentSpeed = ( d_ptr->position - d_ptr->lastPosition ) / delta;
    d_ptr->velocity = 0.2 * lastSpeed + 0.8 * currentSpeed;
    d_ptr->lastPosition = d_ptr->position;

    d_ptr->timestamp.start();
}

int KineticModel::updateInterval() const
{
    return d_ptr->ticker.interval();
}

void KineticModel::setUpdateInterval(int ms)
{
    d_ptr->ticker.setInterval(ms);
}

void KineticModel::resetSpeed()
{
    Q_D(KineticModel);

    d->ticker.stop();
    d->lastPosition = d->position;
    d->timestamp.start();
    d->velocity = QPointF(0, 0);
}

void KineticModel::release()
{
    Q_D(KineticModel);

    d->deacceleration = d->velocity * 1000 / ( 1 + d_ptr->duration );
    if (d->deacceleration.x() < 0) {
        d->deacceleration.setX( -d->deacceleration.x() );
    }
    if (d->deacceleration.y() < 0) {
        d->deacceleration.setY( -d->deacceleration.y() );
    }

    if (d->deacceleration.x() > 0.0005 || d->deacceleration.y() > 0.0005) {
        if (!d->ticker.isActive())
            d->ticker.start();
        update();
    } else {
        d->ticker.stop();
        emit finished();
    }
}

void KineticModel::update()
{
    Q_D(KineticModel);

    int elapsed = d->timestamp.elapsed();
    qreal delta = static_cast<qreal>(elapsed) / 1000.0;

    d->position += d->velocity * delta;
    QPointF vstep = d->deacceleration * delta;

    if (d->velocity.x() < vstep.x() && d->velocity.x() >= -vstep.x()) {
        d->velocity.setX( 0 );
    } else {
        if (d->velocity.x() > 0)
            d->velocity.setX( d->velocity.x() - vstep.x() );
        else
            d->velocity.setX( d->velocity.x() + vstep.x() );
    }

    if (d->velocity.y() < vstep.y() && d->velocity.y() >= -vstep.y()) {
        d->velocity.setY( 0 );
    } else {
        if (d->velocity.y() > 0)
            d->velocity.setY( d->velocity.y() - vstep.y() );
        else
            d->velocity.setY( d->velocity.y() + vstep.y() );
    }

    emit positionChanged( d->position.x(), d->position.y() );

    if (d->velocity.isNull()) {
        emit finished();
        d->ticker.stop();
    }

    d->timestamp.start();
}

#include "kineticmodel.moc"

<commit_msg>do not start kinetic spinning if the last sample is too long ago<commit_after>/*
  This file is part of the Ofi Labs X2 project.

  Copyright (C) 2010 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "kineticmodel.h"

#include <QtCore/QTimer>
#include <QtCore/QDateTime>

static const int KineticModelDefaultUpdateInterval = 15; // ms

class KineticModelPrivate
{
public:
    QTimer ticker;

    int duration;
    QPointF position;
    QPointF velocity;
    QPointF deacceleration;

    QTime timestamp;
    QPointF lastPosition;

    KineticModelPrivate();
};

KineticModelPrivate::KineticModelPrivate()
    : duration(1403)
    , position(0, 0)
    , velocity(0, 0)
    , deacceleration(0, 0)
    , lastPosition(0, 0)
{

}

KineticModel::KineticModel(QObject *parent)
    : QObject(parent)
    , d_ptr(new KineticModelPrivate)
{
    connect(&d_ptr->ticker, SIGNAL(timeout()), SLOT(update()));
    d_ptr->ticker.setInterval(KineticModelDefaultUpdateInterval);
}

KineticModel::~KineticModel()
{

}

int KineticModel::duration() const
{
    return d_ptr->duration;
}

void KineticModel::setDuration(int ms)
{
    d_ptr->duration = ms;
}

QPointF KineticModel::position() const
{
    return d_ptr->position;
}

void KineticModel::setPosition(QPointF position)
{
    setPosition( position.x(), position.y() );
}

void KineticModel::setPosition(qreal posX, qreal posY)
{
    d_ptr->position.setX( posX );
    d_ptr->position.setY( posY );

    int elapsed = d_ptr->timestamp.elapsed();

    // too fast gives less accuracy
    if (elapsed < d_ptr->ticker.interval() / 2) {
        return;
    }

    qreal delta = static_cast<qreal>( elapsed ) / 1000.0;

    QPointF lastSpeed = d_ptr->velocity;
    QPointF currentSpeed = ( d_ptr->position - d_ptr->lastPosition ) / delta;
    d_ptr->velocity = 0.2 * lastSpeed + 0.8 * currentSpeed;
    d_ptr->lastPosition = d_ptr->position;

    d_ptr->timestamp.start();
}

int KineticModel::updateInterval() const
{
    return d_ptr->ticker.interval();
}

void KineticModel::setUpdateInterval(int ms)
{
    d_ptr->ticker.setInterval(ms);
}

void KineticModel::resetSpeed()
{
    Q_D(KineticModel);

    d->ticker.stop();
    d->lastPosition = d->position;
    d->timestamp.start();
    d->velocity = QPointF(0, 0);
}

void KineticModel::release()
{
    Q_D(KineticModel);

    // prevent kinetic spinning if last mouse move is too long ago
    const int elapsed = d->timestamp.elapsed();
    if ( elapsed > 2 * d->ticker.interval() ) {
        d->ticker.stop();
        emit finished();
        return;
    }

    d->deacceleration = d->velocity * 1000 / ( 1 + d_ptr->duration );
    if (d->deacceleration.x() < 0) {
        d->deacceleration.setX( -d->deacceleration.x() );
    }
    if (d->deacceleration.y() < 0) {
        d->deacceleration.setY( -d->deacceleration.y() );
    }

    if (!d->ticker.isActive())
        d->ticker.start();
}

void KineticModel::update()
{
    Q_D(KineticModel);

    int elapsed = d->timestamp.elapsed();
    qreal delta = static_cast<qreal>(elapsed) / 1000.0;

    d->position += d->velocity * delta;
    QPointF vstep = d->deacceleration * delta;

    if (d->velocity.x() < vstep.x() && d->velocity.x() >= -vstep.x()) {
        d->velocity.setX( 0 );
    } else {
        if (d->velocity.x() > 0)
            d->velocity.setX( d->velocity.x() - vstep.x() );
        else
            d->velocity.setX( d->velocity.x() + vstep.x() );
    }

    if (d->velocity.y() < vstep.y() && d->velocity.y() >= -vstep.y()) {
        d->velocity.setY( 0 );
    } else {
        if (d->velocity.y() > 0)
            d->velocity.setY( d->velocity.y() - vstep.y() );
        else
            d->velocity.setY( d->velocity.y() + vstep.y() );
    }

    emit positionChanged( d->position.x(), d->position.y() );

    if (d->velocity.isNull()) {
        emit finished();
        d->ticker.stop();
    }

    d->timestamp.start();
}

#include "kineticmodel.moc"

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* libcdr
 * Version: MPL 1.1 / GPLv2+ / LGPLv2+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch>
 * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com>
 *
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPLv2+"), or
 * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
 * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable
 * instead of those above.
 */

#include "libcdr_utils.h"

#define CDR_NUM_ELEMENTS(array) sizeof(array)/sizeof(array[0])

uint8_t libcdr::readU8(WPXInputStream *input, bool /* bigEndian */)
{
  if (!input || input->atEOS())
  {
    CDR_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint8_t))
    return *(uint8_t const *)(p);
  throw EndOfStreamException();
}

uint16_t libcdr::readU16(WPXInputStream *input, bool bigEndian)
{
  uint16_t p0 = (uint16_t)readU8(input);
  uint16_t p1 = (uint16_t)readU8(input);
  if (bigEndian)
    return (uint16_t)(p1|(p0<<8));
  return (uint16_t)(p0|(p1<<8));
}

uint32_t libcdr::readU32(WPXInputStream *input, bool bigEndian)
{
  uint32_t p0 = (uint32_t)readU8(input);
  uint32_t p1 = (uint32_t)readU8(input);
  uint32_t p2 = (uint32_t)readU8(input);
  uint32_t p3 = (uint32_t)readU8(input);
  if (bigEndian)
    return (uint32_t)(p3|(p2<<8)|(p1<<16)|(p0<<24));
  return (uint32_t)(p0|(p1<<8)|(p2<<16)|(p3<<24));
}

int32_t libcdr::readS32(WPXInputStream *input, bool bigEndian)
{
  return (int32_t)readU32(input, bigEndian);
}

uint64_t libcdr::readU64(WPXInputStream *input, bool bigEndian)
{
  uint64_t p0 = (uint64_t)readU8(input);
  uint64_t p1 = (uint64_t)readU8(input);
  uint64_t p2 = (uint64_t)readU8(input);
  uint64_t p3 = (uint64_t)readU8(input);
  uint64_t p4 = (uint64_t)readU8(input);
  uint64_t p5 = (uint64_t)readU8(input);
  uint64_t p6 = (uint64_t)readU8(input);
  uint64_t p7 = (uint64_t)readU8(input);
  if (bigEndian)
    return (uint64_t)(p7|(p6<<8)|(p5<<16)|(p4<<24)|(p3<<32)|(p2<<40)|(p1<<48)|(p0<<56));
  return (uint64_t)(p0|(p1<<8)|(p2<<16)|(p3<<24)|(p4<<32)|(p5<<40)|(p6<<48)|(p7<<56));
}

double libcdr::readDouble(WPXInputStream *input, bool bigEndian)
{
  union
  {
    uint64_t u;
    double d;
  } tmpUnion;

  tmpUnion.u = readU64(input, bigEndian);

  return tmpUnion.d;
}

#ifdef DEBUG
const char *libcdr::toFourCC(unsigned value)
{
  static char sValue[5] = { 0, 0, 0, 0, 0 };
  sValue[0] = value & 0xff;
  sValue[1] = (value & 0xff00) >> 8;
  sValue[2] = (value & 0xff0000) >> 16;
  sValue[3] = (value & 0xff000000) >> 24;
  return sValue;
}
#endif

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>Read longer integers in one run<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* libcdr
 * Version: MPL 1.1 / GPLv2+ / LGPLv2+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch>
 * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com>
 *
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPLv2+"), or
 * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
 * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable
 * instead of those above.
 */

#include "libcdr_utils.h"

#define CDR_NUM_ELEMENTS(array) sizeof(array)/sizeof(array[0])

uint8_t libcdr::readU8(WPXInputStream *input, bool /* bigEndian */)
{
  if (!input || input->atEOS())
  {
    CDR_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint8_t))
    return *(uint8_t const *)(p);
  CDR_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

uint16_t libcdr::readU16(WPXInputStream *input, bool bigEndian)
{
  if (!input || input->atEOS())
  {
    CDR_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint16_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint16_t))
  {
    if (bigEndian)
      return (uint16_t)p[1]|((uint16_t)p[0]<<8);
    return (uint16_t)p[0]|((uint16_t)p[1]<<8);
  }
  CDR_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

uint32_t libcdr::readU32(WPXInputStream *input, bool bigEndian)
{
  if (!input || input->atEOS())
  {
    CDR_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint32_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint32_t))
  {
    if (bigEndian)
      return (uint32_t)p[3]|((uint32_t)p[2]<<8)|((uint32_t)p[1]<<16)|((uint32_t)p[0]<<24);
    return (uint32_t)p[0]|((uint32_t)p[1]<<8)|((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24);
  }
  CDR_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

int32_t libcdr::readS32(WPXInputStream *input, bool bigEndian)
{
  return (int32_t)readU32(input, bigEndian);
}

uint64_t libcdr::readU64(WPXInputStream *input, bool bigEndian)
{
  if (!input || input->atEOS())
  {
    CDR_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint64_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint64_t))
  {
    if (bigEndian)
      return (uint64_t)p[7]|((uint64_t)p[6]<<8)|((uint64_t)p[5]<<16)|((uint64_t)p[4]<<24)|((uint64_t)p[3]<<32)|((uint64_t)p[2]<<40)|((uint64_t)p[1]<<48)|((uint64_t)p[0]<<56);
    return (uint64_t)p[0]|((uint64_t)p[1]<<8)|((uint64_t)p[2]<<16)|((uint64_t)p[3]<<24)|((uint64_t)p[4]<<32)|((uint64_t)p[5]<<40)|((uint64_t)p[6]<<48)|((uint64_t)p[7]<<56);
  }
  CDR_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

double libcdr::readDouble(WPXInputStream *input, bool bigEndian)
{
  union
  {
    uint64_t u;
    double d;
  } tmpUnion;

  tmpUnion.u = readU64(input, bigEndian);

  return tmpUnion.d;
}

#ifdef DEBUG
const char *libcdr::toFourCC(unsigned value)
{
  static char sValue[5] = { 0, 0, 0, 0, 0 };
  sValue[0] = value & 0xff;
  sValue[1] = (value & 0xff00) >> 8;
  sValue[2] = (value & 0xff0000) >> 16;
  sValue[3] = (value & 0xff000000) >> 24;
  return sValue;
}
#endif

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>


<commit_before>/** \file
 * Implements zero-cost abstractions for the getenv(3) facilities.
 */

#ifndef _POWERDXX_SYS_ENV_HPP_
#define _POWERDXX_SYS_ENV_HPP_

#include "error.hpp"    /* sys::sc_error */

#include <cstdlib>      /* getenv(), setenv() etc. */

namespace sys {

/**
 * Provides wrappers around the getenv() family of functions.
 */
namespace env {

/**
 * The domain error type.
 */
struct error {};

/**
 * A reference type refering to an environment variable.
 *
 * To avoid issues with the lifetime of the name string this is not
 * copy constructible or assignable.
 */
class Var {
	private:
	/**
	 * A pointer to the variable name.
	 */
	char const * const name;

	public:
	/**
	 * Construct an environment variable reference.
	 *
	 * @tparam Size
	 *	The size of the name buffer
	 * @param name
	 *	The name of the environment variable
	 */
	template <size_t Size>
	Var(char const (& name)[Size]) : name{name} {}

	/**
	 * Do not permit copy construction.
	 */
	Var(Var const &) = delete;

	/**
	 * Do not permit copy assignment.
	 */
	Var & operator =(Var const &) = delete;

	/**
	 * Retrieve the value of the environment variable.
	 *
	 * @return
	 *	A pointer to the character array with the variable value
	 * @retval nullptr
	 *	The variable does not exist
	 */
	operator char const *() const {
		return getenv(this->name);
	}

	/**
	 * Assign a new value to the environment variable.
	 *
	 * Deletes the variable if nullptr is assigned.
	 *
	 * @param assign
	 *	The new value
	 * @return
	 *	A self-reference
	 * @throws sc_error<error>{EINVAL}
	 *	Invalid variable name
	 * @throws sc_error<error>{ENOMEM}
	 *	Failed to allocate memory when updating the environment
	 */
	Var & operator =(char const * const assign) {
		auto const result =
		    assign
		    ? setenv(this->name, assign, 1)
		    : unsetenv(this->name);
		if (0 != result) {
			throw sc_error<error>{errno};
		}
		return *this;
	}

	/**
	 * Explicitly deletes the environment variable.
	 *
	 * @return
	 *	A self-reference
	 * @throws sc_error<error>{EINVAL}
	 *	Invalid variable name
	 * @throws sc_error<error>{ENOMEM}
	 *	Failed to allocate memory when updating the environment
	 */
	Var & erase() {
		return *this = nullptr;
	}

	/**
	 * Explicitly retrieve the value as a character array.
	 *
	 * @return
	 *	A pointer to the character array with the variable value
	 * @retval nullptr
	 *	The variable does not exist
	 */
	char const * c_str() const {
		return *this;
	}

	/**
	 * Explicitly retrieve the value as a std::string.
	 *
	 * Returns an empty string if the variable does not exist.
	 * Use c_str() to distinguish between an empty string and
	 * an inexistant variable.
	 *
	 * @return
	 *	A string containing the variable value
	 */
	std::string str() const {
		auto const result = c_str();
		return {result ? result : ""};
	}
};

/**
 * A singleton class providing access to environment variables.
 */
struct Vars {
	/**
	 * Access environment variable by name.
	 *
	 * @tparam T
	 *	The name argument type
	 * @param name
	 *	The name of the variable by reference
	 */
	template <typename T>
	Var const operator [](T const & name) const {
		return {name};
	}

	/**
	 * Access environment variable by name.
	 *
	 * @tparam T
	 *	The name argument type
	 * @param name
	 *	The name of the variable by reference
	 */
	template <typename T>
	Var operator [](T const & name) {
		return {name};
	}
} vars; /**< Singleton providing access to environment variables. */

} /* namespace env */

} /* namespace sys */

#endif /* _POWERDXX_SYS_ENV_HPP_ */
<commit_msg>Remove obsolete method<commit_after>/** \file
 * Implements zero-cost abstractions for the getenv(3) facilities.
 */

#ifndef _POWERDXX_SYS_ENV_HPP_
#define _POWERDXX_SYS_ENV_HPP_

#include "error.hpp"    /* sys::sc_error */

#include <cstdlib>      /* getenv(), setenv() etc. */

namespace sys {

/**
 * Provides wrappers around the getenv() family of functions.
 */
namespace env {

/**
 * The domain error type.
 */
struct error {};

/**
 * A reference type refering to an environment variable.
 *
 * To avoid issues with the lifetime of the name string this is not
 * copy constructible or assignable.
 */
class Var {
	private:
	/**
	 * A pointer to the variable name.
	 */
	char const * const name;

	public:
	/**
	 * Construct an environment variable reference.
	 *
	 * @tparam Size
	 *	The size of the name buffer
	 * @param name
	 *	The name of the environment variable
	 */
	template <size_t Size>
	Var(char const (& name)[Size]) : name{name} {}

	/**
	 * Do not permit copy construction.
	 */
	Var(Var const &) = delete;

	/**
	 * Do not permit copy assignment.
	 */
	Var & operator =(Var const &) = delete;

	/**
	 * Retrieve the value of the environment variable.
	 *
	 * @return
	 *	A pointer to the character array with the variable value
	 * @retval nullptr
	 *	The variable does not exist
	 */
	operator char const *() const {
		return getenv(this->name);
	}

	/**
	 * Assign a new value to the environment variable.
	 *
	 * Deletes the variable if nullptr is assigned.
	 *
	 * @param assign
	 *	The new value
	 * @return
	 *	A self-reference
	 * @throws sc_error<error>{EINVAL}
	 *	Invalid variable name
	 * @throws sc_error<error>{ENOMEM}
	 *	Failed to allocate memory when updating the environment
	 */
	Var & operator =(char const * const assign) {
		auto const result =
		    assign
		    ? setenv(this->name, assign, 1)
		    : unsetenv(this->name);
		if (0 != result) {
			throw sc_error<error>{errno};
		}
		return *this;
	}

	/**
	 * Explicitly deletes the environment variable.
	 *
	 * @return
	 *	A self-reference
	 * @throws sc_error<error>{EINVAL}
	 *	Invalid variable name
	 * @throws sc_error<error>{ENOMEM}
	 *	Failed to allocate memory when updating the environment
	 */
	Var & erase() {
		return *this = nullptr;
	}

	/**
	 * Explicitly retrieve the value as a character array.
	 *
	 * @return
	 *	A pointer to the character array with the variable value
	 * @retval nullptr
	 *	The variable does not exist
	 */
	char const * c_str() const {
		return *this;
	}
};

/**
 * A singleton class providing access to environment variables.
 */
struct Vars {
	/**
	 * Access environment variable by name.
	 *
	 * @tparam T
	 *	The name argument type
	 * @param name
	 *	The name of the variable by reference
	 */
	template <typename T>
	Var const operator [](T const & name) const {
		return {name};
	}

	/**
	 * Access environment variable by name.
	 *
	 * @tparam T
	 *	The name argument type
	 * @param name
	 *	The name of the variable by reference
	 */
	template <typename T>
	Var operator [](T const & name) {
		return {name};
	}
} vars; /**< Singleton providing access to environment variables. */

} /* namespace env */

} /* namespace sys */

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


<commit_before>#include "attributes.h"
#include "ui_attributes.h"

Attributes::Attributes(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Attributes)
{
    ui->setupUi(this);
}

Attributes::~Attributes()
{
    delete ui;
}

void Attributes::setPlayer(Player player) {
    this->player = player;
    ui->nameLabel->setText(this->player.getName());
}
<commit_msg>Delete attributes.cpp<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <fs/vfs.hpp>
#include <common.cxx>

using namespace std::string_literals;

extern lest::tests & specification();

class Person {
public:
  explicit Person(std::string name, int age) : name_ {name}, age_ {age} {};
  bool isBjarne() const { return (name_ == "Bjarne") ? true : false; }
private:
  std::string name_;
  int age_;
};

CASE("VFS entries can have names")
{
  fs::VFS_entry e("entry", "description");
  EXPECT(e.name() == "entry");
}

CASE("VFS entries can have descriptions")
{
  fs::VFS_entry e("entry", "description");
  EXPECT(e.desc() == "description");
}

CASE("VFS entries can return type info as string")
{
  fs::VFS_entry e("entry", "description");
  auto info {e.type_name()};
  EXPECT(info.length() > 0);
  EXPECT(info == "decltype(nullptr)");
}

CASE("VFS entries can return their number of children")
{
  fs::VFS_entry e("entry", "description");
  EXPECT(e.child_count() == 0);
}

CASE("VFS entries can contain arbitrary objects")
{
  Person p {"Bjarne", 65};
  fs::VFS_entry e(p, "creator", "duh");
  auto info = e.type_name();
  EXPECT(info != "decltype(nullptr)");
  EXPECT(info == "Person");
  Person bjarne = e.obj<Person>();
  EXPECT(bjarne.isBjarne() == true);
  EXPECT_THROWS(e.obj<std::string>());
}

CASE("VFS can mount entries in a tree")
{
  // tree is initially empty
  EXPECT(fs::VFS::root().child_count() == 0);

  // mount a char
  char a {'a'};
  fs::mount("/mnt/chars/a", a, "the letter a");
  EXPECT(fs::VFS::root().child_count() == 1);

  // cannot mount if already occupied
  char b {'b'};
  EXPECT_THROWS(fs::mount("/mnt/chars/a", b, "the letter b"));
  EXPECT_NO_THROW(fs::mount("/mnt/chars/b", b, "the letter c"));

  // mount another
  char c {'c'};
  EXPECT_NO_THROW(fs::mount("/mnt/chars/c", c, "the letter c"));
}
<commit_msg>test: added missing license header to vfs unit test<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <iostream>
#include <fs/vfs.hpp>
#include <common.cxx>

using namespace std::string_literals;

extern lest::tests & specification();

class Person {
public:
  explicit Person(std::string name, int age) : name_ {name}, age_ {age} {};
  bool isBjarne() const { return (name_ == "Bjarne") ? true : false; }
private:
  std::string name_;
  int age_;
};

CASE("VFS entries can have names")
{
  fs::VFS_entry e("entry", "description");
  EXPECT(e.name() == "entry");
}

CASE("VFS entries can have descriptions")
{
  fs::VFS_entry e("entry", "description");
  EXPECT(e.desc() == "description");
}

CASE("VFS entries can return type info as string")
{
  fs::VFS_entry e("entry", "description");
  auto info {e.type_name()};
  EXPECT(info.length() > 0);
  EXPECT(info == "decltype(nullptr)");
}

CASE("VFS entries can return their number of children")
{
  fs::VFS_entry e("entry", "description");
  EXPECT(e.child_count() == 0);
}

CASE("VFS entries can contain arbitrary objects")
{
  Person p {"Bjarne", 65};
  fs::VFS_entry e(p, "creator", "duh");
  auto info = e.type_name();
  EXPECT(info != "decltype(nullptr)");
  EXPECT(info == "Person");
  Person bjarne = e.obj<Person>();
  EXPECT(bjarne.isBjarne() == true);
  EXPECT_THROWS(e.obj<std::string>());
}

CASE("VFS can mount entries in a tree")
{
  // tree is initially empty
  EXPECT(fs::VFS::root().child_count() == 0);

  // mount a char
  char a {'a'};
  fs::mount("/mnt/chars/a", a, "the letter a");
  EXPECT(fs::VFS::root().child_count() == 1);

  // cannot mount if already occupied
  char b {'b'};
  EXPECT_THROWS(fs::mount("/mnt/chars/a", b, "the letter b"));
  EXPECT_NO_THROW(fs::mount("/mnt/chars/b", b, "the letter c"));

  // mount another
  char c {'c'};
  EXPECT_NO_THROW(fs::mount("/mnt/chars/c", c, "the letter c"));
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680)
#define XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <XercesPlatformSupport/XercesPlatformSupportDefinitions.hpp>

#include <cstdio>
#include <vector>

// Base class header file.
#include <PlatformSupport/TextOutputStream.hpp>

#include <XercesPlatformSupport/XercesPlatformSupportException.hpp>

// A base class for all text output streams.
class XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStream : public TextOutputStream
{
public :

    virtual
	~XercesTextOutputStream();

	// These interfaces are inherited from TextOutputStream...

    virtual void
	flush();

    virtual void
	write(char	theChar);

    virtual void
	write(XalanDOMChar	theChar);

    virtual void
	write(const char*	theBuffer);

    virtual void
	write(const XalanDOMChar*	theBuffer);

    virtual void
	write(
			const char*		theBuffer,
			unsigned long	theBufferLength);

    virtual void
	write(
			const XalanDOMChar*		theBuffer,
			unsigned long			theBufferLength);

	enum
	{
		eDefaultBufferSize = 512
	};

	typedef std::vector<XalanDOMChar>	BufferType;

	virtual void
	setBufferSize(BufferType::size_type		theBufferSize);

protected:

	explicit
    XercesTextOutputStream(BufferType::size_type	theBufferSize = eDefaultBufferSize);

	virtual void
	writeData(const char*		theBuffer,
			  unsigned long		theBufferLength) = 0;

	virtual void
	doFlush() = 0;

private:

    // These are not implemented...
    XercesTextOutputStream(const XercesTextOutputStream&);

    XercesTextOutputStream&
	operator=(const XercesTextOutputStream&);

	// Utility functions...
	void
	flushBuffer();

	void
	doWrite(const XalanDOMChar*		theBuffer);

	BufferType				m_buffer;

	BufferType::size_type	m_bufferSize;
};

class XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStreamException : public XercesPlatformSupportException
{
public:

	virtual
	~XercesTextOutputStreamException();

protected:

	XercesTextOutputStreamException(
		const DOMString&	theMessage,
		const DOMString&	theType);
};

#endif	// TEXTFILEOUTPUTSTREAM_HEADER_GUARD_1357924680
<commit_msg>Added comment.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680)
#define XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <XercesPlatformSupport/XercesPlatformSupportDefinitions.hpp>

#include <cstdio>
#include <vector>

// Base class header file.
#include <PlatformSupport/TextOutputStream.hpp>

#include <XercesPlatformSupport/XercesPlatformSupportException.hpp>

// A base class for all text output streams.
class XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStream : public TextOutputStream
{
public :

    virtual
	~XercesTextOutputStream();

	// These interfaces are inherited from TextOutputStream...

    virtual void
	flush();

    virtual void
	write(char	theChar);

    virtual void
	write(XalanDOMChar	theChar);

    virtual void
	write(const char*	theBuffer);

    virtual void
	write(const XalanDOMChar*	theBuffer);

    virtual void
	write(
			const char*		theBuffer,
			unsigned long	theBufferLength);

    virtual void
	write(
			const XalanDOMChar*		theBuffer,
			unsigned long			theBufferLength);

	enum
	{
		eDefaultBufferSize = 512
	};

	typedef std::vector<XalanDOMChar>	BufferType;

	virtual void
	setBufferSize(BufferType::size_type		theBufferSize);

protected:

	/**
	 * Constructor.
	 *
	 * @param theBufferSize The initial size of the buffer.
	 */
	explicit
    XercesTextOutputStream(BufferType::size_type	theBufferSize = eDefaultBufferSize);

	virtual void
	writeData(const char*		theBuffer,
			  unsigned long		theBufferLength) = 0;

	virtual void
	doFlush() = 0;

private:

    // These are not implemented...
    XercesTextOutputStream(const XercesTextOutputStream&);

    XercesTextOutputStream&
	operator=(const XercesTextOutputStream&);

	// Utility functions...
	void
	flushBuffer();

	void
	doWrite(const XalanDOMChar*		theBuffer);

	BufferType				m_buffer;

	BufferType::size_type	m_bufferSize;
};

class XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStreamException : public XercesPlatformSupportException
{
public:

	virtual
	~XercesTextOutputStreamException();

protected:

	XercesTextOutputStreamException(
		const DOMString&	theMessage,
		const DOMString&	theType);
};

#endif	// TEXTFILEOUTPUTSTREAM_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/searchlib/bitcompression/compression.h>
#include <vespa/searchlib/bitcompression/countcompression.h>
#include <vespa/searchlib/bitcompression/pagedict4.h>
#include <vespa/searchlib/test/diskindex/threelevelcountbuffers.h>
#include <vespa/searchlib/test/diskindex/pagedict4_mem_writer.h>
#include <vespa/searchlib/test/diskindex/pagedict4_mem_seq_reader.h>
#include <vespa/searchlib/index/postinglistcounts.h>

#include <vespa/log/log.h>
LOG_SETUP("pagedict4_hugeword_cornercase_test");

using search::index::PostingListCounts;
using search::ComprFileWriteContext;

constexpr uint32_t minChunkDocs = 262144;
constexpr uint32_t numWordIds = 65536;

struct BitBuffer
{
    using EC = search::bitcompression::PostingListCountFileEncodeContext;

    EC e;
    ComprFileWriteContext wc;

    BitBuffer()
        : e(),
          wc(e)
    {
        e._minChunkDocs = minChunkDocs;
        e._numWordIds = numWordIds;
        wc.allocComprBuf();
        e.setWriteContext(&wc);
        e.setupWrite(wc);
        assert(e.getWriteOffset() == 0);
    }

    void clear() { e.setupWrite(wc); }

    uint64_t getSize(const PostingListCounts &counts)
    {
        clear();
        e.writeCounts(counts);
        return e.getWriteOffset();
    }

    ~BitBuffer() = default;
};

void addSegment(PostingListCounts &counts)
{
    PostingListCounts::Segment lastseg = counts._segments.back();
    PostingListCounts::Segment fillseg;
    fillseg._bitLength = 4000000;
    fillseg._numDocs = minChunkDocs;
    fillseg._lastDoc = minChunkDocs;
    counts._bitLength += fillseg._bitLength;
    counts._numDocs += fillseg._numDocs;
    counts._segments.back() = fillseg;
    uint32_t lastDoc = counts._segments.size() * fillseg._numDocs;
    counts._segments.back()._lastDoc = lastDoc;
    counts._segments.push_back(lastseg);
    counts._segments.back()._lastDoc = lastDoc + lastseg._numDocs;
}

PostingListCounts makeBaseCounts()
{
    PostingListCounts counts;
    PostingListCounts::Segment lastseg;
    lastseg._bitLength = 100;
    lastseg._numDocs = 10;
    lastseg._lastDoc = 10;
    counts._bitLength = lastseg._bitLength;
    counts._numDocs = lastseg._numDocs;
    counts._segments.push_back(lastseg);
    addSegment(counts);
    return counts;
}

PostingListCounts makeSegmentedCounts(uint32_t segments)
{
    PostingListCounts counts = makeBaseCounts();
    while (counts._segments.size() < segments) {
        addSegment(counts);
    }
    return counts;
}

uint32_t
calcSegments(uint32_t maxLen)
{
    BitBuffer bb;
    PostingListCounts counts = makeBaseCounts();
    uint32_t len = bb.getSize(counts);
    unsigned int i = 0;
    while (len <= maxLen) {
        addSegment(counts);
        ++i;
        len = bb.getSize(counts);
    }
    return counts._segments.size() - 1;
}

PostingListCounts makeCounts(uint32_t wantLen)
{
    BitBuffer bb;
    uint32_t segments = calcSegments(wantLen);
    PostingListCounts counts = makeSegmentedCounts(segments);
    PostingListCounts counts2 = makeSegmentedCounts(segments - 1);
    uint32_t len = bb.getSize(counts);
    uint32_t len2 = bb.getSize(counts2);
    for (unsigned int i = 1; i + 2 < counts._segments.size(); ++i) {
        counts._bitLength += counts._segments[0]._bitLength;
        counts._segments[i]._bitLength += counts._segments[0]._bitLength;
        counts2._bitLength += counts2._segments[0]._bitLength;
        counts2._segments[i]._bitLength += counts2._segments[0]._bitLength;
        len = bb.getSize(counts);
        len2 = bb.getSize(counts2);
        if (len == wantLen) {
            return counts;
        }
        if (len2 == wantLen) {
            return counts2;
        }
    }
    LOG(info, "Could not calculate counts with wanted compressed length");
    abort();
}

using StartOffset = search::bitcompression::PageDict4StartOffset;
using Writer = search::diskindex::test::PageDict4MemWriter;
using SeqReader = search::diskindex::test::PageDict4MemSeqReader;

void testPageSizedCounts()
{
    uint32_t pageBitSize = 32768;
    uint32_t startBits = 15 * 3 + 12;

    uint32_t ssPad = 64;
    uint32_t spPad = 64;
    uint32_t pPad = 64;
    Writer w(minChunkDocs, numWordIds, ssPad, spPad, pPad);
    PostingListCounts baseCounts = makeBaseCounts();
    PostingListCounts largeCounts = makeCounts(pageBitSize - startBits);
    w.addCounts("a", baseCounts);
    w.addCounts("b", baseCounts);
    w.addCounts("c", largeCounts);
    w.addCounts("d", baseCounts);
    w.addCounts("e", baseCounts);
    w.flush();

    SeqReader r(minChunkDocs, numWordIds, w._buffers);

    uint64_t checkWordNum = 0;
    PostingListCounts counts;
    for (uint64_t wordNum = 1; wordNum < 7; ++wordNum) {
        vespalib::string word;
        counts.clear();
        r.readCounts(word, checkWordNum, counts);
        if (wordNum < 6) {
            EXPECT_EQUAL(checkWordNum, wordNum);
            if (wordNum == 3) {
                EXPECT_TRUE(counts == largeCounts);
            } else {
                EXPECT_TRUE(counts == baseCounts);
            }
        } else {
            EXPECT_GREATER(checkWordNum, 100u);
        }
    }
}

TEST("require that counts exactly filling dictionary page works")
{
    testPageSizedCounts();
}

TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>Add comments. Use more descriptive variable names.<commit_after>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/searchlib/bitcompression/compression.h>
#include <vespa/searchlib/bitcompression/countcompression.h>
#include <vespa/searchlib/bitcompression/pagedict4.h>
#include <vespa/searchlib/test/diskindex/threelevelcountbuffers.h>
#include <vespa/searchlib/test/diskindex/pagedict4_mem_writer.h>
#include <vespa/searchlib/test/diskindex/pagedict4_mem_seq_reader.h>
#include <vespa/searchlib/index/postinglistcounts.h>

#include <vespa/log/log.h>
LOG_SETUP("pagedict4_hugeword_cornercase_test");

using search::index::PostingListCounts;
using search::ComprFileWriteContext;

constexpr uint32_t minChunkDocs = 262144;
constexpr uint32_t numWordIds = 65536;

struct BitBuffer
{
    using EC = search::bitcompression::PostingListCountFileEncodeContext;

    EC encodeCtx;
    ComprFileWriteContext writeCtx;

    BitBuffer()
        : encodeCtx(),
          writeCtx(encodeCtx)
    {
        encodeCtx._minChunkDocs = minChunkDocs;
        encodeCtx._numWordIds = numWordIds;
        writeCtx.allocComprBuf();
        encodeCtx.setWriteContext(&writeCtx);
        encodeCtx.setupWrite(writeCtx);
        assert(encodeCtx.getWriteOffset() == 0);
    }

    void clear() { encodeCtx.setupWrite(writeCtx); }

    uint64_t getSize(const PostingListCounts &counts)
    {
        clear();
        encodeCtx.writeCounts(counts);
        return encodeCtx.getWriteOffset();
    }

    ~BitBuffer() = default;
};

void addSegment(PostingListCounts &counts)
{
    PostingListCounts::Segment lastseg = counts._segments.back();
    PostingListCounts::Segment fillseg;
    fillseg._bitLength = 4000000;
    fillseg._numDocs = minChunkDocs;
    fillseg._lastDoc = minChunkDocs;
    counts._bitLength += fillseg._bitLength;
    counts._numDocs += fillseg._numDocs;
    counts._segments.back() = fillseg;
    uint32_t lastDoc = counts._segments.size() * fillseg._numDocs;
    counts._segments.back()._lastDoc = lastDoc;
    counts._segments.push_back(lastseg);
    counts._segments.back()._lastDoc = lastDoc + lastseg._numDocs;
}

PostingListCounts makeBaseCounts()
{
    PostingListCounts counts;
    PostingListCounts::Segment lastseg;
    lastseg._bitLength = 100;
    lastseg._numDocs = 10;
    lastseg._lastDoc = 10;
    counts._bitLength = lastseg._bitLength;
    counts._numDocs = lastseg._numDocs;
    counts._segments.push_back(lastseg);
    addSegment(counts);
    return counts;
}

PostingListCounts makeSegmentedCounts(uint32_t segments)
{
    PostingListCounts counts = makeBaseCounts();
    while (counts._segments.size() < segments) {
        addSegment(counts);
    }
    return counts;
}

uint32_t
calcSegments(uint32_t maxLen)
{
    BitBuffer bb;
    PostingListCounts counts = makeBaseCounts();
    uint32_t len = bb.getSize(counts);
    unsigned int i = 0;
    while (len <= maxLen) {
        addSegment(counts);
        ++i;
        len = bb.getSize(counts);
    }
    return counts._segments.size() - 1;
}

/*
 * Calculate posting list counts that compresses to wantLen bits.
 */
PostingListCounts makeCounts(uint32_t wantLen)
{
    BitBuffer bb;
    uint32_t segments = calcSegments(wantLen);
    PostingListCounts counts = makeSegmentedCounts(segments);
    PostingListCounts counts2 = makeSegmentedCounts(segments - 1);
    uint32_t len = bb.getSize(counts);
    uint32_t len2 = bb.getSize(counts2);
    for (uint32_t i = 1; i + 2 < counts._segments.size(); ++i) {
        counts._bitLength += counts._segments[0]._bitLength;
        counts._segments[i]._bitLength += counts._segments[0]._bitLength;
        counts2._bitLength += counts2._segments[0]._bitLength;
        counts2._segments[i]._bitLength += counts2._segments[0]._bitLength;
        len = bb.getSize(counts);
        len2 = bb.getSize(counts2);
        if (len == wantLen) {
            return counts;
        }
        if (len2 == wantLen) {
            return counts2;
        }
    }
    LOG(info, "Could not calculate counts with wanted compressed length");
    abort();
}

using StartOffset = search::bitcompression::PageDict4StartOffset;
using Writer = search::diskindex::test::PageDict4MemWriter;
using SeqReader = search::diskindex::test::PageDict4MemSeqReader;

/*
 * Test corner case where a dictionary page has a single word, and the
 * page header and compressed counts completely fills the page.
 */
void testPageSizedCounts()
{
    uint32_t pageBitSize = 32768;
    uint32_t startBits = 15 * 3 + 12;

    uint32_t ssPad = 64;
    uint32_t spPad = 64;
    uint32_t pPad = 64;
    Writer w(minChunkDocs, numWordIds, ssPad, spPad, pPad);
    PostingListCounts baseCounts = makeBaseCounts();
    PostingListCounts largeCounts = makeCounts(pageBitSize - startBits);
    w.addCounts("a", baseCounts);
    w.addCounts("b", baseCounts);
    w.addCounts("c", largeCounts);
    w.addCounts("d", baseCounts);
    w.addCounts("e", baseCounts);
    w.flush();

    SeqReader r(minChunkDocs, numWordIds, w._buffers);

    uint64_t checkWordNum = 0;
    PostingListCounts counts;
    for (uint64_t wordNum = 1; wordNum < 7; ++wordNum) {
        vespalib::string word;
        counts.clear();
        r.readCounts(word, checkWordNum, counts);
        if (wordNum < 6) {
            EXPECT_EQUAL(checkWordNum, wordNum);
            if (wordNum == 3) {
                EXPECT_TRUE(counts == largeCounts);
            } else {
                EXPECT_TRUE(counts == baseCounts);
            }
        } else {
            EXPECT_GREATER(checkWordNum, 100u);
        }
    }
}

TEST("require that counts exactly filling dictionary page works")
{
    testPageSizedCounts();
}

TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>


<commit_before>// FRAGMENT(main)
#include <iostream>
#include <seqan/align.h>

using namespace seqan;

int main()
{
	typedef String<Dna>			TSequence;	// sequence type
	typedef Align<TSequence,ArrayGaps>	TAlign;		// align type
	typedef Row<TAlign>::Type		TRow;
	typedef Iterator<TRow>::Type		TIterator;

// FRAGMENT(init)
	TSequence seq1 = "acgtacgtact";
	TSequence seq2 = "actactacgt";

	TAlign align;
	resize(rows(align), 2);
	assignSource(row(align,0),seq1);
	assignSource(row(align,1),seq2);

// FRAGMENT(alignment)
	int score = globalAlignment(align,Score<int>(1,-1,-1,-1), Hirschberg());
	::std::cout << "Score = " << score << ::std::endl;
	::std::cout << align;

//FRAGMENT(iterate)
	for(unsigned i = 0; i < length(rows(align)); ++i)
	{
		TIterator it = begin(row(align,i));
		TIterator itEnd = end(row(align,i));
		unsigned pos = 0;
		std::cout << "Row " << i << " contains gaps at positions: ";
		std::cout << std::endl;
		while (it != itEnd)
		{
			if(isGap(it))
 				std::cout << pos << std::endl;
			++it;
			++pos;
		}
	}

	return 0;
}
<commit_msg>Fixed for possible leading or trailing gaps.<commit_after>// FRAGMENT(main)
#include <iostream>
#include <seqan/align.h>

using namespace seqan;

int main()
{
	typedef String<Dna>			TSequence;	// sequence type
	typedef Align<TSequence,ArrayGaps>	TAlign;		// align type
	typedef Row<TAlign>::Type		TRow;
	typedef Iterator<TRow>::Type		TIterator;

// FRAGMENT(init)
	TSequence seq1 = "acgtacgtact";
	TSequence seq2 = "actactacgt";

	TAlign align;
	resize(rows(align), 2);
	assignSource(row(align,0),seq1);
	assignSource(row(align,1),seq2);

// FRAGMENT(alignment)
	int score = globalAlignment(align,Score<int>(1,-1,-1,-1), Hirschberg());
	::std::cout << "Score = " << score << ::std::endl;
	::std::cout << align;

//FRAGMENT(iterate)
	unsigned aliLength = _max(length(row(align, 0)), length(row(align, 1)));
	for(unsigned i = 0; i < length(rows(align)); ++i)
	{
		TIterator it = iter(row(align,i), 0);
		TIterator itEnd = iter(row(align,i), aliLength);
		unsigned pos = 0;
		std::cout << "Row " << i << " contains gaps at positions: ";
		std::cout << std::endl;
		while (it != itEnd)
		{
			if(isGap(it))
 				std::cout << pos << std::endl;
			++it;
			++pos;
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Shader.h"

using namespace ci;
using namespace ci::app;

class BasicApp : public App {
public:
    void draw() override;
};

void BasicApp::draw()
{
    gl::clear();

	gl::enableDepthRead();
	gl::enableDepthWrite();

	CameraPersp cam;
	cam.lookAt(vec3(3, 4.5, 4.5), vec3(0, 1, 0));
	gl::setMatrices(cam);

	auto lambert = gl::ShaderDef().lambert().color();
	auto shader = gl::getStockShader(lambert);
	shader->bind();

	int numSpheres = 64;
	float maxAngle = M_PI * 7;
	float spiralRadius = 1;
	float height = 3;
	float anim = getElapsedFrames() / 30.0f;

	for (int s = 0; s < numSpheres; ++s)
	{
		float rel = s / (float)numSpheres;
		float angle = rel * maxAngle;
		float y = fabs(cos(rel * M_PI + anim));
		float r = rel * spiralRadius;
		vec3 offset(r * cos(angle), y, r * sin(angle));

		gl::pushModelMatrix();
		gl::translate(offset);
		gl::scale(vec3(0.05f, y, 0.05f));
		gl::color(Color(CM_HSV, rel, 1, 1));
		gl::drawCube(vec3(), vec3(1));
		gl::popModelMatrix();
	}
}

CINDER_APP( BasicApp, RendererGl )
<commit_msg>Complete part 3<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Shader.h"
#include "cinder/Easing.h"

using namespace ci;
using namespace ci::app;

class BasicApp : public App {
public:
	void setup() override;
    void draw() override;

	static const int NUM_SLICES = 4;

	CameraPersp mCam;
	gl::BatchRef mSlices[NUM_SLICES];
};

void BasicApp::setup()
{
	auto lambert = gl::ShaderDef().lambert().color();
	gl::GlslProgRef shader = gl::getStockShader(lambert);

	for (int i = 0; i < NUM_SLICES; ++i)
	{
		float rel = i / (float)NUM_SLICES;
		float sliceHeight = 1.0f / NUM_SLICES;
		auto slice = geom::Cube().size(1, sliceHeight, 1);
		auto trans = geom::Translate(0, rel, 0);
		auto color = geom::Constant(
			geom::COLOR,
			Color(CM_HSV, rel, 1, 1));
		mSlices[i] = gl::Batch::create(slice >> trans >> color, shader);
	}

	mCam.lookAt(vec3(2, 3, 2), vec3(0, 0.5f, 0));
}

void BasicApp::draw()
{
    gl::clear();

	gl::enableDepthRead();
	gl::enableDepthWrite();

	gl::setMatrices(mCam);

	const float delay = 0.25f;
	const float rotationTime = 1.5f;
	const float rotationOffset = 0.1f;
	const float totalTime = delay + rotationTime + NUM_SLICES * rotationOffset;

	// loop every `totalTime` seconds
	float time = fmod(getElapsedFrames() / 30.0f, totalTime);

	for (int i = 0; i < NUM_SLICES; ++i)
	{
		// animates from 0 to 1
		float rotation = 0;

		// when does the slice begin rotating
		float startTime = i * rotationOffset;
		float endTime = startTime + rotationTime;
		if (time > startTime && time < endTime)
		{
			rotation = (time - startTime) / rotationTime;
		}

		float angle = easeInOutQuint(rotation) * M_PI / 2.0f;

		gl::ScopedModelMatrix scpModelMtx;
		gl::rotate(angleAxis(angle, vec3(0, 1, 0)));
		mSlices[i]->draw();
	}
}

CINDER_APP( BasicApp, RendererGl )
<|endoftext|>


<commit_before>// Copyright (c) 2019 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <fstream>
#include <iostream>
#include <sstream>
#include "lexer.h"
#include "lox.h"

namespace lox {

void Lox::eval(int argc, char* argv[]) {
  if (argc < 2) {
    eval_with_repl();
  }
  else if (argc == 2) {
    eval_with_file(argv[1]);
  }
  else {
    std::cerr << "USAGE: " << argv[0] << " {script}" << std::endl;
    std::exit(1);
  }
}

void Lox::eval_with_file(const std::string& fname) {
  std::ifstream fp(fname);
  if (fp.is_open()) {
    std::stringstream ss;
    ss << fp.rdbuf();

    run(ss.str(), fname);
  }
}

void Lox::eval_with_repl(void) {
  std::string line;
  for (;;) {
    std::cout << ">>> ";

    if (!std::getline(std::cin, line) || line == "exit") {
      break;
    }
    run(line);
  }
}

void Lox::run(const std::string& sources, const std::string& fname) {
  // std::cout << sources << std::endl;

  lox::Lexer lex(err_report_, sources, fname);

  const auto& tokens = lex.parse_tokens();
  if (err_report_.had_error())
    return;

  for (auto& tok : tokens)
    std::cout << tok << std::endl;
}

}
<commit_msg>:construction: chore(lox): add parser testing<commit_after>// Copyright (c) 2019 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <fstream>
#include <iostream>
#include <sstream>
#include "lexer.h"
#include "parser.h"
#include "ast_printer.h"
#include "lox.h"

namespace lox {

void Lox::eval(int argc, char* argv[]) {
  if (argc < 2) {
    eval_with_repl();
  }
  else if (argc == 2) {
    eval_with_file(argv[1]);
  }
  else {
    std::cerr << "USAGE: " << argv[0] << " {script}" << std::endl;
    std::exit(1);
  }
}

void Lox::eval_with_file(const std::string& fname) {
  std::ifstream fp(fname);
  if (fp.is_open()) {
    std::stringstream ss;
    ss << fp.rdbuf();

    run(ss.str(), fname);
  }
}

void Lox::eval_with_repl(void) {
  std::string line;
  for (;;) {
    std::cout << ">>> ";

    if (!std::getline(std::cin, line) || line == "exit") {
      break;
    }
    run(line);
  }
}

void Lox::run(const std::string& sources, const std::string& fname) {
  Lexer lex(err_report_, sources, fname);
  const auto& tokens = lex.parse_tokens();
  if (err_report_.had_error())
    std::abort();

  for (auto& tok : tokens)
    std::cout << tok << std::endl;

  Parser parser(err_report_, tokens);
  auto expr = parser.parse();
  auto astp = std::make_shared<AstPrinter>();
  if (err_report_.had_error())
    std::abort();

  std::cout << astp->stringify(expr) << std::endl;
}

}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008-2009 Gael Guennebaud <g.gael@free.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"
#include <Eigen/Geometry>
#include <Eigen/LU>
#include <Eigen/SVD>

/* this test covers the following files:
   Geometry/OrthoMethods.h
*/

template<typename Scalar> void orthomethods_3()
{
  typedef Matrix<Scalar,3,3> Matrix3;
  typedef Matrix<Scalar,3,1> Vector3;

  Vector3 v0 = Vector3::Random(),
          v1 = Vector3::Random(),
          v2 = Vector3::Random();

  // cross product
  VERIFY_IS_MUCH_SMALLER_THAN(v1.cross(v2).dot(v1), Scalar(1));
  Matrix3 mat3;
  mat3 << v0.normalized(),
         (v0.cross(v1)).normalized(),
         (v0.cross(v1).cross(v0)).normalized();
  VERIFY(mat3.isUnitary());

  // colwise/rowwise cross product
  mat3.setRandom();
  Vector3 vec3 = Vector3::Random();
  Matrix3 mcross;
  int i = ei_random<int>(0,2);
  mcross = mat3.colwise().cross(vec3);
  VERIFY_IS_APPROX(mcross.col(i), mat3.col(i).cross(vec3));
  mcross = mat3.rowwise().cross(vec3);
  VERIFY_IS_APPROX(mcross.row(i), mat3.row(i).cross(vec3));

}

template<typename Scalar, int Size> void orthomethods(int size=Size)
{
  typedef Matrix<Scalar,Size,1> VectorType;
  typedef Matrix<Scalar,3,Size> Matrix3N;
  typedef Matrix<Scalar,Size,3> MatrixN3;
  typedef Matrix<Scalar,3,1> Vector3;

  VectorType v0 = VectorType::Random(size),
             v1 = VectorType::Random(size),
             v2 = VectorType::Random(size);

  // unitOrthogonal
  VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().dot(v0), Scalar(1));
  VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), Scalar(1));

  // colwise/rowwise cross product
  Vector3 vec3 = Vector3::Random();
  int i = ei_random<int>(0,size-1);

  Matrix3N mat3N(3,size), mcross3N(3,size);
  mat3N.setRandom();
  mcross3N = mat3N.colwise().cross(vec3);
  VERIFY_IS_APPROX(mcross3N.col(i), mat3N.col(i).cross(vec3));

  MatrixN3 matN3(size,3), mcrossN3(size,3);
  matN3.setRandom();
  mcrossN3 = matN3.rowwise().cross(vec3);
  VERIFY_IS_APPROX(mcrossN3.row(i), matN3.row(i).cross(vec3));

}

void test_geo_orthomethods()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST( orthomethods_3<float>() );
    CALL_SUBTEST( orthomethods_3<double>() );
    CALL_SUBTEST( (orthomethods<float,2>()) );
    CALL_SUBTEST( (orthomethods<double,2>()) );
    CALL_SUBTEST( (orthomethods<float,3>()) );
    CALL_SUBTEST( (orthomethods<double,3>()) );
    CALL_SUBTEST( (orthomethods<float,7>()) );
    CALL_SUBTEST( (orthomethods<double,8>()) );
    CALL_SUBTEST( (orthomethods<float,Dynamic>(36)) );
    CALL_SUBTEST( (orthomethods<double,Dynamic>(35)) );
  }
}
<commit_msg>add tests showing bug in unitOrthogonal such that we don't forget it!<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008-2009 Gael Guennebaud <g.gael@free.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"
#include <Eigen/Geometry>
#include <Eigen/LU>
#include <Eigen/SVD>

/* this test covers the following files:
   Geometry/OrthoMethods.h
*/

template<typename Scalar> void orthomethods_3()
{
  typedef Matrix<Scalar,3,3> Matrix3;
  typedef Matrix<Scalar,3,1> Vector3;

  Vector3 v0 = Vector3::Random(),
          v1 = Vector3::Random(),
          v2 = Vector3::Random();

  // cross product
  VERIFY_IS_MUCH_SMALLER_THAN(v1.cross(v2).dot(v1), Scalar(1));
  Matrix3 mat3;
  mat3 << v0.normalized(),
         (v0.cross(v1)).normalized(),
         (v0.cross(v1).cross(v0)).normalized();
  VERIFY(mat3.isUnitary());

  // colwise/rowwise cross product
  mat3.setRandom();
  Vector3 vec3 = Vector3::Random();
  Matrix3 mcross;
  int i = ei_random<int>(0,2);
  mcross = mat3.colwise().cross(vec3);
  VERIFY_IS_APPROX(mcross.col(i), mat3.col(i).cross(vec3));
  mcross = mat3.rowwise().cross(vec3);
  VERIFY_IS_APPROX(mcross.row(i), mat3.row(i).cross(vec3));

}

template<typename Scalar, int Size> void orthomethods(int size=Size)
{
  typedef Matrix<Scalar,Size,1> VectorType;
  typedef Matrix<Scalar,3,Size> Matrix3N;
  typedef Matrix<Scalar,Size,3> MatrixN3;
  typedef Matrix<Scalar,3,1> Vector3;

  VectorType v0 = VectorType::Random(size),
             v1 = VectorType::Random(size),
             v2 = VectorType::Random(size);

  // unitOrthogonal
  VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().dot(v0), Scalar(1));
  VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), Scalar(1));

  if (size>3)
  {
    v0.template start<3>().setZero();
    v0.end(size-3).setRandom();

    VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().dot(v0), Scalar(1));
    VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), Scalar(1));
  }

  // colwise/rowwise cross product
  Vector3 vec3 = Vector3::Random();
  int i = ei_random<int>(0,size-1);

  Matrix3N mat3N(3,size), mcross3N(3,size);
  mat3N.setRandom();
  mcross3N = mat3N.colwise().cross(vec3);
  VERIFY_IS_APPROX(mcross3N.col(i), mat3N.col(i).cross(vec3));

  MatrixN3 matN3(size,3), mcrossN3(size,3);
  matN3.setRandom();
  mcrossN3 = matN3.rowwise().cross(vec3);
  VERIFY_IS_APPROX(mcrossN3.row(i), matN3.row(i).cross(vec3));
}

void test_geo_orthomethods()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST( orthomethods_3<float>() );
    CALL_SUBTEST( orthomethods_3<double>() );
    CALL_SUBTEST( (orthomethods<float,2>()) );
    CALL_SUBTEST( (orthomethods<double,2>()) );
    CALL_SUBTEST( (orthomethods<float,3>()) );
    CALL_SUBTEST( (orthomethods<double,3>()) );
    CALL_SUBTEST( (orthomethods<float,7>()) );
    CALL_SUBTEST( (orthomethods<double,8>()) );
    CALL_SUBTEST( (orthomethods<float,Dynamic>(36)) );
    CALL_SUBTEST( (orthomethods<double,Dynamic>(35)) );
  }
}
<|endoftext|>


<commit_before>#ifndef DIRICHLET_SHETXCOC
#define DIRICHLET_SHETXCOC

namespace Dune {
namespace Functionals {
namespace Constraints {

/** @brief Constraints for Dirichlet values on the entire boundary domain
 *
 * This class implements constraints on the degrees of freedom on a @ref
 * Subspace::Linear "linear subspace" @endref.
 *
 * Constraints efficiently implement functionals @f$ f_i:\cal X_H \to
 * \mathbb{R}@f$ for each degree of freedom @f$i\in C \subset
 * \{1,\dots,H\}@f$, where $H$ is the number of degree of freedoms in the
 * underlying discrete function space @f$\cal X_H\@f$. In case of this Dirichlet constraints class, the set
 * @f$\{1,\dots,C\}@f$ includes all
 *
 * @note The Dirichlet constraints only make sense on a finite element space,
 * not on a discontinuous discrete function space.
 *
 * @tparam DiscFuncSpace discrete function space on which constraints shall
 * be applied.
 */
template <class DiscFuncSpace>
class Dirichlet
{
public:
  //! Discrete function space on which the Dirichlet constraints are applied
  typedef DiscFuncSpace DiscreteFunctionSpace;

  //! Underlying grid part
  typedef typename DiscreteFunctionSpace::GridPartType GridPartType;

  //! Dimension of the grid part
  static const int griddim = GridPartType::GridType::dimension;

  //! Return type of local() method, implementing the LocalConstraints
  //! interface
  typedef Constraints::LocalDefault<double, griddim, griddim> LocalConstraintsType;

public:
  /** Constructor for the Dirichlet constraints
   *
   *  @param space    discrete function space object on which the Dirichlet
   *                  constraints are applied
   */
  Dirichlet(DiscFuncSpace& space)
    : space_(space)
    , gridPart_(space.gridPart())
  {
  }

  /** return a local constraint object for the entity \a en
   *
   * @param en Entity for which the local constraints shall be compted
   *
   * @returns local constraints object (copyable).
   */
  template <class Entity>
  const LocalConstraintsType local(const Entity& en)
  {
    typedef typename DiscFuncSpace::BaseFunctionSet BFS;

    const BFS& bfs    = space_.baseFunctionSet(en);
    const int numCols = bfs.numBaseFunctions();
    LocalConstraintsType lc(numCols);

    typedef typename DFS::Iterator ItType;
    typedef typename Entity::LeafIntersectionIterator IntersectionIterator;
    typedef typename IntersectionIterator::Intersection Intersection;

    int numRows = 0;
    ItType it = space_.begin();
    for (; it != space_.end(); it++) {
      const Entity& en = *it;

      IntersectionIterator iit = en.ileafbegin();
      for (; iit != en.ileafend(); iit++) {
        const Intersection& ii = *iit;
        if (ii.boundary()) {
          lc.setRowDofs(numRows, space_.mapToGlobal(en, numRows));
          for (unsigned int i = 0; i < numCols; i++) {
            lc.setColumnDofs(i, space_.mapToGlobal(en, i));
            lc.setLocalMatrix(numRows, i) = 0;
          }
          lc.setLocalMatrix(numRows, numRows) = 1;
          ++numRows;
        }
      }
    }
    lc.setRowDofsSize(numRows);
    return lc;
  }

private:
  DiscreteFunctionSpace& space_;
  GridPartType& gridPart_;
}; // end class Dirichlet

} // end of namespace Constraints
} // end of namespace Functionals
} // end of namespace Dune

#endif /* end of include guard: DIRICHLET_SHETXCOC */
<commit_msg>update documentation in Constraints::Dirichlet<commit_after>#ifndef DIRICHLET_SHETXCOC
#define DIRICHLET_SHETXCOC

namespace Dune {
namespace Functionals {
namespace Constraints {

/** @brief Constraints for Dirichlet values on the entire boundary domain
 *
 * This class implements constraints on the degrees of freedom on a @link
 * Subspace::Linear "linear subspace" @endlink.
 *
 * Constraints efficiently implement functionals @f$ f_i:{\cal X}_H \to
 * \mathbb{R}@f$ for each degree of freedom @f$i\in {\cal C} \subset
 * \{1,\dots,H\}@f$, where @f$ H @f$ is the number of degree of freedoms in the
 * underlying discrete function space @f$ {\cal X}_H @f$. In case of this
 * Dirichlet constraints class, the set @f$ {\cal C} @f$ includes all degrees of
 * freedom "lying" on boundary edges and @f$ f_i(u) = 0 @f$ for all @f$ i=\cal
 * C @f$.
 *
 * @note The Dirichlet constraints only make sense on a finite element space,
 * not on a discontinuous discrete function space.
 *
 * @tparam DiscFuncSpace discrete function space on which constraints shall
 * be applied.
 */
template <class DiscFuncSpace>
class Dirichlet
{
public:
  //! Discrete function space on which the Dirichlet constraints are applied
  typedef DiscFuncSpace DiscreteFunctionSpace;

  //! Underlying grid part
  typedef typename DiscreteFunctionSpace::GridPartType GridPartType;

  //! @brief dimension of the grid part
  static const int griddim = GridPartType::GridType::dimension;

  //! @brief Return type of local() method, implementing the LocalConstraints
  //! interface
  typedef Constraints::LocalDefault<double, griddim, griddim> LocalConstraintsType;

public:
  /** @brief Constructor for the Dirichlet constraints
   *
   *  @param space    discrete function space object on which the Dirichlet
   *                  constraints are applied
   */
  Dirichlet(DiscFuncSpace& space)
    : space_(space)
    , gridPart_(space.gridPart())
  {
  }

  /** @brief returns a local constraint object for the entity \a en
   *
   * @param en Entity for which the local constraints shall be compted
   *
   * @returns local constraints object (copyable). c.f.
   * Constraints::LocalDefault for more details on the return type
   * implementation.
   */
  template <class Entity>
  const LocalConstraintsType local(const Entity& en)
  {
    typedef typename DiscFuncSpace::BaseFunctionSet BFS;

    const BFS& bfs    = space_.baseFunctionSet(en);
    const int numCols = bfs.numBaseFunctions();
    LocalConstraintsType lc(numCols);

    typedef typename DFS::Iterator ItType;
    typedef typename Entity::LeafIntersectionIterator IntersectionIterator;
    typedef typename IntersectionIterator::Intersection Intersection;

    int numRows = 0;
    ItType it = space_.begin();
    for (; it != space_.end(); it++) {
      const Entity& en = *it;

      IntersectionIterator iit = en.ileafbegin();
      for (; iit != en.ileafend(); iit++) {
        const Intersection& ii = *iit;
        if (ii.boundary()) {
          lc.setRowDofs(numRows, space_.mapToGlobal(en, numRows));
          for (unsigned int i = 0; i < numCols; i++) {
            lc.setColumnDofs(i, space_.mapToGlobal(en, i));
            lc.setLocalMatrix(numRows, i) = 0;
          }
          lc.setLocalMatrix(numRows, numRows) = 1;
          ++numRows;
        }
      }
    }
    lc.setRowDofsSize(numRows);
    return lc;
  }

private:
  DiscreteFunctionSpace& space_;
  GridPartType& gridPart_;
}; // end class Dirichlet

} // end of namespace Constraints
} // end of namespace Functionals
} // end of namespace Dune

#endif /* end of include guard: DIRICHLET_SHETXCOC */
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2009-2011 by Patrick Schaefer, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */
#include "libxtreemfs/pbrpc_url.h"

#include <boost/algorithm/string.hpp>
#include <string>
#include <utility>

#include "libxtreemfs/xtreemfs_exception.h"

using namespace std;

namespace xtreemfs {

const std::string PBRPCURL::SCHEME_PBRPC = "pbrpc";
const std::string PBRPCURL::SCHEME_PBRPCS = "pbrpcs";
const std::string PBRPCURL::SCHEME_PBRPCG = "pbrpcg";
const std::string PBRPCURL::SCHEME_PBRPCU = "pbrpcu";

PBRPCURL::PBRPCURL(const std::string& scheme,
    const std::string& server, std::string& volume, uint16_t port)
    : scheme_(scheme), server_(server), port_(port), volume_(volume) {
}

PBRPCURL::PBRPCURL() : scheme_(""), server_(""), port_(0), volume_("") {
}

bool PBRPCURL::protocolContains(std::string url, std::string scheme) {
  size_t scheme_pos = url.find("://");
  if (scheme_pos != std::string::npos) {
    std::string s = url.substr(0, scheme_pos);
    return scheme == s;
  }
  return false;
}

void PBRPCURL::parseURL(
    const std::string& original_url,
    const std::string& default_scheme,
    const uint16_t default_port) {
  string url(original_url);
  boost::trim(url);

  scheme_ = default_scheme;
  size_t scheme_pos = url.find("://");
  size_t address_pos = 0;
  if (scheme_pos != std::string::npos) {
    // scheme specified
    scheme_ = url.substr(0, scheme_pos);
    if ((scheme_ != SCHEME_PBRPC)
        && (scheme_ != SCHEME_PBRPCS)
        && (scheme_ != SCHEME_PBRPCG)
        && (scheme_ != SCHEME_PBRPCU)) {
      throw InvalidURLException(scheme_ + " is not a valid scheme");
    }
    address_pos = scheme_pos + 3;
  }
  port_ = default_port;

  size_t last_slash = url.find_last_of("/");
  size_t last_colon = url.find_last_of(":");
  if (last_colon != std::string::npos) {
    // Port found.
    if (last_colon > address_pos) {
      try {
        if (last_slash !=  std::string::npos && last_slash > last_colon+1) {
          port_ = boost::lexical_cast<uint16_t>(
              url.substr(last_colon + 1, last_slash-last_colon-1));
        }
      } catch(const boost::bad_lexical_cast&) {
        throw InvalidURLException("invalid port: " +
            url.substr(last_colon + 1, last_slash-last_colon-1));
      }
    } else {
      last_colon = last_slash;
    }
  } else {
    last_colon = last_slash;
  }

  // volume is optional
  if (last_slash > address_pos && last_slash != std::string::npos) {
    volume_ = url.substr(last_slash+1, url.length() - last_slash);
  }

  server_ = url.substr(address_pos, last_colon-address_pos);
}

}  // namespace xtreemfs
<commit_msg>client: Fixed correct parsing of the port if the volume name is not present.<commit_after>/*
 * Copyright (c) 2009-2011 by Patrick Schaefer, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */
#include "libxtreemfs/pbrpc_url.h"

#include <boost/algorithm/string.hpp>
#include <string>
#include <utility>

#include "libxtreemfs/xtreemfs_exception.h"

using namespace std;

namespace xtreemfs {

const std::string PBRPCURL::SCHEME_PBRPC = "pbrpc";
const std::string PBRPCURL::SCHEME_PBRPCS = "pbrpcs";
const std::string PBRPCURL::SCHEME_PBRPCG = "pbrpcg";
const std::string PBRPCURL::SCHEME_PBRPCU = "pbrpcu";

PBRPCURL::PBRPCURL(const std::string& scheme,
    const std::string& server, std::string& volume, uint16_t port)
    : scheme_(scheme), server_(server), port_(port), volume_(volume) {
}

PBRPCURL::PBRPCURL() : scheme_(""), server_(""), port_(0), volume_("") {
}

bool PBRPCURL::protocolContains(std::string url, std::string scheme) {
  size_t scheme_pos = url.find("://");
  if (scheme_pos != std::string::npos) {
    std::string s = url.substr(0, scheme_pos);
    return scheme == s;
  }
  return false;
}

void PBRPCURL::parseURL(
    const std::string& original_url,
    const std::string& default_scheme,
    const uint16_t default_port) {
  string url(original_url);
  boost::trim(url);

  scheme_ = default_scheme;
  size_t scheme_pos = url.find("://");
  size_t address_pos = 0;
  if (scheme_pos != std::string::npos) {
    // scheme specified
    scheme_ = url.substr(0, scheme_pos);
    if ((scheme_ != SCHEME_PBRPC)
        && (scheme_ != SCHEME_PBRPCS)
        && (scheme_ != SCHEME_PBRPCG)
        && (scheme_ != SCHEME_PBRPCU)) {
      throw InvalidURLException(scheme_ + " is not a valid scheme");
    }
    address_pos = scheme_pos + 3;
  }
  port_ = default_port;

  size_t last_slash = url.find_last_of("/");
  size_t last_colon = url.find_last_of(":");
  if (last_colon != std::string::npos) {
    // Port found.
    if (last_colon > address_pos) {
      try {
        if (last_slash != std::string::npos) {
          if (last_slash > last_colon + 1) {
            port_ = boost::lexical_cast<uint16_t>(
                url.substr(last_colon + 1, last_slash - last_colon - 1));
          }
        } else {
          port_ = boost::lexical_cast<uint16_t>(url.substr(last_colon + 1));
        }
      } catch(const boost::bad_lexical_cast&) {
        throw InvalidURLException("invalid port: " +
            url.substr(last_colon + 1, last_slash - last_colon - 1));
      }
    } else {
      last_colon = last_slash;
    }
  } else {
    last_colon = last_slash;
  }

  // volume is optional
  if (last_slash > address_pos && last_slash != std::string::npos) {
    volume_ = url.substr(last_slash+1, url.length() - last_slash);
  }

  server_ = url.substr(address_pos, last_colon-address_pos);
}

}  // namespace xtreemfs
<|endoftext|>