<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xenumerator.h"
#include "xenia/kernel/objects/xuser_module.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/util/xex2.h"
#include "xenia/kernel/xam_private.h"
#include "xenia/xbox.h"

namespace xe {
namespace kernel {

SHIM_CALL XamGetSystemVersion_shim(PPCContext* ppc_state, KernelState* state) {
  XELOGD("XamGetSystemVersion()");
  // eh, just picking one. If we go too low we may break new games, but
  // this value seems to be used for conditionally loading symbols and if
  // we pretend to be old we have less to worry with implementing.
  // 0x200A3200
  // 0x20096B00
  SHIM_SET_RETURN_64(0);
}

SHIM_CALL XGetAVPack_shim(PPCContext* ppc_state, KernelState* state) {
  // DWORD
  // Not sure what the values are for this, but 6 is VGA.
  // Other likely values are 3/4/8 for HDMI or something.
  // Games seem to use this as a PAL check - if the result is not 3/4/6/8
  // they explode with errors if not in PAL mode.
  SHIM_SET_RETURN_64(6);
}

SHIM_CALL XGetGameRegion_shim(PPCContext* ppc_state, KernelState* state) {
  XELOGD("XGetGameRegion()");

  SHIM_SET_RETURN_64(0xFFFF);
}

SHIM_CALL XGetLanguage_shim(PPCContext* ppc_state, KernelState* state) {
  XELOGD("XGetLanguage()");

  uint32_t desired_language = X_LANGUAGE_ENGLISH;

  // Switch the language based on game region.
  // TODO(benvanik): pull from xex header.
  uint32_t game_region = XEX_REGION_NTSCU;
  if (game_region & XEX_REGION_NTSCU) {
    desired_language = X_LANGUAGE_ENGLISH;
  } else if (game_region & XEX_REGION_NTSCJ) {
    desired_language = X_LANGUAGE_JAPANESE;
  }
  // Add more overrides?

  SHIM_SET_RETURN_64(desired_language);
}

SHIM_CALL XamVoiceIsActiveProcess_shim(PPCContext* ppc_state,
                                       KernelState* state) {
  XELOGD("XamVoiceIsActiveProcess()");
  // Returning 0 here will short-circuit a bunch of voice stuff.
  SHIM_SET_RETURN_32(0);
}

SHIM_CALL XamGetExecutionId_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t info_ptr = SHIM_GET_ARG_32(0);

  XELOGD("XamGetExecutionId(%.8X)", info_ptr);

  auto module = state->GetExecutableModule();
  assert_not_null(module);

  SHIM_SET_MEM_32(info_ptr, module->execution_info_ptr());

  SHIM_SET_RETURN_32(0);
}

SHIM_CALL XamLoaderSetLaunchData_shim(PPCContext* ppc_state,
                                      KernelState* state) {
  uint32_t data_ptr = SHIM_GET_ARG_32(0);
  uint32_t data_size = SHIM_GET_ARG_32(1);

  XELOGD("XamLoaderSetLaunchData(%.8X, %d)", data_ptr, data_size);

  // Unknown return value.
  SHIM_SET_RETURN_32(0);
}

SHIM_CALL XamLoaderGetLaunchDataSize_shim(PPCContext* ppc_state,
                                          KernelState* state) {
  uint32_t size_ptr = SHIM_GET_ARG_32(0);

  XELOGD("XamLoaderGetLaunchDataSize(%.8X)", size_ptr);

  SHIM_SET_MEM_32(size_ptr, 0);

  SHIM_SET_RETURN_32(1);
}

SHIM_CALL XamLoaderGetLaunchData_shim(PPCContext* ppc_state,
                                      KernelState* state) {
  uint32_t buffer_ptr = SHIM_GET_ARG_32(0);
  uint32_t buffer_size = SHIM_GET_ARG_32(1);

  XELOGD("XamLoaderGetLaunchData(%.8X, %d)", buffer_ptr, buffer_size);

  SHIM_SET_RETURN_32(0);
}

SHIM_CALL XamLoaderLaunchTitle_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t name_ptr = SHIM_GET_ARG_32(0);
  const char* name = (const char*)SHIM_MEM_ADDR(name_ptr);
  uint32_t unk2 = SHIM_GET_ARG_32(1);

  XELOGD("XamLoaderLaunchTitle(%.8X(%s), %.8X)", name_ptr, name, unk2);
  assert_always();
}

SHIM_CALL XamLoaderTerminateTitle_shim(PPCContext* ppc_state,
                                       KernelState* state) {
  XELOGD("XamLoaderTerminateTitle()");
  assert_always();
}

SHIM_CALL XamAlloc_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t unk = SHIM_GET_ARG_32(0);
  uint32_t size = SHIM_GET_ARG_32(1);
  uint32_t out_ptr = SHIM_GET_ARG_32(2);

  XELOGD("XamAlloc(%d, %d, %.8X)", unk, size, out_ptr);

  assert_true(unk == 0);

  // Allocate from the heap. Not sure why XAM does this specially, perhaps
  // it keeps stuff in a separate heap?
  uint32_t ptr = state->memory()->SystemHeapAlloc(size);
  SHIM_SET_MEM_32(out_ptr, ptr);

  SHIM_SET_RETURN_32(X_ERROR_SUCCESS);
}

SHIM_CALL XamFree_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t ptr = SHIM_GET_ARG_32(0);

  XELOGD("XamFree(%.8X)", ptr);

  state->memory()->SystemHeapFree(ptr);

  SHIM_SET_RETURN_32(X_ERROR_SUCCESS);
}

SHIM_CALL XamEnumerate_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t handle = SHIM_GET_ARG_32(0);
  uint32_t zero = SHIM_GET_ARG_32(1);
  uint32_t buffer_ptr = SHIM_GET_ARG_32(2);
  uint32_t buffer_length = SHIM_GET_ARG_32(3);
  uint32_t item_count_ptr = SHIM_GET_ARG_32(4);
  uint32_t overlapped_ptr = SHIM_GET_ARG_32(5);

  assert_true(zero == 0);

  XELOGD("XamEnumerate(%.8X, %d, %.8X, %d, %.8X, %.8X)", handle, zero,
         buffer_ptr, buffer_length, item_count_ptr, overlapped_ptr);

  auto e = state->object_table()->LookupObject<XEnumerator>(handle);
  if (!e) {
    if (overlapped_ptr) {
      state->CompleteOverlappedImmediateEx(overlapped_ptr, 0,
                                           X_ERROR_INVALID_HANDLE, 0);
      SHIM_SET_RETURN_64(X_ERROR_IO_PENDING);
    } else {
      SHIM_SET_RETURN_64(X_ERROR_INVALID_HANDLE);
    }
    return;
  }

  auto item_count = e->item_count();
  e->WriteItems(SHIM_MEM_ADDR(buffer_ptr));

  X_RESULT result = item_count ? X_ERROR_SUCCESS : X_ERROR_NO_MORE_FILES;
  if (item_count_ptr) {
    assert_zero(overlapped_ptr);
    SHIM_SET_MEM_32(item_count_ptr, item_count);
  } else if (overlapped_ptr) {
    assert_zero(item_count_ptr);
    state->CompleteOverlappedImmediateEx(overlapped_ptr, result, result,
                                         item_count);
    result = X_ERROR_IO_PENDING;
  } else {
    assert_always();
    result = X_ERROR_INVALID_PARAMETER;
  }

  SHIM_SET_RETURN_64(result);
}

}  // namespace kernel
}  // namespace xe

void xe::kernel::xam::RegisterInfoExports(
    xe::cpu::ExportResolver* export_resolver, KernelState* state) {
  SHIM_SET_MAPPING("xam.xex", XamGetSystemVersion, state);
  SHIM_SET_MAPPING("xam.xex", XGetAVPack, state);
  SHIM_SET_MAPPING("xam.xex", XGetGameRegion, state);
  SHIM_SET_MAPPING("xam.xex", XGetLanguage, state);

  SHIM_SET_MAPPING("xam.xex", XamVoiceIsActiveProcess, state);
  SHIM_SET_MAPPING("xam.xex", XamGetExecutionId, state);

  SHIM_SET_MAPPING("xam.xex", XamLoaderSetLaunchData, state);
  SHIM_SET_MAPPING("xam.xex", XamLoaderGetLaunchDataSize, state);
  SHIM_SET_MAPPING("xam.xex", XamLoaderGetLaunchData, state);
  SHIM_SET_MAPPING("xam.xex", XamLoaderLaunchTitle, state);
  SHIM_SET_MAPPING("xam.xex", XamLoaderTerminateTitle, state);

  SHIM_SET_MAPPING("xam.xex", XamAlloc, state);
  SHIM_SET_MAPPING("xam.xex", XamFree, state);

  SHIM_SET_MAPPING("xam.xex", XamEnumerate, state);
}
<commit_msg>Hurf. SHIM_SET_RETURN_64 -> SHIM_SET_RETURN_32.<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xenumerator.h"
#include "xenia/kernel/objects/xuser_module.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/util/xex2.h"
#include "xenia/kernel/xam_private.h"
#include "xenia/xbox.h"

namespace xe {
namespace kernel {

SHIM_CALL XamGetSystemVersion_shim(PPCContext* ppc_state, KernelState* state) {
  XELOGD("XamGetSystemVersion()");
  // eh, just picking one. If we go too low we may break new games, but
  // this value seems to be used for conditionally loading symbols and if
  // we pretend to be old we have less to worry with implementing.
  // 0x200A3200
  // 0x20096B00
  SHIM_SET_RETURN_64(0);
}

SHIM_CALL XGetAVPack_shim(PPCContext* ppc_state, KernelState* state) {
  // DWORD
  // Not sure what the values are for this, but 6 is VGA.
  // Other likely values are 3/4/8 for HDMI or something.
  // Games seem to use this as a PAL check - if the result is not 3/4/6/8
  // they explode with errors if not in PAL mode.
  SHIM_SET_RETURN_64(6);
}

SHIM_CALL XGetGameRegion_shim(PPCContext* ppc_state, KernelState* state) {
  XELOGD("XGetGameRegion()");

  SHIM_SET_RETURN_64(0xFFFF);
}

SHIM_CALL XGetLanguage_shim(PPCContext* ppc_state, KernelState* state) {
  XELOGD("XGetLanguage()");

  uint32_t desired_language = X_LANGUAGE_ENGLISH;

  // Switch the language based on game region.
  // TODO(benvanik): pull from xex header.
  uint32_t game_region = XEX_REGION_NTSCU;
  if (game_region & XEX_REGION_NTSCU) {
    desired_language = X_LANGUAGE_ENGLISH;
  } else if (game_region & XEX_REGION_NTSCJ) {
    desired_language = X_LANGUAGE_JAPANESE;
  }
  // Add more overrides?

  SHIM_SET_RETURN_64(desired_language);
}

SHIM_CALL XamVoiceIsActiveProcess_shim(PPCContext* ppc_state,
                                       KernelState* state) {
  XELOGD("XamVoiceIsActiveProcess()");
  // Returning 0 here will short-circuit a bunch of voice stuff.
  SHIM_SET_RETURN_32(0);
}

SHIM_CALL XamGetExecutionId_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t info_ptr = SHIM_GET_ARG_32(0);

  XELOGD("XamGetExecutionId(%.8X)", info_ptr);

  auto module = state->GetExecutableModule();
  assert_not_null(module);

