<commit_before>#include "samson/common/coding.h"

namespace samson
{

    bool operator==(const KVFormat & left, const KVFormat & right)
    {
        if ( left.keyFormat != right.keyFormat )
            return false;
        if ( left.valueFormat != right.valueFormat )
            return false;
        return true;
    }

    bool operator!=(const KVFormat & left, const KVFormat & right)
    {
        if ( left.keyFormat != right.keyFormat )
            return true;
        if ( left.valueFormat != right.valueFormat )
            return true;
        return false;
    }

    bool operator<(const KVRange & left, const KVRange & right)
    {
        if( left.hg_begin < left.hg_begin )
            return true;
        if( left.hg_begin > left.hg_begin )
            return false;

        if( left.hg_end < left.hg_end )
            return true;

        return false;
    }

    bool operator!=(const KVRange & left, const KVRange & right)
    {
        if( left.hg_begin != right.hg_begin )
            return true;

        if( left.hg_end != right.hg_end )
            return true;

        return false;
    }

    bool operator==(const KVRange & left, const KVRange & right)
    {
        if( left.hg_begin != right.hg_begin )
            return false;

        if( left.hg_end != right.hg_end )
            return false;

        return true;

    }

#pragma mark KVRange

    KVRange::KVRange()
    {
        hg_begin = 0;
        hg_end = KVFILE_NUM_HASHGROUPS;
    }

    KVRange::KVRange( int _hg_begin , int _hg_end )
    {
        hg_begin = _hg_begin;
        hg_end = _hg_end;
    }

    void KVRange::set( int _hg_begin , int _hg_end )
    {
        hg_begin = _hg_begin;
        hg_end = _hg_end;
    }

    void KVRange::setFrom( KVInfo *info )
    {
        int i = 0 ;
        while( (info[i].size == 0) || ( i < KVFILE_NUM_HASHGROUPS ) )
            i++;

        if( i == KVFILE_NUM_HASHGROUPS)
        {
	  	   LM_W(("No content for generated block"));
            set(0,1);   // Smaller set
            return;
        }

        hg_begin = i;
        i++;
        while( (info[i].size == 0) || ( i < KVFILE_NUM_HASHGROUPS ) )
            i++;
        hg_end = i;

    }

    bool KVRange::isValid()
    {
        if ( ( hg_begin < 0 ) || (hg_begin > (KVFILE_NUM_HASHGROUPS) ) )
            return false;
        if ( ( hg_end < 0 ) || (hg_end > KVFILE_NUM_HASHGROUPS ) )
            return false;

        if( hg_begin >= hg_end )
            return false;

        return true;
    }

    void KVRange::getInfo( std::ostringstream& output)
    {
        au::xml_open(output, "kv_range");
        au::xml_simple( output , "hg_begin" , hg_begin );
        au::xml_simple( output , "hg_end" , hg_end );
        au::xml_close(output, "kv_range");
    }

    std::string KVRange::str()
    {
        return au::str("[%d %d]", hg_begin , hg_end);
    }

    bool KVRange::overlap( KVRange range )
    {
        if( range.hg_end <= hg_begin )
            return false;

        if( range.hg_begin >= hg_end )
            return false;

        return true;
    }

    int KVRange::getNumHashGroups()
    {
        return hg_end - hg_begin;
    }

    bool KVRange::includes( KVRange range )
    {
        if( range.hg_begin < hg_begin )
            return false;
        if( range.hg_end > hg_end )
            return false;

        return true;
    }

    bool KVRange::contains( int hg )
    {
        if( hg < hg_begin )
            return false;
        if( hg >= hg_end )
            return false;

        return true;
    }

    bool KVRange::contains(  KVRange range )
    {
        if ( range.hg_begin < hg_begin )
            return false;
        if( range.hg_end > hg_end )
            return false;

        return true;
    }

    // Get the maximum division pattern for this range

    bool KVRange::isValidForNumDivisions( int num_divisions )
    {
        int size_per_division = KVFILE_NUM_HASHGROUPS / num_divisions;

        if( ( hg_end - hg_begin ) > size_per_division )
            return false;

        int max_hg_end = ( hg_begin / size_per_division ) * size_per_division + size_per_division;

        if ( hg_end > max_hg_end )
            return false;

        return true;

    }

    int KVRange::getMaxNumDivisions()
    {
        int num_divisions = 1;

        while( true )
        {
            if( isValidForNumDivisions( num_divisions*2 ) )
                num_divisions*=2;
            else
                return num_divisions;
        }
    }

    // Get the division for a particular hg
    int divisionForHG( int hg , int num_divisions )
    {
        int size_per_division = KVFILE_NUM_HASHGROUPS / num_divisions;
        return hg / size_per_division;
    }

    KVRange rangeForDivision( int pos , int num_divisions )
    {
        int size_per_division = KVFILE_NUM_HASHGROUPS / num_divisions;
        int hg_begin = pos*size_per_division;
        int hg_end = (pos+1)*size_per_division;

        if( pos == (num_divisions-1) )
            hg_end = KVFILE_NUM_HASHGROUPS;

        return KVRange( hg_begin , hg_end );
    }

    void clear( KVInfo* info )
    {
        for (int i = 0 ; i < KVFILE_NUM_HASHGROUPS ; i++ )
            info[i].clear();
    }

    // Get the agregation of
    KVInfo selectRange( KVInfo* info , KVRange range )
    {
        KVInfo tmp;
        tmp.clear();

        for (int i = 0 ; i < KVFILE_NUM_HASHGROUPS ; i++)
            if( range.contains(i) )
                tmp.append( info[i] );

        return tmp;
    }

}
<commit_msg>Fix bug in implementation to compute ranges for generated blocks<commit_after>#include "samson/common/coding.h"

namespace samson
{

    bool operator==(const KVFormat & left, const KVFormat & right)
    {
        if ( left.keyFormat != right.keyFormat )
            return false;
        if ( left.valueFormat != right.valueFormat )
            return false;
        return true;
    }

    bool operator!=(const KVFormat & left, const KVFormat & right)
    {
        if ( left.keyFormat != right.keyFormat )
            return true;
        if ( left.valueFormat != right.valueFormat )
            return true;
        return false;
    }

    bool operator<(const KVRange & left, const KVRange & right)
    {
        if( left.hg_begin < left.hg_begin )
            return true;
        if( left.hg_begin > left.hg_begin )
            return false;

        if( left.hg_end < left.hg_end )
            return true;

        return false;
    }

    bool operator!=(const KVRange & left, const KVRange & right)
    {
        if( left.hg_begin != right.hg_begin )
            return true;

        if( left.hg_end != right.hg_end )
            return true;

        return false;
    }

    bool operator==(const KVRange & left, const KVRange & right)
    {
        if( left.hg_begin != right.hg_begin )
            return false;

        if( left.hg_end != right.hg_end )
            return false;

        return true;

    }

#pragma mark KVRange

    KVRange::KVRange()
    {
        hg_begin = 0;
        hg_end = KVFILE_NUM_HASHGROUPS;
    }

    KVRange::KVRange( int _hg_begin , int _hg_end )
    {
        hg_begin = _hg_begin;
        hg_end = _hg_end;
    }

    void KVRange::set( int _hg_begin , int _hg_end )
    {
        hg_begin = _hg_begin;
        hg_end = _hg_end;
    }

    void KVRange::setFrom( KVInfo *info )
    {
        int i = 0 ;
        while( (info[i].size == 0) && ( i < KVFILE_NUM_HASHGROUPS ) )
            i++;

        if( i == KVFILE_NUM_HASHGROUPS)
        {
	  	   LM_W(("No content for generated block"));
            set(0,1);   // Smaller set
            return;
        }

        hg_begin = i;

        int j = KVFILE_NUM_HASHGROUPS;
        while( (info[j-1].size == 0) && ( j > (i+1) ) )
            j++;

        hg_end = j;

		LM_M(("KVRange for output block %s" , str().c_str()));
    }

    bool KVRange::isValid()
    {
        if ( ( hg_begin < 0 ) || (hg_begin > (KVFILE_NUM_HASHGROUPS) ) )
            return false;
        if ( ( hg_end < 0 ) || (hg_end > KVFILE_NUM_HASHGROUPS ) )
            return false;

        if( hg_begin >= hg_end )
            return false;

        return true;
    }

    void KVRange::getInfo( std::ostringstream& output)
    {
        au::xml_open(output, "kv_range");
        au::xml_simple( output , "hg_begin" , hg_begin );
        au::xml_simple( output , "hg_end" , hg_end );
        au::xml_close(output, "kv_range");
    }

    std::string KVRange::str()
    {
        return au::str("[%d %d]", hg_begin , hg_end);
    }

    bool KVRange::overlap( KVRange range )
    {
        if( range.hg_end <= hg_begin )
            return false;

        if( range.hg_begin >= hg_end )
            return false;

        return true;
    }

    int KVRange::getNumHashGroups()
    {
        return hg_end - hg_begin;
    }

    bool KVRange::includes( KVRange range )
    {
        if( range.hg_begin < hg_begin )
            return false;
        if( range.hg_end > hg_end )
            return false;

        return true;
    }

    bool KVRange::contains( int hg )
    {
        if( hg < hg_begin )
            return false;
        if( hg >= hg_end )
            return false;

        return true;
    }

