<commit_before>/*
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * ``The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * The Original Code is SimpleAmqpClient for RabbitMQ.
 *
 * The Initial Developer of the Original Code is Alan Antonuk.
 * Original code is Copyright (C) Alan Antonuk.
 *
 * All Rights Reserved.
 *
 * Contributor(s): ______________________________________.
 *
 * Alternatively, the contents of this file may be used under the terms
 * of the GNU General Public License Version 2 or later (the "GPL"), in
 * which case the provisions of the GPL are applicable instead of those
 * above. If you wish to allow use of your version of this file only
 * under the terms of the GPL, and not to allow others to use your
 * version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the
 * notice and other provisions required by the GPL. If you do not
 * delete the provisions above, a recipient may use your version of
 * this file under the terms of any one of the MPL or the GPL.
 *
 * ***** END LICENSE BLOCK *****
 */

#include "SimpleAmqpClient.h"

#define BOOST_ALL_NO_LIB
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/thread.hpp>
#include <boost/utility.hpp>

#include <iostream>
#include <stdlib.h>

using namespace AmqpClient;

class thread_body : boost::noncopyable
{
	public:
		thread_body()
		{
			char* szBroker = getenv("AMQP_BROKER");
			Channel::ptr_t channel;
			if (szBroker != NULL)
				channel = Channel::Create(szBroker);
			else
				channel = Channel::Create();

			server = SimpleRpcServer::Create(channel);

			m_thread =
				boost::make_shared<boost::thread>(boost::bind(&thread_body::run,
							this));
		}

		virtual ~thread_body()
		{
			std::cout << "Is joinable " << m_thread->joinable() << "inter reqd: " << m_thread->interruption_requested() << std::endl;
			m_thread->interrupt();
			std::cout << "Is joinable " << m_thread->joinable() << "inter reqd: " << m_thread->interruption_requested() << std::endl;
			m_thread->join();
		}

		void run()
		{
			while (!boost::this_thread::interruption_requested())
			{
				std::cout << "Waiting for message... " << std::flush;
				BasicMessage::ptr_t message;
				if (server->GetNextIncomingMessage(message, 1))
				{
					std::cout << "message received.\n";
				}
				else
				{
					std::cout << "message not received.\n";
				}
			}
		}

		SimpleRpcServer::ptr_t server;
		boost::shared_ptr<boost::thread> m_thread;

};
int main()
{
	boost::shared_ptr<thread_body> body = boost::make_shared<thread_body>();

	boost::this_thread::sleep(boost::posix_time::seconds(3));

	return 0;
}
<commit_msg>Adding more complete consume with timeout example<commit_after>/*
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * ``The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * The Original Code is SimpleAmqpClient for RabbitMQ.
 *
 * The Initial Developer of the Original Code is Alan Antonuk.
 * Original code is Copyright (C) Alan Antonuk.
 *
 * All Rights Reserved.
 *
 * Contributor(s): ______________________________________.
 *
 * Alternatively, the contents of this file may be used under the terms
 * of the GNU General Public License Version 2 or later (the "GPL"), in
 * which case the provisions of the GPL are applicable instead of those
 * above. If you wish to allow use of your version of this file only
 * under the terms of the GPL, and not to allow others to use your
 * version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the
 * notice and other provisions required by the GPL. If you do not
 * delete the provisions above, a recipient may use your version of
 * this file under the terms of any one of the MPL or the GPL.
 *
 * ***** END LICENSE BLOCK *****
 */

#include <SimpleAmqpClient.h>
#include <SimpleAmqpClient/SimpleRpcClient.h>
#include <SimpleAmqpClient/SimpleRpcServer.h>

#define BOOST_ALL_NO_LIB
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/thread.hpp>
#include <boost/utility.hpp>

#include <iostream>
#include <stdlib.h>

using namespace AmqpClient;

class thread_body : boost::noncopyable
{
	public:
		thread_body()
		{
			char* szBroker = getenv("AMQP_BROKER");
			Channel::ptr_t channel;
			if (szBroker != NULL)
				channel = Channel::Create(szBroker);
			else
				channel = Channel::Create();

			server = SimpleRpcServer::Create(channel, "consume_timeout_test");

			m_thread =
				boost::make_shared<boost::thread>(boost::bind(&thread_body::run,
							this));
		}

		virtual ~thread_body()
		{
			std::cout << "Is joinable " << m_thread->joinable() << "inter reqd: " << m_thread->interruption_requested() << std::endl;
			m_thread->interrupt();
			std::cout << "Is joinable " << m_thread->joinable() << "inter reqd: " << m_thread->interruption_requested() << std::endl;
			m_thread->join();
		}

		void run()
		{
			while (!boost::this_thread::interruption_requested())
			{
				std::cout << "Waiting for message... " << std::flush;
				BasicMessage::ptr_t message;
				if (server->GetNextIncomingMessage(message, 1))
				{
					std::cout << "message received.\n";
          server->RespondToMessage(message, "this is a response");
				}
				else
				{
					std::cout << "message not received.\n";
				}
			}
		}

