<commit_before>/*
 *  Copyright 2008-2013 NVIDIA Corporation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <thrust/detail/config.h>
#include <thrust/merge.h>
#include <thrust/detail/seq.h>
#include <thrust/system/cuda/detail/merge.h>
#include <thrust/system/cuda/detail/bulk.h>
#include <thrust/detail/temporary_array.h>
#include <thrust/tabulate.h>
#include <thrust/iterator/detail/join_iterator.h>
#include <thrust/detail/minmax.h>
#include <thrust/system/cuda/detail/execute_on_stream.h>

namespace thrust
{
namespace system
{
namespace cuda
{
namespace detail
{
namespace merge_detail
{

template<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size,typename RandomAccessIterator2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>
__device__
RandomAccessIterator4
  staged_merge(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &exec,
               RandomAccessIterator1 first1, Size n1,
               RandomAccessIterator2 first2, Size n2,
               RandomAccessIterator3 stage,
               RandomAccessIterator4 result,
               Compare comp)
{
  // copy into the stage
  bulk_::copy_n(bulk_::bound<groupsize * grainsize>(exec),
                thrust::detail::make_join_iterator(first1, n1, first2),
                n1 + n2,
                stage);

  // inplace merge in the stage
  bulk_::inplace_merge(bulk_::bound<groupsize * grainsize>(exec),
                       stage, stage + n1, stage + n1 + n2,
                       comp);

  // copy to the result
  // XXX this might be slightly faster with a bounded copy_n
  return bulk_::copy_n(exec, stage, n1 + n2, result);
} // end staged_merge()

struct merge_kernel
{
  template<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size, typename RandomAccessIterator2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>
  __device__
  void operator()(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &g,
                  RandomAccessIterator1 first1, Size n1,
                  RandomAccessIterator2 first2, Size n2,
                  RandomAccessIterator3 merge_paths_first,
                  RandomAccessIterator4 result,
                  Compare comp)
  {
    typedef int size_type;

    size_type elements_per_group = g.size() * g.this_exec.grainsize();

    // determine the ranges to merge
    size_type mp0  = merge_paths_first[g.index()];
    size_type mp1  = merge_paths_first[g.index()+1];
    size_type diag = elements_per_group * g.index();

    size_type local_size1 = mp1 - mp0;
    size_type local_size2 = thrust::min<size_type>(n1 + n2, diag + elements_per_group) - mp1 - diag + mp0;

    first1 += mp0;
    first2 += diag - mp0;
    result += elements_per_group * g.index();

    // XXX this assumes that RandomAccessIterator2's value_type converts to RandomAccessIterator1's value_type
    typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;

#if __CUDA_ARCH__ >= 200
    // merge through a stage
    value_type *stage = reinterpret_cast<value_type*>(bulk_::malloc(g, elements_per_group * sizeof(value_type)));

    if(bulk_::is_on_chip(stage))
    {
      staged_merge(g,
                   first1, local_size1,
                   first2, local_size2,
                   bulk_::on_chip_cast(stage),
                   result,
                   comp);
    } // end if
    else
    {
      staged_merge(g,
                   first1, local_size1,
                   first2, local_size2,
                   stage,
                   result,
                   comp);
    } // end else

    bulk_::free(g, stage);
#else
    __shared__ bulk_::uninitialized_array<value_type, groupsize * grainsize> stage;
    staged_merge(g, first1, local_size1, first2, local_size2, stage.data(), result, comp);
#endif
  } // end operator()
}; // end merge_kernel

template<typename Size, typename RandomAccessIterator1,typename RandomAccessIterator2, typename Compare>
struct locate_merge_path
{
  Size partition_size;
  RandomAccessIterator1 first1, last1;
  RandomAccessIterator2 first2, last2;
  Compare comp;

  __host__ __device__
  locate_merge_path(Size partition_size, RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, RandomAccessIterator2 last2, Compare comp)
    : partition_size(partition_size),
      first1(first1), last1(last1),
      first2(first2), last2(last2),
      comp(comp)
  {}

  template<typename Index>
  __device__
  Size operator()(Index i)
  {
    Size n1 = last1 - first1;
    Size n2 = last2 - first2;
    Size diag = thrust::min<Size>(partition_size * i, n1 + n2);
    return bulk_::merge_path(first1, n1, first2, n2, diag, comp);
  }
};

template<typename DerivedPolicy,
         typename RandomAccessIterator1,
         typename RandomAccessIterator2,
	 typename RandomAccessIterator3,
         typename Compare>
__host__ __device__
RandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,
                            RandomAccessIterator1 first1,
                            RandomAccessIterator1 last1,
                            RandomAccessIterator2 first2,
                            RandomAccessIterator2 last2,
                            RandomAccessIterator3 result,
                            Compare comp)
{
  typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;
  typedef typename thrust::iterator_difference<RandomAccessIterator1>::type difference_type;
  typedef int size_type;

  // determined through empirical testing on K20c
  const size_type groupsize = (sizeof(value_type) == sizeof(int)) ? 256 : 256 + 32;
  const size_type grainsize = (sizeof(value_type) == sizeof(int)) ? 9   : 5;

  const size_type tile_size = groupsize * grainsize;

  difference_type n = (last1 - first1) + (last2 - first2);
  difference_type num_groups = (n + tile_size - 1) / tile_size;

  thrust::detail::temporary_array<size_type,DerivedPolicy> merge_paths(exec, num_groups + 1);

  thrust::tabulate(exec, merge_paths.begin(), merge_paths.end(), merge_detail::locate_merge_path<size_type,RandomAccessIterator1,RandomAccessIterator2,Compare>(tile_size,first1,last1,first2,last2,comp));

  // merge partitions
  size_type heap_size = tile_size * sizeof(value_type);
  bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> g(heap_size);
  bulk_::async(bulk_::par(stream(thrust::detail::derived_cast(exec)), g, num_groups), merge_detail::merge_kernel(), bulk_::root.this_exec, first1, last1 - first1, first2, last2 - first2, merge_paths.begin(), result, comp);

  return result + n;
} // end merge()

} // end merge_detail

template<typename DerivedPolicy,
         typename RandomAccessIterator1,
         typename RandomAccessIterator2,
	 typename RandomAccessIterator3,
         typename Compare>
__host__ __device__
RandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,
                            RandomAccessIterator1 first1,
                            RandomAccessIterator1 last1,
                            RandomAccessIterator2 first2,
                            RandomAccessIterator2 last2,
                            RandomAccessIterator3 result,
                            Compare comp)
{
  // we're attempting to launch a kernel, assert we're compiling with nvcc
  // ========================================================================
  // X Note to the user: If you've found this line due to a compiler error, X
  // X you need to compile your code using nvcc, rather than g++ or cl.exe  X
  // ========================================================================
  THRUST_STATIC_ASSERT( (thrust::detail::depend_on_instantiation<RandomAccessIterator1, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );

  struct workaround
  {
    __host__ __device__
    static RandomAccessIterator3 parallel_path(execution_policy<DerivedPolicy> &exec,
                                               RandomAccessIterator1 first1,
                                               RandomAccessIterator1 last1,
                                               RandomAccessIterator2 first2,
                                               RandomAccessIterator2 last2,
                                               RandomAccessIterator3 result,
                                               Compare comp)
    {
      return thrust::system::cuda::detail::merge_detail::merge(exec, first1, last1, first2, last2, result, comp);
    }

    __host__ __device__
    static RandomAccessIterator3 sequential_path(execution_policy<DerivedPolicy> &,
                                                 RandomAccessIterator1 first1,
                                                 RandomAccessIterator1 last1,
                                                 RandomAccessIterator2 first2,
                                                 RandomAccessIterator2 last2,
                                                 RandomAccessIterator3 result,
                                                 Compare comp)
    {
      return thrust::merge(thrust::seq, first1, last1, first2, last2, result, comp);
    }
  };

#if __BULK_HAS_CUDART__
  return workaround::parallel_path(exec, first1, last1, first2, last2, result, comp);
#else
  return workaround::sequential_path(exec, first1, last1, first2, last2, result, comp);
#endif
} // end merge()

} // end namespace detail
} // end namespace cuda
} // end namespace system
} // end namespace thrust

<commit_msg>Generalized merge_kernel::operator() to use two difference_type size parameters<commit_after>/*
 *  Copyright 2008-2013 NVIDIA Corporation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <thrust/detail/config.h>
#include <thrust/merge.h>
#include <thrust/detail/seq.h>
#include <thrust/system/cuda/detail/merge.h>
#include <thrust/system/cuda/detail/bulk.h>
#include <thrust/detail/temporary_array.h>
#include <thrust/tabulate.h>
#include <thrust/iterator/detail/join_iterator.h>
#include <thrust/detail/minmax.h>
#include <thrust/system/cuda/detail/execute_on_stream.h>

namespace thrust
{
namespace system
{
namespace cuda
{
namespace detail
{
namespace merge_detail
{

template<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size,typename RandomAccessIterator2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>
__device__
RandomAccessIterator4
  staged_merge(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &exec,
               RandomAccessIterator1 first1, Size n1,
               RandomAccessIterator2 first2, Size n2,
               RandomAccessIterator3 stage,
               RandomAccessIterator4 result,
               Compare comp)
{
  // copy into the stage
  bulk_::copy_n(bulk_::bound<groupsize * grainsize>(exec),
                thrust::detail::make_join_iterator(first1, n1, first2),
                n1 + n2,
                stage);

  // inplace merge in the stage
  bulk_::inplace_merge(bulk_::bound<groupsize * grainsize>(exec),
                       stage, stage + n1, stage + n1 + n2,
                       comp);

  // copy to the result
  // XXX this might be slightly faster with a bounded copy_n
  return bulk_::copy_n(exec, stage, n1 + n2, result);
} // end staged_merge()

struct merge_kernel
{
  template<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size1, typename RandomAccessIterator2, typename Size2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>
  __device__
  void operator()(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &g,
                  RandomAccessIterator1 first1, Size1 n1,
                  RandomAccessIterator2 first2, Size2 n2,
                  RandomAccessIterator3 merge_paths_first,
                  RandomAccessIterator4 result,
                  Compare comp)
  {
    typedef int size_type;

    size_type elements_per_group = g.size() * g.this_exec.grainsize();

    // determine the ranges to merge
    size_type mp0  = merge_paths_first[g.index()];
    size_type mp1  = merge_paths_first[g.index()+1];
    size_type diag = elements_per_group * g.index();

    size_type local_size1 = mp1 - mp0;
    size_type local_size2 = thrust::min<size_type>(n1 + n2, diag + elements_per_group) - mp1 - diag + mp0;

    first1 += mp0;
    first2 += diag - mp0;
    result += elements_per_group * g.index();

    // XXX this assumes that RandomAccessIterator2's value_type converts to RandomAccessIterator1's value_type
    typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;

#if __CUDA_ARCH__ >= 200
    // merge through a stage
    value_type *stage = reinterpret_cast<value_type*>(bulk_::malloc(g, elements_per_group * sizeof(value_type)));

    if(bulk_::is_on_chip(stage))
    {
      staged_merge(g,
                   first1, local_size1,
                   first2, local_size2,
                   bulk_::on_chip_cast(stage),
                   result,
                   comp);
    } // end if
    else
    {
      staged_merge(g,
                   first1, local_size1,
                   first2, local_size2,
                   stage,
                   result,
                   comp);
    } // end else

    bulk_::free(g, stage);
#else
    __shared__ bulk_::uninitialized_array<value_type, groupsize * grainsize> stage;
    staged_merge(g, first1, local_size1, first2, local_size2, stage.data(), result, comp);
#endif
  } // end operator()
}; // end merge_kernel

template<typename Size, typename RandomAccessIterator1,typename RandomAccessIterator2, typename Compare>
struct locate_merge_path
{
  Size partition_size;
  RandomAccessIterator1 first1, last1;
  RandomAccessIterator2 first2, last2;
  Compare comp;

  __host__ __device__
  locate_merge_path(Size partition_size, RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, RandomAccessIterator2 last2, Compare comp)
    : partition_size(partition_size),
      first1(first1), last1(last1),
      first2(first2), last2(last2),
      comp(comp)
  {}

  template<typename Index>
  __device__
  Size operator()(Index i)
  {
    Size n1 = last1 - first1;
    Size n2 = last2 - first2;
    Size diag = thrust::min<Size>(partition_size * i, n1 + n2);
    return bulk_::merge_path(first1, n1, first2, n2, diag, comp);
  }
};

template<typename DerivedPolicy,
         typename RandomAccessIterator1,
         typename RandomAccessIterator2,
	 typename RandomAccessIterator3,
         typename Compare>
__host__ __device__
RandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,
                            RandomAccessIterator1 first1,
                            RandomAccessIterator1 last1,
                            RandomAccessIterator2 first2,
                            RandomAccessIterator2 last2,
                            RandomAccessIterator3 result,
                            Compare comp)
{
  typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;
  typedef typename thrust::iterator_difference<RandomAccessIterator1>::type difference_type;
  typedef int size_type;

  // determined through empirical testing on K20c
  const size_type groupsize = (sizeof(value_type) == sizeof(int)) ? 256 : 256 + 32;
  const size_type grainsize = (sizeof(value_type) == sizeof(int)) ? 9   : 5;

  const size_type tile_size = groupsize * grainsize;

  difference_type n = (last1 - first1) + (last2 - first2);
  difference_type num_groups = (n + tile_size - 1) / tile_size;

  thrust::detail::temporary_array<size_type,DerivedPolicy> merge_paths(exec, num_groups + 1);

  thrust::tabulate(exec, merge_paths.begin(), merge_paths.end(), merge_detail::locate_merge_path<size_type,RandomAccessIterator1,RandomAccessIterator2,Compare>(tile_size,first1,last1,first2,last2,comp));

  // merge partitions
  size_type heap_size = tile_size * sizeof(value_type);
  bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> g(heap_size);
  bulk_::async(bulk_::par(stream(thrust::detail::derived_cast(exec)), g, num_groups), merge_detail::merge_kernel(), bulk_::root.this_exec, first1, last1 - first1, first2, last2 - first2, merge_paths.begin(), result, comp);

  return result + n;
} // end merge()

} // end merge_detail

template<typename DerivedPolicy,
         typename RandomAccessIterator1,
         typename RandomAccessIterator2,
	 typename RandomAccessIterator3,
         typename Compare>
__host__ __device__
RandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,
                            RandomAccessIterator1 first1,
                            RandomAccessIterator1 last1,
                            RandomAccessIterator2 first2,
                            RandomAccessIterator2 last2,
                            RandomAccessIterator3 result,
                            Compare comp)
{
  // we're attempting to launch a kernel, assert we're compiling with nvcc
  // ========================================================================
  // X Note to the user: If you've found this line due to a compiler error, X
  // X you need to compile your code using nvcc, rather than g++ or cl.exe  X
  // ========================================================================
  THRUST_STATIC_ASSERT( (thrust::detail::depend_on_instantiation<RandomAccessIterator1, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );

  struct workaround
  {
    __host__ __device__
    static RandomAccessIterator3 parallel_path(execution_policy<DerivedPolicy> &exec,
                                               RandomAccessIterator1 first1,
                                               RandomAccessIterator1 last1,
                                               RandomAccessIterator2 first2,
                                               RandomAccessIterator2 last2,
                                               RandomAccessIterator3 result,
                                               Compare comp)
    {
      return thrust::system::cuda::detail::merge_detail::merge(exec, first1, last1, first2, last2, result, comp);
    }

    __host__ __device__
    static RandomAccessIterator3 sequential_path(execution_policy<DerivedPolicy> &,
                                                 RandomAccessIterator1 first1,
                                                 RandomAccessIterator1 last1,
                                                 RandomAccessIterator2 first2,
                                                 RandomAccessIterator2 last2,
                                                 RandomAccessIterator3 result,
                                                 Compare comp)
    {
      return thrust::merge(thrust::seq, first1, last1, first2, last2, result, comp);
    }
  };

#if __BULK_HAS_CUDART__
  return workaround::parallel_path(exec, first1, last1, first2, last2, result, comp);
#else
  return workaround::sequential_path(exec, first1, last1, first2, last2, result, comp);
#endif
} // end merge()

} // end namespace detail
} // end namespace cuda
} // end namespace system
} // end namespace thrust

<|endoftext|>


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

#include <set>
#include <vector>

#include "base/command_line.h"
#include "base/ref_counted.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/webdata/autofill_entry.h"
#include "chrome/browser/webdata/web_database.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/browser/webdata/web_data_service_test_util.h"
#include "chrome/common/notification_observer_mock.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/live_sync/profile_sync_service_test_harness.h"
#include "chrome/test/live_sync/live_sync_test.h"
#include "chrome/test/thread_observer_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "webkit/glue/form_field.h"

using base::WaitableEvent;
using testing::_;

namespace {

// Define these << operators so we can use EXPECT_EQ with the
// AutofillKeys type.
template<class T1, class T2, class T3>
std::ostream& operator<<(std::ostream& os, const std::set<T1, T2, T3>& seq) {
  typedef typename std::set<T1, T2, T3>::const_iterator SetConstIterator;
  for (SetConstIterator i = seq.begin(); i != seq.end(); ++i) {
    os << *i << ", ";
  }
  return os;
}

std::ostream& operator<<(std::ostream& os, const AutofillKey& key) {
  return os << UTF16ToUTF8(key.name()) << ", " << UTF16ToUTF8(key.value());
}

class GetAllAutofillEntries
    : public base::RefCountedThreadSafe<GetAllAutofillEntries> {
 public:
  explicit GetAllAutofillEntries(WebDataService* web_data_service)
      : web_data_service_(web_data_service),
        done_event_(false, false) {}

  void Init() {
    DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
    ChromeThread::PostTask(
        ChromeThread::DB,
        FROM_HERE,
        NewRunnableMethod(this, &GetAllAutofillEntries::Run));
    done_event_.Wait();
  }

  const std::vector<AutofillEntry>& entries() const {
    return entries_;
  }

 private:
  friend class base::RefCountedThreadSafe<GetAllAutofillEntries>;

  void Run() {
    DCHECK(ChromeThread::CurrentlyOn(ChromeThread::DB));
    web_data_service_->GetDatabase()->GetAllAutofillEntries(&entries_);
    done_event_.Signal();
  }

  WebDataService* web_data_service_;
  base::WaitableEvent done_event_;
  std::vector<AutofillEntry> entries_;
};

ACTION_P(SignalEvent, event) {
  event->Signal();
}

class AutofillDBThreadObserverHelper : public DBThreadObserverHelper {
 protected:
  virtual void RegisterObservers() {
    registrar_.Add(&observer_,
                   NotificationType::AUTOFILL_ENTRIES_CHANGED,
                   NotificationService::AllSources());
    registrar_.Add(&observer_,
                   NotificationType::AUTOFILL_PROFILE_CHANGED,
                   NotificationService::AllSources());
  }
};

}  // namespace;

class TwoClientLiveAutofillSyncTest : public LiveSyncTest {
 public:
  typedef std::set<AutofillKey> AutofillKeys;
  TwoClientLiveAutofillSyncTest()
      : name1_(ASCIIToUTF16("name1")),
        name2_(ASCIIToUTF16("name2")),
        value1_(ASCIIToUTF16("value1")),
        value2_(ASCIIToUTF16("value2")),
        done_event1_(false, false),
        done_event2_(false, false) {
    // This makes sure browser is visible and active while running test.
    InProcessBrowserTest::set_show_window(true);
    // Set the initial timeout value to 5 min.
    InProcessBrowserTest::SetInitialTimeoutInMS(300000);
  }
  ~TwoClientLiveAutofillSyncTest() {}

 protected:
  void SetupHarness() {
    client1_.reset(new ProfileSyncServiceTestHarness(
        browser()->profile(), username_, password_));
    profile2_.reset(MakeProfile(FILE_PATH_LITERAL("client2")));
    client2_.reset(new ProfileSyncServiceTestHarness(
        profile2_.get(), username_, password_));
    wds1_ = browser()->profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);
    wds2_ = profile2_->GetWebDataService(Profile::EXPLICIT_ACCESS);
  }

  void SetupSync() {
    EXPECT_TRUE(client1_->SetupSync());
    EXPECT_TRUE(client1_->AwaitSyncCycleCompletion("Initial setup 1"));
    EXPECT_TRUE(client2_->SetupSync());
    EXPECT_TRUE(client2_->AwaitSyncCycleCompletion("Initial setup 2"));
  }

  void Cleanup() {
    client2_.reset();
    profile2_.reset();
  }

  void AddToWds(WebDataService* wds, const AutofillKeys& keys) {
    std::vector<webkit_glue::FormField> form_fields;
    for (AutofillKeys::const_iterator i = keys.begin(); i != keys.end(); ++i) {
      form_fields.push_back(
          webkit_glue::FormField(string16(),
                                 (*i).name(),
                                 (*i).value(),
                                 string16()));
    }

    WaitableEvent done_event(false, false);
    scoped_refptr<AutofillDBThreadObserverHelper> observer_helper(
        new AutofillDBThreadObserverHelper());
    observer_helper->Init();

    EXPECT_CALL(*observer_helper->observer(), Observe(_, _, _)).
        WillOnce(SignalEvent(&done_event));
    wds->AddFormFields(form_fields);
    done_event.Wait();
  }

  void GetAllAutofillKeys(WebDataService* wds, AutofillKeys* keys) {
    scoped_refptr<GetAllAutofillEntries> get_all_entries =
        new GetAllAutofillEntries(wds);
    get_all_entries->Init();
    const std::vector<AutofillEntry>& entries = get_all_entries->entries();

    for (size_t i = 0; i < entries.size(); ++i) {
      keys->insert(entries[i].key());
    }
  }

  ProfileSyncServiceTestHarness* client1() { return client1_.get(); }
  ProfileSyncServiceTestHarness* client2() { return client2_.get(); }

  PrefService* prefs1() { return browser()->profile()->GetPrefs(); }
  PrefService* prefs2() { return profile2_->GetPrefs(); }

  string16 name1_;
  string16 name2_;
  string16 value1_;
  string16 value2_;
  base::WaitableEvent done_event1_;
  base::WaitableEvent done_event2_;

  scoped_ptr<ProfileSyncServiceTestHarness> client1_;
  scoped_ptr<ProfileSyncServiceTestHarness> client2_;
  scoped_ptr<Profile> profile2_;
  WebDataService* wds1_;
  WebDataService* wds2_;

  DISALLOW_COPY_AND_ASSIGN(TwoClientLiveAutofillSyncTest);
};

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Client1HasData) {
  SetupHarness();

  AutofillKeys keys;
  keys.insert(AutofillKey("name1", "value1"));
  keys.insert(AutofillKey("name1", "value2"));
  keys.insert(AutofillKey("name2", "value3"));
  keys.insert(AutofillKey("Sigur R\u00F3s", "\u00C1g\u00E6tis byrjun"));
  AddToWds(wds1_, keys);

  SetupSync();

  AutofillKeys wd2_keys;
  GetAllAutofillKeys(wds2_, &wd2_keys);
  EXPECT_EQ(keys, wd2_keys);

  Cleanup();
}

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, BothHaveData) {
  SetupHarness();

  AutofillKeys keys1;
  keys1.insert(AutofillKey("name1", "value1"));
  keys1.insert(AutofillKey("name1", "value2"));
  keys1.insert(AutofillKey("name2", "value3"));
  AddToWds(wds1_, keys1);

  AutofillKeys keys2;
  keys2.insert(AutofillKey("name1", "value2"));
  keys2.insert(AutofillKey("name2", "value3"));
  keys2.insert(AutofillKey("name3", "value4"));
  keys2.insert(AutofillKey("name4", "value4"));
  AddToWds(wds2_, keys2);

  SetupSync();
  // Wait for client1 to get the new keys from client2.
  EXPECT_TRUE(client1()->AwaitSyncCycleCompletion("sync cycle"));

  AutofillKeys expected_keys;
  expected_keys.insert(AutofillKey("name1", "value1"));
  expected_keys.insert(AutofillKey("name1", "value2"));
  expected_keys.insert(AutofillKey("name2", "value3"));
  expected_keys.insert(AutofillKey("name3", "value4"));
  expected_keys.insert(AutofillKey("name4", "value4"));

  AutofillKeys wd1_keys;
  GetAllAutofillKeys(wds1_, &wd1_keys);
  EXPECT_EQ(expected_keys, wd1_keys);

  AutofillKeys wd2_keys;
  GetAllAutofillKeys(wds2_, &wd2_keys);
  EXPECT_EQ(expected_keys, wd2_keys);

  Cleanup();
}

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Steady) {
  SetupHarness();
  SetupSync();

  AutofillKeys add_one_key;
  add_one_key.insert(AutofillKey("name1", "value1"));
  AddToWds(wds1_, add_one_key);

  AutofillKeys expected_keys;
  expected_keys.insert(AutofillKey("name1", "value1"));

  EXPECT_TRUE(client1()->AwaitMutualSyncCycleCompletion(client2()));

  AutofillKeys keys;
  GetAllAutofillKeys(wds1_, &keys);
  EXPECT_EQ(expected_keys, keys);
  keys.clear();
  GetAllAutofillKeys(wds2_, &keys);
  EXPECT_EQ(expected_keys, keys);

  Cleanup();
}
<commit_msg>Embed unicode literals the correct way<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <set>
#include <vector>

#include "base/command_line.h"
#include "base/ref_counted.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/waitable_event.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/webdata/autofill_entry.h"
#include "chrome/browser/webdata/web_database.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/browser/webdata/web_data_service_test_util.h"
#include "chrome/common/notification_observer_mock.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/live_sync/profile_sync_service_test_harness.h"
#include "chrome/test/live_sync/live_sync_test.h"
#include "chrome/test/thread_observer_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "webkit/glue/form_field.h"

using base::WaitableEvent;
using testing::_;

namespace {

// Define these << operators so we can use EXPECT_EQ with the
// AutofillKeys type.
template<class T1, class T2, class T3>
std::ostream& operator<<(std::ostream& os, const std::set<T1, T2, T3>& seq) {
  typedef typename std::set<T1, T2, T3>::const_iterator SetConstIterator;
  for (SetConstIterator i = seq.begin(); i != seq.end(); ++i) {
    os << *i << ", ";
  }
  return os;
}

std::ostream& operator<<(std::ostream& os, const AutofillKey& key) {
  return os << UTF16ToUTF8(key.name()) << ", " << UTF16ToUTF8(key.value());
}

class GetAllAutofillEntries
    : public base::RefCountedThreadSafe<GetAllAutofillEntries> {
 public:
  explicit GetAllAutofillEntries(WebDataService* web_data_service)
      : web_data_service_(web_data_service),
        done_event_(false, false) {}

  void Init() {
    DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
    ChromeThread::PostTask(
        ChromeThread::DB,
        FROM_HERE,
        NewRunnableMethod(this, &GetAllAutofillEntries::Run));
    done_event_.Wait();
  }

  const std::vector<AutofillEntry>& entries() const {
    return entries_;
  }

 private:
  friend class base::RefCountedThreadSafe<GetAllAutofillEntries>;

  void Run() {
    DCHECK(ChromeThread::CurrentlyOn(ChromeThread::DB));
    web_data_service_->GetDatabase()->GetAllAutofillEntries(&entries_);
    done_event_.Signal();
  }

  WebDataService* web_data_service_;
  base::WaitableEvent done_event_;
  std::vector<AutofillEntry> entries_;
};

ACTION_P(SignalEvent, event) {
  event->Signal();
}

class AutofillDBThreadObserverHelper : public DBThreadObserverHelper {
 protected:
  virtual void RegisterObservers() {
    registrar_.Add(&observer_,
                   NotificationType::AUTOFILL_ENTRIES_CHANGED,
                   NotificationService::AllSources());
    registrar_.Add(&observer_,
                   NotificationType::AUTOFILL_PROFILE_CHANGED,
                   NotificationService::AllSources());
  }
};

}  // namespace;

class TwoClientLiveAutofillSyncTest : public LiveSyncTest {
 public:
  typedef std::set<AutofillKey> AutofillKeys;
  TwoClientLiveAutofillSyncTest()
      : name1_(ASCIIToUTF16("name1")),
        name2_(ASCIIToUTF16("name2")),
        value1_(ASCIIToUTF16("value1")),
        value2_(ASCIIToUTF16("value2")),
        done_event1_(false, false),
        done_event2_(false, false) {
    // This makes sure browser is visible and active while running test.
    InProcessBrowserTest::set_show_window(true);
    // Set the initial timeout value to 5 min.
    InProcessBrowserTest::SetInitialTimeoutInMS(300000);
  }
  ~TwoClientLiveAutofillSyncTest() {}

 protected:
  void SetupHarness() {
    client1_.reset(new ProfileSyncServiceTestHarness(
        browser()->profile(), username_, password_));
    profile2_.reset(MakeProfile(FILE_PATH_LITERAL("client2")));
    client2_.reset(new ProfileSyncServiceTestHarness(
        profile2_.get(), username_, password_));
    wds1_ = browser()->profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);
    wds2_ = profile2_->GetWebDataService(Profile::EXPLICIT_ACCESS);
  }

  void SetupSync() {
    EXPECT_TRUE(client1_->SetupSync());
    EXPECT_TRUE(client1_->AwaitSyncCycleCompletion("Initial setup 1"));
    EXPECT_TRUE(client2_->SetupSync());
    EXPECT_TRUE(client2_->AwaitSyncCycleCompletion("Initial setup 2"));
  }

  void Cleanup() {
    client2_.reset();
    profile2_.reset();
  }

  void AddToWds(WebDataService* wds, const AutofillKeys& keys) {
    std::vector<webkit_glue::FormField> form_fields;
    for (AutofillKeys::const_iterator i = keys.begin(); i != keys.end(); ++i) {
      form_fields.push_back(
          webkit_glue::FormField(string16(),
                                 (*i).name(),
                                 (*i).value(),
                                 string16()));
    }

    WaitableEvent done_event(false, false);
    scoped_refptr<AutofillDBThreadObserverHelper> observer_helper(
        new AutofillDBThreadObserverHelper());
    observer_helper->Init();

    EXPECT_CALL(*observer_helper->observer(), Observe(_, _, _)).
        WillOnce(SignalEvent(&done_event));
    wds->AddFormFields(form_fields);
    done_event.Wait();
  }

  void GetAllAutofillKeys(WebDataService* wds, AutofillKeys* keys) {
    scoped_refptr<GetAllAutofillEntries> get_all_entries =
        new GetAllAutofillEntries(wds);
    get_all_entries->Init();
    const std::vector<AutofillEntry>& entries = get_all_entries->entries();

    for (size_t i = 0; i < entries.size(); ++i) {
      keys->insert(entries[i].key());
    }
  }

  ProfileSyncServiceTestHarness* client1() { return client1_.get(); }
  ProfileSyncServiceTestHarness* client2() { return client2_.get(); }

  PrefService* prefs1() { return browser()->profile()->GetPrefs(); }
  PrefService* prefs2() { return profile2_->GetPrefs(); }

  string16 name1_;
  string16 name2_;
  string16 value1_;
  string16 value2_;
  base::WaitableEvent done_event1_;
  base::WaitableEvent done_event2_;

  scoped_ptr<ProfileSyncServiceTestHarness> client1_;
  scoped_ptr<ProfileSyncServiceTestHarness> client2_;
  scoped_ptr<Profile> profile2_;
  WebDataService* wds1_;
  WebDataService* wds2_;

  DISALLOW_COPY_AND_ASSIGN(TwoClientLiveAutofillSyncTest);
};

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Client1HasData) {
  SetupHarness();

  AutofillKeys keys;
  keys.insert(AutofillKey("name1", "value1"));
  keys.insert(AutofillKey("name1", "value2"));
  keys.insert(AutofillKey("name2", "value3"));
  keys.insert(AutofillKey(WideToUTF16(L"Sigur R\u00F3s"),
                          WideToUTF16(L"\u00C1g\u00E6tis byrjun")));
  AddToWds(wds1_, keys);

  SetupSync();

  AutofillKeys wd2_keys;
  GetAllAutofillKeys(wds2_, &wd2_keys);
  EXPECT_EQ(keys, wd2_keys);

  Cleanup();
}

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, BothHaveData) {
  SetupHarness();

  AutofillKeys keys1;
  keys1.insert(AutofillKey("name1", "value1"));
  keys1.insert(AutofillKey("name1", "value2"));
  keys1.insert(AutofillKey("name2", "value3"));
  AddToWds(wds1_, keys1);

  AutofillKeys keys2;
  keys2.insert(AutofillKey("name1", "value2"));
  keys2.insert(AutofillKey("name2", "value3"));
  keys2.insert(AutofillKey("name3", "value4"));
  keys2.insert(AutofillKey("name4", "value4"));
  AddToWds(wds2_, keys2);

  SetupSync();
  // Wait for client1 to get the new keys from client2.
  EXPECT_TRUE(client1()->AwaitSyncCycleCompletion("sync cycle"));

  AutofillKeys expected_keys;
  expected_keys.insert(AutofillKey("name1", "value1"));
  expected_keys.insert(AutofillKey("name1", "value2"));
  expected_keys.insert(AutofillKey("name2", "value3"));
  expected_keys.insert(AutofillKey("name3", "value4"));
  expected_keys.insert(AutofillKey("name4", "value4"));

  AutofillKeys wd1_keys;
  GetAllAutofillKeys(wds1_, &wd1_keys);
  EXPECT_EQ(expected_keys, wd1_keys);

  AutofillKeys wd2_keys;
  GetAllAutofillKeys(wds2_, &wd2_keys);
  EXPECT_EQ(expected_keys, wd2_keys);

  Cleanup();
}

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Steady) {
  SetupHarness();
  SetupSync();

  AutofillKeys add_one_key;
  add_one_key.insert(AutofillKey("name1", "value1"));
  AddToWds(wds1_, add_one_key);

  AutofillKeys expected_keys;
  expected_keys.insert(AutofillKey("name1", "value1"));

  EXPECT_TRUE(client1()->AwaitMutualSyncCycleCompletion(client2()));

  AutofillKeys keys;
  GetAllAutofillKeys(wds1_, &keys);
  EXPECT_EQ(expected_keys, keys);
  keys.clear();
  GetAllAutofillKeys(wds2_, &keys);
  EXPECT_EQ(expected_keys, keys);

  Cleanup();
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkRegularStepGradientDescentOptimizerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <itkRegularStepGradientDescentOptimizer.h>
#include <vnl/vnl_math.h>

/**
 *  The objectif function is the quadratic form:
 *
 *  1/2 x^T A x - b^T x
 *
 *  Where A is a matrix and b is a vector
 *  The system in this example is:
 *
 *     | 3  2 ||x|   | 2|   |0|
 *     | 2  6 ||y| + |-8| = |0|
 *
 *
 *   the solution is the vector | 2 -2 |
 *
 */
