<commit_before>/*

Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.

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

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

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

*/

#ifndef DISTANCE_TABLE_PLUGIN_H
#define DISTANCE_TABLE_PLUGIN_H

#include "plugin_base.hpp"

#include "../algorithms/object_encoder.hpp"
#include "../data_structures/json_container.hpp"
#include "../data_structures/query_edge.hpp"
#include "../data_structures/search_engine.hpp"
#include "../descriptors/descriptor_base.hpp"
#include "../Util/json_renderer.hpp"
#include "../Util/make_unique.hpp"
#include "../Util/StringUtil.h"
#include "../Util/timing_util.hpp"

#include <cstdlib>

#include <algorithm>
#include <memory>
#include <unordered_map>
#include <string>
#include <vector>

template <class DataFacadeT> class DistanceTablePlugin final : public BasePlugin
{
  private:
    std::unique_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;

  public:
    explicit DistanceTablePlugin(DataFacadeT *facade) : descriptor_string("table"), facade(facade)
    {
        search_engine_ptr = osrm::make_unique<SearchEngine<DataFacadeT>>(facade);
    }

    virtual ~DistanceTablePlugin() {}

    const std::string GetDescriptor() const final { return descriptor_string; }

    void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final
    {
        if (!check_all_coordinates(route_parameters.coordinates))
        {
            reply = http::Reply::StockReply(http::Reply::badRequest);
            return;
        }

        // const bool checksum_OK = (route_parameters.check_sum == facade->GetCheckSum());
        unsigned max_locations =
            std::min(100u, static_cast<unsigned>(route_parameters.coordinates.size()));
        PhantomNodeArray phantom_node_vector(max_locations);
        for (const auto i : osrm::irange(0u, max_locations))
        {
            // if (checksum_OK && i < route_parameters.hints.size() &&
            //     !route_parameters.hints[i].empty())
            // {
            //     PhantomNode current_phantom_node;
            //     ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node);
            //     if (current_phantom_node.is_valid(facade->GetNumberOfNodes()))
            //     {
            //         phantom_node_vector[i].emplace_back(std::move(current_phantom_node));
            //         continue;
            //     }
            // }
            facade->IncrementalFindPhantomNodeForCoordinate(route_parameters.coordinates[i],
                                                            phantom_node_vector[i],
                                                            1);

            BOOST_ASSERT(phantom_node_vector[i].front().is_valid(facade->GetNumberOfNodes()));
        }

        // TIMER_START(distance_table);
        std::shared_ptr<std::vector<EdgeWeight>> result_table =
            search_engine_ptr->distance_table(phantom_node_vector);
        // TIMER_STOP(distance_table);

        if (!result_table)
        {
            reply = http::Reply::StockReply(http::Reply::badRequest);
            return;
        }

        JSON::Object json_object;
        JSON::Array json_array;
        const auto number_of_locations = phantom_node_vector.size();
        for (const auto row : osrm::irange<std::size_t>(0, number_of_locations))
        {
            JSON::Array json_row;
            auto row_begin_iterator = result_table->begin() + (row * number_of_locations);
            auto row_end_iterator = result_table->begin() + ((row + 1) * number_of_locations);
            json_row.values.insert(json_row.values.end(), row_begin_iterator, row_end_iterator);
            json_array.values.push_back(json_row);
        }
        json_object.values["distance_table"] = json_array;
        JSON::render(reply.content, json_object);
    }

  private:
    std::string descriptor_string;
    DataFacadeT *facade;
};

#endif // DISTANCE_TABLE_PLUGIN_H
<commit_msg>remove debug code<commit_after>/*

Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.

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

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

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

*/

#ifndef DISTANCE_TABLE_PLUGIN_H
#define DISTANCE_TABLE_PLUGIN_H

#include "plugin_base.hpp"

#include "../algorithms/object_encoder.hpp"
#include "../data_structures/json_container.hpp"
#include "../data_structures/query_edge.hpp"
#include "../data_structures/search_engine.hpp"
#include "../descriptors/descriptor_base.hpp"
#include "../Util/json_renderer.hpp"
#include "../Util/make_unique.hpp"
#include "../Util/StringUtil.h"
#include "../Util/timing_util.hpp"

#include <cstdlib>

#include <algorithm>
#include <memory>
#include <unordered_map>
#include <string>
#include <vector>

template <class DataFacadeT> class DistanceTablePlugin final : public BasePlugin
{
  private:
    std::unique_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;

  public:
    explicit DistanceTablePlugin(DataFacadeT *facade) : descriptor_string("table"), facade(facade)
    {
        search_engine_ptr = osrm::make_unique<SearchEngine<DataFacadeT>>(facade);
    }

    virtual ~DistanceTablePlugin() {}

    const std::string GetDescriptor() const final { return descriptor_string; }

    void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final
    {
        if (!check_all_coordinates(route_parameters.coordinates))
        {
            reply = http::Reply::StockReply(http::Reply::badRequest);
            return;
        }

        // const bool checksum_OK = (route_parameters.check_sum == facade->GetCheckSum());
        unsigned max_locations =
            std::min(100u, static_cast<unsigned>(route_parameters.coordinates.size()));
        PhantomNodeArray phantom_node_vector(max_locations);
        for (const auto i : osrm::irange(0u, max_locations))
        {
            facade->IncrementalFindPhantomNodeForCoordinate(route_parameters.coordinates[i],
                                                            phantom_node_vector[i],
                                                            1);

            BOOST_ASSERT(phantom_node_vector[i].front().is_valid(facade->GetNumberOfNodes()));
        }

        // TIMER_START(distance_table);
        std::shared_ptr<std::vector<EdgeWeight>> result_table =
            search_engine_ptr->distance_table(phantom_node_vector);
        // TIMER_STOP(distance_table);

        if (!result_table)
        {
            reply = http::Reply::StockReply(http::Reply::badRequest);
            return;
        }

        JSON::Object json_object;
        JSON::Array json_array;
        const auto number_of_locations = phantom_node_vector.size();
        for (const auto row : osrm::irange<std::size_t>(0, number_of_locations))
        {
            JSON::Array json_row;
            auto row_begin_iterator = result_table->begin() + (row * number_of_locations);
            auto row_end_iterator = result_table->begin() + ((row + 1) * number_of_locations);
            json_row.values.insert(json_row.values.end(), row_begin_iterator, row_end_iterator);
            json_array.values.push_back(json_row);
        }
        json_object.values["distance_table"] = json_array;
        JSON::render(reply.content, json_object);
    }

  private:
    std::string descriptor_string;
    DataFacadeT *facade;
};

#endif // DISTANCE_TABLE_PLUGIN_H
<|endoftext|>


<commit_before>#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <cstring>
#include <fstream>
using namespace std;

#define all(o) (o).begin(), (o).end()
#define allr(o) (o).rbegin(), (o).rend()
#define INF 2147483647
typedef long long ll;
typedef pair<int, int> ii;
template <class T> int size(T x) { return x.size(); }<commit_msg>Made header a singleton.<commit_after>#ifndef MAIN_HEADER
#define MAIN_HEADER
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <cstring>
#include <fstream>
using namespace std;

#define all(o) (o).begin(), (o).end()
#define allr(o) (o).rbegin(), (o).rend()
#define INF 2147483647
typedef long long ll;
typedef pair<int, int> ii;
template <class T> int size(T x) { return x.size(); }
#endif
<|endoftext|>


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

namespace KDots
{
	namespace simpleai
	{
		Rival::Rival (QObject *parent)
			: IRival (parent)
			, m_table (NULL)
		{
			PriorityMap::instance ();
		}

		bool Rival::isAllow () const
		{
			if (!m_table)
				return false;

			return m_table->stepQueue ()->getCurrentOwner () == m_table->stepQueue ()->firstOwner ();
		}

		namespace
		{
			float calcImportance(const Graph& graph, const Point& point, const Owner currentOwner)
			{
				float priority = -1;
				const Owner otherOwner = StepQueue::other (currentOwner);

				for (const MapData& table : PriorityMap::instance ().priorityMap ())
				{
					const MapType& map = table.m_map;
					const Point& currentPoint = table.m_current;

					for (std::size_t j = 0, height = map.size (), i,
							width = map.front ().size (); j < height; ++j)
					{
						for (i = 0; i < width; ++i)
						{
							const int dx = currentPoint.x () - i;
							const int dy = currentPoint.y () - j;
							const int newX = point.x () + dx;
							const int newY = point.y () + dy;
							if (newX < 0 || newY < 0 || newX >= graph.width ()
									|| newY >= graph.height ())
								goto endloop;

							const MapElement el = map[j][i];
							const GraphPoint& graphPoint = graph[newX][newY];
							const Owner own = graphPoint.owner ();
							switch (el)
							{
							case EM: //Empty
								if (own != NONE)
									goto endloop;
								break;
							case FI: //First
								if (own != currentOwner)
									goto endloop;
								break;
							case SE: //Second
								if (own != otherOwner)
									goto endloop;
								break;
							case PF: // Possibly first
								if (own == otherOwner)
									goto endloop;
								break;
							case PS: // Possibly second
								if (own == currentOwner)
									goto endloop;
							default:
								break;
							}
						}
					}

					if (table.m_priority > priority)
						priority = table.m_priority;
endloop:
					;
				}

				return priority;
			}
		}

		void Rival::nextStep (const Point& point)
		{
			if (isAllow ())
				return;

			const Graph& gr = m_table->graph ();

			const Owner current = m_table->stepQueue ()->getCurrentOwner ();
			const Owner other = StepQueue::other (current);
			std::vector<Point> points;
			float max_priority = -1;

			int min_x = point.x () - 2, min_y = point.y () - 2;
			int max_x = point.x () + 2, max_y = point.y () + 2;
			for (int j = 0, max_j = gr.height (), max_i = gr.width (), i; j < max_j; ++j)
			{
				for (i = 0; i < max_i; ++i)
				{
					const GraphPoint& point = gr[i][j];
					if (point.owner () == other)
					{
						if (i - 2 < min_x)
							min_x = i - 2;
						else if (i + 2 > max_x)
							max_x = i + 2;

						if (j - 2 < min_y)
							min_y = j - 2;
						else if (j + 2 > max_y)
							max_y = j + 2;
					}
				}
			}

			for (Graph::const_iterator itr = gr.begin (), itrEnd = gr.end ();
					itr != itrEnd; ++itr)
			{
				if (itr->owner () != NONE)
					continue;

				const Point& newPoint = itr.point ();

				if (newPoint.x () < min_x || newPoint.x () > max_x
						|| newPoint.y () < min_y || newPoint.y () > max_y)
					continue;

				const float imp = calcImportance (gr, newPoint, current);
				if (imp == max_priority)
					points.push_back (newPoint);
				else if (imp > max_priority)
				{
					max_priority = imp;
					points.clear ();
					points.push_back (newPoint);
				}
			}

			srand (time (NULL));
			if (!points.empty ())
				m_table->pushPoint (points[rand () % points.size ()]);
		}

