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

#include "chrome/browser/media/media_stream_capture_indicator.h"

#include "base/bind.h"
#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/status_icons/status_icon.h"
#include "chrome/browser/status_icons/status_tray.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"

using content::BrowserThread;
using content::WebContents;

MediaStreamCaptureIndicator::TabEquals::TabEquals(
    int render_process_id,
    int render_view_id,
    content::MediaStreamDeviceType type)
        : render_process_id_(render_process_id),
          render_view_id_(render_view_id),
          type_(type) {}

MediaStreamCaptureIndicator::TabEquals::TabEquals(int render_process_id,
                                                  int render_view_id)
    : render_process_id_(render_process_id),
      render_view_id_(render_view_id),
      type_(content::MEDIA_STREAM_DEVICE_TYPE_NO_SERVICE) {}

bool MediaStreamCaptureIndicator::TabEquals::operator() (
    const MediaStreamCaptureIndicator::CaptureDeviceTab& tab) {
  if (type_ == content::MEDIA_STREAM_DEVICE_TYPE_NO_SERVICE) {
    return (render_process_id_ == tab.render_process_id &&
            render_view_id_ == tab.render_view_id);
  } else {
    return (render_process_id_ == tab.render_process_id &&
            render_view_id_ == tab.render_view_id &&
            type_ == tab.type);
  }
}

MediaStreamCaptureIndicator::MediaStreamCaptureIndicator()
    : status_icon_(NULL) {
}

MediaStreamCaptureIndicator::~MediaStreamCaptureIndicator() {
  // The user is responsible for cleaning up by closing all the opened devices.
  DCHECK(tabs_.empty());
}

bool MediaStreamCaptureIndicator::IsCommandIdChecked(
    int command_id) const {
  NOTIMPLEMENTED() << "There are no checked items in the MediaStream menu.";
  return false;
}

bool MediaStreamCaptureIndicator::IsCommandIdEnabled(
    int command_id) const {
  return command_id != IDC_MinimumLabelValue;
}

bool MediaStreamCaptureIndicator::GetAcceleratorForCommandId(
    int command_id, ui::Accelerator* accelerator) {
  // No accelerators for status icon context menu.
  return false;
}

void MediaStreamCaptureIndicator::ExecuteCommand(int command_id) {
  // TODO(xians) : Implement all the following execute command function.
  switch (command_id) {
    case IDC_MEDIA_CONTEXT_MEDIA_STREAM_CAPTURE_LIST_FIRST:
      break;
    default:
      NOTREACHED();
      break;
  }
}

void MediaStreamCaptureIndicator::CaptureDevicesOpened(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(!devices.empty());

  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&MediaStreamCaptureIndicator::DoDevicesOpenedOnUIThread,
                 this, render_process_id, render_view_id, devices));
}

void MediaStreamCaptureIndicator::CaptureDevicesClosed(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(!devices.empty());

  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&MediaStreamCaptureIndicator::DoDevicesClosedOnUIThread,
                 this, render_process_id, render_view_id, devices));
}

void MediaStreamCaptureIndicator::DoDevicesOpenedOnUIThread(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  CreateStatusTray();

  // If we don't have a status icon or one could not be created successfully,
  // then no need to continue.
  if (!status_icon_)
    return;

  AddCaptureDeviceTab(render_process_id, render_view_id, devices);

  ShowBalloon(render_process_id, render_view_id, devices);
}

void MediaStreamCaptureIndicator::DoDevicesClosedOnUIThread(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!status_icon_)
    return;

  DCHECK(!tabs_.empty());
  RemoveCaptureDeviceTab(render_process_id, render_view_id, devices);

  if (tabs_.empty())
    Hide();
}

void MediaStreamCaptureIndicator::CreateStatusTray() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (status_icon_)
    return;

  // If there is no browser process, we should not create the status tray.
  if (!g_browser_process)
    return;

  StatusTray* status_tray = g_browser_process->status_tray();
  if (!status_tray)
    return;

  status_icon_ = status_tray->CreateStatusIcon();

  status_icon_->SetToolTip(l10n_util::GetStringFUTF16(
      IDS_MEDIA_STREAM_STATUS_TRAY_TOOLTIP,
      l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));

  EnsureStatusTrayIcon();
  DCHECK(!icon_image_.empty());

  status_icon_->SetImage(icon_image_);
}

void MediaStreamCaptureIndicator::EnsureStatusTrayIcon() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (icon_image_.empty()) {
    icon_image_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
        IDR_MEDIA_STREAM_CAPTURE_LED);
  }
}

void MediaStreamCaptureIndicator::ShowBalloon(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  string16 title = l10n_util::GetStringFUTF16(
      IDS_MEDIA_STREAM_STATUS_TRAY_BALLOON_TITLE,
      l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));

  int message_id = IDS_MEDIA_STREAM_STATUS_TRAY_BALLOON_BODY_AUDIO_AND_VIDEO;
  if (devices.size() == 1) {
    if (devices.front().type == content::MEDIA_STREAM_DEVICE_TYPE_AUDIO_CAPTURE)
      message_id = IDS_MEDIA_STREAM_STATUS_TRAY_BALLOON_BODY_AUDIO_ONLY;
    else
      message_id = IDS_MEDIA_STREAM_STATUS_TRAY_BALLOON_BODY_VIDEO_ONLY;
  }

  string16 message = l10n_util::GetStringFUTF16(
      message_id, GetTitle(render_process_id, render_view_id));

  status_icon_->DisplayBalloon(icon_image_, title, message);
}

void MediaStreamCaptureIndicator::Hide() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!status_icon_)
    return;

  // If there is no browser process, we should not do anything.
  if (!g_browser_process)
    return;

  StatusTray* status_tray = g_browser_process->status_tray();
  if (status_tray != NULL) {
    status_tray->RemoveStatusIcon(status_icon_);
    status_icon_ = NULL;
  }
}

void MediaStreamCaptureIndicator::UpdateStatusTrayIconContextMenu() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  scoped_ptr<ui::SimpleMenuModel> menu(new ui::SimpleMenuModel(this));

  for (CaptureDeviceTabList::iterator iter = tabs_.begin();
       iter != tabs_.end();  ++iter) {
    // Search backward to see if the tab has been added.
    CaptureDeviceTabList::iterator iter_backward = std::find_if(
        tabs_.begin(), iter, TabEquals(iter->render_process_id,
                                       iter->render_view_id));
    // Do nothing if the tab has been added to the menu.
    if (iter_backward != iter)
      continue;

    string16 tab_title = GetTitle(iter->render_process_id,
                                  iter->render_view_id);
    // The tab has gone away.
    if (tab_title.empty())
      continue;

    string16 message = l10n_util::GetStringFUTF16(
        IDS_MEDIA_STREAM_STATUS_TRAY_MENU_ITEM, tab_title);
    menu->AddItem(IDC_MEDIA_CONTEXT_MEDIA_STREAM_CAPTURE_LIST_FIRST, message);
    menu->AddSeparator();
  }

  // The icon will take the ownership of the passed context menu.
  status_icon_->SetContextMenu(menu.release());
}

void MediaStreamCaptureIndicator::AddCaptureDeviceTab(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  content::MediaStreamDevices::const_iterator dev = devices.begin();
  for (; dev != devices.end(); ++dev) {
    DCHECK(dev->type == content::MEDIA_STREAM_DEVICE_TYPE_AUDIO_CAPTURE ||
           dev->type == content::MEDIA_STREAM_DEVICE_TYPE_VIDEO_CAPTURE);
    tabs_.push_back(CaptureDeviceTab(render_process_id,
                                     render_view_id,
                                     dev->type));
  }

  UpdateStatusTrayIconContextMenu();
}

void MediaStreamCaptureIndicator::RemoveCaptureDeviceTab(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  content::MediaStreamDevices::const_iterator dev = devices.begin();
  for (; dev != devices.end(); ++dev) {
    CaptureDeviceTabList::iterator iter = std::find_if(
        tabs_.begin(), tabs_.end(), TabEquals(render_process_id,
                                              render_view_id,
                                              dev->type));
    if (iter != tabs_.end()) {
      tabs_.erase(iter);
    } else {
      DLOG(ERROR) << "Failed to find MediaStream host "
                  << GetTitle(render_process_id, render_view_id)
                  << " for device " << dev->name
                  << " for type " << dev->type;
    }
  }

  if (!tabs_.empty())
    UpdateStatusTrayIconContextMenu();
}

string16 MediaStreamCaptureIndicator::GetTitle(int render_process_id,
                                               int render_view_id) const {
  WebContents* tab_content = tab_util::GetWebContentsByID(
      render_process_id, render_view_id);
  if (!tab_content)
    return NULL;

  string16 tab_title = tab_content->GetTitle();
  if (tab_title.empty()) {
    GURL url = tab_content->GetURL();
    tab_title = UTF8ToUTF16(url.spec());
    // Force URL to be LTR.
    tab_title = base::i18n::GetDisplayStringInLTRDirectionality(tab_title);
  } else {
    // Sets the title explicitly as LTR format. Please look at the comments in
    // TaskManagerTabContentsResource::GetTitle() for the reasons of doing this.
    base::i18n::AdjustStringForLocaleDirection(&tab_title);
  }

  return tab_title;
}
<commit_msg>Simple fix for a crash after last night's checkin. When |tab_content| was NULL we tried to return NULL as string16, which string16 does not like.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/media/media_stream_capture_indicator.h"