  SHIM_SET_MEM_32(info_ptr, module->execution_info_ptr());

  SHIM_SET_RETURN_32(0);
}

SHIM_CALL XamLoaderSetLaunchData_shim(PPCContext* ppc_state,
                                      KernelState* state) {
  uint32_t data_ptr = SHIM_GET_ARG_32(0);
  uint32_t data_size = SHIM_GET_ARG_32(1);

  XELOGD("XamLoaderSetLaunchData(%.8X, %d)", data_ptr, data_size);

  // Unknown return value.
  SHIM_SET_RETURN_32(0);
}

SHIM_CALL XamLoaderGetLaunchDataSize_shim(PPCContext* ppc_state,
                                          KernelState* state) {
  uint32_t size_ptr = SHIM_GET_ARG_32(0);

  XELOGD("XamLoaderGetLaunchDataSize(%.8X)", size_ptr);

  SHIM_SET_MEM_32(size_ptr, 0);

  SHIM_SET_RETURN_32(1);
}

SHIM_CALL XamLoaderGetLaunchData_shim(PPCContext* ppc_state,
                                      KernelState* state) {
  uint32_t buffer_ptr = SHIM_GET_ARG_32(0);
  uint32_t buffer_size = SHIM_GET_ARG_32(1);

  XELOGD("XamLoaderGetLaunchData(%.8X, %d)", buffer_ptr, buffer_size);

  SHIM_SET_RETURN_32(0);
}

SHIM_CALL XamLoaderLaunchTitle_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t name_ptr = SHIM_GET_ARG_32(0);
  const char* name = (const char*)SHIM_MEM_ADDR(name_ptr);
  uint32_t unk2 = SHIM_GET_ARG_32(1);

  XELOGD("XamLoaderLaunchTitle(%.8X(%s), %.8X)", name_ptr, name, unk2);
  assert_always();
}

SHIM_CALL XamLoaderTerminateTitle_shim(PPCContext* ppc_state,
                                       KernelState* state) {
  XELOGD("XamLoaderTerminateTitle()");
  assert_always();
}

SHIM_CALL XamAlloc_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t unk = SHIM_GET_ARG_32(0);
  uint32_t size = SHIM_GET_ARG_32(1);
  uint32_t out_ptr = SHIM_GET_ARG_32(2);

  XELOGD("XamAlloc(%d, %d, %.8X)", unk, size, out_ptr);

  assert_true(unk == 0);

  // Allocate from the heap. Not sure why XAM does this specially, perhaps
  // it keeps stuff in a separate heap?
  uint32_t ptr = state->memory()->SystemHeapAlloc(size);
  SHIM_SET_MEM_32(out_ptr, ptr);

  SHIM_SET_RETURN_32(X_ERROR_SUCCESS);
}

SHIM_CALL XamFree_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t ptr = SHIM_GET_ARG_32(0);

  XELOGD("XamFree(%.8X)", ptr);

  state->memory()->SystemHeapFree(ptr);

  SHIM_SET_RETURN_32(X_ERROR_SUCCESS);
}

SHIM_CALL XamEnumerate_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t handle = SHIM_GET_ARG_32(0);
  uint32_t zero = SHIM_GET_ARG_32(1);
  uint32_t buffer_ptr = SHIM_GET_ARG_32(2);
  uint32_t buffer_length = SHIM_GET_ARG_32(3);
  uint32_t item_count_ptr = SHIM_GET_ARG_32(4);
  uint32_t overlapped_ptr = SHIM_GET_ARG_32(5);

  assert_true(zero == 0);

  XELOGD("XamEnumerate(%.8X, %d, %.8X, %d, %.8X, %.8X)", handle, zero,
         buffer_ptr, buffer_length, item_count_ptr, overlapped_ptr);

  auto e = state->object_table()->LookupObject<XEnumerator>(handle);
  if (!e) {
    if (overlapped_ptr) {
      state->CompleteOverlappedImmediateEx(overlapped_ptr, 0,
                                           X_ERROR_INVALID_HANDLE, 0);
      SHIM_SET_RETURN_32(X_ERROR_IO_PENDING);
    } else {
      SHIM_SET_RETURN_32(X_ERROR_INVALID_HANDLE);
    }
    return;
  }

  auto item_count = e->item_count();
  e->WriteItems(SHIM_MEM_ADDR(buffer_ptr));

  X_RESULT result = item_count ? X_ERROR_SUCCESS : X_ERROR_NO_MORE_FILES;
  if (item_count_ptr) {
    assert_zero(overlapped_ptr);
    SHIM_SET_MEM_32(item_count_ptr, item_count);
  } else if (overlapped_ptr) {
    assert_zero(item_count_ptr);
    state->CompleteOverlappedImmediateEx(overlapped_ptr, result, result,
                                         item_count);
    result = X_ERROR_IO_PENDING;
  } else {
    assert_always();
    result = X_ERROR_INVALID_PARAMETER;
  }

  SHIM_SET_RETURN_32(result);
}

}  // namespace kernel
}  // namespace xe