		void Rival::setDotTable (DotTable *table)
		{
			m_table = table;
		}
	}
}
<commit_msg>Minor fix<commit_after>/*
 * KDots
 * Copyright (c) 2011-2012 Minh Ngo <nlminhtl@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "rival.hpp"
#include <ctime>
#include <KDebug>
#include <include/point.hpp>
#include <include/dottable.hpp>
#include <include/stepqueue.hpp>
#include "prioritymap.hpp"

namespace KDots
{
	namespace simpleai
	{
		Rival::Rival (QObject *parent)
			: IRival (parent)
			, m_table (NULL)
		{
			PriorityMap::instance ();
		}

		bool Rival::isAllow () const
		{
			if (!m_table)
				return false;

			return m_table->stepQueue ()->getCurrentOwner () == m_table->stepQueue ()->firstOwner ();
		}

		namespace
		{
			float calcImportance(const Graph& graph, const Point& point, const Owner currentOwner)
			{
				float priority = -1;
				const Owner otherOwner = StepQueue::other (currentOwner);

				for (const MapData& table : PriorityMap::instance ().priorityMap ())
				{
					const MapType& map = table.m_map;
					const Point& currentPoint = table.m_current;

					for (std::size_t j = 0, height = map.size (), i,
							width = map.front ().size (); j < height; ++j)
					{
						for (i = 0; i < width; ++i)
						{
							const int dx = currentPoint.x () - i;
							const int dy = currentPoint.y () - j;
							const int newX = point.x () + dx;
							const int newY = point.y () + dy;
							if (newX < 0 || newY < 0 || newX >= graph.width ()
									|| newY >= graph.height ())
								goto endloop;

							const MapElement el = map[j][i];
							const GraphPoint& graphPoint = graph[newX][newY];
							const Owner own = graphPoint.owner ();
							switch (el)
							{
							case EM: //Empty
								if (own != NONE)
									goto endloop;
								break;
							case FI: //First
								if (own != currentOwner)
									goto endloop;
								break;
							case SE: //Second
								if (own != otherOwner)
									goto endloop;
								break;
							case PF: // Possibly first
								if (own == otherOwner)
									goto endloop;
								break;
							case PS: // Possibly second
								if (own == currentOwner)
									goto endloop;
							default:
								break;
							}
						}
					}

					if (table.m_priority > priority)
						priority = table.m_priority;
endloop:
					;
				}

				return priority;
			}
		}

		void Rival::nextStep (const Point& point)
		{
			if (isAllow ())
				return;

			//std::vector<Point> pointStack;

			const Graph& gr = m_table->graph ();

			const Owner current = m_table->stepQueue ()->getCurrentOwner ();
			const Owner other = StepQueue::other (current);
			std::vector<Point> points;
			float max_priority = -1;

			int min_x = point.x () - 2, min_y = point.y () - 2;
			int max_x = point.x () + 2, max_y = point.y () + 2;
			for (int j = 0, max_j = gr.height (), max_i = gr.width (), i; j < max_j; ++j)
			{
				for (i = 0; i < max_i; ++i)
				{
					const GraphPoint& point = gr[i][j];
					if (point.owner () == other)
					{
						if (i - 2 < min_x)
							min_x = i - 2;
						else if (i + 2 > max_x)
							max_x = i + 2;

						if (j - 2 < min_y)
							min_y = j - 2;
						else if (j + 2 > max_y)
							max_y = j + 2;
					}
				}
			}

			for (Graph::const_iterator itr = gr.begin (), itrEnd = gr.end ();
					itr != itrEnd; ++itr)
			{
				if (itr->owner () != NONE || itr->isCaptured ())
					continue;

				const Point& newPoint = itr.point ();

				if (newPoint.x () < min_x || newPoint.x () > max_x
						|| newPoint.y () < min_y || newPoint.y () > max_y)
					continue;

				const float imp = calcImportance (gr, newPoint, current);
				if (imp == max_priority)
					points.push_back (newPoint);
				else if (imp > max_priority)
				{
					max_priority = imp;
					points.clear ();
					points.push_back (newPoint);
				}
			}

			srand (time (NULL));
			if (!points.empty ())
				m_table->pushPoint (points[rand () % points.size ()]);
		}

		void Rival::setDotTable (DotTable *table)
		{
			m_table = table;
		}
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006  Brad Hards <bradh@frogmouth.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include "pk11func.h"
#include "nss.h"
#include "hasht.h"

#include <QtCrypto>
#include <QtCore>

#include <qstringlist.h>

//-----------------------------------------------------------
class nssHashContext : public QCA::HashContext
{
public:
    nssHashContext( QCA::Provider *p, const QString &type) : QCA::HashContext(p, type)
    {
	SECStatus s;

	NSS_NoDB_Init(".");

	m_status = 0;

	/* Get a slot to use for the crypto operations */
	m_slot = PK11_GetInternalKeySlot();
	if (!m_slot)
	{
	    qDebug() << "GetInternalKeySlot failed";
	    m_status = 1;
	    return;
	}

	if ( QString("md2") == type ) {
	    m_hashAlgo = SEC_OID_MD2;
	}
	else if ( QString("md5") == type ) {
	    m_hashAlgo = SEC_OID_MD5;
	}
	else if ( QString("sha1") == type ) {
	    m_hashAlgo = SEC_OID_SHA1;
	}
	else if ( QString("sha256") == type ) {
	    m_hashAlgo = SEC_OID_SHA256;
	}
	else if ( QString("sha384") == type ) {
	    m_hashAlgo = SEC_OID_SHA384;
	}
	else if ( QString("sha512") == type ) {
	    m_hashAlgo = SEC_OID_SHA512;
	} else {
	    qDebug() << "Unknown provider type: " << type;
	    return; /* this will probably cause a segfault... */
	}

	m_context = PK11_CreateDigestContext(m_hashAlgo);
	if (! m_context) {
	    qDebug() << "CreateDigestContext failed";
	    return;
	}

	s = PK11_DigestBegin(m_context);
	if (s != SECSuccess) {
	    qDebug() << "DigestBegin failed";
	    return;
	}
    }

    ~nssHashContext()
    {
	PK11_DestroyContext(m_context, PR_TRUE);
	if (m_slot)
	    PK11_FreeSlot(m_slot);
    }

    Context *clone() const
    {
	return new nssHashContext(*this);
    }

    void clear()
    {
	SECStatus s;

	PK11_DestroyContext(m_context, PR_TRUE);

	m_context = PK11_CreateDigestContext(m_hashAlgo);
	if (! m_context) {
	    qDebug() << "CreateDigestContext failed";
	    return;
	}

	s = PK11_DigestBegin(m_context);
	if (s != SECSuccess) {
	    qDebug() << "DigestBegin failed";
	    return;
	}
    }

    void update(const QSecureArray &a)
    {
	PK11_DigestOp(m_context, (const unsigned char*)a.data(), a.size());
    }

    QSecureArray final()
    {
	unsigned int len = 0;
	QSecureArray a( 64 );
	PK11_DigestFinal(m_context, (unsigned char*)a.data(), &len, a.size());
	a.resize(len);
	return a;
    }

private:
    PK11SlotInfo *m_slot;
    int m_status;
    PK11Context *m_context;
    SECOidTag m_hashAlgo;
};

//-----------------------------------------------------------
class nssHmacContext : public QCA::MACContext
{
public:
    nssHmacContext( QCA::Provider *p, const QString &type) : QCA::MACContext(p, type)
    {
	NSS_NoDB_Init(".");

	m_status = 0;

	/* Get a slot to use for the crypto operations */
	m_slot = PK11_GetInternalKeySlot();
	if (!m_slot)
	{
	    qDebug() << "GetInternalKeySlot failed";
	    m_status = 1;
	    return;
	}

	if ( QString("hmac(md5)") == type ) {
	    m_macAlgo = CKM_MD5_HMAC;
	}
	else if ( QString("hmac(sha1)") == type ) {
	    m_macAlgo = CKM_SHA_1_HMAC;
	}
	else if ( QString("hmac(sha256)") == type ) {
	    m_macAlgo = CKM_SHA256_HMAC;
	}
	else if ( QString("hmac(sha384)") == type ) {
	    m_macAlgo = CKM_SHA384_HMAC;
	}
	else if ( QString("hmac(sha512)") == type ) {
	    m_macAlgo = CKM_SHA512_HMAC;
	}
	else if ( QString("hmac(ripemd160)") == type ) {
	    m_macAlgo = CKM_RIPEMD160_HMAC;
	}
	else {
	    qDebug() << "Unknown provider type: " << type;
	    return; /* this will probably cause a segfault... */
	}
    }

    ~nssHmacContext()
    {
	PK11_DestroyContext(m_context, PR_TRUE);
	if (m_slot)
	    PK11_FreeSlot(m_slot);
    }

    Context *clone() const
    {
	return new nssHmacContext(*this);
    }

    void clear()
    {
	PK11_DestroyContext(m_context, PR_TRUE);

	SECItem noParams;
	noParams.data = 0;
	noParams.len = 0;

	m_context = PK11_CreateContextBySymKey(m_macAlgo, CKA_SIGN, m_nssKey, &noParams);
	if (! m_context) {
	    qDebug() << "CreateContextBySymKey failed";
	    return;
	}

	SECStatus s = PK11_DigestBegin(m_context);
	if (s != SECSuccess) {
	    qDebug() << "DigestBegin failed";
	    return;
	}
    }

    QCA::KeyLength keyLength() const
    {
        return anyKeyLength();
    }