#include "base/bind.h"
#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/status_icons/status_icon.h"
#include "chrome/browser/status_icons/status_tray.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"

using content::BrowserThread;
using content::WebContents;

MediaStreamCaptureIndicator::TabEquals::TabEquals(
    int render_process_id,
    int render_view_id,
    content::MediaStreamDeviceType type)
        : render_process_id_(render_process_id),
          render_view_id_(render_view_id),
          type_(type) {}

MediaStreamCaptureIndicator::TabEquals::TabEquals(int render_process_id,
                                                  int render_view_id)
    : render_process_id_(render_process_id),
      render_view_id_(render_view_id),
      type_(content::MEDIA_STREAM_DEVICE_TYPE_NO_SERVICE) {}

bool MediaStreamCaptureIndicator::TabEquals::operator() (
    const MediaStreamCaptureIndicator::CaptureDeviceTab& tab) {
  if (type_ == content::MEDIA_STREAM_DEVICE_TYPE_NO_SERVICE) {
    return (render_process_id_ == tab.render_process_id &&
            render_view_id_ == tab.render_view_id);
  } else {
    return (render_process_id_ == tab.render_process_id &&
            render_view_id_ == tab.render_view_id &&
            type_ == tab.type);
  }
}

MediaStreamCaptureIndicator::MediaStreamCaptureIndicator()
    : status_icon_(NULL) {
}

MediaStreamCaptureIndicator::~MediaStreamCaptureIndicator() {
  // The user is responsible for cleaning up by closing all the opened devices.
  DCHECK(tabs_.empty());
}

bool MediaStreamCaptureIndicator::IsCommandIdChecked(
    int command_id) const {
  NOTIMPLEMENTED() << "There are no checked items in the MediaStream menu.";
  return false;
}

bool MediaStreamCaptureIndicator::IsCommandIdEnabled(
    int command_id) const {
  return command_id != IDC_MinimumLabelValue;
}

bool MediaStreamCaptureIndicator::GetAcceleratorForCommandId(
    int command_id, ui::Accelerator* accelerator) {
  // No accelerators for status icon context menu.
  return false;
}

void MediaStreamCaptureIndicator::ExecuteCommand(int command_id) {
  // TODO(xians) : Implement all the following execute command function.
  switch (command_id) {
    case IDC_MEDIA_CONTEXT_MEDIA_STREAM_CAPTURE_LIST_FIRST:
      break;
    default:
      NOTREACHED();
      break;
  }
}

void MediaStreamCaptureIndicator::CaptureDevicesOpened(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(!devices.empty());

  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&MediaStreamCaptureIndicator::DoDevicesOpenedOnUIThread,
                 this, render_process_id, render_view_id, devices));
}

void MediaStreamCaptureIndicator::CaptureDevicesClosed(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(!devices.empty());

  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&MediaStreamCaptureIndicator::DoDevicesClosedOnUIThread,
                 this, render_process_id, render_view_id, devices));
}

void MediaStreamCaptureIndicator::DoDevicesOpenedOnUIThread(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  CreateStatusTray();

  // If we don't have a status icon or one could not be created successfully,
  // then no need to continue.
  if (!status_icon_)
    return;

  AddCaptureDeviceTab(render_process_id, render_view_id, devices);

  ShowBalloon(render_process_id, render_view_id, devices);
}

void MediaStreamCaptureIndicator::DoDevicesClosedOnUIThread(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!status_icon_)
    return;

  DCHECK(!tabs_.empty());
  RemoveCaptureDeviceTab(render_process_id, render_view_id, devices);

  if (tabs_.empty())
    Hide();
}

void MediaStreamCaptureIndicator::CreateStatusTray() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (status_icon_)
    return;

  // If there is no browser process, we should not create the status tray.
  if (!g_browser_process)
    return;

  StatusTray* status_tray = g_browser_process->status_tray();
  if (!status_tray)
    return;

  status_icon_ = status_tray->CreateStatusIcon();

  status_icon_->SetToolTip(l10n_util::GetStringFUTF16(
      IDS_MEDIA_STREAM_STATUS_TRAY_TOOLTIP,
      l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));

  EnsureStatusTrayIcon();
  DCHECK(!icon_image_.empty());

  status_icon_->SetImage(icon_image_);
}

void MediaStreamCaptureIndicator::EnsureStatusTrayIcon() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (icon_image_.empty()) {
    icon_image_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
        IDR_MEDIA_STREAM_CAPTURE_LED);
  }
}

void MediaStreamCaptureIndicator::ShowBalloon(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  string16 title = l10n_util::GetStringFUTF16(
      IDS_MEDIA_STREAM_STATUS_TRAY_BALLOON_TITLE,
      l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));

  int message_id = IDS_MEDIA_STREAM_STATUS_TRAY_BALLOON_BODY_AUDIO_AND_VIDEO;
  if (devices.size() == 1) {
    if (devices.front().type == content::MEDIA_STREAM_DEVICE_TYPE_AUDIO_CAPTURE)
      message_id = IDS_MEDIA_STREAM_STATUS_TRAY_BALLOON_BODY_AUDIO_ONLY;
    else
      message_id = IDS_MEDIA_STREAM_STATUS_TRAY_BALLOON_BODY_VIDEO_ONLY;
  }

  string16 message = l10n_util::GetStringFUTF16(
      message_id, GetTitle(render_process_id, render_view_id));

  status_icon_->DisplayBalloon(icon_image_, title, message);
}

void MediaStreamCaptureIndicator::Hide() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!status_icon_)
    return;

  // If there is no browser process, we should not do anything.
  if (!g_browser_process)
    return;

  StatusTray* status_tray = g_browser_process->status_tray();
  if (status_tray != NULL) {
    status_tray->RemoveStatusIcon(status_icon_);
    status_icon_ = NULL;
  }
}

void MediaStreamCaptureIndicator::UpdateStatusTrayIconContextMenu() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  scoped_ptr<ui::SimpleMenuModel> menu(new ui::SimpleMenuModel(this));

  for (CaptureDeviceTabList::iterator iter = tabs_.begin();
       iter != tabs_.end();  ++iter) {
    // Search backward to see if the tab has been added.
    CaptureDeviceTabList::iterator iter_backward = std::find_if(
        tabs_.begin(), iter, TabEquals(iter->render_process_id,
                                       iter->render_view_id));
    // Do nothing if the tab has been added to the menu.
    if (iter_backward != iter)
      continue;

    string16 tab_title = GetTitle(iter->render_process_id,
                                  iter->render_view_id);
    // The tab has gone away.
    if (tab_title.empty())
      continue;

    string16 message = l10n_util::GetStringFUTF16(
        IDS_MEDIA_STREAM_STATUS_TRAY_MENU_ITEM, tab_title);
    menu->AddItem(IDC_MEDIA_CONTEXT_MEDIA_STREAM_CAPTURE_LIST_FIRST, message);
    menu->AddSeparator();
  }

  // The icon will take the ownership of the passed context menu.
  status_icon_->SetContextMenu(menu.release());
}

void MediaStreamCaptureIndicator::AddCaptureDeviceTab(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  content::MediaStreamDevices::const_iterator dev = devices.begin();
  for (; dev != devices.end(); ++dev) {
    DCHECK(dev->type == content::MEDIA_STREAM_DEVICE_TYPE_AUDIO_CAPTURE ||
           dev->type == content::MEDIA_STREAM_DEVICE_TYPE_VIDEO_CAPTURE);
    tabs_.push_back(CaptureDeviceTab(render_process_id,
                                     render_view_id,
                                     dev->type));
  }

  UpdateStatusTrayIconContextMenu();
}

void MediaStreamCaptureIndicator::RemoveCaptureDeviceTab(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  content::MediaStreamDevices::const_iterator dev = devices.begin();
  for (; dev != devices.end(); ++dev) {
    CaptureDeviceTabList::iterator iter = std::find_if(
        tabs_.begin(), tabs_.end(), TabEquals(render_process_id,
                                              render_view_id,
                                              dev->type));
    if (iter != tabs_.end()) {
      tabs_.erase(iter);
    } else {
      DLOG(ERROR) << "Failed to find MediaStream host "
                  << GetTitle(render_process_id, render_view_id)
                  << " for device " << dev->name
                  << " for type " << dev->type;
    }
  }

  if (!tabs_.empty())
    UpdateStatusTrayIconContextMenu();
}