class RSGCostFunction : public itk::SingleValuedCostFunction
{
public:

  typedef RSGCostFunction                     Self;
  typedef itk::SingleValuedCostFunction      Superclass;
  typedef itk::SmartPointer<Self>            Pointer;
  typedef itk::SmartPointer<const Self>      ConstPointer;
  itkNewMacro( Self );

  enum { SpaceDimension=2 };

  typedef Superclass::ParametersType      ParametersType;
  typedef Superclass::DerivativeType      DerivativeType;
  typedef Superclass::MeasureType         MeasureType ;

  RSGCostFunction()
  {
  }

  MeasureType  GetValue( const ParametersType & parameters ) const
  {

    double x = parameters[0];
    double y = parameters[1];

    std::cout << "GetValue( " ;
    std::cout << x << " ";
    std::cout << y << ") = ";

    MeasureType measure = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;

    std::cout << measure << std::endl;
    return measure;

  }

  void GetDerivative( const ParametersType & parameters,
                            DerivativeType  & derivative ) const
  {

    double x = parameters[0];
    double y = parameters[1];

    std::cout << "GetDerivative( " ;
    std::cout << x << " ";
    std::cout << y << ") = ";

    derivative = DerivativeType( SpaceDimension );
    derivative[0] = 3 * x + 2 * y -2;
    derivative[1] = 2 * x + 6 * y +8;

  }