		SimpleRpcServer::ptr_t server;
		boost::shared_ptr<boost::thread> m_thread;

};
int main()
{
	boost::shared_ptr<thread_body> body = boost::make_shared<thread_body>();

	boost::this_thread::sleep(boost::posix_time::seconds(1));

  char* szBroker = getenv("AMQP_BROKER");
  Channel::ptr_t channel;
  if (szBroker != NULL)
    channel = Channel::Create(szBroker);
  else
    channel = Channel::Create();

  SimpleRpcClient::ptr_t client = SimpleRpcClient::Create(channel, "consume_timeout_test");
  std::string str = client->Call("Here is my message");
  std::cout << "Got response: " << str << std::endl;

	boost::this_thread::sleep(boost::posix_time::seconds(2));

	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_POSH_RUNTIME_POSH_RUNTIME_HPP
#define IOX_POSH_RUNTIME_POSH_RUNTIME_HPP

#include "iceoryx_posh/capro/service_description.hpp"
#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/condition_variable_data.hpp"
#include "iceoryx_posh/internal/popo/ports/application_port.hpp"
#include "iceoryx_posh/internal/popo/ports/interface_port.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_user.hpp"
#include "iceoryx_posh/internal/popo/ports/subscriber_port_user.hpp"
#include "iceoryx_posh/internal/runtime/ipc_runtime_interface.hpp"
#include "iceoryx_posh/internal/runtime/node_property.hpp"
#include "iceoryx_posh/popo/subscriber_options.hpp"
#include "iceoryx_posh/runtime/port_config_info.hpp"

#include <atomic>

namespace iox
{
namespace roudi
{
class RuntimeTestInterface;
} // namespace roudi

namespace runtime
{
class Node;
class NodeData;

enum class FindServiceError
{
    INVALID_STATE,
    UNABLE_TO_WRITE_TO_ROUDI_CHANNEL,
    INSTANCE_CONTAINER_OVERFLOW
};

/// @brief The runtime that is needed for each application to communicate with the RouDi daemon
class PoshRuntime
{
  public:
    PoshRuntime(const PoshRuntime&) = delete;
    PoshRuntime& operator=(const PoshRuntime&) = delete;
    PoshRuntime(PoshRuntime&&) = delete;
    PoshRuntime& operator=(PoshRuntime&&) = delete;
    virtual ~PoshRuntime() noexcept = default;

    /// @brief returns active runtime
    ///
    /// @return active runtime
    static PoshRuntime& getInstance() noexcept;

    /// @brief creates the runtime with given name
    ///
    /// @param[in] name used for registering the process with the RouDi daemon
    ///
    /// @return active runtime
    static PoshRuntime& initRuntime(const RuntimeName_t& name) noexcept;

    /// @brief get the name that was used to register with RouDi
    /// @return name of the registered application
    RuntimeName_t getInstanceName() const noexcept;

    /// @brief initiates the shutdown of the runtime to unblock all potentially blocking publisher
    /// with the SubscriberTooSlowPolicy::WAIT_FOR_SUBSCRIBER option set
    void shutdown() noexcept;

    /// @brief find all services that match the provided service description
    /// @param[in] serviceDescription service to search for
    /// @return cxx::expected<InstanceContainer, FindServiceError>
    /// InstanceContainer: on success, container that is filled with all matching instances
    /// FindServiceError: if any, encountered during the operation
    virtual cxx::expected<InstanceContainer, FindServiceError>
    findService(const capro::ServiceDescription& serviceDescription) noexcept = 0;

    /// @brief offer the provided service, sends the offer from application to RouDi daemon
    /// @param[in] serviceDescription service to offer
    /// @return bool, if service is offered returns true else false
    virtual bool offerService(const capro::ServiceDescription& serviceDescription) noexcept = 0;

    /// @brief stop offering the provided service
    /// @param[in] serviceDescription of the service that shall be no more offered
    virtual void stopOfferService(const capro::ServiceDescription& serviceDescription) noexcept = 0;

    /// @brief request the RouDi daemon to create a publisher port
    /// @param[in] serviceDescription service description for the new publisher port
    /// @param[in] publisherOptions like the history capacity of a publisher
    /// @param[in] portConfigInfo configuration information for the port
    /// (i.e. what type of port is requested, device where its payload memory is located on etc.)
    /// @return pointer to a created publisher port user
    virtual PublisherPortUserType::MemberType_t*
    getMiddlewarePublisher(const capro::ServiceDescription& service,
                           const popo::PublisherOptions& publisherOptions = popo::PublisherOptions(),
                           const PortConfigInfo& portConfigInfo = PortConfigInfo()) noexcept = 0;

    /// @brief request the RouDi daemon to create a subscriber port
    /// @param[in] serviceDescription service description for the new subscriber port
    /// @param[in] subscriberOptions like the queue capacity and history requested by a subscriber
    /// @param[in] portConfigInfo configuration information for the port
    /// (what type of port is requested, device where its payload memory is located on etc.)
    /// @return pointer to a created subscriber port data
    virtual SubscriberPortUserType::MemberType_t*
    getMiddlewareSubscriber(const capro::ServiceDescription& service,
                            const popo::SubscriberOptions& subscriberOptions = popo::SubscriberOptions(),
                            const PortConfigInfo& portConfigInfo = PortConfigInfo()) noexcept = 0;

    /// @brief request the RouDi daemon to create an interface port
    /// @param[in] interface interface to create
    /// @param[in] nodeName name of the node where the interface should belong to
    /// @return pointer to a created interface port data
    virtual popo::InterfacePortData* getMiddlewareInterface(const capro::Interfaces interface,
                                                            const NodeName_t& nodeName = {""}) noexcept = 0;

    /// @brief request the RouDi daemon to create an application port
    /// @return pointer to a created application port data
    virtual popo::ApplicationPortData* getMiddlewareApplication() noexcept = 0;

    /// @brief request the RouDi daemon to create a condition variable
    /// @return pointer to a created condition variable data
    virtual popo::ConditionVariableData* getMiddlewareConditionVariable() noexcept = 0;

    /// @brief request the RouDi daemon to create a node
    /// @param[in] nodeProperty class which contains all properties which the node should have
    /// @return pointer to the data of the node
    virtual NodeData* createNode(const NodeProperty& nodeProperty) noexcept = 0;

    /// @brief requests the serviceRegistryChangeCounter from the shared memory
    /// @return pointer to the serviceRegistryChangeCounter
    virtual const std::atomic<uint64_t>* getServiceRegistryChangeCounter() noexcept = 0;

    /// @brief send a request to the RouDi daemon and get the response
    ///        currently each request is followed by a response
    /// @param[in] msg request message to send
    /// @param[out] response from the RouDi daemon
    /// @return true if sucessful request/response, false on error
    virtual bool sendRequestToRouDi(const IpcMessage& msg, IpcMessage& answer) noexcept = 0;

  protected:
    using factory_t = PoshRuntime& (*)(cxx::optional<const RuntimeName_t*>);

    // Protected constructor for derived classes
    PoshRuntime(cxx::optional<const RuntimeName_t*> name) noexcept;

    static PoshRuntime& defaultRuntimeFactory(cxx::optional<const RuntimeName_t*> name) noexcept;

    static RuntimeName_t& defaultRuntimeInstanceName() noexcept;

    /// @brief gets current runtime factory. If the runtime factory is not yet initialized it is set to
    /// defaultRuntimeFactory.
    ///
    /// @return current runtime factory
    static factory_t& getRuntimeFactory() noexcept;

    /// @brief sets runtime factory, terminates if given factory is empty
    ///
    /// @param[in] factory std::function to which the runtime factory should be set
    static void setRuntimeFactory(const factory_t& factory) noexcept;

    /// @brief creates the runtime or returns the already existing one -> Singleton
    ///
    /// @param[in] name optional containing the name used for registering with the RouDi daemon
    ///
    /// @return active runtime
    static PoshRuntime& getInstance(cxx::optional<const RuntimeName_t*> name) noexcept;

    /// @brief checks the given application name for certain constraints like length or if is empty
    const RuntimeName_t& verifyInstanceName(cxx::optional<const RuntimeName_t*> name) noexcept;

    const RuntimeName_t m_appName;
    std::atomic<bool> m_shutdownRequested{false};
};

} // namespace runtime
} // namespace iox

#endif // IOX_POSH_RUNTIME_POSH_RUNTIME_HPP
<commit_msg>iox-#449 Fix build with latest clang<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_POSH_RUNTIME_POSH_RUNTIME_HPP
#define IOX_POSH_RUNTIME_POSH_RUNTIME_HPP

#include "iceoryx_posh/capro/service_description.hpp"
#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/condition_variable_data.hpp"
#include "iceoryx_posh/internal/popo/ports/application_port.hpp"
#include "iceoryx_posh/internal/popo/ports/interface_port.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_user.hpp"
#include "iceoryx_posh/internal/popo/ports/subscriber_port_user.hpp"
#include "iceoryx_posh/internal/runtime/ipc_runtime_interface.hpp"
#include "iceoryx_posh/internal/runtime/node_property.hpp"
#include "iceoryx_posh/popo/subscriber_options.hpp"
#include "iceoryx_posh/runtime/port_config_info.hpp"

#include <atomic>

namespace iox
{
namespace roudi
{
class RuntimeTestInterface;
} // namespace roudi

namespace runtime
{
class Node;
class NodeData;

enum class FindServiceError
{
    INVALID_STATE,
    UNABLE_TO_WRITE_TO_ROUDI_CHANNEL,
    INSTANCE_CONTAINER_OVERFLOW
};

/// @brief The runtime that is needed for each application to communicate with the RouDi daemon
class PoshRuntime
{
  public:
    PoshRuntime(const PoshRuntime&) = delete;
    PoshRuntime& operator=(const PoshRuntime&) = delete;
    PoshRuntime(PoshRuntime&&) = delete;
    PoshRuntime& operator=(PoshRuntime&&) = delete;
    virtual ~PoshRuntime() noexcept = default;

    /// @brief returns active runtime
    ///
    /// @return active runtime
    static PoshRuntime& getInstance() noexcept;

    /// @brief creates the runtime with given name
    ///
    /// @param[in] name used for registering the process with the RouDi daemon
    ///
    /// @return active runtime
    static PoshRuntime& initRuntime(const RuntimeName_t& name) noexcept;

    /// @brief get the name that was used to register with RouDi
    /// @return name of the registered application
    RuntimeName_t getInstanceName() const noexcept;

    /// @brief initiates the shutdown of the runtime to unblock all potentially blocking publisher
    /// with the SubscriberTooSlowPolicy::WAIT_FOR_SUBSCRIBER option set
    void shutdown() noexcept;

    /// @brief find all services that match the provided service description
    /// @param[in] serviceDescription service to search for
    /// @return cxx::expected<InstanceContainer, FindServiceError>
    /// InstanceContainer: on success, container that is filled with all matching instances
    /// FindServiceError: if any, encountered during the operation
    virtual cxx::expected<InstanceContainer, FindServiceError>
    findService(const capro::ServiceDescription& serviceDescription) noexcept = 0;

    /// @brief offer the provided service, sends the offer from application to RouDi daemon
    /// @param[in] serviceDescription service to offer
    /// @return bool, if service is offered returns true else false
    virtual bool offerService(const capro::ServiceDescription& serviceDescription) noexcept = 0;

    /// @brief stop offering the provided service
    /// @param[in] serviceDescription of the service that shall be no more offered
    virtual void stopOfferService(const capro::ServiceDescription& serviceDescription) noexcept = 0;

    /// @brief request the RouDi daemon to create a publisher port
    /// @param[in] serviceDescription service description for the new publisher port
    /// @param[in] publisherOptions like the history capacity of a publisher
    /// @param[in] portConfigInfo configuration information for the port
    /// (i.e. what type of port is requested, device where its payload memory is located on etc.)
    /// @return pointer to a created publisher port user
    virtual PublisherPortUserType::MemberType_t*
    getMiddlewarePublisher(const capro::ServiceDescription& service,
                           const popo::PublisherOptions& publisherOptions = popo::PublisherOptions(),
                           const PortConfigInfo& portConfigInfo = PortConfigInfo()) noexcept = 0;

    /// @brief request the RouDi daemon to create a subscriber port
    /// @param[in] serviceDescription service description for the new subscriber port
    /// @param[in] subscriberOptions like the queue capacity and history requested by a subscriber
    /// @param[in] portConfigInfo configuration information for the port
    /// (what type of port is requested, device where its payload memory is located on etc.)
    /// @return pointer to a created subscriber port data
    virtual SubscriberPortUserType::MemberType_t*
    getMiddlewareSubscriber(const capro::ServiceDescription& service,
                            const popo::SubscriberOptions& subscriberOptions = popo::SubscriberOptions(),
                            const PortConfigInfo& portConfigInfo = PortConfigInfo()) noexcept = 0;

    /// @brief request the RouDi daemon to create an interface port
    /// @param[in] interface interface to create
    /// @param[in] nodeName name of the node where the interface should belong to
    /// @return pointer to a created interface port data
    virtual popo::InterfacePortData* getMiddlewareInterface(const capro::Interfaces interface,
                                                            const NodeName_t& nodeName = {""}) noexcept = 0;

    /// @brief request the RouDi daemon to create an application port
    /// @return pointer to a created application port data
    virtual popo::ApplicationPortData* getMiddlewareApplication() noexcept = 0;

    /// @brief request the RouDi daemon to create a condition variable
    /// @return pointer to a created condition variable data
    virtual popo::ConditionVariableData* getMiddlewareConditionVariable() noexcept = 0;

    /// @brief request the RouDi daemon to create a node
    /// @param[in] nodeProperty class which contains all properties which the node should have
    /// @return pointer to the data of the node
    virtual NodeData* createNode(const NodeProperty& nodeProperty) noexcept = 0;

    /// @brief requests the serviceRegistryChangeCounter from the shared memory
    /// @return pointer to the serviceRegistryChangeCounter
    virtual const std::atomic<uint64_t>* getServiceRegistryChangeCounter() noexcept = 0;

    /// @brief send a request to the RouDi daemon and get the response
    ///        currently each request is followed by a response
    /// @param[in] msg request message to send
    /// @param[out] response from the RouDi daemon
    /// @return true if sucessful request/response, false on error
    virtual bool sendRequestToRouDi(const IpcMessage& msg, IpcMessage& answer) noexcept = 0;

  protected:
    friend class roudi::RuntimeTestInterface;
    using factory_t = PoshRuntime& (*)(cxx::optional<const RuntimeName_t*>);

    // Protected constructor for derived classes
    PoshRuntime(cxx::optional<const RuntimeName_t*> name) noexcept;

    static PoshRuntime& defaultRuntimeFactory(cxx::optional<const RuntimeName_t*> name) noexcept;

    static RuntimeName_t& defaultRuntimeInstanceName() noexcept;

    /// @brief gets current runtime factory. If the runtime factory is not yet initialized it is set to
    /// defaultRuntimeFactory.
    ///
    /// @return current runtime factory
    static factory_t& getRuntimeFactory() noexcept;

    /// @brief sets runtime factory, terminates if given factory is empty
    ///
    /// @param[in] factory std::function to which the runtime factory should be set
    static void setRuntimeFactory(const factory_t& factory) noexcept;

    /// @brief creates the runtime or returns the already existing one -> Singleton
    ///
    /// @param[in] name optional containing the name used for registering with the RouDi daemon
    ///
    /// @return active runtime
    static PoshRuntime& getInstance(cxx::optional<const RuntimeName_t*> name) noexcept;

    /// @brief checks the given application name for certain constraints like length or if is empty
    const RuntimeName_t& verifyInstanceName(cxx::optional<const RuntimeName_t*> name) noexcept;

    const RuntimeName_t m_appName;
    std::atomic<bool> m_shutdownRequested{false};
};

} // namespace runtime
} // namespace iox

#endif // IOX_POSH_RUNTIME_POSH_RUNTIME_HPP
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//                       Copyright (c) 2011 - 2012 by                        //
//                                Simon Pratt                                //
//                           (All rights reserved)                           //
///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// FILE:    test_polygonal_subdivision.cpp                                   //
//                                                                           //
// MODULE:  Polygonal Subdivision                                            //
//                                                                           //
// NOTES:   None.                                                            //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <iterator>
#include <ctime>
#include "../Point2D.hpp"
#include "../LineSegment.hpp"
#include "../PolygonalSubdivision.hpp"

using namespace std;
using namespace geometry;

int main(int argc, char** argv) {
  // if not enough parameters provided, print a helpful message and quit
  if(argc < 3) {
    cout << "usage: " << argv[0] << " [segments file] [points file]" << endl
	 << "\t where [segments file] is a file containing line segments" << endl
	 << "\t and   [points file]   is a file containing query points" << endl;
    return 0;
  }
  time_t start = time(0);
  time_t last = start;
  // for segment input
  ifstream segment_file(argv[1]);
  istream_iterator<LineSegment> segment_begin(segment_file);
  istream_iterator<LineSegment> segment_end;

  // for point input
  ifstream point_file(argv[2]);
  istream_iterator<Point2D> point_begin(point_file);
  istream_iterator<Point2D> point_end;

  PolygonalSubdivision ps;

  // read in the segments
  while(segment_begin != segment_end) {
    ps.addLineSegment(*segment_begin);
    ++segment_begin;
  }
  // ready the structure for queries
  ps.lock();

  time_t now = time(0);
  cout << "Build took: " << difftime(now,last) << endl;
  last = now;

  // locate and print the containing polygon for each point
  while(point_begin != point_end) {
    try{
      cout << ps.locate_point(*point_begin) << endl;
    }catch(char const* str) {
      cout << "=== ERROR === " << str << endl;
      return 1;
    }
    ++point_begin;
  }

  now = time(0);
  cout << "Queries took: " << difftime(now,last) << endl;
  cout << "Total time: " << difftime(now,start) << endl;
  last = now;

  return 0;
}
<commit_msg>Now printing query points<commit_after>///////////////////////////////////////////////////////////////////////////////
//                       Copyright (c) 2011 - 2012 by                        //
//                                Simon Pratt                                //
//                           (All rights reserved)                           //
///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// FILE:    test_polygonal_subdivision.cpp                                   //
//                                                                           //
// MODULE:  Polygonal Subdivision                                            //
//                                                                           //
// NOTES:   None.                                                            //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <iterator>
#include <ctime>
#include "../Point2D.hpp"
#include "../LineSegment.hpp"
#include "../PolygonalSubdivision.hpp"

using namespace std;
using namespace geometry;

int main(int argc, char** argv) {
  // if not enough parameters provided, print a helpful message and quit
  if(argc < 3) {
    cout << "usage: " << argv[0] << " [segments file] [points file]" << endl
	 << "\t where [segments file] is a file containing line segments" << endl
	 << "\t and   [points file]   is a file containing query points" << endl;
    return 0;
  }
  time_t start = time(0);
  time_t last = start;
  // for segment input
  ifstream segment_file(argv[1]);
  istream_iterator<LineSegment> segment_begin(segment_file);
  istream_iterator<LineSegment> segment_end;

  // for point input
  ifstream point_file(argv[2]);
  istream_iterator<Point2D> point_begin(point_file);
  istream_iterator<Point2D> point_end;

  PolygonalSubdivision ps;

  // read in the segments
  while(segment_begin != segment_end) {
    ps.addLineSegment(*segment_begin);
    ++segment_begin;
  }
  // ready the structure for queries
  ps.lock();

  time_t now = time(0);
  cout << "Build took: " << difftime(now,last) << endl;
  last = now;

  // locate and print the containing polygon for each point
  while(point_begin != point_end) {
    try{
      cout << "Point " << *point_begin << ": "
	   << ps.locate_point(*point_begin) << endl;
    }catch(char const* str) {
      cout << "=== ERROR === " << str << endl;
      return 1;
    }
    ++point_begin;
  }

  now = time(0);
  cout << "Queries took: " << difftime(now,last) << endl;
  cout << "Total time: " << difftime(now,start) << endl;
  last = now;

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>`SettingMaster::set_and_print`: print message if Entity name is invalid.<commit_after><|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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_dbaccess.hxx"

#if defined(WNT)
#if defined _MSC_VER
#pragma warning(push, 1)
#pragma warning(disable: 4917)
#endif
#include "msdasc.h"        // OLE DB Service Component header
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include "stdio.h"

#include <initguid.h>  // Include only once in your application
#include <adoid.h>     // needed for CLSID_CADOConnection
#include <adoint.h>    // needed for ADOConnection

#include "adodatalinks.hxx"

BSTR PromptEdit(long hWnd,BSTR connstr);
BSTR PromptNew(long hWnd);

::rtl::OUString getAdoDatalink(long hWnd,::rtl::OUString& oldLink)
{
    ::rtl::OUString dataLink;
    if (oldLink.getLength())
    {
        dataLink=reinterpret_cast<sal_Unicode *>(PromptEdit(hWnd,(BSTR)oldLink.getStr()));
    }
    else
        dataLink=reinterpret_cast<sal_Unicode *>(PromptNew(hWnd));
    return dataLink;
}
BSTR PromptNew(long hWnd)
{
    BSTR connstr=NULL;
    HRESULT hr;
    IDataSourceLocator* dlPrompt = NULL;
    ADOConnection* piTmpConnection = NULL;
    BSTR _result=NULL;

     // Initialize COM
     ::CoInitialize( NULL );

    // Instantiate DataLinks object.
      hr = CoCreateInstance(
                    CLSID_DataLinks,                //clsid -- Data Links UI
                    NULL,                           //pUnkOuter
                    CLSCTX_INPROC_SERVER,           //dwClsContext
                    IID_IDataSourceLocator,     //riid
                    (void**)&dlPrompt   //ppvObj
                    );
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    dlPrompt->put_hWnd(hWnd);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    // Prompt for connection information.
    hr = dlPrompt->PromptNew((IDispatch **)&piTmpConnection);

    if( FAILED( hr ) || !piTmpConnection )
    {
        dlPrompt->Release( );
        return connstr;
    }

    hr = piTmpConnection->get_ConnectionString(&_result);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    piTmpConnection->Release( );
    dlPrompt->Release( );
    CoUninitialize();
    return _result;
}

BSTR PromptEdit(long hWnd,BSTR connstr)
{
    HRESULT hr;
    IDataSourceLocator* dlPrompt = NULL;
    ADOConnection* piTmpConnection = NULL;
    BSTR _result=NULL;

     // Initialize COM
     ::CoInitialize( NULL );

     hr = CoCreateInstance(CLSID_CADOConnection,
                NULL,
                CLSCTX_INPROC_SERVER,
                IID_IADOConnection,
                (LPVOID *)&piTmpConnection);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        return connstr;
    }

    hr = piTmpConnection->put_ConnectionString(connstr);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        return connstr;
    }

    // Instantiate DataLinks object.
      hr = CoCreateInstance(
                    CLSID_DataLinks,                //clsid -- Data Links UI
                    NULL,                           //pUnkOuter
                    CLSCTX_INPROC_SERVER,           //dwClsContext
                    IID_IDataSourceLocator,     //riid
                    (void**)&dlPrompt   //ppvObj
                    );
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    dlPrompt->put_hWnd(hWnd);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    VARIANT_BOOL pbSuccess;

    // Prompt for connection information.
    hr = dlPrompt->PromptEdit((IDispatch **)&piTmpConnection,&pbSuccess);
    if( SUCCEEDED( hr ) && sal_False == pbSuccess ) //if user press cancel then sal_False == pbSuccess
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    if( FAILED( hr ) )
    {
        // Prompt for new connection information.
        piTmpConnection->Release( );
        piTmpConnection = NULL;
        hr = dlPrompt->PromptNew((IDispatch **)&piTmpConnection);
        if(  FAILED( hr ) || !piTmpConnection )
        {
            dlPrompt->Release( );
            return connstr;
        }
    }

    hr = piTmpConnection->get_ConnectionString(&_result);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    piTmpConnection->Release( );
    dlPrompt->Release( );
    CoUninitialize();
    return _result;
}
#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Plug MinGW gaps<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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_dbaccess.hxx"

