<commit_before>/*************************************************************************
 *
 *  $RCSfile: attriblistmerge.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: fs $ $Date: 2000-12-12 12:02:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_
#define _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_

#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif

//.........................................................................
namespace xmloff
{
//.........................................................................

    //=====================================================================
    //= OAttribListMerger
    //=====================================================================
    typedef ::cppu::WeakImplHelper1 <   ::com::sun::star::xml::sax::XAttributeList
                                    >   OAttribListMerger_Base;
    /** implements the XAttributeList list by merging different source attribute lists

Currently, the time behavious is O(n), though it would be possible to change it to O(log n).

    */
    class OAttribListMerger : public OAttribListMerger_Base
    {
    protected:
        ::osl::Mutex        m_aMutex;
        DECLARE_STL_VECTOR( ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >, AttributeListArray );
        AttributeListArray  m_aLists;

        ~OAttribListMerger() { }

    public:
        OAttribListMerger() { }

        // attribute list handling
        // (very thinn at the moment ... only adding lists is allowed ... add more if you need it :)
        void addList(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rList);

        // XAttributeList
        virtual sal_Int16 SAL_CALL getLength(  ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getNameByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getTypeByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getTypeByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getValueByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getValueByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);

    protected:
        sal_Bool seekToIndex(sal_Int16 _nGlobalIndex, ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rSubList, sal_Int16& _rLocalIndex);
        sal_Bool seekToName(const ::rtl::OUString& _rName, ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rSubList, sal_Int16& _rLocalIndex);
    };

//.........................................................................
}   // namespace xmloff
//.........................................................................

#endif // _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *
 *  Revision 1.0 12.12.00 10:25:25  fs
 ************************************************************************/

<commit_msg>INTEGRATION: CWS ooo19126 (1.1.646); FILE MERGED 2005/09/05 14:38:54 rt 1.1.646.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: attriblistmerge.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:03:13 $
 *
 *  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 _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_
#define _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_

#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif

//.........................................................................
namespace xmloff
{
//.........................................................................

    //=====================================================================
    //= OAttribListMerger
    //=====================================================================
    typedef ::cppu::WeakImplHelper1 <   ::com::sun::star::xml::sax::XAttributeList
                                    >   OAttribListMerger_Base;
    /** implements the XAttributeList list by merging different source attribute lists

Currently, the time behavious is O(n), though it would be possible to change it to O(log n).

    */
    class OAttribListMerger : public OAttribListMerger_Base
    {
    protected:
        ::osl::Mutex        m_aMutex;
        DECLARE_STL_VECTOR( ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >, AttributeListArray );
        AttributeListArray  m_aLists;

        ~OAttribListMerger() { }

    public:
        OAttribListMerger() { }

        // attribute list handling
        // (very thinn at the moment ... only adding lists is allowed ... add more if you need it :)
        void addList(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rList);

        // XAttributeList
        virtual sal_Int16 SAL_CALL getLength(  ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getNameByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getTypeByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getTypeByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getValueByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getValueByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);

    protected:
        sal_Bool seekToIndex(sal_Int16 _nGlobalIndex, ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rSubList, sal_Int16& _rLocalIndex);
        sal_Bool seekToName(const ::rtl::OUString& _rName, ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rSubList, sal_Int16& _rLocalIndex);
    };

//.........................................................................
}   // namespace xmloff
//.........................................................................

#endif // _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.1.646.1  2005/09/05 14:38:54  rt
 *  #i54170# Change license header: remove SISSL
 *
 *  Revision 1.1  2000/12/12 12:02:13  fs
 *  initial checkin - helper class for mergin XAttributeList instances
 *
 *
 *  Revision 1.0 12.12.00 10:25:25  fs
 ************************************************************************/

<|endoftext|>


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

#include "base/command_line.h"
#include "base/prefs/pref_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/component_loader.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/test_launcher.h"
#include "testing/gtest/include/gtest/gtest.h"

typedef InProcessBrowserTest FirstRunBrowserTest;

IN_PROC_BROWSER_TEST_F(FirstRunBrowserTest, SetShowFirstRunBubblePref) {
  EXPECT_TRUE(g_browser_process->local_state()->FindPreference(
      prefs::kShowFirstRunBubbleOption));
  EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_DONT_SHOW,
            g_browser_process->local_state()->GetInteger(
                prefs::kShowFirstRunBubbleOption));
  EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
      first_run::FIRST_RUN_BUBBLE_SHOW));
  ASSERT_TRUE(g_browser_process->local_state()->FindPreference(
      prefs::kShowFirstRunBubbleOption));
  EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SHOW,
            g_browser_process->local_state()->GetInteger(
                prefs::kShowFirstRunBubbleOption));
  // Test that toggling the value works in either direction after it's been set.
  EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
      first_run::FIRST_RUN_BUBBLE_DONT_SHOW));
  EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_DONT_SHOW,
            g_browser_process->local_state()->GetInteger(
                prefs::kShowFirstRunBubbleOption));
  // Test that the value can't be set to FIRST_RUN_BUBBLE_SHOW after it has been
  // set to FIRST_RUN_BUBBLE_SUPPRESS.
  EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
      first_run::FIRST_RUN_BUBBLE_SUPPRESS));
  EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SUPPRESS,
            g_browser_process->local_state()->GetInteger(
                prefs::kShowFirstRunBubbleOption));
  EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
      first_run::FIRST_RUN_BUBBLE_SHOW));
  EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SUPPRESS,
            g_browser_process->local_state()->GetInteger(
                prefs::kShowFirstRunBubbleOption));
}

IN_PROC_BROWSER_TEST_F(FirstRunBrowserTest, SetShouldShowWelcomePage) {
  EXPECT_FALSE(first_run::ShouldShowWelcomePage());
  first_run::SetShouldShowWelcomePage();
  EXPECT_TRUE(first_run::ShouldShowWelcomePage());
  EXPECT_FALSE(first_run::ShouldShowWelcomePage());
}

#if !defined(OS_CHROMEOS)
namespace {
class FirstRunIntegrationBrowserTest : public InProcessBrowserTest {
 public:
  FirstRunIntegrationBrowserTest() {}
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    InProcessBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kForceFirstRun);
    EXPECT_FALSE(first_run::DidPerformProfileImport(NULL));

    extensions::ComponentLoader::EnableBackgroundExtensionsForTesting();

    // The forked import process should run BrowserMain.
    CommandLine import_arguments((CommandLine::NoProgram()));
    import_arguments.AppendSwitch(content::kLaunchAsBrowser);
    first_run::SetExtraArgumentsForImportProcess(import_arguments);
  }
 private:
  DISALLOW_COPY_AND_ASSIGN(FirstRunIntegrationBrowserTest);
};

class FirstRunMasterPrefsBrowserTest : public FirstRunIntegrationBrowserTest {
 public:
  FirstRunMasterPrefsBrowserTest() {}

 protected:
  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(file_util::CreateTemporaryFile(&prefs_file_));
    // TODO(tapted): Make this reusable.
    const char text[] =
        "{\n"
        "  \"distribution\": {\n"
        "    \"import_bookmarks\": false,\n"
        "    \"import_history\": false,\n"
        "    \"import_home_page\": false,\n"
        "    \"import_search_engine\": false\n"
        "  }\n"
        "}\n";
    EXPECT_TRUE(file_util::WriteFile(prefs_file_, text, strlen(text)));
    first_run::SetMasterPrefsPathForTesting(prefs_file_);

    // This invokes BrowserMain, and does the import, so must be done last.
    FirstRunIntegrationBrowserTest::SetUp();
  }

  virtual void TearDown() OVERRIDE {
    EXPECT_TRUE(file_util::Delete(prefs_file_, false));
    FirstRunIntegrationBrowserTest::TearDown();
  }

 private:
  base::FilePath prefs_file_;

  DISALLOW_COPY_AND_ASSIGN(FirstRunMasterPrefsBrowserTest);
};
}

// TODO(tapted): Investigate why this fails on Linux bots but does not
// reproduce locally. See http://crbug.com/178062 .
#if defined(OS_LINUX)
#define MAYBE_WaitForImport DISABLED_WaitForImport
#else
#define MAYBE_WaitForImport WaitForImport
#endif

IN_PROC_BROWSER_TEST_F(FirstRunIntegrationBrowserTest, MAYBE_WaitForImport) {
  bool success = false;
  EXPECT_TRUE(first_run::DidPerformProfileImport(&success));
  // Aura builds skip over the import process.
#if defined(USE_AURA)
  EXPECT_FALSE(success);
#else
  EXPECT_TRUE(success);
#endif
}

// Test an import with all import options disabled. This is a regression test
// for http://crbug.com/169984 where this would cause the import process to
// stay running, and the NTP to be loaded with no apps.
IN_PROC_BROWSER_TEST_F(FirstRunMasterPrefsBrowserTest,
                       ImportNothingAndShowNewTabPage) {
  EXPECT_TRUE(first_run::DidPerformProfileImport(NULL));
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL(chrome::kChromeUINewTabURL), CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  content::WebContents* tab = browser()->tab_strip_model()->GetWebContentsAt(0);
  EXPECT_EQ(1, tab->GetMaxPageID());
}

#endif  // !defined(OS_CHROMEOS)
<commit_msg>Disable FirstRunIntegrationBrowserTest.WaitForImport on mac_asan.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/prefs/pref_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/component_loader.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/test_launcher.h"
#include "testing/gtest/include/gtest/gtest.h"

typedef InProcessBrowserTest FirstRunBrowserTest;