string16 MediaStreamCaptureIndicator::GetTitle(int render_process_id,
                                               int render_view_id) const {
  WebContents* tab_content = tab_util::GetWebContentsByID(
      render_process_id, render_view_id);
  if (!tab_content)
    return string16();

  string16 tab_title = tab_content->GetTitle();
  if (tab_title.empty()) {
    GURL url = tab_content->GetURL();
    tab_title = UTF8ToUTF16(url.spec());
    // Force URL to be LTR.
    tab_title = base::i18n::GetDisplayStringInLTRDirectionality(tab_title);
  } else {
    // Sets the title explicitly as LTR format. Please look at the comments in
    // TaskManagerTabContentsResource::GetTitle() for the reasons of doing this.
    base::i18n::AdjustStringForLocaleDirection(&tab_title);
  }

  return tab_title;
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkExtractSelection.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkExtractSelection.h"

#include "vtkDataSet.h"
#include "vtkExtractCells.h"
#include "vtkIdList.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkSelection.h"
#include "vtkUnstructuredGrid.h"

vtkCxxRevisionMacro(vtkExtractSelection, "1.1");
vtkStandardNewMacro(vtkExtractSelection);
vtkCxxSetObjectMacro(vtkExtractSelection,
                     Selection,vtkSelection);

//----------------------------------------------------------------------------
vtkExtractSelection::vtkExtractSelection()
{
  this->Selection = 0;
  this->ExtractFilter = vtkExtractCells::New();
}

//----------------------------------------------------------------------------
vtkExtractSelection::~vtkExtractSelection()
{
  this->SetSelection(NULL);
  this->ExtractFilter->Delete();
}

//----------------------------------------------------------------------------
// Overload standard modified time function. If selection is modified,
// then this object is modified as well.
unsigned long vtkExtractSelection::GetMTime()
{
  unsigned long mTime=this->MTime.GetMTime();
  unsigned long selTime;

  if ( this->Selection != NULL )
    {
    selTime = this->Selection->GetMTime();
    mTime = ( selTime > mTime ? selTime : mTime );
    }

  return mTime;
}

//----------------------------------------------------------------------------
int vtkExtractSelection::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // get the input and ouptut
  vtkDataSet *input = vtkDataSet::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));
  vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  vtkDebugMacro(<< "Extracting from dataset");

  vtkSelection* sel = this->Selection;
  if ( ! sel )
    {
    vtkErrorMacro(<<"No selection specified");
    return 1;
    }

  if (!sel->GetProperties()->Has(vtkSelection::CONTENT_TYPE()) ||
      sel->GetProperties()->Get(vtkSelection::CONTENT_TYPE()) != vtkSelection::CELL_IDS)
    {
    return 1;
    }

  vtkIdTypeArray* idArray =
    vtkIdTypeArray::SafeDownCast(sel->GetSelectionList());

  if (!idArray)
    {
    return 1;
    }

  vtkIdType numCells =
    idArray->GetNumberOfComponents()*idArray->GetNumberOfTuples();

  if (numCells == 0)
    {
    return 1;
    }

  vtkIdList* ids = vtkIdList::New();
  vtkIdType* idsPtr = ids->WritePointer(0, numCells);

  memcpy(idsPtr, idArray->GetPointer(0), numCells*sizeof(vtkIdType));

  this->ExtractFilter->SetCellList(ids);
  ids->Delete();

  vtkDataSet* inputCopy = input->NewInstance();
  inputCopy->ShallowCopy(input);

  this->ExtractFilter->SetInput(input);

  this->ExtractFilter->Update();

  vtkUnstructuredGrid* ecOutput = vtkUnstructuredGrid::SafeDownCast(
    this->ExtractFilter->GetOutputDataObject(0));
  output->ShallowCopy(ecOutput);
  ecOutput->Initialize();

  return 1;
}

//----------------------------------------------------------------------------
void vtkExtractSelection::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Selection: ";
  if (this->Selection)
    {
    this->Selection->PrintSelf(os, indent.GetNextIndent());
    }
  else
    {
    os << "(none)" << endl;
    }
}

//----------------------------------------------------------------------------
int vtkExtractSelection::FillInputPortInformation(
  int vtkNotUsed(port), vtkInformation* info)
{
  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
  return 1;
}
<commit_msg>BUG: Fixed leak<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkExtractSelection.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkExtractSelection.h"

#include "vtkDataSet.h"
#include "vtkExtractCells.h"
#include "vtkIdList.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkSelection.h"
#include "vtkUnstructuredGrid.h"

vtkCxxRevisionMacro(vtkExtractSelection, "1.2");
vtkStandardNewMacro(vtkExtractSelection);
vtkCxxSetObjectMacro(vtkExtractSelection,
                     Selection,vtkSelection);

//----------------------------------------------------------------------------
vtkExtractSelection::vtkExtractSelection()
{
  this->Selection = 0;
  this->ExtractFilter = vtkExtractCells::New();
}

//----------------------------------------------------------------------------
vtkExtractSelection::~vtkExtractSelection()
{
  this->SetSelection(NULL);
  this->ExtractFilter->Delete();
}

//----------------------------------------------------------------------------
// Overload standard modified time function. If selection is modified,
// then this object is modified as well.
unsigned long vtkExtractSelection::GetMTime()
{
  unsigned long mTime=this->MTime.GetMTime();
  unsigned long selTime;

  if ( this->Selection != NULL )
    {
    selTime = this->Selection->GetMTime();
    mTime = ( selTime > mTime ? selTime : mTime );
    }

  return mTime;
}

//----------------------------------------------------------------------------
int vtkExtractSelection::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // get the input and ouptut
  vtkDataSet *input = vtkDataSet::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));
  vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  vtkDebugMacro(<< "Extracting from dataset");

  vtkSelection* sel = this->Selection;
  if ( ! sel )
    {
    vtkErrorMacro(<<"No selection specified");
    return 1;
    }

  if (!sel->GetProperties()->Has(vtkSelection::CONTENT_TYPE()) ||
      sel->GetProperties()->Get(vtkSelection::CONTENT_TYPE()) != vtkSelection::CELL_IDS)
    {
    return 1;
    }

  vtkIdTypeArray* idArray =
    vtkIdTypeArray::SafeDownCast(sel->GetSelectionList());

  if (!idArray)
    {
    return 1;
    }

  vtkIdType numCells =
    idArray->GetNumberOfComponents()*idArray->GetNumberOfTuples();

  if (numCells == 0)
    {
    return 1;
    }

  vtkIdList* ids = vtkIdList::New();
  vtkIdType* idsPtr = ids->WritePointer(0, numCells);

  memcpy(idsPtr, idArray->GetPointer(0), numCells*sizeof(vtkIdType));

  this->ExtractFilter->SetCellList(ids);
  ids->Delete();

  vtkDataSet* inputCopy = input->NewInstance();
  inputCopy->ShallowCopy(input);
  this->ExtractFilter->SetInput(inputCopy);
  inputCopy->Delete();

  this->ExtractFilter->Update();

  vtkUnstructuredGrid* ecOutput = vtkUnstructuredGrid::SafeDownCast(
    this->ExtractFilter->GetOutputDataObject(0));
  output->ShallowCopy(ecOutput);
  ecOutput->Initialize();

  return 1;
}

//----------------------------------------------------------------------------
void vtkExtractSelection::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Selection: ";
  if (this->Selection)
    {
    this->Selection->PrintSelf(os, indent.GetNextIndent());
    }
  else
    {
    os << "(none)" << endl;
    }
}

//----------------------------------------------------------------------------
int vtkExtractSelection::FillInputPortInformation(
  int vtkNotUsed(port), vtkInformation* info)
{
  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
  return 1;
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "SimpleRollbackTest.h"

#include <activemq/util/CMSListener.h>
#include <activemq/util/IntegrationCommon.h>
#include <activemq/exceptions/ActiveMQException.h>
#include <decaf/lang/Thread.h>
#include <decaf/util/UUID.h>

#include <sstream>

using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::test;
using namespace activemq::util;
using namespace activemq::exceptions;
using namespace decaf::lang;
using namespace decaf::util;

////////////////////////////////////////////////////////////////////////////////
SimpleRollbackTest::SimpleRollbackTest() {
}

////////////////////////////////////////////////////////////////////////////////
SimpleRollbackTest::~SimpleRollbackTest() {
}

////////////////////////////////////////////////////////////////////////////////
void SimpleRollbackTest::testRollbacks() {

    try {

        // Create CMS Object for Comms
        cms::Session* session( cmsProvider->getSession() );

        CMSListener listener( session );

        cms::MessageConsumer* consumer = cmsProvider->getConsumer();
        consumer->setMessageListener( &listener );
        cms::MessageProducer* producer = cmsProvider->getProducer();
        producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

        auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage() );

        for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {
            ostringstream lcStream;
            lcStream << "SimpleTest - Message #" << i << ends;
            txtMessage->setText( lcStream.str() );
            producer->send( txtMessage.get() );
        }

        session->commit();
        Thread::sleep( 50 );

        // Wait for the messages to get here
        listener.asyncWaitForMessages( IntegrationCommon::defaultMsgCount );
        unsigned int numReceived = listener.getNumReceived();
        CPPUNIT_ASSERT( numReceived == IntegrationCommon::defaultMsgCount );

        for( unsigned int i = 0; i < 5; ++i ) {
            ostringstream lcStream;
            lcStream << "SimpleTest - Message #" << i << ends;
            txtMessage->setText( lcStream.str() );
            producer->send( txtMessage.get() );
        }

        listener.reset();
        session->rollback();
        Thread::sleep( 50 );

        listener.reset();
        txtMessage->setText( "SimpleTest - Message after Rollback" );
        producer->send( txtMessage.get() );
        session->commit();

        // Wait for the messages to get here
        listener.asyncWaitForMessages( 1 );
        CPPUNIT_ASSERT( listener.getNumReceived() == 1 );

        listener.reset();
        txtMessage->setText( "SimpleTest - Message after Rollback" );
        producer->send( txtMessage.get() );
        session->commit();

        // Wait for the messages to get here
        listener.asyncWaitForMessages( 1 );
        CPPUNIT_ASSERT( listener.getNumReceived() == 1 );
        session->commit();

    } catch( std::exception& ex ) {
        std::cout << ex.what() << std::endl;
        throw ex;
    }
}
<commit_msg>Add a missing commit call.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "SimpleRollbackTest.h"