#if defined(WNT)
#if defined _MSC_VER
#pragma warning(push, 1)
#pragma warning(disable: 4917)
#endif
#include "msdasc.h"        // OLE DB Service Component header
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include "stdio.h"

#include <initguid.h>  // Include only once in your application
#include <adoid.h>     // needed for CLSID_CADOConnection
#include <adoint.h>    // needed for ADOConnection

#include "adodatalinks.hxx"

#ifdef __MINGW32__
const IID IID_IDataSourceLocator = { 0x2206CCB2, 0x19C1, 0x11D1, { 0x89, 0xE0, 0x00, 0xC0, 0x4F, 0xD7, 0xA8, 0x29 } };
const CLSID CLSID_DataLinks = { 0x2206CDB2, 0x19C1, 0x11D1, { 0x89, 0xE0, 0x00, 0xC0, 0x4F, 0xD7, 0xA8, 0x29 } };
#endif

BSTR PromptEdit(long hWnd,BSTR connstr);
BSTR PromptNew(long hWnd);

::rtl::OUString getAdoDatalink(long hWnd,::rtl::OUString& oldLink)
{
    ::rtl::OUString dataLink;
    if (oldLink.getLength())
    {
        dataLink=reinterpret_cast<sal_Unicode *>(PromptEdit(hWnd,(BSTR)oldLink.getStr()));
    }
    else
        dataLink=reinterpret_cast<sal_Unicode *>(PromptNew(hWnd));
    return dataLink;
}
BSTR PromptNew(long hWnd)
{
    BSTR connstr=NULL;
    HRESULT hr;
    IDataSourceLocator* dlPrompt = NULL;
    ADOConnection* piTmpConnection = NULL;
    BSTR _result=NULL;

     // Initialize COM
     ::CoInitialize( NULL );

    // Instantiate DataLinks object.
      hr = CoCreateInstance(
                    CLSID_DataLinks,                //clsid -- Data Links UI
                    NULL,                           //pUnkOuter
                    CLSCTX_INPROC_SERVER,           //dwClsContext
                    IID_IDataSourceLocator,     //riid
                    (void**)&dlPrompt   //ppvObj
                    );
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    dlPrompt->put_hWnd(hWnd);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    // Prompt for connection information.
    hr = dlPrompt->PromptNew((IDispatch **)&piTmpConnection);

    if( FAILED( hr ) || !piTmpConnection )
    {
        dlPrompt->Release( );
        return connstr;
    }

    hr = piTmpConnection->get_ConnectionString(&_result);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    piTmpConnection->Release( );
    dlPrompt->Release( );
    CoUninitialize();
    return _result;
}