  unsigned int GetNumberOfParameters(void) const
    {
    return SpaceDimension;
    }

private:

};

int itkRegularStepGradientDescentOptimizerTest(int, char* [] )
{
  std::cout << "RegularStepGradientDescentOptimizer Test ";
  std::cout << std::endl << std::endl;

  typedef  itk::RegularStepGradientDescentOptimizer  OptimizerType;

  typedef  OptimizerType::ScalesType            ScalesType;

  // Declaration of a itkOptimizer
  OptimizerType::Pointer  itkOptimizer = OptimizerType::New();

  // Declaration of the CostFunction
  RSGCostFunction::Pointer costFunction = RSGCostFunction::New();

  itkOptimizer->SetCostFunction( costFunction.GetPointer() );

  typedef RSGCostFunction::ParametersType    ParametersType;

  const unsigned int spaceDimension =
                      costFunction->GetNumberOfParameters();

  // We start not so far from  | 2 -2 |
  ParametersType  initialPosition( spaceDimension );
  initialPosition[0] =  100;
  initialPosition[1] = -100;

  ScalesType    parametersScale( spaceDimension );
  parametersScale[0] = 1.0;
  parametersScale[1] = 1.0;

  itkOptimizer->MinimizeOn();
  itkOptimizer->SetScales( parametersScale );
  itkOptimizer->SetGradientMagnitudeTolerance( 1e-6 );
  itkOptimizer->SetMaximumStepLength( 30.0 );
  itkOptimizer->SetMinimumStepLength( 1e-6 );
  itkOptimizer->SetNumberOfIterations( 900 );

  itkOptimizer->SetInitialPosition( initialPosition );

  try
    {
    itkOptimizer->StartOptimization();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cout << "Exception thrown ! " << std::endl;
    std::cout << "An error ocurred during Optimization" << std::endl;
    std::cout << "Location    = " << e.GetLocation()    << std::endl;
    std::cout << "Description = " << e.GetDescription() << std::endl;
    return EXIT_FAILURE;
    }

  ParametersType finalPosition = itkOptimizer->GetCurrentPosition();
  std::cout << "Solution        = (";
  std::cout << finalPosition[0] << "," ;
  std::cout << finalPosition[1] << ")" << std::endl;

  //
  // check results to see if it is within range
  //
  bool pass = true;
  double trueParameters[2] = { 2, -2 };
  for( unsigned int j = 0; j < 2; j++ )
    {
    if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )
      {
      pass = false;
      }
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  // Run now with a different relaxation factor

  {
  itkOptimizer->SetInitialPosition( initialPosition );

  itkOptimizer->SetRelaxationFactor( 0.8 );
  try
    {
    itkOptimizer->StartOptimization();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cout << "Exception thrown ! " << std::endl;
    std::cout << "An error ocurred during Optimization" << std::endl;
    std::cout << "Location    = " << e.GetLocation()    << std::endl;
    std::cout << "Description = " << e.GetDescription() << std::endl;
    return EXIT_FAILURE;
    }

  finalPosition = itkOptimizer->GetCurrentPosition();
  std::cout << "Solution        = (";
  std::cout << finalPosition[0] << "," ;
  std::cout << finalPosition[1] << ")" << std::endl;

  //
  // check results to see if it is within range
  //
  pass = true;
  for( unsigned int j = 0; j < 2; j++ )
    {
    if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )
      {
      pass = false;
      }
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  }

  //
  // Verify that the optimizer doesn't run if the
  // number of iterations is set to zero.
  //
  {
  itkOptimizer->SetNumberOfIterations( 0 );
  itkOptimizer->SetInitialPosition( initialPosition );

  try
    {
    itkOptimizer->StartOptimization();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cout << excp << std::endl;
    return EXIT_FAILURE;
    }

  if( itkOptimizer->GetCurrentIteration() > 0 )
    {
    std::cerr << "The optimizer is running iterations despite of ";
    std::cerr << "having a maximum number of iterations set to zero" << std::endl;
    return EXIT_FAILURE;
    }
  }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;

}

