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

#include "chrome/renderer/pepper_widget.h"

#include "base/hash_tables.h"
#include "base/lazy_instance.h"
#include "chrome/renderer/pepper_scrollbar_widget.h"
#include "chrome/renderer/webplugin_delegate_pepper.h"
#include "webkit/glue/plugins/plugin_instance.h"
#include "webkit/glue/plugins/webplugin.h"
#include "webkit/glue/plugins/webplugin_delegate.h"

static int g_next_id;
typedef base::hash_map<int, PepperWidget*> WidgetMap;
static base::LazyInstance<WidgetMap> g_widgets(base::LINKER_INITIALIZED);

NPError NPCreateWidget(NPP instance,
                       NPWidgetType type,
                       void* params,
                       NPWidgetID* id) {
  PepperWidget* widget;
  switch(type) {
    case NPWidgetTypeScrollbar:
      widget = new PepperScrollbarWidget(
          *static_cast<NPScrollbarCreateParams*>(params));
      break;
    default:
      return NPERR_INVALID_PARAM;
  }

  *id = ++g_next_id;
  widget->Init(instance, *id);
  return NPERR_NO_ERROR;
}

NPError NPDestroyWidget(NPP instance, NPWidgetID id) {
  WidgetMap::iterator iter = g_widgets.Get().find(id);
  if (iter == g_widgets.Get().end())
    return NPERR_INVALID_PARAM;

  iter->second->Destroy();
  return NPERR_NO_ERROR;
}

NPError NPPaintWidget(NPP instance,
                      NPWidgetID id,
                      NPDeviceContext2D* context,
                      NPRect* dirty) {
  WidgetMap::iterator iter = g_widgets.Get().find(id);
  if (iter == g_widgets.Get().end())
    return NPERR_INVALID_PARAM;

  NPAPI::PluginInstance* plugin =
      static_cast<NPAPI::PluginInstance*>(instance->ndata);
  WebPluginDelegatePepper* delegate =
      static_cast<WebPluginDelegatePepper*>(plugin->webplugin()->delegate());
  Graphics2DDeviceContext* gdc = delegate->GetGraphicsContext(context);
  iter->second->Paint(gdc, *dirty);
  return NPERR_NO_ERROR;
}

bool NPHandleWidgetEvent(NPP instance, NPWidgetID id, NPPepperEvent* event) {
  WidgetMap::iterator iter = g_widgets.Get().find(id);
  if (iter == g_widgets.Get().end())
    return false;

  return iter->second->HandleEvent(*event);
}

NPError NPGetWidgetProperty(NPP instance,
                            NPWidgetID id,
                            NPWidgetProperty property,
                            void* value) {
  WidgetMap::iterator iter = g_widgets.Get().find(id);
  if (iter == g_widgets.Get().end())
    return NPERR_INVALID_PARAM;

  iter->second->GetProperty(property, value);
  return NPERR_NO_ERROR;
}

NPError NPSetWidgetProperty(NPP instance,
                            NPWidgetID id,
                            NPWidgetProperty property,
                            void* value) {
  WidgetMap::iterator iter = g_widgets.Get().find(id);
  if (iter == g_widgets.Get().end())
    return NPERR_INVALID_PARAM;

  iter->second->SetProperty(property, value);
  return NPERR_NO_ERROR;
}

NPWidgetExtensions g_widget_extensions = {
  NPCreateWidget,
  NPDestroyWidget,
  NPPaintWidget,
  NPHandleWidgetEvent,
  NPGetWidgetProperty,
  NPSetWidgetProperty
};

// static
NPWidgetExtensions* PepperWidget::GetWidgetExtensions() {
  return &g_widget_extensions;
}

PepperWidget::PepperWidget() : instance_(NULL), id_(0) {
}

PepperWidget::~PepperWidget() {
  if (id_)
    g_widgets.Get().erase(id_);
}

void PepperWidget::Init(NPP instance, int id) {
  instance_ = instance;
  id_ = id;
  g_widgets.Get()[id] = this;
}

void PepperWidget::WidgetPropertyChanged(NPWidgetProperty property) {
  NPAPI::PluginInstance* instance =
      static_cast<NPAPI::PluginInstance*>(instance_->ndata);
  NPPExtensions* extensions = NULL;
  instance->NPP_GetValue(NPPVPepperExtensions, &extensions);
  if (!extensions)
    return;

  extensions->widgetPropertyChanged(instance_, id_, property);
}
<commit_msg>Need to call makeOpaque on the platform device after drawing widgets on XP.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/pepper_widget.h"

#include "base/hash_tables.h"
#include "base/lazy_instance.h"
#include "chrome/renderer/pepper_scrollbar_widget.h"
#include "chrome/renderer/webplugin_delegate_pepper.h"
#include "webkit/glue/plugins/plugin_instance.h"
#include "webkit/glue/plugins/webplugin.h"
#include "webkit/glue/plugins/webplugin_delegate.h"

#if defined(OS_WIN)
#include "base/win_util.h"
#endif

static int g_next_id;
typedef base::hash_map<int, PepperWidget*> WidgetMap;
static base::LazyInstance<WidgetMap> g_widgets(base::LINKER_INITIALIZED);

NPError NPCreateWidget(NPP instance,
                       NPWidgetType type,
                       void* params,
                       NPWidgetID* id) {
  PepperWidget* widget;
  switch(type) {
    case NPWidgetTypeScrollbar:
      widget = new PepperScrollbarWidget(
          *static_cast<NPScrollbarCreateParams*>(params));
      break;
    default:
      return NPERR_INVALID_PARAM;
  }

  *id = ++g_next_id;
  widget->Init(instance, *id);
  return NPERR_NO_ERROR;
}

NPError NPDestroyWidget(NPP instance, NPWidgetID id) {
  WidgetMap::iterator iter = g_widgets.Get().find(id);
  if (iter == g_widgets.Get().end())
    return NPERR_INVALID_PARAM;

  iter->second->Destroy();
  return NPERR_NO_ERROR;
}

NPError NPPaintWidget(NPP instance,
                      NPWidgetID id,
                      NPDeviceContext2D* context,
                      NPRect* dirty) {
  WidgetMap::iterator iter = g_widgets.Get().find(id);
  if (iter == g_widgets.Get().end())
    return NPERR_INVALID_PARAM;

  NPAPI::PluginInstance* plugin =
      static_cast<NPAPI::PluginInstance*>(instance->ndata);
  WebPluginDelegatePepper* delegate =
      static_cast<WebPluginDelegatePepper*>(plugin->webplugin()->delegate());
  Graphics2DDeviceContext* gdc = delegate->GetGraphicsContext(context);
  iter->second->Paint(gdc, *dirty);

#if defined(OS_WIN)
  if (win_util::GetWinVersion() == win_util::WINVERSION_XP) {
    gdc->canvas()->getTopPlatformDevice().makeOpaque(
        dirty->left, dirty->top, dirty->right - dirty->left,
        dirty->bottom - dirty->top);
  }
#endif
  return NPERR_NO_ERROR;
}

bool NPHandleWidgetEvent(NPP instance, NPWidgetID id, NPPepperEvent* event) {
  WidgetMap::iterator iter = g_widgets.Get().find(id);
  if (iter == g_widgets.Get().end())
    return false;

  return iter->second->HandleEvent(*event);
}

NPError NPGetWidgetProperty(NPP instance,
                            NPWidgetID id,
                            NPWidgetProperty property,
                            void* value) {
  WidgetMap::iterator iter = g_widgets.Get().find(id);
  if (iter == g_widgets.Get().end())
    return NPERR_INVALID_PARAM;

  iter->second->GetProperty(property, value);
  return NPERR_NO_ERROR;
}

NPError NPSetWidgetProperty(NPP instance,
                            NPWidgetID id,
                            NPWidgetProperty property,
                            void* value) {
  WidgetMap::iterator iter = g_widgets.Get().find(id);
  if (iter == g_widgets.Get().end())
    return NPERR_INVALID_PARAM;

  iter->second->SetProperty(property, value);
  return NPERR_NO_ERROR;
}

NPWidgetExtensions g_widget_extensions = {
  NPCreateWidget,
  NPDestroyWidget,
  NPPaintWidget,
  NPHandleWidgetEvent,
  NPGetWidgetProperty,
  NPSetWidgetProperty
};

// static
NPWidgetExtensions* PepperWidget::GetWidgetExtensions() {
  return &g_widget_extensions;
}

PepperWidget::PepperWidget() : instance_(NULL), id_(0) {
}

PepperWidget::~PepperWidget() {
  if (id_)
    g_widgets.Get().erase(id_);
}

void PepperWidget::Init(NPP instance, int id) {
  instance_ = instance;
  id_ = id;
  g_widgets.Get()[id] = this;
}

void PepperWidget::WidgetPropertyChanged(NPWidgetProperty property) {
  NPAPI::PluginInstance* instance =
      static_cast<NPAPI::PluginInstance*>(instance_->ndata);
  NPPExtensions* extensions = NULL;
  instance->NPP_GetValue(NPPVPepperExtensions, &extensions);
  if (!extensions)
    return;

  extensions->widgetPropertyChanged(instance_, id_, property);
}
<|endoftext|>


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

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::lang;
using namespace comphelper;
using namespace connectivity;