IN_PROC_BROWSER_TEST_F(FirstRunBrowserTest, SetShowFirstRunBubblePref) {
  EXPECT_TRUE(g_browser_process->local_state()->FindPreference(
      prefs::kShowFirstRunBubbleOption));
  EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_DONT_SHOW,
            g_browser_process->local_state()->GetInteger(
                prefs::kShowFirstRunBubbleOption));
  EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
      first_run::FIRST_RUN_BUBBLE_SHOW));
  ASSERT_TRUE(g_browser_process->local_state()->FindPreference(
      prefs::kShowFirstRunBubbleOption));
  EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SHOW,
            g_browser_process->local_state()->GetInteger(
                prefs::kShowFirstRunBubbleOption));
  // Test that toggling the value works in either direction after it's been set.
  EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
      first_run::FIRST_RUN_BUBBLE_DONT_SHOW));
  EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_DONT_SHOW,
            g_browser_process->local_state()->GetInteger(
                prefs::kShowFirstRunBubbleOption));
  // Test that the value can't be set to FIRST_RUN_BUBBLE_SHOW after it has been
  // set to FIRST_RUN_BUBBLE_SUPPRESS.
  EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
      first_run::FIRST_RUN_BUBBLE_SUPPRESS));
  EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SUPPRESS,
            g_browser_process->local_state()->GetInteger(
                prefs::kShowFirstRunBubbleOption));
  EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
      first_run::FIRST_RUN_BUBBLE_SHOW));
  EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SUPPRESS,
            g_browser_process->local_state()->GetInteger(
                prefs::kShowFirstRunBubbleOption));
}

IN_PROC_BROWSER_TEST_F(FirstRunBrowserTest, SetShouldShowWelcomePage) {
  EXPECT_FALSE(first_run::ShouldShowWelcomePage());
  first_run::SetShouldShowWelcomePage();
  EXPECT_TRUE(first_run::ShouldShowWelcomePage());
  EXPECT_FALSE(first_run::ShouldShowWelcomePage());
}

#if !defined(OS_CHROMEOS)
namespace {
class FirstRunIntegrationBrowserTest : public InProcessBrowserTest {
 public:
  FirstRunIntegrationBrowserTest() {}
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    InProcessBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kForceFirstRun);
    EXPECT_FALSE(first_run::DidPerformProfileImport(NULL));

    extensions::ComponentLoader::EnableBackgroundExtensionsForTesting();

    // The forked import process should run BrowserMain.
    CommandLine import_arguments((CommandLine::NoProgram()));
    import_arguments.AppendSwitch(content::kLaunchAsBrowser);
    first_run::SetExtraArgumentsForImportProcess(import_arguments);
  }
 private:
  DISALLOW_COPY_AND_ASSIGN(FirstRunIntegrationBrowserTest);
};

class FirstRunMasterPrefsBrowserTest : public FirstRunIntegrationBrowserTest {
 public:
  FirstRunMasterPrefsBrowserTest() {}

 protected:
  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(file_util::CreateTemporaryFile(&prefs_file_));
    // TODO(tapted): Make this reusable.
    const char text[] =
        "{\n"
        "  \"distribution\": {\n"
        "    \"import_bookmarks\": false,\n"
        "    \"import_history\": false,\n"
        "    \"import_home_page\": false,\n"
        "    \"import_search_engine\": false\n"
        "  }\n"
        "}\n";
    EXPECT_TRUE(file_util::WriteFile(prefs_file_, text, strlen(text)));
    first_run::SetMasterPrefsPathForTesting(prefs_file_);

    // This invokes BrowserMain, and does the import, so must be done last.
    FirstRunIntegrationBrowserTest::SetUp();
  }

  virtual void TearDown() OVERRIDE {
    EXPECT_TRUE(file_util::Delete(prefs_file_, false));
    FirstRunIntegrationBrowserTest::TearDown();
  }

 private:
  base::FilePath prefs_file_;

  DISALLOW_COPY_AND_ASSIGN(FirstRunMasterPrefsBrowserTest);
};
}

// TODO(tapted): Investigate why this fails on Linux bots but does not
// reproduce locally. See http://crbug.com/178062 .
// TODO(tapted): Investigate why this fails on mac_asan flakily
// http://crbug.com/181499 .
#if defined(OS_LINUX) || (defined(OS_MACOSX) && defined(ADDRESS_SANITIZER))
#define MAYBE_WaitForImport DISABLED_WaitForImport
#else
#define MAYBE_WaitForImport WaitForImport
#endif

IN_PROC_BROWSER_TEST_F(FirstRunIntegrationBrowserTest, MAYBE_WaitForImport) {
  bool success = false;
  EXPECT_TRUE(first_run::DidPerformProfileImport(&success));
  // Aura builds skip over the import process.
#if defined(USE_AURA)
  EXPECT_FALSE(success);
#else
  EXPECT_TRUE(success);
#endif
}

// Test an import with all import options disabled. This is a regression test
// for http://crbug.com/169984 where this would cause the import process to
// stay running, and the NTP to be loaded with no apps.
IN_PROC_BROWSER_TEST_F(FirstRunMasterPrefsBrowserTest,
                       ImportNothingAndShowNewTabPage) {
  EXPECT_TRUE(first_run::DidPerformProfileImport(NULL));
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL(chrome::kChromeUINewTabURL), CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  content::WebContents* tab = browser()->tab_strip_model()->GetWebContentsAt(0);
  EXPECT_EQ(1, tab->GetMaxPageID());
}

#endif  // !defined(OS_CHROMEOS)
<|endoftext|>


<commit_before>

#include <QVBoxLayout>

#include <quartz_common/widgets/QzScroller.h>

#include "QuartzWindow.h"

namespace Vam { namespace Quartz {

QuartzWindow::QuartzWindow( QWidget *parent )
    : QMainWindow( parent )
{
    QWidget * widget = new QWidget( this );
    QVBoxLayout *layout = new QVBoxLayout();

    widget->setContentsMargins( QMargins() );
    layout->setContentsMargins( QMargins() );

    QzScroller *scroller = new QzScroller( Qt::Vertical, this );
    layout->addWidget( scroller );

    widget->setLayout( layout );
    setCentralWidget( widget );
}

QString QuartzWindow::createStylesheet()
{
    return "QWidget{"
            "background-color: black; "
            "color: #FFA858;"
            "border-color: black;"
        "}"
        "QPushButton{"
            "background-color: #202020; "
            "color: #FFA858;"
            "border-width: 8px;"
            "border-color: black;"
        "}"
        "QPushButton:pressed{"
           "background-color: #FFA858; "
           "color: white;"
           "border-width: 8px;"
           "border-color: black;"
        "}"
        "QLabel{"
           "color: #FFA858; "
           "border-width: 8px;"
           "border-color: black;"
           "font: monospace;"
        "}"
        "QPushButton:checked{"
           "background-color: #FFA858; "
           "color: black;"
           "border-width: 8px;"
           "border-color: black;"
        "}"
        "QToolButton{"
            "background-color: #323232; "
            "color: #FFA858;"
            "border-style: outset;"
            "border-color: black;"
            "border-radius: 5px;"
            "min-width: 40px;"
            "min-height: 20px;"
            "font-size: 10px;"
        "}"
         "QToolButton:hover{"
             "background-color: #6F5C44;"
         "}"
         "QToolButton:pressed{"
           "background-color: #FFA858; "
           "color: #323232;"
        "}"
         "QToolButton:disabled{"
            "background-color: #404040; "
            "color: gray;"
        "}"
        "QToolBar{"
            "spacing: 3px;"
        "}"
        "QTreeView{ "
            "background-color: #151515;"
            "alternate-background-color: #202020;"
        "}"
        "QTreeView::item:selected:active, QTreeView::item:selected:!active,"
        "QListView::item:selected:active, QListView::item:selected:!active{"
            "color: #151515; "
              "background-color: rgba( 255, 168, 48, 200 );"
            "background-color: #B2936C;"
        "}"
        "QHeaderView::section {"
            "background-color: #202020;"
            "color: white;"
        "}"
        "QTreeView::item:hover, QListView::item:hover { "
            "background-color: rgba( 255, 168, 48, 50 );"
        "}"
        "QProgressBar{ "
            "border-radius: 5px;"
            "color: white;"
            "text-align: center;"
        "}"
        "QProgressBar::chunk {"
            "background-color: #FFA858;"
        "}"
        "QLineEdit{ background-color: #444444;}"
        "QMenu{ background-color: #444444;}"
        "QMenu::item:selected{background-color: #696969; }"
        "QScrollBar::handle {"
            "background: #6F5C44;;"
            "min-width: 30px;"
            "border-radius: 3px;"
        "}"
        "QScrollBar{"
            "background: #202020;"
            "border-radius: 5px;"
        "}"
        "QScrollBar::add-line, QScrollBar::sub-line{"
            "border: 2px solid #202020;"
            "background: #202020;"
        "}";
}

} }
<commit_msg>1. Updating creation of scroller with size information 2. Testing the vertical orientation for scroller<commit_after>

#include <QVBoxLayout>

#include <quartz_common/widgets/QzScroller.h>

#include "QuartzWindow.h"

