<commit_before>#include <glib.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <ctime>
#include <chrono>
#include "libsoc_gpio.h"
#include "libsoc_debug.h"

#define PING_OUTPUT 38
#define PING_INPUT 219
#define RESET_OUTPUT 63
#define PING_INTERVAL 1
#define RESET_INTERVAL 5
#define BOOT_INTERVAL 10
#define DEBUG_MESSAGES 1

using namespace std::chrono;

// Compilation instruction:
//g++ -std=gnu++0x glib_test.cpp -o glibtest -I/usr/local/include -I/usr/include/glib-2.0 -I/usr/lib/aarch64-linux-gnu/glib-2.0/include -L/usr/local/lib -lglib-2.0 -lsoc

typedef struct {
  gpio *ping_output;
  gpio *ping_input;
  gpio *reset_output;
  milliseconds prevPing;
  milliseconds curPing;
  guint resetTimerId;
  guint bootTimerId;
} pinData;

/* Make some forward declarations so that we can access functions within one another */
static gboolean bootFinished (gpointer args);
static gboolean sendPing (gpointer args);
static gboolean checkReset (gpointer args);
static gboolean sendReset (gpointer args);
int receivePing (void *arg);

/**
 * After awaiting a boot for a specified amount of time, remove the timer source
 * and add a repeating timer for reset checks.
 */
static gboolean
bootFinished (gpointer args)
{
  if (DEBUG_MESSAGES == 1) {
    std::cout << "Finished awaiting boot. Removing boot timer." << std::endl;
  }

  // Cast args to the correct pointer type
  pinData *pins;
  pins = (pinData *) args;

  // Remove the bootTimer source
  g_source_remove (pins->bootTimerId);

  // Create a new resetTimer source
  pins->resetTimerId = g_timeout_add_seconds (RESET_INTERVAL,
                                              checkReset,
                                              (gpointer) pins);

  // Remove the bootTimerId
  pins->bootTimerId = 0; // TODO: might want to change these to pointers
  return TRUE;
}

/**
 * Send a momentary ping signal
 */
static gboolean
sendPing (gpointer args)
{
  // Cast args to the correct pointer type
  pinData *pins;
  pins = (pinData *) args;

  // Send a short ping
  libsoc_gpio_set_level (pins->ping_output, HIGH);
  libsoc_gpio_set_level (pins->ping_output, LOW);

  return TRUE;
}

/**
 * Reset timer callback. If no ping has been received, sends a reset signal
 * and creates a boot timer source, otherwise updates prev ping to current ping
 */
static gboolean
checkReset (gpointer args)
{
  // Cast args to the correct pointer type
  pinData *pins;
  pins = (pinData *) args;

  // Check if a ping has been received by comparing ping times
  if (pins->prevPing == pins->curPing) {
    if (DEBUG_MESSAGES == 1) {
      std::cout << "No ping receipt detected. Resetting..." << std::endl;
    }

    // No ping has been received. Send a reset signal
    sendReset (args);

    // Reset signal was sent. Remove the resetTimerId and reset timer source
    g_source_remove (pins->resetTimerId);
    pins->resetTimerId = 0; // TODO: might want to make this a pointer and set to NULL

    // Create a new boot timer and store its id
    pins->bootTimerId = g_timeout_add_seconds (BOOT_INTERVAL,
                                               bootFinished,
                                               (gpointer) pins);
  } else {
    // A ping has been received. Update the prev ping to the current ping time
    // TODO: could this asynchronicity be messed up?
    pins->prevPing = pins->curPing;
    if (DEBUG_MESSAGES == 1) {
      std::cout << "Receipt detected. No reset necessary" << std::endl;
    }
  }

  return TRUE;
}

/**
 * Send a momentary reset signal
 */
static gboolean
sendReset (gpointer args)
{
  // Cast args to the correct pointer type
  pinData *pins;
  pins = (pinData *) args;

  // Send a reset signal
  libsoc_gpio_set_level (pins->reset_output, HIGH);
  // Unset the reset signal
  libsoc_gpio_set_level (pins->reset_output, LOW);

  return TRUE;
}

/**
 * Handle a received ping by updating the counter
 */
int
receivePing (void *arg) {
  pinData *pins = (pinData *) arg;
  milliseconds now = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
  );
  if (DEBUG_MESSAGES == 1) {
    std::cout << "Received a ping!" << std::endl;
    long long nowMs = now.count();
    long long curMs = pins->curPing.count();
    std::cout << "Time difference: " << (nowMs - curMs) << std::endl;
  }
  pins->curPing = now;
  return EXIT_SUCCESS;
}

int main (int argc, char **argv)
{
  // Spawn an event loop
  GMainLoop *loop = g_main_loop_new(0, 0);

  pinData *pins = (pinData *) malloc (sizeof (*pins));

  // Setup initial reset timer values
  // pins->prevPing = std::time (nullptr);
  // pins->curPing = std::time (&pins->prevPing);

  pins->prevPing = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
  );
  pins->curPing = pins->prevPing;

  // Setup pins
  pins->ping_output = libsoc_gpio_request (PING_OUTPUT, LS_GPIO_SHARED);
  pins->ping_input = libsoc_gpio_request (PING_INPUT, LS_GPIO_SHARED);
  pins->reset_output = libsoc_gpio_request (RESET_OUTPUT, LS_GPIO_SHARED);

  // Make sure pins are actually requested
  if (pins->ping_output == NULL || pins->ping_input == NULL ||
      pins->reset_output == NULL)
  {
    goto fail;
  }

  // Set the pin directions
  libsoc_gpio_set_direction (pins->ping_output, OUTPUT);
  libsoc_gpio_set_direction (pins->ping_input, INPUT);
  libsoc_gpio_set_direction (pins->reset_output, OUTPUT);

  // Check that directions were indeed set
  if (libsoc_gpio_get_direction (pins->ping_output) != OUTPUT) {
    printf ("Failed to set ping_output direction to OUTPUT\n");
    goto fail;
  }

  if (libsoc_gpio_get_direction(pins->ping_input) != INPUT)
  {
    printf ("Failed to set ping_input direction to INPUT\n");
    goto fail;
  }

  if (libsoc_gpio_get_direction(pins->reset_output) != OUTPUT)
  {
    printf ("Failed to set reset_output direction to OUTPUT\n");
    goto fail;
  }

  // Set the edge on the ping input pin to "falling" to detect interrupts
  libsoc_gpio_set_edge (pins->ping_input, FALLING);

  // Setup the ping callback to handle interrupts
  libsoc_gpio_callback_interrupt (pins->ping_input,
                                  &receivePing,
                                  (void *) pins);

  // Add a timeout to the main loop to send pings at regular intervals
  // g_timeout_add_seconds (PING_INTERVAL, sendPing, (gpointer) pins);
  // libsoc_gpio_set_level (pins->ping_output, LOW);
  // Add a timeout to the main loop to check if a reset is necessary at
  // regular intervals
  pins->resetTimerId = g_timeout_add_seconds (RESET_INTERVAL,
                                              checkReset,
                                              (gpointer) pins);

  // Run the main loop
  g_main_loop_run(loop);

  fail:

  // Clear the gpio memory
  if (pins->ping_output) {
    libsoc_gpio_free (pins->ping_output);
  }

  if (pins->ping_input) {
    libsoc_gpio_free (pins->ping_input);
  }

  if (pins->reset_output) {
    libsoc_gpio_free (pins->reset_output);
  }
}
<commit_msg>UPDATE: minor cleanup and added documentation<commit_after>/**
 * The purpose of this file is to define a behavior for the Jetson wherein
 * the Jetson will...
 *  - Send outbound pings on a GPIO pin at a regular interval of PING_INTERVAL
 *    seconds.
 *  - Receive inbound pings on an interrupt basis (i.e. through threaded
 *    polling).
 *  - Send reset signals when appropriate. Appropriate here is defined to be
 *    when the Jetson has not received an inbound ping within the time
 *    interval defined to be RESET_INTERVAL seconds. When no ping is detected
 *    within that timeframe, the Jetson will assume the chip that is expected
 *    to send such pings has been deactivated and will attempt to reset it in
 *    response.
 *  - Await boots after resetting. The Jetson will not immediately expect to
 *    begin receiving inbound pings again upon reset. Rather, the Jetson will
 *    continue simply sending pings for a number of seconds defined by
 *    BOOT_INTERVAL. Upon the completion of this interval, the Jetson will
 *    again expect to receive inbound pings.
 *
 * This program depends on two libraries: glib-2.0 and libsoc.
 *
 * GLib allows for simplified creation of an event loop so that asynchronous
 * behavior may occur within a single thread context. The main use of this event
 * loop here is to coordinate timeout events. Interrupt detection occurs in
 * a separate thread.
 *
 * libsoc provides a simple C interface for working with the Jetson's GPIO pins.
 * Lighter-weight libraries were tested, however this particular library provides
 * a threaded callback-based implementation of edge detection on the GPIO pins,
 * so we opted for it instead.
 *
 * All GPIO interfacing is accomplished through libsoc while any events of note
 * are handled within the main event loop.
 */

