<commit_before>
#include "pch.h"
#include "keyman-debug-etw.h"

#ifdef _WIN64
#define DEBUG_PLATFORM_STRING "x64"
#define DEBUG_PLATFORM_STRINGW L"x64"
#else
#define DEBUG_PLATFORM_STRING "x86"
#define DEBUG_PLATFORM_STRINGW L"x86"
#endif

#define TAB L"\t"

int GetActualShiftState() {   // I4843
  int state = 0;
  if (GetKeyState(VK_NUMLOCK) & 1) state |= NUMLOCKFLAG;
  if (GetKeyState(VK_CAPITAL) & 1) state |= CAPITALFLAG;
  if (GetKeyState(VK_SHIFT) < 0) state |= K_SHIFTFLAG;
  if (GetKeyState(VK_RCONTROL) < 0) state |= RCTRLFLAG;
  if (GetKeyState(VK_LCONTROL) < 0) state |= LCTRLFLAG;
  if (GetKeyState(VK_LMENU) < 0) state |= LALTFLAG;
  if (GetKeyState(VK_RMENU) < 0) state |= RALTFLAG;

  if (GetKeyState(VK_LSHIFT) < 0) state |= 0x10000;
  if (GetKeyState(VK_RSHIFT) < 0) state |= 0x20000;

  return state;
}

extern "C" void _declspec(dllexport) WINAPI Keyman_WriteDebugEvent(char *file, int line, PWCHAR msg) {
  if (file == NULL || msg == NULL) {
    return;
  }

  PKEYMAN64THREADDATA _td = ThreadGlobals();
  if (!_td) {
    return;
  }

  if (!Globals::get_debug_KeymanLog()) {
    return;
  }

  GUITHREADINFO gti;
  WCHAR sProcessPath[256], sProcessName[32];

  gti.cbSize = sizeof(gti);
  GetGUIThreadInfo(GetCurrentThreadId(), &gti);

  GetModuleFileNameW(NULL, sProcessPath, 256);
  _wsplitpath_s(sProcessPath, NULL, 0, NULL, 0, sProcessName, 32, NULL, 0);
  sProcessName[31] = 0;

  if (wcslen(msg) > 256) {
    msg[255] = 0;
  }

  if (Globals::get_debug_ToConsole()) {   // I3951
    WCHAR windowinfo[1024];
    wsprintfW(windowinfo,
      DEBUG_PLATFORM_STRINGW TAB //"Platform" TAB
      L"%s" TAB  //"Process" TAB
      L"%x" TAB  //"PID" TAB
      L"%x" TAB  //"TID" TAB
      L"%x" TAB  //"ShiftState" TAB
      L"%x" TAB  //"ActualShiftState" TAB
      L"%d" TAB  //"TickCount" TAB
      L"%x" TAB  //"FocusHWND" TAB
      L"%8x" TAB //"ActiveHKL" TAB
      L"%hs:%d" TAB  //"SourceFile" TAB
      L"%s\n",     //"Message"
      sProcessName,                    //"Process" TAB
      GetCurrentProcessId(),           //"PID" TAB
      GetCurrentThreadId(),            //"TID" TAB
      Globals::get_ShiftState(),       //"ShiftState" TAB
      GetActualShiftState(),           // ActualShiftState TAB
      GetTickCount(),                  //"TickCount" TAB
      gti.hwndFocus,                   //"FocusHWND" TAB
      GetKeyboardLayout(0),            //"ActiveHKL" TAB
      file, line,                      //"SourceFile" TAB
      msg);                            //"Message"

    OutputDebugStringW(windowinfo);
  }

  if (_td->etwRegHandle != NULL) {
#define MAX_DESCRIPTORS 12
    EVENT_DATA_DESCRIPTOR Descriptors[MAX_DESCRIPTORS];
    DWORD pid = GetCurrentProcessId();
    DWORD tid = GetCurrentThreadId();
    DWORD shiftState = Globals::get_ShiftState();
    DWORD actualShiftState = GetActualShiftState();
    DWORD tickCount = GetTickCount();
    HKL activeHKL = GetKeyboardLayout(0);

#ifdef _WIN64
    DWORD platform = 2;
#else
    DWORD platform = 1;
#endif

    // TODO Convert to Unicode
    PWCHAR fileW = strtowstr(file);

    // These must match the manifest template in keyman-debug-etw.man
    EventDataDescCreate(&Descriptors[0], &platform, sizeof(DWORD)); // <data name = "Platform" inType = "Platform" / >
    EventDataDescCreate(&Descriptors[1], sProcessName, (ULONG)(wcslen(sProcessName) + 1) * sizeof(WCHAR)); //  <data name = "Process" inType = "win:UnicodeString" / >
    EventDataDescCreate(&Descriptors[2], &pid, sizeof(DWORD)); //  <data name = "PID" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[3], &tid, sizeof(DWORD)); //  <data name = "TID" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[4], &shiftState, sizeof(DWORD)); //  <data name = "ShiftState" inType = "ShiftState" / >
    EventDataDescCreate(&Descriptors[5], &actualShiftState, sizeof(DWORD)); //  <data name = "ActualShiftState" inType = "ShiftState" / >
    EventDataDescCreate(&Descriptors[6], &tickCount, sizeof(DWORD)); //  <data name = "TickCount" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[7], (PDWORD)&gti.hwndFocus, sizeof(DWORD)); //  <data name = "FocusHWND" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[8], (PDWORD)&activeHKL, sizeof(DWORD)); //  <data name = "ActiveHKL" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[9], fileW, (ULONG)(wcslen(fileW) + 1) * sizeof(WCHAR)); //  <data name = "SourceFile" inType = "win:UnicodeString" / >
    EventDataDescCreate(&Descriptors[10], (PDWORD)&line, sizeof(DWORD)); //  <data name = "SourceLine" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[11], msg, (ULONG)(wcslen(msg) + 1) * sizeof(WCHAR)); //  <data name = "Message" inType = "win:UnicodeString" / >

    DWORD dwErr = EventWrite(_td->etwRegHandle, &DebugEvent, (ULONG)MAX_DESCRIPTORS, &Descriptors[0]);
    if (dwErr != ERROR_SUCCESS) {
      OutputDebugString("Keyman k32_dbg: Failed to call EventWrite");
    }

    delete fileW;
  }
}
<commit_msg>[Windows] Resolve review comments<commit_after>
#include "pch.h"
#include "keyman-debug-etw.h"

#ifdef _WIN64
#define DEBUG_PLATFORM_STRING "x64"
#define DEBUG_PLATFORM_STRINGW L"x64"
#else
#define DEBUG_PLATFORM_STRING "x86"
#define DEBUG_PLATFORM_STRINGW L"x86"
#endif

#define TAB L"\t"

int GetActualShiftState() {   // I4843
  int state = 0;
  if (GetKeyState(VK_NUMLOCK) & 1) state |= NUMLOCKFLAG;
  if (GetKeyState(VK_CAPITAL) & 1) state |= CAPITALFLAG;
  if (GetKeyState(VK_SHIFT) < 0) state |= K_SHIFTFLAG;
  if (GetKeyState(VK_RCONTROL) < 0) state |= RCTRLFLAG;
  if (GetKeyState(VK_LCONTROL) < 0) state |= LCTRLFLAG;
  if (GetKeyState(VK_LMENU) < 0) state |= LALTFLAG;
  if (GetKeyState(VK_RMENU) < 0) state |= RALTFLAG;

  if (GetKeyState(VK_LSHIFT) < 0) state |= 0x10000;
  if (GetKeyState(VK_RSHIFT) < 0) state |= 0x20000;

  return state;
}

extern "C" void _declspec(dllexport) WINAPI Keyman_WriteDebugEvent(char *file, int line, PWCHAR msg) {
  if (file == NULL || msg == NULL) {
    return;
  }

  PKEYMAN64THREADDATA _td = ThreadGlobals();
  if (!_td) {
    return;
  }

  if (!Globals::get_debug_KeymanLog()) {
    return;
  }

  GUITHREADINFO gti;
  WCHAR sProcessPath[256], sProcessName[32];

  gti.cbSize = sizeof(gti);
  GetGUIThreadInfo(GetCurrentThreadId(), &gti);

  GetModuleFileNameW(NULL, sProcessPath, 256);
  _wsplitpath_s(sProcessPath, NULL, 0, NULL, 0, sProcessName, 32, NULL, 0);
  sProcessName[31] = 0;

  if (wcslen(msg) > 256) {
    msg[255] = 0;
  }

  DWORD pid = GetCurrentProcessId();
  DWORD tid = GetCurrentThreadId();
  DWORD shiftState = Globals::get_ShiftState();
  DWORD actualShiftState = GetActualShiftState();
  DWORD tickCount = GetTickCount();
  HKL activeHKL = GetKeyboardLayout(0);

  if (Globals::get_debug_ToConsole()) {   // I3951
    WCHAR windowinfo[1024];
    wsprintfW(windowinfo,
      DEBUG_PLATFORM_STRINGW TAB //"Platform" TAB
      L"%s" TAB  //"Process" TAB
      L"%x" TAB  //"PID" TAB
      L"%x" TAB  //"TID" TAB
      L"%x" TAB  //"ShiftState" TAB
      L"%x" TAB  //"ActualShiftState" TAB
      L"%d" TAB  //"TickCount" TAB
      L"%x" TAB  //"FocusHWND" TAB
      L"%8x" TAB //"ActiveHKL" TAB
      L"%hs:%d" TAB  //"SourceFile" TAB
      L"%s\n",     //"Message"
      sProcessName,                    //"Process" TAB
      pid,                             //"PID" TAB
      tid,                             //"TID" TAB
      shiftState,                      //"ShiftState" TAB
      actualShiftState,                // ActualShiftState TAB
      tickCount,                       //"TickCount" TAB
      gti.hwndFocus,                   //"FocusHWND" TAB
      activeHKL,                       //"ActiveHKL" TAB
      file, line,                      //"SourceFile" TAB
      msg);                            //"Message"

    OutputDebugStringW(windowinfo);
  }

  if (_td->etwRegHandle != NULL) {
#define MAX_DESCRIPTORS 12
    EVENT_DATA_DESCRIPTOR Descriptors[MAX_DESCRIPTORS];

#ifdef _WIN64
    DWORD platform = 2;
#else
    DWORD platform = 1;
#endif

    // TODO Convert to Unicode
    PWCHAR fileW = strtowstr(file);

    // These must match the manifest template in keyman-debug-etw.man
    EventDataDescCreate(&Descriptors[0], &platform, sizeof(DWORD)); // <data name = "Platform" inType = "Platform" / >
    EventDataDescCreate(&Descriptors[1], sProcessName, (ULONG)(wcslen(sProcessName) + 1) * sizeof(WCHAR)); //  <data name = "Process" inType = "win:UnicodeString" / >
    EventDataDescCreate(&Descriptors[2], &pid, sizeof(DWORD)); //  <data name = "PID" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[3], &tid, sizeof(DWORD)); //  <data name = "TID" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[4], &shiftState, sizeof(DWORD)); //  <data name = "ShiftState" inType = "ShiftState" / >
    EventDataDescCreate(&Descriptors[5], &actualShiftState, sizeof(DWORD)); //  <data name = "ActualShiftState" inType = "ShiftState" / >
    EventDataDescCreate(&Descriptors[6], &tickCount, sizeof(DWORD)); //  <data name = "TickCount" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[7], (PDWORD)&gti.hwndFocus, sizeof(DWORD)); //  <data name = "FocusHWND" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[8], (PDWORD)&activeHKL, sizeof(DWORD)); //  <data name = "ActiveHKL" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[9], fileW, (ULONG)(wcslen(fileW) + 1) * sizeof(WCHAR)); //  <data name = "SourceFile" inType = "win:UnicodeString" / >
    EventDataDescCreate(&Descriptors[10], (PDWORD)&line, sizeof(DWORD)); //  <data name = "SourceLine" inType = "win:UInt32" / >
    EventDataDescCreate(&Descriptors[11], msg, (ULONG)(wcslen(msg) + 1) * sizeof(WCHAR)); //  <data name = "Message" inType = "win:UnicodeString" / >

    DWORD dwErr = EventWrite(_td->etwRegHandle, &DebugEvent, (ULONG)MAX_DESCRIPTORS, &Descriptors[0]);
    if (dwErr != ERROR_SUCCESS) {
      OutputDebugString("Keyman k32_dbg: Failed to call EventWrite");
    }

    delete fileW;
  }
}
<|endoftext|>