<commit_msg>BUG: 4893. Verifying that an exception is thrown from StartOptimization()      when the GradientMagnitudeTolerance value has been set to a negative number.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkRegularStepGradientDescentOptimizerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <itkRegularStepGradientDescentOptimizer.h>
#include <vnl/vnl_math.h>

/**
 *  The objectif function is the quadratic form:
 *
 *  1/2 x^T A x - b^T x
 *
 *  Where A is a matrix and b is a vector
 *  The system in this example is:
 *
 *     | 3  2 ||x|   | 2|   |0|
 *     | 2  6 ||y| + |-8| = |0|
 *
 *
 *   the solution is the vector | 2 -2 |
 *
 */
class RSGCostFunction : public itk::SingleValuedCostFunction
{
public:

  typedef RSGCostFunction                     Self;
  typedef itk::SingleValuedCostFunction      Superclass;
  typedef itk::SmartPointer<Self>            Pointer;
  typedef itk::SmartPointer<const Self>      ConstPointer;
  itkNewMacro( Self );

  enum { SpaceDimension=2 };

  typedef Superclass::ParametersType      ParametersType;
  typedef Superclass::DerivativeType      DerivativeType;
  typedef Superclass::MeasureType         MeasureType ;

  RSGCostFunction()
  {
  }