#include <activemq/util/CMSListener.h>
#include <activemq/util/IntegrationCommon.h>
#include <activemq/exceptions/ActiveMQException.h>
#include <decaf/lang/Thread.h>
#include <decaf/util/UUID.h>

#include <sstream>

using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::test;
using namespace activemq::util;
using namespace activemq::exceptions;
using namespace decaf::lang;
using namespace decaf::util;

////////////////////////////////////////////////////////////////////////////////
SimpleRollbackTest::SimpleRollbackTest() {
}

////////////////////////////////////////////////////////////////////////////////
SimpleRollbackTest::~SimpleRollbackTest() {
}

////////////////////////////////////////////////////////////////////////////////
void SimpleRollbackTest::testRollbacks() {

    try {

        // Create CMS Object for Comms
        cms::Session* session( cmsProvider->getSession() );

        CMSListener listener( session );

        cms::MessageConsumer* consumer = cmsProvider->getConsumer();
        consumer->setMessageListener( &listener );
        cms::MessageProducer* producer = cmsProvider->getProducer();
        producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

        auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage() );

        for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {
            ostringstream lcStream;
            lcStream << "SimpleTest - Message #" << i << ends;
            txtMessage->setText( lcStream.str() );
            producer->send( txtMessage.get() );
        }

        session->commit();
        Thread::sleep( 50 );

        // Wait for the messages to get here
        listener.asyncWaitForMessages( IntegrationCommon::defaultMsgCount );
        unsigned int numReceived = listener.getNumReceived();
        CPPUNIT_ASSERT( numReceived == IntegrationCommon::defaultMsgCount );

        session->commit();
        Thread::sleep( 50 );

        for( unsigned int i = 0; i < 5; ++i ) {
            ostringstream lcStream;
            lcStream << "SimpleTest - Message #" << i << ends;
            txtMessage->setText( lcStream.str() );
            producer->send( txtMessage.get() );
        }

        listener.reset();
        session->rollback();
        Thread::sleep( 50 );

        listener.reset();
        txtMessage->setText( "SimpleTest - Message after Rollback" );
        producer->send( txtMessage.get() );
        session->commit();

        // Wait for the messages to get here
        listener.asyncWaitForMessages( 1 );
        CPPUNIT_ASSERT( listener.getNumReceived() == 1 );

        listener.reset();
        txtMessage->setText( "SimpleTest - Message after Rollback" );
        producer->send( txtMessage.get() );
        session->commit();

        // Wait for the messages to get here
        listener.asyncWaitForMessages( 1 );
        CPPUNIT_ASSERT( listener.getNumReceived() == 1 );
        session->commit();

    } catch( std::exception& ex ) {
        std::cout << ex.what() << std::endl;
        throw ex;
    }
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <omp.h>
#include <random>
#include <stdio.h>
#include <string>
#include <time.h>

#include "Neural_Networks.h"

using namespace std;

void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {
	ifstream file(training_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
	}

	file.open(training_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
	}

	file.open(test_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
	}

	file.open(test_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
	}
}

int main() {
	bool *time_mask;

	int batch_size = 128;
	int epochs = 100;
	int number_threads = 6;
	int number_training = 60000;
	int number_test = 10000;
	int number_nodes[] = { 784, 10 };
	int time_step = 28;

	float **x_data = new float*[number_training + number_test];
	float **y_data = new float*[number_training + number_test];
	float **x_train = x_data;
	float **y_train = y_data;
	float **x_test = &x_data[number_training];
	float **y_test = &y_data[number_training];

	double decay = 0.000001;
	double learning_rate = 0.05;

	string path;

	Neural_Networks NN = Neural_Networks();

	cout << "path where MNIST handwritten digits dataset is : ";
	getline(cin, path);

	for (int h = 0; h < number_training + number_test; h++) {
		x_data[h] = new float[number_nodes[0]];
		memset(y_data[h] = new float[time_step * number_nodes[1]], 0, sizeof(float) * time_step * number_nodes[1]);
	}
	Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, x_data, y_data);
	omp_set_num_threads(number_threads);

	srand(2);

	for (int h = 0; h < number_training + number_test; h++) {
		memcpy(&y_data[h][(time_step - 1) * number_nodes[1]], y_data[h], sizeof(float) * number_nodes[1]);
	}
	memset(time_mask = new bool[time_step], 0, time_step);
	time_mask[time_step - 1] = true;

	NN.Add(Layer(time_step, number_nodes[0] / time_step));
	NN.Add(RNN(time_step, 128))->Activation(Activation::relu);
	NN.Add(Layer(time_step, number_nodes[1]))->Activation(Activation::softmax)->Time_Mask(time_mask, time_step);

	NN.Connect(1, 0, "W");
	NN.Connect(1, 1, "W,recurrent");
	NN.Connect(2, 1, "W");

	NN.Compile(Loss::cross_entropy, new Optimizer(SGD(learning_rate, decay)));

	for (int e = 0, time = clock(); e < epochs; e++) {
		int score[2] = { 0, };

		float **_input = new float*[batch_size];
		float **output = new float*[batch_size];

		double loss[2] = { NN.Fit(NN.Shuffle(x_train, number_training), NN.Shuffle(y_train, number_training), number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };

		for (int h = 0; h < batch_size; h++) {
			output[h] = new float[time_step * number_nodes[1]];
		}
		for (int h = 0, i = 0; i < number_training + number_test; i++) {
			_input[h] = x_data[i];

			if (++h == batch_size || i == number_training + number_test - 1) {
				NN.Predict(_input, output, h);

				for (int argmax, index = i - h + 1; --h >= 0;) {
					double max = 0;

					for (int j = 0, offset = (time_step - 1) * number_nodes[1]; j < number_nodes[1]; j++) {
						if (j == 0 || max < output[h][offset + j]) {
							max = output[h][argmax = offset + j];
						}
					}
					score[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];
				}
				h = 0;
			}
		}
		printf("loss: %.4f / %.4f	accuracy: %.4f / %.4f	step %d  %.2f sec\n", loss[0], loss[1], 1.0 * score[0] / number_training, 1.0 * score[1] / number_test, e + 1, (double)(clock() - time) / CLOCKS_PER_SEC);

		for (int h = 0; h < batch_size; h++) {
			delete[] output[h];
		}
		delete[] _input;
		delete[] output;
	}

	for (int i = 0; i < number_training + number_test; i++) {
		delete[] x_data[i];
		delete[] y_data[i];
	}
	delete[] x_data;
	delete[] y_data;
}<commit_msg>Update main.cpp<commit_after>#include <fstream>
#include <iostream>
#include <omp.h>
#include <random>
#include <stdio.h>
#include <string>
#include <time.h>

#include "Neural_Networks.h"

using namespace std;

void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {
	ifstream file(training_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
	}

	file.open(training_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
	}

	file.open(test_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
	}

	file.open(test_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
	}
}