void xe::kernel::xam::RegisterInfoExports(
    xe::cpu::ExportResolver* export_resolver, KernelState* state) {
  SHIM_SET_MAPPING("xam.xex", XamGetSystemVersion, state);
  SHIM_SET_MAPPING("xam.xex", XGetAVPack, state);
  SHIM_SET_MAPPING("xam.xex", XGetGameRegion, state);
  SHIM_SET_MAPPING("xam.xex", XGetLanguage, state);

  SHIM_SET_MAPPING("xam.xex", XamVoiceIsActiveProcess, state);
  SHIM_SET_MAPPING("xam.xex", XamGetExecutionId, state);

  SHIM_SET_MAPPING("xam.xex", XamLoaderSetLaunchData, state);
  SHIM_SET_MAPPING("xam.xex", XamLoaderGetLaunchDataSize, state);
  SHIM_SET_MAPPING("xam.xex", XamLoaderGetLaunchData, state);
  SHIM_SET_MAPPING("xam.xex", XamLoaderLaunchTitle, state);
  SHIM_SET_MAPPING("xam.xex", XamLoaderTerminateTitle, state);

  SHIM_SET_MAPPING("xam.xex", XamAlloc, state);
  SHIM_SET_MAPPING("xam.xex", XamFree, state);

  SHIM_SET_MAPPING("xam.xex", XamEnumerate, state);
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "support.h"
#include <qmessageaccountid.h>
#include <qmessagefolderid.h>
#include <qmessageid.h>

namespace Support {

void clearMessageStore()
{
}

QMessageAccountId addAccount(const Parameters &params)
{
    Q_UNUSED(params)

    return QMessageAccountId();
}
#ifdef QMESSAGING_OPTIONAL_FOLDER
QMessageFolderId addFolder(const Parameters &params)
{
    Q_UNUSED(params)

    return QMessageFolderId();
}
#endif
QMessageId addMessage(const Parameters &params)
{
    Q_UNUSED(params)

    return QMessageId();
}

}

<commit_msg>AddAccount for MAPI.<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "support.h"
#include <qmessageaccountid.h>
#include <qmessagefolderid.h>
#include <qmessageid.h>
#include <qmessagestore.h>
#include <QDataStream>
#include <QDebug>

#include <Mapidefs.h>
#include <Mapitags.h>
#include <Mapix.h>
#include <MAPIUtil.h>

// Missing definitions
#ifndef PR_PST_CONFIG_FLAGS
#define PR_PST_CONFIG_FLAGS PROP_TAG( PT_LONG, 0x6770 )
#endif
#ifndef PST_CONFIG_UNICODE
#define PST_CONFIG_UNICODE 0x80000000
#endif
#ifndef PR_PST_PATH_A
#define PR_PST_PATH_A PROP_TAG( PT_STRING8, 0x6700 )
#endif

namespace {

void doInit()
{
    static QMessageStore *store(0);
    if (!store) {
        store = QMessageStore::instance();
    }
}

typedef QPair<QByteArray, bool> ProfileDetail;

QList<ProfileDetail> profileDetails(LPPROFADMIN profAdmin)
{
    QList<ProfileDetail> result;

    LPMAPITABLE profileTable(0);
    HRESULT rv = profAdmin->GetProfileTable(0, &profileTable);
    if (HR_SUCCEEDED(rv)) {
        LPSRowSet rows(0);
        SizedSPropTagArray(2, cols) = {2, {PR_DISPLAY_NAME_A, PR_DEFAULT_PROFILE}};
        rv = HrQueryAllRows(profileTable, reinterpret_cast<LPSPropTagArray>(&cols), NULL, NULL, 0, &rows);
        if (HR_SUCCEEDED(rv)) {
            for (uint n = 0; n < rows->cRows; ++n) {
                if (rows->aRow[n].lpProps[0].ulPropTag == PR_DISPLAY_NAME_A) {
                    QByteArray profileName(rows->aRow[n].lpProps[0].Value.lpszA);
                    bool defaultProfile(rows->aRow[n].lpProps[1].Value.b);
                    result.append(qMakePair(profileName, defaultProfile));
                }
            }

            FreeProws(rows);
        } else {
            qWarning() << "profileNames: HrQueryAllRows failed";
        }

        profileTable->Release();
    } else {
        qWarning() << "profileNames: GetProfileTable failed";
    }

    return result;
}

typedef QPair<QByteArray, MAPIUID> ServiceDetail;

QList<ServiceDetail> serviceDetails(LPSERVICEADMIN svcAdmin)
{
    QList<ServiceDetail> result;

    IMAPITable *svcTable(0);
    HRESULT rv = svcAdmin->GetMsgServiceTable(0, &svcTable);
    if (HR_SUCCEEDED(rv)) {
        LPSRowSet rows(0);
        SizedSPropTagArray(2, cols) = {2, {PR_SERVICE_NAME_A, PR_SERVICE_UID}};
        rv = HrQueryAllRows(svcTable, reinterpret_cast<LPSPropTagArray>(&cols), 0, 0, 0, &rows);
        if (HR_SUCCEEDED(rv)) {
            for (uint n = 0; n < rows->cRows; ++n) {
                if (rows->aRow[n].lpProps[0].ulPropTag == PR_SERVICE_NAME_A) {
                    QByteArray svcName(rows->aRow[n].lpProps[0].Value.lpszA);
                    MAPIUID svcUid(*(reinterpret_cast<MAPIUID*>(rows->aRow[n].lpProps[1].Value.bin.lpb)));
                    result.append(qMakePair(svcName, svcUid));
                }
            }

            FreeProws(rows);
        } else {
            qWarning() << "serviceDetails: HrQueryAllRows failed";
        }

        svcTable->Release();
    } else {
        qWarning() << "serviceDetails: GetMsgServiceTable failed";
    }

    return result;
}

typedef QPair<QByteArray, QByteArray> StoreDetail;

QList<StoreDetail> storeDetails(LPMAPISESSION session)
{
    QList<StoreDetail> result;

    IMAPITable *storesTable(0);
    HRESULT rv = session->GetMsgStoresTable(0, &storesTable);
    if (HR_SUCCEEDED(rv)) {
        LPSRowSet rows(0);
        SizedSPropTagArray(2, cols) = {2, {PR_DISPLAY_NAME_A, PR_RECORD_KEY}};
        rv = HrQueryAllRows(storesTable, reinterpret_cast<LPSPropTagArray>(&cols), 0, 0, 0, &rows);
        if (HR_SUCCEEDED(rv)) {
            for (uint n = 0; n < rows->cRows; ++n) {
                if (rows->aRow[n].lpProps[0].ulPropTag == PR_DISPLAY_NAME_A) {
                    QByteArray storeName(rows->aRow[n].lpProps[0].Value.lpszA);
                    QByteArray recordKey(reinterpret_cast<const char*>(rows->aRow[n].lpProps[1].Value.bin.lpb), rows->aRow[n].lpProps[1].Value.bin.cb);
                    result.append(qMakePair(storeName, recordKey));
                }
            }

            FreeProws(rows);
        } else {
            qWarning() << "storeDetails: HrQueryAllRows failed";
        }

        storesTable->Release();
    } else {
        qWarning() << "storeDetails: GetMsgStoresTable failed";
    }

    return result;
}

QMessageAccountId accountIdFromRecordKey(const QByteArray &recordKey)
{
    QByteArray encodedId;
    {
        QDataStream encodedIdStream(&encodedId, QIODevice::WriteOnly);
        encodedIdStream << recordKey;
    }

    return QMessageAccountId(encodedId.toBase64());
}

}

namespace Support {

void clearMessageStore()
{
    // Ensure the store is instantiated
    doInit();
}

QMessageAccountId addAccount(const Parameters &params)
{
    QMessageAccountId result;

    doInit();

    QString accountName(params["name"]);
    if (!accountName.isEmpty()) {
        // Profile name must be ASCII
        QByteArray name(accountName.toAscii());

        // See if a profile exists with the given name
        LPPROFADMIN profAdmin(0);
        HRESULT rv = MAPIAdminProfiles(0, &profAdmin);
        if (HR_SUCCEEDED(rv)) {
            // Find the default profile
            QByteArray defaultProfileName;
            foreach (const ProfileDetail &profile, profileDetails(profAdmin)) {
                if (profile.second) {
                    defaultProfileName = profile.first;
                    break;
                }
            }

            if (!defaultProfileName.isEmpty()) {
                // Open a session on the profile
                LPMAPISESSION session(0);
                rv = MAPILogonEx(0, reinterpret_cast<LPTSTR>(defaultProfileName.data()), 0, MAPI_EXTENDED | MAPI_NEW_SESSION | MAPI_NO_MAIL, &session);
                if (HR_SUCCEEDED(rv)) {
                    LPSERVICEADMIN svcAdmin(0);
                    rv = profAdmin->AdminServices(reinterpret_cast<LPTSTR>(defaultProfileName.data()), 0, 0, 0, &svcAdmin);
                    if (HR_SUCCEEDED(rv)) {
                        char *providerName = "MSUPST MS";
                        bool serviceExists(false);
                        MAPIUID svcUid = { 0 };

                        foreach (const ServiceDetail &svc, serviceDetails(svcAdmin)) {
                            if (svc.first.toLower() == QByteArray(providerName).toLower()) {
                                svcUid = svc.second;
                                serviceExists = true;
                                break;
                            }
                        }

                        if (serviceExists) {
                            // Delete the existing service
                            rv = svcAdmin->DeleteMsgService(&svcUid);
                            if (HR_SUCCEEDED(rv)) {
                                serviceExists = false;
                            } else {
                                qWarning() << "DeleteMsgService failed";
                            }
                        }

                        if (!serviceExists) {
                            // Create a message service for this profile using the standard provider
                            rv = svcAdmin->CreateMsgService(reinterpret_cast<LPTSTR>(providerName), reinterpret_cast<LPTSTR>(name.data()), 0, 0);
                            if (HR_SUCCEEDED(rv)) {
                                foreach (const ServiceDetail &svc, serviceDetails(svcAdmin)) {
                                    // Find the name/UID for the service we added
                                    if (svc.first.toLower() == QByteArray(providerName).toLower()) {
                                        // Create a .PST message store for this service
                                        QByteArray path(QString("%1.pst").arg(name.constData()).toAscii());

                                        SPropValue props[3] = { 0 };
                                        props[0].ulPropTag = PR_DISPLAY_NAME_A;
                                        props[0].Value.lpszA = name.data();
                                        props[1].ulPropTag = PR_PST_PATH_A;
                                        props[1].Value.lpszA = path.data();
                                        props[2].ulPropTag = PR_PST_CONFIG_FLAGS;
                                        props[2].Value.l = PST_CONFIG_UNICODE;

                                        svcUid = svc.second;
                                        rv = svcAdmin->ConfigureMsgService(&svcUid, 0, 0, 3, props);
                                        if (HR_SUCCEEDED(rv)) {
                                            serviceExists = true;
                                        } else {
                                            qWarning() << "ConfigureMsgService failed";
                                        }
                                        break;
                                    }
                                }
                            } else {
                                qWarning() << "CreateMsgService failed";
                            }
                        }

                        if (serviceExists) {
                            foreach (const StoreDetail &store, storeDetails(session)) {
                                if (store.first.toLower() == name.toLower()) {
                                    result = accountIdFromRecordKey(store.second);
                                    break;
                                }
                            }
                        }

                        svcAdmin->Release();
                    } else {
                        qWarning() << "AdminServices failed";
                    }

                    session->Release();
                } else {
                    qWarning() << "MAPILogonEx failed";
                }
            } else {
                qWarning() << "No default profile found!";
            }

            profAdmin->Release();
        } else {
            qWarning() << "MAPIAdminProfiles failed";
        }
    }

    return result;
}
#ifdef QMESSAGING_OPTIONAL_FOLDER
QMessageFolderId addFolder(const Parameters &params)
{
    Q_UNUSED(params)

    return QMessageFolderId();
}
#endif
QMessageId addMessage(const Parameters &params)
{
    Q_UNUSED(params)

    return QMessageId();
}

}

<|endoftext|>


<commit_before>//----------------------------  support_point_map.cc  ---------------------------
//    support_point_map.cc,v 1.6 2003/04/09 15:49:54 wolf Exp
//    Version:
//
//    Copyright (C) 2000, 2001, 2003 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  support_point_map.cc  ---------------------------

/* Author: Wolfgang Bangerth, University of Heidelberg, 2001 */
/* Purpose: check the map_dofs_to_support_points and
   map_support_points_to_dofs functions.                     */

#include "../tests.h"
#include <base/logstream.h>
#include <base/function_lib.h>
#include <lac/vector.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_accessor.h>
#include <grid/grid_generator.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_tools.h>
#include <fe/fe_q.h>
#include <fe/fe_dgq.h>
#include <fe/fe_system.h>
#include <fe/mapping_q.h>

#include <fstream>

template <int dim>
struct PointComp
{
    bool operator () (const Point<dim> &, const Point<dim> &) const;
};

template <>
bool PointComp<1>::operator () (const Point<1> &p1,
				const Point<1> &p2) const
{
  return p1(0) < p2(0);
}

// have somewhat weird orderings in 2d and 3d
template <>
bool PointComp<2>::operator () (const Point<2> &p1,
				const Point<2> &p2) const
{
  return ((p1(0)+p1(1) < p2(0)+p2(1)) ||
	  ((p1(0)+p1(1) == p2(0)+p2(1)) &&
	   (p1(0)-p1(1) < p2(0)-p2(1))));
}

template <>
bool PointComp<3>::operator () (const Point<3> &p1,
				const Point<3> &p2) const
{
  return ((p1(2) < p2(2)) ||
	  (p1(2) == p2(2)) &&
	  ((p1(0)+p1(1) < p2(0)+p2(1)) ||
	   ((p1(0)+p1(1) == p2(0)+p2(1)) &&
	    (p1(0)-p1(1) < p2(0)-p2(1)))));
}

template <int dim>
void
check ()
{
  Triangulation<dim> tr;
  if (dim==2)
    {
      GridGenerator::hyper_ball(tr, Point<dim>(), 1);
    }
  else
    GridGenerator::hyper_cube(tr, -1./sqrt(dim),1./sqrt(dim));
  if (dim != 1)
    {
      static const HyperBallBoundary<dim> boundary;
      tr.set_boundary (0, boundary);
    };
  tr.refine_global (1);
  tr.begin_active()->set_refine_flag ();
  tr.execute_coarsening_and_refinement ();
  if (dim==1)
    tr.refine_global(2);

  MappingQ<dim> mapping(3);

  FESystem<dim> element (FE_Q<dim>(2), 1, FE_DGQ<dim>(1), 1);
  DoFHandler<dim> dof(tr);
  dof.distribute_dofs(element);

				   // get the forward map
  std::vector<Point<dim> > support_points (dof.n_dofs());
  DoFTools::map_dofs_to_support_points (mapping, dof, support_points);
  for (unsigned int i=0; i<dof.n_dofs(); ++i)
    deallog << i << ": " << support_points[i] << std::endl;

				   // now get the backward map
  std::map<Point<dim>,unsigned int,PointComp<dim> > point_map;
  DoFTools::map_support_points_to_dofs (mapping, dof, point_map);
  typename std::map<Point<dim>,unsigned int,PointComp<dim> >::const_iterator
    i = point_map.begin(),
    e = point_map.end();
  for (; i!=e; ++i)
    deallog << i->first << ',' << i->second << std::endl;
}

int main ()
{
  std::ofstream logfile ("support_point_map.output");
  logfile.precision (2);
  logfile.setf(std::ios::fixed);
  deallog.attach(logfile);
  deallog.depth_console (0);

  deallog.push ("1d");
  check<1> ();
  deallog.pop ();
  deallog.push ("2d");
  check<2> ();
  deallog.pop ();
  deallog.push ("3d");
  check<3> ();
  deallog.pop ();
}
<commit_msg>Add some missing std.<commit_after>//----------------------------  support_point_map.cc  ---------------------------
//    support_point_map.cc,v 1.6 2003/04/09 15:49:54 wolf Exp
//    Version:
//
//    Copyright (C) 2000, 2001, 2003 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  support_point_map.cc  ---------------------------

/* Author: Wolfgang Bangerth, University of Heidelberg, 2001 */
/* Purpose: check the map_dofs_to_support_points and
   map_support_points_to_dofs functions.                     */

#include "../tests.h"
#include <base/logstream.h>
#include <base/function_lib.h>
#include <lac/vector.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_accessor.h>
#include <grid/grid_generator.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_tools.h>
#include <fe/fe_q.h>
#include <fe/fe_dgq.h>
#include <fe/fe_system.h>
#include <fe/mapping_q.h>

#include <fstream>

template <int dim>
struct PointComp
{
    bool operator () (const Point<dim> &, const Point<dim> &) const;
};

template <>
bool PointComp<1>::operator () (const Point<1> &p1,
				const Point<1> &p2) const
{
  return p1(0) < p2(0);
}

// have somewhat weird orderings in 2d and 3d
template <>
bool PointComp<2>::operator () (const Point<2> &p1,
				const Point<2> &p2) const
{
  return ((p1(0)+p1(1) < p2(0)+p2(1)) ||
	  ((p1(0)+p1(1) == p2(0)+p2(1)) &&
	   (p1(0)-p1(1) < p2(0)-p2(1))));
}

template <>
bool PointComp<3>::operator () (const Point<3> &p1,
				const Point<3> &p2) const
{
  return ((p1(2) < p2(2)) ||
	  (p1(2) == p2(2)) &&
	  ((p1(0)+p1(1) < p2(0)+p2(1)) ||
	   ((p1(0)+p1(1) == p2(0)+p2(1)) &&
	    (p1(0)-p1(1) < p2(0)-p2(1)))));
}

template <int dim>
void
check ()
{
  Triangulation<dim> tr;
  if (dim==2)
    {
      GridGenerator::hyper_ball(tr, Point<dim>(), 1);
    }
  else
    GridGenerator::hyper_cube(tr, -1./std::sqrt(static_cast<double>(dim)),1./std::sqrt(static_cast<double>(dim)));
  if (dim != 1)
    {
      static const HyperBallBoundary<dim> boundary;
      tr.set_boundary (0, boundary);
    };
  tr.refine_global (1);
  tr.begin_active()->set_refine_flag ();
  tr.execute_coarsening_and_refinement ();
  if (dim==1)
    tr.refine_global(2);

  MappingQ<dim> mapping(3);

  FESystem<dim> element (FE_Q<dim>(2), 1, FE_DGQ<dim>(1), 1);
  DoFHandler<dim> dof(tr);
  dof.distribute_dofs(element);

				   // get the forward map
  std::vector<Point<dim> > support_points (dof.n_dofs());
  DoFTools::map_dofs_to_support_points (mapping, dof, support_points);
  for (unsigned int i=0; i<dof.n_dofs(); ++i)
    deallog << i << ": " << support_points[i] << std::endl;

				   // now get the backward map
  std::map<Point<dim>,unsigned int,PointComp<dim> > point_map;
  DoFTools::map_support_points_to_dofs (mapping, dof, point_map);
  typename std::map<Point<dim>,unsigned int,PointComp<dim> >::const_iterator
    i = point_map.begin(),
    e = point_map.end();
  for (; i!=e; ++i)
    deallog << i->first << ',' << i->second << std::endl;
}

int main ()
{
  std::ofstream logfile ("support_point_map.output");
  logfile.precision (2);
  logfile.setf(std::ios::fixed);
  deallog.attach(logfile);
  deallog.depth_console (0);

  deallog.push ("1d");
  check<1> ();
  deallog.pop ();
  deallog.push ("2d");
  check<2> ();
  deallog.pop ();
  deallog.push ("3d");
  check<3> ();
  deallog.pop ();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>

#include <matrix.h>

#define WITHOUT_NUMPY
#include <matplotlib-cpp/matplotlibcpp.h>
namespace plt = matplotlibcpp;

///////////////////////////////////////////////
// Pattern initialization

int
random_plus_minus_one()
{
    return (std::rand() % 2) * 2 - 1;
}

void
fill_with_random_noise(Pattern& pattern)
{
    for (size_t i = 0; i < pattern.num_elements; ++i) {
        pattern.set_linear(i, random_plus_minus_one());
    }
}

///////////////////////////////////////////////
// Hebb's rule related

float
calculate_weight_at_ij(const std::vector<Pattern>& patterns, size_t N, size_t i, size_t j)
{
    if (i == j) return 0.0f;

    float weight = 0.0f;
    for (size_t idx = 0; idx < patterns.size(); ++idx) {
        auto& pattern = patterns.at(idx);
        weight += pattern.get_linear(i) * pattern.get_linear(j);
    }
    return weight / static_cast<float>(N);
}

WeightMatrix
create_weight_matrix(const std::vector<Pattern>& patterns, size_t num_bits)
{
    size_t N = num_bits;
    WeightMatrix weights(N, N);

    for (size_t i = 0; i < N; ++i)  {
        for (size_t j = 0; j < N; ++j)  {
            float w = calculate_weight_at_ij(patterns, N, i, j);
            weights.set(i, j, w);
        }
    }

    return weights;
}

///////////////////////////////////////////////
// Stochastic update rule

float
local_field(Pattern& pattern, size_t i, const WeightMatrix& weights)
{
    float b = 0.0f;
    for (size_t j = 0; j < pattern.num_elements; ++j) {
        b += weights.get(i, j) * pattern.get_linear(j);
    }
    return b;
}

float random_float()
{
    return static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);
}

#define g_func(b, beta) stochastic_signum(b, beta)

float
stochastic_signum(float b, float beta)
{
    return 1.0f / (1.0f + expf(-2.0f * b * beta));
}

void
stochastic_update_neuron(Pattern& pattern, size_t i, const WeightMatrix& weights, float beta)
{
    float b = local_field(pattern, i, weights);
    int new_value = random_float() <= g_func(b, beta) ? +1 : -1;
    pattern.set_linear(i, new_value);
}

///////////////////////////////////////////////
// Order parameter calculation

float
order_parameter_for_iteration(const Pattern &stored_pattern, const Pattern &test_pattern)
{
    assert(stored_pattern.num_elements == test_pattern.num_elements);
    size_t N = stored_pattern.num_elements;

    float m = 0.0f;
    for (size_t i = 0; i < N; ++i) {
        m += test_pattern.get_linear(i) * stored_pattern.get_linear(i);
    }
    m /= static_cast<float>(N);

    return m;
}

///////////////////////////////////////////////
// Test procedure

int
main()
{
    std::srand(static_cast<uint>(std::time(0)));

    const size_t NUM_TESTS_TO_PERFORM = 20;
    const size_t NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST = 10000;

    const size_t N = 200;
    const size_t p = 5;
    const float beta = 2;

    std::cout << "Testing for p = " << p << ", N = " << N << ", and beta = " << beta << ":" << std::endl;

    // Create p random patterns to store
    std::vector<Pattern> stored_patterns;
    stored_patterns.reserve(p);
    for (size_t i = 0; i < p; ++i) {
        stored_patterns.emplace_back(N);
        fill_with_random_noise(stored_patterns.at(i));
    }

    // Store patterns in the weight matrix according to Hebb's rule
    const WeightMatrix& weights = create_weight_matrix(stored_patterns, N);

    // Feed the first stored pattern to the network
    Pattern test_pattern = stored_patterns.at(0);

    // For storing data for plotting
    std::vector<float> iteration_step_vector;
    std::vector<float> order_parameter_for_iteration_vector;
    iteration_step_vector.resize(NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST);
    order_parameter_for_iteration_vector.resize(NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST);

    plt::figure();
    plt::title("Phase diagram for p = 5");

    for (size_t current_test = 0; current_test < NUM_TESTS_TO_PERFORM; ++current_test) {

        std::cout << "Performing test " << (current_test + 1) << " out of " << NUM_TESTS_TO_PERFORM << std::endl;

        for (size_t current_step = 0; current_step < NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST; ++current_step) {

            // Pick random neuron to update
            size_t i = std::rand() % N;

            stochastic_update_neuron(test_pattern, i, weights, beta);

            float m = order_parameter_for_iteration(stored_patterns.at(0), test_pattern);

            // Store data for plotting
            iteration_step_vector.at(current_step) = current_step;
            order_parameter_for_iteration_vector.at(current_step) = m;
        }

        plt::plot(iteration_step_vector, order_parameter_for_iteration_vector, "r-");
    }

    std::cout << "Tests done, plotting" << std::endl;

    // Draw and show graph results
    plt::xlabel("t");
    plt::ylabel("m(t)");
    plt::ylim(0.0, 1.1);
    plt::grid(true);
    plt::show();

    return 0;
}

<commit_msg>Finish up stochastic Hopfield program<commit_after>#include <iostream>
#include <sstream>
#include <cmath>

#include <matrix.h>

#define WITHOUT_NUMPY
#include <matplotlib-cpp/matplotlibcpp.h>
namespace plt = matplotlibcpp;

///////////////////////////////////////////////
// Pattern initialization

int
random_plus_minus_one()
{
    return (std::rand() % 2) * 2 - 1;
}

void
fill_with_random_noise(Pattern& pattern)
{
    for (size_t i = 0; i < pattern.num_elements; ++i) {
        pattern.set_linear(i, random_plus_minus_one());
    }
}

///////////////////////////////////////////////
// Hebb's rule related

double
calculate_weight_at_ij(const std::vector<Pattern>& patterns, size_t N, size_t i, size_t j)
{
    if (i == j) return 0.0f;

    double weight = 0.0f;
    for (size_t idx = 0; idx < patterns.size(); ++idx) {
        auto& pattern = patterns.at(idx);
        weight += pattern.get_linear(i) * pattern.get_linear(j);
    }
    return weight / static_cast<double>(N);
}

WeightMatrix
create_weight_matrix(const std::vector<Pattern>& patterns, size_t num_bits)
{
    size_t N = num_bits;
    WeightMatrix weights(N, N);

    for (size_t i = 0; i < N; ++i)  {
        for (size_t j = 0; j < N; ++j)  {
            double w = calculate_weight_at_ij(patterns, N, i, j);
            weights.set(i, j, w);
        }
    }

    return weights;
}

///////////////////////////////////////////////
// Stochastic update rule

double
local_field(Pattern& pattern, size_t i, const WeightMatrix& weights)
{
    double b = 0.0f;
    for (size_t j = 0; j < pattern.num_elements; ++j) {
        b += weights.get(i, j) * pattern.get_linear(j);
    }
    return b;
}

double random_double()
{
    return static_cast<double>(std::rand()) / static_cast<double>(RAND_MAX);
}

#define g_func(b, beta) activation_function_g(b, beta)

double
activation_function_g(double b, double beta)
{
    return 1.0f / (1.0f + exp(-2.0f * b * beta));
}

void
stochastic_update_neuron(Pattern& pattern, size_t i, const WeightMatrix& weights, double beta)
{
    double b = local_field(pattern, i, weights);
    int new_value = random_double() <= g_func(b, beta) ? +1 : -1;
    pattern.set_linear(i, new_value);
}

///////////////////////////////////////////////
// Order parameter calculation

double
order_parameter_for_iteration(const Pattern &stored_pattern, const Pattern &test_pattern)
{
    assert(stored_pattern.num_elements == test_pattern.num_elements);
    size_t N = stored_pattern.num_elements;

    double m = 0.0f;
    for (size_t i = 0; i < N; ++i) {
        m += test_pattern.get_linear(i) * stored_pattern.get_linear(i);
    }
    m /= static_cast<double>(N);

    return m;
}

///////////////////////////////////////////////
// Test procedure

int
main()
{
    std::srand(static_cast<uint>(std::time(0)));

    const size_t NUM_TESTS_TO_PERFORM = 20;
    const size_t NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST = 25000;
    const int SMOOTHING_KERNEL_SIZE = 1000;

    const size_t N = 200;
    const size_t p_list[] = { 5, 40 };
    const double beta = 2;

    for (int current_p_index = 0; current_p_index < 2; ++current_p_index) {

        size_t p = p_list[current_p_index];

        std::cout << "Testing for p = " << p << ", N = " << N << ", and beta = " << beta << ":" << std::endl;

        // Create p random patterns to store
        std::vector<Pattern> stored_patterns;
        stored_patterns.reserve(p);
        for (size_t i = 0; i < p; ++i) {
            stored_patterns.emplace_back(N);
            fill_with_random_noise(stored_patterns.at(i));
        }

        // Store patterns in the weight matrix according to Hebb's rule
        const WeightMatrix& weights = create_weight_matrix(stored_patterns, N);

        // For storing data for plotting
        std::vector<double> iteration_step_vector;
        std::vector<double> order_parameter_for_iteration_vector;
        iteration_step_vector.resize(NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST);
        order_parameter_for_iteration_vector.resize(NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST);

        for (size_t current_test = 0; current_test < NUM_TESTS_TO_PERFORM; ++current_test) {

            std::cout << " test " << (current_test + 1) << "/" << NUM_TESTS_TO_PERFORM << std::endl;

            // Feed the first stored pattern to the network
            Pattern test_pattern = stored_patterns.at(0);

            for (size_t current_step = 0; current_step < NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST; ++current_step) {

                // Pick random neuron to update
                size_t i = std::rand() % N;

                stochastic_update_neuron(test_pattern, i, weights, beta);

                double m = order_parameter_for_iteration(stored_patterns.at(0), test_pattern);

                // Store data for plotting
                iteration_step_vector.at(current_step) = current_step;
                order_parameter_for_iteration_vector.at(current_step) = m;
            }

            // Apply moving average filter
            size_t num_elements = order_parameter_for_iteration_vector.size();
            std::vector<double> smooth_order_parameter_for_iteration_vector(num_elements);
            for (int i = 0; i < num_elements; ++i) {

                double sum = 0.0;
                int count = 0;

                for (int j = -SMOOTHING_KERNEL_SIZE / 2; j < SMOOTHING_KERNEL_SIZE / 2; ++j) {
                    int idx = i + j;
                    if (idx < 0) idx = 0;
                    if (idx >= num_elements) idx = (int) num_elements - 1;
                    size_t index = static_cast<size_t>(idx);
                    sum += order_parameter_for_iteration_vector.at(index);
                    count += 1;
                }

                double average = sum / count;
                smooth_order_parameter_for_iteration_vector.at((size_t)i) = average;
            }

            // Plot results
            {
                int row = 2 * current_p_index;
                std::stringstream title;
                title << "Phase diagram for p = " << p;

                plt::subplot(2, 2, row + 1);
                plt::title(title.str());
                plt::plot(iteration_step_vector, order_parameter_for_iteration_vector, "r-");
                plt::xlabel("t");
                plt::ylabel("m(t)");
                plt::ylim(0.0, 1.1);
                plt::grid(true);

                plt::subplot(2, 2, row + 2);
                title << " (smoothed)";
                plt::title(title.str());
                plt::plot(iteration_step_vector, smooth_order_parameter_for_iteration_vector, "b-");
                plt::xlabel("t");
                plt::ylabel("m(t)");
                plt::ylim(0.0, 1.1);
                plt::grid(true);
            }
        }
    }

    std::cout << "Tests done, plotting" << std::endl;
    plt::show();

    return 0;
}

<|endoftext|>


<commit_before>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------

#include "ProcessesDataView.h"

#include "App.h"
#include "Callstack.h"
#include "Capture.h"
#include "ModulesDataView.h"
#include "OrbitType.h"
#include "Params.h"
#include "Pdb.h"
#include "TcpClient.h"

//-----------------------------------------------------------------------------
ProcessesDataView::ProcessesDataView() {
  InitColumnsIfNeeded();
  m_SortingOrders.insert(m_SortingOrders.end(), s_InitialOrders.begin(),
                         s_InitialOrders.end());

  UpdateProcessList();
  m_UpdatePeriodMs = 1000;
  m_IsRemote = false;

  GOrbitApp->RegisterProcessesDataView(this);
}

//-----------------------------------------------------------------------------
std::vector<std::wstring> ProcessesDataView::s_Headers;
std::vector<float> ProcessesDataView::s_HeaderRatios;
std::vector<DataView::SortingOrder> ProcessesDataView::s_InitialOrders;

//-----------------------------------------------------------------------------
void ProcessesDataView::InitColumnsIfNeeded() {
  if (s_Headers.empty()) {
    s_Headers.emplace_back(L"PID");
    s_HeaderRatios.push_back(0);
    s_InitialOrders.push_back(AscendingOrder);

    s_Headers.emplace_back(L"Name");
    s_HeaderRatios.push_back(0.5f);
    s_InitialOrders.push_back(AscendingOrder);

    s_Headers.emplace_back(L"CPU");
    s_HeaderRatios.push_back(0);
    s_InitialOrders.push_back(DescendingOrder);

    s_Headers.emplace_back(L"Type");
    s_HeaderRatios.push_back(0);
    s_InitialOrders.push_back(AscendingOrder);
  }
}

//-----------------------------------------------------------------------------
const std::vector<std::wstring>& ProcessesDataView::GetColumnHeaders() {
  return s_Headers;
}

//-----------------------------------------------------------------------------
const std::vector<float>& ProcessesDataView::GetColumnHeadersRatios() {
  return s_HeaderRatios;
}

//-----------------------------------------------------------------------------
const std::vector<DataView::SortingOrder>&
ProcessesDataView::GetColumnInitialOrders() {
  return s_InitialOrders;
}

//-----------------------------------------------------------------------------
int ProcessesDataView::GetDefaultSortingColumn() { return PDV_CPU; }

//-----------------------------------------------------------------------------
std::wstring ProcessesDataView::GetValue(int row, int col) {
  const Process& process = *GetProcess(row);
  std::wstring value;

  switch (col) {
    case PDV_ProcessID:
      value = std::to_wstring((long)process.GetID());
      break;
    case PDV_ProcessName:
      value = s2ws(process.GetName());
      if (process.IsElevated()) {
        value += L"*";
      }
      break;
    case PDV_CPU:
      value = Format(L"%.1f", process.GetCpuUsage());
      break;
    case PDV_Type:
      value = process.GetIs64Bit() ? L"64 bit" : L"32 bit";
      break;
    default:
      break;
  }

  return value;
}

//-----------------------------------------------------------------------------
std::wstring ProcessesDataView::GetToolTip(int a_Row, int /*a_Column*/) {
  const Process& process = *GetProcess(a_Row);
  return s2ws(process.GetFullName());
}

//-----------------------------------------------------------------------------
#define ORBIT_PROC_SORT(Member)                                            \
  [&](int a, int b) {                                                      \
    return OrbitUtils::Compare(processes[a]->Member, processes[b]->Member, \
                               ascending);                                 \
  }

//-----------------------------------------------------------------------------
void ProcessesDataView::OnSort(int a_Column,
                               std::optional<SortingOrder> a_NewOrder) {
  if (a_Column == -1) {
    a_Column = PdvColumn::PDV_CPU;
  }

  const std::vector<std::shared_ptr<Process>>& processes =
      m_ProcessList.m_Processes;
  auto pdvColumn = static_cast<PdvColumn>(a_Column);

  if (a_NewOrder.has_value()) {
    m_SortingOrders[pdvColumn] = a_NewOrder.value();
  }

  bool ascending = m_SortingOrders[pdvColumn] == AscendingOrder;
  std::function<bool(int a, int b)> sorter = nullptr;

  switch (pdvColumn) {
    case PDV_ProcessID:
      sorter = ORBIT_PROC_SORT(GetID());
      break;
    case PDV_ProcessName:
      sorter = ORBIT_PROC_SORT(GetName());
      break;
    case PDV_CPU:
      sorter = ORBIT_PROC_SORT(GetCpuUsage());
      break;
    case PDV_Type:
      sorter = ORBIT_PROC_SORT(GetIs64Bit());
      break;
    default:
      break;
  }

  if (sorter) {
    std::sort(m_Indices.begin(), m_Indices.end(), sorter);
  }

  m_LastSortedColumn = a_Column;
  SetSelectedItem();
}

//-----------------------------------------------------------------------------
void ProcessesDataView::OnSelect(int a_Index) {
  m_SelectedProcess = GetProcess(a_Index);
  if (!m_IsRemote) {
    m_SelectedProcess->ListModules();
  } else if (m_SelectedProcess->GetModules().size() == 0) {
    Message msg(Msg_RemoteProcessRequest);
    msg.m_Header.m_GenericHeader.m_Address = m_SelectedProcess->GetID();
    GTcpClient->Send(msg);
  }

  UpdateModuleDataView(m_SelectedProcess);
}

void ProcessesDataView::UpdateModuleDataView(
    std::shared_ptr<Process> a_Process) {
  if (m_ModulesDataView) {
    m_ModulesDataView->SetProcess(a_Process);
    Capture::SetTargetProcess(a_Process);
    GOrbitApp->FireRefreshCallbacks();
  }
}

//-----------------------------------------------------------------------------
void ProcessesDataView::OnTimer() { Refresh(); }

//-----------------------------------------------------------------------------
void ProcessesDataView::Refresh() {
  if (Capture::IsCapturing()) {
    return;
  }

  if (m_RemoteProcess) {
    std::shared_ptr<Process> CurrentRemoteProcess =
        m_ProcessList.m_Processes.size() == 1 ? m_ProcessList.m_Processes[0]
                                              : nullptr;

    if (m_RemoteProcess != CurrentRemoteProcess) {
      m_ProcessList.Clear();
      m_ProcessList.m_Processes.push_back(m_RemoteProcess);
      UpdateProcessList();
      SetFilter(L"");
      SelectProcess(m_RemoteProcess->GetID());
      SetSelectedItem();
    }
  } else {
    if (!m_IsRemote) {
      m_ProcessList.Refresh();
      m_ProcessList.UpdateCpuTimes();
    }
    UpdateProcessList();
    OnSort(m_LastSortedColumn, {});
    OnFilter(m_Filter);
    SetSelectedItem();

    if (Capture::GTargetProcess && !Capture::IsCapturing()) {
      Capture::GTargetProcess->UpdateThreadUsage();
    }
  }

  GParams.m_ProcessFilter = ws2s(m_Filter);
}

//-----------------------------------------------------------------------------
void ProcessesDataView::SetSelectedItem() {
  int initialIndex = m_SelectedIndex;
  m_SelectedIndex = -1;

  for (uint32_t i = 0; i < (uint32_t)GetNumElements(); ++i) {
    if (m_SelectedProcess &&
        GetProcess(i)->GetID() == m_SelectedProcess->GetID()) {
      m_SelectedIndex = i;
      return;
    }
  }

  if (GParams.m_AutoReleasePdb && initialIndex != -1) {
    ClearSelectedProcess();
  }
}

//-----------------------------------------------------------------------------
void ProcessesDataView::ClearSelectedProcess() {
  std::shared_ptr<Process> process = std::make_shared<Process>();
  Capture::SetTargetProcess(process);
  m_ModulesDataView->SetProcess(process);
  m_SelectedProcess = process;
  GPdbDbg = nullptr;
  GOrbitApp->FireRefreshCallbacks();
}

//-----------------------------------------------------------------------------
bool ProcessesDataView::SelectProcess(const std::wstring& a_ProcessName) {
  for (uint32_t i = 0; i < GetNumElements(); ++i) {
    Process& process = *GetProcess(i);
    if (process.GetFullName().find(ws2s(a_ProcessName)) != std::string::npos) {
      OnSelect(i);
      Capture::GPresetToLoad = "";
      return true;
    }
  }

  return false;
}

//-----------------------------------------------------------------------------
std::shared_ptr<Process> ProcessesDataView::SelectProcess(DWORD a_ProcessId) {
  Refresh();

  for (uint32_t i = 0; i < GetNumElements(); ++i) {
    Process& process = *GetProcess(i);
    if (process.GetID() == a_ProcessId) {
      OnSelect(i);
      Capture::GPresetToLoad = "";
      return m_SelectedProcess;
    }
  }

  return nullptr;
}

//-----------------------------------------------------------------------------
void ProcessesDataView::OnFilter(const std::wstring& a_Filter) {
  std::vector<uint32_t> indices;
  const std::vector<std::shared_ptr<Process>>& processes =
      m_ProcessList.m_Processes;

  std::vector<std::wstring> tokens = Tokenize(ToLower(a_Filter));

  for (uint32_t i = 0; i < processes.size(); ++i) {
    const Process& process = *processes[i];
    std::wstring name = s2ws(ToLower(process.GetName()));
    std::wstring type = process.GetIs64Bit() ? L"64" : L"32";

    bool match = true;

    for (std::wstring& filterToken : tokens) {
      if (!(name.find(filterToken) != std::wstring::npos ||
            type.find(filterToken) != std::wstring::npos)) {
        match = false;
        break;
      }
    }

    if (match) {
      indices.push_back(i);
    }
  }

  m_Indices = indices;

  if (m_LastSortedColumn != -1) {
    OnSort(m_LastSortedColumn, {});
  }
}

//-----------------------------------------------------------------------------
void ProcessesDataView::UpdateProcessList() {
  size_t numProcesses = m_ProcessList.m_Processes.size();
  m_Indices.resize(numProcesses);
  for (uint32_t i = 0; i < numProcesses; ++i) {
    m_Indices[i] = i;
  }
}

//-----------------------------------------------------------------------------
void ProcessesDataView::SetRemoteProcessList(
    std::shared_ptr<ProcessList> a_RemoteProcessList) {
  m_IsRemote = true;
  m_ProcessList = *a_RemoteProcessList;
  UpdateProcessList();
  OnSort(m_LastSortedColumn, {});
  OnFilter(m_Filter);
  SetSelectedItem();
}

//-----------------------------------------------------------------------------
void ProcessesDataView::SetRemoteProcess(std::shared_ptr<Process> a_Process) {
  std::shared_ptr<Process> targetProcess =
      m_ProcessList.GetProcess(a_Process->GetID());
  if (targetProcess) {
    m_SelectedProcess = a_Process;
    UpdateModuleDataView(m_SelectedProcess);
  } else {
    m_RemoteProcess = a_Process;
  }
}

//-----------------------------------------------------------------------------
std::shared_ptr<Process> ProcessesDataView::GetProcess(
    unsigned int a_Row) const {
  return m_ProcessList.m_Processes[m_Indices[a_Row]];
}
<commit_msg>Make sure we can re-load module information on process selection.<commit_after>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------

#include "ProcessesDataView.h"

#include "App.h"
#include "Callstack.h"
#include "Capture.h"
#include "ModulesDataView.h"
#include "OrbitType.h"
#include "Params.h"
#include "Pdb.h"
#include "TcpClient.h"

//-----------------------------------------------------------------------------
ProcessesDataView::ProcessesDataView() {
  InitColumnsIfNeeded();
  m_SortingOrders.insert(m_SortingOrders.end(), s_InitialOrders.begin(),
                         s_InitialOrders.end());

  UpdateProcessList();
  m_UpdatePeriodMs = 1000;
  m_IsRemote = false;

  GOrbitApp->RegisterProcessesDataView(this);
}

//-----------------------------------------------------------------------------
std::vector<std::wstring> ProcessesDataView::s_Headers;
std::vector<float> ProcessesDataView::s_HeaderRatios;
std::vector<DataView::SortingOrder> ProcessesDataView::s_InitialOrders;

//-----------------------------------------------------------------------------
void ProcessesDataView::InitColumnsIfNeeded() {
  if (s_Headers.empty()) {
    s_Headers.emplace_back(L"PID");
    s_HeaderRatios.push_back(0);
    s_InitialOrders.push_back(AscendingOrder);

    s_Headers.emplace_back(L"Name");
    s_HeaderRatios.push_back(0.5f);
    s_InitialOrders.push_back(AscendingOrder);

    s_Headers.emplace_back(L"CPU");
    s_HeaderRatios.push_back(0);
    s_InitialOrders.push_back(DescendingOrder);

    s_Headers.emplace_back(L"Type");
    s_HeaderRatios.push_back(0);
    s_InitialOrders.push_back(AscendingOrder);
  }
}

//-----------------------------------------------------------------------------
const std::vector<std::wstring>& ProcessesDataView::GetColumnHeaders() {
  return s_Headers;
}

//-----------------------------------------------------------------------------
const std::vector<float>& ProcessesDataView::GetColumnHeadersRatios() {
  return s_HeaderRatios;
}

//-----------------------------------------------------------------------------
const std::vector<DataView::SortingOrder>&
ProcessesDataView::GetColumnInitialOrders() {
  return s_InitialOrders;
}

//-----------------------------------------------------------------------------
int ProcessesDataView::GetDefaultSortingColumn() { return PDV_CPU; }

//-----------------------------------------------------------------------------
std::wstring ProcessesDataView::GetValue(int row, int col) {
  const Process& process = *GetProcess(row);
  std::wstring value;

  switch (col) {
    case PDV_ProcessID:
      value = std::to_wstring((long)process.GetID());
      break;
    case PDV_ProcessName:
      value = s2ws(process.GetName());
      if (process.IsElevated()) {
        value += L"*";
      }
      break;
    case PDV_CPU:
      value = Format(L"%.1f", process.GetCpuUsage());
      break;
    case PDV_Type:
      value = process.GetIs64Bit() ? L"64 bit" : L"32 bit";
      break;
    default:
      break;
  }

  return value;
}

//-----------------------------------------------------------------------------
std::wstring ProcessesDataView::GetToolTip(int a_Row, int /*a_Column*/) {
  const Process& process = *GetProcess(a_Row);
  return s2ws(process.GetFullName());
}

//-----------------------------------------------------------------------------
#define ORBIT_PROC_SORT(Member)                                            \
  [&](int a, int b) {                                                      \
    return OrbitUtils::Compare(processes[a]->Member, processes[b]->Member, \
                               ascending);                                 \
  }

//-----------------------------------------------------------------------------
void ProcessesDataView::OnSort(int a_Column,
                               std::optional<SortingOrder> a_NewOrder) {
  if (a_Column == -1) {
    a_Column = PdvColumn::PDV_CPU;
  }

  const std::vector<std::shared_ptr<Process>>& processes =
      m_ProcessList.m_Processes;
  auto pdvColumn = static_cast<PdvColumn>(a_Column);

  if (a_NewOrder.has_value()) {
    m_SortingOrders[pdvColumn] = a_NewOrder.value();
  }

  bool ascending = m_SortingOrders[pdvColumn] == AscendingOrder;
  std::function<bool(int a, int b)> sorter = nullptr;

  switch (pdvColumn) {
    case PDV_ProcessID:
      sorter = ORBIT_PROC_SORT(GetID());
      break;
    case PDV_ProcessName:
      sorter = ORBIT_PROC_SORT(GetName());
      break;
    case PDV_CPU:
      sorter = ORBIT_PROC_SORT(GetCpuUsage());
      break;
    case PDV_Type:
      sorter = ORBIT_PROC_SORT(GetIs64Bit());
      break;
    default:
      break;
  }

  if (sorter) {
    std::sort(m_Indices.begin(), m_Indices.end(), sorter);
  }

  m_LastSortedColumn = a_Column;
  SetSelectedItem();
}

//-----------------------------------------------------------------------------
void ProcessesDataView::OnSelect(int a_Index) {
  m_SelectedProcess = GetProcess(a_Index);
  if (!m_IsRemote) {
    m_SelectedProcess->ListModules();
  } else {
    Message msg(Msg_RemoteProcessRequest);
    msg.m_Header.m_GenericHeader.m_Address = m_SelectedProcess->GetID();
    GTcpClient->Send(msg);
  }

  UpdateModuleDataView(m_SelectedProcess);
}

void ProcessesDataView::UpdateModuleDataView(
    std::shared_ptr<Process> a_Process) {
  if (m_ModulesDataView) {
    m_ModulesDataView->SetProcess(a_Process);
    Capture::SetTargetProcess(a_Process);
    GOrbitApp->FireRefreshCallbacks();
  }
}

//-----------------------------------------------------------------------------
void ProcessesDataView::OnTimer() { Refresh(); }

//-----------------------------------------------------------------------------
void ProcessesDataView::Refresh() {
  if (Capture::IsCapturing()) {
    return;
  }

  if (m_RemoteProcess) {
    std::shared_ptr<Process> CurrentRemoteProcess =
        m_ProcessList.m_Processes.size() == 1 ? m_ProcessList.m_Processes[0]
                                              : nullptr;

    if (m_RemoteProcess != CurrentRemoteProcess) {
      m_ProcessList.Clear();
      m_ProcessList.m_Processes.push_back(m_RemoteProcess);
      UpdateProcessList();
      SetFilter(L"");
      SelectProcess(m_RemoteProcess->GetID());
      SetSelectedItem();
    }
  } else {
    if (!m_IsRemote) {
      m_ProcessList.Refresh();
      m_ProcessList.UpdateCpuTimes();
    }
    UpdateProcessList();
    OnSort(m_LastSortedColumn, {});
    OnFilter(m_Filter);
    SetSelectedItem();

    if (Capture::GTargetProcess && !Capture::IsCapturing()) {
      Capture::GTargetProcess->UpdateThreadUsage();
    }
  }

  GParams.m_ProcessFilter = ws2s(m_Filter);
}

//-----------------------------------------------------------------------------
void ProcessesDataView::SetSelectedItem() {
  int initialIndex = m_SelectedIndex;
  m_SelectedIndex = -1;

  for (uint32_t i = 0; i < (uint32_t)GetNumElements(); ++i) {
    if (m_SelectedProcess &&
        GetProcess(i)->GetID() == m_SelectedProcess->GetID()) {
      m_SelectedIndex = i;
      return;
    }
  }

  if (GParams.m_AutoReleasePdb && initialIndex != -1) {
    ClearSelectedProcess();
  }
}

//-----------------------------------------------------------------------------
void ProcessesDataView::ClearSelectedProcess() {
  std::shared_ptr<Process> process = std::make_shared<Process>();
  Capture::SetTargetProcess(process);
  m_ModulesDataView->SetProcess(process);
  m_SelectedProcess = process;
  GPdbDbg = nullptr;
  GOrbitApp->FireRefreshCallbacks();
}

//-----------------------------------------------------------------------------
bool ProcessesDataView::SelectProcess(const std::wstring& a_ProcessName) {
  for (uint32_t i = 0; i < GetNumElements(); ++i) {
    Process& process = *GetProcess(i);
    if (process.GetFullName().find(ws2s(a_ProcessName)) != std::string::npos) {
      OnSelect(i);
      Capture::GPresetToLoad = "";
      return true;
    }
  }

  return false;
}

//-----------------------------------------------------------------------------
std::shared_ptr<Process> ProcessesDataView::SelectProcess(DWORD a_ProcessId) {
  Refresh();

  for (uint32_t i = 0; i < GetNumElements(); ++i) {
    Process& process = *GetProcess(i);
    if (process.GetID() == a_ProcessId) {
      OnSelect(i);
      Capture::GPresetToLoad = "";
      return m_SelectedProcess;
    }
  }

  return nullptr;
}

//-----------------------------------------------------------------------------
void ProcessesDataView::OnFilter(const std::wstring& a_Filter) {
  std::vector<uint32_t> indices;
  const std::vector<std::shared_ptr<Process>>& processes =
      m_ProcessList.m_Processes;

  std::vector<std::wstring> tokens = Tokenize(ToLower(a_Filter));

  for (uint32_t i = 0; i < processes.size(); ++i) {
    const Process& process = *processes[i];
    std::wstring name = s2ws(ToLower(process.GetName()));
    std::wstring type = process.GetIs64Bit() ? L"64" : L"32";

    bool match = true;

    for (std::wstring& filterToken : tokens) {
      if (!(name.find(filterToken) != std::wstring::npos ||
            type.find(filterToken) != std::wstring::npos)) {
        match = false;
        break;
      }
    }

    if (match) {
      indices.push_back(i);
    }
  }

  m_Indices = indices;

  if (m_LastSortedColumn != -1) {
    OnSort(m_LastSortedColumn, {});
  }
}

//-----------------------------------------------------------------------------
void ProcessesDataView::UpdateProcessList() {
  size_t numProcesses = m_ProcessList.m_Processes.size();
  m_Indices.resize(numProcesses);
  for (uint32_t i = 0; i < numProcesses; ++i) {
    m_Indices[i] = i;
  }
}

//-----------------------------------------------------------------------------
void ProcessesDataView::SetRemoteProcessList(
    std::shared_ptr<ProcessList> a_RemoteProcessList) {
  m_IsRemote = true;
  m_ProcessList = *a_RemoteProcessList;
  UpdateProcessList();
  OnSort(m_LastSortedColumn, {});
  OnFilter(m_Filter);
  SetSelectedItem();
}

//-----------------------------------------------------------------------------
void ProcessesDataView::SetRemoteProcess(std::shared_ptr<Process> a_Process) {
  std::shared_ptr<Process> targetProcess =
      m_ProcessList.GetProcess(a_Process->GetID());
  if (targetProcess) {
    m_SelectedProcess = a_Process;
    UpdateModuleDataView(m_SelectedProcess);
  } else {
    m_RemoteProcess = a_Process;
  }
}

//-----------------------------------------------------------------------------
std::shared_ptr<Process> ProcessesDataView::GetProcess(
    unsigned int a_Row) const {
  return m_ProcessList.m_Processes[m_Indices[a_Row]];
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <vector>
#include <fstream>
#include "ioHandler.h"
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem.hpp>
#include <map>
#include <unordered_map>
#include <boost/functional/hash.hpp>

#include "overlapper.h"

#define AST_COUNT 4096
namespace
{
    const size_t SUCCESS = 0;
    const size_t ERROR_IN_COMMAND_LINE = 1;
    const size_t ERROR_UNHANDLED_EXCEPTION = 2;

} // namespace

namespace bi = boost::iostreams;

int main(int argc, char** argv)
{
    const std::string program_name = "Overlapper";

    Counter counters;
    setupCounter(counters);

    std::string prefix;
    std::vector<std::string> default_outfiles = {"PE1", "PE2", "SE"};

    bool fastq_out;
    bool tab_out;
    bool std_out;
    bool std_in;
    bool gzip_out;
    bool interleaved_out;
    bool force;

    bool checkR2;

    size_t maxMismatch;
    size_t minLength;
    size_t minOverlap;
    bool adapterTrimming;
    bool stranded;
    std::string histFile;
    size_t checkLengths;
    std::string statsFile;
    bool appendStats;

    try
    {
        /** Define and parse the program options
         */
        namespace po = boost::program_options;
        po::options_description desc("Options");
        desc.add_options()
            ("version,v",                  "Version print")
            ("read1-input,1", po::value< std::vector<std::string> >(),
                                           "Read 1 input <comma sep for multiple files>")
            ("read2-input,2", po::value< std::vector<std::string> >(),
                                           "Read 2 input <comma sep for multiple files>")
            ("singleend-input,U", po::value< std::vector<std::string> >(),
                                           "Single end read input <comma sep for multiple files>")
            ("tab-input,T", po::value< std::vector<std::string> >(),
                                           "Tab input <comma sep for multiple files>")
            ("interleaved-input,I", po::value< std::vector<std::string> >(),
                                           "Interleaved input I <comma sep for multiple files>")
            ("stdin-input,S", po::bool_switch(&std_in)->default_value(false), "STDIN input <MUST BE TAB DELIMITED INPUT>")
            ("gzip-output,g", po::bool_switch(&gzip_out)->default_value(false),  "Output gzipped")
            ("interleaved-output,i", po::bool_switch(&interleaved_out)->default_value(false),     "Output to interleaved")
            ("fastq-output,f", po::bool_switch(&fastq_out)->default_value(false), "Fastq format output")
            ("force,F", po::bool_switch(&force)->default_value(false),         "Forces overwrite of files")
            ("tab-output,t", po::bool_switch(&tab_out)->default_value(false),   "Tab-delimited output")
            ("to-stdout,O", po::bool_switch(&std_out)->default_value(false),    "Prints to STDOUT in Tab Delimited")
            ("prefix,p", po::value<std::string>(&prefix)->default_value("overlapped_"),
                                           "Prefix for outputted files")
            ("minLength,l", po::value<size_t>(&minLength)->default_value(50), "Mismatches allowed in overlapped section")
            ("max-mismatches,x", po::value<size_t>(&maxMismatch)->default_value(5), "Mismatches allowed in overlapped section")
            ("check-lengths,c", po::value<size_t>(&checkLengths)->default_value(20), "Check lengths on the ends")
            ("min-overlap,o", po::value<size_t>(&minOverlap)->default_value(8), "Min overlap required to merge two reads")
            ("adapter-trimming,a", po::bool_switch(&adapterTrimming)->default_value(false), "Trims adapters based on overlap, only returns PE reads, will correct quality scores and BP in the PE reads")
            ("stranded,s", po::bool_switch(&stranded)->default_value(false), "Makes sure the correct complement is returned upon overlap")
            ("hist-file,e", po::value<std::string>(&histFile)->default_value(""), "A tab delimited hist file with insert lengths.")
            ("stats-file,L", po::value<std::string>(&statsFile)->default_value("stats.log") , "String for output stats file name")
            ("append-stats-file,A", po::bool_switch(&appendStats)->default_value(false),  "Append Stats file.")
            ("help,h",                     "Prints help.");

        po::variables_map vm;
        try
        {
            po::store(po::parse_command_line(argc, argv, desc),
                      vm); // can throw

            /** --help option
             */
            if ( vm.count("help")  || vm.size() == 0)
            {
                std::cout << "Tab-Converter" << std::endl
                          << desc << std::endl;
                return SUCCESS;
            }

            po::notify(vm); // throws on error, so do after help in case
            //Index 1 start location (making it more human friendly)

            std::shared_ptr<HtsOfstream> out_1 = nullptr;
            std::shared_ptr<HtsOfstream> out_2 = nullptr;
            std::shared_ptr<HtsOfstream> out_3 = nullptr;

            std::shared_ptr<OutputWriter> pe = nullptr;
            std::shared_ptr<OutputWriter> se = nullptr;

            if (fastq_out || (! std_out && ! tab_out) ) {
                for (auto& outfile: default_outfiles) {
                    outfile = prefix + outfile + ".fastq";
                }

                out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, false));
                out_2.reset(new HtsOfstream(default_outfiles[1], force, gzip_out, false));
                out_3.reset(new HtsOfstream(default_outfiles[2], force, gzip_out, false));

                pe.reset(new PairedEndReadOutFastq(out_1, out_2));
                se.reset(new SingleEndReadOutFastq(out_3));
            } else if (interleaved_out)  {
                for (auto& outfile: default_outfiles) {
                    outfile = prefix + "INTER" + ".fastq";
                }

                out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, false));
                out_3.reset(new HtsOfstream(default_outfiles[1], force, gzip_out, false));

                pe.reset(new PairedEndReadOutInter(out_1));
                se.reset(new SingleEndReadOutFastq(out_3));
            } else if (tab_out || std_out) {
                for (auto& outfile: default_outfiles) {
                    outfile = prefix + "tab" + ".tastq";
                }
                out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, std_out));

                pe.reset(new ReadBaseOutTab(out_1));
                se.reset(new ReadBaseOutTab(out_1));
            }
            histVec insertLengths;

            if (histFile == "") {
                insertLengths = nullptr;
            } else {
                insertLengths = histVec(new std::vector<unsigned long long int>);
            }

            //setLookup(lookup, lookup_rc, readPhix);
            // there are any problems
            if(vm.count("read1-input")) {
                if (!vm.count("read2-input")) {
                    throw std::runtime_error("must specify both read1 and read2 input files.");
                } else if (vm.count("read2-input") != vm.count("read1-input")) {
                    throw std::runtime_error("must have same number of input files for read1 and read2");
                }
                auto read1_files = vm["read1-input"].as<std::vector<std::string> >();
                auto read2_files = vm["read2-input"].as<std::vector<std::string> >();

                for(size_t i = 0; i < read1_files.size(); ++i) {
                    bi::stream<bi::file_descriptor_source> is1{check_open_r(read1_files[i]), bi::close_handle};
                    bi::stream<bi::file_descriptor_source> is2{check_open_r(read2_files[i]), bi::close_handle};
                    InputReader<PairedEndRead, PairedEndReadFastqImpl> ifp(is1, is2);
                    helper_overlapper(ifp, pe, se, counters, maxMismatch,  minOverlap, insertLengths, stranded, minLength, checkLengths,  adapterTrimming);
                }
            }

            if(vm.count("singleend-input")) {
                auto read_files = vm["singleend-input"].as<std::vector<std::string> >();
                for (auto file : read_files) {
                    bi::stream<bi::file_descriptor_source> sef{ check_open_r(file), bi::close_handle};
                    InputReader<SingleEndRead, SingleEndReadFastqImpl> ifs(sef);
                    //JUST WRITE se read out - no way to overlap
                    helper_overlapper(ifs, pe, se, counters, maxMismatch,  minOverlap, insertLengths, stranded, minLength, checkLengths,  adapterTrimming);
                }
            }

            if(vm.count("tab-input")) {
                auto read_files = vm["tab-input"].as<std::vector<std::string> > ();
                for (auto file : read_files) {
                    bi::stream<bi::file_descriptor_source> tabin{ check_open_r(file), bi::close_handle};
                    InputReader<ReadBase, TabReadImpl> ift(tabin);
                    helper_overlapper(ift, pe, se, counters, maxMismatch,  minOverlap, insertLengths, stranded, minLength, checkLengths,  adapterTrimming);
                }
            }

            if (vm.count("interleaved-input")) {
                auto read_files = vm["interleaved-input"].as<std::vector<std::string > >();
                for (auto file : read_files) {
                    bi::stream<bi::file_descriptor_source> inter{ check_open_r(file), bi::close_handle};
                    InputReader<PairedEndRead, InterReadImpl> ifp(inter);
                    helper_overlapper(ifp, pe, se, counters, maxMismatch,  minOverlap, insertLengths, stranded, minLength, checkLengths,  adapterTrimming);
                }
            }

            if (std_in) {
                bi::stream<bi::file_descriptor_source> tabin {fileno(stdin), bi::close_handle};
                InputReader<ReadBase, TabReadImpl> ift(tabin);
                helper_overlapper(ift, pe, se, counters, maxMismatch,  minOverlap, insertLengths, stranded, minLength, checkLengths,  adapterTrimming);
            }

            if (insertLengths) {
                std::ofstream histOutputFile(histFile);
                //0 is reserved for no overlap
                std::string stars;
                for (int i = 1; i < insertLengths->size(); ++i) {
                    stars = "";
                    if ((*insertLengths)[i]) {
                        stars = stars.insert(0, (*insertLengths)[i]/AST_COUNT, '*');
                        histOutputFile << i << '\t' << (*insertLengths)[i] << '\t' << stars << '\n';
                    }
                }
                stars = stars.insert(0, (*insertLengths)[0]/AST_COUNT, '*');
                histOutputFile << "None" << '\t' << (*insertLengths)[0] << '\t' << stars << '\n';
                histOutputFile.close();
            }
            write_stats(statsFile, appendStats, counters, program_name);
        }
        catch(po::error& e)
        {
            std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
            std::cerr << desc << std::endl;
            return ERROR_IN_COMMAND_LINE;
        }

    }
    catch(std::exception& e)
    {
        std::cerr << "\n\tUnhandled Exception: "
                  << e.what() << std::endl;
        return ERROR_UNHANDLED_EXCEPTION;

    }

    return SUCCESS;

}