ODatabaseMetaDataBase::ODatabaseMetaDataBase(const Reference< XConnection >& _rxConnection)
    : m_xConnection(_rxConnection)
{
    osl_incrementInterlockedCount( &m_refCount );
    {
        m_xListenerHelper = new OEventListenerHelper(this);
        Reference<XComponent> xCom(m_xConnection,UNO_QUERY);
        if(xCom.is())
            xCom->addEventListener(m_xListenerHelper);
    }
    osl_decrementInterlockedCount( &m_refCount );
}
// -------------------------------------------------------------------------
ODatabaseMetaDataBase::~ODatabaseMetaDataBase()
{
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseMetaDataBase::disposing( const EventObject& Source ) throw(RuntimeException)
{
    // cut off all references to the connection
    m_xConnection       = NULL;
    m_xListenerHelper   = NULL;
}

<commit_msg>INTEGRATION: CWS warnings01 (1.3.30); FILE MERGED 2005/11/16 12:58:44 fs 1.3.30.1: #i57457# warning free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TDatabaseMetaDataBase.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 01:03:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_ODATABASEMETADATABASE_HXX_
#include "TDatabaseMetaDataBase.hxx"
#endif
#ifndef COMPHELPER_EVENTLISTENERHELPER_HXX
#include <comphelper/evtlistenerhlp.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::lang;
using namespace comphelper;
using namespace connectivity;

ODatabaseMetaDataBase::ODatabaseMetaDataBase(const Reference< XConnection >& _rxConnection)
    : m_xConnection(_rxConnection)
{
    osl_incrementInterlockedCount( &m_refCount );
    {
        m_xListenerHelper = new OEventListenerHelper(this);
        Reference<XComponent> xCom(m_xConnection,UNO_QUERY);
        if(xCom.is())
            xCom->addEventListener(m_xListenerHelper);
    }
    osl_decrementInterlockedCount( &m_refCount );
}
// -------------------------------------------------------------------------
ODatabaseMetaDataBase::~ODatabaseMetaDataBase()
{
}
// -----------------------------------------------------------------------------
void SAL_CALL ODatabaseMetaDataBase::disposing( const EventObject& /*Source*/ ) throw(RuntimeException)
{
    // cut off all references to the connection
    m_xConnection       = NULL;
    m_xListenerHelper   = NULL;
}

<|endoftext|>


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

#include "content/common/sandbox_linux/bpf_renderer_policy_linux.h"

#include <errno.h>

#include "base/basictypes.h"
#include "build/build_config.h"
#include "content/common/sandbox_linux/sandbox_linux.h"
#include "sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h"
#include "sandbox/linux/seccomp-bpf-helpers/syscall_sets.h"
#include "sandbox/linux/seccomp-bpf/sandbox_bpf_policy.h"
#include "sandbox/linux/services/linux_syscalls.h"

using sandbox::SyscallSets;

namespace content {

namespace {

inline bool IsUsingToolKitGtk() {
#if defined(TOOLKIT_GTK)
  return true;
#else
  return false;
#endif
}

}  // namespace

RendererProcessPolicy::RendererProcessPolicy() {}
RendererProcessPolicy::~RendererProcessPolicy() {}

ErrorCode RendererProcessPolicy::EvaluateSyscall(SandboxBPF* sandbox,
                                                 int sysno) const {
  switch (sysno) {
    case __NR_clone:
      return sandbox::RestrictCloneToThreadsAndEPERMFork(sandbox);
    case __NR_ioctl:
      return sandbox::RestrictIoctl(sandbox);
    case __NR_prctl:
      return sandbox::RestrictPrctl(sandbox);
    // Allow the system calls below.
    case __NR_fdatasync:
    case __NR_fsync:
    case __NR_getpriority:
#if defined(__i386__) || defined(__x86_64__)
    case __NR_getrlimit:
#endif
#if defined(__i386__) || defined(__arm__)
    case __NR_ugetrlimit:
#endif
    case __NR_mremap:  // See crbug.com/149834.
    case __NR_pread64:
    case __NR_pwrite64:
    case __NR_sched_getaffinity:
    case __NR_sched_get_priority_max:
    case __NR_sched_get_priority_min:
    case __NR_sched_getparam:
    case __NR_sched_getscheduler:
    case __NR_sched_setscheduler:
    case __NR_setpriority:
    case __NR_sysinfo:
    case __NR_times:
    case __NR_uname:
      return ErrorCode(ErrorCode::ERR_ALLOWED);
    case __NR_prlimit64:
      return ErrorCode(EPERM);  // See crbug.com/160157.
    default:
      if (IsUsingToolKitGtk()) {
#if defined(__x86_64__) || defined(__arm__)
        if (SyscallSets::IsSystemVSharedMemory(sysno))
          return ErrorCode(ErrorCode::ERR_ALLOWED);
#endif
#if defined(__i386__)
        if (SyscallSets::IsSystemVIpc(sysno))
          return ErrorCode(ErrorCode::ERR_ALLOWED);
#endif
      }

      // Default on the content baseline policy.
      return SandboxBPFBasePolicy::EvaluateSyscall(sandbox, sysno);
  }
}

}  // namespace content
<commit_msg>Linux sandbox: allow clock_getres() in renderers.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/common/sandbox_linux/bpf_renderer_policy_linux.h"

#include <errno.h>

#include "base/basictypes.h"
#include "build/build_config.h"
#include "content/common/sandbox_linux/sandbox_linux.h"
#include "sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h"
#include "sandbox/linux/seccomp-bpf-helpers/syscall_sets.h"
#include "sandbox/linux/seccomp-bpf/sandbox_bpf_policy.h"
#include "sandbox/linux/services/linux_syscalls.h"

using sandbox::SyscallSets;

namespace content {

namespace {

inline bool IsUsingToolKitGtk() {
#if defined(TOOLKIT_GTK)
  return true;
#else
  return false;
#endif
}

}  // namespace

RendererProcessPolicy::RendererProcessPolicy() {}
RendererProcessPolicy::~RendererProcessPolicy() {}

ErrorCode RendererProcessPolicy::EvaluateSyscall(SandboxBPF* sandbox,
                                                 int sysno) const {
  switch (sysno) {
    case __NR_clone:
      return sandbox::RestrictCloneToThreadsAndEPERMFork(sandbox);
    case __NR_ioctl:
      return sandbox::RestrictIoctl(sandbox);
    case __NR_prctl:
      return sandbox::RestrictPrctl(sandbox);
    // Allow the system calls below.
    // The baseline policy allows __NR_clock_gettime. Allow
    // clock_getres() for V8. crbug.com/329053.
    case __NR_clock_getres:
    case __NR_fdatasync:
    case __NR_fsync:
    case __NR_getpriority:
#if defined(__i386__) || defined(__x86_64__)
    case __NR_getrlimit:
#endif
#if defined(__i386__) || defined(__arm__)
    case __NR_ugetrlimit:
#endif
    case __NR_mremap:  // See crbug.com/149834.
    case __NR_pread64:
    case __NR_pwrite64:
    case __NR_sched_getaffinity:
    case __NR_sched_get_priority_max:
    case __NR_sched_get_priority_min:
    case __NR_sched_getparam:
    case __NR_sched_getscheduler:
    case __NR_sched_setscheduler:
    case __NR_setpriority:
    case __NR_sysinfo:
    case __NR_times:
    case __NR_uname:
      return ErrorCode(ErrorCode::ERR_ALLOWED);
    case __NR_prlimit64:
      return ErrorCode(EPERM);  // See crbug.com/160157.
    default:
      if (IsUsingToolKitGtk()) {
#if defined(__x86_64__) || defined(__arm__)
        if (SyscallSets::IsSystemVSharedMemory(sysno))
          return ErrorCode(ErrorCode::ERR_ALLOWED);
#endif
#if defined(__i386__)
        if (SyscallSets::IsSystemVIpc(sysno))
          return ErrorCode(ErrorCode::ERR_ALLOWED);
#endif
      }

      // Default on the content baseline policy.
      return SandboxBPFBasePolicy::EvaluateSyscall(sandbox, sysno);
  }
}

}  // namespace content
<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include <memory>
#include <string>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/Settings.h"
#include "joynr/LibjoynrSettings.h"
#include "joynr/system/RoutingProxy.h"
#include "joynr/serializer/Serializer.h"

#include "tests/JoynrTest.h"
#include "tests/utils/MockObjects.h"

using namespace joynr;
using ::testing::Mock;

class SystemServicesRoutingTest : public ::testing::Test {
public:
    SystemServicesRoutingTest() :
            settingsFilename("test-resources/SystemServicesRoutingTest.settings"),
            settings(std::make_unique<Settings>(settingsFilename)),
            routingDomain(),
            routingProviderParticipantId(),
            runtime(nullptr),
            mockMessageReceiverHttp(std::make_shared<MockTransportMessageReceiver>()),
            mockMessageReceiverMqtt(std::make_shared<MockTransportMessageReceiver>()),
            mockMessageSender(std::make_shared<MockTransportMessageSender>()),
            discoveryQos(),
            routingProxyBuilder(nullptr),
            routingProxy(nullptr)
    {
        SystemServicesSettings systemSettings(*settings);
        systemSettings.printSettings();
        routingDomain = systemSettings.getDomain();
        routingProviderParticipantId = systemSettings.getCcRoutingProviderParticipantId();

        discoveryQos.setCacheMaxAgeMs(1000);
        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT);
        discoveryQos.addCustomParameter("fixedParticipantId", routingProviderParticipantId);
        discoveryQos.setDiscoveryTimeoutMs(50);

        std::string httpChannelId("http_SystemServicesRoutingTest.ChannelId");
        std::string httpEndPointUrl("http_SystemServicesRoutingTest.endPointUrl");
        std::string mqttTopic("mqtt_SystemServicesRoutingTest.topic");
        std::string mqttBrokerUrl("mqtt_SystemServicesRoutingTest.brokerUrl");

        using system::RoutingTypes::ChannelAddress;
        using system::RoutingTypes::MqttAddress;

        std::string serializedChannelAddress = joynr::serializer::serializeToJson(ChannelAddress(httpEndPointUrl, httpChannelId));
        std::string serializedMqttAddress = joynr::serializer::serializeToJson(MqttAddress(mqttBrokerUrl, mqttTopic));

        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverHttp).get()), getGlobalClusterControllerAddress())
                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedChannelAddress));
        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverMqtt).get()), getGlobalClusterControllerAddress())
                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedMqttAddress));

        //runtime can only be created, after MockMessageReceiver has been told to return
        //a channelId for getReceiveChannelId.
        runtime = std::make_unique<JoynrClusterControllerRuntime>(
                std::move(settings),
                nullptr,
                nullptr,
                mockMessageReceiverHttp,
                mockMessageSender,
                mockMessageReceiverMqtt,
                mockMessageSender);
        // routing provider is normally registered in JoynrClusterControllerRuntime::create
        runtime->init();
    }

    ~SystemServicesRoutingTest(){
        runtime->deleteChannel();
        runtime->stopExternalCommunication();
        runtime.reset();

        std::remove(settingsFilename.c_str());

        // Delete persisted files
        std::remove(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str());

        EXPECT_TRUE(Mock::VerifyAndClearExpectations(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverMqtt).get()));
        EXPECT_TRUE(Mock::VerifyAndClearExpectations(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverHttp).get()));
    }

    void SetUp(){
        participantId = util::createUuid();
        isGloballyVisible = true;
        routingProxyBuilder = runtime->createProxyBuilder<joynr::system::RoutingProxy>(routingDomain);
    }