#include <glib.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <chrono>
#include "libsoc_gpio.h"
#include "libsoc_debug.h"

#define PING_OUTPUT 38
#define PING_INPUT 219
#define RESET_OUTPUT 63
#define PING_INTERVAL 1
#define RESET_INTERVAL 5
#define BOOT_INTERVAL 10
#define DEBUG_MESSAGES 1

using namespace std::chrono;

// Compilation instruction:
//g++ -std=gnu++0x glib_test.cpp -o glibtest -I/usr/local/include -I/usr/include/glib-2.0 -I/usr/lib/aarch64-linux-gnu/glib-2.0/include -L/usr/local/lib -lglib-2.0 -lsoc

typedef struct {
  gpio *ping_output;
  gpio *ping_input;
  gpio *reset_output;
  milliseconds prevPing;
  milliseconds curPing;
  guint resetTimerId;
  guint bootTimerId;
} pinData;

/* Make some forward declarations so that we can access functions within one another */
static gboolean bootFinished (gpointer args);
static gboolean sendPing (gpointer args);
static gboolean checkReset (gpointer args);
static gboolean sendReset (gpointer args);
int receivePing (void *arg);

/**
 * After awaiting a boot for a specified amount of time, remove the timer source
 * and add a repeating timer for reset checks.
 */
static gboolean
bootFinished (gpointer args)
{
  if (DEBUG_MESSAGES == 1) {
    std::cout << "Finished awaiting boot. Removing boot timer." << std::endl;
  }

  // Cast args to the correct pointer type
  pinData *pins;
  pins = (pinData *) args;

  // Remove the bootTimer source
  g_source_remove (pins->bootTimerId);

  // Create a new resetTimer source
  pins->resetTimerId = g_timeout_add_seconds (RESET_INTERVAL,
                                              checkReset,
                                              (gpointer) pins);

  // Remove the bootTimerId
  pins->bootTimerId = 0; // TODO: might want to change these to pointers
  return TRUE;
}

/**
 * Send a momentary ping signal
 */
static gboolean
sendPing (gpointer args)
{
  // Cast args to the correct pointer type
  pinData *pins;
  pins = (pinData *) args;

  // Send a short ping
  libsoc_gpio_set_level (pins->ping_output, HIGH);
  libsoc_gpio_set_level (pins->ping_output, LOW);

  return TRUE;
}

/**
 * Reset timer callback. If no ping has been received, sends a reset signal
 * and creates a boot timer source, otherwise updates prev ping to current ping
 */
static gboolean
checkReset (gpointer args)
{
  // Cast args to the correct pointer type
  pinData *pins;
  pins = (pinData *) args;

  // Check if a ping has been received by comparing ping times
  if (pins->prevPing == pins->curPing) {
    if (DEBUG_MESSAGES == 1) {
      std::cout << "No ping receipt detected. Resetting..." << std::endl;
    }

    // No ping has been received. Send a reset signal
    sendReset (args);

    // Reset signal was sent. Remove the resetTimerId and reset timer source
    g_source_remove (pins->resetTimerId);
    pins->resetTimerId = 0; // TODO: might want to make this a pointer and set to NULL

    // Create a new boot timer and store its id
    pins->bootTimerId = g_timeout_add_seconds (BOOT_INTERVAL,
                                               bootFinished,
                                               (gpointer) pins);
  } else {
    // A ping has been received. Update the prev ping to the current ping time
    // TODO: could this asynchronicity be messed up?
    pins->prevPing = pins->curPing;
    if (DEBUG_MESSAGES == 1) {
      std::cout << "Receipt detected. No reset necessary" << std::endl;
    }
  }

  return TRUE;
}

/**
 * Send a momentary reset signal
 */
static gboolean
sendReset (gpointer args)
{
  // Cast args to the correct pointer type
  pinData *pins;
  pins = (pinData *) args;

  // Send a reset signal
  libsoc_gpio_set_level (pins->reset_output, HIGH);
  // Unset the reset signal
  libsoc_gpio_set_level (pins->reset_output, LOW);

  return TRUE;
}

/**
 * Handle a received ping by updating the counter
 */
int
receivePing (void *arg) {
  pinData *pins = (pinData *) arg;
  milliseconds now = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
  );
  if (DEBUG_MESSAGES == 1) {
    std::cout << "Received a ping!" << std::endl;
    long long nowMs = now.count();
    long long curMs = pins->curPing.count();
    std::cout << "Time difference: " << (nowMs - curMs) << std::endl;
  }
  pins->curPing = now;
  return EXIT_SUCCESS;
}