    void setup(const QCA::SymmetricKey &key)
    {
        /* turn the raw key into a SECItem */
        SECItem keyItem;
	keyItem.data = (unsigned char*) key.data();
	keyItem.len = key.size();

	m_nssKey = PK11_ImportSymKey(m_slot, m_macAlgo, PK11_OriginUnwrap, CKA_SIGN, &keyItem, NULL);

	SECItem noParams;
	noParams.data = 0;
	noParams.len = 0;

	m_context = PK11_CreateContextBySymKey(m_macAlgo, CKA_SIGN, m_nssKey, &noParams);
	if (! m_context) {
	    qDebug() << "CreateContextBySymKey failed";
	    return;
	}

	SECStatus s = PK11_DigestBegin(m_context);
	if (s != SECSuccess) {
	    qDebug() << "DigestBegin failed";
	    return;
	}
    }

    void update(const QSecureArray &a)
    {
	PK11_DigestOp(m_context, (const unsigned char*)a.data(), a.size());
    }

    void final( QSecureArray *out)
    {
	// NSS doesn't appear to be able to tell us how big the digest will
	// be for a given algorithm until after we finalise it, so we work
	// around the problem a bit.
	out->resize( HASH_LENGTH_MAX ); // assume the biggest hash size we know
	unsigned int len = 0;
	PK11_DigestFinal(m_context, (unsigned char*)out->data(), &len, out->size());
	out->resize(len); // and fix it up later
    }

private:
    PK11SlotInfo *m_slot;
    int m_status;
    PK11Context *m_context;
    CK_MECHANISM_TYPE m_macAlgo;
    PK11SymKey* m_nssKey;
};

//==========================================================
class nssProvider : public QCA::Provider
{
public:
    void init()
    {
    }

    ~nssProvider()
    {
    }

    QString name() const
    {
	return "qca-nss";
    }

    QStringList features() const
    {
	QStringList list;

	list += "md2";
	list += "md5";
	list += "sha1";
	list += "sha256";
	list += "sha384";
	list += "sha512";

	list += "hmac(md5)";
	list += "hmac(sha1)";
	list += "hmac(sha256)";
	list += "hmac(sha384)";
	list += "hmac(sha512)";
	// appears to not be implemented in NSS
	// list += "hmac(ripemd160)";
	return list;
    }

    Context *createContext(const QString &type)
    {
	if ( type == "md2" )
	    return new nssHashContext( this, type );
	if ( type == "md5" )
	    return new nssHashContext( this, type );
	if ( type == "sha1" )
	    return new nssHashContext( this, type );
	if ( type == "sha256" )
	    return new nssHashContext( this, type );
	if ( type == "sha384" )
	    return new nssHashContext( this, type );
	if ( type == "sha512" )
	    return new nssHashContext( this, type );

	if ( type == "hmac(md5)" )
	    return new nssHmacContext( this, type );
	if ( type == "hmac(sha1)" )
	    return new nssHmacContext( this, type );
	if ( type == "hmac(sha256)" )
	    return new nssHmacContext( this, type );
	if ( type == "hmac(sha384)" )
	    return new nssHmacContext( this, type );
	if ( type == "hmac(sha512)" )
	    return new nssHmacContext( this, type );
	if ( type == "hmac(ripemd160)" )
	    return new nssHmacContext( this, type );
	else
	    return 0;
    }
private:

};

class nssPlugin : public QCAPlugin
{
	Q_OBJECT
	Q_INTERFACES( QCAPlugin )
public:
	virtual QCA::Provider *createProvider() { return new nssProvider; }
};

#include "qca-nss.moc"

Q_EXPORT_PLUGIN2(qca-nss, nssPlugin);

<commit_msg>Initial Cipher support for the NSS provider.<commit_after>/*
 * Copyright (C) 2006  Brad Hards <bradh@frogmouth.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include "pk11func.h"
#include "nss.h"
#include "hasht.h"

#include <QtCrypto>
#include <QtCore>

#include <qstringlist.h>

//-----------------------------------------------------------
class nssHashContext : public QCA::HashContext
{
public:
    nssHashContext( QCA::Provider *p, const QString &type) : QCA::HashContext(p, type)
    {
	SECStatus s;

	NSS_NoDB_Init(".");

	m_status = 0;

	/* Get a slot to use for the crypto operations */
	m_slot = PK11_GetInternalKeySlot();
	if (!m_slot)
	{
	    qDebug() << "GetInternalKeySlot failed";
	    m_status = 1;
	    return;
	}

	if ( QString("md2") == type ) {
	    m_hashAlgo = SEC_OID_MD2;
	}
	else if ( QString("md5") == type ) {
	    m_hashAlgo = SEC_OID_MD5;
	}
	else if ( QString("sha1") == type ) {
	    m_hashAlgo = SEC_OID_SHA1;
	}
	else if ( QString("sha256") == type ) {
	    m_hashAlgo = SEC_OID_SHA256;
	}
	else if ( QString("sha384") == type ) {
	    m_hashAlgo = SEC_OID_SHA384;
	}
	else if ( QString("sha512") == type ) {
	    m_hashAlgo = SEC_OID_SHA512;
	} else {
	    qDebug() << "Unknown provider type: " << type;
	    return; /* this will probably cause a segfault... */
	}

	m_context = PK11_CreateDigestContext(m_hashAlgo);
	if (! m_context) {
	    qDebug() << "CreateDigestContext failed";
	    return;
	}

	s = PK11_DigestBegin(m_context);
	if (s != SECSuccess) {
	    qDebug() << "DigestBegin failed";
	    return;
	}
    }

    ~nssHashContext()
    {
	PK11_DestroyContext(m_context, PR_TRUE);
	if (m_slot)
	    PK11_FreeSlot(m_slot);
    }

    Context *clone() const
    {
	return new nssHashContext(*this);
    }

    void clear()
    {
	SECStatus s;

	PK11_DestroyContext(m_context, PR_TRUE);

	m_context = PK11_CreateDigestContext(m_hashAlgo);
	if (! m_context) {
	    qDebug() << "CreateDigestContext failed";
	    return;
	}

	s = PK11_DigestBegin(m_context);
	if (s != SECSuccess) {
	    qDebug() << "DigestBegin failed";
	    return;
	}
    }

    void update(const QSecureArray &a)
    {
	PK11_DigestOp(m_context, (const unsigned char*)a.data(), a.size());
    }

    QSecureArray final()
    {
	unsigned int len = 0;
	QSecureArray a( 64 );
	PK11_DigestFinal(m_context, (unsigned char*)a.data(), &len, a.size());
	a.resize(len);
	return a;
    }

private:
    PK11SlotInfo *m_slot;
    int m_status;
    PK11Context *m_context;
    SECOidTag m_hashAlgo;
};

//-----------------------------------------------------------
class nssHmacContext : public QCA::MACContext
{
public:
    nssHmacContext( QCA::Provider *p, const QString &type) : QCA::MACContext(p, type)
    {
	NSS_NoDB_Init(".");

	m_status = 0;

	/* Get a slot to use for the crypto operations */
	m_slot = PK11_GetInternalKeySlot();
	if (!m_slot)
	{
	    qDebug() << "GetInternalKeySlot failed";
	    m_status = 1;
	    return;
	}

	if ( QString("hmac(md5)") == type ) {
	    m_macAlgo = CKM_MD5_HMAC;
	}
	else if ( QString("hmac(sha1)") == type ) {
	    m_macAlgo = CKM_SHA_1_HMAC;
	}
	else if ( QString("hmac(sha256)") == type ) {
	    m_macAlgo = CKM_SHA256_HMAC;
	}
	else if ( QString("hmac(sha384)") == type ) {
	    m_macAlgo = CKM_SHA384_HMAC;
	}
	else if ( QString("hmac(sha512)") == type ) {
	    m_macAlgo = CKM_SHA512_HMAC;
	}
	else if ( QString("hmac(ripemd160)") == type ) {
	    m_macAlgo = CKM_RIPEMD160_HMAC;
	}
	else {
	    qDebug() << "Unknown provider type: " << type;
	    return; /* this will probably cause a segfault... */
	}
    }

    ~nssHmacContext()
    {
	PK11_DestroyContext(m_context, PR_TRUE);
	if (m_slot)
	    PK11_FreeSlot(m_slot);
    }

    Context *clone() const
    {
	return new nssHmacContext(*this);
    }

    void clear()
    {
	PK11_DestroyContext(m_context, PR_TRUE);

	SECItem noParams;
	noParams.data = 0;
	noParams.len = 0;

	m_context = PK11_CreateContextBySymKey(m_macAlgo, CKA_SIGN, m_nssKey, &noParams);
	if (! m_context) {
	    qDebug() << "CreateContextBySymKey failed";
	    return;
	}

	SECStatus s = PK11_DigestBegin(m_context);
	if (s != SECSuccess) {
	    qDebug() << "DigestBegin failed";
	    return;
	}
    }

    QCA::KeyLength keyLength() const
    {
        return anyKeyLength();
    }

    void setup(const QCA::SymmetricKey &key)
    {
        /* turn the raw key into a SECItem */
        SECItem keyItem;
	keyItem.data = (unsigned char*) key.data();
	keyItem.len = key.size();

	m_nssKey = PK11_ImportSymKey(m_slot, m_macAlgo, PK11_OriginUnwrap, CKA_SIGN, &keyItem, NULL);

	SECItem noParams;
	noParams.data = 0;
	noParams.len = 0;

	m_context = PK11_CreateContextBySymKey(m_macAlgo, CKA_SIGN, m_nssKey, &noParams);
	if (! m_context) {
	    qDebug() << "CreateContextBySymKey failed";
	    return;
	}

	SECStatus s = PK11_DigestBegin(m_context);
	if (s != SECSuccess) {
	    qDebug() << "DigestBegin failed";
	    return;
	}
    }

    void update(const QSecureArray &a)
    {
	PK11_DigestOp(m_context, (const unsigned char*)a.data(), a.size());
    }