namespace Vam { namespace Quartz {

QuartzWindow::QuartzWindow( QWidget *parent )
    : QMainWindow( parent )
{
    QWidget * widget = new QWidget( this );
    QVBoxLayout *layout = new QVBoxLayout();

    widget->setContentsMargins( QMargins() );
    layout->setContentsMargins( QMargins() );

    QzScroller *scroller = new QzScroller( Qt::Horizontal,
                                           30,
                                           30,
                                           this );
    layout->addWidget( scroller );

    widget->setLayout( layout );
    setCentralWidget( widget );
}

QString QuartzWindow::createStylesheet()
{
    return "QWidget{"
            "background-color: black; "
            "color: #FFA858;"
            "border-color: black;"
        "}"
        "QPushButton{"
            "background-color: #202020; "
            "color: #FFA858;"
            "border-width: 8px;"
            "border-color: black;"
        "}"
        "QPushButton:pressed{"
           "background-color: #FFA858; "
           "color: white;"
           "border-width: 8px;"
           "border-color: black;"
        "}"
        "QLabel{"
           "color: #FFA858; "
           "border-width: 8px;"
           "border-color: black;"
           "font: monospace;"
        "}"
        "QPushButton:checked{"
           "background-color: #FFA858; "
           "color: black;"
           "border-width: 8px;"
           "border-color: black;"
        "}"
        "QToolButton{"
            "background-color: #323232; "
            "color: #FFA858;"
            "border-style: outset;"
            "border-color: black;"
            "border-radius: 5px;"
            "min-width: 40px;"
            "min-height: 20px;"
            "font-size: 10px;"
        "}"
         "QToolButton:hover{"
             "background-color: #6F5C44;"
         "}"
         "QToolButton:pressed{"
           "background-color: #FFA858; "
           "color: #323232;"
        "}"
         "QToolButton:disabled{"
            "background-color: #404040; "
            "color: gray;"
        "}"
        "QToolBar{"
            "spacing: 3px;"
        "}"
        "QTreeView{ "
            "background-color: #151515;"
            "alternate-background-color: #202020;"
        "}"
        "QTreeView::item:selected:active, QTreeView::item:selected:!active,"
        "QListView::item:selected:active, QListView::item:selected:!active{"
            "color: #151515; "
              "background-color: rgba( 255, 168, 48, 200 );"
            "background-color: #B2936C;"
        "}"
        "QHeaderView::section {"
            "background-color: #202020;"
            "color: white;"
        "}"
        "QTreeView::item:hover, QListView::item:hover { "
            "background-color: rgba( 255, 168, 48, 50 );"
        "}"
        "QProgressBar{ "
            "border-radius: 5px;"
            "color: white;"
            "text-align: center;"
        "}"
        "QProgressBar::chunk {"
            "background-color: #FFA858;"
        "}"
        "QLineEdit{ background-color: #444444;}"
        "QMenu{ background-color: #444444;}"
        "QMenu::item:selected{background-color: #696969; }"
        "QScrollBar::handle {"
            "background: #6F5C44;;"
            "min-width: 30px;"
            "border-radius: 3px;"
        "}"
        "QScrollBar{"
            "background: #202020;"
            "border-radius: 5px;"
        "}"
        "QScrollBar::add-line, QScrollBar::sub-line{"
            "border: 2px solid #202020;"
            "background: #202020;"
        "}";
}

} }
<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetReaderTest
#include <boost/test/unit_test.hpp>

#define private public
#define protected public

#include <cstddef>
#include <iostream>
#include <vector>

#include "../../JPetScopeReader/JPetScopeReader.h"
#include "../../JPetSignal/JPetSignal.h"
#include "../../JPetSigCh/JPetSigCh.h"

BOOST_AUTO_TEST_SUITE (FirstSuite)

BOOST_AUTO_TEST_CASE (default_constructor)
{
  JPetScopeReader reader;

  BOOST_REQUIRE(reader.fInputFile.is_open() == false);
  BOOST_REQUIRE(reader.fIsFileOpen == false);

//  BOOST_REQUIRE_EQUAL(reader.fSegments, 0);
  BOOST_REQUIRE_EQUAL(reader.fSegmentSize, 0);
}

BOOST_AUTO_TEST_CASE (open_file)
{
  JPetScopeReader reader;
  reader.openFile("C1_00000.txt");

  BOOST_REQUIRE(reader.fInputFile.is_open());
  BOOST_REQUIRE(reader.fIsFileOpen);

//  BOOST_REQUIRE_EQUAL(reader.fSegments, 0);
  BOOST_REQUIRE_EQUAL(reader.fSegmentSize, 0);

  reader.readHeader();

//  BOOST_CHECK_EQUAL(reader.fSegments, 1);
  BOOST_CHECK_EQUAL(reader.fSegmentSize, 502);

  JPetSignal* sig = reader.readData();
  int points  = sig->getNumberOfLeadingEdgePoints();
      points += sig->getNumberOfTrailingEdgePoints();

  BOOST_CHECK_EQUAL(points, 502);

  reader.closeFile();

  BOOST_REQUIRE(reader.fInputFile.is_open() == false);
  BOOST_REQUIRE(reader.fIsFileOpen == false);

}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Removed error with JPetScopeReaderTest $584<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetReaderTest
#include <boost/test/unit_test.hpp>

#define private public
#define protected public

#include <cstddef>
#include <iostream>
#include <vector>

#include "../../JPetScopeReader/JPetScopeReader.h"
#include "../../JPetSignal/JPetSignal.h"
#include "../../JPetSigCh/JPetSigCh.h"

BOOST_AUTO_TEST_SUITE (FirstSuite)

BOOST_AUTO_TEST_CASE (default_constructor)
{
  JPetScopeReader reader;

  BOOST_REQUIRE(reader.isFileOpen() == false);

//  BOOST_REQUIRE_EQUAL(reader.fSegments, 0);
  BOOST_REQUIRE_EQUAL(reader.fSegmentSize, 0);
}

BOOST_AUTO_TEST_CASE (open_file)
{
  JPetScopeReader reader;
  reader.openFile("C1_00000.txt");

  BOOST_REQUIRE(reader.isFileOpen());

//  BOOST_REQUIRE_EQUAL(reader.fSegments, 0);
  BOOST_REQUIRE_EQUAL(reader.fSegmentSize, 0);

  reader.readHeader();

//  BOOST_CHECK_EQUAL(reader.fSegments, 1);
  BOOST_CHECK_EQUAL(reader.fSegmentSize, 502);

  JPetSignal* sig = reader.readData();
  int points  = sig->getNumberOfLeadingEdgePoints();
      points += sig->getNumberOfTrailingEdgePoints();

  BOOST_CHECK_EQUAL(points, 502);

  reader.closeFile();

  BOOST_REQUIRE(reader.isFileOpen() == false);

}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"

/**
 * @brief Gives a std::string representation of a primitive type
 *
 * @param x Primitive type such as int, double, long
 * @return std::string conversion of param x
 */
template<typename T> std::string to_string(T x) {
	return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}

//function to calculate a temperature for the select action function as a function of time
double temperature();

//function to select next action
int selectAction(const PriorityQueue<int,double>& a_queue);

//function to update a q value
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);

int main()
{
	// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	// Libraries to load
	std::string bodyLibName = "bodyinfo";
	std::string movementLibName = "movementtools";

	// Name of camera module in library
	std::string bodyModuleName = "BodyInfo";
	std::string movementModuleName = "MovementTools";

	// Set broker name, ip and port, finding first available port from 54000
	const std::string brokerName = "MotionTimingBroker";
	int brokerPort = qi::os::findAvailablePort(54000);
	const std::string brokerIp = "0.0.0.0";

	// Default parent port and ip
	int pport = 9559;
	std::string pip = "127.0.0.1";

	// Need this for SOAP serialisation of floats to work
	setlocale(LC_NUMERIC, "C");

	// Create a broker
	boost::shared_ptr<AL::ALBroker> broker;
	try
	{
		broker = AL::ALBroker::createBroker(
				brokerName,
				brokerIp,
				brokerPort,
				pip,
				pport,
				0);
	}
	// Throw error and quit if a broker could not be created
	catch(...)
	{
		std::cerr << "Failed to connect broker to: "
			  << pip
			  << ":"
			  << pport
			  << std::endl;
		AL::ALBrokerManager::getInstance()->killAllBroker();
		AL::ALBrokerManager::kill();

		return 1;
	}

	// Add the broker to NAOqi
	AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
	AL::ALBrokerManager::getInstance()->addBroker(broker);

	CreateModule(movementLibName, movementModuleName, broker, false, true);
	CreateModule(bodyLibName, bodyModuleName, broker, false, true);

	AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
	AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
	AL::ALMotionProxy motion(pip, pport);
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW

	//learning factor
	const double alpha=0.5;
	//discount factor
	const double gamma=0.5;

	//seed rng
	std::srand(static_cast<unsigned int>(std::time(NULL)));

	int action_forwards = FORWARD;
	int action_backwards = BACKWARD;
	int chosen_action = action_forwards;

	//create a priority queue to copy to all the state space priority queues
	PriorityQueue<int,double> initiator_queue(MAX);
	initiator_queue.enqueueWithPriority(action_forwards,0);
	initiator_queue.enqueueWithPriority(action_backwards,0);

	//create encoder
	Encoder encoder;
	encoder.Calibrate();

	//create the state space
	StateSpace space(100,50,initiator_queue);

	//state objects
	State current_state(0,0,FORWARD);
	State old_state(0,0,FORWARD);

	while(true)
	{
		// set current state angle to angle received from encoder
		// and set current state velocity to difference in new and
		// old state angles over some time difference
		current_state.theta= M_PI * (encoder.GetAngle())/180;
		current_state.theta_dot=(current_state.theta - old_state.theta)/700; //Needs actual time
		current_state.robot_state=static_cast<ROBOT_STATE>(chosen_action);

		// call updateQ function with state space, old and current states
		// and learning rate, discount factor
		updateQ(space, chosen_action, old_state, current_state, alpha, gamma);

		// set old_state to current_state
		old_state=current_state;

		// determine chosen_action for current state
		chosen_action=selectAction(space[current_state]);

		// depending upon chosen action, call robot movement tools proxy with either
		// swingForwards or swingBackwards commands.
		(chosen_action)?movementToolsProxy.callVoid("swingForwards"):movementToolsProxy.callVoid("swingBackwards");
	}

	return 1;
}

/**
 * @brief Analog to temperature variable in Boltzmann Distribution.
 *
 * @return current system time in milliseconds
 */
double temperature()
{
	return static_cast<double>(std::time(NULL));
}

/**
 * @brief Selects an action to perform based on probabilities.
 *
 * @param a_queue A priority queue instance storing integral types with double type priorities,
 *		  represents the queue of possible actions with pre-initialised priority levels.
 * @return integer corresponding to chosen action
 */
int selectAction(const PriorityQueue<int,double>& a_queue)
{
	typedef PriorityQueue<int,double> PQ;
	typedef std::vector< std::pair<int, double> > Vec_Pair;
	typedef std::pair<int, double> Pair;

	double sum= 0;
	size_t i = 0;

	size_t size = a_queue.getSize();
	Vec_Pair action_vec(size);

	//Calculate partition function by iterating over action-values
	for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
	{
		sum += std::exp((iter->second)/temperature());
	}
	//Calculate boltzmann factors for action-values
	for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
	{
	    it->first = a_queue[i].first;
	    it->second = std::exp(a_queue[i].second /temperature()) / sum;
	    ++i;
	}

	//calculate cumulative probability distribution
	for(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it1 < end; ++it1,++it2)
	{
	    it1->second += it2->second;
	}

	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand())/ RAND_MAX;

	//select action based on probability
	for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
	{
		//if RN falls within cumulative probability bin return the corresponding action
		if(rand_num < it->second)return it->first;
	}

	return -1; //note that this line should never be reached
}