BSTR PromptEdit(long hWnd,BSTR connstr)
{
    HRESULT hr;
    IDataSourceLocator* dlPrompt = NULL;
    ADOConnection* piTmpConnection = NULL;
    BSTR _result=NULL;

     // Initialize COM
     ::CoInitialize( NULL );

     hr = CoCreateInstance(CLSID_CADOConnection,
                NULL,
                CLSCTX_INPROC_SERVER,
                IID_IADOConnection,
                (LPVOID *)&piTmpConnection);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        return connstr;
    }

    hr = piTmpConnection->put_ConnectionString(connstr);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        return connstr;
    }

    // Instantiate DataLinks object.
      hr = CoCreateInstance(
                    CLSID_DataLinks,                //clsid -- Data Links UI
                    NULL,                           //pUnkOuter
                    CLSCTX_INPROC_SERVER,           //dwClsContext
                    IID_IDataSourceLocator,     //riid
                    (void**)&dlPrompt   //ppvObj
                    );
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    dlPrompt->put_hWnd(hWnd);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    VARIANT_BOOL pbSuccess;

    // Prompt for connection information.
    hr = dlPrompt->PromptEdit((IDispatch **)&piTmpConnection,&pbSuccess);
    if( SUCCEEDED( hr ) && sal_False == pbSuccess ) //if user press cancel then sal_False == pbSuccess
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    if( FAILED( hr ) )
    {
        // Prompt for new connection information.
        piTmpConnection->Release( );
        piTmpConnection = NULL;
        hr = dlPrompt->PromptNew((IDispatch **)&piTmpConnection);
        if(  FAILED( hr ) || !piTmpConnection )
        {
            dlPrompt->Release( );
            return connstr;
        }
    }

    hr = piTmpConnection->get_ConnectionString(&_result);
    if( FAILED( hr ) )
    {
        piTmpConnection->Release( );
        dlPrompt->Release( );
        return connstr;
    }

    piTmpConnection->Release( );
    dlPrompt->Release( );
    CoUninitialize();
    return _result;
}
#endif

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


<commit_before><commit_msg>Bugfix: added missing `#include` line.<commit_after><|endoftext|>


<commit_before>#include <GL/glew.h> // include GLEW and new version of GL on Windows
#include <GLFW/glfw3.h>

#include "graphics/gatherer_graphics.h"
#include "GLContextWindow.h"
#include "OGLESGPGPUTest.h"

#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

#include <iostream>

int main(int argc, char **argv)
{
    cv::VideoCapture capture(0);
    cv::Size size(int(capture.get(cv::CAP_PROP_FRAME_WIDTH)), int(capture.get(cv::CAP_PROP_FRAME_HEIGHT)));

    size = size / 4;

    // Create the context
    gatherer::graphics::GLContextWindow window(size, "display");
    gatherer::graphics::OEGLGPGPUTest test(&window, window.getResolution().x);

    while( /*capture */ true )
    {
        cv::Mat frame;
        capture >> frame;
        cv::resize(frame, frame, size);
        cv::cvtColor(frame, frame, cv::COLOR_BGR2BGRA);
        test.captureOutput(frame);
        window.swapBuffers();
    }
}
<commit_msg>display full resolution video in ogles_gpgpu_test sample<commit_after>#include <GL/glew.h> // include GLEW and new version of GL on Windows
#include <GLFW/glfw3.h>

#include "graphics/gatherer_graphics.h"
#include "GLContextWindow.h"
#include "OGLESGPGPUTest.h"

#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

#include <iostream>