    void final( QSecureArray *out)
    {
	// NSS doesn't appear to be able to tell us how big the digest will
	// be for a given algorithm until after we finalise it, so we work
	// around the problem a bit.
	out->resize( HASH_LENGTH_MAX ); // assume the biggest hash size we know
	unsigned int len = 0;
	PK11_DigestFinal(m_context, (unsigned char*)out->data(), &len, out->size());
	out->resize(len); // and fix it up later
    }

private:
    PK11SlotInfo *m_slot;
    int m_status;
    PK11Context *m_context;
    CK_MECHANISM_TYPE m_macAlgo;
    PK11SymKey* m_nssKey;
};

//-----------------------------------------------------------
class nssCipherContext : public QCA::CipherContext
{
public:
    nssCipherContext( QCA::Provider *p, const QString &type) : QCA::CipherContext(p, type)
    {
	NSS_NoDB_Init(".");

	if ( QString("aes128-ecb") == type ) {
	    m_cipherMechanism = CKM_AES_ECB;
	}
	else if ( QString("aes128-cbc") == type ) {
	    m_cipherMechanism = CKM_AES_CBC;
	}
	else if ( QString("des-ecb") == type ) {
	    m_cipherMechanism = CKM_DES_ECB;
	}
	else if ( QString("des-cbc") == type ) {
	    m_cipherMechanism = CKM_DES_CBC;
	}
	else if ( QString("des-cbc-pkcs7") == type ) {
	    m_cipherMechanism = CKM_DES_CBC_PAD;
	}
	else if ( QString("tripledes-ecb") == type ) {
	    m_cipherMechanism = CKM_DES3_ECB;
	}
	else {
	    qDebug() << "Unknown provider type: " << type;
	    return; /* this will probably cause a segfault... */
	}
    }

    ~nssCipherContext()
	{
	}

    void setup( QCA::Direction dir,
		const QCA::SymmetricKey &key,
		const QCA::InitializationVector &iv )
    {
	/* Get a slot to use for the crypto operations */
	m_slot = PK11_GetBestSlot( m_cipherMechanism, NULL );
	if (!m_slot)
	{
	    qDebug() << "GetBestSlot failed";
	    return;
	}

	/* turn the raw key into a SECItem */
        SECItem keyItem;
	keyItem.data = (unsigned char*) key.data();
	keyItem.len = key.size();

	if (QCA::Encode == dir) {
	    m_nssKey = PK11_ImportSymKey(m_slot, m_cipherMechanism,
					 PK11_OriginUnwrap, CKA_ENCRYPT,
					 &keyItem, NULL);
	} else {
	    // decryption
	    m_nssKey = PK11_ImportSymKey(m_slot, m_cipherMechanism,
					 PK11_OriginUnwrap, CKA_DECRYPT,
					 &keyItem, NULL);
	}

	SECItem ivItem;
	ivItem.data = (unsigned char*) iv.data();
	ivItem.len = iv.size();

	m_params = PK11_ParamFromIV(m_cipherMechanism, &ivItem);

	if (QCA::Encode == dir) {
	    m_context = PK11_CreateContextBySymKey(m_cipherMechanism,
						   CKA_ENCRYPT, m_nssKey,
						   m_params);
	} else {
	    // decryption
	    m_context = PK11_CreateContextBySymKey(m_cipherMechanism,
						   CKA_DECRYPT, m_nssKey,
						   m_params);
	}

	if (! m_context) {
	    qDebug() << "CreateContextBySymKey failed";
	    return;
	}
    }

    QCA::Provider::Context *clone() const
	{
	}

    unsigned int blockSize() const
	{
	    return PK11_GetBlockSize( m_cipherMechanism, m_params);
	}

    bool update( const QSecureArray &in, QSecureArray *out )
	{
	    out->resize(in.size()+blockSize());
	    int resultLength;

	    PK11_CipherOp(m_context, (unsigned char*)out->data(),
			  &resultLength, out->size(),
			  (unsigned char*)in.data(), in.size());
	    out->resize(resultLength);

	    return true;
	}

    bool final( QSecureArray *out )
	{
	    out->resize(blockSize());
	    unsigned int resultLength;

	    PK11_DigestFinal(m_context, (unsigned char*)out->data(),
			     &resultLength, out->size());
	    out->resize(resultLength);

	    return true;
	}

    QCA::KeyLength keyLength() const
	{
	}

private:
    PK11SymKey* m_nssKey;
    CK_MECHANISM_TYPE m_cipherMechanism;
    PK11SlotInfo *m_slot;
    PK11Context *m_context;
    SECItem* m_params;
};

//==========================================================
class nssProvider : public QCA::Provider
{
public:
    void init()
    {
    }

    ~nssProvider()
    {
    }

    QString name() const
    {
	return "qca-nss";
    }

    QStringList features() const
    {
	QStringList list;

	list += "md2";
	list += "md5";
	list += "sha1";
	list += "sha256";
	list += "sha384";
	list += "sha512";

	list += "hmac(md5)";
	list += "hmac(sha1)";
	list += "hmac(sha256)";
	list += "hmac(sha384)";
	list += "hmac(sha512)";
	// appears to not be implemented in NSS yet
	// list += "hmac(ripemd160)";

	list += "aes128-ecb";
	list += "aes128-cbc";
	list += "des-ecb";
	list += "des-cbc";
	list += "des-cbc-pkcs7";
	list += "tripledes-ecb";

	return list;
    }

    Context *createContext(const QString &type)
    {
	if ( type == "md2" )
	    return new nssHashContext( this, type );
	if ( type == "md5" )
	    return new nssHashContext( this, type );
	if ( type == "sha1" )
	    return new nssHashContext( this, type );
	if ( type == "sha256" )
	    return new nssHashContext( this, type );
	if ( type == "sha384" )
	    return new nssHashContext( this, type );
	if ( type == "sha512" )
	    return new nssHashContext( this, type );

	if ( type == "hmac(md5)" )
	    return new nssHmacContext( this, type );
	if ( type == "hmac(sha1)" )
	    return new nssHmacContext( this, type );
	if ( type == "hmac(sha256)" )
	    return new nssHmacContext( this, type );
	if ( type == "hmac(sha384)" )
	    return new nssHmacContext( this, type );
	if ( type == "hmac(sha512)" )
	    return new nssHmacContext( this, type );
	if ( type == "hmac(ripemd160)" )
	    return new nssHmacContext( this, type );

	if ( type == "aes128-ecb" )
	    return new nssCipherContext( this, type);
	if ( type == "aes128-cbc" )
	    return new nssCipherContext( this, type);
	if ( type == "des-ecb" )
	    return new nssCipherContext( this, type);
	if ( type == "des-cbc" )
	    return new nssCipherContext( this, type);
	if ( type == "des-cbc-pkcs7" )
	    return new nssCipherContext( this, type);
	if ( type == "tripledes-ecb" )
	    return new nssCipherContext( this, type);
	else
	    return 0;
    }
};

class nssPlugin : public QCAPlugin
{
	Q_OBJECT
	Q_INTERFACES( QCAPlugin )
public:
	virtual QCA::Provider *createProvider() { return new nssProvider; }
};

#include "qca-nss.moc"

Q_EXPORT_PLUGIN2(qca-nss, nssPlugin);

<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "motor_shield.h"

#define SPEED_L 1
#define DIR_L 2

#define SPEED_R 3
#define DIR_R 4

MotorShield mshield(SPEED_L, DIR_L, SPEED_R, DIR_R);

TEST(MotorShield, Initialization) {
  ASSERT_EQ(0, mshield.getMinSpeed());
  ASSERT_EQ(255, mshield.getMaxSpeed());

  ASSERT_EQ(SPEED_L, mshield.getLeftSpeedPin());
  ASSERT_EQ(SPEED_R, mshield.getRightSpeedPin());

  ASSERT_EQ(DIR_L, mshield.getLeftDirPin());
  ASSERT_EQ(DIR_R, mshield.getRightDirPin());
}
<commit_msg>Test MotorShield setup method<commit_after>#include "gtest/gtest.h"
#include "motor_shield.h"

#define SPEED_L 1
#define DIR_L 2

#define SPEED_R 3
#define DIR_R 4

MotorShield mshield(SPEED_L, DIR_L, SPEED_R, DIR_R);

TEST(MotorShield, Initialization) {
  ASSERT_EQ(0, mshield.getMinSpeed());
  ASSERT_EQ(255, mshield.getMaxSpeed());

  ASSERT_EQ(SPEED_L, mshield.getLeftSpeedPin());
  ASSERT_EQ(SPEED_R, mshield.getRightSpeedPin());

  ASSERT_EQ(DIR_L, mshield.getLeftDirPin());
  ASSERT_EQ(DIR_R, mshield.getRightDirPin());
}

TEST(MotorShield, Setup) {
  ArduinoMock mock;

  EXPECT_CALL(mock, pinMode(SPEED_L, OUTPUT));
  EXPECT_CALL(mock, pinMode(DIR_L, OUTPUT));
  EXPECT_CALL(mock, pinMode(SPEED_R, OUTPUT));
  EXPECT_CALL(mock, pinMode(DIR_R, OUTPUT));

  EXPECT_CALL(mock, analogWrite(SPEED_L, 0));
  EXPECT_CALL(mock, analogWrite(SPEED_R, 0));

  EXPECT_CALL(mock, digitalWrite(DIR_L, LOW));
  EXPECT_CALL(mock, digitalWrite(DIR_R, LOW));

  mshield.init();
}
<|endoftext|>


<commit_before>#include "../write_code_segment.hpp"

#include "vm/processor.hpp"
#include "vm/stack.hpp"
#include "vm/exceptions.hpp"

#include <utility>
#include <cstdint>
#include <array>

#include <boost/test/unit_test.hpp>

using perseus::detail::processor;
using perseus::detail::opcode;
using perseus::invalid_opcode;
using perseus::code_segmentation_fault;
using perseus::execution_finished;
using perseus::stack;
using perseus::stack_underflow;

BOOST_AUTO_TEST_SUITE( vm )

BOOST_AUTO_TEST_SUITE( execution )

BOOST_AUTO_TEST_CASE( exit_0_test ) // X
{
  auto code = create_code_segment( opcode::exit, std::uint32_t( 0 ) );
  processor proc( std::move( code ) );
  auto result = proc.continue_execution();
  BOOST_CHECK( result.execution_finished );
  BOOST_CHECK_EQUAL( result.stack.size(), 0 );
  BOOST_CHECK_THROW( proc.continue_execution(), execution_finished );
}