<commit_before>#include "error_calc.hh"

#include <dune/fem/misc/h1norm.hh>
#include <dune/fem/misc/l2norm.hh>
#include <dune/fem/misc/l2error.hh>

#include <dune/multiscale/problems/elliptic/selector.hh>
#include <iostream>

Dune::Multiscale::ErrorCalculator::ErrorCalculator(const CommonTraits::DiscreteFunctionType *msfem_solution,
                                                   const CommonTraits::DiscreteFunctionType *fem_solution)
    : msfem_solution_(msfem_solution)
    , fem_solution_(fem_solution)
{}

void Dune::Multiscale::ErrorCalculator::print(std::ostream &out)
{
    assert(msfem_solution_ || fem_solution_);
    out << std::endl << "The L2 errors:" << std::endl << std::endl;

    auto gridPart = fem_solution_ ? fem_solution_->gridPart()
                                  : msfem_solution_->gridPart();
    Dune::H1Norm< CommonTraits::GridPartType > h1norm(gridPart);
    Dune::L2Error< typename CommonTraits::DiscreteFunctionType > l2error;

    //! ----------------- compute L2- and H1- errors -------------------
    if (Problem::ModelProblemData::has_exact_solution)
    {

      const CommonTraits::ExactSolutionType u;
      const int experimentally_determined_maximum_order_for_GridFunctionAdapter_bullshit = 6;
      const Dune::GridFunctionAdapter<CommonTraits::ExactSolutionType, CommonTraits::GridPartType>
          u_disc("", u, gridPart, experimentally_determined_maximum_order_for_GridFunctionAdapter_bullshit);

      if (msfem_solution_)
      {
          CommonTraits::RangeType msfem_error = l2error.norm(u, *msfem_solution_ );
          out << "|| u_msfem - u_exact ||_L2 =  " << msfem_error << std::endl;

          CommonTraits::RangeType h1_msfem_error = h1norm.distance(u_disc, *msfem_solution_);
          out << "|| u_msfem - u_exact ||_H1 =  " << h1_msfem_error << std::endl << std::endl;
      }

      if (fem_solution_)
      {
        CommonTraits::RangeType fem_error = l2error.norm(u, *fem_solution_);
        out << "|| u_fem - u_exact ||_L2 =  " << fem_error << std::endl;

        CommonTraits::RangeType h1_fem_error = h1norm.distance(u_disc, *fem_solution_);
        out << "|| u_fem - u_exact ||_H1 =  " << h1_fem_error << std::endl << std::endl;
      }
    }
    if ( msfem_solution_ && fem_solution_) {
      CommonTraits::RangeType approx_msfem_error = l2error.norm2< 2* CommonTraits::DiscreteFunctionSpaceType::polynomialOrder + 2 >(*fem_solution_,
                                                                                *msfem_solution_);
      out << "|| u_msfem - u_fem ||_L2 =  " << approx_msfem_error << std::endl;

      CommonTraits::RangeType h1_approx_msfem_error = h1norm.distance(*fem_solution_, *msfem_solution_);
      out << "|| u_msfem - u_fem ||_H1 =  " << h1_approx_msfem_error << std::endl << std::endl;
    }
}
<commit_msg>output errors to csv file<commit_after>#include "error_calc.hh"

#include <dune/fem/misc/h1norm.hh>
#include <dune/fem/misc/l2norm.hh>
#include <dune/fem/misc/l2error.hh>
#include <dune/stuff/common/filesystem.hh>

#include <dune/multiscale/problems/elliptic/selector.hh>
#include <iostream>

Dune::Multiscale::ErrorCalculator::ErrorCalculator(const CommonTraits::DiscreteFunctionType *msfem_solution,
                                                   const CommonTraits::DiscreteFunctionType *fem_solution)
    : msfem_solution_(msfem_solution)
    , fem_solution_(fem_solution)
{}

void Dune::Multiscale::ErrorCalculator::print(std::ostream &out)
{
    assert(msfem_solution_ || fem_solution_);
    out << std::endl << "The L2 errors:" << std::endl << std::endl;

    auto gridPart = fem_solution_ ? fem_solution_->gridPart()
                                  : msfem_solution_->gridPart();
    Dune::H1Norm< CommonTraits::GridPartType > h1norm(gridPart);
    Dune::L2Error< typename CommonTraits::DiscreteFunctionType > l2error;

    std::map<std::string,double> csv;

    //! ----------------- compute L2- and H1- errors -------------------
    if (Problem::ModelProblemData::has_exact_solution)
    {

      const CommonTraits::ExactSolutionType u;
      const int experimentally_determined_maximum_order_for_GridFunctionAdapter_bullshit = 6;
      const Dune::GridFunctionAdapter<CommonTraits::ExactSolutionType, CommonTraits::GridPartType>
          u_disc("", u, gridPart, experimentally_determined_maximum_order_for_GridFunctionAdapter_bullshit);

      if (msfem_solution_)
      {
          CommonTraits::RangeType msfem_error = l2error.norm(u, *msfem_solution_ );
          out << "|| u_msfem - u_exact ||_L2 =  " << msfem_error << std::endl;

          CommonTraits::RangeType h1_msfem_error = h1norm.distance(u_disc, *msfem_solution_);
          out << "|| u_msfem - u_exact ||_H1 =  " << h1_msfem_error << std::endl << std::endl;

          csv["msfem_exact_L2"] = msfem_error;
          csv["msfem_exact_H1"] = h1_msfem_error;
      }

      if (fem_solution_)
      {
        CommonTraits::RangeType fem_error = l2error.norm(u, *fem_solution_);
        out << "|| u_fem - u_exact ||_L2 =  " << fem_error << std::endl;

        CommonTraits::RangeType h1_fem_error = h1norm.distance(u_disc, *fem_solution_);
        out << "|| u_fem - u_exact ||_H1 =  " << h1_fem_error << std::endl << std::endl;

        csv["fem_exact_L2"] = fem_error;
        csv["fem_exact_H1"] = h1_fem_error;
      }
    }
    if ( msfem_solution_ && fem_solution_) {
      CommonTraits::RangeType approx_msfem_error = l2error.norm2< 2* CommonTraits::DiscreteFunctionSpaceType::polynomialOrder + 2 >(*fem_solution_,
                                                                                *msfem_solution_);
      out << "|| u_msfem - u_fem ||_L2 =  " << approx_msfem_error << std::endl;

      CommonTraits::RangeType h1_approx_msfem_error = h1norm.distance(*fem_solution_, *msfem_solution_);
      out << "|| u_msfem - u_fem ||_H1 =  " << h1_approx_msfem_error << std::endl << std::endl;

      csv["msfem_fem_L2"] = approx_msfem_error;
      csv["msfem_fem_H1"] = h1_approx_msfem_error;
    }

    std::unique_ptr<boost::filesystem::ofstream> csvfile(DSC::make_ofstream("errors.csv"));
    const std::string sep(",");
    for(const auto& key_val : csv)
    {
      *csvfile << key_val.first << sep;
    }
    *csvfile << std::endl;
    for(const auto& key_val : csv)
    {
      *csvfile << key_val.second << sep;
    }
    *csvfile << std::endl;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: chalign.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-04-11 21:16:47 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SFX_CHILDALIGN_HXX
#define _SFX_CHILDALIGN_HXX

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

// Neue Reihenfolge: zuerst Navigationsleiste, dann senkrecht angedockte
// ChildWindows (Explorer!), dann horizontal angedockte ChildWindows (Browser!),
// dann die Formatleiste, die Statuszeile, am Ende die Werkzeugleiste.

enum SfxChildAlignment
{
    SFX_ALIGN_HIGHESTTOP,       // z.B. Navigationsleiste
    SFX_ALIGN_LOWESTBOTTOM,
    SFX_ALIGN_FIRSTLEFT,
    SFX_ALIGN_LASTRIGHT,
    SFX_ALIGN_LEFT,             // z.B. SplitWindow
    SFX_ALIGN_RIGHT,
    SFX_ALIGN_LASTLEFT,
    SFX_ALIGN_FIRSTRIGHT,
    SFX_ALIGN_TOP,              // z.B. Hyperlink-Builder, SplitWindow
    SFX_ALIGN_BOTTOM,           // z.B. SplitWindow
    SFX_ALIGN_TOOLBOXTOP,       // z.B. Objektleiste
    SFX_ALIGN_TOOLBOXBOTTOM,
    SFX_ALIGN_LOWESTTOP,        // z.B. Calc-Rechenleiste
    SFX_ALIGN_HIGHESTBOTTOM,    // z.B. Statusleiste
    SFX_ALIGN_TOOLBOXLEFT,      // z.B. Werkzeugleiste
    SFX_ALIGN_TOOLBOXRIGHT,
    SFX_ALIGN_NOALIGNMENT       // alle FloatingWindows
};

// "Uberpr"uft, ob ein g"ultiges Alignment verwendet wird
inline BOOL SfxChildAlignValid( SfxChildAlignment eAlign )
{
    return ( eAlign >= SFX_ALIGN_HIGHESTTOP && eAlign <= SFX_ALIGN_NOALIGNMENT );
}

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.280); FILE MERGED 2008/04/01 15:38:19 thb 1.2.280.2: #i85898# Stripping all external header guards 2008/03/31 13:37:55 rt 1.2.280.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: chalign.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SFX_CHILDALIGN_HXX
#define _SFX_CHILDALIGN_HXX

#include <tools/solar.h>

// Neue Reihenfolge: zuerst Navigationsleiste, dann senkrecht angedockte
// ChildWindows (Explorer!), dann horizontal angedockte ChildWindows (Browser!),
// dann die Formatleiste, die Statuszeile, am Ende die Werkzeugleiste.