/**
 * @brief Updates the utility (Q-value) of the system
 *
 * @param space Reference to StateSpace object
 * @param new_state Reference to State instance giving the new system state
 * @param old_state Reference to State instance giving the old system state
 * @param alpha Learning rate of temporal difference learning algorithm
 * @param gamma Discount factor applied to q-learning equation
 */
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma)
{
    //oldQ value reference
    double oldQ = space[old_state].search(action).second;

    //reward given to current state
    double R = new_state.getReward();

    //optimal Q value for new state i.e. first element
    double maxQ = space[new_state].peekFront().second;

    //new Q value determined by Q learning algorithm
    double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);

    // change priority of action to new Q value
    space[old_state].changePriority(action, newQ);
}

/**
 * @brief Selects an action to perform based on probabilities.
 *
 * @param a_queue A priority queue instance storing integral types with double type priorities,
 *		  represents the queue of possible actions with pre-initialised priority levels.
 * @return integer corresponding to chosen action
 */
int selectActionAlt(const PriorityQueue<int, double>& a_queue) {

	// queue to store action values
	PriorityQueue<int, double> actionQueue(MAX);

	double sum = 0.0;

	// calculate partition function by iterating over action-values
	for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) {
		sum += std::exp((iter->second) / temperature());
	}

	// compute Boltzmann factors for action-values and enqueue to actionQueue
	for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) {
		double priority = std::exp(iter.operator*().second / temperature()) / sum;
		actionQueue.enqueueWithPriority(iter.operator*().first, priority);
	}

	// calculate cumulative probability distribution
	for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) {
		// change priority of it1->first data item in actionQueue to
		// sum of priorities of it1 and it2 items
		actionQueue.changePriority(it1->first, it1->second + it2->second);
	}

	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()) / RAND_MAX;

	// choose action based on random number relation to priorities within action queue
	for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) {
		if (rand_num < iter->second)
			return iter->first;
	}

	return -1; //note that this line should never be reached
}
<commit_msg>updated select action and commented out the depreeciated version<commit_after>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"

/**
 * @brief Gives a std::string representation of a primitive type
 *
 * @param x Primitive type such as int, double, long
 * @return std::string conversion of param x
 */
template<typename T> std::string to_string(T x) {
	return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}

//function to calculate a temperature for the select action function as a function of time
double temperature();

//function to select next action
int selectAction(const PriorityQueue<int,double>& a_queue);

//function to update a q value
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);

int main()
{
	// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	// Libraries to load
	std::string bodyLibName = "bodyinfo";
	std::string movementLibName = "movementtools";

	// Name of camera module in library
	std::string bodyModuleName = "BodyInfo";
	std::string movementModuleName = "MovementTools";

	// Set broker name, ip and port, finding first available port from 54000
	const std::string brokerName = "MotionTimingBroker";
	int brokerPort = qi::os::findAvailablePort(54000);
	const std::string brokerIp = "0.0.0.0";

	// Default parent port and ip
	int pport = 9559;
	std::string pip = "127.0.0.1";

	// Need this for SOAP serialisation of floats to work
	setlocale(LC_NUMERIC, "C");

	// Create a broker
	boost::shared_ptr<AL::ALBroker> broker;
	try
	{
		broker = AL::ALBroker::createBroker(
				brokerName,
				brokerIp,
				brokerPort,
				pip,
				pport,
				0);
	}
	// Throw error and quit if a broker could not be created
	catch(...)
	{
		std::cerr << "Failed to connect broker to: "
			  << pip
			  << ":"
			  << pport
			  << std::endl;
		AL::ALBrokerManager::getInstance()->killAllBroker();
		AL::ALBrokerManager::kill();

		return 1;
	}

	// Add the broker to NAOqi
	AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
	AL::ALBrokerManager::getInstance()->addBroker(broker);

	CreateModule(movementLibName, movementModuleName, broker, false, true);
	CreateModule(bodyLibName, bodyModuleName, broker, false, true);

	AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
	AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
	AL::ALMotionProxy motion(pip, pport);
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW

	//learning factor
	const double alpha=0.5;
	//discount factor
	const double gamma=0.5;

	//seed rng
	std::srand(static_cast<unsigned int>(std::time(NULL)));

	int action_forwards = FORWARD;
	int action_backwards = BACKWARD;
	int chosen_action = action_forwards;

	//create a priority queue to copy to all the state space priority queues
	PriorityQueue<int,double> initiator_queue(MAX);
	initiator_queue.enqueueWithPriority(action_forwards,0);
	initiator_queue.enqueueWithPriority(action_backwards,0);

	//create encoder
	Encoder encoder;
	encoder.Calibrate();

	//create the state space
	StateSpace space(100,50,initiator_queue);

	//state objects
	State current_state(0,0,FORWARD);
	State old_state(0,0,FORWARD);

	while(true)
	{
		// set current state angle to angle received from encoder
		// and set current state velocity to difference in new and
		// old state angles over some time difference
		current_state.theta= M_PI * (encoder.GetAngle())/180;
		current_state.theta_dot=(current_state.theta - old_state.theta)/700; //Needs actual time
		current_state.robot_state=static_cast<ROBOT_STATE>(chosen_action);

		// call updateQ function with state space, old and current states
		// and learning rate, discount factor
		updateQ(space, chosen_action, old_state, current_state, alpha, gamma);

		// set old_state to current_state
		old_state=current_state;

		// determine chosen_action for current state
		chosen_action=selectAction(space[current_state]);

		// depending upon chosen action, call robot movement tools proxy with either
		// swingForwards or swingBackwards commands.
		(chosen_action)?movementToolsProxy.callVoid("swingForwards"):movementToolsProxy.callVoid("swingBackwards");
	}

	return 1;
}

/**
 * @brief Analog to temperature variable in Boltzmann Distribution.
 *
 * @return current system time in milliseconds
 */
double temperature()
{
	return static_cast<double>(std::time(NULL));
}

/**
 * @brief Selects an action to perform based on probabilities.
 *
 * @param a_queue A priority queue instance storing integral types with double type priorities,
 *		  represents the queue of possible actions with pre-initialised priority levels.
 * @return integer corresponding to chosen action
 */
int selectAction(const PriorityQueue<int, double>& a_queue) {

	// queue to store action values
	PriorityQueue<int, double> actionQueue(MAX);

	double sum = 0.0;

	// calculate partition function by iterating over action-values
	for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) {
		sum += std::exp((iter->second) / temperature());
	}

	// compute Boltzmann factors for action-values and enqueue to actionQueue
	for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) {
		double priority = std::exp(iter.operator*().second / temperature()) / sum;
		actionQueue.enqueueWithPriority(iter.operator*().first, priority);
	}

	// calculate cumulative probability distribution
	for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) {
		// change priority of it1->first data item in actionQueue to
		// sum of priorities of it1 and it2 items
		actionQueue.changePriority(it1->first, it1->second + it2->second);
	}

	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()) / RAND_MAX;

	// choose action based on random number relation to priorities within action queue
	for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) {
		if (rand_num < iter->second)
			return iter->first;
	}

	return -1; //note that this line should never be reached
}

/**
 * @brief Updates the utility (Q-value) of the system
 *
 * @param space Reference to StateSpace object
 * @param new_state Reference to State instance giving the new system state
 * @param old_state Reference to State instance giving the old system state
 * @param alpha Learning rate of temporal difference learning algorithm
 * @param gamma Discount factor applied to q-learning equation
 */
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma)
{
    //oldQ value reference
    double oldQ = space[old_state].search(action).second;

    //reward given to current state
    double R = new_state.getReward();

    //optimal Q value for new state i.e. first element
    double maxQ = space[new_state].peekFront().second;

    //new Q value determined by Q learning algorithm
    double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);

    // change priority of action to new Q value
    space[old_state].changePriority(action, newQ);
}

/*old select action function in case the new one doesn't work
int selectAction(const PriorityQueue<int,double>& a_queue)
{
	typedef PriorityQueue<int,double> PQ;
	typedef std::vector< std::pair<int, double> > Vec_Pair;
	typedef std::pair<int, double> Pair;

	double sum= 0;
	size_t i = 0;

	size_t size = a_queue.getSize();
	Vec_Pair action_vec(size);

	//Calculate partition function by iterating over action-values
	for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
	{
		sum += std::exp((iter->second)/temperature());
	}
	//Calculate boltzmann factors for action-values
	for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
	{
	    it->first = a_queue[i].first;
	    it->second = std::exp(a_queue[i].second /temperature()) / sum;
	    ++i;
	}

	//calculate cumulative probability distribution
	for(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it1 < end; ++it1,++it2)
	{
	    it1->second += it2->second;
	}

	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand())/ RAND_MAX;

	//select action based on probability
	for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
	{
		//if RN falls within cumulative probability bin return the corresponding action
		if(rand_num < it->second)return it->first;
	}

	return -1; //note that this line should never be reached
}
*/
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2004-2007 Torsten Rahn  <tackat@kde.org>
// Copyright 2007      Inge Wallin   <ingwa@kde.org>
// Copyright 2007      Thomas Zander <zander@kde.org>
// Copyright 2010      Bastian Holst <bastianholst@gmx.de>
//

// Self
#include "CurrentLocationWidget.h"

// Marble
#include "AdjustNavigation.h"
#include "MarbleLocale.h"
#include "MarbleModel.h"
#include "MarbleWidget.h"
#include "GeoDataCoordinates.h"
#include "PositionProviderPlugin.h"
#include "PluginManager.h"
#include "PositionTracking.h"
#include "routing/RoutingManager.h"

using namespace Marble;
/* TRANSLATOR Marble::CurrentLocationWidget */

// Ui
#include "ui_CurrentLocationWidget.h"

#include <QtCore/QDateTime>
#include <QtGui/QFileDialog>

namespace Marble
{

class CurrentLocationWidgetPrivate
{
 public:
    Ui::CurrentLocationWidget      m_currentLocationUi;
    MarbleWidget                  *m_widget;
    AdjustNavigation *m_adjustNavigation;