int main() {
	bool *time_mask;

	int batch_size = 128;
	int epochs = 100;
	int number_threads = 6;
	int number_training = 60000;
	int number_test = 10000;
	int number_nodes[] = { 784, 10 };
	int time_step = 28;

	float **x_data = new float*[number_training + number_test];
	float **y_data = new float*[number_training + number_test];
	float **x_train = x_data;
	float **y_train = y_data;
	float **x_test = &x_data[number_training];
	float **y_test = &y_data[number_training];

	double decay = 0.000001;
	double learning_rate = 0.05;

	string path;

	Neural_Networks NN = Neural_Networks();

	cout << "path where MNIST handwritten digits dataset is : ";
	getline(cin, path);

	for (int h = 0; h < number_training + number_test; h++) {
		x_data[h] = new float[number_nodes[0]];
		memset(y_data[h] = new float[time_step * number_nodes[1]], 0, sizeof(float) * time_step * number_nodes[1]);
	}
	Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, x_data, y_data);
	omp_set_num_threads(number_threads);

	srand(2);

	for (int h = 0; h < number_training + number_test; h++) {
		memcpy(&y_data[h][(time_step - 1) * number_nodes[1]], y_data[h], sizeof(float) * number_nodes[1]);
	}
	memset(time_mask = new bool[time_step], 0, time_step);
	time_mask[time_step - 1] = true;

	NN.Add(Layer(time_step, number_nodes[0] / time_step));
	NN.Add(RNN(time_step, 128))->Activation(Activation::relu);
	NN.Add(Layer(time_step, number_nodes[1]))->Activation(Activation::softmax)->Time_Mask(time_mask);

	NN.Connect(1, 0, "W");
	NN.Connect(1, 1, "W,recurrent");
	NN.Connect(2, 1, "W");

	NN.Compile(Loss::cross_entropy, new Optimizer(SGD(learning_rate, decay)));

	for (int e = 0, time = clock(); e < epochs; e++) {
		int score[2] = { 0, };

		float **_input = new float*[batch_size];
		float **output = new float*[batch_size];

		double loss[2] = { NN.Fit(NN.Shuffle(x_train, number_training), NN.Shuffle(y_train, number_training), number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };

		for (int h = 0; h < batch_size; h++) {
			output[h] = new float[time_step * number_nodes[1]];
		}
		for (int h = 0, i = 0; i < number_training + number_test; i++) {
			_input[h] = x_data[i];

			if (++h == batch_size || i == number_training + number_test - 1) {
				NN.Predict(_input, output, h);

				for (int argmax, index = i - h + 1; --h >= 0;) {
					double max = 0;

					for (int j = 0, offset = (time_step - 1) * number_nodes[1]; j < number_nodes[1]; j++) {
						if (j == 0 || max < output[h][offset + j]) {
							max = output[h][argmax = offset + j];
						}
					}
					score[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];
				}
				h = 0;
			}
		}
		printf("loss: %.4f / %.4f	accuracy: %.4f / %.4f	step %d  %.2f sec\n", loss[0], loss[1], 1.0 * score[0] / number_training, 1.0 * score[1] / number_test, e + 1, (double)(clock() - time) / CLOCKS_PER_SEC);

		for (int h = 0; h < batch_size; h++) {
			delete[] output[h];
		}
		delete[] _input;
		delete[] output;
	}

	for (int i = 0; i < number_training + number_test; i++) {
		delete[] x_data[i];
		delete[] y_data[i];
	}
	delete[] x_data;
	delete[] y_data;
}
<|endoftext|>


<commit_before>#include "Module/Interleaver/LTE/Interleaver_LTE.hpp"
#include "Module/Interleaver/CCSDS/Interleaver_CCSDS.hpp"
#include "Module/Interleaver/NO/Interleaver_NO.hpp"
#include "Module/Interleaver/Columns/Interleaver_columns.hpp"
#include "Module/Interleaver/Golden/Interleaver_golden.hpp"
#include "Module/Interleaver/Random/Interleaver_random.hpp"
#include "Module/Interleaver/User/Interleaver_user.hpp"

#include "Factory_interleaver.hpp"

using namespace aff3ct::module;
using namespace aff3ct::tools;

template <typename T>
Interleaver<T>* Factory_interleaver<T>
::build(const parameters &params, const int &size, const int seed)
{
	Interleaver<T> *interleaver = nullptr;

	// build the interleaver
	if (params.interleaver.type == "LTE")
		interleaver = new Interleaver_LTE<T>(size);
	else if (params.interleaver.type == "CCSDS")
		interleaver = new Interleaver_CCSDS<T>(size);
	else if (params.interleaver.type == "RANDOM")
		interleaver = new Interleaver_random<T>(size, seed);
	else if (params.interleaver.type == "COLUMNS")
		interleaver = new Interleaver_columns<T>(size, params.interleaver.n_cols, seed);
	else if (params.interleaver.type == "GOLDEN")
		interleaver = new Interleaver_golden<T>(size);
	else if (params.interleaver.type == "USER")
		interleaver = new Interleaver_user<T>(size, params.interleaver.path);
	else if (params.interleaver.type == "NO")
		interleaver = new Interleaver_NO<T>(size);

	return interleaver;
}

// ==================================================================================== explicit template instantiation
template struct aff3ct::tools::Factory_interleaver<short>;
template struct aff3ct::tools::Factory_interleaver<int>;
template struct aff3ct::tools::Factory_interleaver<long long>;
// ==================================================================================== explicit template instantiation
<commit_msg>Pass the seed to the Golden interleaver in the factory.<commit_after>#include "Module/Interleaver/LTE/Interleaver_LTE.hpp"
#include "Module/Interleaver/CCSDS/Interleaver_CCSDS.hpp"
#include "Module/Interleaver/NO/Interleaver_NO.hpp"
#include "Module/Interleaver/Columns/Interleaver_columns.hpp"
#include "Module/Interleaver/Golden/Interleaver_golden.hpp"
#include "Module/Interleaver/Random/Interleaver_random.hpp"
#include "Module/Interleaver/User/Interleaver_user.hpp"

#include "Factory_interleaver.hpp"

using namespace aff3ct::module;
using namespace aff3ct::tools;

template <typename T>
Interleaver<T>* Factory_interleaver<T>
::build(const parameters &params, const int &size, const int seed)
{
	Interleaver<T> *interleaver = nullptr;

	// build the interleaver
	if (params.interleaver.type == "LTE")
		interleaver = new Interleaver_LTE<T>(size);
	else if (params.interleaver.type == "CCSDS")
		interleaver = new Interleaver_CCSDS<T>(size);
	else if (params.interleaver.type == "RANDOM")
		interleaver = new Interleaver_random<T>(size, seed);
	else if (params.interleaver.type == "COLUMNS")
		interleaver = new Interleaver_columns<T>(size, params.interleaver.n_cols, seed);
	else if (params.interleaver.type == "GOLDEN")
		interleaver = new Interleaver_golden<T>(size, seed);
	else if (params.interleaver.type == "USER")
		interleaver = new Interleaver_user<T>(size, params.interleaver.path);
	else if (params.interleaver.type == "NO")
		interleaver = new Interleaver_NO<T>(size);

	return interleaver;
}

// ==================================================================================== explicit template instantiation
template struct aff3ct::tools::Factory_interleaver<short>;
template struct aff3ct::tools::Factory_interleaver<int>;
template struct aff3ct::tools::Factory_interleaver<long long>;
// ==================================================================================== explicit template instantiation
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALAN_TRANSFORMER_HEADER_GUARD)
#define XALAN_TRANSFORMER_HEADER_GUARD

// Base include file.  Must be first.
#include <XalanTransformer/XalanTransformerDefinitions.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>

#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/StylesheetRoot.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInit.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>

#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp>

#include <XalanTransformer/XalanTransformerOutputStream.hpp>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif

#if !defined(XALAN_NO_NAMESPACES)
	using std::ostream;
	using std::istream;
#endif

/**
 * This is a simple C++ interface for some common usage patterns. It's
 * the user's responsibility to call initialize and terminate
 * before creating and after deleting any XalanTransformer instances
 * respectively. After calling XalanTransformToData, the user should
 * call XalanFreeData to release the memory allocated by that operation.
*/
class XALAN_TRANSFORMER_EXPORT XalanTransformer
{
public:

	XalanTransformer();

	virtual ~XalanTransformer();

	/**
	 * Initialize Xerces and Xalan.
	 * Should be called only once per process before creating any
	 * instances of XalanTransformer. See class XSLTInit.
	 */
	static void
	initialize();

	/**
	 * Terminate Xalan and Xerces.
	 * Should be called only once per process after deleting all
	 * instances of XalanTransformer. See class XSLTInit.
	 */
	static void
	terminate();

	/**
	 * Returns the last error that occurred as a
	 * result of calling transform.
	 *
	 * @return	error message const character pointer.
	 */
	const char*
	getLastError() const;

	/**
	 * Transform the source tree to output in the given result tree target.
	 * The processor will apply the the stylesheet source to the input source
	 * and write the transformation output to the target. Called internally by
	 * all transform methods.
	 *
	 * @param inputSource		input source
	 * @param stylesheetSource	stylesheet source
	 * @param outputTarget		output source tree
	 * @return	0 for success
	 */
	int
	transform(
			const XSLTInputSource&		inputSource,
			const XSLTInputSource&		stylesheetSource,
			XSLTResultTarget&			outputTarget);

	/**
	 * Transform the XML source tree to the given result file.
	 * The processor will apply the the stylesheet source to the input source
	 * and write the transformation output to the output file.
	 *
	 * @param theXMLFileName	filename of XML input file
	 * @param theXSLFileName	filename of stylesheet file
	 * @param theOutFileName	filename of output file
	 * @return	0 for success
	 */
	int
	transform(
			const char*					theXMLFileName,
			const char*					theXSLFileName,
			const char*					theOutFileName);

	/**
	 * Transform the XML source tree to the given result file.
	 * The processor will apply the the stylesheet provided as a PI in the
	 * the XML to the input file and write the transformation output to the
	 * output file.
	 *
	 * @param theXMLFileName	filename of XML input file
	 * @param theOutFileName	filename of output file
	 * @return	0 for success
	 */
	int
	transform(
			const char*					theXMLFileName,
			const char*					theOutFileName);