enum SfxChildAlignment
{
    SFX_ALIGN_HIGHESTTOP,       // z.B. Navigationsleiste
    SFX_ALIGN_LOWESTBOTTOM,
    SFX_ALIGN_FIRSTLEFT,
    SFX_ALIGN_LASTRIGHT,
    SFX_ALIGN_LEFT,             // z.B. SplitWindow
    SFX_ALIGN_RIGHT,
    SFX_ALIGN_LASTLEFT,
    SFX_ALIGN_FIRSTRIGHT,
    SFX_ALIGN_TOP,              // z.B. Hyperlink-Builder, SplitWindow
    SFX_ALIGN_BOTTOM,           // z.B. SplitWindow
    SFX_ALIGN_TOOLBOXTOP,       // z.B. Objektleiste
    SFX_ALIGN_TOOLBOXBOTTOM,
    SFX_ALIGN_LOWESTTOP,        // z.B. Calc-Rechenleiste
    SFX_ALIGN_HIGHESTBOTTOM,    // z.B. Statusleiste
    SFX_ALIGN_TOOLBOXLEFT,      // z.B. Werkzeugleiste
    SFX_ALIGN_TOOLBOXRIGHT,
    SFX_ALIGN_NOALIGNMENT       // alle FloatingWindows
};

// "Uberpr"uft, ob ein g"ultiges Alignment verwendet wird
inline BOOL SfxChildAlignValid( SfxChildAlignment eAlign )
{
    return ( eAlign >= SFX_ALIGN_HIGHESTTOP && eAlign <= SFX_ALIGN_NOALIGNMENT );
}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2010 MQWeb - Franky Braem
 *
 * Licensed under the EUPL, Version 1.1 or - as soon they
 * will be approved by the European Commission - subsequent
 * versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the
 * Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in
 * writing, software distributed under the Licence is
 * distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the Licence for the specific language governing
 * permissions and limitations under the Licence.
 */
#include "MQ/Web/MQMapper.h"

#include "MQ/MQException.h"

#include "Poco/JSON/Object.h"
#include "Poco/Logger.h"

namespace MQ {
namespace Web {

DictionaryCache MQMapper::_dictionaryCache;

Dictionary MQMapper::_operators = Dictionary()
	(MQCFOP_LESS, "LT")
	(MQCFOP_LESS | MQCFOP_EQUAL, "LE")
	(MQCFOP_EQUAL, "EQ")
	(MQCFOP_GREATER, "GT")
	(MQCFOP_GREATER | MQCFOP_EQUAL, "GE")
	(MQCFOP_NOT_LESS, "NLT")
	(MQCFOP_NOT_EQUAL, "NE")
	(MQCFOP_NOT_GREATER, "NGT")
	(MQCFOP_LIKE, "LK")
	(MQCFOP_NOT_LIKE, "NL")
	(MQCFOP_CONTAINS, "CT")
	(MQCFOP_EXCLUDES, "EX")
	(MQCFOP_CONTAINS_GEN, "CTG")
	(MQCFOP_EXCLUDES_GEN, "EXG")
;

MQMapper::MQMapper(CommandServer& commandServer, const std::string& objectType, Poco::JSON::Object::Ptr input)
  : _commandServer(commandServer)
  , _input(input)
{
	_dictionary = _dictionaryCache.getDictionary(objectType);
	poco_assert_dbg(!_dictionary.isNull());

	if ( _dictionary.isNull() )
	{
		Poco::Logger& logger = Poco::Logger::get("mq.web");
		logger.error(Poco::Logger::format("$0 not found in dictionary database", objectType));
	}
}

MQMapper::~MQMapper()
{
}

std::string MQMapper::getReasonString(MQLONG reasonCode)
{
	static Poco::SharedPtr<Dictionary> dict = _dictionaryCache.getDictionary("Reason");

	return dict->getDisplayValue(MQIACF_REASON_CODE, reasonCode);
}

std::string MQMapper::getCommandString(MQLONG command)
{
	static Poco::SharedPtr<Dictionary> dict = _dictionaryCache.getDictionary("Event");
	return dict->getDisplayValue(MQIACF_COMMAND, command);
}

MQLONG MQMapper::getOperator(const std::string& op)
{
	return _operators.getId(op);
}

const DisplayMap& MQMapper::getDisplayMap(const std::string& objectType, MQLONG id)
{
	Poco::SharedPtr<Dictionary> dict = _dictionaryCache.getDictionary(objectType);
	poco_assert_dbg(!dict.isNull());

	if ( dict.isNull() )
	{
		Poco::Logger& logger = Poco::Logger::get("mq.web");
		logger.error(Poco::Logger::format("$0 not found in dictionary database", objectType));
	}

	return dict->getDisplayMap(id);
}

void MQMapper::addIntegerFilter()
{
	poco_assert_dbg(!_pcf.isNull());

	Poco::JSON::Object::Ptr integerFilter = _input->getObject("IntegerFilterCommand");
	if ( integerFilter.isNull() )
		return;

	std::string parameterName = integerFilter->optValue<std::string>("Parameter", "");
	MQLONG parameter = _dictionary->getId(parameterName);
	if ( parameter == -1 )
		return;

	std::string opString = integerFilter->optValue<std::string>("Operator", "EQ");
	MQLONG op = getOperator(Poco::toUpper(opString));
	if ( op == -1 ) op = MQCFOP_EQUAL;

	Poco::Dynamic::Var value = integerFilter->get("FilterValue");
	MQLONG filterValue;
	if ( value.isString() )
	{
		// A String is passed ... try to find the MQ integer value
		filterValue = _dictionary->getDisplayId(parameter, value);
	}
	else if ( value.isNumeric() )
	{
		filterValue = value;
	}
	_pcf->addFilter(parameter, op, filterValue);
}

void MQMapper::addStringFilter()
{
	poco_assert_dbg(!_pcf.isNull());

	Poco::JSON::Object::Ptr stringFilter = _input->getObject("StringFilterCommand");
	if ( stringFilter.isNull() )
		return;

	std::string parameterName = stringFilter->optValue<std::string>("Parameter", "");
	MQLONG parameter = _dictionary->getId(parameterName);
	if ( parameter == -1 )
		return;

	std::string opString = stringFilter->optValue<std::string>("Operator", "EQ");
	MQLONG op = getOperator(Poco::toUpper(opString));
	if ( op == -1 ) op = MQCFOP_EQUAL;

	std::string filterValue = stringFilter->optValue<std::string>("FilterValue", "");
	_pcf->addFilter(parameter, op, filterValue);
}

void MQMapper::addAttributeList(MQLONG attrId, const std::string& attr)
{
	poco_assert_dbg(!_pcf.isNull());

	if ( _input->has(attr) )
	{
		Poco::JSON::Array::Ptr attrs = _input->getArray(attr);
		if ( !attrs.isNull() && attrs->size() > 0 )
		{
			std::vector<MQLONG> numList;
			for(Poco::JSON::Array::ValueVec::const_iterator it = attrs->begin(); it != attrs->end(); ++it)
			{
				MQLONG id = _dictionary->getId(*it);
				if ( id != -1 ) numList.push_back(id);
			}
			if ( numList.size() > 0 ) _pcf->addParameterList(attrId, numList);
		}
	}
}

void MQMapper::addParameterNumFromString(MQLONG parameter, const std::string& name)
{
	poco_assert_dbg(!_pcf.isNull());

	Poco::Dynamic::Var value = _input->get(name);
	if ( ! value.isEmpty() )
	{
		try
		{
			std::string stringValue = value.convert<std::string>();
			MQLONG numValue = _dictionary->getDisplayId(parameter, stringValue);
			poco_assert_dbg(numValue != -1);
			if ( numValue != - 1 )
			{
				_pcf->addParameter(parameter, numValue);
			}
		}
		catch(...)
		{
			poco_assert_dbg(false);
		}
	}
}

void MQMapper::execute(PCF::Vector& response)
{
	poco_assert_dbg(!_pcf.isNull());
	_commandServer.sendCommand(_pcf, response);

	if ( response.size() > 0 )
	{
		PCF::Vector::const_iterator it = response.begin();
		if (     (*it)->getCompletionCode() == MQCC_FAILED
			  && (*it)->getReasonCode() > 3000
			  && (*it)->getReasonCode() < 4000
			  && (*it)->getReasonCode() != MQRCCF_NONE_FOUND
			  && (*it)->getReasonCode() != MQRCCF_CHL_STATUS_NOT_FOUND )
		{
			throw MQException("PCF", getCommandString((*it)->getCommand()), (*it)->getCompletionCode(), (*it)->getReasonCode());
		}
	}
}

Poco::JSON::Object::Ptr MQMapper::createError(const PCF& pcf)
{
	Poco::JSON::Object::Ptr error = new Poco::JSON::Object();
	error->set("object", "PCF");
	error->set("fn", getCommandString(pcf.getCommand()));
	switch(pcf.getCompletionCode())
	{
		case MQCC_OK: error->set("code", "OK"); break;
		case MQCC_WARNING: error->set("code", "WARNING"); break;
		case MQCC_FAILED: error->set("code", "ERROR"); break;
	}

	Poco::JSON::Object::Ptr reason = new Poco::JSON::Object();
	error->set("reason", reason);
	reason->set("code", pcf.getReasonCode());
	reason->set("desc", MQMapper::getReasonString(pcf.getReasonCode()));

	return error;
}

}} //  Namespace MQ::Web
<commit_msg>Don't throw MQException for MQRCCF_TOPIC_STRING_NOT_FOUND<commit_after>/*
 * Copyright 2010 MQWeb - Franky Braem
 *
 * Licensed under the EUPL, Version 1.1 or - as soon they
 * will be approved by the European Commission - subsequent
 * versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the
 * Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in
 * writing, software distributed under the Licence is
 * distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the Licence for the specific language governing
 * permissions and limitations under the Licence.
 */
#include "MQ/Web/MQMapper.h"

#include "MQ/MQException.h"

#include "Poco/JSON/Object.h"
#include "Poco/Logger.h"