int main(int argc, char **argv)
{
    cv::VideoCapture capture(0);
    cv::Size size(int(capture.get(cv::CAP_PROP_FRAME_WIDTH)), int(capture.get(cv::CAP_PROP_FRAME_HEIGHT)));

    //size = size / 4;

    // Create the context
    gatherer::graphics::GLContextWindow window(size, "display");
    gatherer::graphics::OEGLGPGPUTest test(&window, window.getResolution().x);

    while( /*capture */ true )
    {
        cv::Mat frame;
        capture >> frame;
        cv::resize(frame, frame, size);
        cv::cvtColor(frame, frame, cv::COLOR_BGR2BGRA);
        test.captureOutput(frame);
        window.swapBuffers();
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: javamaker.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 02:17:32 $
 *
 *  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
 *
 ************************************************************************/

#include <stdio.h>

#include "sal/main.h"

#ifndef _CODEMAKER_TYPEMANAGER_HXX_
#include <codemaker/typemanager.hxx>
#endif
#include "codemaker/generatedtypeset.hxx"

#include "javaoptions.hxx"
#include "javatype.hxx"

using namespace rtl;

sal_Bool produceAllTypes(RegistryKey& rTypeKey, sal_Bool bIsExtraType,
                         TypeManager const & typeMgr,
                         codemaker::GeneratedTypeSet & generated,
                         JavaOptions* pOptions,
                         sal_Bool bFullScope)
    throw( CannotDumpException )
{
    OString typeName = typeMgr.getTypeName(rTypeKey);

    if (!produceType(rTypeKey, bIsExtraType, typeMgr, generated, pOptions))
    {
        fprintf(stderr, "%s ERROR: %s\n",
                pOptions->getProgramName().getStr(),
                OString("cannot dump Type '" + typeName + "'").getStr());
        exit(99);
    }

    RegistryKeyList typeKeys = typeMgr.getTypeKeys(typeName);
    RegistryKeyList::const_iterator iter = typeKeys.begin();
    RegistryKey key, subKey;
    RegistryKeyArray subKeys;

    while (iter != typeKeys.end())
    {
        key = (*iter).first;

        if (!(*iter).second  && !key.openSubKeys(OUString(), subKeys))
        {
            for (sal_uInt32 i = 0; i < subKeys.getLength(); i++)
            {
                subKey = subKeys.getElement(i);
                if (bFullScope)
                {
                    if (!produceAllTypes(
                            subKey, (*iter).second,
                            typeMgr, generated, pOptions, sal_True))
                        return sal_False;
                } else
                {
                    if (!produceType(subKey, (*iter).second,
                                     typeMgr, generated, pOptions))
                        return sal_False;
                }
            }
        }

        ++iter;
    }

    return sal_True;
}

sal_Bool produceAllTypes(const OString& typeName,
                         TypeManager const & typeMgr,
                         codemaker::GeneratedTypeSet & generated,
                         JavaOptions* pOptions,
                         sal_Bool bFullScope)
    throw( CannotDumpException )
{
    if (!produceType(typeName, typeMgr, generated, pOptions))
    {
        fprintf(stderr, "%s ERROR: %s\n",
                pOptions->getProgramName().getStr(),
                OString("cannot dump Type '" + typeName + "'").getStr());
        exit(99);
    }

    RegistryKeyList typeKeys = typeMgr.getTypeKeys(typeName);
    RegistryKeyList::const_iterator iter = typeKeys.begin();
    RegistryKey key, subKey;
    RegistryKeyArray subKeys;

    while (iter != typeKeys.end())
    {
        key = (*iter).first;
        if (!(*iter).second  && !key.openSubKeys(OUString(), subKeys))
        {
            for (sal_uInt32 i = 0; i < subKeys.getLength(); i++)
            {
                subKey = subKeys.getElement(i);
                if (bFullScope)
                {
                    if (!produceAllTypes(
                            subKey, (*iter).second,
                            typeMgr, generated, pOptions, sal_True))
                        return sal_False;
                } else
                {
                    if (!produceType(subKey, (*iter).second,
                                     typeMgr, generated, pOptions))
                        return sal_False;
                }
            }
        }

        ++iter;
    }

    return sal_True;
}

SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
    JavaOptions options;

    try
    {
        if (!options.initOptions(argc, argv))
        {
            exit(1);
        }
    }
    catch( IllegalArgument& e)
    {
        fprintf(stderr, "Illegal option: %s\n", e.m_message.getStr());
        exit(99);
    }

    RegistryTypeManager typeMgr;

    if (!typeMgr.init(options.getInputFiles(), options.getExtraInputFiles()))
    {
        fprintf(stderr, "%s : init registries failed, check your registry files.\n", options.getProgramName().getStr());
        exit(99);
    }

    if (options.isValid("-B"))
    {
        typeMgr.setBase(options.getOption("-B"));
    }

    try
    {
        if (options.isValid("-T"))
        {
            OString tOption(options.getOption("-T"));
            sal_Int32 nIndex = 0;

            codemaker::GeneratedTypeSet generated;
            OString typeName, tmpName;
            sal_Bool ret = sal_False;
            do
            {
                typeName = tOption.getToken(0, ';', nIndex);

                sal_Int32 nPos = typeName.lastIndexOf( '.' );
                tmpName = typeName.copy( nPos != -1 ? nPos+1 : 0 );
                if (tmpName == "*")
                {
                    // produce this type and his scope.
                    if (typeName.equals("*"))
                    {
                        tmpName = "/";
                    } else
                    {
                        tmpName = typeName.copy(0, typeName.lastIndexOf('.')).replace('.', '/');
                        if (tmpName.getLength() == 0)
                            tmpName = "/";
                        else
                            tmpName.replace('.', '/');
                    }
                    // related to task #116780# the scope is recursively
                    // generated.  bFullScope = true
                    ret = produceAllTypes(
                        tmpName, typeMgr, generated, &options, sal_True);
                } else
                {
                    // produce only this type
                    ret = produceType(
                        typeName.replace('.', '/'), typeMgr, generated,
                        &options);
                }

                if (!ret)
                {
                    fprintf(stderr, "%s ERROR: %s\n",
                            options.getProgramName().getStr(),
                            OString("cannot dump Type '" + typeName + "'").getStr());
                    exit(99);
                }
            } while( nIndex != -1 );
        } else
        {
            // produce all types
            codemaker::GeneratedTypeSet generated;
            if (!produceAllTypes("/", typeMgr, generated, &options, sal_True))
            {
                fprintf(stderr, "%s ERROR: %s\n",
                        options.getProgramName().getStr(),
                        "an error occurs while dumping all types.");
                exit(99);
            }
        }
    }
    catch( CannotDumpException& e)
    {
        fprintf(stderr, "%s ERROR: %s\n",
                options.getProgramName().getStr(),
                e.m_message.getStr());
        exit(99);
    }

    return 0;
}

<commit_msg>INTEGRATION: CWS jsc3 (1.7.16); FILE MERGED 2006/01/20 13:02:25 jsc 1.7.16.1: #i56247# unify include guards<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: javamaker.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: vg $ $Date: 2006-03-15 09:16:04 $
 *
 *  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
 *
 ************************************************************************/

#include <stdio.h>

#include "sal/main.h"

#include "codemaker/typemanager.hxx"
#include "codemaker/generatedtypeset.hxx"
#include "javaoptions.hxx"
#include "javatype.hxx"

using namespace rtl;

sal_Bool produceAllTypes(RegistryKey& rTypeKey, sal_Bool bIsExtraType,
                         TypeManager const & typeMgr,
                         codemaker::GeneratedTypeSet & generated,
                         JavaOptions* pOptions,
                         sal_Bool bFullScope)
    throw( CannotDumpException )
{
    OString typeName = typeMgr.getTypeName(rTypeKey);

    if (!produceType(rTypeKey, bIsExtraType, typeMgr, generated, pOptions))
    {
        fprintf(stderr, "%s ERROR: %s\n",
                pOptions->getProgramName().getStr(),
                OString("cannot dump Type '" + typeName + "'").getStr());
        exit(99);
    }

    RegistryKeyList typeKeys = typeMgr.getTypeKeys(typeName);
    RegistryKeyList::const_iterator iter = typeKeys.begin();
    RegistryKey key, subKey;
    RegistryKeyArray subKeys;

    while (iter != typeKeys.end())
    {
        key = (*iter).first;

        if (!(*iter).second  && !key.openSubKeys(OUString(), subKeys))
        {
            for (sal_uInt32 i = 0; i < subKeys.getLength(); i++)
            {
                subKey = subKeys.getElement(i);
                if (bFullScope)
                {
                    if (!produceAllTypes(
                            subKey, (*iter).second,
                            typeMgr, generated, pOptions, sal_True))
                        return sal_False;
                } else
                {
                    if (!produceType(subKey, (*iter).second,
                                     typeMgr, generated, pOptions))
                        return sal_False;
                }
            }
        }

        ++iter;
    }

    return sal_True;
}

sal_Bool produceAllTypes(const OString& typeName,
                         TypeManager const & typeMgr,
                         codemaker::GeneratedTypeSet & generated,
                         JavaOptions* pOptions,
                         sal_Bool bFullScope)
    throw( CannotDumpException )
{
    if (!produceType(typeName, typeMgr, generated, pOptions))
    {
        fprintf(stderr, "%s ERROR: %s\n",
                pOptions->getProgramName().getStr(),
                OString("cannot dump Type '" + typeName + "'").getStr());
        exit(99);
    }

    RegistryKeyList typeKeys = typeMgr.getTypeKeys(typeName);
    RegistryKeyList::const_iterator iter = typeKeys.begin();
    RegistryKey key, subKey;
    RegistryKeyArray subKeys;

    while (iter != typeKeys.end())
    {
        key = (*iter).first;
        if (!(*iter).second  && !key.openSubKeys(OUString(), subKeys))
        {
            for (sal_uInt32 i = 0; i < subKeys.getLength(); i++)
            {
                subKey = subKeys.getElement(i);
                if (bFullScope)
                {
                    if (!produceAllTypes(
                            subKey, (*iter).second,
                            typeMgr, generated, pOptions, sal_True))
                        return sal_False;
                } else
                {
                    if (!produceType(subKey, (*iter).second,
                                     typeMgr, generated, pOptions))
                        return sal_False;
                }
            }
        }

        ++iter;
    }

    return sal_True;
}

SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
    JavaOptions options;

    try
    {
        if (!options.initOptions(argc, argv))
        {
            exit(1);
        }
    }
    catch( IllegalArgument& e)
    {
        fprintf(stderr, "Illegal option: %s\n", e.m_message.getStr());
        exit(99);
    }

    RegistryTypeManager typeMgr;

    if (!typeMgr.init(options.getInputFiles(), options.getExtraInputFiles()))
    {
        fprintf(stderr, "%s : init registries failed, check your registry files.\n", options.getProgramName().getStr());
        exit(99);
    }

    if (options.isValid("-B"))
    {
        typeMgr.setBase(options.getOption("-B"));
    }

    try
    {
        if (options.isValid("-T"))
        {
            OString tOption(options.getOption("-T"));
            sal_Int32 nIndex = 0;

            codemaker::GeneratedTypeSet generated;
            OString typeName, tmpName;
            sal_Bool ret = sal_False;
            do
            {
                typeName = tOption.getToken(0, ';', nIndex);

                sal_Int32 nPos = typeName.lastIndexOf( '.' );
                tmpName = typeName.copy( nPos != -1 ? nPos+1 : 0 );
                if (tmpName == "*")
                {
                    // produce this type and his scope.
                    if (typeName.equals("*"))
                    {
                        tmpName = "/";
                    } else
                    {
                        tmpName = typeName.copy(0, typeName.lastIndexOf('.')).replace('.', '/');
                        if (tmpName.getLength() == 0)
                            tmpName = "/";
                        else
                            tmpName.replace('.', '/');
                    }
                    // related to task #116780# the scope is recursively
                    // generated.  bFullScope = true
                    ret = produceAllTypes(
                        tmpName, typeMgr, generated, &options, sal_True);
                } else
                {
                    // produce only this type
                    ret = produceType(
                        typeName.replace('.', '/'), typeMgr, generated,
                        &options);
                }

                if (!ret)
                {
                    fprintf(stderr, "%s ERROR: %s\n",
                            options.getProgramName().getStr(),
                            OString("cannot dump Type '" + typeName + "'").getStr());
                    exit(99);
                }
            } while( nIndex != -1 );
        } else
        {
            // produce all types
            codemaker::GeneratedTypeSet generated;
            if (!produceAllTypes("/", typeMgr, generated, &options, sal_True))
            {
                fprintf(stderr, "%s ERROR: %s\n",
                        options.getProgramName().getStr(),
                        "an error occurs while dumping all types.");
                exit(99);
            }
        }
    }
    catch( CannotDumpException& e)
    {
        fprintf(stderr, "%s ERROR: %s\n",
                options.getProgramName().getStr(),
                e.m_message.getStr());
        exit(99);
    }

    return 0;
}

<|endoftext|>