    bool KVRange::contains(  KVRange range )
    {
        if ( range.hg_begin < hg_begin )
            return false;
        if( range.hg_end > hg_end )
            return false;

        return true;
    }

    // Get the maximum division pattern for this range

    bool KVRange::isValidForNumDivisions( int num_divisions )
    {
        int size_per_division = KVFILE_NUM_HASHGROUPS / num_divisions;

        if( ( hg_end - hg_begin ) > size_per_division )
            return false;

        int max_hg_end = ( hg_begin / size_per_division ) * size_per_division + size_per_division;

        if ( hg_end > max_hg_end )
            return false;

        return true;

    }

    int KVRange::getMaxNumDivisions()
    {
        int num_divisions = 1;

        while( true )
        {
            if( isValidForNumDivisions( num_divisions*2 ) )
                num_divisions*=2;
            else
                return num_divisions;
        }
    }

    // Get the division for a particular hg
    int divisionForHG( int hg , int num_divisions )
    {
        int size_per_division = KVFILE_NUM_HASHGROUPS / num_divisions;
        return hg / size_per_division;
    }

    KVRange rangeForDivision( int pos , int num_divisions )
    {
        int size_per_division = KVFILE_NUM_HASHGROUPS / num_divisions;
        int hg_begin = pos*size_per_division;
        int hg_end = (pos+1)*size_per_division;

        if( pos == (num_divisions-1) )
            hg_end = KVFILE_NUM_HASHGROUPS;

        return KVRange( hg_begin , hg_end );
    }

    void clear( KVInfo* info )
    {
        for (int i = 0 ; i < KVFILE_NUM_HASHGROUPS ; i++ )
            info[i].clear();
    }

    // Get the agregation of
    KVInfo selectRange( KVInfo* info , KVRange range )
    {
        KVInfo tmp;
        tmp.clear();

        for (int i = 0 ; i < KVFILE_NUM_HASHGROUPS ; i++)
            if( range.contains(i) )
                tmp.append( info[i] );

        return tmp;
    }

}
<|endoftext|>


<commit_before>#include "pch.h"

#include "style.h"

using namespace Windows::Foundation;

style::style()
    : fill_(paint_type::color, Colors::Black)
    , stroke_(paint_type::none, Colors::Black)
    , strokeWidth_(length{ 0, unit::unspecified })
{
}

ICanvasBrush^ style::fillBrush(ICanvasResourceCreator^ resourceCreator)
{
    return fill_.brush(resourceCreator);
}

ICanvasBrush^ style::strokeBrush(ICanvasResourceCreator^ resourceCreator)
{
    return stroke_.brush(resourceCreator);
}

float style::stroke_width()
{
    return strokeWidth_.Number; // TODO: respect the Unit!
}

inherited_style::inherited_style()
{
    style defaultStyle;
    stack_.push(defaultStyle);
}

void inherited_style::push()
{
    stack_.push(stack_.top());
}

void inherited_style::pop()
{
    stack_.pop();
    assert(!stack_.empty());
}
<commit_msg>Set default stroke-width to 1<commit_after>#include "pch.h"

#include "style.h"

using namespace Windows::Foundation;

style::style()
    : fill_(paint_type::color, Colors::Black)
    , stroke_(paint_type::none, Colors::Black)
    , strokeWidth_(length{ 1, unit::unspecified })
{
}

ICanvasBrush^ style::fillBrush(ICanvasResourceCreator^ resourceCreator)
{
    return fill_.brush(resourceCreator);
}

ICanvasBrush^ style::strokeBrush(ICanvasResourceCreator^ resourceCreator)
{
    return stroke_.brush(resourceCreator);
}

float style::stroke_width()
{
    return strokeWidth_.Number; // TODO: respect the Unit!
}

inherited_style::inherited_style()
{
    style defaultStyle;
    stack_.push(defaultStyle);
}

void inherited_style::push()
{
    stack_.push(stack_.top());
}

void inherited_style::pop()
{
    stack_.pop();
    assert(!stack_.empty());
}
<|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(XOBJECT_HEADER_GUARD_1357924680)
#define XOBJECT_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <XPath/XPathDefinitions.hpp>

#include <XalanDOM/XalanDOMString.hpp>

#include <PlatformSupport/FormatterListener.hpp>
#include <PlatformSupport/XalanReferenceCountedObject.hpp>

#include <XPath/XPathException.hpp>

class MutableNodeRefList;
class NodeRefListBase;
class ResultTreeFragBase;
class XObjectFactory;
class XObjectTypeCallback;
class XPathExecutionContext;

/**
 * Class to hold XPath return types.
 */
class XALAN_XPATH_EXPORT XObject : protected XalanReferenceCountedObject
{
public:

	friend class XObjectPtr;

	/**
	 * Enumeration of possible object types
	 */
	enum	eObjectType { eTypeNull = 0,
						  eTypeUnknown = 1,
						  eTypeBoolean = 2,
						  eTypeNumber = 3,
						  eTypeString = 4,
						  eTypeNodeSet = 5,
						  eTypeResultTreeFrag = 6,
						  eTypeUserDefined = 7,
						  // These next types are implementation-specific, and
						  // are never returned by getType().
						  eTypeStringReference = 8,
						  eTypeStringAdapter = 9,
						  eTypeStringCached = 10,
						  eTypeXTokenNumberAdapter = 11,
						  eTypeXTokenStringAdapter = 12,
						  eUnknown
						};

	/**
	 * Create an XObject.
	 *
	 * @param theObjectType The enum for the type of the object.
	 */
	XObject(eObjectType		theObjectType);

	XObject(const XObject&	source);

	/**
	 * Clone the instance
	 *
	 * @param If theAddress is not null, the XObject will clone itself into that address.
	 * @return a clone of the instance.
	 */
	virtual XObject*
	clone(void*		theAddress = 0) const = 0;

	/**
	 * Given a request type, return the equivalent string.
	 * For diagnostic purposes.
	 *
	 * @return string for type
	 */
	virtual XalanDOMString
	getTypeString() const = 0;

	/**
	 * Cast result object to a number.
	 *
	 * @return numeric value
	 */
	virtual double
	num() const;

	/**
	 * Cast result object to a boolean.
	 *
	 * @return boolean value
	 */
	virtual bool
	boolean() const;

	/**
	 * Cast result object to a string.
	 *
	 * @return string value
	 */
	virtual const XalanDOMString&
	str() const;

	typedef void (FormatterListener::*MemberFunctionPtr)(const XMLCh* const, const unsigned int);

	/**
	 * Send the string value to a FormatterListener instance.
	 *
	 * @param formatterListener The FormatterListener instance
	 * @param function A pointer to the member function of FormatterListener to call
	 *
	 */
	virtual void
	str(
			FormatterListener&	formatterListener,
			MemberFunctionPtr	function) const = 0;

	/**
	 * Cast result object to a result tree fragment.
	 *
	 * @param executionContext the current execution context
	 * @return result tree fragment
	 */
	virtual const ResultTreeFragBase&
	rtree(XPathExecutionContext&	executionContext) const;

	/**
	 * Cast result object to a nodelist.
	 *
	 * @return node list
	 */
	virtual const NodeRefListBase&
	nodeset() const;

	/**
	 * Process a callback request for preferred type information.
	 *
	 * @param theCallbackObject object to call back
	 */
	virtual void
	ProcessXObjectTypeCallback(XObjectTypeCallback&		theCallbackObject) = 0;

	/**
	 * Process a callback request for preferred type information.
	 *
	 * @param theCallbackObject object to call back
	 */
	virtual void
	ProcessXObjectTypeCallback(XObjectTypeCallback&		theCallbackObject) const = 0;