protected:
    std::string settingsFilename;
    std::unique_ptr<Settings> settings;
    std::string routingDomain;
    std::string routingProviderParticipantId;
    std::shared_ptr<JoynrClusterControllerRuntime> runtime;
    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverHttp;
    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverMqtt;
    std::shared_ptr<MockTransportMessageSender> mockMessageSender;
    DiscoveryQos discoveryQos;
    std::shared_ptr<ProxyBuilder<joynr::system::RoutingProxy>> routingProxyBuilder;
    std::shared_ptr<joynr::system::RoutingProxy> routingProxy;
    std::string participantId;
    bool isGloballyVisible;

private:
    DISALLOW_COPY_AND_ASSIGN(SystemServicesRoutingTest);
};

TEST_F(SystemServicesRoutingTest, routingProviderIsAvailable)
{
    JOYNR_EXPECT_NO_THROW(
        routingProxy = routingProxyBuilder
                ->setMessagingQos(MessagingQos(5000))
                ->setDiscoveryQos(discoveryQos)
                ->build()
    );
}

TEST_F(SystemServicesRoutingTest, unknowParticipantIsNotResolvable)
{
    routingProxy = routingProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    bool isResolvable = false;
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);
}

TEST_F(SystemServicesRoutingTest, addNextHopHttp)
{
    routingProxy = routingProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    joynr::system::RoutingTypes::ChannelAddress address("SystemServicesRoutingTest.ChanneldId.A", "SystemServicesRoutingTest.endPointUrl");
    bool isResolvable = false;

    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);

    try {
        routingProxy->addNextHop(participantId, address, isGloballyVisible);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "addNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_TRUE(isResolvable);
}

TEST_F(SystemServicesRoutingTest, removeNextHopHttp)
{
    routingProxy = routingProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    joynr::system::RoutingTypes::ChannelAddress address("SystemServicesRoutingTest.ChanneldId.A", "SystemServicesRoutingTest.endPointUrl");
    bool isResolvable = false;

    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);

    try {
        routingProxy->addNextHop(participantId, address, isGloballyVisible);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "addNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_TRUE(isResolvable);

    try {
        routingProxy->removeNextHop(participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "removeNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);
}

TEST_F(SystemServicesRoutingTest, addNextHopMqtt)
{
    routingProxy = routingProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    joynr::system::RoutingTypes::MqttAddress address("brokerUri", "SystemServicesRoutingTest.ChanneldId.A");
    bool isResolvable = false;

    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);

    try {
        routingProxy->addNextHop(participantId, address, isGloballyVisible);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "addNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_TRUE(isResolvable);
}

TEST_F(SystemServicesRoutingTest, removeNextHopMqtt)
{
    routingProxy = routingProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    joynr::system::RoutingTypes::MqttAddress address("brokerUri", "SystemServicesRoutingTest.ChanneldId.A");
    bool isResolvable = false;

    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);

    try {
        routingProxy->addNextHop(participantId, address, isGloballyVisible);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "addNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_TRUE(isResolvable);

    try {
        routingProxy->removeNextHop(participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "removeNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);
}
<commit_msg>[C++] SystemServicesRoutingTest waits until runtime is destroyed<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include <memory>
#include <string>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/Settings.h"
#include "joynr/LibjoynrSettings.h"
#include "joynr/system/RoutingProxy.h"
#include "joynr/serializer/Serializer.h"

#include "tests/JoynrTest.h"
#include "tests/utils/MockObjects.h"
#include "tests/utils/PtrUtils.h"

using namespace joynr;
using ::testing::Mock;

class SystemServicesRoutingTest : public ::testing::Test {
public:
    SystemServicesRoutingTest() :
            settingsFilename("test-resources/SystemServicesRoutingTest.settings"),
            settings(std::make_unique<Settings>(settingsFilename)),
            routingDomain(),
            routingProviderParticipantId(),
            runtime(nullptr),
            mockMessageReceiverHttp(std::make_shared<MockTransportMessageReceiver>()),
            mockMessageReceiverMqtt(std::make_shared<MockTransportMessageReceiver>()),
            mockMessageSender(std::make_shared<MockTransportMessageSender>()),
            discoveryQos(),
            routingProxyBuilder(nullptr),
            routingProxy(nullptr)
    {
        SystemServicesSettings systemSettings(*settings);
        systemSettings.printSettings();
        routingDomain = systemSettings.getDomain();
        routingProviderParticipantId = systemSettings.getCcRoutingProviderParticipantId();

        discoveryQos.setCacheMaxAgeMs(1000);
        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT);
        discoveryQos.addCustomParameter("fixedParticipantId", routingProviderParticipantId);
        discoveryQos.setDiscoveryTimeoutMs(50);

        std::string httpChannelId("http_SystemServicesRoutingTest.ChannelId");
        std::string httpEndPointUrl("http_SystemServicesRoutingTest.endPointUrl");
        std::string mqttTopic("mqtt_SystemServicesRoutingTest.topic");
        std::string mqttBrokerUrl("mqtt_SystemServicesRoutingTest.brokerUrl");

        using system::RoutingTypes::ChannelAddress;
        using system::RoutingTypes::MqttAddress;

        std::string serializedChannelAddress = joynr::serializer::serializeToJson(ChannelAddress(httpEndPointUrl, httpChannelId));
        std::string serializedMqttAddress = joynr::serializer::serializeToJson(MqttAddress(mqttBrokerUrl, mqttTopic));

        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverHttp).get()), getGlobalClusterControllerAddress())
                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedChannelAddress));
        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverMqtt).get()), getGlobalClusterControllerAddress())
                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedMqttAddress));

        //runtime can only be created, after MockMessageReceiver has been told to return
        //a channelId for getReceiveChannelId.
        runtime = std::make_unique<JoynrClusterControllerRuntime>(
                std::move(settings),
                nullptr,
                nullptr,
                mockMessageReceiverHttp,
                mockMessageSender,
                mockMessageReceiverMqtt,
                mockMessageSender);
        // routing provider is normally registered in JoynrClusterControllerRuntime::create
        runtime->init();
    }

    ~SystemServicesRoutingTest(){
        runtime->deleteChannel();
        runtime->stopExternalCommunication();
        runtime.reset();

        EXPECT_TRUE(Mock::VerifyAndClearExpectations(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverMqtt).get()));
        EXPECT_TRUE(Mock::VerifyAndClearExpectations(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverHttp).get()));

        test::util::resetAndWaitUntilDestroyed(runtime);

        std::remove(settingsFilename.c_str());

        // Delete persisted files
        std::remove(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str());
    }

    void SetUp(){
        participantId = util::createUuid();
        isGloballyVisible = true;
        routingProxyBuilder = runtime->createProxyBuilder<joynr::system::RoutingProxy>(routingDomain);
    }

protected:
    std::string settingsFilename;
    std::unique_ptr<Settings> settings;
    std::string routingDomain;
    std::string routingProviderParticipantId;
    std::shared_ptr<JoynrClusterControllerRuntime> runtime;
    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverHttp;
    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverMqtt;
    std::shared_ptr<MockTransportMessageSender> mockMessageSender;
    DiscoveryQos discoveryQos;
    std::shared_ptr<ProxyBuilder<joynr::system::RoutingProxy>> routingProxyBuilder;
    std::shared_ptr<joynr::system::RoutingProxy> routingProxy;
    std::string participantId;
    bool isGloballyVisible;

private:
    DISALLOW_COPY_AND_ASSIGN(SystemServicesRoutingTest);
};

TEST_F(SystemServicesRoutingTest, routingProviderIsAvailable)
{
    JOYNR_EXPECT_NO_THROW(
        routingProxy = routingProxyBuilder
                ->setMessagingQos(MessagingQos(5000))
                ->setDiscoveryQos(discoveryQos)
                ->build()
    );
}

TEST_F(SystemServicesRoutingTest, unknowParticipantIsNotResolvable)
{
    routingProxy = routingProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    bool isResolvable = false;
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);
}

TEST_F(SystemServicesRoutingTest, addNextHopHttp)
{
    routingProxy = routingProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    joynr::system::RoutingTypes::ChannelAddress address("SystemServicesRoutingTest.ChanneldId.A", "SystemServicesRoutingTest.endPointUrl");
    bool isResolvable = false;

    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);

    try {
        routingProxy->addNextHop(participantId, address, isGloballyVisible);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "addNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_TRUE(isResolvable);
}