namespace MQ {
namespace Web {

DictionaryCache MQMapper::_dictionaryCache;

Dictionary MQMapper::_operators = Dictionary()
	(MQCFOP_LESS, "LT")
	(MQCFOP_LESS | MQCFOP_EQUAL, "LE")
	(MQCFOP_EQUAL, "EQ")
	(MQCFOP_GREATER, "GT")
	(MQCFOP_GREATER | MQCFOP_EQUAL, "GE")
	(MQCFOP_NOT_LESS, "NLT")
	(MQCFOP_NOT_EQUAL, "NE")
	(MQCFOP_NOT_GREATER, "NGT")
	(MQCFOP_LIKE, "LK")
	(MQCFOP_NOT_LIKE, "NL")
	(MQCFOP_CONTAINS, "CT")
	(MQCFOP_EXCLUDES, "EX")
	(MQCFOP_CONTAINS_GEN, "CTG")
	(MQCFOP_EXCLUDES_GEN, "EXG")
;

MQMapper::MQMapper(CommandServer& commandServer, const std::string& objectType, Poco::JSON::Object::Ptr input)
  : _commandServer(commandServer)
  , _input(input)
{
	_dictionary = _dictionaryCache.getDictionary(objectType);
	poco_assert_dbg(!_dictionary.isNull());

	if ( _dictionary.isNull() )
	{
		Poco::Logger& logger = Poco::Logger::get("mq.web");
		logger.error(Poco::Logger::format("$0 not found in dictionary database", objectType));
	}
}

MQMapper::~MQMapper()
{
}

std::string MQMapper::getReasonString(MQLONG reasonCode)
{
	static Poco::SharedPtr<Dictionary> dict = _dictionaryCache.getDictionary("Reason");

	return dict->getDisplayValue(MQIACF_REASON_CODE, reasonCode);
}

std::string MQMapper::getCommandString(MQLONG command)
{
	static Poco::SharedPtr<Dictionary> dict = _dictionaryCache.getDictionary("Event");
	return dict->getDisplayValue(MQIACF_COMMAND, command);
}

MQLONG MQMapper::getOperator(const std::string& op)
{
	return _operators.getId(op);
}

const DisplayMap& MQMapper::getDisplayMap(const std::string& objectType, MQLONG id)
{
	Poco::SharedPtr<Dictionary> dict = _dictionaryCache.getDictionary(objectType);
	poco_assert_dbg(!dict.isNull());

	if ( dict.isNull() )
	{
		Poco::Logger& logger = Poco::Logger::get("mq.web");
		logger.error(Poco::Logger::format("$0 not found in dictionary database", objectType));
	}

	return dict->getDisplayMap(id);
}

void MQMapper::addIntegerFilter()
{
	poco_assert_dbg(!_pcf.isNull());

	Poco::JSON::Object::Ptr integerFilter = _input->getObject("IntegerFilterCommand");
	if ( integerFilter.isNull() )
		return;

	std::string parameterName = integerFilter->optValue<std::string>("Parameter", "");
	MQLONG parameter = _dictionary->getId(parameterName);
	if ( parameter == -1 )
		return;

	std::string opString = integerFilter->optValue<std::string>("Operator", "EQ");
	MQLONG op = getOperator(Poco::toUpper(opString));
	if ( op == -1 ) op = MQCFOP_EQUAL;

	Poco::Dynamic::Var value = integerFilter->get("FilterValue");
	MQLONG filterValue;
	if ( value.isString() )
	{
		// A String is passed ... try to find the MQ integer value
		filterValue = _dictionary->getDisplayId(parameter, value);
	}
	else if ( value.isNumeric() )
	{
		filterValue = value;
	}
	_pcf->addFilter(parameter, op, filterValue);
}

void MQMapper::addStringFilter()
{
	poco_assert_dbg(!_pcf.isNull());

	Poco::JSON::Object::Ptr stringFilter = _input->getObject("StringFilterCommand");
	if ( stringFilter.isNull() )
		return;

	std::string parameterName = stringFilter->optValue<std::string>("Parameter", "");
	MQLONG parameter = _dictionary->getId(parameterName);
	if ( parameter == -1 )
		return;

	std::string opString = stringFilter->optValue<std::string>("Operator", "EQ");
	MQLONG op = getOperator(Poco::toUpper(opString));
	if ( op == -1 ) op = MQCFOP_EQUAL;

	std::string filterValue = stringFilter->optValue<std::string>("FilterValue", "");
	_pcf->addFilter(parameter, op, filterValue);
}

void MQMapper::addAttributeList(MQLONG attrId, const std::string& attr)
{
	poco_assert_dbg(!_pcf.isNull());

	if ( _input->has(attr) )
	{
		Poco::JSON::Array::Ptr attrs = _input->getArray(attr);
		if ( !attrs.isNull() && attrs->size() > 0 )
		{
			std::vector<MQLONG> numList;
			for(Poco::JSON::Array::ValueVec::const_iterator it = attrs->begin(); it != attrs->end(); ++it)
			{
				MQLONG id = _dictionary->getId(*it);
				if ( id != -1 ) numList.push_back(id);
			}
			if ( numList.size() > 0 ) _pcf->addParameterList(attrId, numList);
		}
	}
}

void MQMapper::addParameterNumFromString(MQLONG parameter, const std::string& name)
{
	poco_assert_dbg(!_pcf.isNull());

	Poco::Dynamic::Var value = _input->get(name);
	if ( ! value.isEmpty() )
	{
		try
		{
			std::string stringValue = value.convert<std::string>();
			MQLONG numValue = _dictionary->getDisplayId(parameter, stringValue);
			poco_assert_dbg(numValue != -1);
			if ( numValue != - 1 )
			{
				_pcf->addParameter(parameter, numValue);
			}
		}
		catch(...)
		{
			poco_assert_dbg(false);
		}
	}
}

void MQMapper::execute(PCF::Vector& response)
{
	poco_assert_dbg(!_pcf.isNull());
	_commandServer.sendCommand(_pcf, response);

	if ( response.size() > 0 )
	{
		PCF::Vector::const_iterator it = response.begin();
		if (     (*it)->getCompletionCode() == MQCC_FAILED
			  && (*it)->getReasonCode() > 3000
			  && (*it)->getReasonCode() < 4000
			  && (*it)->getReasonCode() != MQRCCF_NONE_FOUND
			  && (*it)->getReasonCode() != MQRCCF_CHL_STATUS_NOT_FOUND
			  && (*it)->getReasonCode() != MQRCCF_TOPIC_STRING_NOT_FOUND )
		{
			throw MQException("PCF", getCommandString((*it)->getCommand()), (*it)->getCompletionCode(), (*it)->getReasonCode());
		}
	}
}

Poco::JSON::Object::Ptr MQMapper::createError(const PCF& pcf)
{
	Poco::JSON::Object::Ptr error = new Poco::JSON::Object();
	error->set("object", "PCF");
	error->set("fn", getCommandString(pcf.getCommand()));
	switch(pcf.getCompletionCode())
	{
		case MQCC_OK: error->set("code", "OK"); break;
		case MQCC_WARNING: error->set("code", "WARNING"); break;
		case MQCC_FAILED: error->set("code", "ERROR"); break;
	}

	Poco::JSON::Object::Ptr reason = new Poco::JSON::Object();
	error->set("reason", reason);
	reason->set("code", pcf.getReasonCode());
	reason->set("desc", MQMapper::getReasonString(pcf.getReasonCode()));

	return error;
}

}} //  Namespace MQ::Web
<|endoftext|>


<commit_before>//===-- Emitter.cpp - Write machine code to executable memory -------------===//
//
// This file defines a MachineCodeEmitter object that is used by Jello to write
// machine code to memory and remember where relocatable values lie.
//
//===----------------------------------------------------------------------===//

#include "VM.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Function.h"
#include "Support/Statistic.h"

static VM *TheVM = 0;

namespace {
  Statistic<> NumBytes("jello", "Number of bytes of machine code compiled");

  class Emitter : public MachineCodeEmitter {
    // CurBlock - The start of the current block of memory.  CurByte - The
    // current byte being emitted to.
    unsigned char *CurBlock, *CurByte;

    // When outputting a function stub in the context of some other function, we
    // save CurBlock and CurByte here.
    unsigned char *SavedCurBlock, *SavedCurByte;

    // ConstantPoolAddresses - Contains the location for each entry in the
    // constant pool.
    std::vector<void*> ConstantPoolAddresses;
  public:
    Emitter(VM &vm) { TheVM = &vm; }

    virtual void startFunction(MachineFunction &F);
    virtual void finishFunction(MachineFunction &F);
    virtual void emitConstantPool(MachineConstantPool *MCP);
    virtual void startFunctionStub(const Function &F, unsigned StubSize);
    virtual void* finishFunctionStub(const Function &F);
    virtual void emitByte(unsigned char B);
    virtual void emitWord(unsigned W);

    virtual uint64_t getGlobalValueAddress(GlobalValue *V);
    virtual uint64_t getGlobalValueAddress(const std::string &Name);
    virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
    virtual uint64_t getCurrentPCValue();

    // forceCompilationOf - Force the compilation of the specified function, and
    // return its address, because we REALLY need the address now.
    //
    // FIXME: This is JIT specific!
    //
    virtual uint64_t forceCompilationOf(Function *F);
  };
}

MachineCodeEmitter *VM::createX86Emitter(VM &V) {
  return new Emitter(V);
}

#define _POSIX_MAPPED_FILES
#include <unistd.h>
#include <sys/mman.h>

// FIXME: This should be rewritten to support a real memory manager for
// executable memory pages!
static void *getMemory(unsigned NumPages) {
  return mmap(0, 4096*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
              MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);
}

void Emitter::startFunction(MachineFunction &F) {
  CurBlock = (unsigned char *)getMemory(16);
  CurByte = CurBlock;  // Start writing at the beginning of the fn.
  TheVM->addGlobalMapping(F.getFunction(), CurBlock);
}

void Emitter::finishFunction(MachineFunction &F) {
  ConstantPoolAddresses.clear();
  NumBytes += CurByte-CurBlock;

  DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
                  << (unsigned)(intptr_t)CurBlock
                  << std::dec << "] Function: " << F.getFunction()->getName()
                  << ": " << CurByte-CurBlock << " bytes of text\n");
}

void Emitter::emitConstantPool(MachineConstantPool *MCP) {
  const std::vector<Constant*> &Constants = MCP->getConstants();
  for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
    // For now we just allocate some memory on the heap, this can be
    // dramatically improved.
    const Type *Ty = ((Value*)Constants[i])->getType();
    void *Addr = malloc(TheVM->getTargetData().getTypeSize(Ty));
    TheVM->InitializeMemory(Constants[i], Addr);
    ConstantPoolAddresses.push_back(Addr);
  }
}

void Emitter::startFunctionStub(const Function &F, unsigned StubSize) {
  SavedCurBlock = CurBlock;  SavedCurByte = CurByte;
  // FIXME: this is a huge waste of memory.
  CurBlock = (unsigned char *)getMemory((StubSize+4095)/4096);
  CurByte = CurBlock;  // Start writing at the beginning of the fn.
}

void *Emitter::finishFunctionStub(const Function &F) {
  NumBytes += CurByte-CurBlock;
  DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
                  << (unsigned)(intptr_t)CurBlock
                  << std::dec << "] Function stub for: " << F.getName()
                  << ": " << CurByte-CurBlock << " bytes of text\n");
  std::swap(CurBlock, SavedCurBlock);
  CurByte = SavedCurByte;
  return SavedCurBlock;
}

void Emitter::emitByte(unsigned char B) {
  *CurByte++ = B;   // Write the byte to memory
}

void Emitter::emitWord(unsigned W) {
  // FIXME: This won't work if the endianness of the host and target don't
  // agree!  (For a JIT this can't happen though.  :)
  *(unsigned*)CurByte = W;
  CurByte += sizeof(unsigned);
}

uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
  // Try looking up the function to see if it is already compiled, if not return
  // 0.
  return (intptr_t)TheVM->getPointerToGlobalIfAvailable(V);
}
uint64_t Emitter::getGlobalValueAddress(const std::string &Name) {
  return (intptr_t)TheVM->getPointerToNamedFunction(Name);
}

// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
// in the constant pool that was last emitted with the 'emitConstantPool'
// method.
//
uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
  assert(ConstantNum < ConstantPoolAddresses.size() &&
	 "Invalid ConstantPoolIndex!");
  return (intptr_t)ConstantPoolAddresses[ConstantNum];
}

// getCurrentPCValue - This returns the address that the next emitted byte
// will be output to.
//
uint64_t Emitter::getCurrentPCValue() {
  return (intptr_t)CurByte;
}

uint64_t Emitter::forceCompilationOf(Function *F) {
  return (intptr_t)TheVM->getPointerToFunction(F);
}

#if 0

// emitPCRelativeDisp - For functions, just output a displacement that will
// cause a reference to the zero page, which will cause a seg-fault, causing
// things to get resolved on demand.  Keep track of these markers.
//
// For basic block references, keep track of where the references are so they
// may be patched up when the basic block is defined.
//
void Emitter::emitPCRelativeDisp(Value *V) {
  BasicBlock *BB = cast<BasicBlock>(V);     // Keep track of reference...
  BBRefs.push_back(std::make_pair(BB, (unsigned*)CurByte));
  CurByte += 4;
}

// emitAddress - Emit an address in either direct or PCRelative form...
//
void Emitter::emitAddress(void *Addr, bool isPCRelative) {
  if (isPCRelative) {
    *(intptr_t*)CurByte = (intptr_t)Addr - (intptr_t)CurByte-4;
  } else {
    *(void**)CurByte = Addr;
  }
  CurByte += 4;
}

void Emitter::emitGlobalAddress(GlobalValue *V, bool isPCRelative) {
  if (isPCRelative) { // must be a call, this is a major hack!
    // Try looking up the function to see if it is already compiled!
    if (void *Addr = TheVM->getPointerToGlobalIfAvailable(V)) {
      emitAddress(Addr, isPCRelative);
    } else {  // Function has not yet been code generated!
      TheVM->addFunctionRef(CurByte, cast<Function>(V));

      // Delayed resolution...
      emitAddress((void*)VM::CompilationCallback, isPCRelative);
    }
  } else {
    emitAddress(TheVM->getPointerToGlobal(V), isPCRelative);
  }
}

void Emitter::emitFunctionConstantValueAddress(unsigned ConstantNum,
					       int Offset) {
  assert(ConstantNum < ConstantPoolAddresses.size() &&
	 "Invalid ConstantPoolIndex!");
  *(void**)CurByte = (char*)ConstantPoolAddresses[ConstantNum]+Offset;
  CurByte += 4;
}
#endif
<commit_msg>Remove obsolete code<commit_after>//===-- Emitter.cpp - Write machine code to executable memory -------------===//
//
// This file defines a MachineCodeEmitter object that is used by Jello to write
// machine code to memory and remember where relocatable values lie.
//
//===----------------------------------------------------------------------===//

#include "VM.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Function.h"
#include "Support/Statistic.h"

static VM *TheVM = 0;

namespace {
  Statistic<> NumBytes("jello", "Number of bytes of machine code compiled");

  class Emitter : public MachineCodeEmitter {
    // CurBlock - The start of the current block of memory.  CurByte - The
    // current byte being emitted to.
    unsigned char *CurBlock, *CurByte;

    // When outputting a function stub in the context of some other function, we
    // save CurBlock and CurByte here.
    unsigned char *SavedCurBlock, *SavedCurByte;

    // ConstantPoolAddresses - Contains the location for each entry in the
    // constant pool.
    std::vector<void*> ConstantPoolAddresses;
  public:
    Emitter(VM &vm) { TheVM = &vm; }

    virtual void startFunction(MachineFunction &F);
    virtual void finishFunction(MachineFunction &F);
    virtual void emitConstantPool(MachineConstantPool *MCP);
    virtual void startFunctionStub(const Function &F, unsigned StubSize);
    virtual void* finishFunctionStub(const Function &F);
    virtual void emitByte(unsigned char B);
    virtual void emitWord(unsigned W);

    virtual uint64_t getGlobalValueAddress(GlobalValue *V);
    virtual uint64_t getGlobalValueAddress(const std::string &Name);
    virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
    virtual uint64_t getCurrentPCValue();

    // forceCompilationOf - Force the compilation of the specified function, and
    // return its address, because we REALLY need the address now.
    //
    // FIXME: This is JIT specific!
    //
    virtual uint64_t forceCompilationOf(Function *F);
  };
}

MachineCodeEmitter *VM::createX86Emitter(VM &V) {
  return new Emitter(V);
}

#define _POSIX_MAPPED_FILES
#include <unistd.h>
#include <sys/mman.h>

// FIXME: This should be rewritten to support a real memory manager for
// executable memory pages!
static void *getMemory(unsigned NumPages) {
  return mmap(0, 4096*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
              MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);
}

void Emitter::startFunction(MachineFunction &F) {
  CurBlock = (unsigned char *)getMemory(16);
  CurByte = CurBlock;  // Start writing at the beginning of the fn.
  TheVM->addGlobalMapping(F.getFunction(), CurBlock);
}

void Emitter::finishFunction(MachineFunction &F) {
  ConstantPoolAddresses.clear();
  NumBytes += CurByte-CurBlock;

  DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
                  << (unsigned)(intptr_t)CurBlock
                  << std::dec << "] Function: " << F.getFunction()->getName()
                  << ": " << CurByte-CurBlock << " bytes of text\n");
}

void Emitter::emitConstantPool(MachineConstantPool *MCP) {
  const std::vector<Constant*> &Constants = MCP->getConstants();
  for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
    // For now we just allocate some memory on the heap, this can be
    // dramatically improved.
    const Type *Ty = ((Value*)Constants[i])->getType();
    void *Addr = malloc(TheVM->getTargetData().getTypeSize(Ty));
    TheVM->InitializeMemory(Constants[i], Addr);
    ConstantPoolAddresses.push_back(Addr);
  }
}

void Emitter::startFunctionStub(const Function &F, unsigned StubSize) {
  SavedCurBlock = CurBlock;  SavedCurByte = CurByte;
  // FIXME: this is a huge waste of memory.
  CurBlock = (unsigned char *)getMemory((StubSize+4095)/4096);
  CurByte = CurBlock;  // Start writing at the beginning of the fn.
}

void *Emitter::finishFunctionStub(const Function &F) {
  NumBytes += CurByte-CurBlock;
  DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
                  << (unsigned)(intptr_t)CurBlock
                  << std::dec << "] Function stub for: " << F.getName()
                  << ": " << CurByte-CurBlock << " bytes of text\n");
  std::swap(CurBlock, SavedCurBlock);
  CurByte = SavedCurByte;
  return SavedCurBlock;
}

void Emitter::emitByte(unsigned char B) {
  *CurByte++ = B;   // Write the byte to memory
}

void Emitter::emitWord(unsigned W) {
  // FIXME: This won't work if the endianness of the host and target don't
  // agree!  (For a JIT this can't happen though.  :)
  *(unsigned*)CurByte = W;
  CurByte += sizeof(unsigned);
}

uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
  // Try looking up the function to see if it is already compiled, if not return
  // 0.
  return (intptr_t)TheVM->getPointerToGlobalIfAvailable(V);
}
uint64_t Emitter::getGlobalValueAddress(const std::string &Name) {
  return (intptr_t)TheVM->getPointerToNamedFunction(Name);
}

// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
// in the constant pool that was last emitted with the 'emitConstantPool'
// method.
//
uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
  assert(ConstantNum < ConstantPoolAddresses.size() &&
	 "Invalid ConstantPoolIndex!");
  return (intptr_t)ConstantPoolAddresses[ConstantNum];
}

// getCurrentPCValue - This returns the address that the next emitted byte
// will be output to.
//
uint64_t Emitter::getCurrentPCValue() {
  return (intptr_t)CurByte;
}

uint64_t Emitter::forceCompilationOf(Function *F) {
  return (intptr_t)TheVM->getPointerToFunction(F);
}

<|endoftext|>


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

#ifndef _EDITDBG_HXX
#define _EDITDBG_HXX

#include <svtools/solar.hrc>
#include <tools/string.hxx>
#include <stdio.h>

class EditEngine;
class ParaPortion;
class EditUndoList;
class TextPortionList;
class SfxItemSet;
class SfxItemPool;
class SfxPoolItem;

ByteString  DbgOutItem( const SfxItemPool& rPool, const SfxPoolItem& rItem );
void        DbgOutItemSet( FILE* fp, const SfxItemSet& rSet, BOOL bSearchInParent, BOOL bShowALL );

class EditDbg
{
public:
    static void         ShowEditEngineData( EditEngine* pEditEngine, BOOL bInfoBox = TRUE );
    static void         ShowPortionData( ParaPortion* pPortion );
    static ByteString   GetPortionInfo( ParaPortion* pPPortion );
    static ByteString   GetTextPortionInfo( TextPortionList& rPortions );
    static ByteString   GetUndoDebStr( EditUndoList* pUndoList );
};

#endif // _EDITDBG_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1670); FILE MERGED 2005/09/05 14:23:49 rt 1.1.1.1.1670.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: editdbg.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 22:26:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _EDITDBG_HXX
#define _EDITDBG_HXX

#include <svtools/solar.hrc>
#include <tools/string.hxx>
#include <stdio.h>

class EditEngine;
class ParaPortion;
class EditUndoList;
class TextPortionList;
class SfxItemSet;
class SfxItemPool;
class SfxPoolItem;

ByteString  DbgOutItem( const SfxItemPool& rPool, const SfxPoolItem& rItem );
void        DbgOutItemSet( FILE* fp, const SfxItemSet& rSet, BOOL bSearchInParent, BOOL bShowALL );

class EditDbg
{
public:
    static void         ShowEditEngineData( EditEngine* pEditEngine, BOOL bInfoBox = TRUE );
    static void         ShowPortionData( ParaPortion* pPortion );
    static ByteString   GetPortionInfo( ParaPortion* pPPortion );
    static ByteString   GetTextPortionInfo( TextPortionList& rPortions );
    static ByteString   GetUndoDebStr( EditUndoList* pUndoList );
};

#endif // _EDITDBG_HXX
<|endoftext|>


<commit_before>//
//  main.cpp
//  thermaleraser
//
//  Created by Mark Larus on 9/8/12.
//  Copyright (c) 2012 Kenyon College. All rights reserved.
//

#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>

#include "States.h"
#include "System.h"
#include "Utilities.h"

#define print(x) std::cout<<#x <<": " <<x<<std::endl;

namespace opt = boost::program_options;

enum OutputType {
    CommaSeparated,
    PrettyPrint,
    Mathematica,
    NoOutput
};

void simulate_and_print(Constants constants, int iterations, OutputType type);