BOOST_AUTO_TEST_CASE( exit_2_test ) // X
{
  auto code = create_code_segment( opcode::exit, std::uint32_t( 2 ) );
  stack input;
  input.push< std::array< char, 4 > >( { 'a', 'b', 'c', 'd' } );
  auto result = processor( std::move( code ) ).continue_execution( std::move( input ) );
  return;
  BOOST_CHECK( result.execution_finished );
  BOOST_CHECK_EQUAL( result.stack.size(), 2 );
  BOOST_CHECK_EQUAL( result.stack.pop< char >(), 'd' );
  BOOST_CHECK_EQUAL( result.stack.pop< char >(), 'c' );
}

BOOST_AUTO_TEST_CASE( exit_underflow_test )
{
  auto code = create_code_segment( opcode::exit, std::uint32_t( 2 ) );
  BOOST_CHECK_THROW( processor( std::move( code ) ).continue_execution(), stack_underflow );
}

BOOST_AUTO_TEST_CASE( exit_all_test ) // X
{
  auto code = create_code_segment( opcode::exit_returning_everything );
  stack input;
  input.push< std::array< char, 4 > >( { 'a', 'b', 'c', 'd' } );
  auto result = processor( std::move( code ) ).continue_execution( std::move( input ) );
  BOOST_CHECK( result.execution_finished );
  BOOST_CHECK_EQUAL( result.stack.size(), 4 );
  BOOST_CHECK_EQUAL( result.stack.pop< char >(), 'd' );
  BOOST_CHECK_EQUAL( result.stack.pop< char >(), 'c' );
}

BOOST_AUTO_TEST_CASE( noop_test ) // X
{
  auto code = create_code_segment( opcode::no_operation, opcode::exit, std::uint32_t( 0 ) );
  BOOST_CHECK( processor( std::move( code ) ).continue_execution().execution_finished );
}

BOOST_AUTO_TEST_CASE( out_of_bounds_test )
{
  auto code = create_code_segment( opcode::no_operation );
  BOOST_CHECK_THROW( processor( std::move( code ) ).continue_execution(), code_segmentation_fault );
}