TEST_F(SystemServicesRoutingTest, removeNextHopHttp)
{
    routingProxy = routingProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    joynr::system::RoutingTypes::ChannelAddress address("SystemServicesRoutingTest.ChanneldId.A", "SystemServicesRoutingTest.endPointUrl");
    bool isResolvable = false;

    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);

    try {
        routingProxy->addNextHop(participantId, address, isGloballyVisible);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "addNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_TRUE(isResolvable);

    try {
        routingProxy->removeNextHop(participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "removeNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);
}

TEST_F(SystemServicesRoutingTest, addNextHopMqtt)
{
    routingProxy = routingProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    joynr::system::RoutingTypes::MqttAddress address("brokerUri", "SystemServicesRoutingTest.ChanneldId.A");
    bool isResolvable = false;

    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);

    try {
        routingProxy->addNextHop(participantId, address, isGloballyVisible);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "addNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_TRUE(isResolvable);
}

TEST_F(SystemServicesRoutingTest, removeNextHopMqtt)
{
    routingProxy = routingProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    joynr::system::RoutingTypes::MqttAddress address("brokerUri", "SystemServicesRoutingTest.ChanneldId.A");
    bool isResolvable = false;

    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);

    try {
        routingProxy->addNextHop(participantId, address, isGloballyVisible);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "addNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_TRUE(isResolvable);

    try {
        routingProxy->removeNextHop(participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "removeNextHop was not successful";
    }
    try {
        routingProxy->resolveNextHop(isResolvable, participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "resolveNextHop was not successful";
    }
    EXPECT_FALSE(isResolvable);
}
<|endoftext|>


<commit_before>#include <iostream>
#include "Sudoku.h"
#include "CrooksSudokuSolver.h"
#include "RecursiveSudokuSolver.h"
using namespace std;

CrooksSudokuSolver::CrooksSudokuSolver(Sudoku sudok)
{
    sudoku = sudok;
    exposedSinglesFound = 0;
    hiddenSinglesFound = 0;
    resortedToRecursion = false;
}

bool CrooksSudokuSolver::solve()
{
    bool madeProgress = true;

    while (madeProgress)
    {
        madeProgress = false;

        // Clever use of short-circuiting to repeat the more efficient
        // routune as much as possible.
        while (solveExposedSingles() || solveHiddenSingles())
        {
            madeProgress = true;
        }
    }

    // Solve the puzzle using the recursive method once progress has halted
    if (!sudoku.isSolved())
    {
        RecursiveSudokuSolver finishIt (sudoku);
        finishIt.solve();
        sudoku = finishIt.getSudoku();
        resortedToRecursion = true;
    }

    return sudoku.isSolved();
}

bool CrooksSudokuSolver::solveExposedSingles()
{
    bool madeProgress = false;
    int row, col, num;
    int singleNum;
    int numPossible;

    // Iterate through every cell
    for (row = 0; row < DIMENSION; row++)
    {
        for (col = 0; col < DIMENSION; col++)
        {
            // If a number is already present, move to the next cell
            if (sudoku.get(row, col) != 0)
                continue;

            singleNum = 0;
            numPossible = 0;
            for (num = 1; num <= DIMENSION; num++)
            {
                // Counting the number of possible moves in the cell
                if (sudoku.isValidMove(row, col, num))
                {
                    numPossible++;
                    singleNum = num;
                    if (numPossible > 1)
                    {
                        // A second possibility has been found, so quit
                        break;
                    }
                }
            }

            // If only one number is possible, assign that number
            if (numPossible == 1)
            {
                sudoku.set(row, col, singleNum);
                exposedSinglesFound++;
                madeProgress = true;
            }
        }
    }

    return madeProgress;
}

bool CrooksSudokuSolver::solveHiddenSingles()
{
    bool madeProgress = false;

    int i, j, num;
    int rowCount, colCount;
    int rowSingle, colSingle;

    // Iterate through rows and columns simultaneously
    for (i = 0; i < DIMENSION; i++)
    {
        rowCount = 0;
        colCount = 0;
        rowSingle = -1;
        colSingle = -1;

        // Iterate through every number
        for (num = 1; num <= DIMENSION; num++)
        {
            // Count locations where num is a possible move
            for (j = 0; j < DIMENSION; j++)
            {
                if (sudoku.isValidMove(i, j, num))
                {
                    rowSingle = j;
                    rowCount++;
                }

                if (sudoku.isValidMove(j, i, num))
                {
                    colSingle = j;
                    colCount++;
                }
            }

            // If num is only possible in 1 row/column, assign that number
            if (rowCount == 1)
            {
                sudoku.set(i, rowSingle, num);
                madeProgress = true;
            }

            if (colCount == 1)
            {
                sudoku.set(colSingle, i, num);
                madeProgress = true;
            }

            if (rowCount == 1 || colCount == 1)
            {
                hiddenSinglesFound++;
            }
        }
    }

    return madeProgress;
}

void CrooksSudokuSolver::print()
{
    /*
    cout << "Crook's Algorithm Sudoku Solver ";

    if (sudoku.isSolved())
    {
        cout << "(solved)" << endl;
        cout << "Exposed Singles Found: " << exposedSinglesFound << endl;
        cout << "Hidden  Singles Found: " << hiddenSinglesFound << endl;
        cout << "Resorted to Recursion: " <<
            (resortedToRecursion ? "True" : "False") << endl;
    }
    else
    {
        cout << "(unsolved)" << endl;
    }
    sudoku.print();
    /*/
    if (sudoku.isSolved())
    {
        cout << exposedSinglesFound << ", " << hiddenSinglesFound << ", "
            << resortedToRecursion << endl;
    }
    //*/
}
<commit_msg>Switched back to non-data collection<commit_after>#include <iostream>
#include "Sudoku.h"
#include "CrooksSudokuSolver.h"
#include "RecursiveSudokuSolver.h"
using namespace std;

CrooksSudokuSolver::CrooksSudokuSolver(Sudoku sudok)
{
    sudoku = sudok;
    exposedSinglesFound = 0;
    hiddenSinglesFound = 0;
    resortedToRecursion = false;
}

bool CrooksSudokuSolver::solve()
{
    bool madeProgress = true;

    while (madeProgress)
    {
        madeProgress = false;

        // Clever use of short-circuiting to repeat the more efficient
        // routune as much as possible.
        while (solveExposedSingles() || solveHiddenSingles())
        {
            madeProgress = true;
        }
    }

    // Solve the puzzle using the recursive method once progress has halted
    if (!sudoku.isSolved())
    {
        RecursiveSudokuSolver finishIt (sudoku);
        finishIt.solve();
        sudoku = finishIt.getSudoku();
        resortedToRecursion = true;
    }

    return sudoku.isSolved();
}

bool CrooksSudokuSolver::solveExposedSingles()
{
    bool madeProgress = false;
    int row, col, num;
    int singleNum;
    int numPossible;

    // Iterate through every cell
    for (row = 0; row < DIMENSION; row++)
    {
        for (col = 0; col < DIMENSION; col++)
        {
            // If a number is already present, move to the next cell
            if (sudoku.get(row, col) != 0)
                continue;

            singleNum = 0;
            numPossible = 0;
            for (num = 1; num <= DIMENSION; num++)
            {
                // Counting the number of possible moves in the cell
                if (sudoku.isValidMove(row, col, num))
                {
                    numPossible++;
                    singleNum = num;
                    if (numPossible > 1)
                    {
                        // A second possibility has been found, so quit
                        break;
                    }
                }
            }

            // If only one number is possible, assign that number
            if (numPossible == 1)
            {
                sudoku.set(row, col, singleNum);
                exposedSinglesFound++;
                madeProgress = true;
            }
        }
    }

    return madeProgress;
}

bool CrooksSudokuSolver::solveHiddenSingles()
{
    bool madeProgress = false;

    int i, j, num;
    int rowCount, colCount;
    int rowSingle, colSingle;

    // Iterate through rows and columns simultaneously
    for (i = 0; i < DIMENSION; i++)
    {
        rowCount = 0;
        colCount = 0;
        rowSingle = -1;
        colSingle = -1;

        // Iterate through every number
        for (num = 1; num <= DIMENSION; num++)
        {
            // Count locations where num is a possible move
            for (j = 0; j < DIMENSION; j++)
            {
                if (sudoku.isValidMove(i, j, num))
                {
                    rowSingle = j;
                    rowCount++;
                }

                if (sudoku.isValidMove(j, i, num))
                {
                    colSingle = j;
                    colCount++;
                }
            }

            // If num is only possible in 1 row/column, assign that number
            if (rowCount == 1)
            {
                sudoku.set(i, rowSingle, num);
                madeProgress = true;
            }

            if (colCount == 1)
            {
                sudoku.set(colSingle, i, num);
                madeProgress = true;
            }

            if (rowCount == 1 || colCount == 1)
            {
                hiddenSinglesFound++;
            }
        }
    }

    return madeProgress;
}

void CrooksSudokuSolver::print()
{
    //*
    cout << "Crook's Algorithm Sudoku Solver ";

    if (sudoku.isSolved())
    {
        cout << "(solved)" << endl;
        cout << "Exposed Singles Found: " << exposedSinglesFound << endl;
        cout << "Hidden  Singles Found: " << hiddenSinglesFound << endl;
        cout << "Resorted to Recursion: " <<
            (resortedToRecursion ? "True" : "False") << endl;
    }
    else
    {
        cout << "(unsolved)" << endl;
    }
    sudoku.print();
    /* This portion of code is for data collection to easily import into excel
    if (sudoku.isSolved())
    {
        cout << exposedSinglesFound << ", " << hiddenSinglesFound << ", "
            << resortedToRecursion << endl;
    }
    */
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Fuzz.h"
#include <stdlib.h>

// This really is just an example Fuzz*.cpp file.
// It tests that two different ways of calculating the Paeth predictor function are equivalent.

static uint8_t paeth_std(uint8_t a, uint8_t b, uint8_t c) {
    int p = a+b-c;

    int pa = abs(p-a),
        pb = abs(p-b),
        pc = abs(p-c);

    if (pb < pa) { pa = pb; a = b; }
    if (pc < pa) {          a = c; }
    return a;
}

static uint8_t paeth_alt(uint8_t a, uint8_t b, uint8_t c) {
    int min = SkTMin(a,b),
        max = SkTMax(a,b);
    int delta = (max-min)/3;

    if (c <= min+delta) return max;
    if (c >= max-delta) return min;
    return c;
}

DEF_FUZZ(Paeth, fuzz) {
    auto a = fuzz->nextB(),
         b = fuzz->nextB(),
         c = fuzz->nextB();
    SkDebugf("Paeth(%d,%d,%d)\n", a,b,c);

    if (a == b && b == c) {
        fuzz->signalBoring();  // Not really boring, just demoing signalBoring().
    }

    if (paeth_alt(a,b,c) != paeth_std(a,b,c)) {
        fuzz->signalBug();
    }
}
<commit_msg>Remove FuzzPaeth now that we have some real Fuzzes.<commit_after><|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
              Vladimír Vondruš <mosra@centrum.cz>
    Copyright © 2016 Jonathan Hale <squareys@googlemail.com>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include "GlfwApplication.h"

#include <tuple>

#include "Magnum/Version.h"
#include "Magnum/Platform/Context.h"
#include "Magnum/Platform/ScreenedApplication.hpp"

namespace Magnum { namespace Platform {

GlfwApplication* GlfwApplication::_instance = nullptr;

#ifdef GLFW_TRUE
/* The docs say that it's the same, verify that just in case */
static_assert(GLFW_TRUE == true && GLFW_FALSE == false, "GLFW does not have sane bool values");
#endif

#ifndef DOXYGEN_GENERATING_OUTPUT
GlfwApplication::GlfwApplication(const Arguments& arguments): GlfwApplication{arguments, Configuration{}} {}
#endif

GlfwApplication::GlfwApplication(const Arguments& arguments, const Configuration& configuration): GlfwApplication{arguments, nullptr} {
    createContext(configuration);
}

GlfwApplication::GlfwApplication(const Arguments& arguments, std::nullptr_t):
    _context{new Context{NoCreate, arguments.argc, arguments.argv}},
    _needsRedraw(true)
{
    /* Save global instance */
    _instance = this;

    /* Init GLFW */
    glfwSetErrorCallback(staticErrorCallback);

    if(!glfwInit()) {
        Error() << "Could not initialize GLFW";
        std::exit(8);
    }
}

void GlfwApplication::createContext() { createContext({}); }

void GlfwApplication::createContext(const Configuration& configuration) {
    if(!tryCreateContext(configuration)) std::exit(1);
}

bool GlfwApplication::tryCreateContext(const Configuration& configuration) {
    CORRADE_ASSERT(_context->version() == Version::None, "Platform::GlfwApplication::tryCreateContext(): context already created", false);

    /* Window flags */
    GLFWmonitor* monitor = nullptr; /* Needed for setting fullscreen */
    if (configuration.windowFlags() >= Configuration::WindowFlag::Fullscreen) {
        monitor = glfwGetPrimaryMonitor();
        glfwWindowHint(GLFW_AUTO_ICONIFY, configuration.windowFlags() >= Configuration::WindowFlag::AutoIconify);
    } else {
        const Configuration::WindowFlags& flags = configuration.windowFlags();
        glfwWindowHint(GLFW_RESIZABLE, flags >= Configuration::WindowFlag::Resizeable);
        glfwWindowHint(GLFW_VISIBLE, !(flags >= Configuration::WindowFlag::Hidden));
        #ifdef GLFW_MAXIMIZED
        glfwWindowHint(GLFW_MAXIMIZED, flags >= Configuration::WindowFlag::Maximized);
        #endif
        glfwWindowHint(GLFW_ICONIFIED, flags >= Configuration::WindowFlag::Minimized);
        glfwWindowHint(GLFW_FLOATING, flags >= Configuration::WindowFlag::Floating);
    }
    glfwWindowHint(GLFW_FOCUSED, configuration.windowFlags() >= Configuration::WindowFlag::Focused);

    /* Context window hints */
    glfwWindowHint(GLFW_SAMPLES, configuration.sampleCount());
    glfwWindowHint(GLFW_SRGB_CAPABLE, configuration.isSRGBCapable());

    const Configuration::Flags& flags = configuration.flags();
    #ifdef GLFW_CONTEXT_NO_ERROR
    glfwWindowHint(GLFW_CONTEXT_NO_ERROR, flags >= Configuration::Flag::NoError);
    #endif
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, flags >= Configuration::Flag::Debug);
    glfwWindowHint(GLFW_STEREO, flags >= Configuration::Flag::Stereo);

    /* Cursor flags */
    glfwWindowHint(GLFW_CURSOR, Int(configuration.cursorMode()));

    /* Set context version, if requested */
    if(configuration.version() != Version::None) {
        Int major, minor;
        std::tie(major, minor) = version(configuration.version());
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
        #ifndef MAGNUM_TARGET_GLES
        if(configuration.version() >= Version::GL310) {
            glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
            glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        }
        #else
        glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
        #endif
    }

    /* Set context flags */
    _window = glfwCreateWindow(configuration.size().x(), configuration.size().y(), configuration.title().c_str(), monitor, nullptr);
    if(!_window) {
        Error() << "Platform::GlfwApplication::tryCreateContext(): cannot create context";
        glfwTerminate();
        return false;
    }

    /* Set callbacks */
    glfwSetFramebufferSizeCallback(_window, staticViewportEvent);
    glfwSetKeyCallback(_window, staticKeyEvent);
    glfwSetCursorPosCallback(_window, staticMouseMoveEvent);
    glfwSetMouseButtonCallback(_window, staticMouseEvent);
    glfwSetScrollCallback(_window, staticMouseScrollEvent);

    glfwMakeContextCurrent(_window);

    /* Return true if the initialization succeeds */
    return _context->tryCreate();
}

GlfwApplication::~GlfwApplication() {
    glfwDestroyWindow(_window);
    glfwTerminate();
}

void GlfwApplication::setSwapInterval(const Int interval) {
    glfwSwapInterval(interval);
}

int GlfwApplication::exec() {
    while(!glfwWindowShouldClose(_window)) {
        if(_needsRedraw) {
            drawEvent();
        }
        glfwPollEvents();
    }
    return 0;
}

void GlfwApplication::staticKeyEvent(GLFWwindow*, int key, int, int action, int mods) {
    KeyEvent e(static_cast<KeyEvent::Key>(key), {static_cast<InputEvent::Modifier>(mods)});

    if(action == GLFW_PRESS) {
        _instance->keyPressEvent(e);
    } else if(action == GLFW_RELEASE) {
        _instance->keyReleaseEvent(e);
    } /* we don't handle GLFW_REPEAT */
}

void GlfwApplication::staticMouseMoveEvent(GLFWwindow* window, double x, double y) {
    MouseMoveEvent e{Vector2i{Int(x), Int(y)}, KeyEvent::getCurrentGlfwModifiers(window)};
    _instance->mouseMoveEvent(e);
}

void GlfwApplication::staticMouseEvent(GLFWwindow*, int button, int action, int mods) {
    MouseEvent e(static_cast<MouseEvent::Button>(button), {static_cast<InputEvent::Modifier>(mods)});

    if(action == GLFW_PRESS) {
        _instance->mousePressEvent(e);
    } else if(action == GLFW_RELEASE) {
        _instance->mouseReleaseEvent(e);
    } /* we don't handle GLFW_REPEAT */
}

void GlfwApplication::staticMouseScrollEvent(GLFWwindow* window, double xoffset, double yoffset) {
    MouseScrollEvent e(Vector2{Float(xoffset), Float(yoffset)}, KeyEvent::getCurrentGlfwModifiers(window));
    _instance->mouseScrollEvent(e);

    #ifdef MAGNUM_BUILD_DEPRECATED
    if(yoffset != 0.0) {
        #ifdef __GNUC__
        #pragma GCC diagnostic push
        #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
        #endif
        MouseEvent e1((yoffset > 0.0) ? MouseEvent::Button::WheelUp : MouseEvent::Button::WheelDown, KeyEvent::getCurrentGlfwModifiers(window));
        #ifdef __GNUC__
        #pragma GCC diagnostic pop
        #endif
        _instance->mousePressEvent(e1);
    }
    #endif
}

void GlfwApplication::staticErrorCallback(int, const char* description) {
    Error() << description;
}

auto GlfwApplication::KeyEvent::getCurrentGlfwModifiers(GLFWwindow* window) -> Modifiers {
    static_assert(GLFW_PRESS == true && GLFW_RELEASE == false,
        "GLFW press and release constants do not correspond to bool values");

    Modifiers mods;
    if(glfwGetKey(window, Int(Key::LeftShift)) || glfwGetKey(window, Int(Key::RightShift)))
        mods |= Modifier::Shift;
    if(glfwGetKey(window, Int(Key::LeftAlt)) || glfwGetKey(window, Int(Key::RightAlt)))
        mods |= Modifier::Alt;
    if(glfwGetKey(window, Int(Key::LeftCtrl)) || glfwGetKey(window, Int(Key::RightCtrl)))
        mods |= Modifier::Ctrl;
    if(glfwGetKey(window, Int(Key::RightSuper)))
        mods |= Modifier::Super;

    return mods;
}

void GlfwApplication::viewportEvent(const Vector2i&) {}
void GlfwApplication::keyPressEvent(KeyEvent&) {}
void GlfwApplication::keyReleaseEvent(KeyEvent&) {}
void GlfwApplication::mousePressEvent(MouseEvent&) {}
void GlfwApplication::mouseReleaseEvent(MouseEvent&) {}
void GlfwApplication::mouseMoveEvent(MouseMoveEvent&) {}
void GlfwApplication::mouseScrollEvent(MouseScrollEvent&) {}

GlfwApplication::Configuration::Configuration():
    _title{"Magnum GLFW Application"},
    _size{800, 600}, _sampleCount{0},
    _version{Version::None},
    _windowFlags{WindowFlag::Focused},
    _cursorMode{CursorMode::Normal} {}

GlfwApplication::Configuration::~Configuration() = default;

template class BasicScreen<GlfwApplication>;
template class BasicScreenedApplication<GlfwApplication>;

}}
<commit_msg>Platform: send GLFW_REPEAT events through `keyPressEvent()`<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
              Vladimír Vondruš <mosra@centrum.cz>
    Copyright © 2016 Jonathan Hale <squareys@googlemail.com>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include "GlfwApplication.h"

#include <tuple>

#include "Magnum/Version.h"
#include "Magnum/Platform/Context.h"
#include "Magnum/Platform/ScreenedApplication.hpp"

namespace Magnum { namespace Platform {

GlfwApplication* GlfwApplication::_instance = nullptr;

#ifdef GLFW_TRUE
/* The docs say that it's the same, verify that just in case */
static_assert(GLFW_TRUE == true && GLFW_FALSE == false, "GLFW does not have sane bool values");
#endif

#ifndef DOXYGEN_GENERATING_OUTPUT
GlfwApplication::GlfwApplication(const Arguments& arguments): GlfwApplication{arguments, Configuration{}} {}
#endif

GlfwApplication::GlfwApplication(const Arguments& arguments, const Configuration& configuration): GlfwApplication{arguments, nullptr} {
    createContext(configuration);
}

GlfwApplication::GlfwApplication(const Arguments& arguments, std::nullptr_t):
    _context{new Context{NoCreate, arguments.argc, arguments.argv}},
    _needsRedraw(true)
{
    /* Save global instance */
    _instance = this;

    /* Init GLFW */
    glfwSetErrorCallback(staticErrorCallback);

    if(!glfwInit()) {
        Error() << "Could not initialize GLFW";
        std::exit(8);
    }
}

void GlfwApplication::createContext() { createContext({}); }

void GlfwApplication::createContext(const Configuration& configuration) {
    if(!tryCreateContext(configuration)) std::exit(1);
}

bool GlfwApplication::tryCreateContext(const Configuration& configuration) {
    CORRADE_ASSERT(_context->version() == Version::None, "Platform::GlfwApplication::tryCreateContext(): context already created", false);

    /* Window flags */
    GLFWmonitor* monitor = nullptr; /* Needed for setting fullscreen */
    if (configuration.windowFlags() >= Configuration::WindowFlag::Fullscreen) {
        monitor = glfwGetPrimaryMonitor();
        glfwWindowHint(GLFW_AUTO_ICONIFY, configuration.windowFlags() >= Configuration::WindowFlag::AutoIconify);
    } else {
        const Configuration::WindowFlags& flags = configuration.windowFlags();
        glfwWindowHint(GLFW_RESIZABLE, flags >= Configuration::WindowFlag::Resizeable);
        glfwWindowHint(GLFW_VISIBLE, !(flags >= Configuration::WindowFlag::Hidden));
        #ifdef GLFW_MAXIMIZED
        glfwWindowHint(GLFW_MAXIMIZED, flags >= Configuration::WindowFlag::Maximized);
        #endif
        glfwWindowHint(GLFW_ICONIFIED, flags >= Configuration::WindowFlag::Minimized);
        glfwWindowHint(GLFW_FLOATING, flags >= Configuration::WindowFlag::Floating);
    }
    glfwWindowHint(GLFW_FOCUSED, configuration.windowFlags() >= Configuration::WindowFlag::Focused);

    /* Context window hints */
    glfwWindowHint(GLFW_SAMPLES, configuration.sampleCount());
    glfwWindowHint(GLFW_SRGB_CAPABLE, configuration.isSRGBCapable());

    const Configuration::Flags& flags = configuration.flags();
    #ifdef GLFW_CONTEXT_NO_ERROR
    glfwWindowHint(GLFW_CONTEXT_NO_ERROR, flags >= Configuration::Flag::NoError);
    #endif
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, flags >= Configuration::Flag::Debug);
    glfwWindowHint(GLFW_STEREO, flags >= Configuration::Flag::Stereo);

    /* Cursor flags */
    glfwWindowHint(GLFW_CURSOR, Int(configuration.cursorMode()));

    /* Set context version, if requested */
    if(configuration.version() != Version::None) {
        Int major, minor;
        std::tie(major, minor) = version(configuration.version());
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
        #ifndef MAGNUM_TARGET_GLES
        if(configuration.version() >= Version::GL310) {
            glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
            glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        }
        #else
        glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
        #endif
    }

    /* Set context flags */
    _window = glfwCreateWindow(configuration.size().x(), configuration.size().y(), configuration.title().c_str(), monitor, nullptr);
    if(!_window) {
        Error() << "Platform::GlfwApplication::tryCreateContext(): cannot create context";
        glfwTerminate();
        return false;
    }

    /* Set callbacks */
    glfwSetFramebufferSizeCallback(_window, staticViewportEvent);
    glfwSetKeyCallback(_window, staticKeyEvent);
    glfwSetCursorPosCallback(_window, staticMouseMoveEvent);
    glfwSetMouseButtonCallback(_window, staticMouseEvent);
    glfwSetScrollCallback(_window, staticMouseScrollEvent);

    glfwMakeContextCurrent(_window);

    /* Return true if the initialization succeeds */
    return _context->tryCreate();
}

GlfwApplication::~GlfwApplication() {
    glfwDestroyWindow(_window);
    glfwTerminate();
}

void GlfwApplication::setSwapInterval(const Int interval) {
    glfwSwapInterval(interval);
}

int GlfwApplication::exec() {
    while(!glfwWindowShouldClose(_window)) {
        if(_needsRedraw) {
            drawEvent();
        }
        glfwPollEvents();
    }
    return 0;
}

void GlfwApplication::staticKeyEvent(GLFWwindow*, int key, int, int action, int mods) {
    KeyEvent e(static_cast<KeyEvent::Key>(key), {static_cast<InputEvent::Modifier>(mods)});

    if(action == GLFW_PRESS) {
        _instance->keyPressEvent(e);
    } else if(action == GLFW_RELEASE) {
        _instance->keyReleaseEvent(e);
    } else if(action == GLFW_REPEAT) {
        _instance->keyPressEvent(e);
    }
}

void GlfwApplication::staticMouseMoveEvent(GLFWwindow* window, double x, double y) {
    MouseMoveEvent e{Vector2i{Int(x), Int(y)}, KeyEvent::getCurrentGlfwModifiers(window)};
    _instance->mouseMoveEvent(e);
}

void GlfwApplication::staticMouseEvent(GLFWwindow*, int button, int action, int mods) {
    MouseEvent e(static_cast<MouseEvent::Button>(button), {static_cast<InputEvent::Modifier>(mods)});

    if(action == GLFW_PRESS) {
        _instance->mousePressEvent(e);
    } else if(action == GLFW_RELEASE) {
        _instance->mouseReleaseEvent(e);
    } /* we don't handle GLFW_REPEAT */
}

void GlfwApplication::staticMouseScrollEvent(GLFWwindow* window, double xoffset, double yoffset) {
    MouseScrollEvent e(Vector2{Float(xoffset), Float(yoffset)}, KeyEvent::getCurrentGlfwModifiers(window));
    _instance->mouseScrollEvent(e);

    #ifdef MAGNUM_BUILD_DEPRECATED
    if(yoffset != 0.0) {
        #ifdef __GNUC__
        #pragma GCC diagnostic push
        #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
        #endif
        MouseEvent e1((yoffset > 0.0) ? MouseEvent::Button::WheelUp : MouseEvent::Button::WheelDown, KeyEvent::getCurrentGlfwModifiers(window));
        #ifdef __GNUC__
        #pragma GCC diagnostic pop
        #endif
        _instance->mousePressEvent(e1);
    }
    #endif
}

void GlfwApplication::staticErrorCallback(int, const char* description) {
    Error() << description;
}

auto GlfwApplication::KeyEvent::getCurrentGlfwModifiers(GLFWwindow* window) -> Modifiers {
    static_assert(GLFW_PRESS == true && GLFW_RELEASE == false,
        "GLFW press and release constants do not correspond to bool values");

    Modifiers mods;
    if(glfwGetKey(window, Int(Key::LeftShift)) || glfwGetKey(window, Int(Key::RightShift)))
        mods |= Modifier::Shift;
    if(glfwGetKey(window, Int(Key::LeftAlt)) || glfwGetKey(window, Int(Key::RightAlt)))
        mods |= Modifier::Alt;
    if(glfwGetKey(window, Int(Key::LeftCtrl)) || glfwGetKey(window, Int(Key::RightCtrl)))
        mods |= Modifier::Ctrl;
    if(glfwGetKey(window, Int(Key::RightSuper)))
        mods |= Modifier::Super;

    return mods;
}

void GlfwApplication::viewportEvent(const Vector2i&) {}
void GlfwApplication::keyPressEvent(KeyEvent&) {}
void GlfwApplication::keyReleaseEvent(KeyEvent&) {}
void GlfwApplication::mousePressEvent(MouseEvent&) {}
void GlfwApplication::mouseReleaseEvent(MouseEvent&) {}
void GlfwApplication::mouseMoveEvent(MouseMoveEvent&) {}
void GlfwApplication::mouseScrollEvent(MouseScrollEvent&) {}

GlfwApplication::Configuration::Configuration():
    _title{"Magnum GLFW Application"},
    _size{800, 600}, _sampleCount{0},
    _version{Version::None},
    _windowFlags{WindowFlag::Focused},
    _cursorMode{CursorMode::Normal} {}

GlfwApplication::Configuration::~Configuration() = default;

template class BasicScreen<GlfwApplication>;
template class BasicScreenedApplication<GlfwApplication>;

}}
<|endoftext|>


<commit_before>/**
 * stats_client.cc
 *
 * stand-alone client to poll a stats server
 *
 */

#include <iostream>
#include <string>
#include <system_error>
#include <thread>

#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>

#include "counter.h"
#include "stats_common.h"
#include "util.h"

using namespace std;
using namespace util;

int
main(int argc, char **argv)
{
  if (argc != 3) {
    cerr << "[usage] " << argv[0] << " sockfile counterspec" << endl;
    return 1;
  }

  const string sockfile(argv[1]);
  const vector<string> counter_names = split(argv[2], ':');

  int fd = socket(AF_UNIX, SOCK_STREAM, 0);
  if (fd < 0)
    throw system_error(errno, system_category(),
        "creating UNIX domain socket");
  struct sockaddr_un addr;
  memset(&addr, 0, sizeof addr);
  addr.sun_family = AF_UNIX;
  if (sockfile.length() + 1 >= sizeof addr.sun_path)
    throw range_error("UNIX domain socket path too long");
  strcpy(addr.sun_path, sockfile.c_str());
  size_t len = strlen(addr.sun_path) + sizeof(addr.sun_family);
  if (connect(fd, (struct sockaddr *) &addr, len) < 0)
    throw system_error(errno, system_category(),
        "connecting to socket");

  packet pkt;
  int r;
  timer loop_timer;
  for (;;) {
    for (auto &name : counter_names) {
      uint8_t buf[1 + name.size()];
      buf[0] = (uint8_t) stats_command::GET_COUNTER_VALUE;
      memcpy(&buf[1], name.data(), name.size());
      pkt.assign((const char *) &buf[0], sizeof(buf));
      if ((r = pkt.sendpkt(fd))) {
        perror("send - disconnecting");
        return 1;
      }
      if ((r = pkt.recvpkt(fd))) {
        if (r == EOF)
          return 0;
        perror("recv - disconnecting");
        return 1;
      }
      const get_counter_value_t *resp = (const get_counter_value_t *) pkt.data();
      cout << name                << " "
           << resp->timestamp_us_ << " "
           << resp->d_.count_     << " "
           << resp->d_.sum_       << " "
           << resp->d_.max_       << endl;
    }

    const uint64_t last_loop_usec  = loop_timer.lap();
    //const uint64_t delay_time_usec = 1000000;
    const uint64_t delay_time_usec = 1000000/4;
    if (last_loop_usec < delay_time_usec) {
      const uint64_t sleep_ns = (delay_time_usec - last_loop_usec) * 1000;
      struct timespec t;
      t.tv_sec  = sleep_ns / ONE_SECOND_NS;
      t.tv_nsec = sleep_ns % ONE_SECOND_NS;
      nanosleep(&t, nullptr);
    }
  }

  return 0;
}
<commit_msg>increase sampling rate<commit_after>/**
 * stats_client.cc
 *
 * stand-alone client to poll a stats server
 *
 */

#include <iostream>
#include <string>
#include <system_error>
#include <thread>

#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>

#include "counter.h"
#include "stats_common.h"
#include "util.h"

using namespace std;
using namespace util;

int
main(int argc, char **argv)
{
  if (argc != 3) {
    cerr << "[usage] " << argv[0] << " sockfile counterspec" << endl;
    return 1;
  }

  const string sockfile(argv[1]);
  const vector<string> counter_names = split(argv[2], ':');

  int fd = socket(AF_UNIX, SOCK_STREAM, 0);
  if (fd < 0)
    throw system_error(errno, system_category(),
        "creating UNIX domain socket");
  struct sockaddr_un addr;
  memset(&addr, 0, sizeof addr);
  addr.sun_family = AF_UNIX;
  if (sockfile.length() + 1 >= sizeof addr.sun_path)
    throw range_error("UNIX domain socket path too long");
  strcpy(addr.sun_path, sockfile.c_str());
  size_t len = strlen(addr.sun_path) + sizeof(addr.sun_family);
  if (connect(fd, (struct sockaddr *) &addr, len) < 0)
    throw system_error(errno, system_category(),
        "connecting to socket");

  packet pkt;
  int r;
  timer loop_timer;
  for (;;) {
    for (auto &name : counter_names) {
      uint8_t buf[1 + name.size()];
      buf[0] = (uint8_t) stats_command::GET_COUNTER_VALUE;
      memcpy(&buf[1], name.data(), name.size());
      pkt.assign((const char *) &buf[0], sizeof(buf));
      if ((r = pkt.sendpkt(fd))) {
        perror("send - disconnecting");
        return 1;
      }
      if ((r = pkt.recvpkt(fd))) {
        if (r == EOF)
          return 0;
        perror("recv - disconnecting");
        return 1;
      }
      const get_counter_value_t *resp = (const get_counter_value_t *) pkt.data();
      cout << name                << " "
           << resp->timestamp_us_ << " "
           << resp->d_.count_     << " "
           << resp->d_.sum_       << " "
           << resp->d_.max_       << endl;
    }

    const uint64_t last_loop_usec  = loop_timer.lap();
    //const uint64_t delay_time_usec = 1000000;
    const uint64_t delay_time_usec = 1000000/1000;
    if (last_loop_usec < delay_time_usec) {
      const uint64_t sleep_ns = (delay_time_usec - last_loop_usec) * 1000;
      struct timespec t;
      t.tv_sec  = sleep_ns / ONE_SECOND_NS;
      t.tv_nsec = sleep_ns % ONE_SECOND_NS;
      nanosleep(&t, nullptr);
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <chrono>
#include <getopt.h>
#include <memory>
#include "snv.hpp"
#include "del.hpp"
#include "read_parsers.hh"

using namespace oxli;
using namespace read_parsers;
typedef Read Sequence;
typedef std::chrono::time_point<std::chrono::system_clock> timepoint;

typedef struct
{
    uint delsize;
    ulong interval;
    uint ksize;
    ulong limit;
    uint histmax;
    double sampling_rate;
    int seed;
    std::string muttype;
    std::string seqfile;
    std::string refrcounts;
} ProgramArgs;

void print_usage(std::ostream& stream = std::cerr)
{
    stream << "Usage: snv-hist [options] genome.fa kmercounts.counttable\n";
    stream << "  options:\n";
    stream << "    -h    print this help message and exit\n";
    stream << "    -i    debug output interval (default: 1000000)\n";
    stream << "    -k    k-mer length (default: 31)\n";
    stream << "    -l    limit number of positions to process\n";
    stream << "    -m    max histogram value (default: 16)\n";
    stream << "    -r    sampling rate (default: 1.0)\n";
    stream << "    -s    seed for random number generator (default: 42)\n";
    stream << "    -t    mutation type: snv (default), del\n";
    stream << "    -z    deletion size (default: 5)\n";
}

void parse_args(int argc, const char **argv, ProgramArgs *args)
{
    char c;
    while ((c = getopt (argc, (char *const *)argv, "d:hi:k:l:m:r:s:t:y:z:")) != -1) {
        if (c == 'd') {
            args->delsize = atoi(optarg);
        }
        else if (c == 'h') {
            print_usage(std::cout);
            exit(0);
        }
        else if (c == 'i') {
            args->interval = atoi(optarg);
        }
        else if (c == 'k') {
            args->ksize = atoi(optarg);
        }
        else if (c == 'l') {
            args->limit = atoi(optarg);
        }
        else if (c == 'm') {
            args->histmax = atoi(optarg);
        }
        else if (c == 'r') {
            args->sampling_rate = atof(optarg);
        }
        else if (c == 's') {
            args->seed = atoi(optarg);
        }
        else if (c == 't') {
            args->muttype = optarg;
        }
        else if (c == 'z') {
            args->delsize = atoi(optarg);
        }
        else {
            std::cerr << "Unknown option '" << c << "'\n";
            print_usage();
            exit(1);
        }
    }

    args->seqfile = argv[optind];
    args->refrcounts = argv[optind + 1];
}

int main(int argc, const char **argv)
{
    if (argc == 1) {
        print_usage(std::cout);
        return 0;
    }

    ProgramArgs args = {5, 1000000, 31, 0, 16, 1.0, 42, "snv", "", ""};
    parse_args(argc, argv, &args);

    timepoint alloc_start = std::chrono::system_clock::now();
    std::cerr << "# loading reference genome k-mers counts from " << args.refrcounts << "...";
    std::vector<uint64_t> tablesizes = {1};
    Counttable counttable(1, tablesizes);
    counttable.load(args.refrcounts);
    timepoint alloc_end = std::chrono::system_clock::now();
    std::chrono::duration<double> alloc_elapsed = alloc_end - alloc_start;
    std::cerr << "done! (in " << alloc_elapsed.count() << " seconds)\n";

    timepoint query_start = std::chrono::system_clock::now();
    std::cerr << "# iterating through " << args.seqfile << ", querying k-mer abundances...";
    Logger logger(args.interval, std::cerr);
    std::unique_ptr<Mutator> mut = NULL;
    if(args.muttype == "snv") {
        mut.reset(new MutatorSNV(args.ksize, logger, args.histmax, args.limit));
    }
    else if(args.muttype == "del") {
        mut.reset(new MutatorDel(args.ksize, args.delsize, logger, args.histmax, args.limit));
    }
    else {
        std::cerr << "Error: unknown mutation type '" << args.muttype << "'\n";
        exit(1);
    }
    mut->set_sampling_rate(args.sampling_rate, args.seed);

    FastxParserPtr parser = get_parser<FastxReader>(args.seqfile);
    Sequence seq;
    while (!parser->is_complete()) {
        try {
            seq = parser->get_next_read();
        } catch (NoMoreReadsAvailable &e) {
            break;
        }
        mut->process(seq.sequence, counttable);
    }
    timepoint query_end = std::chrono::system_clock::now();
    std::chrono::duration<double> query_elapsed = query_end - query_start;

    std::cerr << "done! processed " << mut->get_mut_count()
              << " mutations (in " << query_elapsed.count() << " seconds)\n\n";
    std::cout << *mut;

    return 0;
}
<commit_msg>Enable both counttables and seqfiles for k-mer input<commit_after>#include <chrono>
#include <getopt.h>
#include <memory>
#include "snv.hpp"
#include "del.hpp"
#include "read_parsers.hh"

using namespace oxli;
using namespace read_parsers;
typedef Read Sequence;
typedef std::chrono::time_point<std::chrono::system_clock> timepoint;

typedef struct
{
    uint delsize;
    ulong interval;
    uint ksize;
    ulong limit;
    uint histmax;
    double sampling_rate;
    int seed;
    std::string muttype;
    ulong memory;
    std::string seqfile;
    std::string refrfile;
    std::string refrcounts;
} ProgramArgs;

void print_usage(std::ostream& stream = std::cerr)
{
    stream << "Usage: mut-hist [options] genome.fa\n";
    stream << "  options:\n";
    stream << "    -c    load genome k-mer counts from the specified counttable\n";
    stream << "    -g    load genome k-mer counts from the specified seqfile\n";
    stream << "    -h    print this help message and exit\n";
    stream << "    -i    debug output interval (default: 1000000)\n";
    stream << "    -k    k-mer length (default: 31)\n";
    stream << "    -l    limit number of positions to process\n";
    stream << "    -m    max histogram value (default: 16)\n";
    stream << "    -r    sampling rate (default: 1.0)\n";
    stream << "    -s    seed for random number generator (default: 42)\n";
    stream << "    -t    mutation type: snv (default), del\n";
    stream << "    -y    memory consumption (in bytes; default: 2000000000)\n";
    stream << "    -z    deletion size (default: 5)\n";
}

void parse_args(int argc, const char **argv, ProgramArgs *args)
{
    char c;
    while ((c = getopt (argc, (char *const *)argv, "c:g:hi:k:l:m:r:s:t:y:z:")) != -1) {
        if (c == 'c') {
            args->refrcounts = optarg;
        }
        else if (c == 'g') {
            args->refrfile = optarg;
        }
        else if (c == 'h') {
            print_usage(std::cout);
            exit(0);
        }
        else if (c == 'i') {
            args->interval = atoi(optarg);
        }
        else if (c == 'k') {
            args->ksize = atoi(optarg);
        }
        else if (c == 'l') {
            args->limit = atoi(optarg);
        }
        else if (c == 'm') {
            args->histmax = atoi(optarg);
        }
        else if (c == 'r') {
            args->sampling_rate = atof(optarg);
        }
        else if (c == 's') {
            args->seed = atoi(optarg);
        }
        else if (c == 't') {
            args->muttype = optarg;
        }
        else if (c == 'y') {
            args->memory = strtoul(optarg, NULL, 10);
        }
        else if (c == 'z') {
            args->delsize = atoi(optarg);
        }
        else {
            std::cerr << "Unknown option '" << c << "'\n";
            print_usage();
            exit(1);
        }
    }

    args->seqfile = argv[optind];
    if (args->refrfile.compare("") == 0) {
        args->refrfile = args->seqfile;
    }
}

Counttable load_from_seqfile(std::string &seqfile, uint ksize, ulong memory)
{
    timepoint alloc_start = std::chrono::system_clock::now();
    std::cerr << "# allocating counttable...";
    std::vector<uint64_t> tablesizes = get_n_primes_near_x(4, memory / 4);
    Counttable counttable(ksize, tablesizes);
    timepoint alloc_end = std::chrono::system_clock::now();
    std::chrono::duration<double> alloc_elapsed = alloc_end - alloc_start;
    std::cerr << "done! (in " << alloc_elapsed.count() << " seconds)\n";

    std::cerr << "# consuming k-mers from seqfile " << seqfile << "...";
    timepoint consume_start = std::chrono::system_clock::now();
    unsigned int seqs_consumed = 0;
    unsigned long long kmers_consumed = 0;
    counttable.consume_seqfile<FastxReader>(seqfile, seqs_consumed, kmers_consumed);
    timepoint consume_end = std::chrono::system_clock::now();
    std::chrono::duration<double> consume_elapsed = consume_end - consume_start;
    std::cerr << "done! consumed " << seqs_consumed << " sequence(s) and "
              << kmers_consumed << " " << ksize << "-mers (in "
              << consume_elapsed.count() << " seconds)\n";

    return counttable;
}

Counttable load_from_counttable(std::string &counttablefile)
{
    timepoint alloc_start = std::chrono::system_clock::now();
    std::cerr << "# loading reference genome k-mers counts from " << counttablefile << "...";
    std::vector<uint64_t> tablesizes = {1};
    Counttable counttable(1, tablesizes);
    counttable.load(counttablefile);
    timepoint alloc_end = std::chrono::system_clock::now();
    std::chrono::duration<double> alloc_elapsed = alloc_end - alloc_start;
    std::cerr << "done! (in " << alloc_elapsed.count() << " seconds)\n";
    return counttable;
}

int main(int argc, const char **argv)
{
    if (argc == 1) {
        print_usage(std::cout);
        return 0;
    }

    ProgramArgs args = {5, 1000000, 31, 0, 16, 1.0, 42, "snv", 2000000000, "", "", ""};
    parse_args(argc, argv, &args);

    Counttable counttable = args.refrcounts.compare("") == 0
                              ? load_from_counttable(args.refrcounts)
                              : load_from_seqfile(args.refrfile, args.ksize, args.memory);

    timepoint query_start = std::chrono::system_clock::now();
    std::cerr << "# iterating through " << args.seqfile << ", querying k-mer abundances...";
    Logger logger(args.interval, std::cerr);
    std::unique_ptr<Mutator> mut = NULL;
    if(args.muttype == "snv") {
        mut.reset(new MutatorSNV(args.ksize, logger, args.histmax, args.limit));
    }
    else if(args.muttype == "del") {
        mut.reset(new MutatorDel(args.ksize, args.delsize, logger, args.histmax, args.limit));
    }
    else {
        std::cerr << "Error: unknown mutation type '" << args.muttype << "'\n";
        exit(1);
    }
    mut->set_sampling_rate(args.sampling_rate, args.seed);

    FastxParserPtr parser = get_parser<FastxReader>(args.seqfile);
    Sequence seq;
    while (!parser->is_complete()) {
        try {
            seq = parser->get_next_read();
        } catch (NoMoreReadsAvailable &e) {
            break;
        }
        mut->process(seq.sequence, counttable);
    }
    timepoint query_end = std::chrono::system_clock::now();
    std::chrono::duration<double> query_elapsed = query_end - query_start;

    std::cerr << "done! processed " << mut->get_mut_count()
              << " mutations (in " << query_elapsed.count() << " seconds)\n\n";
    std::cout << *mut;

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Scarabaeus2D Unit for TTBlue
 * http://mathworld.wolfram.com/Scarabaeus.html
 * Originally written for the Jamoma TrajectoryLib
 * Copyright © 2010 by Nils Peters
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "Scarabaeus2D.h"

#define thisTTClass			Scarabaeus2D
#define thisTTClassName		"scarabaeus.2D"
#define thisTTClassTags		"audio, trajectory"

TT_AUDIO_CONSTRUCTOR
{   addAttribute(A,				kTypeFloat64);
	addAttribute(B,				kTypeFloat64);

	setAttributeValue(TT("a"),	0.6);
	setAttributeValue(TT("b"),	0.4);

	setProcessMethod(processAudio);
//	setCalculateMethod(calculateValue);
}

Scarabaeus2D::~Scarabaeus2D()
{
	;
}

//TTErr Scarabaeus2D::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
//{
//	y = x;
//	return kTTErrNone;
//}

TTErr Scarabaeus2D::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&		out = outputs->getSignal(0);
	TTUInt16			numOutputChannels = out.getNumChannelsAsInt();

	if (numOutputChannels != 2) {
		TTValue v = 2;
		out.setMaxNumChannels(v);
		out.setNumChannels(v);
	}

	TTAudioSignal&		in0 = inputs->getSignal(0);
	TTUInt16			 vs = in0.getVectorSizeAsInt();

	TTSampleValuePtr	inSampleX			= in0.mSampleVectors[0];
	TTSampleValuePtr	outSampleX    		= out.mSampleVectors[0];
	TTSampleValuePtr	outSampleY			= out.mSampleVectors[1];
    TTFloat64 phi, r;

	for (int i=0; i<vs; i++) {

		phi = inSampleX[i] * kTTPi; // 0 .. 2Pi
		r = mB * cos(2*phi) - mA * cos(phi);

		outSampleX[i] = sin(phi) * r;
		outSampleY[i] = cos(phi) * r;

	}
return kTTErrNone;
}
<commit_msg>adding a '2D' tag<commit_after>/*
 * Scarabaeus2D Unit for TTBlue
 * http://mathworld.wolfram.com/Scarabaeus.html
 * Originally written for the Jamoma TrajectoryLib
 * Copyright © 2010 by Nils Peters
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "Scarabaeus2D.h"

#define thisTTClass			Scarabaeus2D
#define thisTTClassName		"scarabaeus.2D"
#define thisTTClassTags		"audio, trajectory, 2D"

TT_AUDIO_CONSTRUCTOR
{   addAttribute(A,				kTypeFloat64);
	addAttribute(B,				kTypeFloat64);

	setAttributeValue(TT("a"),	0.6);
	setAttributeValue(TT("b"),	0.4);

	setProcessMethod(processAudio);
//	setCalculateMethod(calculateValue);
}

Scarabaeus2D::~Scarabaeus2D()
{
	;
}

//TTErr Scarabaeus2D::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
//{
//	y = x;
//	return kTTErrNone;
//}

TTErr Scarabaeus2D::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&		out = outputs->getSignal(0);
	TTUInt16			numOutputChannels = out.getNumChannelsAsInt();

	if (numOutputChannels != 2) {
		TTValue v = 2;
		out.setMaxNumChannels(v);
		out.setNumChannels(v);
	}

	TTAudioSignal&		in0 = inputs->getSignal(0);
	TTUInt16			 vs = in0.getVectorSizeAsInt();

	TTSampleValuePtr	inSampleX			= in0.mSampleVectors[0];
	TTSampleValuePtr	outSampleX    		= out.mSampleVectors[0];
	TTSampleValuePtr	outSampleY			= out.mSampleVectors[1];
    TTFloat64 phi, r;

	for (int i=0; i<vs; i++) {

		phi = inSampleX[i] * kTTPi; // 0 .. 2Pi
		r = mB * cos(2*phi) - mA * cos(phi);

		outSampleX[i] = sin(phi) * r;
		outSampleY[i] = cos(phi) * r;

	}
return kTTErrNone;
}
<|endoftext|>