int main(int argc, char * argv[])
{
    const int default_iterations = 1<<16;

    opt::options_description desc("Allowed options");
    desc.add_options()
        ("iterations,n",opt::value<int>(), "Number of iterations")
        ("help","Show help message")
    ;

    opt::variables_map vmap;
    opt::store(opt::parse_command_line(argc,argv,desc),vmap);
    opt::notify(vmap);

    if (vmap.count("help")) {
        std::cout << desc << "\n";
        return 1;
    }

    int iterations = vmap.count("iterations,n") ? vmap["iterations,n"].as<int>() : default_iterations;

    /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
     represented by an object with pointers to the next states and the bit-flip states. */
    setupStates();

    Constants constants;

    /*! The delta used here is NOT, at this point, the delta used in the paper. This is the
     ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
     calculating this at runtime is just an invitation for bugs. */
    constants.delta = .5;
    constants.epsilon = .7;
    constants.tau = 1;
    int dimension = 50;
    for (int k=dimension*dimension; k>=0; k--) {
        constants.epsilon = (k % dimension)/(double)(dimension);
        constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
        simulate_and_print(constants, iterations, CommaSeparated);
    }

}

void simulate_and_print(Constants constants, int iterations, OutputType type) {

    /*! Use this to change the length of the tape. */
    const int BIT_STREAM_LENGTH = 8;

    int first_pass_iterations = iterations;

    System *systems = new System[first_pass_iterations]();

    int *histogram = new int[1<<BIT_STREAM_LENGTH];
    std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);

    #pragma omp parallel default(shared)
    {
        //TODO: Move this into a semaphore in the utility function
        gsl_rng *localRNG = GSLRandomNumberGenerator();

        int *localHistogram = new int[1<<BIT_STREAM_LENGTH];
        std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);

        #pragma omp for
        for (int k=0; k<first_pass_iterations; ++k) {
            System *currentSystem = systems+k;

            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);
            ++localHistogram[currentSystem->endingBitString];

        }

        delete [] localHistogram;

        gsl_rng_free(localRNG);
    }//End parallel

    for(int k=0; k<first_pass_iterations; k++) {
        histogram[systems[k].endingBitString]++;
    }

    delete [] systems;

    //time_t stop_time = time(NULL);

    //std::clog<<"Time elapsed: "<<(stop_time-start_time)<<std::endl;

    long double *p = new long double[1<<BIT_STREAM_LENGTH];
    long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];

    for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
        int setBits = bitCount(k,BIT_STREAM_LENGTH);
        p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
        p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
    }

    delete [] histogram;

    long double sum = 0;

    const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
    long double max_surprise = 0;
    long double min_surprise = LONG_MAX;

    #pragma omp parallel
    {

        //Make sure we don't accidentally share a seed.
        gsl_rng *localRNG = GSLRandomNumberGenerator();

        #pragma omp for reduction(+ : sum)
        for(int k=0; k<iterations; k++) {
            System *currentSystem = new System();
            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);

            long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
            max_surprise = surprise > max_surprise ? surprise : max_surprise;
            min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
            sum = sum + surprise;
            delete currentSystem;
        }
        gsl_rng_free(localRNG);
    }

    delete [] p_prime;
    delete [] p;

    if(type==CommaSeparated) {
        static int once = 0;
        if (!once) {
            std::cout<<"delta,epsilon,avg,max_surprise\n";
            once=1;
        }
        std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
    }

    if(type==PrettyPrint) {
        print(beta);
        print(constants.delta);
        print(constants.epsilon);
        print(sum/iterations);
        print(max_surprise);
        print(sum);
        std::cout<<std::endl;
    }

    if (type==Mathematica) {
        assert(0);
    }
}<commit_msg>Include verbose option for main() function.<commit_after>//
//  main.cpp
//  thermaleraser
//
//  Created by Mark Larus on 9/8/12.
//  Copyright (c) 2012 Kenyon College. All rights reserved.
//

#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>

#include "States.h"
#include "System.h"
#include "Utilities.h"

#define print(x) std::cout<<#x <<": " <<x<<std::endl;

namespace opt = boost::program_options;

enum OutputType {
    CommaSeparated,
    PrettyPrint,
    Mathematica,
    NoOutput
};

void simulate_and_print(Constants constants, int iterations, OutputType type);

int main(int argc, char * argv[]) {
  /*! Initialize options list.
   */

    bool verbose = false;
    const int default_iterations = 1<<16;

    opt::options_description desc("Allowed options");
    desc.add_options()
        ("iterations,n",opt::value<int>(), "Number of iterations")
        ("help","Show help message")
        ("verbose,v", "Show extensive debugging info")
    ;

    opt::variables_map vmap;
    opt::store(opt::parse_command_line(argc,argv,desc),vmap);
    opt::notify(vmap);

    if (vmap.count("help")) {
        std::cout << desc << "\n";
        return 1;
    }

    verbose = vmap.count("verbose");

    int iterations = vmap.count("iterations,n") ? vmap["iterations,n"].as<int>() : default_iterations;

    if (verbose) {
      print(iterations);
    }

    /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
     represented by an object with pointers to the next states and the bit-flip states. */
    setupStates();

    Constants constants;

    /*! The delta used here is NOT, at this point, the delta used in the paper. This is the
     ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
     calculating this at runtime is just an invitation for bugs. */
    constants.delta = .5;
    constants.epsilon = .7;
    constants.tau = 1;
    int dimension = 50;
    for (int k=dimension*dimension; k>=0; k--) {
        constants.epsilon = (k % dimension)/(double)(dimension);
        constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
        simulate_and_print(constants, iterations, CommaSeparated);
    }

}

void simulate_and_print(Constants constants, int iterations, OutputType type) {

    /*! Use this to change the length of the tape. */
    const int BIT_STREAM_LENGTH = 8;

    int first_pass_iterations = iterations;

    System *systems = new System[first_pass_iterations]();

    int *histogram = new int[1<<BIT_STREAM_LENGTH];
    std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);

    #pragma omp parallel default(shared)
    {
        //TODO: Move this into a semaphore in the utility function
        gsl_rng *localRNG = GSLRandomNumberGenerator();

        int *localHistogram = new int[1<<BIT_STREAM_LENGTH];
        std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);

        #pragma omp for
        for (int k=0; k<first_pass_iterations; ++k) {
            System *currentSystem = systems+k;

            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);
            ++localHistogram[currentSystem->endingBitString];

        }

        delete [] localHistogram;

        gsl_rng_free(localRNG);
    }//End parallel

    for(int k=0; k<first_pass_iterations; k++) {
        histogram[systems[k].endingBitString]++;
    }

    delete [] systems;

    //time_t stop_time = time(NULL);

    //std::clog<<"Time elapsed: "<<(stop_time-start_time)<<std::endl;

    long double *p = new long double[1<<BIT_STREAM_LENGTH];
    long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];

    for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
        int setBits = bitCount(k,BIT_STREAM_LENGTH);
        p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
        p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
    }

    delete [] histogram;

    long double sum = 0;

    const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
    long double max_surprise = 0;
    long double min_surprise = LONG_MAX;

    #pragma omp parallel
    {

        //Make sure we don't accidentally share a seed.
        gsl_rng *localRNG = GSLRandomNumberGenerator();

        #pragma omp for reduction(+ : sum)
        for(int k=0; k<iterations; k++) {
            System *currentSystem = new System();
            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);

            long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
            max_surprise = surprise > max_surprise ? surprise : max_surprise;
            min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
            sum = sum + surprise;
            delete currentSystem;
        }
        gsl_rng_free(localRNG);
    }

    delete [] p_prime;
    delete [] p;

    if(type==CommaSeparated) {
        static int once = 0;
        if (!once) {
            std::cout<<"delta,epsilon,avg,max_surprise\n";
            once=1;
        }
        std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
    }

    if(type==PrettyPrint) {
        print(beta);
        print(constants.delta);
        print(constants.epsilon);
        print(sum/iterations);
        print(max_surprise);
        print(sum);
        std::cout<<std::endl;
    }

    if (type==Mathematica) {
        assert(0);
    }
}
<|endoftext|>


<commit_before>#include <thread>
#include <string>
#include <cstring>
#include <sstream>
#include <iostream>
#include <functional>

#include "test.hpp"
#include "ping_pong.hpp"
#include "cppa/cppa.hpp"
#include "cppa/logging.hpp"
#include "cppa/exception.hpp"

using namespace std;
using namespace cppa;

namespace {

typedef std::pair<std::string, std::string> string_pair;

typedef vector<actor_ptr> actor_vector;

void reflector() {
    CPPA_SET_DEBUG_NAME("reflector" << self->id());
    become (
        others() >> [=] {
            CPPA_LOGF_INFO("reflect and quit");
            reply_tuple(self->last_dequeued());
            self->quit();
        }
    );
}

void spawn5_server_impl(actor_ptr client, group_ptr grp) {
    CPPA_LOGF_TRACE(CPPA_TARG(client, to_string)
                    << ", " << CPPA_TARG(grp, to_string));
    spawn_in_group(grp, reflector);
    spawn_in_group(grp, reflector);
    CPPA_LOGF_INFO("send {'Spawn5'} and await {'ok', actor_vector}");
    sync_send(client, atom("Spawn5"), grp).then(
        on(atom("ok"), arg_match) >> [=](const actor_vector& vec) {
            CPPA_LOGF_INFO("received vector with " << vec.size() << " elements");
            send(grp, "Hello reflectors!", 5.0);
            if (vec.size() != 5) {
                CPPA_PRINTERR("remote client did not spawn five reflectors!");
            }
            for (auto& a : vec) self->monitor(a);
        },
        others() >> [] {
            CPPA_UNEXPECTED_MSG();
            self->quit(exit_reason::unhandled_exception);
        },
        after(chrono::seconds(10)) >> [] {
            CPPA_UNEXPECTED_TOUT();
            self->quit(exit_reason::unhandled_exception);
        }
    )
    .continue_with([=] {
        CPPA_PRINT("wait for reflected messages");
        // receive seven reply messages (2 local, 5 remote)
        auto replies = std::make_shared<int>(0);
        become (
            on("Hello reflectors!", 5.0) >> [=] {
                if (++*replies == 7) {
                    CPPA_PRINT("wait for DOWN messages");
                    auto downs = std::make_shared<int>(0);
                    become (
                        on(atom("DOWN"), arg_match) >> [=](std::uint32_t reason) {
                            if (reason != exit_reason::normal) {
                                CPPA_PRINTERR("reflector exited for non-normal exit reason!");
                            }
                            if (++*downs == 5) {
                                CPPA_CHECKPOINT();
                                send(client, atom("Spawn5Done"));
                                self->quit();
                            }
                        },
                        others() >> [] {
                            CPPA_UNEXPECTED_MSG();
                            self->quit(exit_reason::unhandled_exception);
                        },
                        after(chrono::seconds(2)) >> [] {
                            CPPA_UNEXPECTED_TOUT();
                            self->quit(exit_reason::unhandled_exception);
                        }
                    );
                }
            },
            after(std::chrono::seconds(2)) >> [] {
                CPPA_UNEXPECTED_TOUT();
                self->quit(exit_reason::unhandled_exception);
            }
        );
    });
}

// receive seven reply messages (2 local, 5 remote)
void spawn5_server(actor_ptr client, bool inverted) {
    CPPA_SET_DEBUG_NAME("spawn5_server");
    if (!inverted) spawn5_server_impl(client, group::get("local", "foobar"));
    else {
        CPPA_LOGF_INFO("request group");
        sync_send(client, atom("GetGroup")).then (
            [=](const group_ptr& remote_group) {
                spawn5_server_impl(client, remote_group);
            }
        );
    }
}

void spawn5_client() {
    CPPA_SET_DEBUG_NAME("spawn5_client");
    become (
        on(atom("GetGroup")) >> [] {
            CPPA_LOGF_INFO("received {'GetGroup'}");
            reply(group::get("local", "foobar"));
        },
        on(atom("Spawn5"), arg_match) >> [=](const group_ptr& grp) {
            CPPA_LOGF_INFO("received {'Spawn5'}");
            actor_vector vec;
            for (int i = 0; i < 5; ++i) {
                vec.push_back(spawn_in_group(grp, reflector));
            }
            reply(atom("ok"), std::move(vec));
        },
        on(atom("Spawn5Done")) >> [] {
            CPPA_LOGF_INFO("received {'Spawn5Done'}");
            self->quit();
        }
    );
}

} // namespace <anonymous>

