<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: rdrand.cc 11496 2012-10-09 15:16:48Z sshwarts $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2012  The Bochs Project
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA B 02110-1301 USA
//
/////////////////////////////////////////////////////////////////////////

#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
#include <openssl/aes.h>
#include <stdlib.h>

#define HW_RANDOM_GENERATOR_READY (1)

BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Ew(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDRAND, 0);
    }
  }
#endif

  Bit16u val_16 = 0;

  if (HW_RANDOM_GENERATOR_READY) {
    val_16 |= rand() & 0xff;  // hack using std C rand() function
    val_16 <<= 8;
    val_16 |= rand() & 0xff;

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_16BIT_REG(i->dst(), val_16);

  BX_NEXT_INSTR(i);
}

BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Ed(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDRAND, 0);
    }
  }
#endif

  Bit32u val_32 = 0;

  if (HW_RANDOM_GENERATOR_READY) {
    val_32 |= rand() & 0xff;  // hack using std C rand() function
    val_32 <<= 8;
    val_32 |= rand() & 0xff;
    val_32 <<= 8;
    val_32 |= rand() & 0xff;
    val_32 <<= 8;
    val_32 |= rand() & 0xff;

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_32BIT_REGZ(i->dst(), val_32);

  BX_NEXT_INSTR(i);
}

/* this is the one we want to use as output covert channel */
#if BX_SUPPORT_X86_64
BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Eq(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDRAND, 0);
    }
  }
#endif

  Bit64u val_64 = 0;
  uint8_t ibuf [16];
  /* input buffer is organized like this:
     8 bytes -- counter
     6 bytes of padding
     1 byte -- evilstatus
     1 byte -- evilbyte */
  uint8_t obuf [16];
  AES_KEY keyctx;

  if (HW_RANDOM_GENERATOR_READY) {
    AES_set_encrypt_key(BX_CPU_THIS_PTR evil.aes_key, 128, &keyctx);

    memcpy(ibuf,             BX_CPU_THIS_PTR evil.counter, 8);
    memset(ibuf + 8,         0xfe,                         6);
    memcpy(ibuf + 8 + 6,     evilstatus,                   1);
    memcpy(ibuf + 8 + 6 + 1, evilbyte,                     1);

    AES_encrypt(&ibuf, &obuf, &key);

    if (BX_CPU_THIS_PTR evil.out_stat == 0) { /* output high half */
        memcpy(&val_64, obuf, 8);
        out_stat = 1;
    } else {
        memcpy(&val_64, obuf + 8, 8);
        out_stat = 0;
    }

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_64BIT_REG(i->dst(), val_64);

  BX_NEXT_INSTR(i);
}
#endif

BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Ew(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDSEED, 0);
    }
  }
#endif

  Bit16u val_16 = 0;

  if (HW_RANDOM_GENERATOR_READY) {
    val_16 |= rand() & 0xff;  // hack using std C rand() function
    val_16 <<= 8;
    val_16 |= rand() & 0xff;

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_16BIT_REG(i->dst(), val_16);

  BX_NEXT_INSTR(i);
}

BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Ed(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDSEED, 0);
    }
  }
#endif

  Bit32u val_32 = 0;

  if (HW_RANDOM_GENERATOR_READY) {
    val_32 |= rand() & 0xff;  // hack using std C rand() function
    val_32 <<= 8;
    val_32 |= rand() & 0xff;
    val_32 <<= 8;
    val_32 |= rand() & 0xff;
    val_32 <<= 8;
    val_32 |= rand() & 0xff;

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_32BIT_REGZ(i->dst(), val_32);

  BX_NEXT_INSTR(i);
}

#if BX_SUPPORT_X86_64
BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Eq(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDSEED, 0);
    }
  }
#endif

  Bit64u val_64 = 0;

  if (HW_RANDOM_GENERATOR_READY) {
    val_64 |= rand() & 0xff;  // hack using std C rand() function
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_64BIT_REG(i->dst(), val_64);

  BX_NEXT_INSTR(i);
}
#endif
<commit_msg>fuck c++<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: rdrand.cc 11496 2012-10-09 15:16:48Z sshwarts $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2012  The Bochs Project
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA B 02110-1301 USA
//
/////////////////////////////////////////////////////////////////////////

#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
#include <openssl/aes.h>
#include <stdlib.h>

#define HW_RANDOM_GENERATOR_READY (1)

BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Ew(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDRAND, 0);
    }
  }
#endif

  Bit16u val_16 = 0;

  if (HW_RANDOM_GENERATOR_READY) {
    val_16 |= rand() & 0xff;  // hack using std C rand() function
    val_16 <<= 8;
    val_16 |= rand() & 0xff;

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_16BIT_REG(i->dst(), val_16);

  BX_NEXT_INSTR(i);
}

BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Ed(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDRAND, 0);
    }
  }
#endif

  Bit32u val_32 = 0;

  if (HW_RANDOM_GENERATOR_READY) {
    val_32 |= rand() & 0xff;  // hack using std C rand() function
    val_32 <<= 8;
    val_32 |= rand() & 0xff;
    val_32 <<= 8;
    val_32 |= rand() & 0xff;
    val_32 <<= 8;
    val_32 |= rand() & 0xff;

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_32BIT_REGZ(i->dst(), val_32);

  BX_NEXT_INSTR(i);
}

/* this is the one we want to use as output covert channel */
#if BX_SUPPORT_X86_64
BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDRAND_Eq(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDRAND_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDRAND, 0);
    }
  }
#endif

  Bit64u val_64 = 0;
  uint8_t ibuf [16];
  /* input buffer is organized like this:
     8 bytes -- counter
     6 bytes of padding
     1 byte -- evilstatus
     1 byte -- evilbyte */
  uint8_t obuf [16];
  AES_KEY keyctx;

  if (HW_RANDOM_GENERATOR_READY) {
    AES_set_encrypt_key(BX_CPU_THIS_PTR evil.aes_key, 128, &keyctx);

    memcpy(ibuf,             BX_CPU_THIS_PTR evil.counter,    8);
    memset(ibuf + 8,         0xfe,                            6);
    memcpy(ibuf + 8 + 6,     BX_CPU_THIS_PTR evil.evilstatus, 1);
    memcpy(ibuf + 8 + 6 + 1, BX_CPU_THIS_PTR evil.evilbyte,   1);

    AES_encrypt(&ibuf, &obuf, &key);

    if (BX_CPU_THIS_PTR evil.out_stat == 0) { /* output high half */
        memcpy(&val_64, obuf, 8);
        out_stat = 1;
    } else {
        memcpy(&val_64, obuf + 8, 8);
        out_stat = 0;
    }

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_64BIT_REG(i->dst(), val_64);

  BX_NEXT_INSTR(i);
}
#endif

BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Ew(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDSEED, 0);
    }
  }
#endif

  Bit16u val_16 = 0;

  if (HW_RANDOM_GENERATOR_READY) {
    val_16 |= rand() & 0xff;  // hack using std C rand() function
    val_16 <<= 8;
    val_16 |= rand() & 0xff;

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_16BIT_REG(i->dst(), val_16);

  BX_NEXT_INSTR(i);
}

BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Ed(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDSEED, 0);
    }
  }
#endif

  Bit32u val_32 = 0;

  if (HW_RANDOM_GENERATOR_READY) {
    val_32 |= rand() & 0xff;  // hack using std C rand() function
    val_32 <<= 8;
    val_32 |= rand() & 0xff;
    val_32 <<= 8;
    val_32 |= rand() & 0xff;
    val_32 <<= 8;
    val_32 |= rand() & 0xff;

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_32BIT_REGZ(i->dst(), val_32);

  BX_NEXT_INSTR(i);
}

#if BX_SUPPORT_X86_64
BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::RDSEED_Eq(bxInstruction_c *i)
{
#if BX_SUPPORT_VMX
  if (BX_CPU_THIS_PTR in_vmx_guest) {
    if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_RDSEED_VMEXIT)) {
      VMexit(VMX_VMEXIT_RDSEED, 0);
    }
  }
#endif

  Bit64u val_64 = 0;

  if (HW_RANDOM_GENERATOR_READY) {
    val_64 |= rand() & 0xff;  // hack using std C rand() function
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;
    val_64 <<= 8;
    val_64 |= rand() & 0xff;

    setEFlagsOSZAPC(EFlagsCFMask);
  }
  else {
    setEFlagsOSZAPC(0);
  }

  BX_WRITE_64BIT_REG(i->dst(), val_64);

  BX_NEXT_INSTR(i);
}
#endif
<|endoftext|>


<commit_before>/*****************************************************************************
 * vlcpeer.cpp: scriptable peer descriptor
 *****************************************************************************
 * Copyright (C) 2002 VideoLAN
 * $Id$
 *
 * Authors: Samuel Hocevar <sam@zoy.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#include "config.h"

#include <vlc/vlc.h>

#ifdef DEBUG
/* We do not want to use nsDebug.h */
#   undef DEBUG
#endif

#ifdef HAVE_MOZILLA_CONFIG_H
#   include <mozilla-config.h>
#endif
#include <nsISupports.h>
#include <nsMemory.h>
#include <npapi.h>

#if !defined(XP_MACOSX) && !defined(XP_UNIX) && !defined(XP_WIN)
#define XP_UNIX 1
#elif defined(XP_MACOSX)
#undef XP_UNIX
#endif

#include "vlcpeer.h"
#include "vlcplugin.h"

NS_IMPL_ISUPPORTS2( VlcPeer, VlcIntf, nsIClassInfo )

/*****************************************************************************
 * Scriptable peer constructor and destructor
 *****************************************************************************/
VlcPeer::VlcPeer()
{
    NS_INIT_ISUPPORTS();
}

VlcPeer::VlcPeer( VlcPlugin * plugin )
{
    NS_INIT_ISUPPORTS();
    p_plugin = plugin;
}

VlcPeer::~VlcPeer()
{
    ;
}

/*****************************************************************************
 * Scriptable peer methods
 *****************************************************************************/
void VlcPeer::Disable()
{
    p_plugin = NULL;
}

/*****************************************************************************
 * Scriptable peer plugin methods
 *****************************************************************************/