    QList<PositionProviderPlugin*> m_positionProviderPlugins;
    GeoDataCoordinates             m_currentPosition;

    MarbleLocale*                  m_locale;

    void adjustPositionTrackingStatus( PositionProviderStatus status );
    void changePositionProvider( const QString &provider );
    void centerOnCurrentLocation();
    void updateRecenterComboBox( int centerMode );
    void updateAutoZoomCheckBox( bool autoZoom );
    void updateActivePositionProvider( PositionProviderPlugin* );
    void saveTrack();
    void clearTrack();
};

CurrentLocationWidget::CurrentLocationWidget( QWidget *parent, Qt::WindowFlags f )
    : QWidget( parent, f ),
      d( new CurrentLocationWidgetPrivate() )
{
    d->m_currentLocationUi.setupUi( this );

    d->m_locale = MarbleGlobal::getInstance()->locale();

    connect( d->m_currentLocationUi.recenterComboBox, SIGNAL ( currentIndexChanged( int ) ),
            this, SLOT( setRecenterMode( int ) ) );

    connect( d->m_currentLocationUi.autoZoomCheckBox, SIGNAL( clicked( bool ) ),
             this, SLOT( setAutoZoom( bool ) ) );

    bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
    d->m_currentLocationUi.positionTrackingComboBox->setVisible( !smallScreen );
    d->m_currentLocationUi.locationLabel->setVisible( !smallScreen );
}

CurrentLocationWidget::~CurrentLocationWidget()
{
    delete d;
}

void CurrentLocationWidget::setMarbleWidget( MarbleWidget *widget )
{
    d->m_widget = widget;

    d->m_adjustNavigation = new AdjustNavigation( d->m_widget, this );
    d->m_widget->model()->routingManager()->setAdjustNavigation( d->m_adjustNavigation );

    PluginManager* pluginManager = d->m_widget->model()->pluginManager();
    d->m_positionProviderPlugins = pluginManager->createPositionProviderPlugins();
    foreach( const PositionProviderPlugin *plugin, d->m_positionProviderPlugins ) {
        d->m_currentLocationUi.positionTrackingComboBox->addItem( plugin->guiString() );
    }
    if ( d->m_positionProviderPlugins.isEmpty() ) {
        d->m_currentLocationUi.positionTrackingComboBox->setEnabled( false );
        QString html = "
No Position Tracking Plugin installed.
";
        d->m_currentLocationUi.locationLabel->setText( html );
        d->m_currentLocationUi.locationLabel->setEnabled ( true );
        d->m_currentLocationUi.showTrackCheckBox->setEnabled( false );
        d->m_currentLocationUi.saveTrackPushButton->setEnabled( false );
        d->m_currentLocationUi.clearTrackPushButton->setEnabled( false );
    }

    //disconnect CurrentLocation Signals
    disconnect( d->m_widget->model()->positionTracking(),
             SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
             this, SLOT( receiveGpsCoordinates( GeoDataCoordinates, qreal ) ) );
    disconnect( d->m_widget->model()->positionTracking(),
             SIGNAL( positionProviderPluginChanged( PositionProviderPlugin* ) ),
             this, SLOT( updateActivePositionProvider( PositionProviderPlugin* ) ) );
    disconnect( d->m_currentLocationUi.positionTrackingComboBox, SIGNAL( currentIndexChanged( QString ) ),
             this, SLOT( changePositionProvider( QString ) ) );
    disconnect( d->m_currentLocationUi.locationLabel, SIGNAL( linkActivated( QString ) ),
             this, SLOT( centerOnCurrentLocation() ) );
    disconnect( d->m_widget->model()->positionTracking(),
             SIGNAL( statusChanged( PositionProviderStatus) ),this,
             SLOT( adjustPositionTrackingStatus( PositionProviderStatus) ) );

    disconnect( d->m_adjustNavigation, SIGNAL( recenterModeChanged( int ) ),
             this, SLOT( updateRecenterComboBox( int ) ) );
    disconnect( d->m_adjustNavigation, SIGNAL( autoZoomToggled( bool ) ),
             this, SLOT( updateAutoZoomCheckBox( bool ) ) );

    //connect CurrentLoctaion signals
    connect( d->m_widget->model()->positionTracking(),
             SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
             this, SLOT( receiveGpsCoordinates( GeoDataCoordinates, qreal ) ) );
    connect( d->m_widget->model()->positionTracking(),
             SIGNAL( positionProviderPluginChanged( PositionProviderPlugin* ) ),
             this, SLOT( updateActivePositionProvider( PositionProviderPlugin* ) ) );
    d->updateActivePositionProvider( d->m_widget->model()->positionTracking()->positionProviderPlugin() );
    connect( d->m_currentLocationUi.positionTrackingComboBox, SIGNAL( currentIndexChanged( QString ) ),
             this, SLOT( changePositionProvider( QString ) ) );
    connect( d->m_currentLocationUi.locationLabel, SIGNAL( linkActivated( QString ) ),
             this, SLOT( centerOnCurrentLocation() ) );
    connect( d->m_widget->model()->positionTracking(),
             SIGNAL( statusChanged( PositionProviderStatus) ), this,
             SLOT( adjustPositionTrackingStatus( PositionProviderStatus) ) );

    connect( d->m_adjustNavigation, SIGNAL( recenterModeChanged( int ) ),
             this, SLOT( updateRecenterComboBox( int ) ) );
    connect( d->m_adjustNavigation, SIGNAL( autoZoomToggled( bool ) ),
             this, SLOT( updateAutoZoomCheckBox( bool ) ) );
    connect (d->m_currentLocationUi.showTrackCheckBox, SIGNAL( clicked(bool) ),
             d->m_widget->model()->positionTracking(), SLOT( setTrackVisible(bool) ));
    connect (d->m_currentLocationUi.showTrackCheckBox, SIGNAL( clicked(bool) ),
             d->m_widget, SLOT(repaint()));
    if ( d->m_widget->model()->positionTracking()->trackVisible() ) {
        d->m_currentLocationUi.showTrackCheckBox->setCheckState(Qt::Checked);
    }
    connect ( d->m_currentLocationUi.saveTrackPushButton, SIGNAL( clicked(bool)),
              this, SLOT(saveTrack()));
    connect (d->m_currentLocationUi.clearTrackPushButton, SIGNAL( clicked(bool)),
             this, SLOT(clearTrack()));
}

void CurrentLocationWidgetPrivate::adjustPositionTrackingStatus( PositionProviderStatus status )
{
    if ( status == PositionProviderStatusAvailable ) {
        return;
    }

    QString html = "
";

    switch ( status ) {
        case PositionProviderStatusUnavailable:
        html += QObject::tr( "Waiting for current location information..." );
            break;
        case PositionProviderStatusAcquiring:
            html += QObject::tr( "Initializing current location service..." );
            break;
        case PositionProviderStatusAvailable:
            Q_ASSERT( false );
            break;
        case PositionProviderStatusError:
            html += QObject::tr( "Error when determining current location: " );
            html += m_widget->model()->positionTracking()->error();
            break;
    }

    html += "
";
    m_currentLocationUi.locationLabel->setEnabled( true );
    m_currentLocationUi.locationLabel->setText( html );
}

void CurrentLocationWidgetPrivate::updateActivePositionProvider( PositionProviderPlugin *plugin )
{
    m_currentLocationUi.positionTrackingComboBox->blockSignals( true );
    if ( !plugin ) {
        m_currentLocationUi.positionTrackingComboBox->setCurrentIndex( 0 );
    } else {
        for( int i=0; i<m_currentLocationUi.positionTrackingComboBox->count(); ++i ) {
            if ( m_currentLocationUi.positionTrackingComboBox->itemText( i ) == plugin->guiString() ) {
                m_currentLocationUi.positionTrackingComboBox->setCurrentIndex( i );
                break;
            }
        }
    }
    m_currentLocationUi.positionTrackingComboBox->blockSignals( false );
    m_currentLocationUi.recenterLabel->setEnabled( plugin );
    m_currentLocationUi.recenterComboBox->setEnabled( plugin );
    m_currentLocationUi.autoZoomCheckBox->setEnabled( plugin );

}

void CurrentLocationWidget::receiveGpsCoordinates( const GeoDataCoordinates &position, qreal speed )
{
    d->m_currentPosition = position;
    QString unitString;
    QString speedString;
    QString distanceUnitString;
    QString distanceString;
    qreal unitSpeed = 0.0;
    qreal distance = 0.0;

    QString html = "";
    html += "
";
    html += "
Longitude	%1
";
    html += "
Latitude	%2
";
    html += "
Altitude	%3
";
    html += "
Speed	%4
";
    html += "
";
    html += "";

    switch ( d->m_locale->measureSystem() ) {
        case Metric:
        //kilometers per hour
        unitString = tr("km/h");
        unitSpeed = speed * HOUR2SEC * METER2KM;
        distanceUnitString = tr("m");
        distance = position.altitude();
        break;

        case Imperial:
        //miles per hour
        unitString = tr("m/h");
        unitSpeed = speed * HOUR2SEC * METER2KM * KM2MI;
        distanceUnitString = tr("ft");
        distance = position.altitude() * M2FT;
        break;
    }
    // TODO read this value from the incoming signal
    speedString = QLocale::system().toString( unitSpeed, 'f', 1);
    distanceString = QString( "%1 %2" ).arg( distance, 0, 'f', 1, QChar(' ') ).arg( distanceUnitString );

    html = html.arg( position.lonToString() ).arg( position.latToString() );
    html = html.arg( distanceString ).arg( speedString + ' ' + unitString );
    d->m_currentLocationUi.locationLabel->setText( html );
    d->m_currentLocationUi.showTrackCheckBox->setEnabled( true );
    d->m_currentLocationUi.saveTrackPushButton->setEnabled( true );
    d->m_currentLocationUi.clearTrackPushButton->setEnabled( true );
}

void CurrentLocationWidgetPrivate::changePositionProvider( const QString &provider )
{
    bool hasProvider = ( provider != QObject::tr("Disabled") );

    if ( hasProvider ) {
        foreach( PositionProviderPlugin* plugin, m_positionProviderPlugins ) {
            if ( plugin->guiString() == provider ) {
                m_currentLocationUi.locationLabel->setEnabled( true );
                PositionProviderPlugin* instance = plugin->newInstance();
                PositionTracking *tracking = m_widget->model()->positionTracking();
                tracking->setPositionProviderPlugin( instance );
                m_widget->setShowGps( true );
                m_widget->update();
                return;
            }
        }
    }
    else {
        m_currentLocationUi.locationLabel->setEnabled( false );
        m_widget->setShowGps( false );
        m_widget->model()->positionTracking()->setPositionProviderPlugin( 0 );
        m_widget->update();
    }
}

void CurrentLocationWidget::setRecenterMode( int centerMode )
{
    d->m_adjustNavigation->setRecenter( centerMode );
}

void CurrentLocationWidget::setAutoZoom( bool autoZoom )
{
    d->m_adjustNavigation->setAutoZoom( autoZoom );
}

void CurrentLocationWidgetPrivate::updateAutoZoomCheckBox( bool autoZoom )
{
    m_currentLocationUi.autoZoomCheckBox->setChecked( autoZoom );
}

void CurrentLocationWidgetPrivate::updateRecenterComboBox( int centerMode )
{
    m_currentLocationUi.recenterComboBox->setCurrentIndex( centerMode );
}

void CurrentLocationWidgetPrivate::centerOnCurrentLocation()
{
    m_widget->centerOn(m_currentPosition, true);
}

void CurrentLocationWidgetPrivate::saveTrack()
{
    static QString s_dirName = QDir::homePath();
    QString fileName = QFileDialog::getSaveFileName(m_widget, QObject::tr("Save Track"), // krazy:exclude=qclasses
                                                    s_dirName.append('/' + QDateTime::currentDateTime().toString("yyyy-MM-dd_hhmmss") + ".kml"),
                            QObject::tr("KML File (*.kml)"));
    if ( fileName ) {
        QFileInfo file( fileName );
        s_dirName = file.absolutePath();
        m_widget->model()->positionTracking()->saveTrack( fileName );
    }
}

void CurrentLocationWidgetPrivate::clearTrack()
{
    m_widget->model()->positionTracking()->clearTrack();
    m_widget->repaint();
    m_currentLocationUi.saveTrackPushButton->setEnabled( false );
    m_currentLocationUi.clearTrackPushButton->setEnabled( false );
}

}