<commit_before>/**
 * This file is part of TelepathyQt
 *
 * @copyright Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2012 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt/PendingCaptchas>

#include "TelepathyQt/debug-internal.h"

#include "TelepathyQt/_gen/pending-captchas.moc.hpp"

#include <TelepathyQt/Captcha>
#include <TelepathyQt/captcha-authentication-internal.h>

namespace Tp {

struct TP_QT_NO_EXPORT PendingCaptchas::Private
{
    Private(PendingCaptchas *parent);
    ~Private();

    CaptchaAuthentication::ChallengeType stringToChallengeType(const QString &string) const;
    void appendCaptchaResult(const QString &mimeType, const QString &label,
            const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id);

    // Public object
    PendingCaptchas *parent;

    CaptchaAuthentication::ChallengeTypes preferredTypes;
    QStringList preferredMimeTypes;

    bool multipleRequired;
    QList<Captcha> captchas;
    int captchasLeft;

    CaptchaAuthenticationPtr captchaAuthentication;
    ChannelPtr channel;
};

PendingCaptchas::Private::Private(PendingCaptchas *parent)
    : parent(parent)
{

}

PendingCaptchas::Private::~Private()
{
}

CaptchaAuthentication::ChallengeType PendingCaptchas::Private::stringToChallengeType(const QString &string) const
{
    if (string == QLatin1String("audio_recog")) {
        return CaptchaAuthentication::AudioRecognitionChallenge;
    } else if (string == QLatin1String("ocr")) {
        return CaptchaAuthentication::OCRChallenge;
    } else if (string == QLatin1String("picture_q")) {
        return CaptchaAuthentication::PictureQuestionChallenge;
    } else if (string == QLatin1String("picture_recog")) {
        return CaptchaAuthentication::PictureRecognitionChallenge;
    } else if (string == QLatin1String("qa")) {
        return CaptchaAuthentication::TextQuestionChallenge;
    } else if (string == QLatin1String("speech_q")) {
        return CaptchaAuthentication::SpeechQuestionChallenge;
    } else if (string == QLatin1String("speech_recog")) {
        return CaptchaAuthentication::SpeechRecognitionChallenge;
    } else if (string == QLatin1String("video_q")) {
        return CaptchaAuthentication::VideoQuestionChallenge;
    } else if (string == QLatin1String("video_recog")) {
        return CaptchaAuthentication::VideoRecognitionChallenge;
    }

    // Not really making sense...
    return CaptchaAuthentication::UnknownChallenge;
}

void PendingCaptchas::Private::appendCaptchaResult(const QString &mimeType, const QString &label,
        const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id)
{
    // Add to the list
    Captcha captchaItem(mimeType, label, data, type, id);

    captchas.append(captchaItem);

    --captchasLeft;

    if (!captchasLeft) {
        parent->setFinished();
    }
}

/**
 * \class PendingCaptchas
 * \ingroup client
 * \headerfile TelepathyQt/pending-captchas.h <TelepathyQt/PendingCaptchas>
 *
 * \brief The PendingCaptchas class represents an asynchronous
 * operation for retrieving a captcha challenge from a connection manager.
 *
 * See \ref async_model
 */

PendingCaptchas::PendingCaptchas(
        const QDBusPendingCall &call,
        const QStringList &preferredMimeTypes,
        CaptchaAuthentication::ChallengeTypes preferredTypes,
        const CaptchaAuthenticationPtr &captchaAuthentication)
    : PendingOperation(captchaAuthentication),
      mPriv(new Private(this))
{
    mPriv->captchaAuthentication = captchaAuthentication;
    mPriv->channel = captchaAuthentication->channel();
    mPriv->preferredMimeTypes = preferredMimeTypes;
    mPriv->preferredTypes = preferredTypes;

    /* keep track of channel invalidation */
    connect(mPriv->channel.data(),
            SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
            SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));

    connect(new QDBusPendingCallWatcher(call),
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            this,
            SLOT(onGetCaptchasWatcherFinished(QDBusPendingCallWatcher*)));
}

PendingCaptchas::PendingCaptchas(
        const QString& errorName,
        const QString& errorMessage,
        const CaptchaAuthenticationPtr &captchaAuthentication)
    : PendingOperation(captchaAuthentication),
      mPriv(new PendingCaptchas::Private(this))
{
    warning() << "PendingCaptchas created with instant failure";
    setFinishedWithError(errorName, errorMessage);
}

/**
 * Class destructor.
 */
PendingCaptchas::~PendingCaptchas()
{
    delete mPriv;
}

void PendingCaptchas::onChannelInvalidated(Tp::DBusProxy *proxy,
        const QString &errorName, const QString &errorMessage)
{
    Q_UNUSED(proxy);

    if (isFinished()) {
        return;
    }

    warning().nospace() << "PendingCaptchas failed because channel was invalidated with " <<
        errorName << ": " << errorMessage;

    setFinishedWithError(errorName, errorMessage);
}

void PendingCaptchas::onGetCaptchasWatcherFinished(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<Tp::CaptchaInfoList, uint, QString> reply = *watcher;

    if (reply.isError()) {
        debug().nospace() << "PendingDBusCall failed: " <<
            reply.error().name() << ": " << reply.error().message();
        setFinishedWithError(reply.error());
        watcher->deleteLater();
        return;
    }

    debug() << "Got reply to PendingDBusCall";
    Tp::CaptchaInfoList list = qdbus_cast<Tp::CaptchaInfoList>(reply.argumentAt(0));
    int howManyRequired = reply.argumentAt(1).toUInt();

    // Compute which captchas are required
    QList<QPair<Tp::CaptchaInfo,QString> > finalList;
    foreach (const Tp::CaptchaInfo &info, list) {
        // First of all, mimetype check
        QString mimeType;
        if (info.availableMIMETypes.isEmpty()) {
            // If it's one of the types which might not have a payload, go for it
            CaptchaAuthentication::ChallengeTypes noPayloadChallenges(
                    CaptchaAuthentication::TextQuestionChallenge |
                    CaptchaAuthentication::UnknownChallenge);
            if (mPriv->stringToChallengeType(info.type) & noPayloadChallenges) {
                // Ok, move on
            } else {
                // In this case, there's something wrong
                warning() << "Got a captcha with type " << info.type << " which does not "
                        "expose any available mimetype for its payload. Something might be "
                        "wrong with the connection manager.";
                continue;
            }
        } else if (mPriv->preferredMimeTypes.isEmpty()) {
            // No preference, let's take the first of the list
            mimeType = info.availableMIMETypes.first();
        } else {
            QSet<QString> supportedMimeTypes = info.availableMIMETypes.toSet().intersect(
                    mPriv->preferredMimeTypes.toSet());
            if (supportedMimeTypes.isEmpty()) {
                // Apparently our handler does not support any of this captcha's mimetypes, skip
                continue;
            }

            // Ok, use the first one
            mimeType = *supportedMimeTypes.constBegin();
        }

        // If it's required, easy
        if (info.flags & CaptchaFlagRequired) {
            finalList.append(qMakePair(info, mimeType));
            continue;
        }

        // Otherwise, let's see if the mimetype matches
        if (mPriv->preferredTypes & mPriv->stringToChallengeType(info.type)) {
            finalList.append(qMakePair(info, mimeType));
        }

        if (finalList.size() == howManyRequired) {
            break;
        }
    }

    if (finalList.size() != howManyRequired) {
        warning() << "No captchas available matching the specified preferences";
        setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE,
                QLatin1String("No captchas matching the handler's request"));
        return;
    }

    // Now, get the infos for all the required captchas in our final list.
    mPriv->captchasLeft = finalList.size();
    mPriv->multipleRequired = howManyRequired > 1 ? true : false;
    for (QList<QPair<Tp::CaptchaInfo,QString> >::const_iterator i = finalList.constBegin();
            i != finalList.constEnd(); ++i) {

        // If the captcha does not have a mimetype, we can add it straight
        if ((*i).second.isEmpty()) {
            mPriv->appendCaptchaResult((*i).second, (*i).first.label, QByteArray(),
                    mPriv->stringToChallengeType((*i).first.type), (*i).first.ID);

            continue;
        }

        QDBusPendingCall call =
        mPriv->channel->interface<Client::ChannelInterfaceCaptchaAuthenticationInterface>()->GetCaptchaData(
                    (*i).first.ID, (*i).second);

        QDBusPendingCallWatcher *dataWatcher = new QDBusPendingCallWatcher(call);
        dataWatcher->setProperty("__Tp_Qt_CaptchaID", (*i).first.ID);
        dataWatcher->setProperty("__Tp_Qt_CaptchaMimeType", (*i).second);
        dataWatcher->setProperty("__Tp_Qt_CaptchaLabel", (*i).first.label);
        dataWatcher->setProperty("__Tp_Qt_CaptchaType",
                mPriv->stringToChallengeType((*i).first.type));

        connect(dataWatcher,
                SIGNAL(finished(QDBusPendingCallWatcher*)),
                this,
                SLOT(onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher*)));
    }

    watcher->deleteLater();
}

void PendingCaptchas::onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QByteArray> reply = *watcher;

    if (reply.isError()) {
        debug().nospace() << "PendingDBusCall failed: " <<
            reply.error().name() << ": " << reply.error().message();
        setFinishedWithError(reply.error());
        watcher->deleteLater();
        return;
    }

    debug() << "Got reply to PendingDBusCall";

    // Add to the list
    mPriv->appendCaptchaResult(watcher->property("__Tp_Qt_CaptchaMimeType").toString(),
            watcher->property("__Tp_Qt_CaptchaLabel").toString(),
            reply.value(), static_cast<CaptchaAuthentication::ChallengeType>(
                watcher->property("__Tp_Qt_CaptchaType").toUInt()),
            watcher->property("__Tp_Qt_CaptchaID").toUInt());

    watcher->deleteLater();
}

/**
 * Return the main captcha of the request. This captcha is guaranteed to be compatible
 * with any constraint specified in CaptchaAuthentication::requestCaptchas().
 *
 * This is a convenience method which should be used when requiresMultipleCaptchas()
 * is false - otherwise, you should use captchaList.
 *
 * The returned Captcha can be answered through CaptchaAuthentication::answer() by
 * using its id.
 *
 * This method will return a meaningful value only if the operation was completed
 * successfully.
 *
 * \return The main captcha for the pending request.
 *
 * \sa captchaList()
 *     CaptchaAuthentication::requestCaptchas()
 *     requiresMultipleCaptchas()
 *     CaptchaAuthentication::answer()
 */
Captcha PendingCaptchas::captcha() const
{
    if (!isFinished()) {
        return Captcha();
    }

    return mPriv->captchas.first();
}

/**
 * Return all the captchas of the request. These captchas are guaranteed to be compatible
 * with any constraint specified in CaptchaAuthentication::requestCaptchas().
 *
 * If requiresMultipleCaptchas() is false, you probably want to use the convenience method
 * captcha() instead.
 *
 * The returned Captchas can be answered through CaptchaAuthentication::answer() by
 * using their ids.
 *
 * This method will return a meaningful value only if the operation was completed
 * successfully.
 *
 * \return All the captchas for the pending request.
 *
 * \sa captcha()
 *     CaptchaAuthentication::requestCaptchas()
 *     requiresMultipleCaptchas()
 *     CaptchaAuthentication::answer()
 */