	/**
	 * Tell if two objects are functionally equal.
	 *
	 * @param theRHS object to compare
	 * @param executionContext the current execution context
	 * @return true if they are equal
	 */
	bool
	equals(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell if two objects are functionally not equal.
	 *
	 * @param theRHS object to compare
	 * @param executionContext the current execution context
	 * @return true if they are equal
	 */
	bool
	notEquals(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell if one object is less than the other.
	 *
	 * @param theRHS object to compare
	 * @return true if they are equal
	 */
	bool
	lessThan(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell if one object is less than or equal
	 * the other.
	 *
	 * @param theRHS object to compare
	 * @return true if they are equal
	 */
	bool
	lessThanOrEquals(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell if one object is greater than the other.
	 *
	 * @param theRHS object to compare
	 * @return true if they are equal
	 */
	bool
	greaterThan(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell if one object is greater than or equal
	 * the other.
	 *
	 * @param theRHS object to compare
	 * @return true if they are equal
	 */
	bool
	greaterThanOrEquals(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell what kind of class this is.
	 *
	 * @return numeric type value
	 */
	eObjectType
	getType() const
	{
		return m_objectType;
	}

	// All XObject instances are controlled by an instance of an XObjectFactory.
	friend class XObjectFactory;

	void
	setFactory(XObjectFactory*	theFactory)
	{
		m_factory = theFactory;
	}

	// Base class for all XObject exceptions...
	class XObjectException : public XPathException
	{
	public:

		explicit
		XObjectException(
				const XalanDOMString&	message = XalanDOMString(),
				const XalanNode*		styleNode = 0,
				const XalanDOMString&	theType = XalanDOMString(XALAN_STATIC_UCODE_STRING("XObjectException")));

		virtual
		~XObjectException();
	};

	class XObjectInvalidConversionException : public XObjectException
	{
	public:

		XObjectInvalidConversionException(
				const XalanDOMString&	fromType,
				const XalanDOMString&	toType);

		virtual
		~XObjectInvalidConversionException();

		const XalanDOMString&
		getFromType() const
		{
			return m_fromType;
		}

		const XalanDOMString&
		getToType() const
		{
			return m_toType;
		}

	private:

		static const XalanDOMString
		formatErrorString(
				const XalanDOMString&	fromType,
				const XalanDOMString&	toType);

		const XalanDOMString	m_fromType;

		const XalanDOMString	m_toType;
	};

protected:

	/**
	 * Tell what kind of class this is.
	 *
	 * @return numeric type value
	 */
	virtual eObjectType
	getRealType() const;

	virtual void
	referenced();

	virtual void
	dereferenced();

	virtual
	~XObject();

	static const XalanDOMString		s_nullString;

private:

	// Not implemented...
	XObject&
	operator=(const XObject&);

	const eObjectType	m_objectType;

	XObjectFactory*		m_factory;
};

/**
 * Class to hold XObjectPtr return types.
 */
class XALAN_XPATH_EXPORT XObjectPtr
{
public:

	friend bool operator==(const XObjectPtr&, const XObjectPtr&);

	/**
	 * Create an XObjectPtr.
	 */
	explicit
	XObjectPtr(XObject*		theXObject = 0) :
		m_xobjectPtr(theXObject)
	{
		XalanReferenceCountedObject::addReference(theXObject);
	}

	XObjectPtr(const XObjectPtr&	theSource) :
		m_xobjectPtr(theSource.m_xobjectPtr)
	{
		XalanReferenceCountedObject::addReference(m_xobjectPtr);
	};

	XObjectPtr&
	operator=(const XObjectPtr&		theRHS)
	{
		if (m_xobjectPtr != theRHS.m_xobjectPtr)
		{
			XalanReferenceCountedObject::removeReference(m_xobjectPtr);

			m_xobjectPtr = theRHS.m_xobjectPtr;

			XalanReferenceCountedObject::addReference(m_xobjectPtr);
		}

		return *this;
	}

	~XObjectPtr()
	{
		XalanReferenceCountedObject::removeReference(m_xobjectPtr);
	};

	bool
	null() const
	{
		return m_xobjectPtr == 0 ? true : false;
	}

	const XObject&
	operator*() const
	{
		return *m_xobjectPtr;
	};

	XObject&
	operator*()
	{
		return *m_xobjectPtr;
	};

	const XObject*
	operator->() const
	{
		return m_xobjectPtr;
	};

	XObject*
	operator->()
	{
		return m_xobjectPtr;
	};

	const XObject*
	get() const
	{
		return m_xobjectPtr;
	};

	XObject*
	get()
	{
		return m_xobjectPtr;
	};

private:

	XObject*	m_xobjectPtr;
};

inline bool
operator==(
			const XObjectPtr&	theLHS,
			const XObjectPtr&	theRHS)
{
	return theLHS.m_xobjectPtr == theRHS.m_xobjectPtr;
}

inline bool
operator!=(
			const XObjectPtr&	theLHS,
			const XObjectPtr&	theRHS)
{
	return !(theLHS == theRHS);
}

#endif	// XOBJECT_HEADER_GUARD_1357924680
<commit_msg>Added operator<() so XObjectPtr can be a key in a map or a value in a set.<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(XOBJECT_HEADER_GUARD_1357924680)
#define XOBJECT_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <XPath/XPathDefinitions.hpp>

#include <XalanDOM/XalanDOMString.hpp>

#include <PlatformSupport/FormatterListener.hpp>
#include <PlatformSupport/XalanReferenceCountedObject.hpp>

#include <XPath/XPathException.hpp>

class MutableNodeRefList;
class NodeRefListBase;
class ResultTreeFragBase;
class XObjectFactory;
class XObjectTypeCallback;
class XPathExecutionContext;

/**
 * Class to hold XPath return types.
 */
class XALAN_XPATH_EXPORT XObject : protected XalanReferenceCountedObject
{
public:

	friend class XObjectPtr;

	/**
	 * Enumeration of possible object types
	 */
	enum	eObjectType { eTypeNull = 0,
						  eTypeUnknown = 1,
						  eTypeBoolean = 2,
						  eTypeNumber = 3,
						  eTypeString = 4,
						  eTypeNodeSet = 5,
						  eTypeResultTreeFrag = 6,
						  eTypeUserDefined = 7,
						  // These next types are implementation-specific, and
						  // are never returned by getType().
						  eTypeStringReference = 8,
						  eTypeStringAdapter = 9,
						  eTypeStringCached = 10,
						  eTypeXTokenNumberAdapter = 11,
						  eTypeXTokenStringAdapter = 12,
						  eUnknown
						};

	/**
	 * Create an XObject.
	 *
	 * @param theObjectType The enum for the type of the object.
	 */
	XObject(eObjectType		theObjectType);

	XObject(const XObject&	source);

	/**
	 * Clone the instance
	 *
	 * @param If theAddress is not null, the XObject will clone itself into that address.
	 * @return a clone of the instance.
	 */
	virtual XObject*
	clone(void*		theAddress = 0) const = 0;

	/**
	 * Given a request type, return the equivalent string.
	 * For diagnostic purposes.
	 *
	 * @return string for type
	 */
	virtual XalanDOMString
	getTypeString() const = 0;

	/**
	 * Cast result object to a number.
	 *
	 * @return numeric value
	 */
	virtual double
	num() const;

	/**
	 * Cast result object to a boolean.
	 *
	 * @return boolean value
	 */
	virtual bool
	boolean() const;

	/**
	 * Cast result object to a string.
	 *
	 * @return string value
	 */
	virtual const XalanDOMString&
	str() const;

	typedef void (FormatterListener::*MemberFunctionPtr)(const XMLCh* const, const unsigned int);

	/**
	 * Send the string value to a FormatterListener instance.
	 *
	 * @param formatterListener The FormatterListener instance
	 * @param function A pointer to the member function of FormatterListener to call
	 *
	 */
	virtual void
	str(
			FormatterListener&	formatterListener,
			MemberFunctionPtr	function) const = 0;

	/**
	 * Cast result object to a result tree fragment.
	 *
	 * @param executionContext the current execution context
	 * @return result tree fragment
	 */
	virtual const ResultTreeFragBase&
	rtree(XPathExecutionContext&	executionContext) const;

	/**
	 * Cast result object to a nodelist.
	 *
	 * @return node list
	 */
	virtual const NodeRefListBase&
	nodeset() const;

	/**
	 * Process a callback request for preferred type information.
	 *
	 * @param theCallbackObject object to call back
	 */
	virtual void
	ProcessXObjectTypeCallback(XObjectTypeCallback&		theCallbackObject) = 0;

	/**
	 * Process a callback request for preferred type information.
	 *
	 * @param theCallbackObject object to call back
	 */
	virtual void
	ProcessXObjectTypeCallback(XObjectTypeCallback&		theCallbackObject) const = 0;

	/**
	 * Tell if two objects are functionally equal.
	 *
	 * @param theRHS object to compare
	 * @param executionContext the current execution context
	 * @return true if they are equal
	 */
	bool
	equals(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell if two objects are functionally not equal.
	 *
	 * @param theRHS object to compare
	 * @param executionContext the current execution context
	 * @return true if they are equal
	 */
	bool
	notEquals(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell if one object is less than the other.
	 *
	 * @param theRHS object to compare
	 * @return true if they are equal
	 */
	bool
	lessThan(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell if one object is less than or equal
	 * the other.
	 *
	 * @param theRHS object to compare
	 * @return true if they are equal
	 */
	bool
	lessThanOrEquals(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell if one object is greater than the other.
	 *
	 * @param theRHS object to compare
	 * @return true if they are equal
	 */
	bool
	greaterThan(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell if one object is greater than or equal
	 * the other.
	 *
	 * @param theRHS object to compare
	 * @return true if they are equal
	 */
	bool
	greaterThanOrEquals(
			const XObject&			theRHS,
			XPathExecutionContext&	executionContext) const;

	/**
	 * Tell what kind of class this is.
	 *
	 * @return numeric type value
	 */
	eObjectType
	getType() const
	{
		return m_objectType;
	}

	// All XObject instances are controlled by an instance of an XObjectFactory.
	friend class XObjectFactory;

	void
	setFactory(XObjectFactory*	theFactory)
	{
		m_factory = theFactory;
	}

	// Base class for all XObject exceptions...
	class XObjectException : public XPathException
	{
	public:

		explicit
		XObjectException(
				const XalanDOMString&	message = XalanDOMString(),
				const XalanNode*		styleNode = 0,
				const XalanDOMString&	theType = XalanDOMString(XALAN_STATIC_UCODE_STRING("XObjectException")));

		virtual
		~XObjectException();
	};

	class XObjectInvalidConversionException : public XObjectException
	{
	public:

		XObjectInvalidConversionException(
				const XalanDOMString&	fromType,
				const XalanDOMString&	toType);

		virtual
		~XObjectInvalidConversionException();

		const XalanDOMString&
		getFromType() const
		{
			return m_fromType;
		}

		const XalanDOMString&
		getToType() const
		{
			return m_toType;
		}

	private:

		static const XalanDOMString
		formatErrorString(
				const XalanDOMString&	fromType,
				const XalanDOMString&	toType);

		const XalanDOMString	m_fromType;

		const XalanDOMString	m_toType;
	};

protected:

	/**
	 * Tell what kind of class this is.
	 *
	 * @return numeric type value
	 */
	virtual eObjectType
	getRealType() const;

	virtual void
	referenced();

	virtual void
	dereferenced();

	virtual
	~XObject();

	static const XalanDOMString		s_nullString;

private:

	// Not implemented...
	XObject&
	operator=(const XObject&);

	const eObjectType	m_objectType;

	XObjectFactory*		m_factory;
};

/**
 * Class to hold XObjectPtr return types.
 */
class XALAN_XPATH_EXPORT XObjectPtr
{
public:

	friend bool operator==(const XObjectPtr&, const XObjectPtr&);
	friend bool operator<(const XObjectPtr&, const XObjectPtr&);

	/**
	 * Create an XObjectPtr.
	 */
	explicit
	XObjectPtr(XObject*		theXObject = 0) :
		m_xobjectPtr(theXObject)
	{
		XalanReferenceCountedObject::addReference(theXObject);
	}

	XObjectPtr(const XObjectPtr&	theSource) :
		m_xobjectPtr(theSource.m_xobjectPtr)
	{
		XalanReferenceCountedObject::addReference(m_xobjectPtr);
	};

	XObjectPtr&
	operator=(const XObjectPtr&		theRHS)
	{
		if (m_xobjectPtr != theRHS.m_xobjectPtr)
		{
			XalanReferenceCountedObject::removeReference(m_xobjectPtr);

			m_xobjectPtr = theRHS.m_xobjectPtr;

			XalanReferenceCountedObject::addReference(m_xobjectPtr);
		}

		return *this;
	}

	~XObjectPtr()
	{
		XalanReferenceCountedObject::removeReference(m_xobjectPtr);
	};

	bool
	null() const
	{
		return m_xobjectPtr == 0 ? true : false;
	}

	const XObject&
	operator*() const
	{
		return *m_xobjectPtr;
	};

	XObject&
	operator*()
	{
		return *m_xobjectPtr;
	};

	const XObject*
	operator->() const
	{
		return m_xobjectPtr;
	};

	XObject*
	operator->()
	{
		return m_xobjectPtr;
	};

	const XObject*
	get() const
	{
		return m_xobjectPtr;
	};

	XObject*
	get()
	{
		return m_xobjectPtr;
	};

private:

	XObject*	m_xobjectPtr;
};

inline bool
operator==(
			const XObjectPtr&	theLHS,
			const XObjectPtr&	theRHS)
{
	return theLHS.m_xobjectPtr == theRHS.m_xobjectPtr;
}

inline bool
operator!=(
			const XObjectPtr&	theLHS,
			const XObjectPtr&	theRHS)
{
	return !(theLHS == theRHS);
}

inline bool
operator<(
			const XObjectPtr&	theLHS,
			const XObjectPtr&	theRHS)
{
	return theLHS.m_xobjectPtr < theRHS.m_xobjectPtr;
}

#endif	// XOBJECT_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>#ifdef ARDUINO_AVR_YUN

#include "YunMQTTClient.h"

#include <FileIO.h>

YunMQTTClient::YunMQTTClient() {}

void YunMQTTClient::begin(const char * hostname) {
  this->begin(hostname, 1883);
}

void YunMQTTClient::begin(const char * hostname, int port) {
  this->hostname = hostname;
  this->port = port;
}

int YunMQTTClient::updateBridge() {
  Process p;

  int r1 = p.runShellCommand("mkdir -p /usr/arduino-mqtt");
  int r2 = p.runShellCommand("wget -N https://raw.githubusercontent.com/256dpi/arduino-mqtt/v1.8.0/yun/mqtt.py --no-check-certificate -P /usr/arduino-mqtt");
  int r3 = p.runShellCommand("wget -N https://raw.githubusercontent.com/256dpi/arduino-mqtt/v1.8.0/yun/bridge.py --no-check-certificate -P /usr/arduino-mqtt");

  boolean success = r1 == 0 && r2 == 0 && r3 == 0;

  if(success) {
    return 2;
  } else {
    return 0;
  }
}

void YunMQTTClient::setWill(const char * topic) {
  this->setWill(topic, "");
}

void YunMQTTClient::setWill(const char * topic, const char * payload) {
  this->willTopic = topic;
  this->willPayload = payload;
}

boolean YunMQTTClient::connect(const char * clientId) {
  return this->connect(clientId, "", "");
}

boolean YunMQTTClient::connect(const char * clientId, const char * username, const char * password) {
  if(this->updateBridge() == 0) {
    return false;
  }

  this->process.begin("python");
  this->process.addParameter("-u");
  this->process.addParameter("/usr/mqtt/bridge.py");
  this->process.runAsynchronously();
  this->process.setTimeout(10000);

  // wait for script to launch
  this->process.readStringUntil('\n');

  // set will if available
  if(this->willTopic != NULL) {
    this->process.print("w:");
    this->process.print(this->willTopic);
    if(this->willPayload != NULL) {
      this->process.print(':');
      this->process.print(this->willPayload);
    }
    this->process.print('\n');
  }

  // send connect request
  this->process.print("c:");
  this->process.print(this->hostname);
  this->process.print(':');
  this->process.print(this->port);
  this->process.print(':');
  this->process.print(clientId);
  if(strlen(username) > 0 && strlen(password) > 0) {
    this->process.print(':');
    this->process.print(username);
    this->process.print(':');
    this->process.print(password);
  }
  this->process.print('\n');

  // wait for answer
  String ret = this->process.readStringUntil('\n');
  this->alive = ret.equals("a");

  if(!this->alive) {
    this->process.close();
    return false;
  } else {
    return true;
  }
}

void YunMQTTClient::publish(String topic) {
  this->publish(topic.c_str(), "");
}

void YunMQTTClient::publish(String topic, String payload) {
  this->publish(topic.c_str(), payload.c_str());
}

void YunMQTTClient::publish(const char * topic, String payload) {
  this->publish(topic, payload.c_str());
}

void YunMQTTClient::publish(const char * topic, const char * payload) {
  // send publish request
  this->process.print("p:");
  this->process.print(topic);
  this->process.print(':');
  this->process.print(payload);
  this->process.print('\n');
}

void YunMQTTClient::subscribe(String topic) {
  this->subscribe(topic.c_str());
}

void YunMQTTClient::subscribe(const char * topic) {
  // send subscribe request
  this->process.print("s:");
  this->process.print(topic);
  this->process.print('\n');
}

void YunMQTTClient::unsubscribe(String topic) {
  this->unsubscribe(topic.c_str());
}

void YunMQTTClient::unsubscribe(const char * topic) {
  // send unsubscribe request
  this->process.print("u:");
  this->process.print(topic);
  this->process.print('\n');
}

void YunMQTTClient::loop() {
  int av = this->process.available();
  if(av > 0) {
    String ret = process.readStringUntil('\n');

    if(ret.startsWith("m")) {
      int startTopic = 2;
      int endTopic = ret.indexOf(':', startTopic + 1);
      int startPayload = endTopic + 1;
      int endPayload = ret.indexOf(':', startPayload + 1);
      String topic = ret.substring(startTopic, endTopic);
      String payload = ret.substring(startPayload, endPayload);
      messageReceived(topic, payload, (char*)payload.c_str(), payload.length());
    } else if(ret.startsWith("e")) {
      this->alive = false;
    }
  }
}

boolean YunMQTTClient::connected() {
  return this->alive;
}

void YunMQTTClient::disconnect() {
  // send disconnect request
  this->process.print("d\n");
}

#endif //ARDUINO_AVR_YUN
<commit_msg>fix bug<commit_after>#ifdef ARDUINO_AVR_YUN

#include "YunMQTTClient.h"

#include <FileIO.h>

YunMQTTClient::YunMQTTClient() {}

void YunMQTTClient::begin(const char * hostname) {
  this->begin(hostname, 1883);
}

void YunMQTTClient::begin(const char * hostname, int port) {
  this->hostname = hostname;
  this->port = port;
}

int YunMQTTClient::updateBridge() {
  Process p;

  int r1 = p.runShellCommand("mkdir -p /usr/arduino-mqtt");
  int r2 = p.runShellCommand("wget -N https://raw.githubusercontent.com/256dpi/arduino-mqtt/v1.8.0/yun/mqtt.py --no-check-certificate -P /usr/arduino-mqtt");
  int r3 = p.runShellCommand("wget -N https://raw.githubusercontent.com/256dpi/arduino-mqtt/v1.8.0/yun/bridge.py --no-check-certificate -P /usr/arduino-mqtt");

  boolean success = r1 == 0 && r2 == 0 && r3 == 0;

  if(success) {
    return 2;
  } else {
    return 0;
  }
}

void YunMQTTClient::setWill(const char * topic) {
  this->setWill(topic, "");
}

void YunMQTTClient::setWill(const char * topic, const char * payload) {
  this->willTopic = topic;
  this->willPayload = payload;
}

boolean YunMQTTClient::connect(const char * clientId) {
  return this->connect(clientId, "", "");
}

boolean YunMQTTClient::connect(const char * clientId, const char * username, const char * password) {
  if(this->updateBridge() == 0) {
    return false;
  }

  this->process.begin("python");
  this->process.addParameter("-u");
  this->process.addParameter("/usr/arduino-mqtt/bridge.py");
  this->process.runAsynchronously();
  this->process.setTimeout(10000);

  // wait for script to launch
  this->process.readStringUntil('\n');

  // set will if available
  if(this->willTopic != NULL) {
    this->process.print("w:");
    this->process.print(this->willTopic);
    if(this->willPayload != NULL) {
      this->process.print(':');
      this->process.print(this->willPayload);
    }
    this->process.print('\n');
  }

  // send connect request
  this->process.print("c:");
  this->process.print(this->hostname);
  this->process.print(':');
  this->process.print(this->port);
  this->process.print(':');
  this->process.print(clientId);
  if(strlen(username) > 0 && strlen(password) > 0) {
    this->process.print(':');
    this->process.print(username);
    this->process.print(':');
    this->process.print(password);
  }
  this->process.print('\n');

  // wait for answer
  String ret = this->process.readStringUntil('\n');
  this->alive = ret.equals("a");

  if(!this->alive) {
    this->process.close();
    return false;
  } else {
    return true;
  }
}

void YunMQTTClient::publish(String topic) {
  this->publish(topic.c_str(), "");
}

void YunMQTTClient::publish(String topic, String payload) {
  this->publish(topic.c_str(), payload.c_str());
}

void YunMQTTClient::publish(const char * topic, String payload) {
  this->publish(topic, payload.c_str());
}

void YunMQTTClient::publish(const char * topic, const char * payload) {
  // send publish request
  this->process.print("p:");
  this->process.print(topic);
  this->process.print(':');
  this->process.print(payload);
  this->process.print('\n');
}

void YunMQTTClient::subscribe(String topic) {
  this->subscribe(topic.c_str());
}

void YunMQTTClient::subscribe(const char * topic) {
  // send subscribe request
  this->process.print("s:");
  this->process.print(topic);
  this->process.print('\n');
}

void YunMQTTClient::unsubscribe(String topic) {
  this->unsubscribe(topic.c_str());
}

void YunMQTTClient::unsubscribe(const char * topic) {
  // send unsubscribe request
  this->process.print("u:");
  this->process.print(topic);
  this->process.print('\n');
}

void YunMQTTClient::loop() {
  int av = this->process.available();
  if(av > 0) {
    String ret = process.readStringUntil('\n');

    if(ret.startsWith("m")) {
      int startTopic = 2;
      int endTopic = ret.indexOf(':', startTopic + 1);
      int startPayload = endTopic + 1;
      int endPayload = ret.indexOf(':', startPayload + 1);
      String topic = ret.substring(startTopic, endTopic);
      String payload = ret.substring(startPayload, endPayload);
      messageReceived(topic, payload, (char*)payload.c_str(), payload.length());
    } else if(ret.startsWith("e")) {
      this->alive = false;
    }
  }
}

boolean YunMQTTClient::connected() {
  return this->alive;
}

void YunMQTTClient::disconnect() {
  // send disconnect request
  this->process.print("d\n");
}

#endif //ARDUINO_AVR_YUN
<|endoftext|>


<commit_before>#ifndef VG_ALGORITHMS_FIND_MIN_CUT_IN_GRAPH_HPP_INCLUDED
#define VG_ALGORITHMS_FIND_MIN_CUT_IN_GRAPH_HPP_INCLUDED

/**
 * \file min_cut_graph.hpp
 * A randomized, probabilistic algorithm that
 * finds the min cut on an undirected, weighted graph
 * that holds the indices of snarls
 */

#include <vector>
#include <utility>
#include <unordered_map>
#include <map>
#include <unordered_set>

namespace vg {
    namespace algorithms {

    using namespace std;

        struct Edge{
            int other; //node at other end
            int weight;
        };

        struct Node{
            int weight;
            vector<Edge> edges;
        };
        struct Graph {
            private:
            unordered_map<size_t,Node> nodes;

            public:
            inline vector<size_t> get_node_ids(){
                vector<size_t> node_ids;
                for (auto& id_and_node : nodes){
                    size_t node_id = id_and_node.first;
                    node_ids.push_back(node_id);
                }
                return node_ids;

            }

            inline size_t get_size(){
                return nodes.size();
            }

            inline Node get_node_by_id(size_t node_id){
                return nodes.at(node_id);
            }

            inline void add_node(size_t id, Node node){
                nodes.emplace(id, node);
            }

            inline size_t get_weight_using_other(Node prev_node, size_t other){
                size_t to_return;
                for(size_t i = 0; i < prev_node.edges.size(); i++){
                    if(prev_node.edges[i].other == other){
                        to_return = prev_node.edges[i].weight;
                    }
                }
                return to_return;

            }

        };

        pair<vector<unordered_set<size_t>>, size_t> kargers_min_cut(Graph graph, const int n_iterations, const int seed);

        pair<vector<unordered_set<size_t>>, size_t> compute_min_cut(Graph graph, const int n_iterations, const int seed);

        //Assumption: handles one connected component at a time
        //Assumption: all edge weights are > 0
        vector<unordered_set<size_t>> min_cut_decomposition(Graph graph, const int n_iterations, const int seed);

    }
}

#endif<commit_msg>return Node& in get_node_with_id and document get_weight_using other<commit_after>#ifndef VG_ALGORITHMS_FIND_MIN_CUT_IN_GRAPH_HPP_INCLUDED
#define VG_ALGORITHMS_FIND_MIN_CUT_IN_GRAPH_HPP_INCLUDED

/**
 * \file min_cut_graph.hpp
 * A randomized, probabilistic algorithm that
 * finds the min cut on an undirected, weighted graph
 * that holds the indices of snarls
 */

#include <vector>
#include <utility>
#include <unordered_map>
#include <map>
#include <unordered_set>

namespace vg {
    namespace algorithms {

    using namespace std;

        struct Edge{
            int other; //node at other end
            int weight;
        };

        struct Node{
            int weight;
            vector<Edge> edges;
        };
        struct Graph {
            private:
            unordered_map<size_t,Node> nodes;

            public:
            inline vector<size_t> get_node_ids(){
                vector<size_t> node_ids;
                for (auto& id_and_node : nodes){
                    size_t node_id = id_and_node.first;
                    node_ids.push_back(node_id);
                }
                return node_ids;

            }

            inline size_t get_size(){
                return nodes.size();
            }

            inline Node& get_node_by_id(size_t node_id){
                Node& node = nodes.at(node_id);
                return node;
            }

            inline void add_node(size_t id, Node node){
                nodes.emplace(id, node);
            }

            // only use this method for unittesting a linear graph with nodes that each contain biderectional edges between nodes
            // since the prev node points to current node, and current node points back to it
            // we can get the randomly generated edge weight for prev<-current from prev -> other (current)
            inline size_t get_weight_using_other(Node prev_node, size_t other){
                size_t to_return;
                for(size_t i = 0; i < prev_node.edges.size(); i++){
                    if(prev_node.edges[i].other == other){
                        to_return = prev_node.edges[i].weight;
                    }
                }
                return to_return;

            }

        };

        pair<vector<unordered_set<size_t>>, size_t> kargers_min_cut(Graph graph, const int n_iterations, const int seed);

        pair<vector<unordered_set<size_t>>, size_t> compute_min_cut(Graph graph, const int n_iterations, const int seed);

        //Assumption: handles one connected component at a time
        //Assumption: all edge weights are > 0
        vector<unordered_set<size_t>> min_cut_decomposition(Graph graph, const int n_iterations, const int seed);

    }
}

#endif<|endoftext|>


<commit_before>#include "SimpleITKTestHarness.h"

#include <sitkImage.h>
#include <sitkImageFileReader.h>
#include <sitkImageFileWriter.h>
#include <sitkImageHashFilter.h>

TEST_F(Lua,SimpleGaussian) {
  // Run the simple gaussian command line program
  std::string Script = dataFinder.GetSourceDirectory() + "/Examples/SimpleGaussian.lua";
  std::string output = dataFinder.GetOutputFile ( "Lua.SimpleGaussian.nrrd" );
  std::vector<std::string> CommandLine;

  CommandLine.push_back ( dataFinder.GetLuaExecutable() );
  CommandLine.push_back ( Script );
  CommandLine.push_back ( dataFinder.GetFile ( "Input/RA-Short.nrrd" ).c_str() );
  CommandLine.push_back ( "2.0" );
  CommandLine.push_back ( output );

  // Run it!
  RunExecutable ( CommandLine, true );
  ASSERT_TRUE ( dataFinder.FileExists ( output ) );
  itk::simple::ImageFileReader reader;
  itk::simple::ImageHashFilter hasher;
  itk::simple::Image::Pointer image;

  image = reader.SetFileName ( output ).Execute();
  ASSERT_TRUE ( image->GetImageBase().IsNotNull() ) << "Loaded output image";
  EXPECT_EQ ( "9d3d4acf41aa62b453cfd6684ad7c361290462d1", hasher.Execute ( image ) );

}
<commit_msg>BUG: only run Lua.SimpleGaussian test when wrapping for lua is enabled<commit_after>#include "SimpleITKTestHarness.h"

#include <sitkImage.h>
#include <sitkImageFileReader.h>
#include <sitkImageFileWriter.h>
#include <sitkImageHashFilter.h>

#if defined(WRAP_LUA)
TEST_F(Lua,SimpleGaussian) {
  // Run the simple gaussian command line program
  std::string Script = dataFinder.GetSourceDirectory() + "/Examples/SimpleGaussian.lua";
  std::string output = dataFinder.GetOutputFile ( "Lua.SimpleGaussian.nrrd" );
  std::vector<std::string> CommandLine;

  CommandLine.push_back ( dataFinder.GetLuaExecutable() );
  CommandLine.push_back ( Script );
  CommandLine.push_back ( dataFinder.GetFile ( "Input/RA-Short.nrrd" ).c_str() );
  CommandLine.push_back ( "2.0" );
  CommandLine.push_back ( output );

  // Run it!
  RunExecutable ( CommandLine, true );
  ASSERT_TRUE ( dataFinder.FileExists ( output ) );
  itk::simple::ImageFileReader reader;
  itk::simple::ImageHashFilter hasher;
  itk::simple::Image::Pointer image;

  image = reader.SetFileName ( output ).Execute();
  ASSERT_TRUE ( image->GetImageBase().IsNotNull() ) << "Loaded output image";
  EXPECT_EQ ( "9d3d4acf41aa62b453cfd6684ad7c361290462d1", hasher.Execute ( image ) );

}
#endif
<|endoftext|>


<commit_before><commit_msg>[test.la.solver] update, due to f413f8d<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: selectioncontroller.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 09:48:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#include <svx/selectioncontroller.hxx>

namespace sdr
{

bool SelectionController::onKeyInput(const KeyEvent& /*rKEvt*/, Window* /*pWin*/)
{
    return false;
}

bool SelectionController::onMouseButtonDown(const MouseEvent& /*rMEvt*/, Window* /*pWin*/)
{
    return false;
}

bool SelectionController::onMouseButtonUp(const MouseEvent& /*rMEvt*/, Window* /*pWin*/)
{
    return false;
}

bool SelectionController::onMouseMove(const MouseEvent& /*rMEvt*/, Window* /*pWin*/)
{
    return false;
}

void SelectionController::onSelectionHasChanged()
{
}

void SelectionController::GetState( SfxItemSet& /*rSet*/ )
{
}

void SelectionController::Execute( SfxRequest& /*rReq*/ )
{
}

bool SelectionController::DeleteMarked()
{
    return false;
}

bool SelectionController::GetAttributes(SfxItemSet& /*rTargetSet*/, bool /*bOnlyHardAttr*/) const
{
    return false;
}

bool SelectionController::SetAttributes(const SfxItemSet& /*rSet*/, bool /*bReplaceAll*/)
{
    return false;
}

bool SelectionController::GetStyleSheet( SfxStyleSheet* &/*rpStyleSheet*/ ) const
{
    return false;
}

bool SelectionController::SetStyleSheet( SfxStyleSheet* /*pStyleSheet*/, bool /*bDontRemoveHardAttr*/ )
{
    return false;
}

bool SelectionController::GetMarkedObjModel( SdrPage* /*pNewPage*/ )
{
    return false;
}

bool SelectionController::PasteObjModel( const SdrModel& /*rModel*/ )
{
    return false;
}

}
<commit_msg>INTEGRATION: CWS changefileheader (1.2.36); FILE MERGED 2008/03/31 14:23:28 rt 1.2.36.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: selectioncontroller.cxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#include <svx/selectioncontroller.hxx>

namespace sdr
{

bool SelectionController::onKeyInput(const KeyEvent& /*rKEvt*/, Window* /*pWin*/)
{
    return false;
}

bool SelectionController::onMouseButtonDown(const MouseEvent& /*rMEvt*/, Window* /*pWin*/)
{
    return false;
}

bool SelectionController::onMouseButtonUp(const MouseEvent& /*rMEvt*/, Window* /*pWin*/)
{
    return false;
}

bool SelectionController::onMouseMove(const MouseEvent& /*rMEvt*/, Window* /*pWin*/)
{
    return false;
}

void SelectionController::onSelectionHasChanged()
{
}

void SelectionController::GetState( SfxItemSet& /*rSet*/ )
{
}

void SelectionController::Execute( SfxRequest& /*rReq*/ )
{
}

bool SelectionController::DeleteMarked()
{
    return false;
}

bool SelectionController::GetAttributes(SfxItemSet& /*rTargetSet*/, bool /*bOnlyHardAttr*/) const
{
    return false;
}

bool SelectionController::SetAttributes(const SfxItemSet& /*rSet*/, bool /*bReplaceAll*/)
{
    return false;
}

bool SelectionController::GetStyleSheet( SfxStyleSheet* &/*rpStyleSheet*/ ) const
{
    return false;
}

bool SelectionController::SetStyleSheet( SfxStyleSheet* /*pStyleSheet*/, bool /*bDontRemoveHardAttr*/ )
{
    return false;
}

bool SelectionController::GetMarkedObjModel( SdrPage* /*pNewPage*/ )
{
    return false;
}

bool SelectionController::PasteObjModel( const SdrModel& /*rModel*/ )
{
    return false;
}

}
<|endoftext|>


<commit_before>#include <algorithm>
#include <cmath>
#include <vector>
#include <Eigen/Dense>
#include "bicycle/bicycle.h"
#include "control_design_functions.h"
#include "firmware_generator.h"
#include "robot_bicycle_parameters.h"

int main(int argc, char ** argv)
{
  if (argc != 2) {
    std::cout << "Filename must be supplied\n";
    return -1;
  }
  std::string filename_base(argv[1]);

  bicycle::Bicycle rb = bicycle::robot_bicycle();

  design_parameters params;
  params.N = 11;
  params.Ts = 0.005;
  params.lowest_speed = 0.5;
  params.highest_speed = 10.0;
  // LQR design parameters
  constexpr double pi = M_PI;
  params.Q = Eigen::MatrixXd::Zero(4, 4);
  params.Q(0, 0) = std::pow(30*pi/180, -2.0);
  params.Q(1, 1) = std::pow(30*pi/180, -2.0);
  params.Q(2, 2) = std::pow(200*pi/180, -2.0);
  params.Q(3, 3) = std::pow(200*pi/180, -2.0);
  params.R.resize(1, 1);
  params.R << std::pow(6.0*.75, -2.0);
  params.pole_placement_factor = 3.0;

  std::vector<model_data> md = design_controller(params, rb);
  std::sort(md.begin(), md.end());
  firmware_generator(md, filename_base);
}

<commit_msg>Output 101 speeds instead of 11.<commit_after>#include <algorithm>
#include <cmath>
#include <vector>
#include <Eigen/Dense>
#include "bicycle/bicycle.h"
#include "control_design_functions.h"
#include "firmware_generator.h"
#include "robot_bicycle_parameters.h"

int main(int argc, char ** argv)
{
  if (argc != 2) {
    std::cout << "Filename must be supplied\n";
    return -1;
  }
  std::string filename_base(argv[1]);

  bicycle::Bicycle rb = bicycle::robot_bicycle();

  design_parameters params;
  params.N = 101;
  params.Ts = 0.005;
  params.lowest_speed = 0.5;
  params.highest_speed = 10.0;
  // LQR design parameters
  constexpr double pi = M_PI;
  params.Q = Eigen::MatrixXd::Zero(4, 4);
  params.Q(0, 0) = std::pow(30*pi/180, -2.0);
  params.Q(1, 1) = std::pow(30*pi/180, -2.0);
  params.Q(2, 2) = std::pow(200*pi/180, -2.0);
  params.Q(3, 3) = std::pow(200*pi/180, -2.0);
  params.R.resize(1, 1);
  params.R << std::pow(6.0*.75, -2.0);
  params.pole_placement_factor = 3.0;

  std::vector<model_data> md = design_controller(params, rb);
  std::sort(md.begin(), md.end());
  firmware_generator(md, filename_base);
}

<|endoftext|>


<commit_before>#ifndef __MAPNIK_VECTOR_TILE_GEOMETRY_ENCODER_H__
#define __MAPNIK_VECTOR_TILE_GEOMETRY_ENCODER_H__

// vector tile
#include "vector_tile.pb.h"
#include <mapnik/vertex.hpp>
#include "vector_tile_config.hpp"

#include <cstdlib>
#include <cmath>
#include <sstream>

namespace mapnik { namespace vector_tile_impl {

MAPNIK_VECTOR_INLINE void handle_skipped_last(vector_tile::Tile_Feature & current_feature,
                                int32_t skipped_index,
                                int32_t cur_x,
                                int32_t cur_y,
                                int32_t & x_,
                                int32_t & y_);

void rollback_geom(vector_tile::Tile_Feature & current_feature, unsigned idx)
{
   auto geom = current_feature.mutable_geometry();
   while (idx < current_feature.geometry_size())
   {
        geom->RemoveLast();
   }
}

template <typename T>
inline unsigned encode_geometry(T & path,
                         vector_tile::Tile_Feature & current_feature,
                         int32_t & x_,
                         int32_t & y_,
                         unsigned tolerance,
                         unsigned path_multiplier)
{
    bool is_polygon = (current_feature.type() == vector_tile::Tile_GeomType_POLYGON);
    bool is_line_string = (current_feature.type() == vector_tile::Tile_GeomType_LINESTRING);
    bool working_on_exterior_ring = is_polygon;
    unsigned verts = 0;
    unsigned count = 0;
    path.rewind(0);
    unsigned first_geom_idx = current_feature.geometry_size();

    vertex2d vtx(vertex2d::no_init);
    int cmd = -1;
    int prev_cmd = -1;
    int cmd_idx = -1;
    const int cmd_bits = 3;
    unsigned length = 0;
    bool skipped_last = false;
    int32_t skipped_index = -1;
    int32_t cur_x = 0;
    int32_t cur_y = 0;

    // See vector_tile.proto for a description of how vertex command
    // encoding works.

    std::vector<vertex2d> output;
    const std::size_t buffer_size = 8;
    output.reserve(buffer_size);
    bool done = false;
    bool cache = true;
    while (true)
    {
        if (cache)
        {
            // read
            vertex2d v(vertex2d::no_init);
            while ((v.cmd = path.vertex(&v.x, &v.y)) != SEG_END)
            {
                output.push_back(std::move(v));
                if (output.size() == buffer_size) break;
            }
            cache = false;
            if (v.cmd == SEG_END)
            {
                done = true;
            }
        }
        else
        {
            if (done && output.empty()) break;
            // process
            vtx = output.front();
            {
                if (static_cast<int>(vtx.cmd) != cmd)
                {
                    if (cmd_idx >= 0)
                    {
                        // Encode the previous length/command value.
                        current_feature.set_geometry(cmd_idx, (length << cmd_bits) | (cmd & ((1 << cmd_bits) - 1)));
                        // abort on degenerate exterior ring of polygon
                        if (working_on_exterior_ring && cmd == SEG_CLOSE)
                        {
                            working_on_exterior_ring = false;
                            if (verts < 4)
                            {
                                rollback_geom(current_feature,first_geom_idx);
                                return 0;
                            }
                        }
                    }
                    cmd = static_cast<int>(vtx.cmd);
                    length = 0;
                    cmd_idx = current_feature.geometry_size();
                    current_feature.add_geometry(0); // placeholder added in first pass
                }

                switch (vtx.cmd)
                {
                case SEG_MOVETO:
                case SEG_LINETO:
                {
                    if (cmd == SEG_MOVETO && skipped_last && skipped_index > 1) // at least one vertex + cmd/length
                    {
                        // if we skipped previous vertex we just update it to the last one here.
                        handle_skipped_last(current_feature, skipped_index, cur_x, cur_y,  x_, y_);
                    }

                    // Compute delta to the previous coordinate.
                    cur_x = static_cast<int32_t>(std::floor((vtx.x * path_multiplier) + 0.5));
                    cur_y = static_cast<int32_t>(std::floor((vtx.y * path_multiplier) + 0.5));
                    int32_t dx = cur_x - x_;
                    int32_t dy = cur_y - y_;
                    // we try hard not to collapse corners that
                    // may have resulted from clipping
                    bool next_segment_axis_aligned = false;
                    auto output_size = output.size();
                    if (output_size > 1)
                    {
                        vertex2d const& next_vtx = output[1];
                        if (next_vtx.cmd == SEG_LINETO)
                        {
                            uint32_t next_dx = std::abs(cur_x - static_cast<int32_t>(std::floor((next_vtx.x * path_multiplier) + 0.5)));
                            uint32_t next_dy = std::abs(cur_y - static_cast<int32_t>(std::floor((next_vtx.y * path_multiplier) + 0.5)));
                            if ((next_dx == 0 && next_dy >= tolerance) || (next_dy == 0 && next_dx >= tolerance))
                            {
                                next_segment_axis_aligned = true;
                            }
                        }
                    }
                    // Keep all move_to commands, but omit other movements that are
                    // not >= the tolerance threshold and should be considered no-ops.
                    // NOTE: length == 0 indicates the command has changed and will
                    // preserve any non duplicate move_to or line_to
                    if ( length == 0 || next_segment_axis_aligned ||
                         (static_cast<unsigned>(std::abs(dx)) >= tolerance) ||
                         (static_cast<unsigned>(std::abs(dy)) >= tolerance)
                        )
                    {
                        // Manual zigzag encoding.
                        current_feature.add_geometry((dx << 1) ^ (dx >> 31));
                        current_feature.add_geometry((dy << 1) ^ (dy >> 31));
                        x_ = cur_x;
                        y_ = cur_y;
                        skipped_last = false;
                        ++length;
                    }
                    else
                    {
                        skipped_last = true;
                        skipped_index = current_feature.geometry_size();
                    }
                    break;
                }

                case SEG_CLOSE:
                {
                    if (prev_cmd != SEG_CLOSE) ++length;
                    break;
                }
                default:
                    std::stringstream msg;
                    msg << "Unknown command type (backend_pbf): "
                        << cmd;
                    throw std::runtime_error(msg.str());
                    break;
                }
            }
            ++count;
            ++verts;
            prev_cmd = cmd;
            output.erase(output.begin());
            if (output.size() < 2) cache = true;
        }
    }
    if (skipped_last && skipped_index > 1) // at least one vertex + cmd/length
    {
        // if we skipped previous vertex we just update it to the last one here.
        handle_skipped_last(current_feature, skipped_index, cur_x, cur_y, x_, y_);
    }
    // Update the last length/command value.
    if (cmd_idx >= 0)
    {
        current_feature.set_geometry(cmd_idx, (length << cmd_bits) | (cmd & ((1 << cmd_bits) - 1)));
        // abort on degenerate exterior ring of polygon
        if (working_on_exterior_ring && cmd == SEG_CLOSE)
        {
            working_on_exterior_ring = false;
            if (verts < 4)
            {
                rollback_geom(current_feature,first_geom_idx);
                return 0;
            }
        }
        // abort on degenerate line
        else if (is_line_string && verts < 2)
        {
            rollback_geom(current_feature,first_geom_idx);
            return 0;
        }
    }
    return count;
}

}} // end ns

#if !defined(MAPNIK_VECTOR_TILE_LIBRARY)
#include "vector_tile_geometry_encoder.ipp"
#endif

#endif // __MAPNIK_VECTOR_TILE_GEOMETRY_ENCODER_H__
<commit_msg>fix -Wsign-compare warning<commit_after>#ifndef __MAPNIK_VECTOR_TILE_GEOMETRY_ENCODER_H__
#define __MAPNIK_VECTOR_TILE_GEOMETRY_ENCODER_H__

// vector tile
#include "vector_tile.pb.h"
#include <mapnik/vertex.hpp>
#include "vector_tile_config.hpp"

#include <cstdlib>
#include <cmath>
#include <sstream>

namespace mapnik { namespace vector_tile_impl {

MAPNIK_VECTOR_INLINE void handle_skipped_last(vector_tile::Tile_Feature & current_feature,
                                int32_t skipped_index,
                                int32_t cur_x,
                                int32_t cur_y,
                                int32_t & x_,
                                int32_t & y_);

void rollback_geom(vector_tile::Tile_Feature & current_feature, unsigned idx)
{
   auto num_geometries = current_feature.geometry_size();
   if (num_geometries > 0)
   {
        unsigned num_geometries2 = static_cast<unsigned>(num_geometries);
        if (num_geometries2 > idx)
        {
            auto geom = current_feature.mutable_geometry();
            while (idx < static_cast<unsigned>(num_geometries2))
            {
                geom->RemoveLast();
                --num_geometries2;
            }
        }
   }
}

template <typename T>
inline unsigned encode_geometry(T & path,
                         vector_tile::Tile_Feature & current_feature,
                         int32_t & x_,
                         int32_t & y_,
                         unsigned tolerance,
                         unsigned path_multiplier)
{
    bool is_polygon = (current_feature.type() == vector_tile::Tile_GeomType_POLYGON);
    bool is_line_string = (current_feature.type() == vector_tile::Tile_GeomType_LINESTRING);
    bool working_on_exterior_ring = is_polygon;
    unsigned verts = 0;
    unsigned count = 0;
    path.rewind(0);
    unsigned first_geom_idx = current_feature.geometry_size();

    vertex2d vtx(vertex2d::no_init);
    int cmd = -1;
    int prev_cmd = -1;
    int cmd_idx = -1;
    const int cmd_bits = 3;
    unsigned length = 0;
    bool skipped_last = false;
    int32_t skipped_index = -1;
    int32_t cur_x = 0;
    int32_t cur_y = 0;

    // See vector_tile.proto for a description of how vertex command
    // encoding works.

    std::vector<vertex2d> output;
    const std::size_t buffer_size = 8;
    output.reserve(buffer_size);
    bool done = false;
    bool cache = true;
    while (true)
    {
        if (cache)
        {
            // read
            vertex2d v(vertex2d::no_init);
            while ((v.cmd = path.vertex(&v.x, &v.y)) != SEG_END)
            {
                output.push_back(std::move(v));
                if (output.size() == buffer_size) break;
            }
            cache = false;
            if (v.cmd == SEG_END)
            {
                done = true;
            }
        }
        else
        {
            if (done && output.empty()) break;
            // process
            vtx = output.front();
            {
                if (static_cast<int>(vtx.cmd) != cmd)
                {
                    if (cmd_idx >= 0)
                    {
                        // Encode the previous length/command value.
                        current_feature.set_geometry(cmd_idx, (length << cmd_bits) | (cmd & ((1 << cmd_bits) - 1)));
                        // abort on degenerate exterior ring of polygon
                        if (working_on_exterior_ring && cmd == SEG_CLOSE)
                        {
                            working_on_exterior_ring = false;
                            if (verts < 4)
                            {
                                rollback_geom(current_feature,first_geom_idx);
                                return 0;
                            }
                        }
                    }
                    cmd = static_cast<int>(vtx.cmd);
                    length = 0;
                    cmd_idx = current_feature.geometry_size();
                    current_feature.add_geometry(0); // placeholder added in first pass
                }

                switch (vtx.cmd)
                {
                case SEG_MOVETO:
                case SEG_LINETO:
                {
                    if (cmd == SEG_MOVETO && skipped_last && skipped_index > 1) // at least one vertex + cmd/length
                    {
                        // if we skipped previous vertex we just update it to the last one here.
                        handle_skipped_last(current_feature, skipped_index, cur_x, cur_y,  x_, y_);
                    }

                    // Compute delta to the previous coordinate.
                    cur_x = static_cast<int32_t>(std::floor((vtx.x * path_multiplier) + 0.5));
                    cur_y = static_cast<int32_t>(std::floor((vtx.y * path_multiplier) + 0.5));
                    int32_t dx = cur_x - x_;
                    int32_t dy = cur_y - y_;
                    // we try hard not to collapse corners that
                    // may have resulted from clipping
                    bool next_segment_axis_aligned = false;
                    auto output_size = output.size();
                    if (output_size > 1)
                    {
                        vertex2d const& next_vtx = output[1];
                        if (next_vtx.cmd == SEG_LINETO)
                        {
                            uint32_t next_dx = std::abs(cur_x - static_cast<int32_t>(std::floor((next_vtx.x * path_multiplier) + 0.5)));
                            uint32_t next_dy = std::abs(cur_y - static_cast<int32_t>(std::floor((next_vtx.y * path_multiplier) + 0.5)));
                            if ((next_dx == 0 && next_dy >= tolerance) || (next_dy == 0 && next_dx >= tolerance))
                            {
                                next_segment_axis_aligned = true;
                            }
                        }
                    }
                    // Keep all move_to commands, but omit other movements that are
                    // not >= the tolerance threshold and should be considered no-ops.
                    // NOTE: length == 0 indicates the command has changed and will
                    // preserve any non duplicate move_to or line_to
                    if ( length == 0 || next_segment_axis_aligned ||
                         (static_cast<unsigned>(std::abs(dx)) >= tolerance) ||
                         (static_cast<unsigned>(std::abs(dy)) >= tolerance)
                        )
                    {
                        // Manual zigzag encoding.
                        current_feature.add_geometry((dx << 1) ^ (dx >> 31));
                        current_feature.add_geometry((dy << 1) ^ (dy >> 31));
                        x_ = cur_x;
                        y_ = cur_y;
                        skipped_last = false;
                        ++length;
                    }
                    else
                    {
                        skipped_last = true;
                        skipped_index = current_feature.geometry_size();
                    }
                    break;
                }

                case SEG_CLOSE:
                {
                    if (prev_cmd != SEG_CLOSE) ++length;
                    break;
                }
                default:
                    std::stringstream msg;
                    msg << "Unknown command type (backend_pbf): "
                        << cmd;
                    throw std::runtime_error(msg.str());
                    break;
                }
            }
            ++count;
            ++verts;
            prev_cmd = cmd;
            output.erase(output.begin());
            if (output.size() < 2) cache = true;
        }
    }
    if (skipped_last && skipped_index > 1) // at least one vertex + cmd/length
    {
        // if we skipped previous vertex we just update it to the last one here.
        handle_skipped_last(current_feature, skipped_index, cur_x, cur_y, x_, y_);
    }
    // Update the last length/command value.
    if (cmd_idx >= 0)
    {
        current_feature.set_geometry(cmd_idx, (length << cmd_bits) | (cmd & ((1 << cmd_bits) - 1)));
        // abort on degenerate exterior ring of polygon
        if (working_on_exterior_ring && cmd == SEG_CLOSE)
        {
            working_on_exterior_ring = false;
            if (verts < 4)
            {
                rollback_geom(current_feature,first_geom_idx);
                return 0;
            }
        }
        // abort on degenerate line
        else if (is_line_string && verts < 2)
        {
            rollback_geom(current_feature,first_geom_idx);
            return 0;
        }
    }
    return count;
}

}} // end ns

#if !defined(MAPNIK_VECTOR_TILE_LIBRARY)
#include "vector_tile_geometry_encoder.ipp"
#endif

#endif // __MAPNIK_VECTOR_TILE_GEOMETRY_ENCODER_H__
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/string_util.h"
#if defined(OS_WIN)
#include "base/win_util.h"
#endif  // defined(OS_WIN)
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/url_request/url_request_unittest.h"

class ErrorPageTest : public UITest {
 protected:
  bool WaitForTitleMatching(const std::wstring& title) {
    for (int i = 0; i < 100; ++i) {
      if (GetActiveTabTitle() == title)
        return true;
      PlatformThread::Sleep(sleep_timeout_ms() / 10);
    }
    EXPECT_EQ(title, GetActiveTabTitle());
    return false;
  }
};

TEST_F(ErrorPageTest, DNSError_Basic) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

TEST_F(ErrorPageTest, DNSError_GoBack1) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, DNSError_GoBack2) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, DNSError_GoBack2AndForward) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.

  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());
  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

TEST_F(ErrorPageTest, DNSError_GoBack2Forward2) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.

  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());
  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoForward());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
  EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}

TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in an iframe does not result in an
  // additional session history entry.

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

// Flaky on Linux too.
TEST_F(ErrorPageTest, FLAKY_IFrameDNSError_GoBackAndForward) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in an iframe does not result in an
  // additional session history entry.

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));

  EXPECT_TRUE(GetActiveTab()->GoBack());
  EXPECT_TRUE(GetActiveTab()->GoForward());

  EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}

TEST_F(ErrorPageTest, IFrame404) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // iframes that have 404 pages should not trigger an alternate error page.
  // In this test, the iframe sets the title of the parent page to "SUCCESS"
  // when the iframe loads.  If the iframe fails to load (because an alternate
  // error page loads instead), then the title will remain as "FAIL".
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(L"chrome/test/data", NULL);
  ASSERT_TRUE(NULL != server.get());
  GURL test_url = server->TestServerPage("files/iframe404.html");
  NavigateToURL(test_url);

  EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}

TEST_F(ErrorPageTest, Page404) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(
      URLRequestMockHTTPJob::GetMockUrl(
          FilePath(FILE_PATH_LITERAL("page404.html"))), 2);

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

TEST_F(ErrorPageTest, Page404_GoBack) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(
      URLRequestMockHTTPJob::GetMockUrl(
          FilePath(FILE_PATH_LITERAL("page404.html"))), 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
<commit_msg>Mark Page404_GoBack as flaky on linux<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/string_util.h"
#if defined(OS_WIN)
#include "base/win_util.h"
#endif  // defined(OS_WIN)
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/url_request/url_request_unittest.h"

class ErrorPageTest : public UITest {
 protected:
  bool WaitForTitleMatching(const std::wstring& title) {
    for (int i = 0; i < 100; ++i) {
      if (GetActiveTabTitle() == title)
        return true;
      PlatformThread::Sleep(sleep_timeout_ms() / 10);
    }
    EXPECT_EQ(title, GetActiveTabTitle());
    return false;
  }
};

TEST_F(ErrorPageTest, DNSError_Basic) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

TEST_F(ErrorPageTest, DNSError_GoBack1) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, DNSError_GoBack2) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, DNSError_GoBack2AndForward) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.

  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());
  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