<commit_msg>Fixed help text Fixed issue #38<commit_after>#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <vector>
#include <fstream>
#include "ioHandler.h"
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem.hpp>
#include <map>
#include <unordered_map>
#include <boost/functional/hash.hpp>

#include "overlapper.h"

#define AST_COUNT 4096
namespace
{
    const size_t SUCCESS = 0;
    const size_t ERROR_IN_COMMAND_LINE = 1;
    const size_t ERROR_UNHANDLED_EXCEPTION = 2;

} // namespace

namespace bi = boost::iostreams;

int main(int argc, char** argv)
{
    const std::string program_name = "Overlapper";

    Counter counters;
    setupCounter(counters);

    std::string prefix;
    std::vector<std::string> default_outfiles = {"PE1", "PE2", "SE"};

    bool fastq_out;
    bool tab_out;
    bool std_out;
    bool std_in;
    bool gzip_out;
    bool interleaved_out;
    bool force;

    bool checkR2;

    size_t maxMismatch;
    size_t minLength;
    size_t minOverlap;
    bool adapterTrimming;
    bool stranded;
    std::string histFile;
    size_t checkLengths;
    std::string statsFile;
    bool appendStats;

    try
    {
        /** Define and parse the program options
         */
        namespace po = boost::program_options;
        po::options_description desc("Options");
        desc.add_options()
            ("version,v",                  "Version print")
            ("read1-input,1", po::value< std::vector<std::string> >(),
                                           "Read 1 input <comma sep for multiple files>")
            ("read2-input,2", po::value< std::vector<std::string> >(),
                                           "Read 2 input <comma sep for multiple files>")
            ("singleend-input,U", po::value< std::vector<std::string> >(),
                                           "Single end read input <comma sep for multiple files>")
            ("tab-input,T", po::value< std::vector<std::string> >(),
                                           "Tab input <comma sep for multiple files>")
            ("interleaved-input,I", po::value< std::vector<std::string> >(),
                                           "Interleaved input I <comma sep for multiple files>")
            ("stdin-input,S", po::bool_switch(&std_in)->default_value(false), "STDIN input <MUST BE TAB DELIMITED INPUT>")
            ("gzip-output,g", po::bool_switch(&gzip_out)->default_value(false),  "Output gzipped")
            ("interleaved-output,i", po::bool_switch(&interleaved_out)->default_value(false),     "Output to interleaved")
            ("fastq-output,f", po::bool_switch(&fastq_out)->default_value(false), "Fastq format output")
            ("force,F", po::bool_switch(&force)->default_value(false),         "Forces overwrite of files")
            ("tab-output,t", po::bool_switch(&tab_out)->default_value(false),   "Tab-delimited output")
            ("to-stdout,O", po::bool_switch(&std_out)->default_value(false),    "Prints to STDOUT in Tab Delimited")
            ("prefix,p", po::value<std::string>(&prefix)->default_value("overlapped_"),
                                           "Prefix for outputted files")
            ("minLength,l", po::value<size_t>(&minLength)->default_value(50), "Minimum sequence length allowed without being discarded")
            ("max-mismatches,x", po::value<size_t>(&maxMismatch)->default_value(5), "Max number of mismatches allowed in overlapped section")
            ("check-lengths,c", po::value<size_t>(&checkLengths)->default_value(20), "Check lengths on the ends")
            ("min-overlap,o", po::value<size_t>(&minOverlap)->default_value(8), "Min overlap required to merge two reads")
            ("adapter-trimming,a", po::bool_switch(&adapterTrimming)->default_value(false), "Trims adapters based on overlap, only returns PE reads, will correct quality scores and BP in the PE reads")
            ("stranded,s", po::bool_switch(&stranded)->default_value(false), "Makes sure the correct complement is returned upon overlap")
            ("hist-file,e", po::value<std::string>(&histFile)->default_value(""), "A tab delimited hist file with insert lengths.")
            ("stats-file,L", po::value<std::string>(&statsFile)->default_value("stats.log") , "String for output stats file name")
            ("append-stats-file,A", po::bool_switch(&appendStats)->default_value(false),  "Append Stats file.")
            ("help,h",                     "Prints help.");

        po::variables_map vm;
        try
        {
            po::store(po::parse_command_line(argc, argv, desc),
                      vm); // can throw

            /** --help option
             */
            if ( vm.count("help")  || vm.size() == 0)
            {
                std::cout << "Tab-Converter" << std::endl
                          << desc << std::endl;
                return SUCCESS;
            }

            po::notify(vm); // throws on error, so do after help in case
            //Index 1 start location (making it more human friendly)

            std::shared_ptr<HtsOfstream> out_1 = nullptr;
            std::shared_ptr<HtsOfstream> out_2 = nullptr;
            std::shared_ptr<HtsOfstream> out_3 = nullptr;

            std::shared_ptr<OutputWriter> pe = nullptr;
            std::shared_ptr<OutputWriter> se = nullptr;

            if (fastq_out || (! std_out && ! tab_out) ) {
                for (auto& outfile: default_outfiles) {
                    outfile = prefix + outfile + ".fastq";
                }

                out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, false));
                out_2.reset(new HtsOfstream(default_outfiles[1], force, gzip_out, false));
                out_3.reset(new HtsOfstream(default_outfiles[2], force, gzip_out, false));

                pe.reset(new PairedEndReadOutFastq(out_1, out_2));
                se.reset(new SingleEndReadOutFastq(out_3));
            } else if (interleaved_out)  {
                for (auto& outfile: default_outfiles) {
                    outfile = prefix + "INTER" + ".fastq";
                }

                out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, false));
                out_3.reset(new HtsOfstream(default_outfiles[1], force, gzip_out, false));

                pe.reset(new PairedEndReadOutInter(out_1));
                se.reset(new SingleEndReadOutFastq(out_3));
            } else if (tab_out || std_out) {
                for (auto& outfile: default_outfiles) {
                    outfile = prefix + "tab" + ".tastq";
                }
                out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, std_out));

                pe.reset(new ReadBaseOutTab(out_1));
                se.reset(new ReadBaseOutTab(out_1));
            }
            histVec insertLengths;

            if (histFile == "") {
                insertLengths = nullptr;
            } else {
                insertLengths = histVec(new std::vector<unsigned long long int>);
            }

            //setLookup(lookup, lookup_rc, readPhix);
            // there are any problems
            if(vm.count("read1-input")) {
                if (!vm.count("read2-input")) {
                    throw std::runtime_error("must specify both read1 and read2 input files.");
                } else if (vm.count("read2-input") != vm.count("read1-input")) {
                    throw std::runtime_error("must have same number of input files for read1 and read2");
                }
                auto read1_files = vm["read1-input"].as<std::vector<std::string> >();
                auto read2_files = vm["read2-input"].as<std::vector<std::string> >();

                for(size_t i = 0; i < read1_files.size(); ++i) {
                    bi::stream<bi::file_descriptor_source> is1{check_open_r(read1_files[i]), bi::close_handle};
                    bi::stream<bi::file_descriptor_source> is2{check_open_r(read2_files[i]), bi::close_handle};
                    InputReader<PairedEndRead, PairedEndReadFastqImpl> ifp(is1, is2);
                    helper_overlapper(ifp, pe, se, counters, maxMismatch,  minOverlap, insertLengths, stranded, minLength, checkLengths,  adapterTrimming);
                }
            }

            if(vm.count("singleend-input")) {
                auto read_files = vm["singleend-input"].as<std::vector<std::string> >();
                for (auto file : read_files) {
                    bi::stream<bi::file_descriptor_source> sef{ check_open_r(file), bi::close_handle};
                    InputReader<SingleEndRead, SingleEndReadFastqImpl> ifs(sef);
                    //JUST WRITE se read out - no way to overlap
                    helper_overlapper(ifs, pe, se, counters, maxMismatch,  minOverlap, insertLengths, stranded, minLength, checkLengths,  adapterTrimming);
                }
            }

            if(vm.count("tab-input")) {
                auto read_files = vm["tab-input"].as<std::vector<std::string> > ();
                for (auto file : read_files) {
                    bi::stream<bi::file_descriptor_source> tabin{ check_open_r(file), bi::close_handle};
                    InputReader<ReadBase, TabReadImpl> ift(tabin);
                    helper_overlapper(ift, pe, se, counters, maxMismatch,  minOverlap, insertLengths, stranded, minLength, checkLengths,  adapterTrimming);
                }
            }

            if (vm.count("interleaved-input")) {
                auto read_files = vm["interleaved-input"].as<std::vector<std::string > >();
                for (auto file : read_files) {
                    bi::stream<bi::file_descriptor_source> inter{ check_open_r(file), bi::close_handle};
                    InputReader<PairedEndRead, InterReadImpl> ifp(inter);
                    helper_overlapper(ifp, pe, se, counters, maxMismatch,  minOverlap, insertLengths, stranded, minLength, checkLengths,  adapterTrimming);
                }
            }

            if (std_in) {
                bi::stream<bi::file_descriptor_source> tabin {fileno(stdin), bi::close_handle};
                InputReader<ReadBase, TabReadImpl> ift(tabin);
                helper_overlapper(ift, pe, se, counters, maxMismatch,  minOverlap, insertLengths, stranded, minLength, checkLengths,  adapterTrimming);
            }

            if (insertLengths) {
                std::ofstream histOutputFile(histFile);
                //0 is reserved for no overlap
                std::string stars;
                for (int i = 1; i < insertLengths->size(); ++i) {
                    stars = "";
                    if ((*insertLengths)[i]) {
                        stars = stars.insert(0, (*insertLengths)[i]/AST_COUNT, '*');
                        histOutputFile << i << '\t' << (*insertLengths)[i] << '\t' << stars << '\n';
                    }
                }
                stars = stars.insert(0, (*insertLengths)[0]/AST_COUNT, '*');
                histOutputFile << "None" << '\t' << (*insertLengths)[0] << '\t' << stars << '\n';
                histOutputFile.close();
            }
            write_stats(statsFile, appendStats, counters, program_name);
        }
        catch(po::error& e)
        {
            std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
            std::cerr << desc << std::endl;
            return ERROR_IN_COMMAND_LINE;
        }

    }
    catch(std::exception& e)
    {
        std::cerr << "\n\tUnhandled Exception: "
                  << e.what() << std::endl;
        return ERROR_UNHANDLED_EXCEPTION;

    }

    return SUCCESS;

}

<|endoftext|>