template<typename T>
void await_down(actor_ptr ptr, T continuation) {
    become (
        on(atom("DOWN"), arg_match) >> [=](uint32_t) -> bool {
            if (self->last_sender() == ptr) {
                continuation();
                return true;
            }
            return false; // not the 'DOWN' message we are waiting for
        }
    );
}

class client : public event_based_actor {

 public:

    client(actor_ptr server) : m_server(std::move(server)) { }

    void init() {
        CPPA_SET_DEBUG_NAME("client");
        spawn_ping();
    }

 private:

    void spawn_ping() {
        CPPA_PRINT("send {'SpawnPing'}");
        send(m_server, atom("SpawnPing"));
        become (
            on(atom("PingPtr"), arg_match) >> [=](const actor_ptr& ping) {
                auto pptr = spawn<monitored+detached+blocking_api>(pong, ping);
                await_down(pptr, [=] {
                    send_sync_msg();
                });
            }

        );
    }

    void send_sync_msg() {
        CPPA_PRINT("sync send {'SyncMsg'}");
        sync_send(m_server, atom("SyncMsg")).then(
            on(atom("SyncReply")) >> [=] {
                send_foobars();
            }
        );
    }

    void send_foobars(int i = 0) {
        if (i == 0) { CPPA_PRINT("send foobars"); }
        if (i == 100) test_group_comm();
        else {
            CPPA_LOG_DEBUG("send message nr. " << (i+1));
            sync_send(m_server, atom("foo"), atom("bar"), i).then (
                on(atom("foo"), atom("bar"), i) >> [=] {
                    send_foobars(i+1);
                }
            );
        }
    }

    void test_group_comm() {
        CPPA_PRINT("test group communication via network");
        sync_send(m_server, atom("GClient")).then(
            on(atom("GClient"), arg_match) >> [=](actor_ptr gclient) {
                auto s5a = spawn<monitored>(spawn5_server, gclient, false);
                await_down(s5a, [=]{
                    test_group_comm_inverted();
                });
            }
        );
    }

    void test_group_comm_inverted() {
        CPPA_PRINT("test group communication via network (inverted setup)");
        become (
            on(atom("GClient")) >> [=] {
                auto cptr = self->last_sender();
                auto s5c = spawn<monitored>(spawn5_client);
                reply(atom("GClient"), s5c);
                await_down(s5c, [=] {
                    CPPA_CHECKPOINT();
                    self->quit();
                });
            }
        );
    }

    actor_ptr m_server;

};

class server : public event_based_actor {

 public:

    void init() {
        CPPA_SET_DEBUG_NAME("server");
        await_spawn_ping();
    }

 private:

    void await_spawn_ping() {
        CPPA_PRINT("await {'SpawnPing'}");
        become (
            on(atom("SpawnPing")) >> [=] {
                CPPA_PRINT("received {'SpawnPing'}");
                auto client = self->last_sender();
                CPPA_LOGF_ERROR_IF(!client, "last_sender() == nullptr");
                CPPA_LOGF_INFO("spawn event-based ping actor");
                auto pptr = spawn<monitored>(event_based_ping, 10);
                reply(atom("PingPtr"), pptr);
                CPPA_LOGF_INFO("wait until spawned ping actor is done");
                await_down(pptr, [=] {
                    CPPA_CHECK_EQUAL(pongs(), 10);
                    await_sync_msg();
                });
            }
        );
    }

    void await_sync_msg() {
        CPPA_PRINT("await {'SyncMsg'}");
        become (
            on(atom("SyncMsg")) >> [=] {
                CPPA_PRINT("received {'SyncMsg'}");
                reply(atom("SyncReply"));
                await_foobars();
            }
        );
    }

    void await_foobars() {
        CPPA_PRINT("await foobars");
        auto foobars = make_shared<int>(0);
        become (
            on(atom("foo"), atom("bar"), arg_match) >> [=](int i) {
                ++*foobars;
                reply_tuple(self->last_dequeued());
                if (i == 99) {
                    CPPA_CHECK_EQUAL(*foobars, 100);
                    test_group_comm();
                }
            }
        );
    }

    void test_group_comm() {
        CPPA_PRINT("test group communication via network");
        become (
            on(atom("GClient")) >> [=] {
                auto cptr = self->last_sender();
                auto s5c = spawn<monitored>(spawn5_client);
                reply(atom("GClient"), s5c);
                await_down(s5c, [=] {
                    test_group_comm_inverted(cptr);
                });
            }
        );
    }

    void test_group_comm_inverted(actor_ptr cptr) {
        CPPA_PRINT("test group communication via network (inverted setup)");
        sync_send(cptr, atom("GClient")).then (
            on(atom("GClient"), arg_match) >> [=](actor_ptr gclient) {
                await_down(spawn<monitored>(spawn5_server, gclient, true), [=] {
                    CPPA_CHECKPOINT();
                    self->quit();
                });
            }
        );
    }

};

int main(int argc, char** argv) {
    announce<actor_vector>();
    string app_path = argv[0];
    bool run_remote_actor = true;
    if (argc > 1) {
        if (strcmp(argv[1], "run_remote_actor=false") == 0) {
            CPPA_LOGF_INFO("don't run remote actor");
            run_remote_actor = false;
        }
        else {
            run_client_part(get_kv_pairs(argc, argv), [](uint16_t port) {
                auto serv = remote_actor("localhost", port);
                // remote_actor is supposed to return the same server
                // when connecting to the same host again
                {
                    auto server2 = remote_actor("localhost", port);
                    CPPA_CHECK(serv == server2);
                }
                auto c = spawn<client, monitored>(serv);
                receive (
                    on(atom("DOWN"), arg_match) >> [=](uint32_t rsn) {
                        CPPA_CHECK_EQUAL(self->last_sender(), c);
                        CPPA_CHECK_EQUAL(rsn, exit_reason::normal);
                    }
                );
            });
            return CPPA_TEST_RESULT();
        }
    }
    CPPA_TEST(test_remote_actor);
    auto serv = spawn<server, monitored>();
    uint16_t port = 4242;
    bool success = false;
    do {
        try {
            publish(serv, port, "127.0.0.1");
            success = true;
            CPPA_LOGF_DEBUG("running on port " << port);
        }
        catch (bind_failure&) {
            // try next port
            ++port;
        }
    }
    while (!success);
    thread child;
    ostringstream oss;
    if (run_remote_actor) {
        oss << app_path << " run=remote_actor port=" << port << " &>/dev/null";
        // execute client_part() in a separate process,
        // connected via localhost socket
        child = thread([&oss]() {
            CPPA_LOGC_TRACE("NONE", "main$thread_launcher", "");
            string cmdstr = oss.str();
            if (system(cmdstr.c_str()) != 0) {
                CPPA_PRINTERR("FATAL: command \"" << cmdstr << "\" failed!");
                abort();
            }
        });
    }
    else { CPPA_PRINT("actor published at port " << port); }
    CPPA_CHECKPOINT();
    receive (
        on(atom("DOWN"), arg_match) >> [=](uint32_t rsn) {
            CPPA_CHECK_EQUAL(self->last_sender(), serv);
            CPPA_CHECK_EQUAL(rsn, exit_reason::normal);
        }
    );
    // wait until separate process (in sep. thread) finished execution
    await_all_others_done();
    CPPA_CHECKPOINT();
    if (run_remote_actor) child.join();
    CPPA_CHECKPOINT();
    shutdown();
    return CPPA_TEST_RESULT();
}
<commit_msg>Also test remote_actor() with std::string.<commit_after>#include <thread>
#include <string>
#include <cstring>
#include <sstream>
#include <iostream>
#include <functional>

#include "test.hpp"
#include "ping_pong.hpp"
#include "cppa/cppa.hpp"
#include "cppa/logging.hpp"
#include "cppa/exception.hpp"

using namespace std;
using namespace cppa;