	/**
	 * Transform the XML source tree to an output stream.
	 * The processor will apply the the stylesheet file to the input file
	 * and write the transformation output to the output stream.
	 *
	 * @param theXMLFileName	filename of XML input source
	 * @param theXSLFileName	filename of stylesheet source
	 * @param theOutStream		a std ostream for the output
	 * @return	0 for success
	 */
	int
	transform(
			const char*					theXMLFileName,
			const char*					theXSLFileName,
			ostream&					theOutStream);

	/**
	 * Transform the XML source tree to an output stream.
	 * The processor will apply the the stylesheet provided as a PI in the
	 * the XML to the input file and write the transformation output to the
	 * output stream.
	 *
	 * @param theXMLFileName	filename of XML input source
	 * @param theXSLFileName	filename of stylesheet source
	 * @param theOutStream		a std ostream for the output
	 * @return	0 for success
	 */
	int
	transform(
			const char*					theXMLFileName,
			ostream&					theOutStream);

	/**
	 * Transform the XML source tree to an output stream.
	 * The processor will apply the the stylesheet stream to the input stream
	 * and write the transformation output to the output stream.
	 *
	 * @param theXMLInStream	a std istream for the input
	 * @param theXSLInStream	a std istream for the input
	 * @param theOutStream		a std ostream for the output
	 * @return	0 for success
	 */
	int
	transform(
			istream&					theXMLInStream,
			istream&					theXSLInStream,
			ostream&					theOutStream);

	/**
	 * Transform the XML source tree to an output stream.
	 * The processor will apply the the stylesheet provided as a PI in the
	 * XML of the input stream and write the transformation output to the
	 * output stream.
	 *
	 * @param theXMLInStream	a std istream for the input
	 * @param theOutStream		a std ostream for the output
	 * @return	0 for success
	 */
	int
	transform(
			istream&					theXMLInStream,
			ostream&					theOutStream);

	/**
	 * Transform the XML source tree to a callback function.
	 * The processor will apply the stylesheet file to the input file
	 * and allocate the transformation result to a callback function
	 * in pre-allocated blocks. Upon termination, Xalan releases any
	 * allocated memory. Data passed to the callback is not guaranteed to
	 * be null terminated.
	 *
	 * - See XalanTransformerOutputStream and XalanOutputHandlerType
	 * for more details.
	 *
	 * @param theXMLFileName	filename of XML input source
	 * @param theXSLFileName	filename of stylesheet source
	 * @param theOutputHandle	void pointer passed through to callback.
	 * @param theOutputHandler	a user defined (callback) function.
	 * @param theFlushHandler	(optional) a user defined (callback) function.
	 * @return	0 for success
	 */
	int
	transform(
			const char*					theXMLFileName,
			const char*					theXSLFileName,
			const void*					theOutputHandle,
			XalanOutputHandlerType		theOutputHandler,
			XalanFlushHandlerType		theFlushHandler = 0);

protected:

private:

	void
	reset();

	XalanSourceTreeDOMSupport				m_domSupport;

	XalanSourceTreeParserLiaison			m_parserLiaison;

	XSLTProcessorEnvSupportDefault			m_xsltprocessorEnvSupport;

	XObjectFactoryDefault					m_xobjectFactory;

	XPathFactoryDefault						m_xpathFactory;

	XSLTEngineImpl							m_processor;

	StylesheetConstructionContextDefault	m_stylesheetConstructionContext;

	StylesheetExecutionContextDefault		m_stylesheetExecutionContext;

	CharVectorType							m_errorMessage;

	static XSLTInit*						m_xsltInit;
};

#endif	// XALAN_TRANSFORMER_HEADER_GUARD

<commit_msg>Removed reference to XalanFreeData (CAPI only).<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALAN_TRANSFORMER_HEADER_GUARD)
#define XALAN_TRANSFORMER_HEADER_GUARD

// Base include file.  Must be first.
#include <XalanTransformer/XalanTransformerDefinitions.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>

#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/StylesheetRoot.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInit.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>

#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp>

#include <XalanTransformer/XalanTransformerOutputStream.hpp>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif

#if !defined(XALAN_NO_NAMESPACES)
	using std::ostream;
	using std::istream;
#endif

/**
 * This is a simple C++ interface for some common usage patterns. It's
 * the user's responsibility to call initialize and terminate
 * before creating and after deleting any XalanTransformer instances
 * respectively.
*/
class XALAN_TRANSFORMER_EXPORT XalanTransformer
{
public:

	XalanTransformer();

	virtual ~XalanTransformer();

	/**
	 * Initialize Xerces and Xalan.
	 * Should be called only once per process before creating any
	 * instances of XalanTransformer. See class XSLTInit.
	 */
	static void
	initialize();

	/**
	 * Terminate Xalan and Xerces.
	 * Should be called only once per process after deleting all
	 * instances of XalanTransformer. See class XSLTInit.
	 */
	static void
	terminate();

	/**
	 * Returns the last error that occurred as a
	 * result of calling transform.
	 *
	 * @return	error message const character pointer.
	 */
	const char*
	getLastError() const;

	/**
	 * Transform the source tree to output in the given result tree target.
	 * The processor will apply the the stylesheet source to the input source
	 * and write the transformation output to the target. Called internally by
	 * all transform methods.
	 *
	 * @param inputSource		input source
	 * @param stylesheetSource	stylesheet source
	 * @param outputTarget		output source tree
	 * @return	0 for success
	 */
	int
	transform(
			const XSLTInputSource&		inputSource,
			const XSLTInputSource&		stylesheetSource,
			XSLTResultTarget&			outputTarget);

	/**
	 * Transform the XML source tree to the given result file.
	 * The processor will apply the the stylesheet source to the input source
	 * and write the transformation output to the output file.
	 *
	 * @param theXMLFileName	filename of XML input file
	 * @param theXSLFileName	filename of stylesheet file
	 * @param theOutFileName	filename of output file
	 * @return	0 for success
	 */
	int
	transform(
			const char*					theXMLFileName,
			const char*					theXSLFileName,
			const char*					theOutFileName);

	/**
	 * Transform the XML source tree to the given result file.
	 * The processor will apply the the stylesheet provided as a PI in the
	 * the XML to the input file and write the transformation output to the
	 * output file.
	 *
	 * @param theXMLFileName	filename of XML input file
	 * @param theOutFileName	filename of output file
	 * @return	0 for success
	 */
	int
	transform(
			const char*					theXMLFileName,
			const char*					theOutFileName);

	/**
	 * Transform the XML source tree to an output stream.
	 * The processor will apply the the stylesheet file to the input file
	 * and write the transformation output to the output stream.
	 *
	 * @param theXMLFileName	filename of XML input source
	 * @param theXSLFileName	filename of stylesheet source
	 * @param theOutStream		a std ostream for the output
	 * @return	0 for success
	 */
	int
	transform(
			const char*					theXMLFileName,
			const char*					theXSLFileName,
			ostream&					theOutStream);

	/**
	 * Transform the XML source tree to an output stream.
	 * The processor will apply the the stylesheet provided as a PI in the
	 * the XML to the input file and write the transformation output to the
	 * output stream.
	 *
	 * @param theXMLFileName	filename of XML input source
	 * @param theXSLFileName	filename of stylesheet source
	 * @param theOutStream		a std ostream for the output
	 * @return	0 for success
	 */
	int
	transform(
			const char*					theXMLFileName,
			ostream&					theOutStream);

	/**
	 * Transform the XML source tree to an output stream.
	 * The processor will apply the the stylesheet stream to the input stream
	 * and write the transformation output to the output stream.
	 *
	 * @param theXMLInStream	a std istream for the input
	 * @param theXSLInStream	a std istream for the input
	 * @param theOutStream		a std ostream for the output
	 * @return	0 for success
	 */
	int
	transform(
			istream&					theXMLInStream,
			istream&					theXSLInStream,
			ostream&					theOutStream);

	/**
	 * Transform the XML source tree to an output stream.
	 * The processor will apply the the stylesheet provided as a PI in the
	 * XML of the input stream and write the transformation output to the
	 * output stream.
	 *
	 * @param theXMLInStream	a std istream for the input
	 * @param theOutStream		a std ostream for the output
	 * @return	0 for success
	 */
	int
	transform(
			istream&					theXMLInStream,
			ostream&					theOutStream);

	/**
	 * Transform the XML source tree to a callback function.
	 * The processor will apply the stylesheet file to the input file
	 * and allocate the transformation result to a callback function
	 * in pre-allocated blocks. Upon termination, Xalan releases any
	 * allocated memory. Data passed to the callback is not guaranteed to
	 * be null terminated.
	 *
	 * - See XalanTransformerOutputStream and XalanOutputHandlerType
	 * for more details.
	 *
	 * @param theXMLFileName	filename of XML input source
	 * @param theXSLFileName	filename of stylesheet source
	 * @param theOutputHandle	void pointer passed through to callback.
	 * @param theOutputHandler	a user defined (callback) function.
	 * @param theFlushHandler	(optional) a user defined (callback) function.
	 * @return	0 for success
	 */
	int
	transform(
			const char*					theXMLFileName,
			const char*					theXSLFileName,
			const void*					theOutputHandle,
			XalanOutputHandlerType		theOutputHandler,
			XalanFlushHandlerType		theFlushHandler = 0);

protected:

private:

	void
	reset();

	XalanSourceTreeDOMSupport				m_domSupport;

	XalanSourceTreeParserLiaison			m_parserLiaison;

	XSLTProcessorEnvSupportDefault			m_xsltprocessorEnvSupport;

	XObjectFactoryDefault					m_xobjectFactory;

	XPathFactoryDefault						m_xpathFactory;

	XSLTEngineImpl							m_processor;

	StylesheetConstructionContextDefault	m_stylesheetConstructionContext;

	StylesheetExecutionContextDefault		m_stylesheetExecutionContext;

	CharVectorType							m_errorMessage;

	static XSLTInit*						m_xsltInit;
};

#endif	// XALAN_TRANSFORMER_HEADER_GUARD

<|endoftext|>


<commit_before>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "TestFixtures/SimpleObject.hpp"
#include <autowiring/Autowired.h>
#include <autowiring/ContextMember.h>
#include THREAD_HEADER

class PostConstructTest:
  public testing::Test
{};

using namespace std;

class ContextExposer:
  public CoreContext
{
public:
  size_t DeferredCount(void) const {
    size_t ct = 0;
    for(const auto& entry : CoreContext::m_typeMemos)
      for(auto cur = entry.second.pFirst; cur; cur = cur->GetFlink())
        ct++;
    return ct;
  }
};

// Two classes to make up the cyclic dependency:
class A:
  public ContextMember
{
public:
  A(void):
    m_value(2)
  {}

  int m_value;

  int GetValue(void) const {return m_value;}
};

// For testing NotifyWhenAutowired with heirarchies
class Interface
{
public:
  virtual int GetValue() = 0;
};

class Implementation :
  public ContextMember,
  public Interface
{
public:
  virtual int GetValue() override { return 2; }
};

class Naive:
  public ContextMember
{
public:
  Naive(void) {
    if(!m_a)
      throw exception();
  }

  Autowired<A> m_a;
};

class Smarter:
  public ContextMember
{
public:
  Smarter(void):
    value(1)
  {
    m_a.NotifyWhenAutowired([this] () {
      this->value = m_a->GetValue();
    });
  }

  int value;
  Autowired<A> m_a;
};

class SmarterInterface
{
public:
  SmarterInterface(void):
    value(1)
  {
    m_interface.NotifyWhenAutowired([this] () {
      this->value = m_interface->GetValue();
    });
  }

  int value;
  Autowired<Interface> m_interface;
};

class FailedAutowiringInstance {
};

TEST_F(PostConstructTest, VerifyNaiveBehavior) {
  // Create a context and add just the naive class, to verify the problematic behavior:
  AutoCurrentContext ctxt;
  EXPECT_THROW(ctxt->Inject<Naive>(), std::exception) << "Naive class didn't throw an exception as expected";
}

TEST_F(PostConstructTest, VerifyExpectedDeferrmentCount) {
  AutoCurrentContext ctxt;

  // Add the smart class, which should introduce a single deferred count:
  ctxt->Inject<Smarter>();

  // Now test the count:
  EXPECT_EQ(
    1UL,
    ((ContextExposer&)*ctxt).DeferredCount()
  ) << "Unexpected number of deferred initializers";
}

TEST_F(PostConstructTest, VerifySmartBehavior) {
  AutoCurrentContext ctxt;

  // Add the smart class, which has a member that autowired type A
  ctxt->Inject<Smarter>();

  // Check that we can get the item we just injected
  Autowired<Smarter> smarter;
  ASSERT_TRUE(smarter.IsAutowired()) << "Slot was not satisfied as expected";
  EXPECT_EQ(1, smarter->value) << "Unexpected initial value of SmarterA instance";

  // Now inject A, and see if delayed autowiring has taken place:
  ctxt->Inject<A>();
  EXPECT_FALSE(!smarter->m_a.get()) << "Autowired member was not wired as expected";

  // Verify the value was updated by the notification routine
  EXPECT_EQ(2, smarter->value) << "Post-construction notification routine wasn't invoked as expected";
}

TEST_F(PostConstructTest, VerifySmartBehaviorWithInheritance) {
  AutoCurrentContext ctxt;

  // Add the smart classes, which should succeed
  ctxt->Inject<SmarterInterface>();

  //Initially value should be one, which is the default
  Autowired<SmarterInterface> smarterI;
  EXPECT_EQ(1, smarterI->value) << "Unexpected initial value of SmarterA instance";

  //Now add Implementation and check the wiring
  ctxt->Inject<Implementation>();
  EXPECT_FALSE(!smarterI->m_interface.get()) << "Autowired subclass was not wired as expected";

  EXPECT_EQ(2, smarterI->value) << "Post-construction notification routine wasn't invoked on subclass";
}

TEST_F(PostConstructTest, VerifyLoopingFailedAutowiring) {
  for(size_t i = 10; i--;) {
    Autowired<FailedAutowiringInstance> ignored;
    ASSERT_FALSE(ignored.IsAutowired()) << "Successfully autowired an instance that should not have been autowirable";
  }
}

TEST_F(PostConstructTest, VerifyTrivialNotifyWhenAutowired) {
  // Inject a type first:
  AutoRequired<SimpleObject>();

  // Now autowire, and add a registration:
  bool called = false;
  Autowired<SimpleObject> so;
  so.NotifyWhenAutowired([&called] { called = true; });

  ASSERT_TRUE(called) << "An autowiring notification was not invoked on an already-satisfied field as expected";
}

TEST_F(PostConstructTest, MultiNotifyWhenAutowired) {
  // Add multiple notifications on the same space:
  int field = 0;
  Autowired<SimpleObject> so;
  for(size_t i = 10; i--;)
    so.NotifyWhenAutowired([&field] { field++; });

  // Inject the type to trigger the autowiring
  AutoRequired<SimpleObject>();

  // Verify that the notification got hit ten times:
  ASSERT_EQ(10, field) << "Autowiring lambdas did not run the expected number of times";
}

TEST_F(PostConstructTest, NotificationTeardownRace) {
  std::shared_ptr<CoreContext> pContext;

  auto quit = false;
  auto shouldQuit = MakeAtExit([&quit] { quit = true; });
  std::atomic<size_t> counter{0};

  // This thread sets up the race pathology:
  std::thread t([&] {
    while(!quit) {
      // Barrier until setup time:
      while(counter != 1)
        std::this_thread::yield();

      if(!pContext)
        break;

      // Set the context current, then try to autowire:
      CurrentContextPusher pshr(pContext);
      Autowired<SimpleObject> sobj;
      sobj.NotifyWhenAutowired([] {});

      // Now barrier, and then we will try to race against the context
      // for teardown.
      counter++;
    }
  });

  for(size_t i = 0; i < 200; i++) {
    // Make a new context:
    AutoCreateContext ctxt;
    pContext = ctxt;

    // Wake up the other thread, let it set a notify-when-autowired:
    counter++;
    while(counter != 2)
      std::this_thread::yield();

    // Counter goes back to zero before we make the next loop iteration:
    counter = 0;

    // Now we reset our pContext pointer, and then tell the thread
    // to race with us against context teardown:
    pContext.reset();
  }

  // All done, wait for the thread to back out:
  quit = true;
  counter = 1;
  t.join();
}

TEST_F(PostConstructTest, VerifyAllInstancesSatisfied) {
  // Create all of our slots and bind to them:
  const size_t ct = 3;
  Autowired<SimpleObject> aw[ct];
  bool hit[ct] = {};

  for(size_t i = ct; i--;)
    aw[i].NotifyWhenAutowired([&hit, i] { hit[i] = true; });

  // Now we inject our simple object:
  AutoRequired<SimpleObject>();

  // Verify that everything got hit:
  for(size_t i = 0; i < ct; i++) {
    ASSERT_TRUE(aw[i]) << "Autowired slot " << i << " was not post-bound correctly";
    ASSERT_TRUE(hit[i]) << "Autowired slot " << i << " did not fire all of its post-construct notifiers as expected";
  }
}

TEST_F(PostConstructTest, ContextNotifyWhenAutowired) {
  auto called = std::make_shared<bool>(false);
  AutoCurrentContext ctxt;

  // Now we'd like to be notified when SimpleObject gets added:
  ctxt->NotifyWhenAutowired<SimpleObject>(
    [called] {
      *called = true;
    }
  );

  // Should only be two uses, at this point, of the capture of the above lambda:
  EXPECT_EQ(2L, called.use_count()) << "Unexpected number of references held in a capture lambda";

  // Create another entry that will add another slot to the deferred list:
  Autowired<SimpleObject> sobj;

  // Insert the SimpleObject, see if the lambda got hit:
  AutoRequired<SimpleObject>();
  ASSERT_TRUE(*called) << "Context-wide autowiring notification was not hit as expected when a matching type was injected into a context";

  // Our shared pointer should be unique by this point, because the lambda should have been destroyed
  ASSERT_TRUE(called.unique()) << "Autowiring notification lambda was not properly cleaned up";
}