QList<Captcha> PendingCaptchas::captchaList() const
{
    if (!isFinished()) {
        return QList<Captcha>();
    }

    return mPriv->captchas;
}

/**
 * Return whether this request requires more than one captcha to be answered or not.
 *
 * This method should always be checked before answering to find out what the
 * connection manager expects. Depending on the result, you might want to use the
 * result from captcha() if just a single answer is required, or from captchaList()
 * otherwise.
 *
 * This method will return a meaningful value only if the operation was completed
 * successfully.
 *
 * \return The main captcha for the pending request.
 *
 * \sa captcha()
 *     captchaList()
 */
bool PendingCaptchas::requiresMultipleCaptchas() const
{
    return mPriv->multipleRequired;
}

}
<commit_msg>captcha-authentication: For clarity, use temporary variables to identify members of a hash when iterating<commit_after>/**
 * This file is part of TelepathyQt
 *
 * @copyright Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2012 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt/PendingCaptchas>

#include "TelepathyQt/debug-internal.h"

#include "TelepathyQt/_gen/pending-captchas.moc.hpp"

#include <TelepathyQt/Captcha>
#include <TelepathyQt/captcha-authentication-internal.h>

namespace Tp {

struct TP_QT_NO_EXPORT PendingCaptchas::Private
{
    Private(PendingCaptchas *parent);
    ~Private();

    CaptchaAuthentication::ChallengeType stringToChallengeType(const QString &string) const;
    void appendCaptchaResult(const QString &mimeType, const QString &label,
            const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id);

    // Public object
    PendingCaptchas *parent;

    CaptchaAuthentication::ChallengeTypes preferredTypes;
    QStringList preferredMimeTypes;

    bool multipleRequired;
    QList<Captcha> captchas;
    int captchasLeft;

    CaptchaAuthenticationPtr captchaAuthentication;
    ChannelPtr channel;
};

PendingCaptchas::Private::Private(PendingCaptchas *parent)
    : parent(parent)
{

}

PendingCaptchas::Private::~Private()
{
}

CaptchaAuthentication::ChallengeType PendingCaptchas::Private::stringToChallengeType(const QString &string) const
{
    if (string == QLatin1String("audio_recog")) {
        return CaptchaAuthentication::AudioRecognitionChallenge;
    } else if (string == QLatin1String("ocr")) {
        return CaptchaAuthentication::OCRChallenge;
    } else if (string == QLatin1String("picture_q")) {
        return CaptchaAuthentication::PictureQuestionChallenge;
    } else if (string == QLatin1String("picture_recog")) {
        return CaptchaAuthentication::PictureRecognitionChallenge;
    } else if (string == QLatin1String("qa")) {
        return CaptchaAuthentication::TextQuestionChallenge;
    } else if (string == QLatin1String("speech_q")) {
        return CaptchaAuthentication::SpeechQuestionChallenge;
    } else if (string == QLatin1String("speech_recog")) {
        return CaptchaAuthentication::SpeechRecognitionChallenge;
    } else if (string == QLatin1String("video_q")) {
        return CaptchaAuthentication::VideoQuestionChallenge;
    } else if (string == QLatin1String("video_recog")) {
        return CaptchaAuthentication::VideoRecognitionChallenge;
    }

    // Not really making sense...
    return CaptchaAuthentication::UnknownChallenge;
}

void PendingCaptchas::Private::appendCaptchaResult(const QString &mimeType, const QString &label,
        const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id)
{
    // Add to the list
    Captcha captchaItem(mimeType, label, data, type, id);

    captchas.append(captchaItem);

    --captchasLeft;

    if (!captchasLeft) {
        parent->setFinished();
    }
}

/**
 * \class PendingCaptchas
 * \ingroup client
 * \headerfile TelepathyQt/pending-captchas.h <TelepathyQt/PendingCaptchas>
 *
 * \brief The PendingCaptchas class represents an asynchronous
 * operation for retrieving a captcha challenge from a connection manager.
 *
 * See \ref async_model
 */

PendingCaptchas::PendingCaptchas(
        const QDBusPendingCall &call,
        const QStringList &preferredMimeTypes,
        CaptchaAuthentication::ChallengeTypes preferredTypes,
        const CaptchaAuthenticationPtr &captchaAuthentication)
    : PendingOperation(captchaAuthentication),
      mPriv(new Private(this))
{
    mPriv->captchaAuthentication = captchaAuthentication;
    mPriv->channel = captchaAuthentication->channel();
    mPriv->preferredMimeTypes = preferredMimeTypes;
    mPriv->preferredTypes = preferredTypes;

    /* keep track of channel invalidation */
    connect(mPriv->channel.data(),
            SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
            SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));

    connect(new QDBusPendingCallWatcher(call),
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            this,
            SLOT(onGetCaptchasWatcherFinished(QDBusPendingCallWatcher*)));
}

PendingCaptchas::PendingCaptchas(
        const QString& errorName,
        const QString& errorMessage,
        const CaptchaAuthenticationPtr &captchaAuthentication)
    : PendingOperation(captchaAuthentication),
      mPriv(new PendingCaptchas::Private(this))
{
    warning() << "PendingCaptchas created with instant failure";
    setFinishedWithError(errorName, errorMessage);
}

/**
 * Class destructor.
 */
PendingCaptchas::~PendingCaptchas()
{
    delete mPriv;
}

void PendingCaptchas::onChannelInvalidated(Tp::DBusProxy *proxy,
        const QString &errorName, const QString &errorMessage)
{
    Q_UNUSED(proxy);

    if (isFinished()) {
        return;
    }

    warning().nospace() << "PendingCaptchas failed because channel was invalidated with " <<
        errorName << ": " << errorMessage;

    setFinishedWithError(errorName, errorMessage);
}

void PendingCaptchas::onGetCaptchasWatcherFinished(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<Tp::CaptchaInfoList, uint, QString> reply = *watcher;

    if (reply.isError()) {
        debug().nospace() << "PendingDBusCall failed: " <<
            reply.error().name() << ": " << reply.error().message();
        setFinishedWithError(reply.error());
        watcher->deleteLater();
        return;
    }

    debug() << "Got reply to PendingDBusCall";
    Tp::CaptchaInfoList list = qdbus_cast<Tp::CaptchaInfoList>(reply.argumentAt(0));
    int howManyRequired = reply.argumentAt(1).toUInt();

    // Compute which captchas are required
    QList<QPair<Tp::CaptchaInfo,QString> > finalList;
    foreach (const Tp::CaptchaInfo &info, list) {
        // First of all, mimetype check
        QString mimeType;
        if (info.availableMIMETypes.isEmpty()) {
            // If it's one of the types which might not have a payload, go for it
            CaptchaAuthentication::ChallengeTypes noPayloadChallenges(
                    CaptchaAuthentication::TextQuestionChallenge |
                    CaptchaAuthentication::UnknownChallenge);
            if (mPriv->stringToChallengeType(info.type) & noPayloadChallenges) {
                // Ok, move on
            } else {
                // In this case, there's something wrong
                warning() << "Got a captcha with type " << info.type << " which does not "
                        "expose any available mimetype for its payload. Something might be "
                        "wrong with the connection manager.";
                continue;
            }
        } else if (mPriv->preferredMimeTypes.isEmpty()) {
            // No preference, let's take the first of the list
            mimeType = info.availableMIMETypes.first();
        } else {
            QSet<QString> supportedMimeTypes = info.availableMIMETypes.toSet().intersect(
                    mPriv->preferredMimeTypes.toSet());
            if (supportedMimeTypes.isEmpty()) {
                // Apparently our handler does not support any of this captcha's mimetypes, skip
                continue;
            }

            // Ok, use the first one
            mimeType = *supportedMimeTypes.constBegin();
        }

        // If it's required, easy
        if (info.flags & CaptchaFlagRequired) {
            finalList.append(qMakePair(info, mimeType));
            continue;
        }

        // Otherwise, let's see if the mimetype matches
        if (mPriv->preferredTypes & mPriv->stringToChallengeType(info.type)) {
            finalList.append(qMakePair(info, mimeType));
        }

        if (finalList.size() == howManyRequired) {
            break;
        }
    }

    if (finalList.size() != howManyRequired) {
        warning() << "No captchas available matching the specified preferences";
        setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE,
                QLatin1String("No captchas matching the handler's request"));
        return;
    }

    // Now, get the infos for all the required captchas in our final list.
    mPriv->captchasLeft = finalList.size();
    mPriv->multipleRequired = howManyRequired > 1 ? true : false;
    for (QList<QPair<Tp::CaptchaInfo,QString> >::const_iterator i = finalList.constBegin();
            i != finalList.constEnd(); ++i) {
        QString mimeType = (*i).second;
        Tp::CaptchaInfo captchaInfo = (*i).first;

        // If the captcha does not have a mimetype, we can add it straight
        if (mimeType.isEmpty()) {
            mPriv->appendCaptchaResult(mimeType, captchaInfo.label, QByteArray(),
                    mPriv->stringToChallengeType(captchaInfo.type), captchaInfo.ID);

            continue;
        }

        QDBusPendingCall call =
        mPriv->channel->interface<Client::ChannelInterfaceCaptchaAuthenticationInterface>()->GetCaptchaData(
                    captchaInfo.ID, mimeType);

        QDBusPendingCallWatcher *dataWatcher = new QDBusPendingCallWatcher(call);
        dataWatcher->setProperty("__Tp_Qt_CaptchaID", captchaInfo.ID);
        dataWatcher->setProperty("__Tp_Qt_CaptchaMimeType", mimeType);
        dataWatcher->setProperty("__Tp_Qt_CaptchaLabel", captchaInfo.label);
        dataWatcher->setProperty("__Tp_Qt_CaptchaType",
                mPriv->stringToChallengeType(captchaInfo.type));

        connect(dataWatcher,
                SIGNAL(finished(QDBusPendingCallWatcher*)),
                this,
                SLOT(onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher*)));
    }

    watcher->deleteLater();
}