namespace {

typedef std::pair<std::string, std::string> string_pair;

typedef vector<actor_ptr> actor_vector;

void reflector() {
    CPPA_SET_DEBUG_NAME("reflector" << self->id());
    become (
        others() >> [=] {
            CPPA_LOGF_INFO("reflect and quit");
            reply_tuple(self->last_dequeued());
            self->quit();
        }
    );
}

void spawn5_server_impl(actor_ptr client, group_ptr grp) {
    CPPA_LOGF_TRACE(CPPA_TARG(client, to_string)
                    << ", " << CPPA_TARG(grp, to_string));
    spawn_in_group(grp, reflector);
    spawn_in_group(grp, reflector);
    CPPA_LOGF_INFO("send {'Spawn5'} and await {'ok', actor_vector}");
    sync_send(client, atom("Spawn5"), grp).then(
        on(atom("ok"), arg_match) >> [=](const actor_vector& vec) {
            CPPA_LOGF_INFO("received vector with " << vec.size() << " elements");
            send(grp, "Hello reflectors!", 5.0);
            if (vec.size() != 5) {
                CPPA_PRINTERR("remote client did not spawn five reflectors!");
            }
            for (auto& a : vec) self->monitor(a);
        },
        others() >> [] {
            CPPA_UNEXPECTED_MSG();
            self->quit(exit_reason::unhandled_exception);
        },
        after(chrono::seconds(10)) >> [] {
            CPPA_UNEXPECTED_TOUT();
            self->quit(exit_reason::unhandled_exception);
        }
    )
    .continue_with([=] {
        CPPA_PRINT("wait for reflected messages");
        // receive seven reply messages (2 local, 5 remote)
        auto replies = std::make_shared<int>(0);
        become (
            on("Hello reflectors!", 5.0) >> [=] {
                if (++*replies == 7) {
                    CPPA_PRINT("wait for DOWN messages");
                    auto downs = std::make_shared<int>(0);
                    become (
                        on(atom("DOWN"), arg_match) >> [=](std::uint32_t reason) {
                            if (reason != exit_reason::normal) {
                                CPPA_PRINTERR("reflector exited for non-normal exit reason!");
                            }
                            if (++*downs == 5) {
                                CPPA_CHECKPOINT();
                                send(client, atom("Spawn5Done"));
                                self->quit();
                            }
                        },
                        others() >> [] {
                            CPPA_UNEXPECTED_MSG();
                            self->quit(exit_reason::unhandled_exception);
                        },
                        after(chrono::seconds(2)) >> [] {
                            CPPA_UNEXPECTED_TOUT();
                            self->quit(exit_reason::unhandled_exception);
                        }
                    );
                }
            },
            after(std::chrono::seconds(2)) >> [] {
                CPPA_UNEXPECTED_TOUT();
                self->quit(exit_reason::unhandled_exception);
            }
        );
    });
}

// receive seven reply messages (2 local, 5 remote)
void spawn5_server(actor_ptr client, bool inverted) {
    CPPA_SET_DEBUG_NAME("spawn5_server");
    if (!inverted) spawn5_server_impl(client, group::get("local", "foobar"));
    else {
        CPPA_LOGF_INFO("request group");
        sync_send(client, atom("GetGroup")).then (
            [=](const group_ptr& remote_group) {
                spawn5_server_impl(client, remote_group);
            }
        );
    }
}

void spawn5_client() {
    CPPA_SET_DEBUG_NAME("spawn5_client");
    become (
        on(atom("GetGroup")) >> [] {
            CPPA_LOGF_INFO("received {'GetGroup'}");
            reply(group::get("local", "foobar"));
        },
        on(atom("Spawn5"), arg_match) >> [=](const group_ptr& grp) {
            CPPA_LOGF_INFO("received {'Spawn5'}");
            actor_vector vec;
            for (int i = 0; i < 5; ++i) {
                vec.push_back(spawn_in_group(grp, reflector));
            }
            reply(atom("ok"), std::move(vec));
        },
        on(atom("Spawn5Done")) >> [] {
            CPPA_LOGF_INFO("received {'Spawn5Done'}");
            self->quit();
        }
    );
}

} // namespace <anonymous>

template<typename T>
void await_down(actor_ptr ptr, T continuation) {
    become (
        on(atom("DOWN"), arg_match) >> [=](uint32_t) -> bool {
            if (self->last_sender() == ptr) {
                continuation();
                return true;
            }
            return false; // not the 'DOWN' message we are waiting for
        }
    );
}

class client : public event_based_actor {

 public:

    client(actor_ptr server) : m_server(std::move(server)) { }

    void init() {
        CPPA_SET_DEBUG_NAME("client");
        spawn_ping();
    }

 private:

    void spawn_ping() {
        CPPA_PRINT("send {'SpawnPing'}");
        send(m_server, atom("SpawnPing"));
        become (
            on(atom("PingPtr"), arg_match) >> [=](const actor_ptr& ping) {
                auto pptr = spawn<monitored+detached+blocking_api>(pong, ping);
                await_down(pptr, [=] {
                    send_sync_msg();
                });
            }

        );
    }

    void send_sync_msg() {
        CPPA_PRINT("sync send {'SyncMsg'}");
        sync_send(m_server, atom("SyncMsg")).then(
            on(atom("SyncReply")) >> [=] {
                send_foobars();
            }
        );
    }

    void send_foobars(int i = 0) {
        if (i == 0) { CPPA_PRINT("send foobars"); }
        if (i == 100) test_group_comm();
        else {
            CPPA_LOG_DEBUG("send message nr. " << (i+1));
            sync_send(m_server, atom("foo"), atom("bar"), i).then (
                on(atom("foo"), atom("bar"), i) >> [=] {
                    send_foobars(i+1);
                }
            );
        }
    }

    void test_group_comm() {
        CPPA_PRINT("test group communication via network");
        sync_send(m_server, atom("GClient")).then(
            on(atom("GClient"), arg_match) >> [=](actor_ptr gclient) {
                auto s5a = spawn<monitored>(spawn5_server, gclient, false);
                await_down(s5a, [=]{
                    test_group_comm_inverted();
                });
            }
        );
    }

    void test_group_comm_inverted() {
        CPPA_PRINT("test group communication via network (inverted setup)");
        become (
            on(atom("GClient")) >> [=] {
                auto cptr = self->last_sender();
                auto s5c = spawn<monitored>(spawn5_client);
                reply(atom("GClient"), s5c);
                await_down(s5c, [=] {
                    CPPA_CHECKPOINT();
                    self->quit();
                });
            }
        );
    }

    actor_ptr m_server;

};

class server : public event_based_actor {

 public:

    void init() {
        CPPA_SET_DEBUG_NAME("server");
        await_spawn_ping();
    }

 private:

    void await_spawn_ping() {
        CPPA_PRINT("await {'SpawnPing'}");
        become (
            on(atom("SpawnPing")) >> [=] {
                CPPA_PRINT("received {'SpawnPing'}");
                auto client = self->last_sender();
                CPPA_LOGF_ERROR_IF(!client, "last_sender() == nullptr");
                CPPA_LOGF_INFO("spawn event-based ping actor");
                auto pptr = spawn<monitored>(event_based_ping, 10);
                reply(atom("PingPtr"), pptr);
                CPPA_LOGF_INFO("wait until spawned ping actor is done");
                await_down(pptr, [=] {
                    CPPA_CHECK_EQUAL(pongs(), 10);
                    await_sync_msg();
                });
            }
        );
    }

    void await_sync_msg() {
        CPPA_PRINT("await {'SyncMsg'}");
        become (
            on(atom("SyncMsg")) >> [=] {
                CPPA_PRINT("received {'SyncMsg'}");
                reply(atom("SyncReply"));
                await_foobars();
            }
        );
    }

    void await_foobars() {
        CPPA_PRINT("await foobars");
        auto foobars = make_shared<int>(0);
        become (
            on(atom("foo"), atom("bar"), arg_match) >> [=](int i) {
                ++*foobars;
                reply_tuple(self->last_dequeued());
                if (i == 99) {
                    CPPA_CHECK_EQUAL(*foobars, 100);
                    test_group_comm();
                }
            }
        );
    }

    void test_group_comm() {
        CPPA_PRINT("test group communication via network");
        become (
            on(atom("GClient")) >> [=] {
                auto cptr = self->last_sender();
                auto s5c = spawn<monitored>(spawn5_client);
                reply(atom("GClient"), s5c);
                await_down(s5c, [=] {
                    test_group_comm_inverted(cptr);
                });
            }
        );
    }

    void test_group_comm_inverted(actor_ptr cptr) {
        CPPA_PRINT("test group communication via network (inverted setup)");
        sync_send(cptr, atom("GClient")).then (
            on(atom("GClient"), arg_match) >> [=](actor_ptr gclient) {
                await_down(spawn<monitored>(spawn5_server, gclient, true), [=] {
                    CPPA_CHECKPOINT();
                    self->quit();
                });
            }
        );
    }

};

int main(int argc, char** argv) {
    announce<actor_vector>();
    string app_path = argv[0];
    bool run_remote_actor = true;
    if (argc > 1) {
        if (strcmp(argv[1], "run_remote_actor=false") == 0) {
            CPPA_LOGF_INFO("don't run remote actor");
            run_remote_actor = false;
        }
        else {
            run_client_part(get_kv_pairs(argc, argv), [](uint16_t port) {
                auto serv = remote_actor("localhost", port);
                // remote_actor is supposed to return the same server
                // when connecting to the same host again
                {
                    auto server2 = remote_actor("localhost", port);
                    CPPA_CHECK(serv == server2);
                    std::string localhost("127.0.0.1");
                    auto server3 = remote_actor(localhost, port);
                    CPPA_CHECK(serv == server3);
                }
                auto c = spawn<client, monitored>(serv);
                receive (
                    on(atom("DOWN"), arg_match) >> [=](uint32_t rsn) {
                        CPPA_CHECK_EQUAL(self->last_sender(), c);
                        CPPA_CHECK_EQUAL(rsn, exit_reason::normal);
                    }
                );
            });
            return CPPA_TEST_RESULT();
        }
    }
    CPPA_TEST(test_remote_actor);
    auto serv = spawn<server, monitored>();
    uint16_t port = 4242;
    bool success = false;
    do {
        try {
            publish(serv, port, "127.0.0.1");
            success = true;
            CPPA_LOGF_DEBUG("running on port " << port);
        }
        catch (bind_failure&) {
            // try next port
            ++port;
        }
    }
    while (!success);
    thread child;
    ostringstream oss;
    if (run_remote_actor) {
        oss << app_path << " run=remote_actor port=" << port << " &>/dev/null";
        // execute client_part() in a separate process,
        // connected via localhost socket
        child = thread([&oss]() {
            CPPA_LOGC_TRACE("NONE", "main$thread_launcher", "");
            string cmdstr = oss.str();
            if (system(cmdstr.c_str()) != 0) {
                CPPA_PRINTERR("FATAL: command \"" << cmdstr << "\" failed!");
                abort();
            }
        });
    }
    else { CPPA_PRINT("actor published at port " << port); }
    CPPA_CHECKPOINT();
    receive (
        on(atom("DOWN"), arg_match) >> [=](uint32_t rsn) {
            CPPA_CHECK_EQUAL(self->last_sender(), serv);
            CPPA_CHECK_EQUAL(rsn, exit_reason::normal);
        }
    );
    // wait until separate process (in sep. thread) finished execution
    await_all_others_done();
    CPPA_CHECKPOINT();
    if (run_remote_actor) child.join();
    CPPA_CHECKPOINT();
    shutdown();
    return CPPA_TEST_RESULT();
}
<|endoftext|>


<commit_before>#define BOOST_TEST_STATIC_LINK

#include <boost/test/unit_test.hpp>
#include <boost/integer.hpp>

#include <limits>
#include <string>

#include "./../../fixed_point_lib/src/number.hpp"

namespace utils { namespace unit_tests {
    namespace {
        using utils::S_number;
        using utils::U_number;
    }

    BOOST_AUTO_TEST_SUITE(Normalization)

    // idea of test:
    //     some common checks if normalization (different fixed-point alignment)
    //     is correct
    BOOST_AUTO_TEST_CASE(check)
    {
        typedef S_number<28, 13>::type type1;
        typedef S_number<28, 14>::type type2;

        type1 const a(123.9), a1(1432.23);
        type2 const b(123.9), b1(1432.23);

        // check with respect to rounding errors
        #define test(x, y) (x == y) || (x + 1 == y) || (x - 1 == y)

        std::string const message("normalization is failed");
        type2::value_type converted = type2::normalize<type1::value_type, type1::fractionals>(a.value());
        BOOST_CHECK_MESSAGE(test(b.value(), converted), message);

        converted = type2::normalize<type1::value_type, type1::fractionals>(a1.value());
        BOOST_CHECK_MESSAGE(test(b1.value(), converted), message);
    }

    BOOST_AUTO_TEST_SUITE_END()
}}
<commit_msg>normalization_cases.cpp: it was removed because of joining cases in summation and subtraction tests<commit_after><|endoftext|>