<commit_msg>Adding unit test demonstrating failure of PostConstruction NotifyWhenAutowired for Context.<commit_after>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "TestFixtures/SimpleObject.hpp"
#include <autowiring/Autowired.h>
#include <autowiring/ContextMember.h>
#include THREAD_HEADER

class PostConstructTest:
  public testing::Test
{};

using namespace std;

class ContextExposer:
  public CoreContext
{
public:
  size_t DeferredCount(void) const {
    size_t ct = 0;
    for(const auto& entry : CoreContext::m_typeMemos)
      for(auto cur = entry.second.pFirst; cur; cur = cur->GetFlink())
        ct++;
    return ct;
  }
};

// Two classes to make up the cyclic dependency:
class A:
  public ContextMember
{
public:
  A(void):
    m_value(2)
  {}

  int m_value;

  int GetValue(void) const {return m_value;}
};

// For testing NotifyWhenAutowired with heirarchies
class Interface
{
public:
  virtual int GetValue() = 0;
};

class Implementation :
  public ContextMember,
  public Interface
{
public:
  virtual int GetValue() override { return 2; }
};

class Naive:
  public ContextMember
{
public:
  Naive(void) {
    if(!m_a)
      throw exception();
  }

  Autowired<A> m_a;
};

class Smarter:
  public ContextMember
{
public:
  Smarter(void):
    value(1)
  {
    m_a.NotifyWhenAutowired([this] () {
      this->value = m_a->GetValue();
    });
  }

  int value;
  Autowired<A> m_a;
};

class SmarterInterface
{
public:
  SmarterInterface(void):
    value(1)
  {
    m_interface.NotifyWhenAutowired([this] () {
      this->value = m_interface->GetValue();
    });
  }

  int value;
  Autowired<Interface> m_interface;
};

class FailedAutowiringInstance {
};

TEST_F(PostConstructTest, VerifyNaiveBehavior) {
  // Create a context and add just the naive class, to verify the problematic behavior:
  AutoCurrentContext ctxt;
  EXPECT_THROW(ctxt->Inject<Naive>(), std::exception) << "Naive class didn't throw an exception as expected";
}

TEST_F(PostConstructTest, VerifyExpectedDeferrmentCount) {
  AutoCurrentContext ctxt;

  // Add the smart class, which should introduce a single deferred count:
  ctxt->Inject<Smarter>();

  // Now test the count:
  EXPECT_EQ(
    1UL,
    ((ContextExposer&)*ctxt).DeferredCount()
  ) << "Unexpected number of deferred initializers";
}

TEST_F(PostConstructTest, VerifySmartBehavior) {
  AutoCurrentContext ctxt;

  // Add the smart class, which has a member that autowired type A
  ctxt->Inject<Smarter>();

  // Check that we can get the item we just injected
  Autowired<Smarter> smarter;
  ASSERT_TRUE(smarter.IsAutowired()) << "Slot was not satisfied as expected";
  EXPECT_EQ(1, smarter->value) << "Unexpected initial value of SmarterA instance";

  // Now inject A, and see if delayed autowiring has taken place:
  ctxt->Inject<A>();
  EXPECT_FALSE(!smarter->m_a.get()) << "Autowired member was not wired as expected";

  // Verify the value was updated by the notification routine
  EXPECT_EQ(2, smarter->value) << "Post-construction notification routine wasn't invoked as expected";
}

TEST_F(PostConstructTest, VerifySmartBehaviorWithInheritance) {
  AutoCurrentContext ctxt;

  // Add the smart classes, which should succeed
  ctxt->Inject<SmarterInterface>();

  //Initially value should be one, which is the default
  Autowired<SmarterInterface> smarterI;
  EXPECT_EQ(1, smarterI->value) << "Unexpected initial value of SmarterA instance";

  //Now add Implementation and check the wiring
  ctxt->Inject<Implementation>();
  EXPECT_FALSE(!smarterI->m_interface.get()) << "Autowired subclass was not wired as expected";

  EXPECT_EQ(2, smarterI->value) << "Post-construction notification routine wasn't invoked on subclass";
}

TEST_F(PostConstructTest, VerifyLoopingFailedAutowiring) {
  for(size_t i = 10; i--;) {
    Autowired<FailedAutowiringInstance> ignored;
    ASSERT_FALSE(ignored.IsAutowired()) << "Successfully autowired an instance that should not have been autowirable";
  }
}

TEST_F(PostConstructTest, VerifyTrivialNotifyWhenAutowired) {
  // Inject a type first:
  AutoRequired<SimpleObject>();

  // Now autowire, and add a registration:
  bool called = false;
  Autowired<SimpleObject> so;
  so.NotifyWhenAutowired([&called] { called = true; });

  ASSERT_TRUE(called) << "An autowiring notification was not invoked on an already-satisfied field as expected";
}

TEST_F(PostConstructTest, MultiNotifyWhenAutowired) {
  // Add multiple notifications on the same space:
  int field = 0;
  Autowired<SimpleObject> so;
  for(size_t i = 10; i--;)
    so.NotifyWhenAutowired([&field] { field++; });

  // Inject the type to trigger the autowiring
  AutoRequired<SimpleObject>();

  // Verify that the notification got hit ten times:
  ASSERT_EQ(10, field) << "Autowiring lambdas did not run the expected number of times";
}

TEST_F(PostConstructTest, NotificationTeardownRace) {
  std::shared_ptr<CoreContext> pContext;

  auto quit = false;
  auto shouldQuit = MakeAtExit([&quit] { quit = true; });
  std::atomic<size_t> counter{0};

  // This thread sets up the race pathology:
  std::thread t([&] {
    while(!quit) {
      // Barrier until setup time:
      while(counter != 1)
        std::this_thread::yield();

      if(!pContext)
        break;

      // Set the context current, then try to autowire:
      CurrentContextPusher pshr(pContext);
      Autowired<SimpleObject> sobj;
      sobj.NotifyWhenAutowired([] {});

      // Now barrier, and then we will try to race against the context
      // for teardown.
      counter++;
    }
  });

  for(size_t i = 0; i < 200; i++) {
    // Make a new context:
    AutoCreateContext ctxt;
    pContext = ctxt;

    // Wake up the other thread, let it set a notify-when-autowired:
    counter++;
    while(counter != 2)
      std::this_thread::yield();

    // Counter goes back to zero before we make the next loop iteration:
    counter = 0;

    // Now we reset our pContext pointer, and then tell the thread
    // to race with us against context teardown:
    pContext.reset();
  }

  // All done, wait for the thread to back out:
  quit = true;
  counter = 1;
  t.join();
}

TEST_F(PostConstructTest, VerifyAllInstancesSatisfied) {
  // Create all of our slots and bind to them:
  const size_t ct = 3;
  Autowired<SimpleObject> aw[ct];
  bool hit[ct] = {};

  for(size_t i = ct; i--;)
    aw[i].NotifyWhenAutowired([&hit, i] { hit[i] = true; });

  // Now we inject our simple object:
  AutoRequired<SimpleObject>();

  // Verify that everything got hit:
  for(size_t i = 0; i < ct; i++) {
    ASSERT_TRUE(aw[i]) << "Autowired slot " << i << " was not post-bound correctly";
    ASSERT_TRUE(hit[i]) << "Autowired slot " << i << " did not fire all of its post-construct notifiers as expected";
  }
}

TEST_F(PostConstructTest, ContextNotifyWhenAutowired) {
  auto called = std::make_shared<bool>(false);
  AutoCurrentContext ctxt;

  // Now we'd like to be notified when SimpleObject gets added:
  ctxt->NotifyWhenAutowired<SimpleObject>(
  [called] {
      *called = true;
  });

  // Should only be two uses, at this point, of the capture of the above lambda:
  EXPECT_EQ(2L, called.use_count()) << "Unexpected number of references held in a capture lambda";

  // Create another entry that will add another slot to the deferred list:
  Autowired<SimpleObject> sobj;

  // Insert the SimpleObject, see if the lambda got hit:
  AutoRequired<SimpleObject>();
  ASSERT_TRUE(*called) << "Context-wide autowiring notification was not hit as expected when a matching type was injected into a context";

  // Our shared pointer should be unique by this point, because the lambda should have been destroyed
  ASSERT_TRUE(called.unique()) << "Autowiring notification lambda was not properly cleaned up";
}

TEST_F(PostConstructTest, ContextNotifyWhenAutowiredPostConstruct) {
  auto called = std::make_shared<bool>(false);
  AutoCurrentContext ctxt;

  // Create an object that will satisfy subsequent notification call:
  AutoRequired<SimpleObject> sobj;

  // Notification should be immediate:
  ctxt->NotifyWhenAutowired<SimpleObject>(
  [called] {
      *called = true;
  });

  // Insert the SimpleObject, see if the lambda got hit:
  ASSERT_TRUE(*called) << "Context-wide autowiring notification was not hit as expected when a matching type was injected into a context";

  // Our shared pointer should be unique by this point, because the lambda should have been destroyed
  ASSERT_TRUE(called.unique()) << "Autowiring notification lambda was not properly cleaned up";
}

<|endoftext|>