#include "CurrentLocationWidget.moc"
<commit_msg>fix cancel case<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2004-2007 Torsten Rahn  <tackat@kde.org>
// Copyright 2007      Inge Wallin   <ingwa@kde.org>
// Copyright 2007      Thomas Zander <zander@kde.org>
// Copyright 2010      Bastian Holst <bastianholst@gmx.de>
//

// Self
#include "CurrentLocationWidget.h"

// Marble
#include "AdjustNavigation.h"
#include "MarbleLocale.h"
#include "MarbleModel.h"
#include "MarbleWidget.h"
#include "GeoDataCoordinates.h"
#include "PositionProviderPlugin.h"
#include "PluginManager.h"
#include "PositionTracking.h"
#include "routing/RoutingManager.h"

using namespace Marble;
/* TRANSLATOR Marble::CurrentLocationWidget */

// Ui
#include "ui_CurrentLocationWidget.h"

#include <QtCore/QDateTime>
#include <QtGui/QFileDialog>

namespace Marble
{

class CurrentLocationWidgetPrivate
{
 public:
    Ui::CurrentLocationWidget      m_currentLocationUi;
    MarbleWidget                  *m_widget;
    AdjustNavigation *m_adjustNavigation;

    QList<PositionProviderPlugin*> m_positionProviderPlugins;
    GeoDataCoordinates             m_currentPosition;

    MarbleLocale*                  m_locale;

    void adjustPositionTrackingStatus( PositionProviderStatus status );
    void changePositionProvider( const QString &provider );
    void centerOnCurrentLocation();
    void updateRecenterComboBox( int centerMode );
    void updateAutoZoomCheckBox( bool autoZoom );
    void updateActivePositionProvider( PositionProviderPlugin* );
    void saveTrack();
    void clearTrack();
};

CurrentLocationWidget::CurrentLocationWidget( QWidget *parent, Qt::WindowFlags f )
    : QWidget( parent, f ),
      d( new CurrentLocationWidgetPrivate() )
{
    d->m_currentLocationUi.setupUi( this );

    d->m_locale = MarbleGlobal::getInstance()->locale();

    connect( d->m_currentLocationUi.recenterComboBox, SIGNAL ( currentIndexChanged( int ) ),
            this, SLOT( setRecenterMode( int ) ) );

    connect( d->m_currentLocationUi.autoZoomCheckBox, SIGNAL( clicked( bool ) ),
             this, SLOT( setAutoZoom( bool ) ) );

    bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
    d->m_currentLocationUi.positionTrackingComboBox->setVisible( !smallScreen );
    d->m_currentLocationUi.locationLabel->setVisible( !smallScreen );
}

CurrentLocationWidget::~CurrentLocationWidget()
{
    delete d;
}

void CurrentLocationWidget::setMarbleWidget( MarbleWidget *widget )
{
    d->m_widget = widget;

    d->m_adjustNavigation = new AdjustNavigation( d->m_widget, this );
    d->m_widget->model()->routingManager()->setAdjustNavigation( d->m_adjustNavigation );

    PluginManager* pluginManager = d->m_widget->model()->pluginManager();
    d->m_positionProviderPlugins = pluginManager->createPositionProviderPlugins();
    foreach( const PositionProviderPlugin *plugin, d->m_positionProviderPlugins ) {
        d->m_currentLocationUi.positionTrackingComboBox->addItem( plugin->guiString() );
    }
    if ( d->m_positionProviderPlugins.isEmpty() ) {
        d->m_currentLocationUi.positionTrackingComboBox->setEnabled( false );
        QString html = "
No Position Tracking Plugin installed.
";
        d->m_currentLocationUi.locationLabel->setText( html );
        d->m_currentLocationUi.locationLabel->setEnabled ( true );
        d->m_currentLocationUi.showTrackCheckBox->setEnabled( false );
        d->m_currentLocationUi.saveTrackPushButton->setEnabled( false );
        d->m_currentLocationUi.clearTrackPushButton->setEnabled( false );
    }

    //disconnect CurrentLocation Signals
    disconnect( d->m_widget->model()->positionTracking(),
             SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
             this, SLOT( receiveGpsCoordinates( GeoDataCoordinates, qreal ) ) );
    disconnect( d->m_widget->model()->positionTracking(),
             SIGNAL( positionProviderPluginChanged( PositionProviderPlugin* ) ),
             this, SLOT( updateActivePositionProvider( PositionProviderPlugin* ) ) );
    disconnect( d->m_currentLocationUi.positionTrackingComboBox, SIGNAL( currentIndexChanged( QString ) ),
             this, SLOT( changePositionProvider( QString ) ) );
    disconnect( d->m_currentLocationUi.locationLabel, SIGNAL( linkActivated( QString ) ),
             this, SLOT( centerOnCurrentLocation() ) );
    disconnect( d->m_widget->model()->positionTracking(),
             SIGNAL( statusChanged( PositionProviderStatus) ),this,
             SLOT( adjustPositionTrackingStatus( PositionProviderStatus) ) );

    disconnect( d->m_adjustNavigation, SIGNAL( recenterModeChanged( int ) ),
             this, SLOT( updateRecenterComboBox( int ) ) );
    disconnect( d->m_adjustNavigation, SIGNAL( autoZoomToggled( bool ) ),
             this, SLOT( updateAutoZoomCheckBox( bool ) ) );

    //connect CurrentLoctaion signals
    connect( d->m_widget->model()->positionTracking(),
             SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
             this, SLOT( receiveGpsCoordinates( GeoDataCoordinates, qreal ) ) );
    connect( d->m_widget->model()->positionTracking(),
             SIGNAL( positionProviderPluginChanged( PositionProviderPlugin* ) ),
             this, SLOT( updateActivePositionProvider( PositionProviderPlugin* ) ) );
    d->updateActivePositionProvider( d->m_widget->model()->positionTracking()->positionProviderPlugin() );
    connect( d->m_currentLocationUi.positionTrackingComboBox, SIGNAL( currentIndexChanged( QString ) ),
             this, SLOT( changePositionProvider( QString ) ) );
    connect( d->m_currentLocationUi.locationLabel, SIGNAL( linkActivated( QString ) ),
             this, SLOT( centerOnCurrentLocation() ) );
    connect( d->m_widget->model()->positionTracking(),
             SIGNAL( statusChanged( PositionProviderStatus) ), this,
             SLOT( adjustPositionTrackingStatus( PositionProviderStatus) ) );

    connect( d->m_adjustNavigation, SIGNAL( recenterModeChanged( int ) ),
             this, SLOT( updateRecenterComboBox( int ) ) );
    connect( d->m_adjustNavigation, SIGNAL( autoZoomToggled( bool ) ),
             this, SLOT( updateAutoZoomCheckBox( bool ) ) );
    connect (d->m_currentLocationUi.showTrackCheckBox, SIGNAL( clicked(bool) ),
             d->m_widget->model()->positionTracking(), SLOT( setTrackVisible(bool) ));
    connect (d->m_currentLocationUi.showTrackCheckBox, SIGNAL( clicked(bool) ),
             d->m_widget, SLOT(repaint()));
    if ( d->m_widget->model()->positionTracking()->trackVisible() ) {
        d->m_currentLocationUi.showTrackCheckBox->setCheckState(Qt::Checked);
    }
    connect ( d->m_currentLocationUi.saveTrackPushButton, SIGNAL( clicked(bool)),
              this, SLOT(saveTrack()));
    connect (d->m_currentLocationUi.clearTrackPushButton, SIGNAL( clicked(bool)),
             this, SLOT(clearTrack()));
}

void CurrentLocationWidgetPrivate::adjustPositionTrackingStatus( PositionProviderStatus status )
{
    if ( status == PositionProviderStatusAvailable ) {
        return;
    }

    QString html = "
";

    switch ( status ) {
        case PositionProviderStatusUnavailable:
        html += QObject::tr( "Waiting for current location information..." );
            break;
        case PositionProviderStatusAcquiring:
            html += QObject::tr( "Initializing current location service..." );
            break;
        case PositionProviderStatusAvailable:
            Q_ASSERT( false );
            break;
        case PositionProviderStatusError:
            html += QObject::tr( "Error when determining current location: " );
            html += m_widget->model()->positionTracking()->error();
            break;
    }

    html += "
";
    m_currentLocationUi.locationLabel->setEnabled( true );
    m_currentLocationUi.locationLabel->setText( html );
}

void CurrentLocationWidgetPrivate::updateActivePositionProvider( PositionProviderPlugin *plugin )
{
    m_currentLocationUi.positionTrackingComboBox->blockSignals( true );
    if ( !plugin ) {
        m_currentLocationUi.positionTrackingComboBox->setCurrentIndex( 0 );
    } else {
        for( int i=0; i<m_currentLocationUi.positionTrackingComboBox->count(); ++i ) {
            if ( m_currentLocationUi.positionTrackingComboBox->itemText( i ) == plugin->guiString() ) {
                m_currentLocationUi.positionTrackingComboBox->setCurrentIndex( i );
                break;
            }
        }
    }
    m_currentLocationUi.positionTrackingComboBox->blockSignals( false );
    m_currentLocationUi.recenterLabel->setEnabled( plugin );
    m_currentLocationUi.recenterComboBox->setEnabled( plugin );
    m_currentLocationUi.autoZoomCheckBox->setEnabled( plugin );

}

void CurrentLocationWidget::receiveGpsCoordinates( const GeoDataCoordinates &position, qreal speed )
{
    d->m_currentPosition = position;
    QString unitString;
    QString speedString;
    QString distanceUnitString;
    QString distanceString;
    qreal unitSpeed = 0.0;
    qreal distance = 0.0;

    QString html = "";
    html += "
";
    html += "
Longitude	%1
";
    html += "
Latitude	%2
";
    html += "
Altitude	%3
";
    html += "
Speed	%4
";
    html += "
";
    html += "";

    switch ( d->m_locale->measureSystem() ) {
        case Metric:
        //kilometers per hour
        unitString = tr("km/h");
        unitSpeed = speed * HOUR2SEC * METER2KM;
        distanceUnitString = tr("m");
        distance = position.altitude();
        break;

        case Imperial:
        //miles per hour
        unitString = tr("m/h");
        unitSpeed = speed * HOUR2SEC * METER2KM * KM2MI;
        distanceUnitString = tr("ft");
        distance = position.altitude() * M2FT;
        break;
    }
    // TODO read this value from the incoming signal
    speedString = QLocale::system().toString( unitSpeed, 'f', 1);
    distanceString = QString( "%1 %2" ).arg( distance, 0, 'f', 1, QChar(' ') ).arg( distanceUnitString );

    html = html.arg( position.lonToString() ).arg( position.latToString() );
    html = html.arg( distanceString ).arg( speedString + ' ' + unitString );
    d->m_currentLocationUi.locationLabel->setText( html );
    d->m_currentLocationUi.showTrackCheckBox->setEnabled( true );
    d->m_currentLocationUi.saveTrackPushButton->setEnabled( true );
    d->m_currentLocationUi.clearTrackPushButton->setEnabled( true );
}

void CurrentLocationWidgetPrivate::changePositionProvider( const QString &provider )
{
    bool hasProvider = ( provider != QObject::tr("Disabled") );

    if ( hasProvider ) {
        foreach( PositionProviderPlugin* plugin, m_positionProviderPlugins ) {
            if ( plugin->guiString() == provider ) {
                m_currentLocationUi.locationLabel->setEnabled( true );
                PositionProviderPlugin* instance = plugin->newInstance();
                PositionTracking *tracking = m_widget->model()->positionTracking();
                tracking->setPositionProviderPlugin( instance );
                m_widget->setShowGps( true );
                m_widget->update();
                return;
            }
        }
    }
    else {
        m_currentLocationUi.locationLabel->setEnabled( false );
        m_widget->setShowGps( false );
        m_widget->model()->positionTracking()->setPositionProviderPlugin( 0 );
        m_widget->update();
    }
}

void CurrentLocationWidget::setRecenterMode( int centerMode )
{
    d->m_adjustNavigation->setRecenter( centerMode );
}

void CurrentLocationWidget::setAutoZoom( bool autoZoom )
{
    d->m_adjustNavigation->setAutoZoom( autoZoom );
}

void CurrentLocationWidgetPrivate::updateAutoZoomCheckBox( bool autoZoom )
{
    m_currentLocationUi.autoZoomCheckBox->setChecked( autoZoom );
}

void CurrentLocationWidgetPrivate::updateRecenterComboBox( int centerMode )
{
    m_currentLocationUi.recenterComboBox->setCurrentIndex( centerMode );
}

void CurrentLocationWidgetPrivate::centerOnCurrentLocation()
{
    m_widget->centerOn(m_currentPosition, true);
}

void CurrentLocationWidgetPrivate::saveTrack()
{
    static QString s_dirName = QDir::homePath();
    QString suggested = s_dirName;
    QString fileName = QFileDialog::getSaveFileName(m_widget, QObject::tr("Save Track"), // krazy:exclude=qclasses
                                                    suggested.append('/' + QDateTime::currentDateTime().toString("yyyy-MM-dd_hhmmss") + ".kml"),
                            QObject::tr("KML File (*.kml)"));
    if ( !fileName.isEmpty() ) {
        QFileInfo file( fileName );
        s_dirName = file.absolutePath();
        m_widget->model()->positionTracking()->saveTrack( fileName );
    }
}

void CurrentLocationWidgetPrivate::clearTrack()
{
    m_widget->model()->positionTracking()->clearTrack();
    m_widget->repaint();
    m_currentLocationUi.saveTrackPushButton->setEnabled( false );
    m_currentLocationUi.clearTrackPushButton->setEnabled( false );
}

}