void PendingCaptchas::onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QByteArray> reply = *watcher;

    if (reply.isError()) {
        debug().nospace() << "PendingDBusCall failed: " <<
            reply.error().name() << ": " << reply.error().message();
        setFinishedWithError(reply.error());
        watcher->deleteLater();
        return;
    }

    debug() << "Got reply to PendingDBusCall";

    // Add to the list
    mPriv->appendCaptchaResult(watcher->property("__Tp_Qt_CaptchaMimeType").toString(),
            watcher->property("__Tp_Qt_CaptchaLabel").toString(),
            reply.value(), static_cast<CaptchaAuthentication::ChallengeType>(
                watcher->property("__Tp_Qt_CaptchaType").toUInt()),
            watcher->property("__Tp_Qt_CaptchaID").toUInt());

    watcher->deleteLater();
}

/**
 * Return the main captcha of the request. This captcha is guaranteed to be compatible
 * with any constraint specified in CaptchaAuthentication::requestCaptchas().
 *
 * This is a convenience method which should be used when requiresMultipleCaptchas()
 * is false - otherwise, you should use captchaList.
 *
 * The returned Captcha can be answered through CaptchaAuthentication::answer() by
 * using its id.
 *
 * This method will return a meaningful value only if the operation was completed
 * successfully.
 *
 * \return The main captcha for the pending request.
 *
 * \sa captchaList()
 *     CaptchaAuthentication::requestCaptchas()
 *     requiresMultipleCaptchas()
 *     CaptchaAuthentication::answer()
 */
Captcha PendingCaptchas::captcha() const
{
    if (!isFinished()) {
        return Captcha();
    }

    return mPriv->captchas.first();
}

/**
 * Return all the captchas of the request. These captchas are guaranteed to be compatible
 * with any constraint specified in CaptchaAuthentication::requestCaptchas().
 *
 * If requiresMultipleCaptchas() is false, you probably want to use the convenience method
 * captcha() instead.
 *
 * The returned Captchas can be answered through CaptchaAuthentication::answer() by
 * using their ids.
 *
 * This method will return a meaningful value only if the operation was completed
 * successfully.
 *
 * \return All the captchas for the pending request.
 *
 * \sa captcha()
 *     CaptchaAuthentication::requestCaptchas()
 *     requiresMultipleCaptchas()
 *     CaptchaAuthentication::answer()
 */
QList<Captcha> PendingCaptchas::captchaList() const
{
    if (!isFinished()) {
        return QList<Captcha>();
    }

    return mPriv->captchas;
}

/**
 * Return whether this request requires more than one captcha to be answered or not.
 *
 * This method should always be checked before answering to find out what the
 * connection manager expects. Depending on the result, you might want to use the
 * result from captcha() if just a single answer is required, or from captchaList()
 * otherwise.
 *
 * This method will return a meaningful value only if the operation was completed
 * successfully.
 *
 * \return The main captcha for the pending request.
 *
 * \sa captcha()
 *     captchaList()
 */
bool PendingCaptchas::requiresMultipleCaptchas() const
{
    return mPriv->multipleRequired;
}

}
<|endoftext|>


<commit_before>/*
 * Servo
 * read joystick data, normalize, write to servo
 *
 * @author: Navid Kalaei <navidkalaie@gmail.com>
 * @github: @navid-kalaei
 * @license: MIT
 */

#include "Arduino.h"
#include "Servo.h"

// time to wait in millis
#define DELAY_TIME 200

#define SERIAL_RATE 9600
#define JOY_PIN_X 0
#define JOY_PIN_Y 1

#define SERVO_PIN 9

// boundries of analogRead()
#define ANALOG_READ_LOW 0
#define ANALOG_READ_HIGH 1023

// boundries for normalizing analogRead() from -90 to +90
#define NORMALIZE_BOUND_LOW -90
#define NORMALIZE_BOUND_HIGH 90
// use this number to shift normalize value be between 0 to 180
#define NORMALIZE_ORIGIN 90

// the value that joystick has at first
// they're usefull in normalizing
short int joyXOrigin = 0;
short int joyYOrigin = 0;

short int joyXOriginNormalized = 0;
short int joyYOriginNormalized = 0;

short int joyValueX = 0;
short int joyValueY = 0;

short int joyValueXNormalized = 0;
short int joyValueYNormalized = 0;

Servo myServo;

int myServoPos = 0;

short int normalize(short int value){
  /*
   * a wrapper for map built-in function
   *
   * @param value: is within analogRead boundries
   * @return: normalize value within normalize boundries
   */

   // https://www.arduino.cc/en/Reference/Map
   // map(value, fromLow, fromHigh, toLow, toHigh)
   return map(value,
    ANALOG_READ_LOW, ANALOG_READ_HIGH,
    NORMALIZE_BOUND_LOW, NORMALIZE_BOUND_HIGH);
}

void checkBoundries(short int &value){
  /*
   * check if value is between normalized boudries or reset it to a boundry
   *
   * @param value: to check
   * @return: void
   */

   if(value > NORMALIZE_BOUND_HIGH){
     value = NORMALIZE_BOUND_HIGH;
   }
   else if(value < NORMALIZE_BOUND_LOW){
     value = NORMALIZE_BOUND_LOW;
   }
}

void setup(){
  myServo.attach(SERVO_PIN);

  // initialize joystick pins
  pinMode(JOY_PIN_X, INPUT);
  pinMode(JOY_PIN_Y, INPUT);

  joyXOrigin = analogRead(JOY_PIN_X);
  joyYOrigin = analogRead(JOY_PIN_Y);

  joyXOriginNormalized = normalize(joyXOrigin);

  joyYOriginNormalized = normalize(joyYOrigin);

  // wait until Serail is not available
  while(!Serial);
  Serial.begin(SERIAL_RATE);
}

void loop(){
  joyValueX = analogRead(JOY_PIN_X);
  joyValueXNormalized = normalize(joyValueX) - joyXOriginNormalized;
  checkBoundries(joyValueXNormalized);

  joyValueY =  analogRead(JOY_PIN_Y);
  joyValueYNormalized = normalize(joyValueY) - joyYOriginNormalized;
  checkBoundries(joyValueYNormalized);

  myServoPos = joyValueXNormalized + NORMALIZE_ORIGIN;
  myServo.write(myServoPos);
  //Serial.println(myServoPos);

  // delay(DELAY_TIME);

}
<commit_msg>decorate header comment servo/main.cpp<commit_after>/*************************************************
 * Servo                                         *
 * read joystick data, normalize, write to servo *
 *                                               *
 * @author: Navid Kalaei <navidkalaie@gmail.com> *
 * @github: @navid-kalaei                        *
 * @license: MIT                                 *
 *************************************************/

#include "Arduino.h"
#include "Servo.h"

// time to wait in millis
#define DELAY_TIME 200

#define SERIAL_RATE 9600
#define JOY_PIN_X 0
#define JOY_PIN_Y 1

#define SERVO_PIN 9

// boundries of analogRead()
#define ANALOG_READ_LOW 0
#define ANALOG_READ_HIGH 1023

// boundries for normalizing analogRead() from -90 to +90
#define NORMALIZE_BOUND_LOW -90
#define NORMALIZE_BOUND_HIGH 90
// use this number to shift normalize value be between 0 to 180
#define NORMALIZE_ORIGIN 90

// the value that joystick has at first
// they're usefull in normalizing
short int joyXOrigin = 0;
short int joyYOrigin = 0;

short int joyXOriginNormalized = 0;
short int joyYOriginNormalized = 0;

short int joyValueX = 0;
short int joyValueY = 0;

short int joyValueXNormalized = 0;
short int joyValueYNormalized = 0;

Servo myServo;

int myServoPos = 0;

short int normalize(short int value){
  /*
   * a wrapper for map built-in function
   *
   * @param value: is within analogRead boundries
   * @return: normalize value within normalize boundries
   */

   // https://www.arduino.cc/en/Reference/Map
   // map(value, fromLow, fromHigh, toLow, toHigh)
   return map(value,
    ANALOG_READ_LOW, ANALOG_READ_HIGH,
    NORMALIZE_BOUND_LOW, NORMALIZE_BOUND_HIGH);
}

void checkBoundries(short int &value){
  /*
   * check if value is between normalized boudries or reset it to a boundry
   *
   * @param value: to check
   * @return: void
   */

   if(value > NORMALIZE_BOUND_HIGH){
     value = NORMALIZE_BOUND_HIGH;
   }
   else if(value < NORMALIZE_BOUND_LOW){
     value = NORMALIZE_BOUND_LOW;
   }
}

void setup(){
  myServo.attach(SERVO_PIN);

  // initialize joystick pins
  pinMode(JOY_PIN_X, INPUT);
  pinMode(JOY_PIN_Y, INPUT);

  joyXOrigin = analogRead(JOY_PIN_X);
  joyYOrigin = analogRead(JOY_PIN_Y);

  joyXOriginNormalized = normalize(joyXOrigin);

  joyYOriginNormalized = normalize(joyYOrigin);

  // wait until Serail is not available
  while(!Serial);
  Serial.begin(SERIAL_RATE);
}

void loop(){
  joyValueX = analogRead(JOY_PIN_X);
  joyValueXNormalized = normalize(joyValueX) - joyXOriginNormalized;
  checkBoundries(joyValueXNormalized);

  joyValueY =  analogRead(JOY_PIN_Y);
  joyValueYNormalized = normalize(joyValueY) - joyYOriginNormalized;
  checkBoundries(joyValueYNormalized);

  myServoPos = joyValueXNormalized + NORMALIZE_ORIGIN;
  myServo.write(myServoPos);
  //Serial.println(myServoPos);

  // delay(DELAY_TIME);

}
<|endoftext|>