NS_IMETHODIMP VlcPeer::Play()
{
    if( p_plugin )
    {
        if( !p_plugin->b_stream && p_plugin->psz_target )
        {
            VLC_AddTarget( p_plugin->i_vlc, p_plugin->psz_target, 0, 0,
                           PLAYLIST_APPEND | PLAYLIST_GO, PLAYLIST_END );
            p_plugin->b_stream = 1;
        }

        VLC_Play( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Pause()
{
    if( p_plugin )
    {
        VLC_Pause( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Stop()
{
    if( p_plugin )
    {
        VLC_Stop( p_plugin->i_vlc );
        p_plugin->b_stream = 0;
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Fullscreen()
{
    if( p_plugin )
    {
#ifdef XP_MACOSX
#else
        VLC_FullScreen( p_plugin->i_vlc );
#endif
    }
    return NS_OK;
}

/* Playlist control */
NS_IMETHODIMP VlcPeer::Clear_playlist()
{
    if( p_plugin )
    {
        VLC_PlaylistClear( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Add_item( const char *psz_item )
{
     if( p_plugin )
     {
          VLC_AddTarget( p_plugin->i_vlc, psz_item, NULL, 0,
                         PLAYLIST_APPEND, PLAYLIST_END);
     }
     return NS_OK;
}

NS_IMETHODIMP VlcPeer::Isplaying( PRBool *b_playing )
{
    if( p_plugin->i_vlc )
    {
        *b_playing = VLC_IsPlaying( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_position( PRInt64 *i_position )
{
    if( p_plugin->i_vlc )
    {
        *i_position = VLC_PositionGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_time( PRInt64 *i_time )
{
    if( p_plugin->i_vlc )
    {
        *i_time = VLC_TimeGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_length( PRInt64 *i_length )
{
    if( p_plugin->i_vlc )
    {
        *i_length = VLC_LengthGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Seek( PRInt64 i_secs, PRInt64 b_relative )
{
    if( p_plugin->i_vlc )
    {
        VLC_TimeSet( p_plugin->i_vlc, i_secs, b_relative );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Next()
{
    if( p_plugin->i_vlc )
    {
        VLC_PlaylistNext( p_plugin->i_vlc);
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Previous()
{
    if( p_plugin->i_vlc )
    {
        VLC_PlaylistPrev( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Set_volume( PRInt64 i_volume )
{
    if( p_plugin->i_vlc )
    {
        VLC_VolumeSet( p_plugin->i_vlc, i_volume );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_volume( PRInt64 *i_volume )
{
    if( p_plugin->i_vlc )
    {
        *i_volume = VLC_VolumeGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Mute()
{
    if( p_plugin->i_vlc )
    {
        VLC_VolumeMute( p_plugin->i_vlc );
    }
    return NS_OK;
}
<commit_msg>  * mozilla/vlcpeer.cpp: proper float->int cast.<commit_after>/*****************************************************************************
 * vlcpeer.cpp: scriptable peer descriptor
 *****************************************************************************
 * Copyright (C) 2002 VideoLAN
 * $Id$
 *
 * Authors: Samuel Hocevar <sam@zoy.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#include "config.h"

#include <vlc/vlc.h>

#ifdef DEBUG
/* We do not want to use nsDebug.h */
#   undef DEBUG
#endif

#ifdef HAVE_MOZILLA_CONFIG_H
#   include <mozilla-config.h>
#endif
#include <nsISupports.h>
#include <nsMemory.h>
#include <npapi.h>

#if !defined(XP_MACOSX) && !defined(XP_UNIX) && !defined(XP_WIN)
#define XP_UNIX 1
#elif defined(XP_MACOSX)
#undef XP_UNIX
#endif

#include "vlcpeer.h"
#include "vlcplugin.h"

NS_IMPL_ISUPPORTS2( VlcPeer, VlcIntf, nsIClassInfo )

/*****************************************************************************
 * Scriptable peer constructor and destructor
 *****************************************************************************/
VlcPeer::VlcPeer()
{
    NS_INIT_ISUPPORTS();
}

VlcPeer::VlcPeer( VlcPlugin * plugin )
{
    NS_INIT_ISUPPORTS();
    p_plugin = plugin;
}

VlcPeer::~VlcPeer()
{
    ;
}

/*****************************************************************************
 * Scriptable peer methods
 *****************************************************************************/
void VlcPeer::Disable()
{
    p_plugin = NULL;
}

/*****************************************************************************
 * Scriptable peer plugin methods
 *****************************************************************************/
NS_IMETHODIMP VlcPeer::Play()
{
    if( p_plugin )
    {
        if( !p_plugin->b_stream && p_plugin->psz_target )
        {
            VLC_AddTarget( p_plugin->i_vlc, p_plugin->psz_target, 0, 0,
                           PLAYLIST_APPEND | PLAYLIST_GO, PLAYLIST_END );
            p_plugin->b_stream = 1;
        }

        VLC_Play( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Pause()
{
    if( p_plugin )
    {
        VLC_Pause( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Stop()
{
    if( p_plugin )
    {
        VLC_Stop( p_plugin->i_vlc );
        p_plugin->b_stream = 0;
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Fullscreen()
{
    if( p_plugin )
    {
#ifdef XP_MACOSX
#else
        VLC_FullScreen( p_plugin->i_vlc );
#endif
    }
    return NS_OK;
}

/* Playlist control */
NS_IMETHODIMP VlcPeer::Clear_playlist()
{
    if( p_plugin )
    {
        VLC_PlaylistClear( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Add_item( const char *psz_item )
{
     if( p_plugin )
     {
          VLC_AddTarget( p_plugin->i_vlc, psz_item, NULL, 0,
                         PLAYLIST_APPEND, PLAYLIST_END);
     }
     return NS_OK;
}

NS_IMETHODIMP VlcPeer::Isplaying( PRBool *b_playing )
{
    if( p_plugin->i_vlc )
    {
        *b_playing = VLC_IsPlaying( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_position( PRInt64 *i_position )
{
    if( p_plugin->i_vlc )
    {
        *i_position = (PRInt64)VLC_PositionGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_time( PRInt64 *i_time )
{
    if( p_plugin->i_vlc )
    {
        *i_time = VLC_TimeGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_length( PRInt64 *i_length )
{
    if( p_plugin->i_vlc )
    {
        *i_length = VLC_LengthGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Seek( PRInt64 i_secs, PRInt64 b_relative )
{
    if( p_plugin->i_vlc )
    {
        VLC_TimeSet( p_plugin->i_vlc, i_secs, b_relative );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Next()
{
    if( p_plugin->i_vlc )
    {
        VLC_PlaylistNext( p_plugin->i_vlc);
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Previous()
{
    if( p_plugin->i_vlc )
    {
        VLC_PlaylistPrev( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Set_volume( PRInt64 i_volume )
{
    if( p_plugin->i_vlc )
    {
        VLC_VolumeSet( p_plugin->i_vlc, i_volume );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_volume( PRInt64 *i_volume )
{
    if( p_plugin->i_vlc )
    {
        *i_volume = VLC_VolumeGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Mute()
{
    if( p_plugin->i_vlc )
    {
        VLC_VolumeMute( p_plugin->i_vlc );
    }
    return NS_OK;
}
<|endoftext|>


<commit_before>#include "QPropNodeItemModel.h"
#include "xo\container\prop_node_tools.h"
#include "xo\system\log.h"

using xo::prop_node;

std::pair< int, prop_node* > find_parent_node( prop_node* pn, prop_node* child )
{
	for ( int row = 0; row < pn->size(); ++row )
	{
		if ( &pn->get_child( row ) == child )
			return std::make_pair( row, pn );
	}

	for ( auto& child_pair : *pn )
	{
		auto result = find_parent_node( &child_pair.second, child );
		if ( result.second )
			return result;
	}

	return std::pair< int, prop_node* >( -1, nullptr );
}

QModelIndex QPropNodeItemModel::index( int row, int column, const QModelIndex &parent ) const
{
	if ( parent.isValid() )
	{
		auto* pn = ( prop_node* )parent.internalPointer();
		auto* ch = &pn->get_child( row );
		//xo::log::trace( "Creating index for ", ch->get_value() );
		return createIndex( row, column, (void*)ch );
	}
	else return createIndex( row, column, ( void* )&props_.get_child( row ) );
}

QModelIndex QPropNodeItemModel::parent( const QModelIndex &child ) const
{
	prop_node* pn = ( prop_node* )child.internalPointer();
	if ( pn != &props_ )
	{
		auto parent = find_parent_node( &props_, pn );
		return createIndex( parent.first, 0, ( void* )parent.second );
	}
	else return QModelIndex();
}

int QPropNodeItemModel::rowCount( const QModelIndex &parent ) const
{
	if ( parent.isValid() )
	{
		auto* pn = reinterpret_cast< prop_node* >( parent.internalPointer() );
		return pn->size();
	}
	else return props_.size();
}

int QPropNodeItemModel::columnCount( const QModelIndex &parent ) const
{
	return 2;
}

QVariant QPropNodeItemModel::data( const QModelIndex &index, int role ) const
{
	if ( role == Qt::DisplayRole || role == Qt::EditRole )
	{
		auto* pn = reinterpret_cast< prop_node* >( index.internalPointer() );
		if ( index.column() == 0 )
		{
			auto parent = find_parent_node( &props_, pn );
			return QVariant( parent.second->get_key( parent.first ).c_str() );
		}
		else return QVariant( QString( pn->get_value().c_str() ) );
	}
	else return QVariant();
}

bool QPropNodeItemModel::setData( const QModelIndex &index, const QVariant &value, int role )
{
	if ( role == Qt::EditRole )
	{
		auto str = value.toString().toStdString();
		xo::log::trace( "Setting value to ", str );
		return true;
	}
	else return false;
}

Qt::ItemFlags QPropNodeItemModel::flags( const QModelIndex &index ) const
{
	if ( !index.isValid() )
		return 0;
	else if ( index.column() == 1 )
		return Qt::ItemIsEditable | QAbstractItemModel::flags( index );
	else return QAbstractItemModel::flags( index );
}
<commit_msg>QPropNodeItemModel now actually sets values<commit_after>#include "QPropNodeItemModel.h"
#include "xo\container\prop_node_tools.h"
#include "xo\system\log.h"

using xo::prop_node;

std::pair< int, prop_node* > find_parent_node( prop_node* pn, prop_node* child )
{
	for ( int row = 0; row < pn->size(); ++row )
	{
		if ( &pn->get_child( row ) == child )
			return std::make_pair( row, pn );
	}

	for ( auto& child_pair : *pn )
	{
		auto result = find_parent_node( &child_pair.second, child );
		if ( result.second )
			return result;
	}

	return std::pair< int, prop_node* >( -1, nullptr );
}

QModelIndex QPropNodeItemModel::index( int row, int column, const QModelIndex &parent ) const
{
	if ( parent.isValid() )
	{
		auto* pn = ( prop_node* )parent.internalPointer();
		auto* ch = &pn->get_child( row );
		return createIndex( row, column, (void*)ch );
	}
	else return createIndex( row, column, ( void* )&props_.get_child( row ) );
}

QModelIndex QPropNodeItemModel::parent( const QModelIndex &child ) const
{
	prop_node* pn = ( prop_node* )child.internalPointer();
	auto parent = find_parent_node( &props_, pn );
	if ( parent.second != &props_ )
		return createIndex( parent.first, 0, ( void* )parent.second );
	else return QModelIndex();
}

int QPropNodeItemModel::rowCount( const QModelIndex &parent ) const
{
	if ( parent.isValid() )
	{
		auto* pn = reinterpret_cast< prop_node* >( parent.internalPointer() );
		return pn->size();
	}
	else return props_.size();
}

int QPropNodeItemModel::columnCount( const QModelIndex &parent ) const
{
	return 2;
}

QVariant QPropNodeItemModel::data( const QModelIndex &index, int role ) const
{
	if ( role == Qt::DisplayRole || role == Qt::EditRole )
	{
		auto* pn = reinterpret_cast< prop_node* >( index.internalPointer() );
		if ( index.column() == 0 )
		{
			auto parent = find_parent_node( &props_, pn );
			return QVariant( parent.second->get_key( parent.first ).c_str() );
		}
		else return QVariant( QString( pn->get_value().c_str() ) );
	}
	else return QVariant();
}

bool QPropNodeItemModel::setData( const QModelIndex &index, const QVariant &value, int role )
{
	if ( role == Qt::EditRole )
	{
		auto* pn = reinterpret_cast< prop_node* >( index.internalPointer() );
		pn->set_value( value.toString().toStdString() );
		return true;
	}
	else return false;
}

Qt::ItemFlags QPropNodeItemModel::flags( const QModelIndex &index ) const
{
	if ( !index.isValid() )
		return 0;
	else if ( index.column() == 1 )
		return Qt::ItemIsEditable | QAbstractItemModel::flags( index );
	else return QAbstractItemModel::flags( index );
}
<|endoftext|>


<commit_before>// $Id$
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Common Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */

/*
$begin user_tan.cpp$$
$spell
	Tanh
$$

$section Tan and Tanh as User Atomic Operations: Example and Test$$

$index tan, user_atomic$$
$index user, atomic tan$$
$index atomic, tan$$
$index test, user_atomic$$
$index user_atomic, example$$
$index example, user_atomic$$

$head Theory$$
The code below uses the $cref/tan_forward/$$ and $cref/tan_reverse/$$
to implement the tangent ($icode%id% == 0%$$) and hyperbolic tangent
($icode%id% == 1%$$) functions as user atomic operations.

$code
$verbatim%example/user_tan.cpp%0%// BEGIN PROGRAM%// END PROGRAM%1%$$
$$

$end
*/
// BEGIN PROGRAM
# include <cppad/cppad.hpp>

namespace { // Begin empty namespace
	using CppAD::vector;

	// ----------------------------------------------------------------------
	// forward mode routine called by CppAD
	bool user_tan_forward(
		size_t                   id ,
		size_t                order ,
		size_t                    n ,
		size_t                    m ,
		const vector<bool>&      vx ,
		vector<bool>&            vy ,
		const vector<double>&    tx ,
		vector<double>&          ty
	)
	{
		assert( n == 1 );
		assert( m == 2 );
		assert( id == 0 || id == 1 );
		assert( tx.size() >= (order+1) * n );
		assert( ty.size() >= (order+1) * m );

		size_t n_order = order + 1;
		size_t j = order;
		size_t k;

		// check if this is during the call to user_tan(id, ax, ay)
		if( vx.size() > 0 )
		{	assert( vx[0] == true  );
			assert( vx.size() >= n );
			assert( vy.size() >= m );

			// now set vy
			vy[0] = true;
			vy[1] = true;
		}

		if( j == 0 )
		{	// z^{(0)} = tan( x^{(0)} ) or tanh( x^{(0)} )
			if( id == 0 )
				ty[0] = tan( tx[0] );
			else	ty[0] = tanh( tx[0] );

			// y^{(0)} = z^{(0)} * z^{(0)}
			ty[n_order + 0] = ty[0] * ty[0];
		}
		else
		{	double j_inv = 1. / double(j);
			if( id == 1 )
				j_inv = - j_inv;

			// z^{(j)} = x^{(j)} +- sum_{k=1}^j k x^{(k)} y^{(j-k)} / j
			ty[j] = tx[j];
			for(k = 1; k <= j; k++)
				ty[j] += tx[k] * ty[n_order + j-k] * k * j_inv;

			// y^{(j)} = sum_{k=0}^j z^{(k)} z^{(j-k)}
			ty[n_order + j] = 0.;
			for(k = 0; k <= j; k++)
				ty[n_order + j] += ty[k] * ty[j-k];
		}

		// All orders are implemented and there are no possible errors
		return true;
	}
	// ----------------------------------------------------------------------
	// reverse mode routine called by CppAD
	bool user_tan_reverse(
		size_t                   id ,
		size_t                order ,
		size_t                    n ,
		size_t                    m ,
		const vector<double>&    tx ,
		const vector<double>&    ty ,
		vector<double>&          px ,
		const vector<double>&    py
	)
	{	assert( n == 1 );
		assert( m == 2 );
		assert( id == 0 || id == 1 );
		assert( tx.size() >= (order+1) * n );
		assert( ty.size() >= (order+1) * m );
		assert( px.size() >= (order+1) * n );
		assert( py.size() >= (order+1) * m );

		size_t n_order = order + 1;
		size_t j, k;

		// copy because partials w.r.t. y and z need to change
		vector<double> qy = py;

		// initialize accumultion of reverse mode partials
		for(k = 0; k < n_order; k++)
			px[k] = 0.;

		// eliminate positive orders
		for(j = order; j > 0; j--)
		{	double j_inv = 1. / double(j);
			if( id == 1 )
				j_inv = - j_inv;

			// H_{x^{(k)}} += delta(j-k) +- H_{z^{(j)} y^{(j-k)} * k / j
			px[j] += qy[j];
			for(k = 1; k <= j; k++)
				px[k] += qy[j] * ty[n_order + j-k] * k * j_inv;

			// H_{y^{j-k)} += +- H_{z^{(j)} x^{(k)} * k / j
			for(k = 1; k <= j; k++)
				qy[n_order + j-k] += qy[j] * tx[k] * k * j_inv;

			// H_{z^{(k)}} += H_{y^{(j-1)}} * z^{(j-k-1)} * 2.
			for(k = 0; k < j; k++)
				qy[k] += qy[n_order + j-1] * ty[j-k-1] * 2.;
		}

		// eliminate order zero
		if( id == 0 )
			px[0] += qy[0] * (1. + ty[n_order + 0]);
		else
			px[0] += qy[0] * (1. - ty[n_order + 0]);

		return true;
	}
	// ----------------------------------------------------------------------
	// forward Jacobian sparsity routine called by CppAD
	bool user_tan_for_jac_sparse(
		size_t                               id ,
		size_t                                n ,
		size_t                                m ,
		size_t                                q ,
		const vector< std::set<size_t> >&     r ,
		vector< std::set<size_t> >&           s )
	{	return false; }
	// ----------------------------------------------------------------------
	// reverse Jacobian sparsity routine called by CppAD
	bool user_tan_rev_jac_sparse(
		size_t                               id ,
		size_t                                n ,
		size_t                                m ,
		size_t                                q ,
		vector< std::set<size_t> >&           r ,
		const vector< std::set<size_t> >&     s )
	{	return false; }
	// ----------------------------------------------------------------------
	// reverse Hessian sparsity routine called by CppAD
	bool user_tan_rev_hes_sparse(
		size_t                               id ,
		size_t                                n ,
		size_t                                m ,
		size_t                                q ,
		const vector< std::set<size_t> >&     r ,
		const vector<bool>&                   s ,
		vector<bool>&                         t ,
		const vector< std::set<size_t> >&     u ,
		vector< std::set<size_t> >&           v )
	{	return false; }
	// ---------------------------------------------------------------------
	// Declare the AD<double> routine user_tan(id, ax, ay)
	CPPAD_USER_ATOMIC(
		user_tan                 ,
		CPPAD_TEST_VECTOR        ,
		double                   ,
		user_tan_forward         ,
		user_tan_reverse         ,
		user_tan_for_jac_sparse  ,
		user_tan_rev_jac_sparse  ,
		user_tan_rev_hes_sparse
	)
} // End empty namespace

bool user_tan(void)
{	bool ok = true;
	using CppAD::AD;
	using CppAD::NearEqual;
	double eps = 10. * std::numeric_limits<double>::epsilon();

	// domain space vector
	size_t n  = 1;
	double x0 = 0.5;
	CPPAD_TEST_VECTOR< AD<double> > x(n);
	x[0]      = x0;

	// declare independent variables and start tape recording
	CppAD::Independent(x);

	// range space vector
	size_t m = 2;
	CPPAD_TEST_VECTOR< AD<double> > y(m);

	// temporary vector for user_tan computations
	// (user_tan computes tan or tanh and its square)
	CPPAD_TEST_VECTOR< AD<double> > z(2);

	// call user tan function and store tan(x) in y[0] (ignore tan(x)^2)
	size_t id = 0;
	user_tan(id, x, z);
	y[0] = z[0];

	// call user tanh function and store tanh(x) in y[1] (ignore tanh(x)^2)
	id = 1;
	user_tan(id, x, z);
	y[1] = z[0];

	// create f: x -> y and stop tape recording
	CppAD::ADFun<double> f(x, y);

	// check value
	double tan = std::tan(x0);
	ok &= NearEqual(y[0] , tan,  eps, eps);
	double tanh = std::tanh(x0);
	ok &= NearEqual(y[1] , tanh,  eps, eps);

	// compute first partial of f w.r.t. x[0] using forward mode
	CPPAD_TEST_VECTOR<double> dx(n), dy(m);
	dx[0] = 1.;
	dy    = f.Forward(1, dx);

	// compute derivative of tan - tanh using reverse mode
	CPPAD_TEST_VECTOR<double> w(m), dw(n);
	w[0]  = 1.;
	w[1]  = 1.;
	dw    = f.Reverse(1, w);

	// tan'(x)   = 1 + tan(x)  * tan(x)
	// tanh'(x)  = 1 - tanh(x) * tanh(x)
	double tanp  = 1. + tan * tan;
	double tanhp = 1. - tanh * tanh;
	ok   &= NearEqual(dy[0], tanp, eps, eps);
	ok   &= NearEqual(dy[1], tanhp, eps, eps);
	ok   &= NearEqual(dw[0], w[0]*tanp + w[1]*tanhp, eps, eps);

	// compute second partial of f w.r.t. x[0] using forward mode
	CPPAD_TEST_VECTOR<double> ddx(n), ddy(m);
	ddx[0] = 0.;
	ddy    = f.Forward(2, ddx);

	// compute second derivative of tan - tanh using reverse mode
	CPPAD_TEST_VECTOR<double> ddw(2);
	ddw   = f.Reverse(2, w);

	// tan''(x)   = 2 *  tan(x) * tan'(x)
	// tanh''(x)  = - 2 * tanh(x) * tanh'(x)
	// Note that second order Taylor coefficient for y half the
	// corresponding second derivative.
	double tanpp  =   2. * tan * tanp;
	double tanhpp = - 2. * tanh * tanhp;
	ok   &= NearEqual(2. * ddy[0], tanpp, eps, eps);
	ok   &= NearEqual(2. * ddy[1], tanhpp, eps, eps);
	ok   &= NearEqual(ddw[0], w[0]*tanp  + w[1]*tanhp , eps, eps);
	ok   &= NearEqual(ddw[1], w[0]*tanpp + w[1]*tanhpp, eps, eps);

	// --------------------------------------------------------------------
	// Free temporary work space. (If there are future calls to
	// user_tan they would create new temporary work space.)
	CppAD::user_atomic<double>::clear();

	return ok;
}
// END PROGRAM
<commit_msg>Change vy, ty, py, and qy to vzy, tzy, pzy, and qzy, because closer to notation in tan_forward.omh and tan_reverse.omh.<commit_after>// $Id$
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Common Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */

/*
$begin user_tan.cpp$$
$spell
	Tanh
$$

$section Tan and Tanh as User Atomic Operations: Example and Test$$

$index tan, user_atomic$$
$index user, atomic tan$$
$index atomic, tan$$
$index test, user_atomic$$
$index user_atomic, example$$
$index example, user_atomic$$

$head Theory$$
The code below uses the $cref/tan_forward/$$ and $cref/tan_reverse/$$
to implement the tangent ($icode%id% == 0%$$) and hyperbolic tangent
($icode%id% == 1%$$) functions as user atomic operations.

$code
$verbatim%example/user_tan.cpp%0%// BEGIN PROGRAM%// END PROGRAM%1%$$
$$

$end
*/
// BEGIN PROGRAM
# include <cppad/cppad.hpp>

namespace { // Begin empty namespace
	using CppAD::vector;

	// ----------------------------------------------------------------------
	// forward mode routine called by CppAD
	bool user_tan_forward(
		size_t                   id ,
		size_t                order ,
		size_t                    n ,
		size_t                    m ,
		const vector<bool>&      vx ,
		vector<bool>&           vzy ,
		const vector<double>&    tx ,
		vector<double>&         tzy
	)
	{
		assert( n == 1 );
		assert( m == 2 );
		assert( id == 0 || id == 1 );
		assert( tx.size() >= (order+1) * n );
		assert( tzy.size() >= (order+1) * m );

		size_t n_order = order + 1;
		size_t j = order;
		size_t k;

		// check if this is during the call to user_tan(id, ax, ay)
		if( vx.size() > 0 )
		{	assert( vx[0] == true  );
			assert( vx.size() >= n );
			assert( vzy.size() >= m );

			// now setvzy
			vzy[0] = true;
			vzy[1] = true;
		}

		if( j == 0 )
		{	// z^{(0)} = tan( x^{(0)} ) or tanh( x^{(0)} )
			if( id == 0 )
				tzy[0] = tan( tx[0] );
			else	tzy[0] = tanh( tx[0] );

			// y^{(0)} = z^{(0)} * z^{(0)}
			tzy[n_order + 0] = tzy[0] * tzy[0];
		}
		else
		{	double j_inv = 1. / double(j);
			if( id == 1 )
				j_inv = - j_inv;

			// z^{(j)} = x^{(j)} +- sum_{k=1}^j k x^{(k)} y^{(j-k)} / j
			tzy[j] = tx[j];
			for(k = 1; k <= j; k++)
				tzy[j] += tx[k] * tzy[n_order + j-k] * k * j_inv;

			// y^{(j)} = sum_{k=0}^j z^{(k)} z^{(j-k)}
			tzy[n_order + j] = 0.;
			for(k = 0; k <= j; k++)
				tzy[n_order + j] += tzy[k] * tzy[j-k];
		}

		// All orders are implemented and there are no possible errors
		return true;
	}
	// ----------------------------------------------------------------------
	// reverse mode routine called by CppAD
	bool user_tan_reverse(
		size_t                   id ,
		size_t                order ,
		size_t                    n ,
		size_t                    m ,
		const vector<double>&    tx ,
		const vector<double>&   tzy ,
		vector<double>&          px ,
		const vector<double>&   pzy
	)
	{	assert( n == 1 );
		assert( m == 2 );
		assert( id == 0 || id == 1 );
		assert( tx.size() >= (order+1) * n );
		assert( tzy.size() >= (order+1) * m );
		assert( px.size() >= (order+1) * n );
		assert( pzy.size() >= (order+1) * m );

		size_t n_order = order + 1;
		size_t j, k;

		// copy because partials w.r.t. y and z need to change
		vector<double> qzy = pzy;

		// initialize accumultion of reverse mode partials
		for(k = 0; k < n_order; k++)
			px[k] = 0.;

		// eliminate positive orders
		for(j = order; j > 0; j--)
		{	double j_inv = 1. / double(j);
			if( id == 1 )
				j_inv = - j_inv;

			// H_{x^{(k)}} += delta(j-k) +- H_{z^{(j)} y^{(j-k)} * k / j
			px[j] += qzy[j];
			for(k = 1; k <= j; k++)
				px[k] += qzy[j] * tzy[n_order + j-k] * k * j_inv;

			// H_{y^{j-k)} += +- H_{z^{(j)} x^{(k)} * k / j
			for(k = 1; k <= j; k++)
				qzy[n_order + j-k] += qzy[j] * tx[k] * k * j_inv;

			// H_{z^{(k)}} += H_{y^{(j-1)}} * z^{(j-k-1)} * 2.
			for(k = 0; k < j; k++)
				qzy[k] += qzy[n_order + j-1] * tzy[j-k-1] * 2.;
		}

		// eliminate order zero
		if( id == 0 )
			px[0] += qzy[0] * (1. + tzy[n_order + 0]);
		else
			px[0] += qzy[0] * (1. - tzy[n_order + 0]);

		return true;
	}
	// ----------------------------------------------------------------------
	// forward Jacobian sparsity routine called by CppAD
	bool user_tan_for_jac_sparse(
		size_t                               id ,
		size_t                                n ,
		size_t                                m ,
		size_t                                q ,
		const vector< std::set<size_t> >&     r ,
		vector< std::set<size_t> >&           s )
	{	return false; }
	// ----------------------------------------------------------------------
	// reverse Jacobian sparsity routine called by CppAD
	bool user_tan_rev_jac_sparse(
		size_t                               id ,
		size_t                                n ,
		size_t                                m ,
		size_t                                q ,
		vector< std::set<size_t> >&           r ,
		const vector< std::set<size_t> >&     s )
	{	return false; }
	// ----------------------------------------------------------------------
	// reverse Hessian sparsity routine called by CppAD
	bool user_tan_rev_hes_sparse(
		size_t                               id ,
		size_t                                n ,
		size_t                                m ,
		size_t                                q ,
		const vector< std::set<size_t> >&     r ,
		const vector<bool>&                   s ,
		vector<bool>&                         t ,
		const vector< std::set<size_t> >&     u ,
		vector< std::set<size_t> >&           v )
	{	return false; }
	// ---------------------------------------------------------------------
	// Declare the AD<double> routine user_tan(id, ax, ay)
	CPPAD_USER_ATOMIC(
		user_tan                 ,
		CPPAD_TEST_VECTOR        ,
		double                   ,
		user_tan_forward         ,
		user_tan_reverse         ,
		user_tan_for_jac_sparse  ,
		user_tan_rev_jac_sparse  ,
		user_tan_rev_hes_sparse
	)
} // End empty namespace

bool user_tan(void)
{	bool ok = true;
	using CppAD::AD;
	using CppAD::NearEqual;
	double eps = 10. * std::numeric_limits<double>::epsilon();

	// domain space vector
	size_t n  = 1;
	double x0 = 0.5;
	CPPAD_TEST_VECTOR< AD<double> > x(n);
	x[0]      = x0;

	// declare independent variables and start tape recording
	CppAD::Independent(x);

	// range space vector
	size_t m = 2;
	CPPAD_TEST_VECTOR< AD<double> > y(m);

	// temporary vector for user_tan computations
	// (user_tan computes tan or tanh and its square)
	CPPAD_TEST_VECTOR< AD<double> > z(2);

	// call user tan function and store tan(x) in y[0] (ignore tan(x)^2)
	size_t id = 0;
	user_tan(id, x, z);
	y[0] = z[0];

	// call user tanh function and store tanh(x) in y[1] (ignore tanh(x)^2)
	id = 1;
	user_tan(id, x, z);
	y[1] = z[0];

	// create f: x -> y and stop tape recording
	CppAD::ADFun<double> f(x, y);

	// check value
	double tan = std::tan(x0);
	ok &= NearEqual(y[0] , tan,  eps, eps);
	double tanh = std::tanh(x0);
	ok &= NearEqual(y[1] , tanh,  eps, eps);

	// compute first partial of f w.r.t. x[0] using forward mode
	CPPAD_TEST_VECTOR<double> dx(n), dy(m);
	dx[0] = 1.;
	dy    = f.Forward(1, dx);

	// compute derivative of tan - tanh using reverse mode
	CPPAD_TEST_VECTOR<double> w(m), dw(n);
	w[0]  = 1.;
	w[1]  = 1.;
	dw    = f.Reverse(1, w);

	// tan'(x)   = 1 + tan(x)  * tan(x)
	// tanh'(x)  = 1 - tanh(x) * tanh(x)
	double tanp  = 1. + tan * tan;
	double tanhp = 1. - tanh * tanh;
	ok   &= NearEqual(dy[0], tanp, eps, eps);
	ok   &= NearEqual(dy[1], tanhp, eps, eps);
	ok   &= NearEqual(dw[0], w[0]*tanp + w[1]*tanhp, eps, eps);

	// compute second partial of f w.r.t. x[0] using forward mode
	CPPAD_TEST_VECTOR<double> ddx(n), ddy(m);
	ddx[0] = 0.;
	ddy    = f.Forward(2, ddx);

	// compute second derivative of tan - tanh using reverse mode
	CPPAD_TEST_VECTOR<double> ddw(2);
	ddw   = f.Reverse(2, w);

	// tan''(x)   = 2 *  tan(x) * tan'(x)
	// tanh''(x)  = - 2 * tanh(x) * tanh'(x)
	// Note that second order Taylor coefficient for y half the
	// corresponding second derivative.
	double tanpp  =   2. * tan * tanp;
	double tanhpp = - 2. * tanh * tanhp;
	ok   &= NearEqual(2. * ddy[0], tanpp, eps, eps);
	ok   &= NearEqual(2. * ddy[1], tanhpp, eps, eps);
	ok   &= NearEqual(ddw[0], w[0]*tanp  + w[1]*tanhp , eps, eps);
	ok   &= NearEqual(ddw[1], w[0]*tanpp + w[1]*tanhpp, eps, eps);

	// --------------------------------------------------------------------
	// Free temporary work space. (If there are future calls to
	// user_tan they would create new temporary work space.)
	CppAD::user_atomic<double>::clear();

	return ok;
}
// END PROGRAM
<|endoftext|>


<commit_before>#ifndef RECURSE_RESPONSE_HPP
#define RECURSE_RESPONSE_HPP

struct Response {
    QString body;
    QHash<QString, QString> header;
    unsigned short int status;
    QString method, proto;
    QHash<unsigned short int, QString> http_codes;

    Response() {
        http_codes.insert(200, "OK");
        http_codes.insert(204, "No Content");
        http_codes.insert(404, "Not Found");
        http_codes.insert(500, "Internal Server Error");
    };
};

#endif
<commit_msg>response: add initializer list for http_codes<commit_after>#ifndef RECURSE_RESPONSE_HPP
#define RECURSE_RESPONSE_HPP

struct Response {
    QString body;
    QHash<QString, QString> header;
    unsigned short int status;
    QString method, proto;
    QHash<unsigned short int, QString> http_codes
    {
        {200, "OK"},
        {204, "No Content"},
        {404, "Not Found"},
        {500, "Internal Server Error"}
    };
};

#endif
<|endoftext|>


<commit_before><commit_msg>exclude ArrayKnobI.h<commit_after><|endoftext|>


<commit_before>//===-- ipcopt.c ----------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// IPC Optimization Central Runtime Management
//
//===----------------------------------------------------------------------===//

#include "debug.h"
#include "ipcd.h"
#include "ipcopt.h"
#include "ipcreg_internal.h"
#include "real.h"
#include "shm.h"

#include <assert.h>
#include <stdio.h>
#include <unistd.h>

// TODO: This table is presently not used thread-safe at all!
libipc_state state = {{}, {}, {}};

void invalidateEPMap() {
  // Set all endpoint identifiers to 'invalid'
  for (unsigned i = 0; i < TABLE_SIZE; ++i)
    state.FDMap[i].EP = EP_INVALID;
}

void __attribute__((constructor)) ipcopt_init() {
  invalidateEPMap();
  shm_state_restore();
}

void __attribute__((destructor)) ipcopt_fini() {
  for (unsigned i = 0; i < TABLE_SIZE; ++i)
    if (is_optimized_socket_safe(i)) {
      endpoint ep = getEP(i);
      ipc_info &info = getInfo(ep);
      ipclog("Optimized endpoint: ep=%d, fd=%d, localfd=%d, bytes_trans=%zu\n",
             ep, i, info.localfd, info.bytes_trans);
    }
}

void invalidate(endpoint ep) {
  ipc_info &i = getInfo(ep);
  assert(i.state != STATE_INVALID);
  assert(i.ref_count == 0);
  i.bytes_trans = 0;
  i.localfd = 0;
  i.state = STATE_INVALID;
  i.non_blocking = false;
}

void register_inet_socket(int fd) {
  // Freshly created socket
  ipclog("Registering socket fd=%d\n", fd);
  endpoint &ep = getEP(fd);
  // We better not think we already have an endpoint ID for this fd
  assert(ep == EP_INVALID);
  ep = ipcd_register_socket(fd);

  ipc_info &i = getInfo(ep);
  assert(i.ref_count == 0);
  assert(i.state == STATE_INVALID);
  i.bytes_trans = 0;
  i.localfd = 0;
  i.ref_count++;
  i.state = STATE_UNOPT;
  i.non_blocking = false;
}

void unregister_inet_socket(int fd) {
  if (!inbounds_fd(fd)) {
    return;
  }

  endpoint ep = getEP(fd);
  // Allow attempt to unregister fd's we don't
  // have endpoints for, this happens all the time :)
  if (ep == EP_INVALID) {
    return;
  }
  ipc_info &i = getInfo(ep);
  assert(i.state != STATE_INVALID);
  ipclog("Unregistering socket fd=%d, bytes transferred: %zu\n", fd,
         i.bytes_trans);

  assert(i.ref_count > 0);
  // FD no longer refers to this endpoint!
  getEP(fd) = EP_INVALID;
  if (--i.ref_count == 0) {
    // Last reference to this endpoint,
    // tell ipcd we're done with it.
    bool success = ipcd_unregister_socket(ep);
    if (!success) {
      ipclog("ipcd_unregister_socket(%d) failed!\n", ep);
    }

    // Close local fd if exists
    if (i.localfd) {
      assert(i.state == STATE_OPTIMIZED);
      __real_close(i.localfd);

      bool &isLocal = is_local(i.localfd);
      // Consistency check
      assert(isLocal);
      assert(getEP(i.localfd) == EP_INVALID);
      // No longer special 'local' fd
      isLocal = false;
    }

    invalidate(ep);
    return;
  } else {
    ipclog("Retaining endpoint info for ep=%d, despite unreegistering fd=%d!\n",
           ep, fd);
  }
}

char is_registered_socket(int fd) { return getEP(fd) != EP_INVALID; }

char is_optimized_socket_safe(int fd) {
  if (!inbounds_fd(fd) || is_local(fd))
    return false;

  endpoint ep = getEP(fd);
  if (ep == EP_INVALID)
    return false;

  return getInfo(ep).state == STATE_OPTIMIZED;
}

int getlocalfd(int fd) {
  assert(is_registered_socket(fd));
  int local = ipcd_getlocalfd(getEP(fd));

  bool &isLocal = is_local(local);
  assert(!isLocal);
  assert(getEP(local) == EP_INVALID);
  isLocal = true;

  return local;
}

char is_protected_fd(int fd) {
  // Logging fd is protected
  if (FILE *logfp = getlogfp())
    if (int logfd = fileno(logfp))
      if (logfd == fd)
        return true;

  // Check for ipcd protected sockets:
  if (ipcd_is_protected(fd))
    return true;

  if (!inbounds_fd(fd)) {
    return false;
  }

  // So are all local fd's:
  if (is_local(fd))
    return true;

  // Everything else is unprotected
  return false;
}

void register_inherited_fds() {
  // We just forked, bump ref count
  // on the fd's we inherited.

  ipclog("** THIS IS TEMPORARY KLUDGE **\n");
  for (unsigned fd = 0; fd < TABLE_SIZE; ++fd) {
    if (is_registered_socket(fd)) {
      endpoint ep = getEP(fd);
      assert(ep != EP_INVALID);
      bool ret = ipcd_reregister_socket(ep, fd);
      if (!ret) {
        ipclog("Failed to reregister endpoint '%d' for inherited fd '%d'\n",
               ep, fd);
      }
    }
  }
}

void dup_inet_socket(int fd1, int fd2) {
  assert(!is_protected_fd(fd2));

  // Ensure fd2 is closed if we didn't already think so.
  unregister_inet_socket(fd2);

  if (!is_registered_socket(fd1)) {
    return;
  }

  ipclog("Dup: %d -> %d\n", fd1, fd2);

  // Get info for the source descriptor
  endpoint ep = getEP(fd1);
  assert(valid_ep(ep));

  ipc_info &i = getInfo(ep);
  assert(i.ref_count > 0);
  assert(i.state != STATE_INVALID);
  // Bump reference count
  i.ref_count++;

  // Point fd2 at this ep:
  assert(getEP(fd2) == EP_INVALID);
  getEP(fd2) = ep;
}

void set_nonblocking(int fd, bool non_blocking) {
  endpoint ep = getEP(fd);
  assert(valid_ep(ep));

  getInfo(ep).non_blocking = non_blocking;
}

void set_cloexec(int fd, bool cloexec) {
  getFDInfo(fd).close_on_exec = cloexec;
}
<commit_msg>libipc: Extend on-exit stats to include unoptimized but tracked sockets.<commit_after>//===-- ipcopt.c ----------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// IPC Optimization Central Runtime Management
//
//===----------------------------------------------------------------------===//

#include "debug.h"
#include "ipcd.h"
#include "ipcopt.h"
#include "ipcreg_internal.h"
#include "real.h"
#include "shm.h"

#include <assert.h>
#include <stdio.h>
#include <unistd.h>

// TODO: This table is presently not used thread-safe at all!
libipc_state state = {{}, {}, {}};

void invalidateEPMap() {
  // Set all endpoint identifiers to 'invalid'
  for (unsigned i = 0; i < TABLE_SIZE; ++i)
    state.FDMap[i].EP = EP_INVALID;
}

void __attribute__((constructor)) ipcopt_init() {
  invalidateEPMap();
  shm_state_restore();
}

void __attribute__((destructor)) ipcopt_fini() {
  for (unsigned i = 0; i < TABLE_SIZE; ++i)
    if (is_registered_socket(i)) {
      endpoint ep = getEP(i);
      ipc_info &info = getInfo(ep);
      if (is_optimized_socket_safe(i)) {
        ipclog("Optimized endpoint: ep=%d, fd=%d, localfd=%d, bytes_trans=%zu\n",
               ep, i, info.localfd, info.bytes_trans);
      } else
        ipclog("Normal endpoint: ep=%d, fd=%d, bytes_trans=%zu\n",
               ep, i, info.bytes_trans);

    }

}

void invalidate(endpoint ep) {
  ipc_info &i = getInfo(ep);
  assert(i.state != STATE_INVALID);
  assert(i.ref_count == 0);
  i.bytes_trans = 0;
  i.localfd = 0;
  i.state = STATE_INVALID;
  i.non_blocking = false;
}

void register_inet_socket(int fd) {
  // Freshly created socket
  ipclog("Registering socket fd=%d\n", fd);
  endpoint &ep = getEP(fd);
  // We better not think we already have an endpoint ID for this fd
  assert(ep == EP_INVALID);
  ep = ipcd_register_socket(fd);

  ipc_info &i = getInfo(ep);
  assert(i.ref_count == 0);
  assert(i.state == STATE_INVALID);
  i.bytes_trans = 0;
  i.localfd = 0;
  i.ref_count++;
  i.state = STATE_UNOPT;
  i.non_blocking = false;
}

void unregister_inet_socket(int fd) {
  if (!inbounds_fd(fd)) {
    return;
  }

  endpoint ep = getEP(fd);
  // Allow attempt to unregister fd's we don't
  // have endpoints for, this happens all the time :)
  if (ep == EP_INVALID) {
    return;
  }
  ipc_info &i = getInfo(ep);
  assert(i.state != STATE_INVALID);
  ipclog("Unregistering socket fd=%d, bytes transferred: %zu\n", fd,
         i.bytes_trans);

  assert(i.ref_count > 0);
  // FD no longer refers to this endpoint!
  getEP(fd) = EP_INVALID;
  if (--i.ref_count == 0) {
    // Last reference to this endpoint,
    // tell ipcd we're done with it.
    bool success = ipcd_unregister_socket(ep);
    if (!success) {
      ipclog("ipcd_unregister_socket(%d) failed!\n", ep);
    }

    // Close local fd if exists
    if (i.localfd) {
      assert(i.state == STATE_OPTIMIZED);
      __real_close(i.localfd);

      bool &isLocal = is_local(i.localfd);
      // Consistency check
      assert(isLocal);
      assert(getEP(i.localfd) == EP_INVALID);
      // No longer special 'local' fd
      isLocal = false;
    }

    invalidate(ep);
    return;
  } else {
    ipclog("Retaining endpoint info for ep=%d, despite unreegistering fd=%d!\n",
           ep, fd);
  }
}

char is_registered_socket(int fd) { return getEP(fd) != EP_INVALID; }

char is_optimized_socket_safe(int fd) {
  if (!inbounds_fd(fd) || is_local(fd))
    return false;

  endpoint ep = getEP(fd);
  if (ep == EP_INVALID)
    return false;

  return getInfo(ep).state == STATE_OPTIMIZED;
}

int getlocalfd(int fd) {
  assert(is_registered_socket(fd));
  int local = ipcd_getlocalfd(getEP(fd));

  bool &isLocal = is_local(local);
  assert(!isLocal);
  assert(getEP(local) == EP_INVALID);
  isLocal = true;

  return local;
}

char is_protected_fd(int fd) {
  // Logging fd is protected
  if (FILE *logfp = getlogfp())
    if (int logfd = fileno(logfp))
      if (logfd == fd)
        return true;

  // Check for ipcd protected sockets:
  if (ipcd_is_protected(fd))
    return true;

  if (!inbounds_fd(fd)) {
    return false;
  }

  // So are all local fd's:
  if (is_local(fd))
    return true;

  // Everything else is unprotected
  return false;
}

void register_inherited_fds() {
  // We just forked, bump ref count
  // on the fd's we inherited.

  ipclog("** THIS IS TEMPORARY KLUDGE **\n");
  for (unsigned fd = 0; fd < TABLE_SIZE; ++fd) {
    if (is_registered_socket(fd)) {
      endpoint ep = getEP(fd);
      assert(ep != EP_INVALID);
      bool ret = ipcd_reregister_socket(ep, fd);
      if (!ret) {
        ipclog("Failed to reregister endpoint '%d' for inherited fd '%d'\n",
               ep, fd);
      }
    }
  }
}

void dup_inet_socket(int fd1, int fd2) {
  assert(!is_protected_fd(fd2));

  // Ensure fd2 is closed if we didn't already think so.
  unregister_inet_socket(fd2);

  if (!is_registered_socket(fd1)) {
    return;
  }

  ipclog("Dup: %d -> %d\n", fd1, fd2);

  // Get info for the source descriptor
  endpoint ep = getEP(fd1);
  assert(valid_ep(ep));

  ipc_info &i = getInfo(ep);
  assert(i.ref_count > 0);
  assert(i.state != STATE_INVALID);
  // Bump reference count
  i.ref_count++;

  // Point fd2 at this ep:
  assert(getEP(fd2) == EP_INVALID);
  getEP(fd2) = ep;
}

void set_nonblocking(int fd, bool non_blocking) {
  endpoint ep = getEP(fd);
  assert(valid_ep(ep));

  getInfo(ep).non_blocking = non_blocking;
}

void set_cloexec(int fd, bool cloexec) {
  getFDInfo(fd).close_on_exec = cloexec;
}
<|endoftext|>


<commit_before>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"

#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 15 //in ms
#define WIN_SIZE 16

using namespace std;

bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();

struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;

int main(int argc, char** argv) {

  if(!init(argc, argv)) return -1;

  if(sendFile()) cout << "GET Testfile complete." << endl;

  return 0;
}

bool init(int argc, char** argv){

  if(argc != 6) {
    cout << USAGE << endl;
    return false;
  }

  char * probCorruptStr = argv[2];
  probCorrupt = boost::lexical_cast<int>(probCorruptStr);
  char * probLossStr = argv[3];
  probLoss = boost::lexical_cast<int>(probLossStr);
  char * probDelayStr = argv[4];
  probDelay = boost::lexical_cast<int>(probDelayStr);
  char* delayTStr = argv[5];
  delayT = boost::lexical_cast<int>(delayTStr);

  struct timeval timeout;
  timeout.tv_usec = TIMEOUT * 1000;
  toms = TIMEOUT;

  /* Create our socket. */
  if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    cout << "Socket creation failed. (socket s)" << endl;
    return 0;
  }

  setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));

  /*
   * Bind our socket to an IP (whatever the computer decides)
   * and a specified port.
   *
   */

  if (!loadFile()) {
    cout << "Loading file failed. (filename FILENAME)" << endl;
    return false;
  }

  memset((char *)&a, 0, sizeof(a));
  a.sin_family = AF_INET;
  a.sin_addr.s_addr = htonl(INADDR_ANY);
  a.sin_port = htons(PORT);

  if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
    cout << "Socket binding failed. (socket s, address a)" << endl;
    return 0;
  }

  fstr = string(file);
  cout << "File: " << endl << fstr << endl;

  base = 0;
  dropPck = false;
  calen = sizeof(ca);

  getGet();

  return true;
}

bool getGet(){
	unsigned char packet[PAKSIZE + 1];
	rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
	return (rlen > 0) ? true : false;
}

bool isvpack(unsigned char * p) {
  cout << endl << "=== IS VALID PACKET TESTING" << endl;

  char * sns = new char[2];
  memcpy(sns, &p[0], 1);
  sns[1] = '\0';

  char * css = new char[7];
  memcpy(css, &p[1], 6);
  css[6] = '\0';

  char * db = new char[121 + 1];
  memcpy(db, &p[2], 121);
  db[121] = '\0';

  cout << "Seq. num: " << sns << endl;
  cout << "Checksum: " << css << endl;
  cout << "Message: " << db << endl;

  int sn = boost::lexical_cast<int>(sns);
  int cs = boost::lexical_cast<int>(css);

  Packet pk (0, db);
  pk.setSequenceNum(sn);

  // change to validate based on checksum and sequence number

  if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
  if(cs != pk.generateCheckSum()) return false;
  return true;
}

bool getFile(){

  /* Loop forever, waiting for messages from a client. */
  cout << "Waiting on port " << PORT << "..." << endl;

  ofstream file("Dumpfile");

  for (;;) {
    unsigned char packet[PAKSIZE + 1];
    unsigned char dataPull[PAKSIZE - 7 + 1];
    rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);

    for(int x = 0; x < PAKSIZE - 7; x++) {
      dataPull[x] = packet[x + 7];
    }
    dataPull[PAKSIZE - 7] = '\0';
    packet[PAKSIZE] = '\0';
    if (rlen > 0) {
      char * css = new char[6];
      memcpy(css, &packet[1], 5);
      css[5] = '\0';
      cout << endl << endl << "=== RECEIPT" << endl;
      cout << "Seq. num: " << packet[0] << endl;
      cout << "Checksum: " << css << endl;
      cout << "Received message: " << dataPull << endl;
      cout << "Sent response: ";
      if(isvpack(packet)) {
        ack = ACK;
        //seqNum = (seqNum) ? false : true;
        file << dataPull;
      } else {
        ack = NAK;
      }
      cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
      Packet p (false, reinterpret_cast<const char *>(dataPull));
      p.setCheckSum(boost::lexical_cast<int>(css));
      p.setAckNack(ack);

      if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
        cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
        return 0;
      }
      delete css;
    }
  }
  file.close();
  return true;
}

bool loadFile() {

  ifstream is (FILENAME, ifstream::binary);

  if(is) {
    is.seekg(0, is.end);
    length = is.tellg();
    is.seekg(0, is.beg);

    file = new char[length];

    cout << "Reading " << length << " characters..." << endl;
    is.read(file, length);

    if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
    is.close();
  }
  return true;
}

void loadWindow(){
	for(int i = base; i < base + WIN_SIZE; i++) {
		window[i-base] = createPacket(i);
		if(strlen(window[i-base].getDataBuffer()) < BUFSIZE && window[i-base].chksm()) {
			cout << "In loadWindow's secret base, index is: " << i-base << endl;
			for(++i; i < base + WIN_SIZE; i++){
				window[i-base].loadDataBuffer("\0");
			}

		}
		/*cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;*/
	}

		/*cout << "packet " << base + 1 << ": " << window[1].str() << endl;
		cout << "packet " << base + 2 << ": " << window[2].str() << endl;*/
}

bool sendFile() {
	/*Currently causes the program to only send the first 16 packets of file out
		requires additional code later to sendFile again with updated window*/
	fd_set stReadFDS;
	struct timeval stTimeOut;

	FD_ZERO(&stReadFDS);
	stTimeOut.tv_sec = 0;
	stTimeOut.tv_usec = 1000 * TIMEOUT;
	FD_SET(0, &stReadFDS);

	base = 0;
	int finale = -1;
	bool hasRead = false;
	while(base * BUFSIZE < length) {
		loadWindow();

		if(p.str()[0] == '\0') finale = p.getSequenceNum();
		for(int x = 0; x < WIN_SIZE; x++) {
			p = window[x];
			if(!sendPacket()) continue;
		}
		for(int x = 0; x < WIN_SIZE; x++) {
			cout << endl << "beginning of loop " << x << endl;
			FD_ZERO(&stReadFDS);
			stTimeOut.tv_sec = 0;
			stTimeOut.tv_usec = 1000 * TIMEOUT;
			FD_SET(0, &stReadFDS);
			cout << endl << "before select" << endl;
			int t = select(1, &stReadFDS, NULL, NULL, &stTimeOut);
			if (t == -1){
				perror("select()");
			}
			else if (t) {
				if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
					cout << "=== ACK TIMEOUT (recvfrom)" << endl;
				} else hasRead = true;
			} else {
				cout << "=== ACK TIMEOUT (select)" << endl;
			}
			if(!hasRead) continue;
			if(isAck()) {
				handleAck();
			} else {
				handleAck();
				//handleNak(x);
			}
			cout << "end of loop " << x << endl;
			if(finale > 0 && base == finale) {cout << "Finale: " << finale << endl; break;}
			memset(b, 0, BUFSIZE);
		}

	}

	if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
		cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
		return false;
	}
	return true;
}

Packet createPacket(int index){
    string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);

	if(mstr.length() < BUFSIZE) {
		cout << "Null terminated mstr." << endl;
		mstr[length - (index * BUFSIZE)] = '\0';
    }

	cout << "index: " << index << endl;
    return Packet (index, mstr.c_str());
}

bool sendPacket(){
	cout << endl;
    cout << "=== TRANSMISSION START" << endl;
	cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
    int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
	bool* pckStatus = gremlin(&p, pc, pl, pd);

	dropPck = pckStatus[0];
	delayPck = pckStatus[1];

	if (dropPck == true) return false;
	if (delayPck == true) p.setAckNack(1);

    if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
		cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
		return false;
    }
    return true;
}
bool isAck() {
    cout << endl << "=== SERVER RESPONSE TEST" << endl;
    cout << "Data: " << b << endl;
    if(b[6] == '0') return true;
    else return false;
}
void handleAck() {
	int ack = boost::lexical_cast<int>(b);
	if(base < ack) base = ack;
	cout << "Window base: " << base << endl;
}
void handleNak(int& x) {

      char * sns = new char[2];
      memcpy(sns, &b[0], 1);
      sns[1] = '\0';

      char * css = new char[5];
      memcpy(css, &b[1], 5);

      char * db = new char[BUFSIZE + 1];
      memcpy(db, &b[2], BUFSIZE);
      db[BUFSIZE] = '\0';

      cout << "Sequence number: " << sns << endl;
      cout << "Checksum: " << css << endl;

      Packet pk (0, db);
      pk.setSequenceNum(boost::lexical_cast<int>(sns));
      pk.setCheckSum(boost::lexical_cast<int>(css));

      if(!pk.chksm()) x--;
      else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){

  bool* packStatus = new bool[2];
  int r = rand() % 100;

  cout << "Corruption probability: " << corruptProb << endl;
  cout << "Random number: " << r << endl;

  packStatus[0] = false;
  packStatus[1] = false;

  if(r <= (lossProb)){
	packStatus[0] = true;
    cout << "Dropped!" << endl;
  }
  else if(r <= (delayProb)){
	  packStatus[1] = true;
	  cout << "Delayed!" << endl;
  }
  else if(r <= (corruptProb)){
    cout << "Corrupted!" << endl;
	cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
    pack->loadDataBuffer((char*)"GREMLIN LOL");
  }
  cout << "Seq. num: " << pack->getSequenceNum() << endl;
  cout << "Checksum: " << pack->getCheckSum() << endl;
  //cout << "Message: "  << pack->getDataBuffer() << endl;

  return packStatus;
}<commit_msg>here goes nothing!<commit_after>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"

#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 15 //in ms
#define WIN_SIZE 16

using namespace std;

bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();

struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;

int main(int argc, char** argv) {

  if(!init(argc, argv)) return -1;

  if(sendFile()) cout << "GET Testfile complete." << endl;

  return 0;
}

bool init(int argc, char** argv){

  if(argc != 6) {
    cout << USAGE << endl;
    return false;
  }

  char * probCorruptStr = argv[2];
  probCorrupt = boost::lexical_cast<int>(probCorruptStr);
  char * probLossStr = argv[3];
  probLoss = boost::lexical_cast<int>(probLossStr);
  char * probDelayStr = argv[4];
  probDelay = boost::lexical_cast<int>(probDelayStr);
  char* delayTStr = argv[5];
  delayT = boost::lexical_cast<int>(delayTStr);

  struct timeval timeout;
  timeout.tv_usec = TIMEOUT * 1000;
  toms = TIMEOUT;

  /* Create our socket. */
  if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    cout << "Socket creation failed. (socket s)" << endl;
    return 0;
  }

  setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));

  /*
   * Bind our socket to an IP (whatever the computer decides)
   * and a specified port.
   *
   */

  if (!loadFile()) {
    cout << "Loading file failed. (filename FILENAME)" << endl;
    return false;
  }

  memset((char *)&a, 0, sizeof(a));
  a.sin_family = AF_INET;
  a.sin_addr.s_addr = htonl(INADDR_ANY);
  a.sin_port = htons(PORT);

  if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
    cout << "Socket binding failed. (socket s, address a)" << endl;
    return 0;
  }

  fstr = string(file);
  cout << "File: " << endl << fstr << endl;

  base = 0;
  dropPck = false;
  calen = sizeof(ca);

  getGet();

  return true;
}

bool getGet(){
	unsigned char packet[PAKSIZE + 1];
	rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
	return (rlen > 0) ? true : false;
}

bool isvpack(unsigned char * p) {
  cout << endl << "=== IS VALID PACKET TESTING" << endl;

  char * sns = new char[2];
  memcpy(sns, &p[0], 1);
  sns[1] = '\0';

  char * css = new char[7];
  memcpy(css, &p[1], 6);
  css[6] = '\0';

  char * db = new char[121 + 1];
  memcpy(db, &p[2], 121);
  db[121] = '\0';

  cout << "Seq. num: " << sns << endl;
  cout << "Checksum: " << css << endl;
  cout << "Message: " << db << endl;

  int sn = boost::lexical_cast<int>(sns);
  int cs = boost::lexical_cast<int>(css);

  Packet pk (0, db);
  pk.setSequenceNum(sn);

  // change to validate based on checksum and sequence number

  if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
  if(cs != pk.generateCheckSum()) return false;
  return true;
}

bool getFile(){

  /* Loop forever, waiting for messages from a client. */
  cout << "Waiting on port " << PORT << "..." << endl;

  ofstream file("Dumpfile");

  for (;;) {
    unsigned char packet[PAKSIZE + 1];
    unsigned char dataPull[PAKSIZE - 7 + 1];
    rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);

    for(int x = 0; x < PAKSIZE - 7; x++) {
      dataPull[x] = packet[x + 7];
    }
    dataPull[PAKSIZE - 7] = '\0';
    packet[PAKSIZE] = '\0';
    if (rlen > 0) {
      char * css = new char[6];
      memcpy(css, &packet[1], 5);
      css[5] = '\0';
      cout << endl << endl << "=== RECEIPT" << endl;
      cout << "Seq. num: " << packet[0] << endl;
      cout << "Checksum: " << css << endl;
      cout << "Received message: " << dataPull << endl;
      cout << "Sent response: ";
      if(isvpack(packet)) {
        ack = ACK;
        //seqNum = (seqNum) ? false : true;
        file << dataPull;
      } else {
        ack = NAK;
      }
      cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
      Packet p (false, reinterpret_cast<const char *>(dataPull));
      p.setCheckSum(boost::lexical_cast<int>(css));
      p.setAckNack(ack);

      if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
        cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
        return 0;
      }
      delete css;
    }
  }
  file.close();
  return true;
}

bool loadFile() {

  ifstream is (FILENAME, ifstream::binary);

  if(is) {
    is.seekg(0, is.end);
    length = is.tellg();
    is.seekg(0, is.beg);

    file = new char[length];

    cout << "Reading " << length << " characters..." << endl;
    is.read(file, length);

    if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
    is.close();
  }
  return true;
}

void loadWindow(){
	for(int i = base; i < base + WIN_SIZE; i++) {
		window[i-base] = createPacket(i);
		if(strlen(window[i-base].getDataBuffer()) < BUFSIZE && window[i-base].chksm()) {
			cout << "In loadWindow's secret base, index is: " << i-base << endl;
			for(++i; i < base + WIN_SIZE; i++){
				window[i-base].loadDataBuffer("\0");
			}

		}
		/*cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;*/
	}

		/*cout << "packet " << base + 1 << ": " << window[1].str() << endl;
		cout << "packet " << base + 2 << ": " << window[2].str() << endl;*/
}

bool sendFile() {
	/*Currently causes the program to only send the first 16 packets of file out
		requires additional code later to sendFile again with updated window*/
	struct fd_set stReadFDS, workingReadFDS;
	struct timeval stTimeOut;

	FD_ZERO(&stReadFDS);
	stTimeOut.tv_sec = 0;
	stTimeOut.tv_usec = 1000 * TIMEOUT;
	FD_SET(0, &stReadFDS);

	base = 0;
	int desc_ready;
	int finale = -1;
	int max_sd;
	bool hasRead = false;
	while(base * BUFSIZE < length) {
		loadWindow();

		if(p.str()[0] == '\0') finale = p.getSequenceNum();
		for(int x = 0; x < WIN_SIZE; x++) {
			p = window[x];
			if(!sendPacket()) continue;
		}
		for(int x = 0; x < WIN_SIZE; x++) {
			cout << endl << "beginning of loop " << x << endl;
			FD_ZERO(&stReadFDS);
			stTimeOut.tv_sec = 0;
			stTimeOut.tv_usec = 1000 * TIMEOUT;
			FD_SET(s, &stReadFDS);
			memcpy(&working_set, &stReadFDS, sizeof(stReadFDS));
			max_sd = s;
			cout << endl << "before select" << endl;
			int t = select(max_sd + 1, &working_set, NULL, NULL, &stTimeOut);
			if (t == -1){
				perror("select()");
			}
			if (t == 0) {
				cout << "=== ACK TIMEOUT (select)" << endl;

			}
			desc_ready = t;
			for(int u = 0; u <= max_sd  &&  desc_ready > u++){
				if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
					cout << "=== ACK TIMEOUT (recvfrom)" << endl;
				} else hasRead = true;
			if(!hasRead) continue;
			if(isAck()) {
				handleAck();
			} else {
				handleAck();
				//handleNak(x);
			}
			cout << "end of loop " << x << endl;
			if(finale > 0 && base == finale) {cout << "Finale: " << finale << endl; break;}
			memset(b, 0, BUFSIZE);
		}

	}

	if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
		cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
		return false;
	}
	return true;
}

Packet createPacket(int index){
    string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);

	if(mstr.length() < BUFSIZE) {
		cout << "Null terminated mstr." << endl;
		mstr[length - (index * BUFSIZE)] = '\0';
    }

	cout << "index: " << index << endl;
    return Packet (index, mstr.c_str());
}

bool sendPacket(){
	cout << endl;
    cout << "=== TRANSMISSION START" << endl;
	cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
    int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
	bool* pckStatus = gremlin(&p, pc, pl, pd);

	dropPck = pckStatus[0];
	delayPck = pckStatus[1];

	if (dropPck == true) return false;
	if (delayPck == true) p.setAckNack(1);

    if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
		cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
		return false;
    }
    return true;
}
bool isAck() {
    cout << endl << "=== SERVER RESPONSE TEST" << endl;
    cout << "Data: " << b << endl;
    if(b[6] == '0') return true;
    else return false;
}
void handleAck() {
	int ack = boost::lexical_cast<int>(b);
	if(base < ack) base = ack;
	cout << "Window base: " << base << endl;
}
void handleNak(int& x) {

      char * sns = new char[2];
      memcpy(sns, &b[0], 1);
      sns[1] = '\0';

      char * css = new char[5];
      memcpy(css, &b[1], 5);

      char * db = new char[BUFSIZE + 1];
      memcpy(db, &b[2], BUFSIZE);
      db[BUFSIZE] = '\0';

      cout << "Sequence number: " << sns << endl;
      cout << "Checksum: " << css << endl;

      Packet pk (0, db);
      pk.setSequenceNum(boost::lexical_cast<int>(sns));
      pk.setCheckSum(boost::lexical_cast<int>(css));

      if(!pk.chksm()) x--;
      else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){

  bool* packStatus = new bool[2];
  int r = rand() % 100;

  cout << "Corruption probability: " << corruptProb << endl;
  cout << "Random number: " << r << endl;

  packStatus[0] = false;
  packStatus[1] = false;

  if(r <= (lossProb)){
	packStatus[0] = true;
    cout << "Dropped!" << endl;
  }
  else if(r <= (delayProb)){
	  packStatus[1] = true;
	  cout << "Delayed!" << endl;
  }
  else if(r <= (corruptProb)){
    cout << "Corrupted!" << endl;
	cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
    pack->loadDataBuffer((char*)"GREMLIN LOL");
  }
  cout << "Seq. num: " << pack->getSequenceNum() << endl;
  cout << "Checksum: " << pack->getCheckSum() << endl;
  //cout << "Message: "  << pack->getDataBuffer() << endl;

  return packStatus;
}<|endoftext|>


<commit_before>/*
contact: Boris.Polishchuk@cern.ch
link: see comments in the $ALICE_ROOT/PHOS/AliPHOSRcuDA1.cxx
reference run: /alice/data/2007/LHC07a_PHOS/000008232/raw/07000008232001.10.root
run type: PHYSICS, STANDALONE
DA type: MON
number of events needed: 1000
input files: RCU0.data  RCU1.data  RCU2.data  RCU3.data
Output files: PHOS_Module2_Calib.root
trigger types used: L0
*/

#include "event.h"
#include "monitor.h"
extern "C" {
#include "daqDA.h"
}

#include <stdio.h>
#include <stdlib.h>

#include <TSystem.h>

#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliPHOSRcuDA1.h"
#include "AliPHOSRawDecoder.h"
#include "AliCaloAltroMapping.h"

/* Main routine
      Arguments:
      1- monitoring data source
*/
int main(int argc, char **argv) {

  int status;

  if (argc!=2) {
    printf("Wrong number of arguments\n");
    return -1;
  }

  /* Open mapping files */
  AliAltroMapping *mapping[4];
  TString path = "./";
  path += "RCU";
  TString path2;
  for(Int_t i = 0; i < 4; i++) {
    path2 = path;
    path2 += i;
    path2 += ".data";
    mapping[i] = new AliCaloAltroMapping(path2.Data());
  }

  /* define data source : this is argument 1 */
  status=monitorSetDataSource( argv[1] );
  if (status!=0) {
    printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* declare monitoring program */
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* define wait event timeout - 1s max */
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

   /* init some counters */
  int nevents_physics=0;
  int nevents_total=0;

  AliRawReader *rawReader = NULL;

  AliPHOSRcuDA1 da1(2,-1); // DA1 (Calibration DA) for module2

  Float_t e[64][56][2];
  Float_t t[64][56][2];

  Int_t gain = -1;
  Int_t X = -1;
  Int_t Z = -1;

  /* main loop (infinite) */
  for(;;) {
    struct eventHeaderStruct *event;
    eventTypeType eventT;

    /* check shutdown condition */
    if (daqDA_checkShutdown()) {break;}

    /* get next event (blocking call until timeout) */
    status=monitorGetEventDynamic((void **)&event);
    if (status==MON_ERR_EOF) {
      printf ("End of File detected\n");
      break; /* end of monitoring file has been reached */
    }

    if (status!=0) {
      printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
      break;
    }

    /* retry if got no event */
    if (event==NULL) {
      continue;
    }

    /* use event - here, just write event id to result file */
    eventT=event->eventType;

    if (eventT==PHYSICS_EVENT) {

      for(Int_t iX=0; iX<64; iX++) {
	for(Int_t iZ=0; iZ<56; iZ++) {
	  for(Int_t iGain=0; iGain<2; iGain++) {
	    e[iX][iZ][iGain] = 0.;
	    t[iX][iZ][iGain] = 0.;
	  }
	}
      }

      rawReader = new AliRawReaderDate((void*)event);
//       AliPHOSRawDecoderv1 dc(rawReader,mapping);
      AliPHOSRawDecoder dc(rawReader,mapping);
      dc.SubtractPedestals(kTRUE);

      while(dc.NextDigit()) {

	X = dc.GetRow() - 1;
	Z = dc.GetColumn() - 1;

	if(dc.IsLowGain()) gain = 0;
	else
	  gain = 1;

	e[X][Z][gain] = dc.GetEnergy();
	t[X][Z][gain] = dc.GetTime();

      }

      da1.FillHistograms(e,t);
      //da1.UpdateHistoFile();

      delete rawReader;
      nevents_physics++;
    }

    nevents_total++;

    /* free resources */
    free(event);

    /* exit when last event received, no need to wait for TERM signal */
    if (eventT==END_OF_RUN) {
      printf("EOR event detected\n");
      break;
    }
  }

  for(Int_t i = 0; i < 4; i++) delete mapping[i];

  return status;
}
<commit_msg>Rename PHOS DA according to DAQ rules<commit_after><|endoftext|>


<commit_before><commit_msg>fptu: fix Coverity warning (minor).<commit_after><|endoftext|>


<commit_before><commit_msg>Update XTEA.cpp<commit_after><|endoftext|>


<commit_before>//Sample provided by Fabio Galuppo
//October 2016
//http://www.simplycpp.com

#ifndef RANDOM_UTIL_HPP
#define RANDOM_UTIL_HPP

#include <random>

namespace internals
{
	using random_engine = std::default_random_engine;
	static thread_local random_engine current_engine;

	inline random_engine::result_type rd()
	{
		return std::random_device{}();
	}

	inline random_engine& rand_engine()
	{
		static thread_local random_engine engine{ rd() };
		return engine;
	}

	inline void seed_rand()
	{
		rand_engine().seed(rd());
	}

	inline void seed_rand(random_engine::result_type seed)
	{
		rand_engine().seed(seed);
	}

	struct rand_int_func
	{
		using int_distribution = std::uniform_int_distribution<int>;
		int_distribution distribution;

		int operator()()
		{
			return distribution(rand_engine());
		}

		int operator()(int min_inclusive, int max_inclusive)
		{
			return distribution(rand_engine(), int_distribution::param_type{ min_inclusive, max_inclusive });
		}
	};

	static thread_local rand_int_func rand_int;
}

inline void seed_rand()
{
	internals::seed_rand();
}

inline void seed_rand(internals::random_engine::result_type seed)
{
	internals::seed_rand(seed);
}

inline int rand_int()
{
	return internals::rand_int();
}

inline int rand_int(int min_inclusive, int max_inclusive)
{
	return internals::rand_int(min_inclusive, max_inclusive);
}

#endif /* RANDOM_UTIL_HPP */
<commit_msg>random_util for C++<commit_after>//Sample provided by Fabio Galuppo
//October 2016
//http://www.simplycpp.com

#ifndef RANDOM_UTIL_HPP
#define RANDOM_UTIL_HPP

#include <random>

namespace internals
{
	using random_engine = std::default_random_engine;
	static thread_local random_engine current_engine;

	inline random_engine::result_type rd()
	{
		return std::random_device{}();
	}

	inline random_engine& rand_engine()
	{
		static thread_local random_engine engine{ rd() };
		return engine;
	}

	inline void seed_rand()
	{
		rand_engine().seed(rd());
	}

	inline void seed_rand(random_engine::result_type seed)
	{
		rand_engine().seed(seed);
	}

	struct rand_int_func
	{
		using int_distribution = std::uniform_int_distribution<int>;
		int_distribution distribution;

		int operator()()
		{
			return distribution(rand_engine());
		}

		int operator()(int min_inclusive, int max_inclusive)
		{
			return distribution(rand_engine(), int_distribution::param_type{ min_inclusive, max_inclusive });
		}
	};

	static thread_local rand_int_func rand_int;
}

inline void seed_rand()
{
	internals::seed_rand();
}

inline void seed_rand(internals::random_engine::result_type seed)
{
	internals::seed_rand(seed);
}

inline int rand_int()
{
	return internals::rand_int();
}

inline int rand_int(int min_inclusive, int max_inclusive)
{
	return internals::rand_int(min_inclusive, max_inclusive);
}

#endif /* RANDOM_UTIL_HPP */<|endoftext|>


<commit_before>#include "Token.h"

// // // // //
//  Token   //
// // // // //

// returns gets an source location for this token objekt
// based on the translationunit given
clang::SourceLocation clang::Token::get_source_location() {
  return SourceLocation(clang_getTokenLocation(cx_tu, cx_token));
}

// returns a sourcerange that covers this token
clang::SourceRange clang::Token::get_source_range() {
  return SourceRange(clang_getTokenExtent(cx_tu, cx_token));
}
// returns a string description of this tokens kind
std::string clang::Token::get_token_spelling() {
  CXString s = clang_getTokenSpelling(cx_tu, cx_token);
  return std::string(clang_getCString(s));
}

const clang::TokenKind clang::Token::kind() {
  return (TokenKind) clang_getTokenKind(cx_token);
}

bool clang::Token::has_type() {
  return !clang_Cursor_isNull(clang_getCursorReferenced(cx_cursor));
}

std::string clang::Token::get_type() {
  std::string spelling;
  auto referenced=clang_getCursorReferenced(cx_cursor);
  if(!clang_Cursor_isNull(referenced)) {
    auto type=clang_getCursorType(referenced);
    auto cxstr=clang_getTypeSpelling(type);
    spelling=clang_getCString(cxstr);
    clang_disposeString(cxstr);
    std::string auto_end="";
    //TODO fix const auto
    if((spelling.size()>=4 && spelling.substr(0, 4)=="auto")) {
      auto_end=spelling.substr(4);
      auto type=clang_getCanonicalType(clang_getCursorType(cx_cursor));
      auto cxstr=clang_getTypeSpelling(type);
      spelling=clang_getCString(cxstr);
      clang_disposeString(cxstr);
      if(spelling.find(" ")==std::string::npos)
        spelling+=auto_end;
    }
  }
  return spelling;
}

std::string clang::Token::get_brief_comments() {
  std::string comment_string;
  auto referenced=clang_getCursorReferenced(cx_cursor);
  auto comment=clang_Cursor_getParsedComment(referenced);
  if(clang_Comment_getKind(comment)==CXComment_FullComment) {
    size_t para_c=0;
    for(unsigned c=0;c<clang_Comment_getNumChildren(comment);c++) {
      auto child_comment=clang_Comment_getChild(comment, c);
      if(clang_Comment_getKind(child_comment)==CXComment_Paragraph) {
        para_c++;
        if(para_c>=2)
          break;
        for(unsigned c=0;c<clang_Comment_getNumChildren(child_comment);c++) {
          auto grandchild_comment=clang_Comment_getChild(child_comment, c);
          if(clang_Comment_getKind(grandchild_comment)==CXComment_Text) {
            auto cxstr=clang_TextComment_getText(grandchild_comment);
            comment_string+=clang_getCString(cxstr);
            comment_string+="\n";
            clang_disposeString(cxstr);
            size_t dot_position=comment_string.find(".");
            if(dot_position!=std::string::npos)
              return comment_string.substr(0, dot_position);
          }
          if(clang_Comment_getKind(grandchild_comment)==CXComment_InlineCommand) {
            auto cxstr=clang_InlineCommandComment_getCommandName(grandchild_comment);
            if(comment_string.size()>0)
              comment_string.pop_back();
            if(clang_InlineCommandComment_getNumArgs(grandchild_comment)==0)
              comment_string+=clang_getCString(cxstr);
            clang_disposeString(cxstr);
            for(unsigned arg_c=0;arg_c<clang_InlineCommandComment_getNumArgs(grandchild_comment);arg_c++) {
              auto cxstr=clang_InlineCommandComment_getArgText(grandchild_comment, arg_c);
              if(cxstr.data!=NULL) {
                if(arg_c>0)
                  comment_string+=" ";
                comment_string+=clang_getCString(cxstr);
                clang_disposeString(cxstr);
              }
            }
          }
        }
      }
      /*cout << "  " << clang_Comment_getKind(child_comment) << ", children: " << clang_Comment_getNumChildren(child_comment) << endl;
      auto cxstr=clang_FullComment_getAsHTML(child_comment);
      cout << "  " << clang_getCString(cxstr) << endl;
      clang_disposeString(cxstr);*/
    }
    while(comment_string.size()>0 && (comment_string.back()=='\n' || comment_string.back()==' '))
      comment_string.pop_back();
  }

  return comment_string;
}
<commit_msg>fixed has_type().<commit_after>#include "Token.h"

// // // // //
//  Token   //
// // // // //

// returns gets an source location for this token objekt
// based on the translationunit given
clang::SourceLocation clang::Token::get_source_location() {
  return SourceLocation(clang_getTokenLocation(cx_tu, cx_token));
}

// returns a sourcerange that covers this token
clang::SourceRange clang::Token::get_source_range() {
  return SourceRange(clang_getTokenExtent(cx_tu, cx_token));
}
// returns a string description of this tokens kind
std::string clang::Token::get_token_spelling() {
  CXString s = clang_getTokenSpelling(cx_tu, cx_token);
  return std::string(clang_getCString(s));
}

const clang::TokenKind clang::Token::kind() {
  return (TokenKind) clang_getTokenKind(cx_token);
}

bool clang::Token::has_type() {
  auto referenced=clang_getCursorReferenced(cx_cursor);
  if(clang_Cursor_isNull(referenced))
    return false;
  auto type=clang_getCursorType(referenced);
  auto cxstr=clang_getTypeSpelling(type);
  std::string spelling=clang_getCString(cxstr);
  clang_disposeString(cxstr);
  return spelling!="";
}

std::string clang::Token::get_type() {
  std::string spelling;
  auto referenced=clang_getCursorReferenced(cx_cursor);
  if(!clang_Cursor_isNull(referenced)) {
    auto type=clang_getCursorType(referenced);
    auto cxstr=clang_getTypeSpelling(type);
    spelling=clang_getCString(cxstr);
    clang_disposeString(cxstr);
    std::string auto_end="";
    //TODO fix const auto
    if((spelling.size()>=4 && spelling.substr(0, 4)=="auto")) {
      auto_end=spelling.substr(4);
      auto type=clang_getCanonicalType(clang_getCursorType(cx_cursor));
      auto cxstr=clang_getTypeSpelling(type);
      spelling=clang_getCString(cxstr);
      clang_disposeString(cxstr);
      if(spelling.find(" ")==std::string::npos)
        spelling+=auto_end;
    }
  }
  return spelling;
}

std::string clang::Token::get_brief_comments() {
  std::string comment_string;
  auto referenced=clang_getCursorReferenced(cx_cursor);
  auto comment=clang_Cursor_getParsedComment(referenced);
  if(clang_Comment_getKind(comment)==CXComment_FullComment) {
    size_t para_c=0;
    for(unsigned c=0;c<clang_Comment_getNumChildren(comment);c++) {
      auto child_comment=clang_Comment_getChild(comment, c);
      if(clang_Comment_getKind(child_comment)==CXComment_Paragraph) {
        para_c++;
        if(para_c>=2)
          break;
        for(unsigned c=0;c<clang_Comment_getNumChildren(child_comment);c++) {
          auto grandchild_comment=clang_Comment_getChild(child_comment, c);
          if(clang_Comment_getKind(grandchild_comment)==CXComment_Text) {
            auto cxstr=clang_TextComment_getText(grandchild_comment);
            comment_string+=clang_getCString(cxstr);
            comment_string+="\n";
            clang_disposeString(cxstr);
            size_t dot_position=comment_string.find(".");
            if(dot_position!=std::string::npos)
              return comment_string.substr(0, dot_position);
          }
          if(clang_Comment_getKind(grandchild_comment)==CXComment_InlineCommand) {
            auto cxstr=clang_InlineCommandComment_getCommandName(grandchild_comment);
            if(comment_string.size()>0)
              comment_string.pop_back();
            if(clang_InlineCommandComment_getNumArgs(grandchild_comment)==0)
              comment_string+=clang_getCString(cxstr);
            clang_disposeString(cxstr);
            for(unsigned arg_c=0;arg_c<clang_InlineCommandComment_getNumArgs(grandchild_comment);arg_c++) {
              auto cxstr=clang_InlineCommandComment_getArgText(grandchild_comment, arg_c);
              if(cxstr.data!=NULL) {
                if(arg_c>0)
                  comment_string+=" ";
                comment_string+=clang_getCString(cxstr);
                clang_disposeString(cxstr);
              }
            }
          }
        }
      }
      /*cout << "  " << clang_Comment_getKind(child_comment) << ", children: " << clang_Comment_getNumChildren(child_comment) << endl;
      auto cxstr=clang_FullComment_getAsHTML(child_comment);
      cout << "  " << clang_getCString(cxstr) << endl;
      clang_disposeString(cxstr);*/
    }
    while(comment_string.size()>0 && (comment_string.back()=='\n' || comment_string.back()==' '))
      comment_string.pop_back();
  }

  return comment_string;
}
<|endoftext|>