#include "CurrentLocationWidget.moc"
<|endoftext|>


<commit_before>/*
 * Telefónica Digital - Product Development and Innovation
 *
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * Copyright (c) Telefónica Investigación y Desarrollo S.A.U.
 * All rights reserved.
 */

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#include "parseArgs/paConfig.h"
#include "parseArgs/parseArgs.h"

#include "logMsg/logMsg.h"

#include "au/CommandLine.h"  // au::CommandLine
#include "au/statistics/Cronometer.h"  // au::Cronometer
#include "au/string/StringUtilities.h"  // au::str()

#include "au/CommandLine.h"     // au::CommandLine

#define PROGRESSIVE_NUMBER 20000

static const char *manShortDescription =
  "word_generator - a simple tool to generate a random sequence of words. Useful in demos on word counting and topic trending.\n";

static const char *manSynopsis =
  "   [-r] [-t secs] [-l len] num_words\n"
  "       [-ramdon] flag to generate randomized sequence of words\n"
  "       [-repeat secs] time_to_repeat in seconds with a new wave of words\n"
  "       [-l length] Number of letters of generated words ( default 9 ) \n"
  "       [-alphabet alphabet size] Number of differnt letters used to generate words ( default 10 ) \n"
  "       [-progresive] flag to generate sequences of numbers in incressing order ( hit demo )\n";

int word_length;
int alphabet_length;
bool rand_flag;
int max_num_lines;
bool progresive;
int max_rate;  // Max rate of words per second
PaArgument paArgs[] =
{
  { "-l",           &word_length,     "", PaInt,  PaOpt, 9,
    1,
    30,
    "Number of letters of generated words ( default 9 )"                           },
  { "-alphabet",    &alphabet_length, "", PaInt,  PaOpt, 10,
    1,
    30,
    "Number of differnt letters used to generate words ( default 10 )"             },
  { "-random",      &rand_flag,       "", PaBool, PaOpt,
    false,
    false, true,
    "Flag to generate completelly randomized sequence of words"                    },
  { "-progressive", &progresive,      "", PaBool, PaOpt,
    false,
    false, true,
    "Flag to generate sequences of numbers in incressing order"                    },
  { "-rate",        &max_rate,        "", PaInt,  PaOpt, 0,
    0,
    10000000000, "Max rate in words / second"                 },
  { " ",            &max_num_lines,   "", PaInt,  PaOpt, 0,
    0,
    1000000000,
    "Number of words to be generated"                                              },
  PA_END_OF_ARGS
};

int logFd = -1;

char word[100];                  // Place for this word
int progressive_word_slots[100];  // Indexes to generate progressive words

au::Cronometer cronometer;

// Get a new random  word
void getNewWord() {
  if (progresive) {
    for (int i = 0; i < word_length; i++) {
      word[i] = 48 + progressive_word_slots[i];
    }

    // Increase counter...
    progressive_word_slots[word_length - 1]++;

    int pos = word_length - 1;
    while ((pos >= 0) && (progressive_word_slots[pos] >= alphabet_length)) {
      progressive_word_slots[pos] = 0;
      if (pos > 0) {
        progressive_word_slots[pos - 1]++;
      }
      pos--;
    }

    return;
  }

  for (int i = 0; i < word_length; i++) {
    word[i] = 48 + rand() % alphabet_length;
  }
}

class BufferToScreen {
  char *buffer;
  size_t max_size;
  size_t size;

public:

  BufferToScreen(size_t _max_size) {
    max_size = _max_size;
    buffer = (char *)malloc(max_size);
    size = 0;
  }

  void append(char *data, int len) {
    if ((size + len) > max_size) {
      flush();
    }
    memcpy(buffer + size, data, len);
    size += len;
  }

  void flush() {
    size_t w = write(1, buffer, size);

    if (w != size) {
      LM_X(1, ("Problem writing %lu bytes to the screen", size));
    }
    size = 0;
  }
};