TEST_F(ErrorPageTest, DNSError_GoBack2Forward2) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.

  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());
  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoForward());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
  EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}

TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in an iframe does not result in an
  // additional session history entry.

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

// Flaky on Linux too.
TEST_F(ErrorPageTest, FLAKY_IFrameDNSError_GoBackAndForward) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // Test that a DNS error occuring in an iframe does not result in an
  // additional session history entry.

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));

  EXPECT_TRUE(GetActiveTab()->GoBack());
  EXPECT_TRUE(GetActiveTab()->GoForward());

  EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}

TEST_F(ErrorPageTest, IFrame404) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  // iframes that have 404 pages should not trigger an alternate error page.
  // In this test, the iframe sets the title of the parent page to "SUCCESS"
  // when the iframe loads.  If the iframe fails to load (because an alternate
  // error page loads instead), then the title will remain as "FAIL".
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(L"chrome/test/data", NULL);
  ASSERT_TRUE(NULL != server.get());
  GURL test_url = server->TestServerPage("files/iframe404.html");
  NavigateToURL(test_url);

  EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}

TEST_F(ErrorPageTest, Page404) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(
      URLRequestMockHTTPJob::GetMockUrl(
          FilePath(FILE_PATH_LITERAL("page404.html"))), 2);

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

#if defined(OS_LINUX)
// Below explains this is flaky on XP, but it also flakes out on Linux.
// http://crbug.com/19361
#define Page404_GoBack FLAKY_Page404_GoBack
#endif

TEST_F(ErrorPageTest, Page404_GoBack) {
#if defined(OS_WIN)
  // Flaky on XP, http://crbug.com/19361.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    return;
#endif  // defined(OS_WIN)
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(
      URLRequestMockHTTPJob::GetMockUrl(
          FilePath(FILE_PATH_LITERAL("page404.html"))), 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
<|endoftext|>