  MeasureType  GetValue( const ParametersType & parameters ) const
  {

    double x = parameters[0];
    double y = parameters[1];

    std::cout << "GetValue( " ;
    std::cout << x << " ";
    std::cout << y << ") = ";

    MeasureType measure = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;

    std::cout << measure << std::endl;
    return measure;

  }

  void GetDerivative( const ParametersType & parameters,
                            DerivativeType  & derivative ) const
  {

    double x = parameters[0];
    double y = parameters[1];

    std::cout << "GetDerivative( " ;
    std::cout << x << " ";
    std::cout << y << ") = ";

    derivative = DerivativeType( SpaceDimension );
    derivative[0] = 3 * x + 2 * y -2;
    derivative[1] = 2 * x + 6 * y +8;

  }

  unsigned int GetNumberOfParameters(void) const
    {
    return SpaceDimension;
    }

private:

};

int itkRegularStepGradientDescentOptimizerTest(int, char* [] )
{
  std::cout << "RegularStepGradientDescentOptimizer Test ";
  std::cout << std::endl << std::endl;

  typedef  itk::RegularStepGradientDescentOptimizer  OptimizerType;

  typedef  OptimizerType::ScalesType            ScalesType;

  // Declaration of a itkOptimizer
  OptimizerType::Pointer  itkOptimizer = OptimizerType::New();

  // Declaration of the CostFunction
  RSGCostFunction::Pointer costFunction = RSGCostFunction::New();

  itkOptimizer->SetCostFunction( costFunction.GetPointer() );

  typedef RSGCostFunction::ParametersType    ParametersType;

  const unsigned int spaceDimension =
                      costFunction->GetNumberOfParameters();

  // We start not so far from  | 2 -2 |
  ParametersType  initialPosition( spaceDimension );
  initialPosition[0] =  100;
  initialPosition[1] = -100;

  ScalesType    parametersScale( spaceDimension );
  parametersScale[0] = 1.0;
  parametersScale[1] = 1.0;

  itkOptimizer->MinimizeOn();
  itkOptimizer->SetScales( parametersScale );
  itkOptimizer->SetGradientMagnitudeTolerance( 1e-6 );
  itkOptimizer->SetMaximumStepLength( 30.0 );
  itkOptimizer->SetMinimumStepLength( 1e-6 );
  itkOptimizer->SetNumberOfIterations( 900 );

  itkOptimizer->SetInitialPosition( initialPosition );

  try
    {
    itkOptimizer->StartOptimization();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cout << "Exception thrown ! " << std::endl;
    std::cout << "An error ocurred during Optimization" << std::endl;
    std::cout << "Location    = " << e.GetLocation()    << std::endl;
    std::cout << "Description = " << e.GetDescription() << std::endl;
    return EXIT_FAILURE;
    }

  ParametersType finalPosition = itkOptimizer->GetCurrentPosition();
  std::cout << "Solution        = (";
  std::cout << finalPosition[0] << "," ;
  std::cout << finalPosition[1] << ")" << std::endl;

  //
  // check results to see if it is within range
  //
  bool pass = true;
  double trueParameters[2] = { 2, -2 };
  for( unsigned int j = 0; j < 2; j++ )
    {
    if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )
      {
      pass = false;
      }
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  // Run now with a different relaxation factor

  {
  itkOptimizer->SetInitialPosition( initialPosition );

  itkOptimizer->SetRelaxationFactor( 0.8 );
  try
    {
    itkOptimizer->StartOptimization();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cout << "Exception thrown ! " << std::endl;
    std::cout << "An error ocurred during Optimization" << std::endl;
    std::cout << "Location    = " << e.GetLocation()    << std::endl;
    std::cout << "Description = " << e.GetDescription() << std::endl;
    return EXIT_FAILURE;
    }

  finalPosition = itkOptimizer->GetCurrentPosition();
  std::cout << "Solution        = (";
  std::cout << finalPosition[0] << "," ;
  std::cout << finalPosition[1] << ")" << std::endl;

  //
  // check results to see if it is within range
  //
  pass = true;
  for( unsigned int j = 0; j < 2; j++ )
    {
    if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )
      {
      pass = false;
      }
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  }

  //
  // Verify that the optimizer doesn't run if the
  // number of iterations is set to zero.
  //
  {
  itkOptimizer->SetNumberOfIterations( 0 );
  itkOptimizer->SetInitialPosition( initialPosition );

  try
    {
    itkOptimizer->StartOptimization();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cout << excp << std::endl;
    return EXIT_FAILURE;
    }

  if( itkOptimizer->GetCurrentIteration() > 0 )
    {
    std::cerr << "The optimizer is running iterations despite of ";
    std::cerr << "having a maximum number of iterations set to zero" << std::endl;
    return EXIT_FAILURE;
    }
  }

  //
  // Test the Exception if the GradientMagnitudeTolerance is set to a negative value
  //
  itkOptimizer->SetGradientMagnitudeTolerance( -1.0 );
  bool expectedExceptionReceived = false;
  try
    {
    itkOptimizer->StartOptimization();
    }
  catch( itk::ExceptionObject & excp )
    {
    expectedExceptionReceived = true;
    std::cout << "Expected Exception " << std::endl;
    std::cout << excp << std::endl;
    }

  if( !expectedExceptionReceived )
    {
    std::cerr << "Failure to produce an exception when";
    std::cerr << "the GradientMagnitudeTolerance is negative " << std::endl;
    std::cerr << "TEST FAILED !" << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "TEST PASSED !" << std::endl;
  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2014, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ----------------------------------------------------------------------
 */

/** @file
 * Implementation of Connections
 */

#include <iostream>
#include <nta/algorithms/Connections.hpp>

using namespace std;
using namespace nta;
using namespace nta::algorithms::connections;

Connections::Connections(CellIdx numCells) : cells_(numCells)
{
}

Segment Connections::createSegment(const Cell& cell)
{
  vector<SegmentData>& segments = cells_[cell.idx].segments;
  Segment segment = {segments.size(), cell};

  SegmentData segmentData;
  segments.push_back(segmentData);

  return segment;
}

Synapse Connections::createSynapse(const Segment& segment,
                                   const Cell& presynapticCell,
                                   Permanence permanence)
{
  const Cell& cell = segment.cell;

  vector<SynapseData>& synapses = cells_[cell.idx].segments[segment.idx].synapses;
  Synapse synapse = {synapses.size(), segment};

  SynapseData synapseData = {presynapticCell, permanence};
  synapses.push_back(synapseData);

  return synapse;
}

void Connections::updateSynapsePermanence(const Synapse& synapse,
                                          Permanence permanence)
{
  const Segment& segment = synapse.segment;
  const Cell& cell = segment.cell;

  cells_[cell.idx].segments[segment.idx].synapses[synapse.idx].permanence = permanence;
}

vector<Segment> Connections::getSegmentsForCell(const Cell& cell)
{
  vector<Segment> segments;
  Segment segment;

  for(SegmentIdx i = 0; i < cells_[cell.idx].segments.size(); i++) {
    segment.idx = i;
    segment.cell = cell;
    segments.push_back(segment);
  }

  return segments;
}

vector<Synapse> Connections::getSynapsesForSegment(const Segment& segment)
{
  const Cell& cell = segment.cell;
  vector<Synapse> synapses;
  Synapse synapse;

  for(SynapseIdx i = 0; i < cells_[cell.idx].segments[segment.idx].synapses.size(); i++) {
    synapse.idx = i;
    synapse.segment = segment;
    synapses.push_back(synapse);
  }

  return synapses;
}

SynapseData Connections::getDataForSynapse(const Synapse& synapse) const
{
  const Segment& segment = synapse.segment;
  const Cell& cell = segment.cell;

  return cells_[cell.idx].segments[segment.idx].synapses[synapse.idx];
}

bool Connections::getMostActiveSegmentForCells(const std::vector<Cell>& cells,
                                               const std::vector<Cell>& input,
                                               UInt synapseThreshold,
                                               Segment& segment) const
{
  return false;
}

Activity Connections::computeActivity(const std::vector<Cell>& input,
                                      Permanence permanenceThreshold,
                                      UInt synapseThreshold) const
{
  Activity activity;
  // vector<Synapse> synapses;
  // SynapseData synapseData;
  // Synapse synapse;

  // for (vector<Cell>::const_iterator c = input.begin(); c != input.end(); c++) {
  //   synapses = synapsesForPresynapticCell_[*c];

  //   for (vector<Synapse>::const_iterator s = synapses.begin(); s != synapses.end(); s++) {
  //     synapseData = getDataForSynapse(*s);

  //     if (synapseData.permanence >= permanenceThreshold) {
  //       activity.numActiveSynapsesForSegment[synapse.segment] += 1;
  //     }

  //     if (activity.numActiveSynapsesForSegment[synapse.segment]) {
  //       activity.numActiveSegmentsForCell[*c] += 1;
  //     }
  //   }
  // }

  return activity;
}
<commit_msg>Added sample code for getMostActiveSegmentForCells<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2014, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ----------------------------------------------------------------------
 */

/** @file
 * Implementation of Connections
 */

#include <iostream>
#include <nta/algorithms/Connections.hpp>

using namespace std;
using namespace nta;
using namespace nta::algorithms::connections;

Connections::Connections(CellIdx numCells) : cells_(numCells)
{
}

Segment Connections::createSegment(const Cell& cell)
{
  vector<SegmentData>& segments = cells_[cell.idx].segments;
  Segment segment = {segments.size(), cell};

  SegmentData segmentData;
  segments.push_back(segmentData);

  return segment;
}

Synapse Connections::createSynapse(const Segment& segment,
                                   const Cell& presynapticCell,
                                   Permanence permanence)
{
  const Cell& cell = segment.cell;

  vector<SynapseData>& synapses = cells_[cell.idx].segments[segment.idx].synapses;
  Synapse synapse = {synapses.size(), segment};

  SynapseData synapseData = {presynapticCell, permanence};
  synapses.push_back(synapseData);

  return synapse;
}

void Connections::updateSynapsePermanence(const Synapse& synapse,
                                          Permanence permanence)
{
  const Segment& segment = synapse.segment;
  const Cell& cell = segment.cell;

  cells_[cell.idx].segments[segment.idx].synapses[synapse.idx].permanence = permanence;
}

vector<Segment> Connections::getSegmentsForCell(const Cell& cell)
{
  vector<Segment> segments;
  Segment segment;

  for(SegmentIdx i = 0; i < cells_[cell.idx].segments.size(); i++) {
    segment.idx = i;
    segment.cell = cell;
    segments.push_back(segment);
  }

  return segments;
}

vector<Synapse> Connections::getSynapsesForSegment(const Segment& segment)
{
  const Cell& cell = segment.cell;
  vector<Synapse> synapses;
  Synapse synapse;

  for(SynapseIdx i = 0; i < cells_[cell.idx].segments[segment.idx].synapses.size(); i++) {
    synapse.idx = i;
    synapse.segment = segment;
    synapses.push_back(synapse);
  }

  return synapses;
}

SynapseData Connections::getDataForSynapse(const Synapse& synapse) const
{
  const Segment& segment = synapse.segment;
  const Cell& cell = segment.cell;

  return cells_[cell.idx].segments[segment.idx].synapses[synapse.idx];
}

bool Connections::getMostActiveSegmentForCells(const std::vector<Cell>& cells,
                                               const std::vector<Cell>& input,
                                               UInt synapseThreshold,
                                               Segment& segment) const
{
  // UInt numSynapses, maxSynapses = synapseThreshold;
  // vector<SegmentData> segments;
  // vector<SynapseData> synapses;
  bool found = false;

  // for (vector<Cell>::const_iterator c = cells.begin(); c != cells.end(); c++) {
  //   segments = cells_[c->idx].segments;

  //   for (vector<SegmentData>::const_iterator s = segments.begin(); s != segments.end(); s++) {
  //     synapses = s->synapses;
  //     numSynapses = 0;

  //     for (vector<SynapseData>::const_iterator syn = synapses.begin(); syn != synapses.end(); syn++) {
  //       if (find(input.begin(), input.end(), syn->presynapticCell) != input.end()) {  // TODO: Optimize this
  //         numSynapses++;
  //       }
  //     }

  //     if (numSynapses >= maxSynapses) {
  //       maxSynapses = numSynapses;
  //       segment.idx = s - segments.begin();
  //       segment.cell = *c;
  //       found = true;
  //     }
  //   }
  // }

  return found;
}

Activity Connections::computeActivity(const std::vector<Cell>& input,
                                      Permanence permanenceThreshold,
                                      UInt synapseThreshold) const
{
  Activity activity;
  // vector<Synapse> synapses;
  // SynapseData synapseData;
  // Synapse synapse;

  // for (vector<Cell>::const_iterator c = input.begin(); c != input.end(); c++) {
  //   synapses = synapsesForPresynapticCell_[*c];

  //   for (vector<Synapse>::const_iterator s = synapses.begin(); s != synapses.end(); s++) {
  //     synapseData = getDataForSynapse(*s);

  //     if (synapseData.permanence >= permanenceThreshold) {
  //       activity.numActiveSynapsesForSegment[synapse.segment] += 1;
  //     }

  //     if (activity.numActiveSynapsesForSegment[synapse.segment]) {
  //       activity.numActiveSegmentsForCell[*c] += 1;
  //     }
  //   }
  // }

  return activity;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * c7a/net/select-dispatcher.hpp
 *
 * Asynchronous callback wrapper around select()
 *
 * Part of Project c7a.
 *
 * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#ifndef C7A_NET_SELECT_DISPATCHER_HEADER
#define C7A_NET_SELECT_DISPATCHER_HEADER

#include <c7a/net/socket.hpp>
#include <c7a/net/select.hpp>

#include <deque>

namespace c7a {

//! \addtogroup netsock Low Level Socket API
//! \{

/**
 * SelectDispatcher is a higher level wrapper for select(). One can register
 * Socket objects for readability and writability checks, buffered reads and
 * writes with completion callbacks, and also timer functions.
 */
class SelectDispatcher : protected Select
{
    static const bool debug = false;

public:
    typedef std::function<bool (Socket&)> Callback;

    //! Register a buffered read callback and a default exception callback.
    void AddRead(Socket& s, const Callback& read_cb)
    {
        Select::SetRead(s.GetFileDescriptor());
        Select::SetException(s.GetFileDescriptor());
        watch_.emplace_back(s.GetFileDescriptor(), s,
                            read_cb, nullptr, ExceptionCallback);
    }

    //! Register a buffered write callback and a default exception callback.
    void AddWrite(Socket& s, const Callback& write_cb)
    {
        Select::SetWrite(s.GetFileDescriptor());
        Select::SetException(s.GetFileDescriptor());
        watch_.emplace_back(s.GetFileDescriptor(), s,
                            nullptr, write_cb, ExceptionCallback);
    }

    //! Register a buffered write callback and a default exception callback.
    void AddReadWrite(Socket& s,
                      const Callback& read_cb, const Callback& write_cb)
    {
        Select::SetRead(s.GetFileDescriptor());
        Select::SetWrite(s.GetFileDescriptor());
        Select::SetException(s.GetFileDescriptor());
        watch_.emplace_back(s.GetFileDescriptor(), s,
                            read_cb, write_cb, ExceptionCallback);
    }

    void Dispatch(double timeout)
    {
        // copy select fdset
        Select fdset = *this;

        if (debug)
        {
            std::ostringstream oss;
            for (Watch& w : watch_) {
                oss << w.fd << " ";
            }
            oss << "| ";
            for (int i = 0; i < Select::max_fd_ + 1; ++i) {
                if (Select::InRead(i))
                    oss << "r" << i << " ";
                if (Select::InWrite(i))
                    oss << "w" << i << " ";
                if (Select::InException(i))
                    oss << "e" << i << " ";
            }
            LOG << "Performing select() on " << oss.str();
        }

        int r = fdset.select_timeout(timeout);

        if (r < 0) {
            throw NetException("OpenConnections() select() failed!", errno);
        }
        if (r == 0) return;

        // save _current_ size, as it may change.
        size_t watch_size = watch_.size();

        for (size_t i = 0; i != watch_size; ++i)
        {
            Watch& w = watch_[i];

            if (w.fd < 0) continue;

            if (fdset.InRead(w.fd))
            {
                if (w.read_cb) {
                    // have to clear the read flag since the callback may add a
                    // new (other) callback for the same fd.
                    Select::ClearRead(w.fd);
                    Select::ClearException(w.fd);

                    if (!w.read_cb(w.socket)) {
                        // callback returned false: remove fd from set
                        w.fd = -1;
                    }
                    else {
                        Select::SetRead(w.fd);
                        Select::SetException(w.fd);
                    }
                }
                else {
                    LOG << "SelectDispatcher: got read event for fd "
                        << w.fd << " without a read handler.";

                    Select::ClearRead(w.fd);
                }
            }

            if (w.fd < 0) continue;

            if (fdset.InWrite(w.fd))
            {
                if (w.write_cb) {
                    // have to clear the read flag since the callback may add a
                    // new (other) callback for the same fd.
                    Select::ClearWrite(w.fd);
                    Select::ClearException(w.fd);

                    if (!w.write_cb(w.socket)) {
                        // callback returned false: remove fd from set
                        w.fd = -1;
                    }
                    else {
                        Select::SetWrite(w.fd);
                        Select::SetException(w.fd);
                    }
                }
                else {
                    LOG << "SelectDispatcher: got write event for fd "
                        << w.fd << " without a write handler.";

                    Select::ClearWrite(w.fd);
                }
            }

            if (w.fd < 0) continue;

            if (fdset.InException(w.fd))
            {
                if (w.except_cb) {
                    Select::ClearException(w.fd);

                    if (!w.except_cb(w.socket)) {
                        // callback returned false: remove fd from set
                        w.fd = -1;
                    }
                    else {
                        Select::SetException(w.fd);
                    }
                }
                else {
                    LOG << "SelectDispatcher: got exception event for fd "
                        << w.fd << " without an exception handler.";

                    Select::ClearException(w.fd);
                }
            }
        }
    }

private:
    //! struct to entries per watched file descriptor
    struct Watch
    {
        int      fd;
        Socket   socket;
        Callback read_cb, write_cb, except_cb;

        Watch(int _fd, Socket& _socket,
              const Callback& _read_cb, const Callback& _write_cb,
              const Callback& _except_cb)
            : fd(_fd),
              socket(_socket),
              read_cb(_read_cb),
              write_cb(_write_cb),
              except_cb(_except_cb)
        { }
    };

    //! handlers for all registered file descriptors, we have to keep them
    //! address local.
    std::deque<Watch> watch_;

    //! Default exception handler
    static bool ExceptionCallback(Socket& s)
    {
        // exception on listen socket ?
        throw NetException("SelectDispatcher() exception on socket fd "
                           + std::to_string(s.GetFileDescriptor()) + "!",
                           errno);
    }
};

//! \}

} // namespace c7a

#endif // !C7A_NET_SELECT_DISPATCHER_HEADER

/******************************************************************************/
<commit_msg>#include net-exception<commit_after>/*******************************************************************************
 * c7a/net/select-dispatcher.hpp
 *
 * Asynchronous callback wrapper around select()
 *
 * Part of Project c7a.
 *
 * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#ifndef C7A_NET_SELECT_DISPATCHER_HEADER
#define C7A_NET_SELECT_DISPATCHER_HEADER

#include <c7a/net/socket.hpp>
#include <c7a/net/select.hpp>
#include <c7a/net/net-exception.hpp>

#include <deque>

namespace c7a {
//! \addtogroup netsock Low Level Socket API
//! \{

/**
 * SelectDispatcher is a higher level wrapper for select(). One can register
 * Socket objects for readability and writability checks, buffered reads and
 * writes with completion callbacks, and also timer functions.
 */
class SelectDispatcher : protected Select
{
    static const bool debug = false;

public:
    typedef std::function<bool (Socket&)> Callback;

    //! Register a buffered read callback and a default exception callback.
    void AddRead(Socket& s, const Callback& read_cb)
    {
        Select::SetRead(s.GetFileDescriptor());
        Select::SetException(s.GetFileDescriptor());
        watch_.emplace_back(s.GetFileDescriptor(), s,
                            read_cb, nullptr, ExceptionCallback);
    }

    //! Register a buffered write callback and a default exception callback.
    void AddWrite(Socket& s, const Callback& write_cb)
    {
        Select::SetWrite(s.GetFileDescriptor());
        Select::SetException(s.GetFileDescriptor());
        watch_.emplace_back(s.GetFileDescriptor(), s,
                            nullptr, write_cb, ExceptionCallback);
    }

    //! Register a buffered write callback and a default exception callback.
    void AddReadWrite(Socket& s,
                      const Callback& read_cb, const Callback& write_cb)
    {
        Select::SetRead(s.GetFileDescriptor());
        Select::SetWrite(s.GetFileDescriptor());
        Select::SetException(s.GetFileDescriptor());
        watch_.emplace_back(s.GetFileDescriptor(), s,
                            read_cb, write_cb, ExceptionCallback);
    }

    void Dispatch(double timeout)
    {
        // copy select fdset
        Select fdset = *this;

        if (debug)
        {
            std::ostringstream oss;
            for (Watch& w : watch_) {
                oss << w.fd << " ";
            }
            oss << "| ";
            for (int i = 0; i < Select::max_fd_ + 1; ++i) {
                if (Select::InRead(i))
                    oss << "r" << i << " ";
                if (Select::InWrite(i))
                    oss << "w" << i << " ";
                if (Select::InException(i))
                    oss << "e" << i << " ";
            }
            LOG << "Performing select() on " << oss.str();
        }

        int r = fdset.select_timeout(timeout);

        if (r < 0) {
            throw NetException("OpenConnections() select() failed!", errno);
        }
        if (r == 0) return;

        // save _current_ size, as it may change.
        size_t watch_size = watch_.size();

        for (size_t i = 0; i != watch_size; ++i)
        {
            Watch& w = watch_[i];

            if (w.fd < 0) continue;

            if (fdset.InRead(w.fd))
            {
                if (w.read_cb) {
                    // have to clear the read flag since the callback may add a
                    // new (other) callback for the same fd.
                    Select::ClearRead(w.fd);
                    Select::ClearException(w.fd);

                    if (!w.read_cb(w.socket)) {
                        // callback returned false: remove fd from set
                        w.fd = -1;
                    }
                    else {
                        Select::SetRead(w.fd);
                        Select::SetException(w.fd);
                    }
                }
                else {
                    LOG << "SelectDispatcher: got read event for fd "
                        << w.fd << " without a read handler.";

                    Select::ClearRead(w.fd);
                }
            }

            if (w.fd < 0) continue;

            if (fdset.InWrite(w.fd))
            {
                if (w.write_cb) {
                    // have to clear the read flag since the callback may add a
                    // new (other) callback for the same fd.
                    Select::ClearWrite(w.fd);
                    Select::ClearException(w.fd);

                    if (!w.write_cb(w.socket)) {
                        // callback returned false: remove fd from set
                        w.fd = -1;
                    }
                    else {
                        Select::SetWrite(w.fd);
                        Select::SetException(w.fd);
                    }
                }
                else {
                    LOG << "SelectDispatcher: got write event for fd "
                        << w.fd << " without a write handler.";

                    Select::ClearWrite(w.fd);
                }
            }

            if (w.fd < 0) continue;

            if (fdset.InException(w.fd))
            {
                if (w.except_cb) {
                    Select::ClearException(w.fd);

                    if (!w.except_cb(w.socket)) {
                        // callback returned false: remove fd from set
                        w.fd = -1;
                    }
                    else {
                        Select::SetException(w.fd);
                    }
                }
                else {
                    LOG << "SelectDispatcher: got exception event for fd "
                        << w.fd << " without an exception handler.";

                    Select::ClearException(w.fd);
                }
            }
        }
    }

private:
    //! struct to entries per watched file descriptor
    struct Watch
    {
        int      fd;
        Socket   socket;
        Callback read_cb, write_cb, except_cb;

        Watch(int _fd, Socket& _socket,
              const Callback& _read_cb, const Callback& _write_cb,
              const Callback& _except_cb)
            : fd(_fd),
              socket(_socket),
              read_cb(_read_cb),
              write_cb(_write_cb),
              except_cb(_except_cb)
        { }
    };

    //! handlers for all registered file descriptors, we have to keep them
    //! address local.
    std::deque<Watch> watch_;

    //! Default exception handler
    static bool ExceptionCallback(Socket& s)
    {
        // exception on listen socket ?
        throw NetException("SelectDispatcher() exception on socket fd "
                           + std::to_string(s.GetFileDescriptor()) + "!",
                           errno);
    }
};

//! \}
} // namespace c7a

#endif // !C7A_NET_SELECT_DISPATCHER_HEADER

/******************************************************************************/
<|endoftext|>


<commit_before>// Copyright (c) 2011 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 "courgette/crc.h"

#ifdef OS_CHROMEOS
#  include "zlib.h"
#else
extern "C" {
#  include "third_party/lzma_sdk/7zCrc.h"
}
#endif

#include "base/basictypes.h"

namespace courgette {

uint32 CalculateCrc(const uint8* buffer, size_t size) {
  uint32 crc;

#ifdef OS_CHROMEOS
  // Calculate Crc by calling CRC method in zlib
  crc = crc32(0, buffer, size);
#else
  // Calculate Crc by calling CRC method in LZMA SDK
  CrcGenerateTable();
  crc = CrcCalc(buffer, size);
#endif

  return ~crc;
}

}  // namespace
<commit_msg>Revert 112083 - Try a different library for Crc32.<commit_after>// Copyright (c) 2009 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.

// Calculate Crc by calling CRC method in LZMA SDK

#include "courgette/crc.h"

extern "C" {
#include "third_party/lzma_sdk/7zCrc.h"
}

namespace courgette {

uint32 CalculateCrc(const uint8* buffer, size_t size) {
  CrcGenerateTable();
  uint32 crc = 0xffffffffL;
  crc = ~CrcCalc(buffer, size);
  return crc;
}

}  // namespace
<|endoftext|>


<commit_before>// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: c-index-test -test-load-source all -comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng -target x86_64-apple-darwin10 std=c++11 %s > %t/out
// RUN: FileCheck %s < %t/out

// Ensure that XML we generate is not invalid.
// RUN: FileCheck %s -check-prefix=WRONG < %t/out
// WRONG-NOT: CommentXMLInvalid
// rdar://12378714

/**
 * \brief Aaa
*/
template<typename T> struct A {
/**
 * \brief Bbb
*/
  A();
/**
 * \brief Ccc
*/
  ~A();
/**
 * \brief Ddd
*/
  void f() { }
};
// CHECK: <Declaration>template <typename T> struct A {\n}</Declaration>
// CHECL: <Declaration>A<T>()</Declaration>
// CHECK: <Declaration>void ~A<T>()</Declaration>

/**
 * \Brief Eee
*/
template <typename T> struct D : A<T> {
/**
 * \brief
*/
  using A<T>::f;

  void f();
};
// CHECK: <Declaration>template <typename T> struct D :  A<T> {\n}</Declaration>
// CHECK: <Declaration>using A<T>::f</Declaration>

struct Base {
    int foo;
};
/**
 * \brief
*/
template<typename T> struct E : Base {
/**
 * \brief
*/
  using Base::foo;
};
// CHECK: <Declaration>template <typename T> struct E :  Base {\n}</Declaration>
// CHECK: <Declaration>using Base::foo</Declaration>

/// \tparam
/// \param AAA Blah blah
template<typename T>
void func_template_1(T AAA);
// CHECK: <Declaration>template <typename T> void func_template_1(T AAA)</Declaration>

template<template<template<typename CCC> class DDD, class BBB> class AAA>
void func_template_2();
<Declaration>template <template <template <typename CCC> class DDD, class BBB> class AAA> void func_template_2()</Declaration>
<commit_msg>Fixes a typo in this test.<commit_after>// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: c-index-test -test-load-source all -comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng -target x86_64-apple-darwin10 std=c++11 %s > %t/out
// RUN: FileCheck %s < %t/out

// Ensure that XML we generate is not invalid.
// RUN: FileCheck %s -check-prefix=WRONG < %t/out
// WRONG-NOT: CommentXMLInvalid
// rdar://12378714

/**
 * \brief Aaa
*/
template<typename T> struct A {
/**
 * \brief Bbb
*/
  A();
/**
 * \brief Ccc
*/
  ~A();
/**
 * \brief Ddd
*/
  void f() { }
};
// CHECK: <Declaration>template <typename T> struct A {\n}</Declaration>
// CHECK: <Declaration>A<T>()</Declaration>
// CHECK: <Declaration>void ~A<T>()</Declaration>

/**
 * \Brief Eee
*/
template <typename T> struct D : A<T> {
/**
 * \brief
*/
  using A<T>::f;

  void f();
};
// CHECK: <Declaration>template <typename T> struct D :  A<T> {\n}</Declaration>
// CHECK: <Declaration>using A<T>::f</Declaration>

struct Base {
    int foo;
};
/**
 * \brief
*/
template<typename T> struct E : Base {
/**
 * \brief
*/
  using Base::foo;
};
// CHECK: <Declaration>template <typename T> struct E :  Base {\n}</Declaration>
// CHECK: <Declaration>using Base::foo</Declaration>

/// \tparam
/// \param AAA Blah blah
template<typename T>
void func_template_1(T AAA);
// CHECK: <Declaration>template <typename T> void func_template_1(T AAA)</Declaration>

template<template<template<typename CCC> class DDD, class BBB> class AAA>
void func_template_2();
<Declaration>template <template <template <typename CCC> class DDD, class BBB> class AAA> void func_template_2()</Declaration>
<|endoftext|>


<commit_before>/*
 * This file is part of ofono-qt
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 *
 * Contact: Alexander Kanavin <alex.kanavin@gmail.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>

#include "qofonoradiosettings.h"

#include <QtDebug>

class TestQOfonoRadioSettings : public QObject
{
    Q_OBJECT

private slots:
    void initTestCase()
    {
        m = new QOfonoRadioSettings(this);
        m->setModemPath("/phonesim");

        QEXPECT_FAIL("", "FIXME: radio settings interface is not supported by AT modems, "
                "and consequently, phonesim", Abort);
        QTRY_VERIFY(m->isValid());
    }

    void testQOfonoRadioSettings()
    {
        QSignalSpy preference(m, SIGNAL(technologyPreferenceChanged(QString)));

        qDebug() << "technologyPreference():" << m->technologyPreference();
    }

    void cleanupTestCase()
    {

    }

private:
    QOfonoRadioSettings *m;
};

QTEST_MAIN(TestQOfonoRadioSettings)
#include "tst_qofonoradiosettings.moc"
<commit_msg>[tests] Fixed tst_qofonoradiosettings<commit_after>/*
 * This file is part of ofono-qt
 *
 * Copyright (C) 2014-2015 Jolla Ltd.
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 *
 * Contact: Alexander Kanavin <alex.kanavin@gmail.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>

#include "qofonoradiosettings.h"

class TestQOfonoRadioSettings : public QObject
{
    Q_OBJECT

private slots:
    void initTestCase()
    {
        m = new QOfonoRadioSettings(this);
        m->setModemPath("/phonesim");
        QTRY_VERIFY(m->isValid());
    }

    void testQOfonoRadioSettings()
    {
        QCOMPARE(m->technologyPreference(), QString("any"));
    }

    void cleanupTestCase()
    {

    }

private:
    QOfonoRadioSettings *m;
};

QTEST_MAIN(TestQOfonoRadioSettings)
#include "tst_qofonoradiosettings.moc"
<|endoftext|>