int main(int argC, const char *argV[]) {
  paConfig("usage and exit on any warning", (void *)true);

  paConfig("log to screen", (void *)true);
  paConfig("log to file", (void *)false);
  paConfig("screen line format", (void *)"TYPE:EXEC: TEXT");
  paConfig("man shortdescription", (void *)manShortDescription);
  paConfig("man synopsis", (void *)manSynopsis);
  paConfig("log to stderr", (void *)true);

  // Parse input arguments
  paParse(paArgs, argC, (char **)argV, 1, false);
  logFd = lmFirstDiskFileDescriptor();

  // Init progressive
  if (progresive) {
    for (int i = 0; i < word_length; i++) {
      progressive_word_slots[i] = 0;
    }  // End of line for all the words...
  }
  word[word_length] = '\n';
  word[word_length + 1] = '\0';

  size_t num_lines = 0;
  size_t total_size = 0;

  // Init random numbers if random specified
  if (rand_flag) {
    srand(time(NULL));
  } else {
    srand(0);  // Time to show a message on screen in verbose mode
  }
  size_t last_message_time = 0;

  // Buffer to flsh data to screen in batches
  BufferToScreen buffer_to_screen(10000);

  double lines_per_second = 0;

  // Generate continuously...
  while (true) {
    // Check the limit of generated words
    if (max_num_lines > 0) {
      if (num_lines >= (size_t)max_num_lines) {
        break;  // Get new word
      }
    }
    getNewWord();

    // Length of this word
    int word_len = strlen(word);

    // Append to the screen
    buffer_to_screen.append(word, word_len);

    // Counter of bytes and words
    total_size += word_len;
    num_lines++;

    // This avoid exesive calls to timeout
    if (lines_per_second > 100000) {
      size_t num_continue = lines_per_second / 100;
      if ((num_lines % num_continue) != 0) {
        continue;
      }
    }

    // Flush accumulated buffer so far
    buffer_to_screen.flush();

    // Get the total number of seconds running...
    size_t total_seconds = cronometer.seconds();

    // Compute the number of lines per second, so far...
    if (total_seconds > 0) {
      lines_per_second = (double)num_lines / (double)total_seconds;
    }
    if ((total_seconds - last_message_time) > 5) {
      last_message_time = total_seconds;
      LM_V(("Generated %s lines ( %s bytes ) in %s. Rate: %s / %s",
            au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
            au::str((double)num_lines / (double)total_seconds,
                    "Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str()));
    }

    if (total_seconds > 0) {
      if (max_num_lines > 100) {
        if ((num_lines % (max_num_lines / 100)) == 0) {
          LM_V(("Generated %s - %s lines ( %s bytes ) in %s. Rate: %s / %s",
                au::str_percentage(num_lines, max_num_lines).c_str(),
                au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
                au::str((double)num_lines / (double)total_seconds,
                        "Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str()));   // Sleep if necessary
        }
      }
    }
    if (max_rate > 0) {
      size_t theoretical_seconds = num_lines / max_rate;

      if (total_seconds < theoretical_seconds) {
        sleep(theoretical_seconds - total_seconds);
      }
    }
  }

  buffer_to_screen.flush();

  size_t total_seconds = cronometer.seconds();
  LM_V(("Generated %s lines ( %s bytes ) in %s. Rate: %s / %s",
        au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
        au::str((double)num_lines / (double)total_seconds,
                "Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str()));
}

<commit_msg>Fix conflicts<commit_after>/*
 * Telefónica Digital - Product Development and Innovation
 *
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * Copyright (c) Telefónica Investigación y Desarrollo S.A.U.
 * All rights reserved.
 */

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#include "parseArgs/paConfig.h"
#include "parseArgs/parseArgs.h"

#include "logMsg/logMsg.h"

#include "au/CommandLine.h"  // au::CommandLine
#include "au/statistics/Cronometer.h"  // au::Cronometer
#include "au/string/StringUtilities.h"  // au::str()

#include "au/CommandLine.h"     // au::CommandLine

#define PROGRESSIVE_NUMBER 20000

static const char *manShortDescription =
"word_generator - a simple tool to generate a random sequence of words. Useful in demos on word counting and topic trending.";

static const char *manSynopsis =
  "   [-r] [-t secs] [-l len] num_words\n"
  "       [-ramdon] flag to generate randomized sequence of words\n"
  "       [-repeat secs] time_to_repeat in seconds with a new wave of words\n"
  "       [-l length] Number of letters of generated words ( default 9 ) \n"
  "       [-alphabet alphabet size] Number of differnt letters used to generate words ( default 10 ) \n"
  "       [-progresive] flag to generate sequences of numbers in incressing order ( hit demo )\n";

int word_length;
int alphabet_length;
bool rand_flag;
int max_num_lines;
bool progresive;
int max_rate;  // Max rate of words per second
PaArgument paArgs[] =
{
  { "-l",           &word_length,     "", PaInt,  PaOpt, 9,
    1,
    30,
    "Number of letters of generated words ( default 9 )"                           },
  { "-alphabet",    &alphabet_length, "", PaInt,  PaOpt, 10,
    1,
    30,
    "Number of differnt letters used to generate words ( default 10 )"             },
  { "-random",      &rand_flag,       "", PaBool, PaOpt,
    false,
    false, true,
    "Flag to generate completelly randomized sequence of words"                    },
  { "-progressive", &progresive,      "", PaBool, PaOpt,
    false,
    false, true,
    "Flag to generate sequences of numbers in incressing order"                    },
  { "-rate",        &max_rate,        "", PaInt,  PaOpt, 0,
    0,
    10000000000, "Max rate in words / second"                 },
  { " ",            &max_num_lines,   "", PaInt,  PaOpt, 0,
    0,
    1000000000,
    "Number of words to be generated"                                              },
  PA_END_OF_ARGS
};

int logFd = -1;

char word[100];                  // Place for this word
int progressive_word_slots[100];  // Indexes to generate progressive words

au::Cronometer cronometer;

// Get a new random  word
void getNewWord() {
  if (progresive) {
    for (int i = 0; i < word_length; i++) {
      word[i] = 48 + progressive_word_slots[i];
    }

    // Increase counter...
    progressive_word_slots[word_length - 1]++;

    int pos = word_length - 1;
    while ((pos >= 0) && (progressive_word_slots[pos] >= alphabet_length)) {
      progressive_word_slots[pos] = 0;
      if (pos > 0) {
        progressive_word_slots[pos - 1]++;
      }
      pos--;
    }

    return;
  }

  for (int i = 0; i < word_length; i++) {
    word[i] = 48 + rand() % alphabet_length;
  }
}

class BufferToScreen {
  char *buffer;
  size_t max_size;
  size_t size;

public:

  BufferToScreen(size_t _max_size) {
    max_size = _max_size;
    buffer = (char *)malloc(max_size);
    size = 0;
  }

  void append(char *data, int len) {
    if ((size + len) > max_size) {
      flush();
    }
    memcpy(buffer + size, data, len);
    size += len;
  }

  void flush() {
    size_t w = write(1, buffer, size);

    if (w != size) {
      LM_X(1, ("Problem writing %lu bytes to the screen", size));
    }
    size = 0;
  }
};

int main(int argC, const char *argV[]) {
  paConfig("usage and exit on any warning", (void *)true);

  paConfig("log to screen", (void *)true);
  paConfig("log to file", (void *)false);
  paConfig("screen line format", (void *)"TYPE:EXEC: TEXT");
  paConfig("man shortdescription", (void *)manShortDescription);
  paConfig("man synopsis", (void *)manSynopsis);
  paConfig("log to stderr", (void *)true);

  // Parse input arguments
  paParse(paArgs, argC, (char **)argV, 1, false);
  logFd = lmFirstDiskFileDescriptor();

  // Init progressive
  if (progresive) {
    for (int i = 0; i < word_length; i++) {
      progressive_word_slots[i] = 0;
    }  // End of line for all the words...
  }
  word[word_length] = '\n';
  word[word_length + 1] = '\0';

  size_t num_lines = 0;
  size_t total_size = 0;

  // Init random numbers if random specified
  if (rand_flag) {
    srand(time(NULL));
  } else {
    srand(0);  // Time to show a message on screen in verbose mode
  }
  size_t last_message_time = 0;

  // Buffer to flsh data to screen in batches
  BufferToScreen buffer_to_screen(10000);

  double lines_per_second = 0;

  // Generate continuously...
  while (true) {
    // Check the limit of generated words
    if (max_num_lines > 0) {
      if (num_lines >= (size_t)max_num_lines) {
        break;  // Get new word
      }
    }
    getNewWord();

    // Length of this word
    int word_len = strlen(word);

    // Append to the screen
    buffer_to_screen.append(word, word_len);

    // Counter of bytes and words
    total_size += word_len;
    num_lines++;

    // This avoid exesive calls to timeout
    if (lines_per_second > 100000) {
      size_t num_continue = lines_per_second / 100;
      if ((num_lines % num_continue) != 0) {
        continue;
      }
    }

    // Flush accumulated buffer so far
    buffer_to_screen.flush();

    // Get the total number of seconds running...
    size_t total_seconds = cronometer.seconds();

    // Compute the number of lines per second, so far...
    if (total_seconds > 0) {
      lines_per_second = (double)num_lines / (double)total_seconds;
    }
    if ((total_seconds - last_message_time) > 5) {
      last_message_time = total_seconds;
      LM_V(("Generated %s lines ( %s bytes ) in %s. Rate: %s / %s",
            au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
            au::str((double)num_lines / (double)total_seconds,
                    "Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str()));
    }

    if (total_seconds > 0) {
      if (max_num_lines > 100) {
        if ((num_lines % (max_num_lines / 100)) == 0) {
          LM_V(("Generated %s - %s lines ( %s bytes ) in %s. Rate: %s / %s",
                au::str_percentage(num_lines, max_num_lines).c_str(),
                au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
                au::str((double)num_lines / (double)total_seconds,
                        "Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str()));   // Sleep if necessary
        }
      }
    }
    if (max_rate > 0) {
      size_t theoretical_seconds = num_lines / max_rate;

      if (total_seconds < theoretical_seconds) {
        sleep(theoretical_seconds - total_seconds);
      }
    }
  }

  buffer_to_screen.flush();

  size_t total_seconds = cronometer.seconds();
  LM_V(("Generated %s lines ( %s bytes ) in %s. Rate: %s / %s",
        au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
        au::str((double)num_lines / (double)total_seconds,
                "Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str()));
}

<|endoftext|>