BOOST_AUTO_TEST_CASE( invalid_opcode_test )
{
  auto code = create_code_segment( opcode::opcode_end );
  BOOST_CHECK_THROW( processor( std::move( code ) ).continue_execution(), invalid_opcode );
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>removed marks on previously leaking tests<commit_after>#include "../write_code_segment.hpp"

#include "vm/processor.hpp"
#include "vm/stack.hpp"
#include "vm/exceptions.hpp"

#include <utility>
#include <cstdint>
#include <array>

#include <boost/test/unit_test.hpp>

using perseus::detail::processor;
using perseus::detail::opcode;
using perseus::invalid_opcode;
using perseus::code_segmentation_fault;
using perseus::execution_finished;
using perseus::stack;
using perseus::stack_underflow;

BOOST_AUTO_TEST_SUITE( vm )

BOOST_AUTO_TEST_SUITE( execution )

BOOST_AUTO_TEST_CASE( exit_0_test )
{
  auto code = create_code_segment( opcode::exit, std::uint32_t( 0 ) );
  processor proc( std::move( code ) );
  auto result = proc.continue_execution();
  BOOST_CHECK( result.execution_finished );
  BOOST_CHECK_EQUAL( result.stack.size(), 0 );
  BOOST_CHECK_THROW( proc.continue_execution(), execution_finished );
}

BOOST_AUTO_TEST_CASE( exit_2_test )
{
  auto code = create_code_segment( opcode::exit, std::uint32_t( 2 ) );
  stack input;
  input.push< std::array< char, 4 > >( { 'a', 'b', 'c', 'd' } );
  auto result = processor( std::move( code ) ).continue_execution( std::move( input ) );
  return;
  BOOST_CHECK( result.execution_finished );
  BOOST_CHECK_EQUAL( result.stack.size(), 2 );
  BOOST_CHECK_EQUAL( result.stack.pop< char >(), 'd' );
  BOOST_CHECK_EQUAL( result.stack.pop< char >(), 'c' );
}

BOOST_AUTO_TEST_CASE( exit_underflow_test )
{
  auto code = create_code_segment( opcode::exit, std::uint32_t( 2 ) );
  BOOST_CHECK_THROW( processor( std::move( code ) ).continue_execution(), stack_underflow );
}

BOOST_AUTO_TEST_CASE( exit_all_test )
{
  auto code = create_code_segment( opcode::exit_returning_everything );
  stack input;
  input.push< std::array< char, 4 > >( { 'a', 'b', 'c', 'd' } );
  auto result = processor( std::move( code ) ).continue_execution( std::move( input ) );
  BOOST_CHECK( result.execution_finished );
  BOOST_CHECK_EQUAL( result.stack.size(), 4 );
  BOOST_CHECK_EQUAL( result.stack.pop< char >(), 'd' );
  BOOST_CHECK_EQUAL( result.stack.pop< char >(), 'c' );
}

BOOST_AUTO_TEST_CASE( noop_test )
{
  auto code = create_code_segment( opcode::no_operation, opcode::exit, std::uint32_t( 0 ) );
  BOOST_CHECK( processor( std::move( code ) ).continue_execution().execution_finished );
}

BOOST_AUTO_TEST_CASE( out_of_bounds_test )
{
  auto code = create_code_segment( opcode::no_operation );
  BOOST_CHECK_THROW( processor( std::move( code ) ).continue_execution(), code_segmentation_fault );
}

BOOST_AUTO_TEST_CASE( invalid_opcode_test )
{
  auto code = create_code_segment( opcode::opcode_end );
  BOOST_CHECK_THROW( processor( std::move( code ) ).continue_execution(), invalid_opcode );
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: wallitem.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-27 14:36:41 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _WALLITEM_HXX
#define _WALLITEM_HXX

#ifndef SHL_HXX
#include <tools/shl.hxx>
#endif

// -----------------------------------------------------------------------------------------
// Hilfsklasse, um die Download-Funktionalitaet des SvxBrushItems unterhalb
// des SVX zu benutzen. Der Link wird im Konstruktor von SvxDialogDll gesetzt.
#ifndef _SFX_BRUSHITEMLINK_DECLARED
#define _SFX_BRUSHITEMLINK_DECLARED
#ifndef _SV_GRAPH_HXX
#include <vcl/graph.hxx>
#endif

#ifndef SHL_BRUSHITEM
#define SHL_BRUSHITEM SHL_SHL1
#endif

class Window;
class SfxItemSet;

typedef void* (*CreateSvxBrushTabPage)(Window *pParent, const SfxItemSet &rAttrSet);
typedef USHORT* (*GetSvxBrushTabPageRanges)();

class Graphic;
class String;
class SfxBrushItemLink
{
public:
    virtual Graphic GetGraphic( const String& rLink, const String& rFilter) = 0;
    virtual CreateSvxBrushTabPage GetBackgroundTabpageCreateFunc() = 0;
    virtual GetSvxBrushTabPageRanges GetBackgroundTabpageRanges() = 0;
    static SfxBrushItemLink* Get() { return *(SfxBrushItemLink**)GetAppData(SHL_BRUSHITEM); }
    static void Set( SfxBrushItemLink* pLink );
};
#endif  // _SFX_BRUSHITEMLINK_DECLARED

#endif // _WALLITEM_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.924); FILE MERGED 2005/09/05 14:51:20 rt 1.3.924.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: wallitem.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:15:48 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _WALLITEM_HXX
#define _WALLITEM_HXX

#ifndef SHL_HXX
#include <tools/shl.hxx>
#endif

// -----------------------------------------------------------------------------------------
// Hilfsklasse, um die Download-Funktionalitaet des SvxBrushItems unterhalb
// des SVX zu benutzen. Der Link wird im Konstruktor von SvxDialogDll gesetzt.
#ifndef _SFX_BRUSHITEMLINK_DECLARED
#define _SFX_BRUSHITEMLINK_DECLARED
#ifndef _SV_GRAPH_HXX
#include <vcl/graph.hxx>
#endif

#ifndef SHL_BRUSHITEM
#define SHL_BRUSHITEM SHL_SHL1
#endif

class Window;
class SfxItemSet;

typedef void* (*CreateSvxBrushTabPage)(Window *pParent, const SfxItemSet &rAttrSet);
typedef USHORT* (*GetSvxBrushTabPageRanges)();

class Graphic;
class String;
class SfxBrushItemLink
{
public:
    virtual Graphic GetGraphic( const String& rLink, const String& rFilter) = 0;
    virtual CreateSvxBrushTabPage GetBackgroundTabpageCreateFunc() = 0;
    virtual GetSvxBrushTabPageRanges GetBackgroundTabpageRanges() = 0;
    static SfxBrushItemLink* Get() { return *(SfxBrushItemLink**)GetAppData(SHL_BRUSHITEM); }
    static void Set( SfxBrushItemLink* pLink );
};
#endif  // _SFX_BRUSHITEMLINK_DECLARED

#endif // _WALLITEM_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svddrgmt.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-06 13:17:23 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _SVDDRGMT_HXX
#define _SVDDRGMT_HXX

#ifndef _SVDDRGV_HXX
#include <svx/svddrgv.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  @@@@@  @@@@@   @@@@   @@@@   @@   @@ @@@@@ @@@@@@ @@  @@  @@@@  @@@@@   @@@@
//  @@  @@ @@  @@ @@  @@ @@  @@  @@@ @@@ @@      @@   @@  @@ @@  @@ @@  @@ @@  @@
//  @@  @@ @@  @@ @@  @@ @@      @@@@@@@ @@      @@   @@  @@ @@  @@ @@  @@ @@
//  @@  @@ @@@@@  @@@@@@ @@ @@@  @@@@@@@ @@@@    @@   @@@@@@ @@  @@ @@  @@  @@@@
//  @@  @@ @@  @@ @@  @@ @@  @@  @@ @ @@ @@      @@   @@  @@ @@  @@ @@  @@     @@
//  @@  @@ @@  @@ @@  @@ @@  @@  @@   @@ @@      @@   @@  @@ @@  @@ @@  @@ @@  @@
//  @@@@@  @@  @@ @@  @@  @@@@@  @@   @@ @@@@@   @@   @@  @@  @@@@  @@@@@   @@@@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

class SdrDragView;
class SdrDragStat;

class SVX_DLLPUBLIC SdrDragMethod {
protected:
    SdrDragView& rView;
    bool         bMoveOnly;
protected:
//#if 0 // _SOLAR__PRIVATE
    void               ImpTakeDescriptionStr(USHORT nStrCacheID, String& rStr, USHORT nVal=0) const;
//#endif // __PRIVATE
    SdrHdl*            GetDragHdl() const              { return rView.pDragHdl; }
    SdrHdlKind         GetDragHdlKind() const          { return rView.eDragHdl; }
    SdrDragStat&       DragStat()                      { return rView.aDragStat; }
    const SdrDragStat& DragStat() const                { return rView.aDragStat; }
    Point&             Ref1() const                    { return rView.aRef1; }
    Point&             Ref2() const                    { return rView.aRef2; }
    const SdrHdlList&  GetHdlList() const              { return rView.aHdl; }
    void               AddUndo(SdrUndoAction* pUndo)   { rView.AddUndo(pUndo); }
    void               SetDragPolys()                  { rView.SetDragPolys(); }
    FASTBOOL           IsDragLimit()                   { return rView.bDragLimit; }
    const Rectangle&   GetDragLimitRect()              { return rView.aDragLimit; }
    const SdrMarkList& GetMarkedObjectList()                   { return rView.GetMarkedObjectList(); }
    Point              GetSnapPos(const Point& rPt) const { return rView.GetSnapPos(rPt,rView.pMarkedPV); }
    USHORT             SnapPos(Point& rPt) const       { return rView.SnapPos(rPt,rView.pMarkedPV); }
    inline const Rectangle& GetMarkedRect() const;
    SdrPageView*       GetDragPV() const;
    SdrObject*         GetDragObj() const;
    OutputDevice*      GetDragWin() const              { return rView.pDragWin; }
    FASTBOOL           IsDraggingPoints() const        { return rView.IsDraggingPoints(); }
    FASTBOOL           IsDraggingGluePoints() const    { return rView.IsDraggingGluePoints(); }

    void CreateOverlayGeometryLines(basegfx::B2DPolyPolygon& rResult);
    void CreateOverlayGeometryPoints(basegfx::B2DPolyPolygon& rResult, const Size& rLogicSize);
    sal_Bool DoAddConnectorOverlays();
    void AddConnectorOverlays(basegfx::B2DPolyPolygon& rResult);
    sal_Bool DoAddDragStripeOverlay();

public:
    TYPEINFO();

    // #i58950# also moved constructor implementation to cxx
    SdrDragMethod(SdrDragView& rNewView);

    // #i58950# virtual destructor was missing
    virtual ~SdrDragMethod();

    virtual void Draw() const;
    virtual void Show();
    virtual void Hide();
    virtual void TakeComment(String& rStr) const=0;
    virtual FASTBOOL Beg()=0;
    virtual void MovAllPoints();
    virtual void MovPoint(Point& rPnt);
    virtual void Mov(const Point& rPnt)=0;
    virtual FASTBOOL End(FASTBOOL bCopy)=0;
    virtual void Brk();
    virtual Pointer GetPointer() const=0;
    virtual FASTBOOL IsMoveOnly() const; // TRUE, wenn nur verschoben wird

    // for migration from XOR to overlay
    virtual void CreateOverlayGeometry(::sdr::overlay::OverlayManager& rOverlayManager, ::sdr::overlay::OverlayObjectList& rOverlayList);
};

inline const Rectangle& SdrDragMethod::GetMarkedRect() const
{
    return rView.eDragHdl==HDL_POLY ? rView.GetMarkedPointsRect() :
           rView.eDragHdl==HDL_GLUE ? rView.GetMarkedGluePointsRect() :
           rView.GetMarkedObjRect();
}

//************************************************************
//   SdrDragMove
//************************************************************

class SVX_DLLPUBLIC SdrDragMove : public SdrDragMethod
{
    long                        nBestXSnap;
    long                        nBestYSnap;
    FASTBOOL                    bXSnapped;
    FASTBOOL                    bYSnapped;

private:
    void ImpCheckSnap(const Point& rPt);

public:
    TYPEINFO();
    SdrDragMove(SdrDragView& rNewView): SdrDragMethod(rNewView) {}

    virtual void TakeComment(String& rStr) const;

    virtual FASTBOOL Beg();
    virtual void MovAllPoints();
    virtual void MovPoint(Point& rPnt);
//  virtual void MovPoint(Point& rPnt, const Point& rPvOfs);
    virtual void Mov(const Point& rPnt);
    virtual FASTBOOL End(FASTBOOL bCopy);
    virtual FASTBOOL IsMoveOnly() const;
    virtual Pointer GetPointer() const;
};

//************************************************************
//   SdrDragResize
//************************************************************

class SVX_DLLPUBLIC SdrDragResize : public SdrDragMethod
{
protected:
    Fraction                    aXFact;
    Fraction                    aYFact;

public:
    TYPEINFO();
    SdrDragResize(SdrDragView& rNewView): SdrDragMethod(rNewView), aXFact(1,1), aYFact(1,1) {}

    virtual void TakeComment(String& rStr) const;

    virtual FASTBOOL Beg();
    virtual void MovPoint(Point& rPnt);
    virtual void Mov(const Point& rPnt);
    virtual FASTBOOL End(FASTBOOL bCopy);
    virtual Pointer GetPointer() const;
};

//************************************************************
//   SdrDragObjOwn
//************************************************************

class SVX_DLLPUBLIC SdrDragObjOwn : public SdrDragMethod
{
public:
    TYPEINFO();
    SdrDragObjOwn(SdrDragView& rNewView): SdrDragMethod(rNewView) {}

    virtual void TakeComment(String& rStr) const;

    virtual FASTBOOL Beg();
    virtual void Mov(const Point& rPnt);
    virtual FASTBOOL End(FASTBOOL bCopy);
    virtual Pointer GetPointer() const;

    // for migration from XOR to overlay
    virtual void CreateOverlayGeometry(::sdr::overlay::OverlayManager& rOverlayManager, ::sdr::overlay::OverlayObjectList& rOverlayList);

    //SJ: added following method, otherwise the object won't be
    //able to notice that dragging has been cancelled.
    virtual void Brk();
};

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SVDDRGMT_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.3.354); FILE MERGED 2008/04/01 12:46:52 thb 1.3.354.2: #i85898# Stripping all external header guards 2008/03/31 14:18:17 rt 1.3.354.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: svddrgmt.hxx,v $
 * $Revision: 1.4 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef _SVDDRGMT_HXX
#define _SVDDRGMT_HXX

#include <svx/svddrgv.hxx>
#include "svx/svxdllapi.h"

////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  @@@@@  @@@@@   @@@@   @@@@   @@   @@ @@@@@ @@@@@@ @@  @@  @@@@  @@@@@   @@@@
//  @@  @@ @@  @@ @@  @@ @@  @@  @@@ @@@ @@      @@   @@  @@ @@  @@ @@  @@ @@  @@
//  @@  @@ @@  @@ @@  @@ @@      @@@@@@@ @@      @@   @@  @@ @@  @@ @@  @@ @@
//  @@  @@ @@@@@  @@@@@@ @@ @@@  @@@@@@@ @@@@    @@   @@@@@@ @@  @@ @@  @@  @@@@
//  @@  @@ @@  @@ @@  @@ @@  @@  @@ @ @@ @@      @@   @@  @@ @@  @@ @@  @@     @@
//  @@  @@ @@  @@ @@  @@ @@  @@  @@   @@ @@      @@   @@  @@ @@  @@ @@  @@ @@  @@
//  @@@@@  @@  @@ @@  @@  @@@@@  @@   @@ @@@@@   @@   @@  @@  @@@@  @@@@@   @@@@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

class SdrDragView;
class SdrDragStat;

class SVX_DLLPUBLIC SdrDragMethod {
protected:
    SdrDragView& rView;
    bool         bMoveOnly;
protected:
//#if 0 // _SOLAR__PRIVATE
    void               ImpTakeDescriptionStr(USHORT nStrCacheID, String& rStr, USHORT nVal=0) const;
//#endif // __PRIVATE
    SdrHdl*            GetDragHdl() const              { return rView.pDragHdl; }
    SdrHdlKind         GetDragHdlKind() const          { return rView.eDragHdl; }
    SdrDragStat&       DragStat()                      { return rView.aDragStat; }
    const SdrDragStat& DragStat() const                { return rView.aDragStat; }
    Point&             Ref1() const                    { return rView.aRef1; }
    Point&             Ref2() const                    { return rView.aRef2; }
    const SdrHdlList&  GetHdlList() const              { return rView.aHdl; }
    void               AddUndo(SdrUndoAction* pUndo)   { rView.AddUndo(pUndo); }
    void               SetDragPolys()                  { rView.SetDragPolys(); }
    FASTBOOL           IsDragLimit()                   { return rView.bDragLimit; }
    const Rectangle&   GetDragLimitRect()              { return rView.aDragLimit; }
    const SdrMarkList& GetMarkedObjectList()                   { return rView.GetMarkedObjectList(); }
    Point              GetSnapPos(const Point& rPt) const { return rView.GetSnapPos(rPt,rView.pMarkedPV); }
    USHORT             SnapPos(Point& rPt) const       { return rView.SnapPos(rPt,rView.pMarkedPV); }
    inline const Rectangle& GetMarkedRect() const;
    SdrPageView*       GetDragPV() const;
    SdrObject*         GetDragObj() const;
    OutputDevice*      GetDragWin() const              { return rView.pDragWin; }
    FASTBOOL           IsDraggingPoints() const        { return rView.IsDraggingPoints(); }
    FASTBOOL           IsDraggingGluePoints() const    { return rView.IsDraggingGluePoints(); }

    void CreateOverlayGeometryLines(basegfx::B2DPolyPolygon& rResult);
    void CreateOverlayGeometryPoints(basegfx::B2DPolyPolygon& rResult, const Size& rLogicSize);
    sal_Bool DoAddConnectorOverlays();
    void AddConnectorOverlays(basegfx::B2DPolyPolygon& rResult);
    sal_Bool DoAddDragStripeOverlay();

public:
    TYPEINFO();

    // #i58950# also moved constructor implementation to cxx
    SdrDragMethod(SdrDragView& rNewView);

    // #i58950# virtual destructor was missing
    virtual ~SdrDragMethod();

    virtual void Draw() const;
    virtual void Show();
    virtual void Hide();
    virtual void TakeComment(String& rStr) const=0;
    virtual FASTBOOL Beg()=0;
    virtual void MovAllPoints();
    virtual void MovPoint(Point& rPnt);
    virtual void Mov(const Point& rPnt)=0;
    virtual FASTBOOL End(FASTBOOL bCopy)=0;
    virtual void Brk();
    virtual Pointer GetPointer() const=0;
    virtual FASTBOOL IsMoveOnly() const; // TRUE, wenn nur verschoben wird

    // for migration from XOR to overlay
    virtual void CreateOverlayGeometry(::sdr::overlay::OverlayManager& rOverlayManager, ::sdr::overlay::OverlayObjectList& rOverlayList);
};

inline const Rectangle& SdrDragMethod::GetMarkedRect() const
{
    return rView.eDragHdl==HDL_POLY ? rView.GetMarkedPointsRect() :
           rView.eDragHdl==HDL_GLUE ? rView.GetMarkedGluePointsRect() :
           rView.GetMarkedObjRect();
}

//************************************************************
//   SdrDragMove
//************************************************************

class SVX_DLLPUBLIC SdrDragMove : public SdrDragMethod
{
    long                        nBestXSnap;
    long                        nBestYSnap;
    FASTBOOL                    bXSnapped;
    FASTBOOL                    bYSnapped;

private:
    void ImpCheckSnap(const Point& rPt);

public:
    TYPEINFO();
    SdrDragMove(SdrDragView& rNewView): SdrDragMethod(rNewView) {}

    virtual void TakeComment(String& rStr) const;

    virtual FASTBOOL Beg();
    virtual void MovAllPoints();
    virtual void MovPoint(Point& rPnt);
//  virtual void MovPoint(Point& rPnt, const Point& rPvOfs);
    virtual void Mov(const Point& rPnt);
    virtual FASTBOOL End(FASTBOOL bCopy);
    virtual FASTBOOL IsMoveOnly() const;
    virtual Pointer GetPointer() const;
};

//************************************************************
//   SdrDragResize
//************************************************************

class SVX_DLLPUBLIC SdrDragResize : public SdrDragMethod
{
protected:
    Fraction                    aXFact;
    Fraction                    aYFact;

public:
    TYPEINFO();
    SdrDragResize(SdrDragView& rNewView): SdrDragMethod(rNewView), aXFact(1,1), aYFact(1,1) {}

    virtual void TakeComment(String& rStr) const;

    virtual FASTBOOL Beg();
    virtual void MovPoint(Point& rPnt);
    virtual void Mov(const Point& rPnt);
    virtual FASTBOOL End(FASTBOOL bCopy);
    virtual Pointer GetPointer() const;
};

//************************************************************
//   SdrDragObjOwn
//************************************************************

class SVX_DLLPUBLIC SdrDragObjOwn : public SdrDragMethod
{
public:
    TYPEINFO();
    SdrDragObjOwn(SdrDragView& rNewView): SdrDragMethod(rNewView) {}

    virtual void TakeComment(String& rStr) const;

    virtual FASTBOOL Beg();
    virtual void Mov(const Point& rPnt);
    virtual FASTBOOL End(FASTBOOL bCopy);
    virtual Pointer GetPointer() const;

    // for migration from XOR to overlay
    virtual void CreateOverlayGeometry(::sdr::overlay::OverlayManager& rOverlayManager, ::sdr::overlay::OverlayObjectList& rOverlayList);

    //SJ: added following method, otherwise the object won't be
    //able to notice that dragging has been cancelled.
    virtual void Brk();
};

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SVDDRGMT_HXX

<|endoftext|>


<commit_before>#include "xchainer/backprop.h"

#include <memory>
#include <queue>
#include <unordered_map>

#include <gsl/gsl>
#include <nonstd/optional.hpp>

#include "xchainer/array.h"
#include "xchainer/array_node.h"
#include "xchainer/op_node.h"

namespace xchainer {
namespace {

auto cmp = [](std::shared_ptr<const OpNode> lhs, std::shared_ptr<const OpNode> rhs) { return lhs->rank() < rhs->rank(); };

class BackwardImpl {
    using CandidateOpNodes = std::priority_queue<std::shared_ptr<const OpNode>, std::vector<std::shared_ptr<const OpNode>>, decltype(cmp)>;
    using PreviousArrayNodeMap = std::unordered_map<std::shared_ptr<const OpNode>, std::shared_ptr<ArrayNode>>;

public:
    BackwardImpl() : candidate_op_nodes_(cmp) {};

    void run(Array& output) {
        std::shared_ptr<ArrayNode> array_node = output.mutable_node();
        if (!array_node->grad()) {
            array_node->set_grad(Array::OnesLike(output));
        }
        BuildCandidateOpNodes(array_node);
        ProcessOpNodes();
    };

private:
    void BuildCandidateOpNodes(std::shared_ptr<ArrayNode> array_node) {
        std::shared_ptr<const OpNode> op_node = array_node->next_node();
        if (op_node) {
            PushOpNode(op_node);
            InsertPreviousArrayNode(op_node, array_node);
            auto next_array_nodes = op_node->next_nodes();
            auto backward_functions = op_node->backward_functions();
            auto next_size = next_array_nodes.size();
            for (decltype(next_size) i = 0; i < next_size; ++i) {
                if (backward_functions[i]) {
                    BuildCandidateOpNodes(next_array_nodes[i]);
                }
            }
        }
    }

    std::vector<nonstd::optional<Array>> ComputeNextGradients() {
        std::shared_ptr<const OpNode> op_node = TopOpNode();
        std::shared_ptr<ArrayNode> previous_array_node = PreviousArrayNode(op_node);

        nonstd::optional<Array> gy = previous_array_node->grad();
        assert(gy);
        previous_array_node->ClearGrad();

        std::vector<nonstd::optional<Array>> gxs;
        for (auto& backward_function : op_node->backward_functions()) {
            if (backward_function) {
                Array gx = backward_function(*gy);
                gxs.emplace_back(std::move(gx));
            } else {
                gxs.emplace_back(nonstd::nullopt);
            }
        }
        return gxs;
    }

    void AccumulateNextGradients(std::vector<nonstd::optional<Array>> gxs) {
        std::shared_ptr<const OpNode> op_node = TopOpNode();
        gsl::span<const std::shared_ptr<ArrayNode>> next_nodes = op_node->next_nodes();
        auto next_size = next_nodes.size();
        for (decltype(next_size) i = 0; i < next_size; ++i) {
            nonstd::optional<Array> gx = std::move(gxs[i]);
            std::shared_ptr<ArrayNode> next_node = next_nodes[i];
            if (gx) {
                const nonstd::optional<Array>& grad = next_node->grad();
                if (grad) {
                    next_node->set_grad(*grad + *gx);
                } else {
                    next_node->set_grad(std::move(*gx));
                }
            }
        }
    }

    void ProcessOpNodes() {
        while (!EmptyOpNodes()) {
            std::vector<nonstd::optional<Array>> gxs = ComputeNextGradients();
            AccumulateNextGradients(gxs);
            PopOpNode();
        }
    }

    const std::shared_ptr<const OpNode>& TopOpNode() const {
        return candidate_op_nodes_.top();
    }

    bool EmptyOpNodes() const noexcept {
        return candidate_op_nodes_.empty();
    }

    void PushOpNode(std::shared_ptr<const OpNode> op_node) {
        candidate_op_nodes_.push(std::move(op_node));
    }

    void PopOpNode() {
        candidate_op_nodes_.pop();
    }

    std::shared_ptr<ArrayNode> PreviousArrayNode(std::shared_ptr<const OpNode> op_node) const {
        auto it = previous_array_node_map_.find(op_node);
        assert(it != previous_array_node_map_.end());
        return it->second;
    }

    void InsertPreviousArrayNode(std::shared_ptr<const OpNode> op_node, std::shared_ptr<ArrayNode> array_node) {
        previous_array_node_map_.emplace(std::move(op_node), std::move(array_node));
    }

    CandidateOpNodes candidate_op_nodes_;
    PreviousArrayNodeMap previous_array_node_map_;
};

}  // namespace

void Backward(Array& output) {
    BackwardImpl impl;
    impl.run(output);
}

}  // namespace xchainer
<commit_msg>Combine lines<commit_after>#include "xchainer/backprop.h"

#include <memory>
#include <queue>
#include <unordered_map>

#include <gsl/gsl>
#include <nonstd/optional.hpp>

#include "xchainer/array.h"
#include "xchainer/array_node.h"
#include "xchainer/op_node.h"

namespace xchainer {
namespace {

auto cmp = [](std::shared_ptr<const OpNode> lhs, std::shared_ptr<const OpNode> rhs) { return lhs->rank() < rhs->rank(); };

class BackwardImpl {
    using CandidateOpNodes = std::priority_queue<std::shared_ptr<const OpNode>, std::vector<std::shared_ptr<const OpNode>>, decltype(cmp)>;
    using PreviousArrayNodeMap = std::unordered_map<std::shared_ptr<const OpNode>, std::shared_ptr<ArrayNode>>;

public:
    BackwardImpl() : candidate_op_nodes_(cmp) {};

    void run(Array& output) {
        std::shared_ptr<ArrayNode> array_node = output.mutable_node();
        if (!array_node->grad()) {
            array_node->set_grad(Array::OnesLike(output));
        }
        BuildCandidateOpNodes(array_node);
        ProcessOpNodes();
    };

private:
    void BuildCandidateOpNodes(std::shared_ptr<ArrayNode> array_node) {
        std::shared_ptr<const OpNode> op_node = array_node->next_node();
        if (op_node) {
            PushOpNode(op_node);
            InsertPreviousArrayNode(op_node, array_node);
            auto next_array_nodes = op_node->next_nodes();
            auto backward_functions = op_node->backward_functions();
            auto next_size = next_array_nodes.size();
            for (decltype(next_size) i = 0; i < next_size; ++i) {
                if (backward_functions[i]) {
                    BuildCandidateOpNodes(next_array_nodes[i]);
                }
            }
        }
    }

    std::vector<nonstd::optional<Array>> ComputeNextGradients() {
        std::shared_ptr<const OpNode> op_node = TopOpNode();
        std::shared_ptr<ArrayNode> previous_array_node = PreviousArrayNode(op_node);

        nonstd::optional<Array> gy = previous_array_node->grad();
        assert(gy);
        previous_array_node->ClearGrad();

        std::vector<nonstd::optional<Array>> gxs;
        for (auto& backward_function : op_node->backward_functions()) {
            if (backward_function) {
                gxs.emplace_back(backward_function(*gy));
            } else {
                gxs.emplace_back(nonstd::nullopt);
            }
        }
        return gxs;
    }

    void AccumulateNextGradients(std::vector<nonstd::optional<Array>> gxs) {
        std::shared_ptr<const OpNode> op_node = TopOpNode();
        gsl::span<const std::shared_ptr<ArrayNode>> next_nodes = op_node->next_nodes();
        auto next_size = next_nodes.size();
        for (decltype(next_size) i = 0; i < next_size; ++i) {
            nonstd::optional<Array> gx = std::move(gxs[i]);
            std::shared_ptr<ArrayNode> next_node = next_nodes[i];
            if (gx) {
                const nonstd::optional<Array>& grad = next_node->grad();
                if (grad) {
                    next_node->set_grad(*grad + *gx);
                } else {
                    next_node->set_grad(std::move(*gx));
                }
            }
        }
    }

    void ProcessOpNodes() {
        while (!EmptyOpNodes()) {
            std::vector<nonstd::optional<Array>> gxs = ComputeNextGradients();
            AccumulateNextGradients(gxs);
            PopOpNode();
        }
    }

    const std::shared_ptr<const OpNode>& TopOpNode() const {
        return candidate_op_nodes_.top();
    }

    bool EmptyOpNodes() const noexcept {
        return candidate_op_nodes_.empty();
    }

    void PushOpNode(std::shared_ptr<const OpNode> op_node) {
        candidate_op_nodes_.push(std::move(op_node));
    }

    void PopOpNode() {
        candidate_op_nodes_.pop();
    }

    std::shared_ptr<ArrayNode> PreviousArrayNode(std::shared_ptr<const OpNode> op_node) const {
        auto it = previous_array_node_map_.find(op_node);
        assert(it != previous_array_node_map_.end());
        return it->second;
    }

    void InsertPreviousArrayNode(std::shared_ptr<const OpNode> op_node, std::shared_ptr<ArrayNode> array_node) {
        previous_array_node_map_.emplace(std::move(op_node), std::move(array_node));
    }

    CandidateOpNodes candidate_op_nodes_;
    PreviousArrayNodeMap previous_array_node_map_;
};

}  // namespace

void Backward(Array& output) {
    BackwardImpl impl;
    impl.run(output);
}

}  // namespace xchainer
<|endoftext|>


<commit_before>#include <QtTest/QtTest>
#include <QtTest/qtestcase.h>
#include <QSignalSpy>
#include <QHostInfo>
#include <QDebug>
#include "websocket.h"
#include "unittests.h"

class ComplianceTest : public QObject
{
	Q_OBJECT

public:
	ComplianceTest();

private Q_SLOTS:
	void initTestCase();
	void cleanupTestCase();
	void init();
	void cleanup();
	/**
	 * @brief Runs the autobahn tests against our implementation
	 */
	void autobahnTest();

private:
	QUrl m_url;

	void runTestCases(int startNbr, int stopNbr = -1);
	void runTestCase(int nbr, int total);
};

ComplianceTest::ComplianceTest() :
	m_url("ws://localhost:9001")
{
}

void ComplianceTest::initTestCase()
{
}

void ComplianceTest::cleanupTestCase()
{
}

void ComplianceTest::init()
{
}

void ComplianceTest::cleanup()
{
}

void ComplianceTest::runTestCase(int nbr, int total)
{
	if (nbr == total)
	{
		return;
	}
	WebSocket *pWebSocket = new WebSocket;
	QSignalSpy spy(pWebSocket, SIGNAL(disconnected()));

	//next for every case, connect to url
	//ws://ipaddress:port/runCase?case=<number>&agent=<agentname>
	//where agent name will be QWebSocket
	QObject::connect(pWebSocket, &WebSocket::textMessageReceived, [=](QString message) {
		pWebSocket->send(message);
	});
	QObject::connect(pWebSocket, &WebSocket::binaryMessageReceived, [=](QByteArray message) {
		pWebSocket->send(message);
	});

	qDebug() << "Executing test" << (nbr + 1) << "/" << total;
	QUrl url = m_url;
	url.setPath("/runCase?");
	QUrlQuery query;
	query.addQueryItem("case", QString::number(nbr + 1));
	query.addQueryItem("agent", "QWebSockets");
	url.setQuery(query);
	pWebSocket->open(url);
	spy.wait(60000);
	//pWebSocket->close();
	delete pWebSocket;
	runTestCase(nbr + 1, total);
}

void ComplianceTest::runTestCases(int startNbr, int stopNbr)
{
	runTestCase(startNbr, stopNbr);
}

void ComplianceTest::autobahnTest()
{
	//connect to autobahn server at url ws://ipaddress:port/getCaseCount
	WebSocket *pWebSocket = new WebSocket;
	QUrl url = m_url;
	int numberOfTestCases = 0;
	QSignalSpy spy(pWebSocket, SIGNAL(disconnected()));
	QObject::connect(pWebSocket, &WebSocket::textMessageReceived, [&](QString message) {
		numberOfTestCases = message.toInt();
	});
//	QObject::connect(pWebSocket, &WebSocket::disconnected, [=]() {
//	});

	url.setPath("/getCaseCount");
	pWebSocket->open(url);
	spy.wait(60000);
	QVERIFY(numberOfTestCases > 0);

	QObject::disconnect(pWebSocket, &WebSocket::textMessageReceived, 0, 0);

	//runTestCases(64 + 7, 64+141);	//141
	//runTestCases(64 + 33, 64+33 + 2);	//141
	//runTestCases(73, 77);	//testcase 6.4.1 - 6.4.4
	runTestCases(0, numberOfTestCases);
	//runTestCases(78, 79);	//testcase 6.6.1

	url.setPath("/updateReports?");
	QUrlQuery query;
	query.addQueryItem("agent", "QWebSockets");
	url.setQuery(query);
	pWebSocket->open(url);
	spy.wait(60000);
	delete pWebSocket;
}

DECLARE_TEST(ComplianceTest)

#include "tst_compliance.moc"

<commit_msg>Fixed early close bug<commit_after>#include <QtTest/QtTest>
#include <QtTest/qtestcase.h>
#include <QSignalSpy>
#include <QHostInfo>
#include <QDebug>
#include "websocket.h"
#include "unittests.h"

class ComplianceTest : public QObject
{
	Q_OBJECT

public:
	ComplianceTest();

private Q_SLOTS:
	void initTestCase();
	void cleanupTestCase();
	void init();
	void cleanup();
	/**
	 * @brief Runs the autobahn tests against our implementation
	 */
	void autobahnTest();

private:
	QUrl m_url;

	void runTestCases(int startNbr, int stopNbr = -1);
	void runTestCase(int nbr, int total);
};

ComplianceTest::ComplianceTest() :
	m_url("ws://localhost:9001")
{
}

void ComplianceTest::initTestCase()
{
}

void ComplianceTest::cleanupTestCase()
{
}

void ComplianceTest::init()
{
}

void ComplianceTest::cleanup()
{
}

void ComplianceTest::runTestCase(int nbr, int total)
{
	if (nbr == total)
	{
		return;
	}
	WebSocket *pWebSocket = new WebSocket;
	QSignalSpy spy(pWebSocket, SIGNAL(disconnected()));

	//next for every case, connect to url
	//ws://ipaddress:port/runCase?case=<number>&agent=<agentname>
	//where agent name will be QWebSocket
	QObject::connect(pWebSocket, &WebSocket::textMessageReceived, [=](QString message) {
		pWebSocket->send(message);
	});
	QObject::connect(pWebSocket, &WebSocket::binaryMessageReceived, [=](QByteArray message) {
		pWebSocket->send(message);
	});

	qDebug() << "Executing test" << (nbr + 1) << "/" << total;
	QUrl url = m_url;
	url.setPath("/runCase?");
	QUrlQuery query;
	query.addQueryItem("case", QString::number(nbr + 1));
	query.addQueryItem("agent", "QWebSockets");
	url.setQuery(query);
	pWebSocket->open(url);
	spy.wait(60000);
	//pWebSocket->close();
	//delete pWebSocket;
	runTestCase(nbr + 1, total);
}

void ComplianceTest::runTestCases(int startNbr, int stopNbr)
{
	runTestCase(startNbr, stopNbr);
}

void ComplianceTest::autobahnTest()
{
	//connect to autobahn server at url ws://ipaddress:port/getCaseCount
	WebSocket *pWebSocket = new WebSocket;
	QUrl url = m_url;
	int numberOfTestCases = 0;
	QSignalSpy spy(pWebSocket, SIGNAL(disconnected()));
	QObject::connect(pWebSocket, &WebSocket::textMessageReceived, [&](QString message) {
		numberOfTestCases = message.toInt();
	});
//	QObject::connect(pWebSocket, &WebSocket::disconnected, [=]() {
//	});

	url.setPath("/getCaseCount");
	pWebSocket->open(url);
	spy.wait(60000);
	QVERIFY(numberOfTestCases > 0);

	QObject::disconnect(pWebSocket, &WebSocket::textMessageReceived, 0, 0);

	//runTestCases(64 + 7, 64+141);	//141
	//runTestCases(64 + 33, 64+33 + 2);	//141
	//runTestCases(73, 77);	//testcase 6.4.1 - 6.4.4
	runTestCases(0, numberOfTestCases);
	//runTestCases(78, 79);	//testcase 6.6.1

	url.setPath("/updateReports?");
	QUrlQuery query;
	query.addQueryItem("agent", "QWebSockets");
	url.setQuery(query);
	pWebSocket->open(url);
	spy.wait(60000);
	//delete pWebSocket;
}

DECLARE_TEST(ComplianceTest)

#include "tst_compliance.moc"

<|endoftext|>