int main (int argc, char **argv)
{
  // Spawn an event loop
  GMainLoop *loop = g_main_loop_new(0, 0);

  pinData *pins = (pinData *) malloc (sizeof (*pins));

  // Setup initial reset timer values
  pins->prevPing = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
  );
  pins->curPing = pins->prevPing;

  // Setup pins
  pins->ping_output = libsoc_gpio_request (PING_OUTPUT, LS_GPIO_SHARED);
  pins->ping_input = libsoc_gpio_request (PING_INPUT, LS_GPIO_SHARED);
  pins->reset_output = libsoc_gpio_request (RESET_OUTPUT, LS_GPIO_SHARED);

  // Make sure pins are actually requested
  if (pins->ping_output == NULL || pins->ping_input == NULL ||
      pins->reset_output == NULL)
  {
    goto fail;
  }

  // Set the pin directions
  libsoc_gpio_set_direction (pins->ping_output, OUTPUT);
  libsoc_gpio_set_direction (pins->ping_input, INPUT);
  libsoc_gpio_set_direction (pins->reset_output, OUTPUT);

  // Check that directions were indeed set
  if (libsoc_gpio_get_direction (pins->ping_output) != OUTPUT) {
    printf ("Failed to set ping_output direction to OUTPUT\n");
    goto fail;
  }

  if (libsoc_gpio_get_direction(pins->ping_input) != INPUT)
  {
    printf ("Failed to set ping_input direction to INPUT\n");
    goto fail;
  }

  if (libsoc_gpio_get_direction(pins->reset_output) != OUTPUT)
  {
    printf ("Failed to set reset_output direction to OUTPUT\n");
    goto fail;
  }

  // Set the edge on the ping input pin to "falling" to detect interrupts
  libsoc_gpio_set_edge (pins->ping_input, FALLING);

  // Setup the ping callback to handle interrupts
  libsoc_gpio_callback_interrupt (pins->ping_input,
                                  &receivePing,
                                  (void *) pins);

  // Add a timeout to the main loop to send pings at regular intervals
  // g_timeout_add_seconds (PING_INTERVAL, sendPing, (gpointer) pins);
  // libsoc_gpio_set_level (pins->ping_output, LOW);
  // Add a timeout to the main loop to check if a reset is necessary at
  // regular intervals
  pins->resetTimerId = g_timeout_add_seconds (RESET_INTERVAL,
                                              checkReset,
                                              (gpointer) pins);

  // Run the main loop
  g_main_loop_run(loop);

  fail:

  // Clear the gpio memory
  if (pins->ping_output) {
    libsoc_gpio_free (pins->ping_output);
  }

  if (pins->ping_input) {
    libsoc_gpio_free (pins->ping_input);
  }

  if (pins->reset_output) {
    libsoc_gpio_free (pins->reset_output);
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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 "config.h"

#include <objidl.h>

#pragma warning(push, 0)
#include "ClipboardWin.h"
#include "COMPtr.h"
#include "DragData.h"
#include "Frame.h"
#include "HitTestResult.h"
#include "Image.h"
#include "KURL.h"
#pragma warning(pop)
#undef LOG

#include "webkit/glue/dragclient_impl.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/glue/context_node_types.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdropdata.h"
#include "webkit/glue/webview_delegate.h"
#include "webkit/glue/webview_impl.h"

void DragClientImpl::willPerformDragDestinationAction(
    WebCore::DragDestinationAction,
    WebCore::DragData*) {
  // FIXME
}

void DragClientImpl::willPerformDragSourceAction(
    WebCore::DragSourceAction,
    const WebCore::IntPoint&,
    WebCore::Clipboard*) {
  // FIXME
}

WebCore::DragDestinationAction DragClientImpl::actionMaskForDrag(
    WebCore::DragData*) {
  return WebCore::DragDestinationActionAny;
}

WebCore::DragSourceAction DragClientImpl::dragSourceActionMaskForPoint(
    const WebCore::IntPoint& window_point) {
  // We want to handle drag operations for all source types.
  return WebCore::DragSourceActionAny;
}

void DragClientImpl::startDrag(WebCore::DragImageRef drag_image,
                               const WebCore::IntPoint& drag_image_origin,
                               const WebCore::IntPoint& event_pos,
                               WebCore::Clipboard* clipboard,
                               WebCore::Frame* frame,
                               bool is_link_drag) {
  // Add a ref to the frame just in case a load occurs mid-drag.
  RefPtr<WebCore::Frame> frame_protector = frame;

  COMPtr<IDataObject> data_object(
      static_cast<WebCore::ClipboardWin*>(clipboard)->dataObject());
  DCHECK(data_object.get());
  WebDropData drop_data;
  WebDropData::PopulateWebDropData(data_object.get(), &drop_data);

  webview_->StartDragging(drop_data);
}

WebCore::DragImageRef DragClientImpl::createDragImageForLink(
    WebCore::KURL&,
    const WebCore::String& label,
    WebCore::Frame*) {
  // FIXME
  return 0;
}

void DragClientImpl::dragControllerDestroyed() {
  delete this;
}

<commit_msg>ifdef around windows code Review URL: http://codereview.chromium.org/249<commit_after>// Copyright (c) 2006-2008 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 "config.h"

#include "build/build_config.h"

#if defined(OS_WIN)
#include <objidl.h>
#endif

#pragma warning(push, 0)
#if defined(OS_WIN)
#include "ClipboardWin.h"
#include "COMPtr.h"
#endif
#include "DragData.h"
#include "Frame.h"
#include "HitTestResult.h"
#include "Image.h"
#include "KURL.h"
#pragma warning(pop)
#undef LOG

#include "webkit/glue/dragclient_impl.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/glue/context_node_types.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdropdata.h"
#include "webkit/glue/webview_delegate.h"
#include "webkit/glue/webview_impl.h"

void DragClientImpl::willPerformDragDestinationAction(
    WebCore::DragDestinationAction,
    WebCore::DragData*) {
  // FIXME
}

void DragClientImpl::willPerformDragSourceAction(
    WebCore::DragSourceAction,
    const WebCore::IntPoint&,
    WebCore::Clipboard*) {
  // FIXME
}

WebCore::DragDestinationAction DragClientImpl::actionMaskForDrag(
    WebCore::DragData*) {
  return WebCore::DragDestinationActionAny;
}

WebCore::DragSourceAction DragClientImpl::dragSourceActionMaskForPoint(
    const WebCore::IntPoint& window_point) {
  // We want to handle drag operations for all source types.
  return WebCore::DragSourceActionAny;
}

void DragClientImpl::startDrag(WebCore::DragImageRef drag_image,
                               const WebCore::IntPoint& drag_image_origin,
                               const WebCore::IntPoint& event_pos,
                               WebCore::Clipboard* clipboard,
                               WebCore::Frame* frame,
                               bool is_link_drag) {
  // Add a ref to the frame just in case a load occurs mid-drag.
  RefPtr<WebCore::Frame> frame_protector = frame;

#if defined(OS_WIN)
  COMPtr<IDataObject> data_object(
      static_cast<WebCore::ClipboardWin*>(clipboard)->dataObject());
  DCHECK(data_object.get());
  WebDropData::PopulateWebDropData(data_object.get(), &drop_data);
#elif defined(OS_MACOSX) || defined(OS_LINUX)
  WebDropData drop_data;
#endif

  webview_->StartDragging(drop_data);
}

WebCore::DragImageRef DragClientImpl::createDragImageForLink(
    WebCore::KURL&,
    const WebCore::String& label,
    WebCore::Frame*) {
  // FIXME
  return 0;
}

void DragClientImpl::dragControllerDestroyed() {
  delete this;
}

<|endoftext|>


<commit_before>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)

// Google Mock - a framework for writing C++ mock classes.
//
// This file tests code in gmock.cc.

#include "gmock/gmock.h"

#include <string>
#include "gtest/gtest.h"

using testing::GMOCK_FLAG(verbose);
using testing::InitGoogleMock;

// Verifies that calling InitGoogleMock() on argv results in new_argv,
// and the gmock_verbose flag's value is set to expected_gmock_verbose.
template <typename Char, int M, int N>
void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
                        const ::std::string& expected_gmock_verbose) {
  const ::std::string old_verbose = GMOCK_FLAG(verbose);

  int argc = M;
  InitGoogleMock(&argc, const_cast<Char**>(argv));
  ASSERT_EQ(N, argc) << "The new argv has wrong number of elements.";

  for (int i = 0; i < N; i++) {
    EXPECT_STREQ(new_argv[i], argv[i]);
  }

  EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG(verbose).c_str());
  GMOCK_FLAG(verbose) = old_verbose;  // Restores the gmock_verbose flag.
}

TEST(InitGoogleMockTest, ParsesInvalidCommandLine) {
  const char* argv[] = {
    NULL
  };

  const char* new_argv[] = {
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(InitGoogleMockTest, ParsesEmptyCommandLine) {
  const char* argv[] = {
    "foo.exe",
    NULL
  };

  const char* new_argv[] = {
    "foo.exe",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(InitGoogleMockTest, ParsesSingleFlag) {
  const char* argv[] = {
    "foo.exe",
    "--gmock_verbose=info",
    NULL
  };

  const char* new_argv[] = {
    "foo.exe",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, "info");
}

TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) {
  const char* argv[] = {
    "foo.exe",
    "--non_gmock_flag=blah",
    NULL
  };

  const char* new_argv[] = {
    "foo.exe",
    "--non_gmock_flag=blah",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
  const char* argv[] = {
    "foo.exe",
    "--non_gmock_flag=blah",
    "--gmock_verbose=error",
    NULL
  };

  const char* new_argv[] = {
    "foo.exe",
    "--non_gmock_flag=blah",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, "error");
}

TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) {
  const wchar_t* argv[] = {
    NULL
  };

  const wchar_t* new_argv[] = {
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) {
  const wchar_t* argv[] = {
    L"foo.exe",
    NULL
  };

  const wchar_t* new_argv[] = {
    L"foo.exe",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(WideInitGoogleMockTest, ParsesSingleFlag) {
  const wchar_t* argv[] = {
    L"foo.exe",
    L"--gmock_verbose=info",
    NULL
  };

  const wchar_t* new_argv[] = {
    L"foo.exe",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, "info");
}

TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) {
  const wchar_t* argv[] = {
    L"foo.exe",
    L"--non_gmock_flag=blah",
    NULL
  };

  const wchar_t* new_argv[] = {
    L"foo.exe",
    L"--non_gmock_flag=blah",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
  const wchar_t* argv[] = {
    L"foo.exe",
    L"--non_gmock_flag=blah",
    L"--gmock_verbose=error",
    NULL
  };

  const wchar_t* new_argv[] = {
    L"foo.exe",
    L"--non_gmock_flag=blah",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, "error");
}

// Makes sure Google Mock flags can be accessed in code.
TEST(FlagTest, IsAccessibleInCode) {
  bool dummy = testing::GMOCK_FLAG(catch_leaked_mocks) &&
      testing::GMOCK_FLAG(verbose) == "";
  (void)dummy;  // Avoids the "unused local variable" warning.
}
<commit_msg>Injection point for GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)

// Google Mock - a framework for writing C++ mock classes.
//
// This file tests code in gmock.cc.

#include "gmock/gmock.h"

#include <string>
#include "gtest/gtest.h"
#include "gtest/internal/custom/gtest.h"

#if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)

using testing::GMOCK_FLAG(verbose);
using testing::InitGoogleMock;

// Verifies that calling InitGoogleMock() on argv results in new_argv,
// and the gmock_verbose flag's value is set to expected_gmock_verbose.
template <typename Char, int M, int N>
void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
                        const ::std::string& expected_gmock_verbose) {
  const ::std::string old_verbose = GMOCK_FLAG(verbose);

  int argc = M;
  InitGoogleMock(&argc, const_cast<Char**>(argv));
  ASSERT_EQ(N, argc) << "The new argv has wrong number of elements.";

  for (int i = 0; i < N; i++) {
    EXPECT_STREQ(new_argv[i], argv[i]);
  }

  EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG(verbose).c_str());
  GMOCK_FLAG(verbose) = old_verbose;  // Restores the gmock_verbose flag.
}

TEST(InitGoogleMockTest, ParsesInvalidCommandLine) {
  const char* argv[] = {
    NULL
  };

  const char* new_argv[] = {
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(InitGoogleMockTest, ParsesEmptyCommandLine) {
  const char* argv[] = {
    "foo.exe",
    NULL
  };

  const char* new_argv[] = {
    "foo.exe",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(InitGoogleMockTest, ParsesSingleFlag) {
  const char* argv[] = {
    "foo.exe",
    "--gmock_verbose=info",
    NULL
  };

  const char* new_argv[] = {
    "foo.exe",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, "info");
}

TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) {
  const char* argv[] = {
    "foo.exe",
    "--non_gmock_flag=blah",
    NULL
  };

  const char* new_argv[] = {
    "foo.exe",
    "--non_gmock_flag=blah",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
  const char* argv[] = {
    "foo.exe",
    "--non_gmock_flag=blah",
    "--gmock_verbose=error",
    NULL
  };

  const char* new_argv[] = {
    "foo.exe",
    "--non_gmock_flag=blah",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, "error");
}

TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) {
  const wchar_t* argv[] = {
    NULL
  };

  const wchar_t* new_argv[] = {
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) {
  const wchar_t* argv[] = {
    L"foo.exe",
    NULL
  };

  const wchar_t* new_argv[] = {
    L"foo.exe",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(WideInitGoogleMockTest, ParsesSingleFlag) {
  const wchar_t* argv[] = {
    L"foo.exe",
    L"--gmock_verbose=info",
    NULL
  };

  const wchar_t* new_argv[] = {
    L"foo.exe",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, "info");
}

TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) {
  const wchar_t* argv[] = {
    L"foo.exe",
    L"--non_gmock_flag=blah",
    NULL
  };

  const wchar_t* new_argv[] = {
    L"foo.exe",
    L"--non_gmock_flag=blah",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}

TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
  const wchar_t* argv[] = {
    L"foo.exe",
    L"--non_gmock_flag=blah",
    L"--gmock_verbose=error",
    NULL
  };

  const wchar_t* new_argv[] = {
    L"foo.exe",
    L"--non_gmock_flag=blah",
    NULL
  };

  TestInitGoogleMock(argv, new_argv, "error");
}

#endif  // !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)

// Makes sure Google Mock flags can be accessed in code.
TEST(FlagTest, IsAccessibleInCode) {
  bool dummy = testing::GMOCK_FLAG(catch_leaked_mocks) &&
      testing::GMOCK_FLAG(verbose) == "";
  (void)dummy;  // Avoids the "unused local variable" warning.
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2003 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <string>

#include "sim/param.hh"
#include "sim/eventq.hh"
#include "base/hostinfo.hh"
#include "sim/sim_events.hh"
#include "sim/sim_exit.hh"
#include "sim/sim_stats.hh"

using namespace std;

//
// handle termination event
//
void
SimExitEvent::process()
{
    // This event does not autodelete because exitNow may be called,
    // and the function will never be allowed to finish.
    if (theQueue() == &mainEventQueue) {
        string _cause = cause;
        int _code = code;
        delete this;
        exitNow(_cause, _code);
    } else {
        new SimExitEvent(cause, code);
        delete this;
    }
}

const char *
SimExitEvent::description()
{
    return "simulation termination";
}

//
// constructor: automatically schedules at specified time
//
CountedExitEvent::CountedExitEvent(EventQueue *q, const std::string &_cause,
                                   Tick _when, int &_downCounter)
    : Event(q, Sim_Exit_Pri),
      cause(_cause),
      downCounter(_downCounter)
{
    // catch stupid mistakes
    assert(downCounter > 0);

    schedule(_when);
}

//
// handle termination event
//
void
CountedExitEvent::process()
{
    if (--downCounter == 0) {
        new SimExitEvent(cause, 0);
    }
}

const char *
CountedExitEvent::description()
{
    return "counted exit";
}

#ifdef CHECK_SWAP_CYCLES
new CheckSwapEvent(&mainEventQueue, CHECK_SWAP_CYCLES);
#endif

void
CheckSwapEvent::process()
{
    /*  Check the amount of free swap space  */
    long swap;

    /*  returns free swap in KBytes  */
    swap = procInfo("/proc/meminfo", "SwapFree:");

    if (swap < 1000)
        ccprintf(cerr, "\a\a\aWarning! Swap space is low (%d)\n", swap);

    if (swap < 100) {
        cerr << "\a\aAborting Simulation! Inadequate swap space!\n\n";
        new SimExitEvent("Lack of swap space");
    }

    schedule(curTick + interval);
}

const char *
CheckSwapEvent::description()
{
    return "check swap";
}

///////////////////////////////////////////////////
//
// Simulation termination parameters
//
///////////////////////////////////////////////////

class TermParamContext : public ParamContext
{
  public:
    TermParamContext(const string &_iniSection)
        : ParamContext(_iniSection) {}
    void checkParams();
};

TermParamContext simTerminationParams("max");

Param<Tick> max_cycle(&simTerminationParams, "cycle",
                        "maximum number of cycles to execute");

void
TermParamContext::checkParams()
{
    // if a max cycle count was specified, put a termination event on
    // the event queue at that point
    if (max_cycle.isValid())
        new SimExitEvent(max_cycle, "reached maximum cycle count");
}

//
// Progress event: print out cycle every so often so we know we're
// making forward progress.
//
class ProgressEvent : public Event
{
  protected:
    Tick interval;

  public:
    ProgressEvent(EventQueue *q, Tick interval);

    void process();	// process event
    virtual const char *description();
};

//
// constructor: schedule at specified time
//
ProgressEvent::ProgressEvent(EventQueue *q, Tick _interval)
    : Event(q), interval(_interval)
{
    schedule(interval);
}

//
// handle progress event: print message and reschedule
//
void
ProgressEvent::process()
{
    DPRINTFN("ProgressEvent\n");
    // reschedule for next interval
    schedule(curTick + interval);
}

const char *
ProgressEvent::description()
{
    return "progress message";
}

/////////
//
// Periodic progress message support: print out a message every n
// cycles so we know we're making forward progress.
//
/////////

// Parameter space for execution address tracing options.  Derive
// from ParamContext so we can override checkParams() function.
class ProgressParamContext : public ParamContext
{
  public:
    ProgressParamContext(const string &_iniSection)
        : ParamContext(_iniSection) {}
    void checkParams();
};

ProgressParamContext progessMessageParams("progress");

Param<Tick> progress_interval(&progessMessageParams, "cycle",
                                "cycle interval for progress messages");

/* check execute options */
void
ProgressParamContext::checkParams()
{
    if (progress_interval.isValid())
        new ProgressEvent(&mainEventQueue, progress_interval);
}
<commit_msg>Make the progress event work even after restoring from a checkpoint<commit_after>/*
 * Copyright (c) 2003 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <string>

#include "base/callback.hh"
#include "base/hostinfo.hh"
#include "sim/eventq.hh"
#include "sim/param.hh"
#include "sim/sim_events.hh"
#include "sim/sim_exit.hh"
#include "sim/sim_init.hh"
#include "sim/sim_stats.hh"

using namespace std;

//
// handle termination event
//
void
SimExitEvent::process()
{
    // This event does not autodelete because exitNow may be called,
    // and the function will never be allowed to finish.
    if (theQueue() == &mainEventQueue) {
        string _cause = cause;
        int _code = code;
        delete this;
        exitNow(_cause, _code);
    } else {
        new SimExitEvent(cause, code);
        delete this;
    }
}

const char *
SimExitEvent::description()
{
    return "simulation termination";
}

//
// constructor: automatically schedules at specified time
//
CountedExitEvent::CountedExitEvent(EventQueue *q, const std::string &_cause,
                                   Tick _when, int &_downCounter)
    : Event(q, Sim_Exit_Pri),
      cause(_cause),
      downCounter(_downCounter)
{
    // catch stupid mistakes
    assert(downCounter > 0);

    schedule(_when);
}

//
// handle termination event
//
void
CountedExitEvent::process()
{
    if (--downCounter == 0) {
        new SimExitEvent(cause, 0);
    }
}

const char *
CountedExitEvent::description()
{
    return "counted exit";
}

#ifdef CHECK_SWAP_CYCLES
new CheckSwapEvent(&mainEventQueue, CHECK_SWAP_CYCLES);
#endif

void
CheckSwapEvent::process()
{
    /*  Check the amount of free swap space  */
    long swap;

    /*  returns free swap in KBytes  */
    swap = procInfo("/proc/meminfo", "SwapFree:");

    if (swap < 1000)
        ccprintf(cerr, "\a\a\aWarning! Swap space is low (%d)\n", swap);

    if (swap < 100) {
        cerr << "\a\aAborting Simulation! Inadequate swap space!\n\n";
        new SimExitEvent("Lack of swap space");
    }

    schedule(curTick + interval);
}

const char *
CheckSwapEvent::description()
{
    return "check swap";
}

///////////////////////////////////////////////////
//
// Simulation termination parameters
//
///////////////////////////////////////////////////

class TermParamContext : public ParamContext
{
  public:
    TermParamContext(const string &_iniSection)
        : ParamContext(_iniSection) {}
    void checkParams();
};

TermParamContext simTerminationParams("max");

Param<Tick> max_cycle(&simTerminationParams, "cycle",
                        "maximum number of cycles to execute");

void
TermParamContext::checkParams()
{
    // if a max cycle count was specified, put a termination event on
    // the event queue at that point
    if (max_cycle.isValid())
        new SimExitEvent(max_cycle, "reached maximum cycle count");
}

//
// Progress event: print out cycle every so often so we know we're
// making forward progress.
//
class ProgressEvent : public Event
{
  protected:
    Tick interval;

  public:
    ProgressEvent(EventQueue *q, Tick interval);

    void process();	// process event
    virtual const char *description();
};

//
// constructor: schedule at specified time
//
ProgressEvent::ProgressEvent(EventQueue *q, Tick _interval)
    : Event(q), interval(_interval)
{
    schedule(curTick + interval);
}

//
// handle progress event: print message and reschedule
//
void
ProgressEvent::process()
{
    DPRINTFN("ProgressEvent\n");
    // reschedule for next interval
    schedule(curTick + interval);
}

const char *
ProgressEvent::description()
{
    return "progress message";
}

/////////
//
// Periodic progress message support: print out a message every n
// cycles so we know we're making forward progress.
//
/////////

// Parameter space for execution address tracing options.  Derive
// from ParamContext so we can override checkParams() function.
class ProgressParamContext : public ParamContext
{
  public:
    ProgressParamContext(const string &_iniSection)
        : ParamContext(_iniSection) {}
    void checkParams();
};

ProgressParamContext progessMessageParams("progress");

Param<Tick> progress_interval(&progessMessageParams, "cycle",
                                "cycle interval for progress messages");

namespace {
    struct SetupProgress : public Callback
    {
        Tick interval;
        SetupProgress(Tick tick) : interval(tick) {}

        virtual void process()
        {
            new ProgressEvent(&mainEventQueue, interval);
            delete this;
        }
    };
}

/* check execute options */
void
ProgressParamContext::checkParams()
{
    if (progress_interval.isValid())
        registerInitCallback(new SetupProgress(progress_interval));
}
<|endoftext|>


<commit_before>/***************************************************************************
 *  @file       The code is for the exercises in C++ Primmer 5th Edition
 *  @author     Alan.W
 *  @date       26  DEC 2013
 *  @remark
 ***************************************************************************/

//!
//! Exercise 12.26:
//! Rewrite the program on page 481 using an allocator.
//!

#include <iostream>
#include <memory>
int main()
{
    //! create a allocator object and use it to handle string.
    //! create a movable pointer to the address p points
    std::allocator<std::string> alloc;
    std::string* const p = alloc.allocate(5);
    std::string* p_movable = p;

    //! constuct each object using copy constructor
    std::string word;
    while(std::cin >> word && p_movable != p + 3)
    {
        alloc.construct(p_movable,word);
        ++p_movable;
    }

    //! move the movable pointer back home
    p_movable = p;

    //! print the strings constructed.
    while(p_movable != p + 3)
        std::cout << *p_movable++ <<"\n";

    //! free the allocated memory.
    delete[] p;

    return 0;
}
<commit_msg>Update ex12.26.cpp<commit_after>/***************************************************************************
 *  @file       The code is for the exercises in C++ Primmer 5th Edition
 *  @author     Alan.W
 *  @date       26  DEC 2013
 *  @remark
 ***************************************************************************/

//!
//! Exercise 12.26:
//! Rewrite the program on page 481 using an allocator.
//!

#include <iostream>
#include <memory>
int main()
{
    //! create a allocator object and use it to handle string.
    //! create a movable pointer to the address p points
    std::allocator<std::string> alloc;
    std::string* const p = alloc.allocate(5);
    std::string* p_movable = p;

    //! constuct each object using copy constructor
    std::string word;
    while(std::cin >> word && p_movable != p + 3)
    {
        alloc.construct(p_movable,word);
        ++p_movable;
    }

    //! move the movable pointer back home
    p_movable = p;

    //! print the strings constructed.
    while(p_movable != p + 3){
        std::cout << *p_movable <<"\n";
        alloc.destroy(p_movable);
        ++p_movable；
    }

    //! free the allocated memory.
    alloc.deallocate(p, 5);

    return 0;
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_FUN_PROD_HPP
#define STAN_MATH_PRIM_FUN_PROD_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <vector>

namespace stan {
namespace math {

/**
 * Returns the product of given scalar. This is a no-op.
 *
 * @tparam T type of the scalar
 * @param v specified scalar
 * @return the scalar
 */
template<typename T, require_stan_scalar_t<T>* = nullptr>
T prod(const T& a){
  return a;
}

/**
 * Returns the product of the coefficients of the specified
 * standard vector.
 *
 * @tparam T type of elements in the vector
 * @param v Specified vector.
 * @return Product of coefficients of vector.
 */
template <typename T>
inline T prod(const std::vector<T>& v) {
  if (v.size() == 0) {
    return 1;
  }
  Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1>> m(&v[0], v.size());
  return m.prod();
}

/**
 * Returns the product of the coefficients of the specified
 * column vector.
 *
 * @tparam T type of elements in the vector
 * @param v Specified vector.
 * @return Product of coefficients of vector.
 */
template <typename EigMat, require_eigen_t<EigMat>* = nullptr>
inline value_type_t<EigMat> prod(const EigMat& v) {
  if (v.size() == 0) {
    return 1.0;
  }
  return v.prod();
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>fixed doxygen<commit_after>#ifndef STAN_MATH_PRIM_FUN_PROD_HPP
#define STAN_MATH_PRIM_FUN_PROD_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <vector>

namespace stan {
namespace math {

/**
 * Returns the product of given scalar. This is a no-op.
 *
 * @tparam T type of the scalar
 * @param v specified scalar
 * @return the scalar
 */
template<typename T, require_stan_scalar_t<T>* = nullptr>
T prod(const T& v){
  return v;
}

/**
 * Returns the product of the coefficients of the specified
 * standard vector.
 *
 * @tparam T type of elements in the vector
 * @param v Specified vector.
 * @return Product of coefficients of vector.
 */
template <typename T>
inline T prod(const std::vector<T>& v) {
  if (v.size() == 0) {
    return 1;
  }
  Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1>> m(&v[0], v.size());
  return m.prod();
}

/**
 * Returns the product of the coefficients of the specified
 * column vector.
 *
 * @tparam T type of elements in the vector
 * @param v Specified vector.
 * @return Product of coefficients of vector.
 */
template <typename EigMat, require_eigen_t<EigMat>* = nullptr>
inline value_type_t<EigMat> prod(const EigMat& v) {
  if (v.size() == 0) {
    return 1.0;
  }
  return v.prod();
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


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

#pragma hdrstop

#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _TOOLS_TENCCVT_HXX
#include <tools/tenccvt.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif

#include <tools/stream.hxx>

#include "starmath.hrc"

#include "utility.hxx"
#include "dialog.hxx"
#include "view.hxx"
#include "smdll.hxx"

SmViewShell * SmGetActiveView()
    // return pointer to active SmViewShell, if this is not possible
    // return 0 instead.
{
    SfxViewShell *pView = SfxViewShell::Current();
    return PTR_CAST(SmViewShell, pView);
}

////////////////////////////////////////////////////////////
//
// SmRectCache
//

SmRectCache::Key::Key(const XubString &rText, const Font &rFont)
{
}

BOOL SmRectCache::Key::operator <  (const Key &rKey) const
{
#ifdef never
    BOOL  bRes = FALSE;

    if (aText < rKey.aText)
        bRes = TRUE;
    else if ()

    return      aText       <  rKey.aText
            ||  aText       == rKey.aText        &&  aFontName   < rKey.aFontName
            ||  aFontName   == rKey.aFontname    &&  aFontSize   < rKey.aFontSize
            ||  aFontSize   == rKey.aFontSize    &&  eFontWeight < rKey.eFontWeight
            ||  eFontWeight == rKey.eFontWeight  &&  eFontItalic < rKey.eFontItalic;
#endif
    return FALSE;
}

BOOL SmRectCache::Key::operator == (const Key &rKey) const
{
    return      aText       == rKey.aText
            &&  aFontName   == rKey.aFontName
            &&  aFontSize   == rKey.aFontSize
            &&  eFontWeight == rKey.eFontWeight
            &&  eFontItalic == rKey.eFontItalic;
}

SmRectCache::SmRectCache()
{
    pVirDev = 0;
}

SmRectCache::~SmRectCache()
{
    delete pVirDev;
}

const SmRect * SmRectCache::Search(const Key &rKey) const
{
    return 0;
}

const SmRect * SmRectCache::Add(const Key &rKey, const SmRect &rRect)
{
    return (const SmRect *)-1;
}

VirtualDevice * SmRectCache::GetVirDev()
{
    if (!pVirDev)
    {
        SmViewShell *pView = SmGetActiveView();
        if (pView)
            pVirDev = new VirtualDevice( pView->GetGraphicWindow() );
        else
            pVirDev = new VirtualDevice;
        pVirDev->SetMapMode( MapMode(MAP_100TH_MM) );
    }
    DBG_ASSERT(pVirDev->GetMapMode().GetMapUnit() == MAP_100TH_MM,
               "Sm : falscher MapMode");

    return pVirDev;
}

void SmRectCache::Reset()
{
}

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

/**************************************************************************/

SmPickList::SmPickList(USHORT nInitSize, USHORT nMaxSize) :
    SfxPtrArr((BYTE) nInitSize, 1)
{
    nSize = nMaxSize;
}

SmPickList::~SmPickList()
{
    Clear();
}

SmPickList& SmPickList::operator=(const SmPickList& rList)
{
    USHORT  nPos;

    Clear();
    nSize = rList.nSize;
    for (nPos = 0; nPos < rList.Count(); nPos++)
        InsertPtr(nPos, CreateItem(rList.Get(nPos)));

    return *this;
}

void SmPickList::Insert(const void *pItem)
{
    Remove(pItem);
    InsertPtr(0, CreateItem(pItem));

    if (Count() > nSize)
    {
        DestroyItem(GetPtr(nSize));
        RemovePtr(nSize, 1);
    }
}

void SmPickList::Update(const void *pItem, const void *pNewItem)
{
    USHORT  nPos;

    for (nPos = 0; nPos < Count(); nPos++)
        if (CompareItem(GetPtr(nPos), pItem))
        {
            DestroyItem(GetPtr(nPos));
            GetPtr(nPos) = CreateItem(pNewItem);
            break;
        }
}

void SmPickList::Remove(const void *pItem)
{
    USHORT  nPos;

    for (nPos = 0; nPos < Count(); nPos++)
        if (CompareItem(GetPtr(nPos), pItem))
        {
            DestroyItem(GetPtr(nPos));
            RemovePtr(nPos, 1);
            break;
        }
}

void SmPickList::SetSize(USHORT nNewSize)
{
    nSize = nNewSize;

    while (Count() > nSize)
    {
        DestroyItem(GetPtr(Count() - 1));
        RemovePtr(Count() - 1, 1);
    }
}

BOOL SmPickList::Contains(const void *pItem) const
{
    USHORT  nPos;

    for (nPos = 0; nPos < Count(); nPos++)
        if (CompareItem(GetPtr(nPos), pItem))
            return TRUE;

    return FALSE;
}

void SmPickList::Clear()
{
    USHORT  nPos;

    for (nPos = 0; nPos < Count(); nPos++)
        DestroyItem(GetPtr(nPos));

    RemovePtr(0, Count());
}

/**************************************************************************/
/**************************************************************************/

void * SmFontPickList::CreateItem(const String& rString)
{
    return new Font();
}

void * SmFontPickList::CreateItem(const void *pItem)
{
    return new Font(*((Font *) pItem));
}

void SmFontPickList::DestroyItem(void *pItem)
{
    delete (Font *)pItem;
}

BOOL SmFontPickList::CompareItem(const void *pFirstItem, const void *pSecondItem) const
{
    Font    *pFirstFont, *pSecondFont;

    pFirstFont  = (Font *)pFirstItem;
    pSecondFont = (Font *)pSecondItem;

    if (pFirstFont->GetName() == pSecondFont->GetName())
        if ((pFirstFont->GetFamily()  == pSecondFont->GetFamily())  &&
            (pFirstFont->GetCharSet() == pSecondFont->GetCharSet()) &&
            (pFirstFont->GetWeight()  == pSecondFont->GetWeight())  &&
            (pFirstFont->GetItalic()  == pSecondFont->GetItalic()))
            return (TRUE);

    return FALSE;
}

String SmFontPickList::GetStringItem(void *pItem)
{
    Font   *pFont;
    String  aString;
    const sal_Char *pDelim = ", ";

    pFont = (Font *)pItem;

    aString = pFont->GetName();

    if (IsItalic( *pFont ))
    {
        aString.AppendAscii( pDelim );
        aString += String(SmResId(RID_FONTITALIC));
    }
    if (IsBold( *pFont ))    // bold?
    {
        aString.AppendAscii( pDelim );
        aString += String(SmResId(RID_FONTBOLD));
    }

    return (aString);
}

void SmFontPickList::Insert(const Font &rFont)
{
    SmPickList::Insert((void *)&rFont);
}

void SmFontPickList::Update(const Font &rFont, const Font &rNewFont)
{
    SmPickList::Update((void *)&rFont, (void *)&rNewFont);
}

void SmFontPickList::Remove(const Font &rFont)
{
    SmPickList::Remove((void *)&rFont);
}

void SmFontPickList::ReadFrom(const SmFontDialog& rDialog)
{
    Insert(rDialog.GetFont());
}

void SmFontPickList::WriteTo(SmFontDialog& rDialog) const
{
    rDialog.SetFont(Get());
}

/**************************************************************************/

/**************************************************************************/

IMPL_LINK( SmFontPickListBox, SelectHdl, ListBox *, pListBox )
{
    USHORT  nPos;
    String  aString;

    nPos = GetSelectEntryPos();

    if (nPos != 0)
    {
        SmFontPickList::Insert(Get(nPos));
        aString = GetEntry(nPos);
        RemoveEntry(nPos);
        InsertEntry(aString, 0);
    }

    SelectEntryPos(0);

    return 0;
}

SmFontPickListBox::SmFontPickListBox(Window* pParent, WinBits nWinStyle, USHORT nMax) :
    SmFontPickList(nMax, nMax),
    ListBox(pParent, nWinStyle)
{
    SetSelectHdl(LINK(this, SmFontPickListBox, SelectHdl));
}

SmFontPickListBox::SmFontPickListBox(Window* pParent, const ResId& rResId, USHORT nMax) :
    SmFontPickList(nMax, nMax),
    ListBox(pParent, rResId)
{
    SetSelectHdl(LINK(this, SmFontPickListBox, SelectHdl));
}

SmFontPickListBox& SmFontPickListBox::operator=(const SmFontPickList& rList)
{
    USHORT nPos;

    *(SmFontPickList *)this = rList;

    for (nPos = 0; nPos < Count(); nPos++)
        InsertEntry(GetStringItem(GetPtr(nPos)), nPos);

    if (Count() > 0)
        SelectEntry(GetStringItem(GetPtr(0)));

    return *this;
}

void SmFontPickListBox::Insert(const Font &rFont)
{
    SmFontPickList::Insert(rFont);

    RemoveEntry(GetStringItem(GetPtr(0)));
    InsertEntry(GetStringItem(GetPtr(0)), 0);
    SelectEntry(GetStringItem(GetPtr(0)));

    while (GetEntryCount() > nSize)
        RemoveEntry(GetEntryCount() - 1);

    return;
}

void SmFontPickListBox::Update(const Font &rFont, const Font &rNewFont)
{
    SmFontPickList::Update(rFont, rNewFont);

    // ********************** hier fehlt noch was

    return;
}

void SmFontPickListBox::Remove(const Font &rFont)
{
    SmFontPickList::Remove(rFont);

    // ********************** hier fehlt noch was

    return;
}

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

BOOL IsItalic( const Font &rFont )
{
    FontItalic eItalic = rFont.GetItalic();
    // the code below leaves only _NONE and _DONTKNOW as not italic
    return eItalic == ITALIC_OBLIQUE  ||  eItalic == ITALIC_NORMAL;
}

BOOL IsBold( const Font &rFont )
{
    FontWeight eWeight = rFont.GetWeight();
    return eWeight != WEIGHT_DONTKNOW && eWeight > WEIGHT_NORMAL;
}

void SmFace::Impl_Init()
{
    SetSize( GetSize() );
    SetTransparent( TRUE );
    SetAlign( ALIGN_BASELINE );
    SetColor( COL_AUTO );
}

void SmFace::SetSize(const Size& rSize)
{
    Size  aSize (rSize);

    // check the requested size against minimum value
    static int __READONLY_DATA  nMinVal = SmPtsTo100th_mm(2);

    if (aSize.Height() < nMinVal)
        aSize.Height() = nMinVal;

    //! we don't force a maximum value here because this may prevent eg the
    //! parentheses in "left ( ... right )" from matching up with large
    //! bodies (eg stack{...} with many entries).
    //! Of course this is holds only if characters are used and not polygons.

    Font::SetSize(aSize);
}

long SmFace::GetBorderWidth() const
{
    if (nBorderWidth < 0)
        return GetDefaultBorderWidth();
    else
        return nBorderWidth;
}

SmFace & SmFace::operator = (const SmFace &rFace)
{
    Font::operator = (rFace);
    nBorderWidth = -1;
    return *this;
}

SmFace & operator *= (SmFace &rFace, const Fraction &rFrac)
    // scales the width and height of 'rFace' by 'rFrac' and returns a
    // reference to 'rFace'.
    // It's main use is to make scaling fonts look easier.
{   const Size &rFaceSize = rFace.GetSize();

    rFace.SetSize(Size(Fraction(rFaceSize.Width())  *= rFrac,
                       Fraction(rFaceSize.Height()) *= rFrac));
    return rFace;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.13.54); FILE MERGED 2005/09/05 17:37:46 rt 1.13.54.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: utility.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 15:15:14 $
 *
 *  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
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _TOOLS_TENCCVT_HXX
#include <tools/tenccvt.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif

#include <tools/stream.hxx>

#include "starmath.hrc"

#include "utility.hxx"
#include "dialog.hxx"
#include "view.hxx"
#include "smdll.hxx"

SmViewShell * SmGetActiveView()
    // return pointer to active SmViewShell, if this is not possible
    // return 0 instead.
{
    SfxViewShell *pView = SfxViewShell::Current();
    return PTR_CAST(SmViewShell, pView);
}

////////////////////////////////////////////////////////////
//
// SmRectCache
//

SmRectCache::Key::Key(const XubString &rText, const Font &rFont)
{
}

BOOL SmRectCache::Key::operator <  (const Key &rKey) const
{
#ifdef never
    BOOL  bRes = FALSE;

    if (aText < rKey.aText)
        bRes = TRUE;
    else if ()

    return      aText       <  rKey.aText
            ||  aText       == rKey.aText        &&  aFontName   < rKey.aFontName
            ||  aFontName   == rKey.aFontname    &&  aFontSize   < rKey.aFontSize
            ||  aFontSize   == rKey.aFontSize    &&  eFontWeight < rKey.eFontWeight
            ||  eFontWeight == rKey.eFontWeight  &&  eFontItalic < rKey.eFontItalic;
#endif
    return FALSE;
}

BOOL SmRectCache::Key::operator == (const Key &rKey) const
{
    return      aText       == rKey.aText
            &&  aFontName   == rKey.aFontName
            &&  aFontSize   == rKey.aFontSize
            &&  eFontWeight == rKey.eFontWeight
            &&  eFontItalic == rKey.eFontItalic;
}

SmRectCache::SmRectCache()
{
    pVirDev = 0;
}

SmRectCache::~SmRectCache()
{
    delete pVirDev;
}

const SmRect * SmRectCache::Search(const Key &rKey) const
{
    return 0;
}

const SmRect * SmRectCache::Add(const Key &rKey, const SmRect &rRect)
{
    return (const SmRect *)-1;
}

VirtualDevice * SmRectCache::GetVirDev()
{
    if (!pVirDev)
    {
        SmViewShell *pView = SmGetActiveView();
        if (pView)
            pVirDev = new VirtualDevice( pView->GetGraphicWindow() );
        else
            pVirDev = new VirtualDevice;
        pVirDev->SetMapMode( MapMode(MAP_100TH_MM) );
    }
    DBG_ASSERT(pVirDev->GetMapMode().GetMapUnit() == MAP_100TH_MM,
               "Sm : falscher MapMode");

    return pVirDev;
}

void SmRectCache::Reset()
{
}

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

/**************************************************************************/

SmPickList::SmPickList(USHORT nInitSize, USHORT nMaxSize) :
    SfxPtrArr((BYTE) nInitSize, 1)
{
    nSize = nMaxSize;
}

SmPickList::~SmPickList()
{
    Clear();
}

SmPickList& SmPickList::operator=(const SmPickList& rList)
{
    USHORT  nPos;

    Clear();
    nSize = rList.nSize;
    for (nPos = 0; nPos < rList.Count(); nPos++)
        InsertPtr(nPos, CreateItem(rList.Get(nPos)));

    return *this;
}

void SmPickList::Insert(const void *pItem)
{
    Remove(pItem);
    InsertPtr(0, CreateItem(pItem));

    if (Count() > nSize)
    {
        DestroyItem(GetPtr(nSize));
        RemovePtr(nSize, 1);
    }
}

void SmPickList::Update(const void *pItem, const void *pNewItem)
{
    USHORT  nPos;

    for (nPos = 0; nPos < Count(); nPos++)
        if (CompareItem(GetPtr(nPos), pItem))
        {
            DestroyItem(GetPtr(nPos));
            GetPtr(nPos) = CreateItem(pNewItem);
            break;
        }
}

void SmPickList::Remove(const void *pItem)
{
    USHORT  nPos;

    for (nPos = 0; nPos < Count(); nPos++)
        if (CompareItem(GetPtr(nPos), pItem))
        {
            DestroyItem(GetPtr(nPos));
            RemovePtr(nPos, 1);
            break;
        }
}

void SmPickList::SetSize(USHORT nNewSize)
{
    nSize = nNewSize;

    while (Count() > nSize)
    {
        DestroyItem(GetPtr(Count() - 1));
        RemovePtr(Count() - 1, 1);
    }
}

BOOL SmPickList::Contains(const void *pItem) const
{
    USHORT  nPos;

    for (nPos = 0; nPos < Count(); nPos++)
        if (CompareItem(GetPtr(nPos), pItem))
            return TRUE;

    return FALSE;
}

void SmPickList::Clear()
{
    USHORT  nPos;

    for (nPos = 0; nPos < Count(); nPos++)
        DestroyItem(GetPtr(nPos));

    RemovePtr(0, Count());
}

/**************************************************************************/
/**************************************************************************/

void * SmFontPickList::CreateItem(const String& rString)
{
    return new Font();
}

void * SmFontPickList::CreateItem(const void *pItem)
{
    return new Font(*((Font *) pItem));
}

void SmFontPickList::DestroyItem(void *pItem)
{
    delete (Font *)pItem;
}

BOOL SmFontPickList::CompareItem(const void *pFirstItem, const void *pSecondItem) const
{
    Font    *pFirstFont, *pSecondFont;

    pFirstFont  = (Font *)pFirstItem;
    pSecondFont = (Font *)pSecondItem;

    if (pFirstFont->GetName() == pSecondFont->GetName())
        if ((pFirstFont->GetFamily()  == pSecondFont->GetFamily())  &&
            (pFirstFont->GetCharSet() == pSecondFont->GetCharSet()) &&
            (pFirstFont->GetWeight()  == pSecondFont->GetWeight())  &&
            (pFirstFont->GetItalic()  == pSecondFont->GetItalic()))
            return (TRUE);

    return FALSE;
}

String SmFontPickList::GetStringItem(void *pItem)
{
    Font   *pFont;
    String  aString;
    const sal_Char *pDelim = ", ";

    pFont = (Font *)pItem;

    aString = pFont->GetName();

    if (IsItalic( *pFont ))
    {
        aString.AppendAscii( pDelim );
        aString += String(SmResId(RID_FONTITALIC));
    }
    if (IsBold( *pFont ))    // bold?
    {
        aString.AppendAscii( pDelim );
        aString += String(SmResId(RID_FONTBOLD));
    }

    return (aString);
}

void SmFontPickList::Insert(const Font &rFont)
{
    SmPickList::Insert((void *)&rFont);
}

void SmFontPickList::Update(const Font &rFont, const Font &rNewFont)
{
    SmPickList::Update((void *)&rFont, (void *)&rNewFont);
}

void SmFontPickList::Remove(const Font &rFont)
{
    SmPickList::Remove((void *)&rFont);
}

void SmFontPickList::ReadFrom(const SmFontDialog& rDialog)
{
    Insert(rDialog.GetFont());
}

void SmFontPickList::WriteTo(SmFontDialog& rDialog) const
{
    rDialog.SetFont(Get());
}

/**************************************************************************/

/**************************************************************************/

IMPL_LINK( SmFontPickListBox, SelectHdl, ListBox *, pListBox )
{
    USHORT  nPos;
    String  aString;

    nPos = GetSelectEntryPos();

    if (nPos != 0)
    {
        SmFontPickList::Insert(Get(nPos));
        aString = GetEntry(nPos);
        RemoveEntry(nPos);
        InsertEntry(aString, 0);
    }

    SelectEntryPos(0);

    return 0;
}

SmFontPickListBox::SmFontPickListBox(Window* pParent, WinBits nWinStyle, USHORT nMax) :
    SmFontPickList(nMax, nMax),
    ListBox(pParent, nWinStyle)
{
    SetSelectHdl(LINK(this, SmFontPickListBox, SelectHdl));
}

SmFontPickListBox::SmFontPickListBox(Window* pParent, const ResId& rResId, USHORT nMax) :
    SmFontPickList(nMax, nMax),
    ListBox(pParent, rResId)
{
    SetSelectHdl(LINK(this, SmFontPickListBox, SelectHdl));
}

SmFontPickListBox& SmFontPickListBox::operator=(const SmFontPickList& rList)
{
    USHORT nPos;

    *(SmFontPickList *)this = rList;

    for (nPos = 0; nPos < Count(); nPos++)
        InsertEntry(GetStringItem(GetPtr(nPos)), nPos);

    if (Count() > 0)
        SelectEntry(GetStringItem(GetPtr(0)));

    return *this;
}

void SmFontPickListBox::Insert(const Font &rFont)
{
    SmFontPickList::Insert(rFont);

    RemoveEntry(GetStringItem(GetPtr(0)));
    InsertEntry(GetStringItem(GetPtr(0)), 0);
    SelectEntry(GetStringItem(GetPtr(0)));

    while (GetEntryCount() > nSize)
        RemoveEntry(GetEntryCount() - 1);

    return;
}

void SmFontPickListBox::Update(const Font &rFont, const Font &rNewFont)
{
    SmFontPickList::Update(rFont, rNewFont);

    // ********************** hier fehlt noch was

    return;
}

void SmFontPickListBox::Remove(const Font &rFont)
{
    SmFontPickList::Remove(rFont);

    // ********************** hier fehlt noch was

    return;
}

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

BOOL IsItalic( const Font &rFont )
{
    FontItalic eItalic = rFont.GetItalic();
    // the code below leaves only _NONE and _DONTKNOW as not italic
    return eItalic == ITALIC_OBLIQUE  ||  eItalic == ITALIC_NORMAL;
}

BOOL IsBold( const Font &rFont )
{
    FontWeight eWeight = rFont.GetWeight();
    return eWeight != WEIGHT_DONTKNOW && eWeight > WEIGHT_NORMAL;
}

void SmFace::Impl_Init()
{
    SetSize( GetSize() );
    SetTransparent( TRUE );
    SetAlign( ALIGN_BASELINE );
    SetColor( COL_AUTO );
}

void SmFace::SetSize(const Size& rSize)
{
    Size  aSize (rSize);

    // check the requested size against minimum value
    static int __READONLY_DATA  nMinVal = SmPtsTo100th_mm(2);

    if (aSize.Height() < nMinVal)
        aSize.Height() = nMinVal;

    //! we don't force a maximum value here because this may prevent eg the
    //! parentheses in "left ( ... right )" from matching up with large
    //! bodies (eg stack{...} with many entries).
    //! Of course this is holds only if characters are used and not polygons.

    Font::SetSize(aSize);
}

long SmFace::GetBorderWidth() const
{
    if (nBorderWidth < 0)
        return GetDefaultBorderWidth();
    else
        return nBorderWidth;
}

SmFace & SmFace::operator = (const SmFace &rFace)
{
    Font::operator = (rFace);
    nBorderWidth = -1;
    return *this;
}

SmFace & operator *= (SmFace &rFace, const Fraction &rFrac)
    // scales the width and height of 'rFace' by 'rFrac' and returns a
    // reference to 'rFace'.
    // It's main use is to make scaling fonts look easier.
{   const Size &rFaceSize = rFace.GetSize();

    rFace.SetSize(Size(Fraction(rFaceSize.Width())  *= rFrac,
                       Fraction(rFaceSize.Height()) *= rFrac));
    return rFace;
}

<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "dll_test.hpp"

#include "dll/dense_layer.hpp"
#include "dll/scale_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE("dense/sgd/1", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t>,
        dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/2", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::TANH>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::TANH>>::layer_t>,
        dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/3", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t>,
        dll::momentum, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/4", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/5", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::TANH>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::TANH>>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/6", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::IDENTITY>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::IDENTITY>>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.4);
}

TEST_CASE("dense/sgd/7", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::RELU>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.4);
}

TEST_CASE("dense/sgd/8", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::SIGMOID>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/9", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::scale_layer_desc<1, 256>::layer_t,
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::SIGMOID>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}
<commit_msg>New test<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "dll_test.hpp"

#include "dll/dense_layer.hpp"
#include "dll/scale_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE("dense/sgd/1", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t>,
        dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/2", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::TANH>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::TANH>>::layer_t>,
        dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/3", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t>,
        dll::momentum, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/4", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/5", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::TANH>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::TANH>>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/6", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::IDENTITY>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::IDENTITY>>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.4);
}

TEST_CASE("dense/sgd/7", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::RELU>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.4);
}

TEST_CASE("dense/sgd/8", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::SIGMOID>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/9", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::scale_layer_desc<1, 256>::layer_t,
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::SIGMOID>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("dense/sgd/10", "[dense][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::RELU>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
        dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS groupingapi (1.65.6); FILE MERGED 2005/01/06 12:06:51 sab 1.65.6.4: RESYNC: (1.65-1.67); FILE MERGED 2004/12/21 12:29:30 sab 1.65.6.3: #i33817#, #i39212# 2004/09/08 17:01:05 sab 1.65.6.2: #i31477#; add additional properties 2004/09/03 18:03:27 sab 1.65.6.1: #i33817#; add grouping API<commit_after><|endoftext|>