<commit_before>/* This is both a sort of unit test, and a demonstration of how to use deadlock
 * prevention.
 *
 * Suggested compilation command:
 *   c++ -Wall -pedantic -std=c++11 test.cpp -o test -lpthread
 */

#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <stdarg.h>
#include <pthread.h>

#include "locking-container.hpp"

//use this definition if you want the simple test
#define THREAD_TYPE thread_multi
//use this definition if you want the multi-lock test
//#define THREAD_TYPE thread_multi

//(probably better as arguments, but I'm too lazy right now)
#define THREADS 10
#define TIME    30
//(if you set either of these to 'false', the threads will gradually die off)
#define READ_BLOCK  true
#define WRITE_BLOCK true

//the data being protected (initialize the 'int' to 'THREADS')
typedef locking_container <int> protected_int;
static protected_int my_data(THREADS);

//(used by 'thread_multi')
static protected_int  my_data2;
static null_container multi_lock;

static void send_output(const char *format, ...);

static void *thread(void *nv);
static void *thread_multi(void *nv);

int main()
{
  //create some threads
  pthread_t threads[THREADS];
  for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
    send_output("start %li\n", i);
    threads[i] = pthread_t();
    if (pthread_create(threads + i, NULL, &THREAD_TYPE, (void*) i) != 0) {
      send_output("error: %s\n", strerror(errno));
    }
  }

  //wait for them to do some stuff
  sleep(TIME);

  //the threads exit when the value goes below 0
  {
    protected_int::proxy write = my_data.get();
    //(no clean way to exit if the container can't be locked)
    assert(write);
    *write = -1;
  } //<-- proxy goes out of scope and unlocks 'my_data' here (you can also 'write.clear()')

  sleep(3);

  for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
    send_output("?join %li\n", i);
    pthread_join(threads[i], NULL);
    send_output("+join %li\n", i);
  }
}

//a print function that ensures we have exclusive access to the output
static void send_output(const char *format, ...) {
  //protect the output file while we're at it
  typedef locking_container <FILE*, w_lock> protected_out;
  //(this is local so that it can't be involved in a deadlock)
  static protected_out stdout2(stdout);

  va_list ap;
  va_start(ap, format);

  //NOTE: authorization isn't important here because it's not possible for the
  //caller to lock another container while it holds a lock on 'stdout2';
  //deadlocks aren't an issue with respect to 'stdout2'
  protected_out::proxy write = stdout2.get();
  if (!write) return;
  vfprintf(*write, format, ap);
}

//a simple thread for repeatedly accessing the data
static void *thread(void *nv) {
  //(cancelation can be messy...)
  if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;

  //get an authorization object, to prevent deadlocks
  //NOTE: for the most part you should be able to use any authorization type
  //with any lock type, but the behavior will be the stricter of the two
  lock_auth_base::auth_type auth(protected_int::new_auth());

  long n = (long) nv, counter = 0;
  struct timespec wait = { 0, (10 + n) * 10 * 1000 * 1000 };
  nanosleep(&wait, NULL);

  //loop through reading and writing forever

  while (true) {
    //read a bunch of times

    for (int i = 0; i < THREADS + n; i++) {
      send_output("?read %li\n", n);
      protected_int::const_proxy read = my_data.get_auth_const(auth, READ_BLOCK);
      if (!read) {
        send_output("!read %li\n", n);
        return NULL;
      }

      send_output("+read %li (%i) -> %i\n", n, read.last_lock_count(), *read);
      send_output("@read %li %i\n", n, !!my_data.get_auth_const(auth, READ_BLOCK));
      if (*read < 0) {
        send_output("counter %li %i\n", n, counter);
        return NULL;
      }
      //(sort of like a contest, to see how many times each thread reads its own number)
      if (*read == n) ++counter;
      nanosleep(&wait, NULL);

      read.clear();
      send_output("-read %li\n", n);
      nanosleep(&wait, NULL);
    }

    //write once

    send_output("?write %li\n", n);
    protected_int::proxy write = my_data.get_auth(auth, WRITE_BLOCK);
    if (!write) {
      send_output("!write %li\n", n);
      return NULL;
    }

    send_output("+write %li (%i)\n", n, write.last_lock_count());
    send_output("@write %li %i\n", n, !!my_data.get_auth(auth, WRITE_BLOCK));
    if (*write < 0) {
      send_output("counter %li %i\n", n, counter);
      return NULL;
    }
    *write = n;
    nanosleep(&wait, NULL);

    write.clear();
    send_output("-write %li\n", n);
    nanosleep(&wait, NULL);
  }
}

//a more complicated thread that requires deadlock prevention, but multiple write locks at once
static void *thread_multi(void *nv) {
  if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;

  //NOTE: multi-locking will work with either 'lock_auth <w_lock>' or
  //'lock_auth <rw_lock>'; however, 'lock_auth <w_lock>' will prevent a thread
  //from holding mutiple read locks at a time when that thread doesn't hold the
  //multi-lock.
  protected_int::auth_type auth(new lock_auth <rw_lock>);

  long n = (long) nv, success = 0, failure = 0;
  struct timespec wait = { 0, (10 + n) * 1 * 1000 * 1000 };
  nanosleep(&wait, NULL);

  while (true) {
    for (int i = 0; i < THREADS + n; i++) {
      send_output("?read0 %li\n", n);
      protected_int::const_proxy read0 = my_data.get_multi_const(multi_lock, auth);
      if (!read0) {
        send_output("!read0 %li\n", n);
        return NULL;
      }

      send_output("+read0 %li (%i) -> %i\n", n, read0.last_lock_count(), *read0);
      if (*read0 < 0) {
        send_output("diff %li %i %i\n", n, success, -failure);
        return NULL;
      }
      nanosleep(&wait, NULL);

      //NOTE: if the auth. type is 'lock_auth <w_lock>', this second read lock
      //will always fail because 'multi_lock' is already in use! (this is because
      //'lock_auth <w_lock>' records the lock above as a write lock; when an
      //auth. object holds a write lock, it can only obtain new read or write
      //locks if the container to be locked has no other locks.)

      send_output("?read1 %li\n", n);
      protected_int::const_proxy read1 = my_data2.get_multi_const(multi_lock, auth);
      if (!read1) {
        //(track the number of successes vs. failures for 'read1')
        ++failure;
        send_output("!read1 %li\n", n);
        //NOTE: due to deadlock prevention, 'auth' will reject a lock if another
        //thread is waiting for a write lock for 'multi_lock' because this
        //thread already holds a read lock (on 'my_data'). (this could easily
        //lead to a deadlock if 'get_multi_const' above blocked.) this isn't a
        //catastrophic error, so we just skip the operation here.
      } else {
        ++success;
        send_output("+read1 %li (%i) -> %i\n", n, read1.last_lock_count(), *read1);
        if (*read1 < 0) {
          send_output("diff %li %i %i\n", n, success, -failure);
          return NULL;
        }
        nanosleep(&wait, NULL);

        read1.clear();
        send_output("-read1 %li\n", n);
      }

      read0.clear();
      send_output("-read0 %li\n", n);
      nanosleep(&wait, NULL);

      send_output("?write %li\n", n);
      protected_int::proxy write = my_data.get_multi(multi_lock, auth);
      if (!write) {
        send_output("!write %li\n", n);
        //(this thread has no locks at this point, so 'get_multi' above should
        //simply block if another thread is waiting for (or has) a write lock on
        //'multi_lock'. a NULL return is therefore an error.)
        return NULL;
      }

      send_output("+write %li (%i)\n", n, write.last_lock_count());
      if (*write < 0) {
        send_output("diff %li %i %i\n", n, success, -failure);
        return NULL;
      }
      *write = n;
      nanosleep(&wait, NULL);

      write.clear();
      send_output("-write %li\n", n);
      nanosleep(&wait, NULL);
    }

    //get a write lock on 'multi_lock'. this blocks until all other locks have
    //been released (provided they were obtained with 'get_multi' or
    //'get_multi_const' using 'multi_lock). this is mostly a way to appease
    //'auth', because it's preventing deadlocks.

    //NOTE: the lock will be rejected without blocking if this thread holds a
    //lock on another object, because a deadlock could otherwise happen!

    send_output("?multi0 %li\n", n);
    null_container::proxy multi = multi_lock.get_auth(auth);
    if (!multi) {
      send_output("!multi0 %li\n", n);
      return NULL;
    }
    send_output("+multi0 %li\n", n);

    //NOTE: even though this thread holds a write lock on 'multi_lock', it will
    //still allow new read locks from this thread. this is why 'get_multi' can
    //be used below.

    //NOTE: even if the auth. type is 'lock_auth <w_lock>', this thread should
    //be able to obtain multiple write locks, since the containers aren't being
    //used by any other threads.

    send_output("?multi1 %li\n", n);
    protected_int::proxy write1 = my_data.get_multi(multi_lock, auth);
    if (!write1) {
      send_output("!multi1 %li\n", n);
      return NULL;
    }
    send_output("+multi1 %li\n", n);
    if (*write1 < 0) return NULL;

    //NOTE: this second write lock is only possible because this thread's write
    //lock on 'multi_lock' ensures that nothing else currently holds a lock on
    //'my_data2'. in fact, that's the only purpose of using 'multi_lock'!

    send_output("?multi2 %li\n", n);
    protected_int::proxy write2 = my_data2.get_multi(multi_lock, auth);
    if (!write2) {
      send_output("!multi2 %li\n", n);
      return NULL;
    }
    send_output("+multi2 %li\n", n);

    //NOTE: since 'get_multi' keeps track of new locks on 'my_data' and
    //'my_data2', the write lock on 'multi_lock' can be cleared. this allows
    //other threads to access those objects as they become free again.

    multi.clear();
    send_output("-multi0 %li\n", n);

    *write1 = *write2 = 100 + n;

    nanosleep(&wait, NULL);
    write2.clear();
    send_output("-multi2 %li\n", n);
    write1.clear();
    send_output("-multi1 %li\n", n);
  }
}
<commit_msg>removed forgotten testing code<commit_after>/* This is both a sort of unit test, and a demonstration of how to use deadlock
 * prevention.
 *
 * Suggested compilation command:
 *   c++ -Wall -pedantic -std=c++11 test.cpp -o test -lpthread
 */

#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <stdarg.h>
#include <pthread.h>

#include "locking-container.hpp"

//use this definition if you want the simple test
#define THREAD_TYPE thread
//use this definition if you want the multi-lock test
//#define THREAD_TYPE thread_multi

//(probably better as arguments, but I'm too lazy right now)
#define THREADS 10
#define TIME    30
//(if you set either of these to 'false', the threads will gradually die off)
#define READ_BLOCK  true
#define WRITE_BLOCK true

//the data being protected (initialize the 'int' to 'THREADS')
typedef locking_container <int> protected_int;
static protected_int my_data(THREADS);

//(used by 'thread_multi')
static protected_int  my_data2;
static null_container multi_lock;

static void send_output(const char *format, ...);

static void *thread(void *nv);
static void *thread_multi(void *nv);

int main()
{
  //create some threads
  pthread_t threads[THREADS];
  for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
    send_output("start %li\n", i);
    threads[i] = pthread_t();
    if (pthread_create(threads + i, NULL, &THREAD_TYPE, (void*) i) != 0) {
      send_output("error: %s\n", strerror(errno));
    }
  }

  //wait for them to do some stuff
  sleep(TIME);

  //the threads exit when the value goes below 0
  {
    protected_int::proxy write = my_data.get();
    //(no clean way to exit if the container can't be locked)
    assert(write);
    *write = -1;
  } //<-- proxy goes out of scope and unlocks 'my_data' here (you can also 'write.clear()')

  sleep(3);

  for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
    send_output("?join %li\n", i);
    pthread_join(threads[i], NULL);
    send_output("+join %li\n", i);
  }
}

//a print function that ensures we have exclusive access to the output
static void send_output(const char *format, ...) {
  //protect the output file while we're at it
  typedef locking_container <FILE*, w_lock> protected_out;
  //(this is local so that it can't be involved in a deadlock)
  static protected_out stdout2(stdout);

  va_list ap;
  va_start(ap, format);

  //NOTE: authorization isn't important here because it's not possible for the
  //caller to lock another container while it holds a lock on 'stdout2';
  //deadlocks aren't an issue with respect to 'stdout2'
  protected_out::proxy write = stdout2.get();
  if (!write) return;
  vfprintf(*write, format, ap);
}

//a simple thread for repeatedly accessing the data
static void *thread(void *nv) {
  //(cancelation can be messy...)
  if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;

  //get an authorization object, to prevent deadlocks
  //NOTE: for the most part you should be able to use any authorization type
  //with any lock type, but the behavior will be the stricter of the two
  lock_auth_base::auth_type auth(protected_int::new_auth());

  long n = (long) nv, counter = 0;
  struct timespec wait = { 0, (10 + n) * 10 * 1000 * 1000 };
  nanosleep(&wait, NULL);

  //loop through reading and writing forever

  while (true) {
    //read a bunch of times

    for (int i = 0; i < THREADS + n; i++) {
      send_output("?read %li\n", n);
      protected_int::const_proxy read = my_data.get_auth_const(auth, READ_BLOCK);
      if (!read) {
        send_output("!read %li\n", n);
        return NULL;
      }

      send_output("+read %li (%i) -> %i\n", n, read.last_lock_count(), *read);
      send_output("@read %li %i\n", n, !!my_data.get_auth_const(auth, READ_BLOCK));
      if (*read < 0) {
        send_output("counter %li %i\n", n, counter);
        return NULL;
      }
      //(sort of like a contest, to see how many times each thread reads its own number)
      if (*read == n) ++counter;
      nanosleep(&wait, NULL);

      read.clear();
      send_output("-read %li\n", n);
      nanosleep(&wait, NULL);
    }

    //write once

    send_output("?write %li\n", n);
    protected_int::proxy write = my_data.get_auth(auth, WRITE_BLOCK);
    if (!write) {
      send_output("!write %li\n", n);
      return NULL;
    }

    send_output("+write %li (%i)\n", n, write.last_lock_count());
    send_output("@write %li %i\n", n, !!my_data.get_auth(auth, WRITE_BLOCK));
    if (*write < 0) {
      send_output("counter %li %i\n", n, counter);
      return NULL;
    }
    *write = n;
    nanosleep(&wait, NULL);

    write.clear();
    send_output("-write %li\n", n);
    nanosleep(&wait, NULL);
  }
}

//a more complicated thread that requires deadlock prevention, but multiple write locks at once
static void *thread_multi(void *nv) {
  if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;

  //NOTE: multi-locking will work with either 'lock_auth <w_lock>' or
  //'lock_auth <rw_lock>'; however, 'lock_auth <w_lock>' will prevent a thread
  //from holding mutiple read locks at a time when that thread doesn't hold the
  //multi-lock.
  protected_int::auth_type auth(new lock_auth <rw_lock>);

  long n = (long) nv, success = 0, failure = 0;
  struct timespec wait = { 0, (10 + n) * 1 * 1000 * 1000 };
  nanosleep(&wait, NULL);

  while (true) {
    for (int i = 0; i < THREADS + n; i++) {
      send_output("?read0 %li\n", n);
      protected_int::const_proxy read0 = my_data.get_multi_const(multi_lock, auth);
      if (!read0) {
        send_output("!read0 %li\n", n);
        return NULL;
      }

      send_output("+read0 %li (%i) -> %i\n", n, read0.last_lock_count(), *read0);
      if (*read0 < 0) {
        send_output("diff %li %i %i\n", n, success, -failure);
        return NULL;
      }
      nanosleep(&wait, NULL);

      //NOTE: if the auth. type is 'lock_auth <w_lock>', this second read lock
      //will always fail because 'multi_lock' is already in use! (this is because
      //'lock_auth <w_lock>' records the lock above as a write lock; when an
      //auth. object holds a write lock, it can only obtain new read or write
      //locks if the container to be locked has no other locks.)

      send_output("?read1 %li\n", n);
      protected_int::const_proxy read1 = my_data2.get_multi_const(multi_lock, auth);
      if (!read1) {
        //(track the number of successes vs. failures for 'read1')
        ++failure;
        send_output("!read1 %li\n", n);
        //NOTE: due to deadlock prevention, 'auth' will reject a lock if another
        //thread is waiting for a write lock for 'multi_lock' because this
        //thread already holds a read lock (on 'my_data'). (this could easily
        //lead to a deadlock if 'get_multi_const' above blocked.) this isn't a
        //catastrophic error, so we just skip the operation here.
      } else {
        ++success;
        send_output("+read1 %li (%i) -> %i\n", n, read1.last_lock_count(), *read1);
        if (*read1 < 0) {
          send_output("diff %li %i %i\n", n, success, -failure);
          return NULL;
        }
        nanosleep(&wait, NULL);

        read1.clear();
        send_output("-read1 %li\n", n);
      }

      read0.clear();
      send_output("-read0 %li\n", n);
      nanosleep(&wait, NULL);

      send_output("?write %li\n", n);
      protected_int::proxy write = my_data.get_multi(multi_lock, auth);
      if (!write) {
        send_output("!write %li\n", n);
        //(this thread has no locks at this point, so 'get_multi' above should
        //simply block if another thread is waiting for (or has) a write lock on
        //'multi_lock'. a NULL return is therefore an error.)
        return NULL;
      }

      send_output("+write %li (%i)\n", n, write.last_lock_count());
      if (*write < 0) {
        send_output("diff %li %i %i\n", n, success, -failure);
        return NULL;
      }
      *write = n;
      nanosleep(&wait, NULL);

      write.clear();
      send_output("-write %li\n", n);
      nanosleep(&wait, NULL);
    }

    //get a write lock on 'multi_lock'. this blocks until all other locks have
    //been released (provided they were obtained with 'get_multi' or
    //'get_multi_const' using 'multi_lock). this is mostly a way to appease
    //'auth', because it's preventing deadlocks.

    //NOTE: the lock will be rejected without blocking if this thread holds a
    //lock on another object, because a deadlock could otherwise happen!

    send_output("?multi0 %li\n", n);
    null_container::proxy multi = multi_lock.get_auth(auth);
    if (!multi) {
      send_output("!multi0 %li\n", n);
      return NULL;
    }
    send_output("+multi0 %li\n", n);

    //NOTE: even though this thread holds a write lock on 'multi_lock', it will
    //still allow new read locks from this thread. this is why 'get_multi' can
    //be used below.

    //NOTE: even if the auth. type is 'lock_auth <w_lock>', this thread should
    //be able to obtain multiple write locks, since the containers aren't being
    //used by any other threads.

    send_output("?multi1 %li\n", n);
    protected_int::proxy write1 = my_data.get_multi(multi_lock, auth);
    if (!write1) {
      send_output("!multi1 %li\n", n);
      return NULL;
    }
    send_output("+multi1 %li\n", n);
    if (*write1 < 0) return NULL;

    //NOTE: this second write lock is only possible because this thread's write
    //lock on 'multi_lock' ensures that nothing else currently holds a lock on
    //'my_data2'. in fact, that's the only purpose of using 'multi_lock'!

    send_output("?multi2 %li\n", n);
    protected_int::proxy write2 = my_data2.get_multi(multi_lock, auth);
    if (!write2) {
      send_output("!multi2 %li\n", n);
      return NULL;
    }
    send_output("+multi2 %li\n", n);

    //NOTE: since 'get_multi' keeps track of new locks on 'my_data' and
    //'my_data2', the write lock on 'multi_lock' can be cleared. this allows
    //other threads to access those objects as they become free again.

    multi.clear();
    send_output("-multi0 %li\n", n);

    *write1 = *write2 = 100 + n;

    nanosleep(&wait, NULL);
    write2.clear();
    send_output("-multi2 %li\n", n);
    write1.clear();
    send_output("-multi1 %li\n", n);
  }
}
<|endoftext|>


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

#ifndef ADC_CPP_CTX2ARY_HXX
#define ADC_CPP_CTX2ARY_HXX

// USED SERVICES
    // BASE CLASSES
#include <ary/cpp/inpcontx.hxx>
#include <doc_deal.hxx>
#include "pev.hxx"
#include "fevnthdl.hxx"
    // COMPONENTS
    // PARAMETERS

namespace ary
{
namespace loc
{
    class File;
}
}

namespace cpp
{

/** @descr
    This class provides information about the context of an
    CodeEntity, which is going to be stored in the repository.
    The information is used mainly by class ary::cpp::Gate.

    Also it provides information for the parser about actual
    state of several public variables.

    @todo
    Include events, which allow correct storing of inline
    documentation after enum values, parameters,
    base classes.
*/
class ContextForAry : public ary::cpp::InputContext,
                      public cpp::PeEnvironment,
                      public cpp::FileScope_EventHandler,
                      public DocuDealer
{
  public:
    // LIFECYCLE
                        ContextForAry(
                            ary::cpp::Gate &  io_rAryGate );
    virtual             ~ContextForAry();

    // OPERATIONS
    void                ResetResult()           { aTokenResult.Reset(); }

    // INQUIRY
    const TokenProcessing_Result &
                        CurResult() const       { return aTokenResult; }
    // ACCESS
    TokenProcessing_Result &
                        CurResult()             { return aTokenResult; }

  private:
    // Interface ary::cpp::InputContext:
    virtual ary::loc::File &
                        inq_CurFile() const;
    virtual ary::cpp::Namespace &
                        inq_CurNamespace() const;
    virtual ary::cpp::Class *
                        inq_CurClass() const;
    virtual ary::cpp::Enum *
                        inq_CurEnum() const;

    virtual Owner &     inq_CurOwner() const;
    virtual ary::cpp::E_Protection
                        inq_CurProtection() const;

    // Interface PeEnvironment
    virtual void        do_SetTokenResult(
                            E_TokenDone         i_eDone,
                            E_EnvStackAction    i_eWhat2DoWithEnvStack,
                            ParseEnvironment *  i_pParseEnv2Push );
    virtual void        do_OpenNamespace(
                            ary::cpp::Namespace &
                                                io_rOpenedNamespace );
    virtual void        do_OpenExternC(
                            bool                i_bOnlyForOneDeclaration );
    virtual void        do_OpenClass(
                            ary::cpp::Class &   io_rOpenedClass );
    virtual void        do_OpenEnum(
                            ary::cpp::Enum &    io_rOpenedEnum );
    virtual void        do_CloseBlock();
    virtual void        do_CloseClass();
    virtual void        do_CloseEnum();
    virtual void        do_SetCurProtection(
                            ary::cpp::E_Protection
                                                i_eProtection );
    virtual void        do_OpenTemplate(
                            const StringVector &
                                                i_rParameters );
    virtual DYN StringVector *
                        do_Get_CurTemplateParameters();
    virtual void        do_Close_OpenTemplate();
    virtual void        do_Event_Class_FinishedBase(
                            const String  &     i_sBaseName );

    virtual void        do_Event_Store_Typedef(
                            ary::cpp::Typedef & io_rTypedef );
    virtual void        do_Event_Store_EnumValue(
                            ary::cpp::EnumValue &
                                                io_rEnumValue );
    virtual void        do_Event_Store_CppDefinition(
                            ary::cpp::DefineEntity &
                                                io_rDefinition );
    virtual void        do_Event_EnterFunction_ParameterList();
    virtual void        do_Event_Function_FinishedParameter(
                            const String  &     i_sParameterName );
    virtual void        do_Event_LeaveFunction_ParameterList();
    virtual void        do_Event_EnterFunction_Implementation();
    virtual void        do_Event_LeaveFunction_Implementation();
    virtual void        do_Event_Store_Function(
                            ary::cpp::Function &
                                                io_rFunction );
    virtual void        do_Event_Store_Variable(
                            ary::cpp::Variable &
                                                io_rVariable );
    virtual void        do_TakeDocu(
                            DYN ary::doc::OldCppDocu &
                                                let_drInfo );
    virtual void        do_StartWaitingFor_Recovery();
    virtual ary::cpp::Gate &
                        inq_AryGate() const;
    virtual const ary::cpp::InputContext &
                        inq_Context() const;
    virtual String      inq_CurFileName() const;
    virtual uintt       inq_LineCount() const;
    virtual bool        inq_IsWaitingFor_Recovery() const;
    virtual bool        inq_IsExternC() const;

    // Interface FileScope_EventHandler
    virtual void        do_SetCurFile(
                            ary::loc::File &    io_rCurFile );
    virtual void        do_Event_IncrLineCount();
    virtual void        do_Event_SwBracketOpen();
    virtual void        do_Event_SwBracketClose();
    virtual void        do_Event_Semicolon();

    // Local types
    struct S_FileScopeInfo;
    struct S_OwnerStack;
    struct S_DocuDistributor;
    struct S_RecoveryGuard;

    // DATA
    ary::cpp::Gate *    pGate;
    TokenProcessing_Result
                        aTokenResult;
    Dyn<S_FileScopeInfo>
                        pFileScopeInfo;
    Dyn<S_OwnerStack>   pOwnerStack;
    Dyn<S_DocuDistributor>
                        pDocuDistributor;
    Dyn<S_RecoveryGuard>
                        pRecoveryGuard;
};

}   // namespace cpp
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.22); FILE MERGED 2008/03/28 16:02:23 rt 1.4.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: cxt2ary.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef ADC_CPP_CTX2ARY_HXX
#define ADC_CPP_CTX2ARY_HXX

// USED SERVICES
    // BASE CLASSES
#include <ary/cpp/inpcontx.hxx>
#include <doc_deal.hxx>
#include "pev.hxx"
#include "fevnthdl.hxx"
    // COMPONENTS
    // PARAMETERS

namespace ary
{
namespace loc
{
    class File;
}
}

namespace cpp
{

/** @descr
    This class provides information about the context of an
    CodeEntity, which is going to be stored in the repository.
    The information is used mainly by class ary::cpp::Gate.

    Also it provides information for the parser about actual
    state of several public variables.

    @todo
    Include events, which allow correct storing of inline
    documentation after enum values, parameters,
    base classes.
*/
class ContextForAry : public ary::cpp::InputContext,
                      public cpp::PeEnvironment,
                      public cpp::FileScope_EventHandler,
                      public DocuDealer
{
  public:
    // LIFECYCLE
                        ContextForAry(
                            ary::cpp::Gate &  io_rAryGate );
    virtual             ~ContextForAry();

    // OPERATIONS
    void                ResetResult()           { aTokenResult.Reset(); }

    // INQUIRY
    const TokenProcessing_Result &
                        CurResult() const       { return aTokenResult; }
    // ACCESS
    TokenProcessing_Result &
                        CurResult()             { return aTokenResult; }

  private:
    // Interface ary::cpp::InputContext:
    virtual ary::loc::File &
                        inq_CurFile() const;
    virtual ary::cpp::Namespace &
                        inq_CurNamespace() const;
    virtual ary::cpp::Class *
                        inq_CurClass() const;
    virtual ary::cpp::Enum *
                        inq_CurEnum() const;

    virtual Owner &     inq_CurOwner() const;
    virtual ary::cpp::E_Protection
                        inq_CurProtection() const;

    // Interface PeEnvironment
    virtual void        do_SetTokenResult(
                            E_TokenDone         i_eDone,
                            E_EnvStackAction    i_eWhat2DoWithEnvStack,
                            ParseEnvironment *  i_pParseEnv2Push );
    virtual void        do_OpenNamespace(
                            ary::cpp::Namespace &
                                                io_rOpenedNamespace );
    virtual void        do_OpenExternC(
                            bool                i_bOnlyForOneDeclaration );
    virtual void        do_OpenClass(
                            ary::cpp::Class &   io_rOpenedClass );
    virtual void        do_OpenEnum(
                            ary::cpp::Enum &    io_rOpenedEnum );
    virtual void        do_CloseBlock();
    virtual void        do_CloseClass();
    virtual void        do_CloseEnum();
    virtual void        do_SetCurProtection(
                            ary::cpp::E_Protection
                                                i_eProtection );
    virtual void        do_OpenTemplate(
                            const StringVector &
                                                i_rParameters );
    virtual DYN StringVector *
                        do_Get_CurTemplateParameters();
    virtual void        do_Close_OpenTemplate();
    virtual void        do_Event_Class_FinishedBase(
                            const String  &     i_sBaseName );

    virtual void        do_Event_Store_Typedef(
                            ary::cpp::Typedef & io_rTypedef );
    virtual void        do_Event_Store_EnumValue(
                            ary::cpp::EnumValue &
                                                io_rEnumValue );
    virtual void        do_Event_Store_CppDefinition(
                            ary::cpp::DefineEntity &
                                                io_rDefinition );
    virtual void        do_Event_EnterFunction_ParameterList();
    virtual void        do_Event_Function_FinishedParameter(
                            const String  &     i_sParameterName );
    virtual void        do_Event_LeaveFunction_ParameterList();
    virtual void        do_Event_EnterFunction_Implementation();
    virtual void        do_Event_LeaveFunction_Implementation();
    virtual void        do_Event_Store_Function(
                            ary::cpp::Function &
                                                io_rFunction );
    virtual void        do_Event_Store_Variable(
                            ary::cpp::Variable &
                                                io_rVariable );
    virtual void        do_TakeDocu(
                            DYN ary::doc::OldCppDocu &
                                                let_drInfo );
    virtual void        do_StartWaitingFor_Recovery();
    virtual ary::cpp::Gate &
                        inq_AryGate() const;
    virtual const ary::cpp::InputContext &
                        inq_Context() const;
    virtual String      inq_CurFileName() const;
    virtual uintt       inq_LineCount() const;
    virtual bool        inq_IsWaitingFor_Recovery() const;
    virtual bool        inq_IsExternC() const;

    // Interface FileScope_EventHandler
    virtual void        do_SetCurFile(
                            ary::loc::File &    io_rCurFile );
    virtual void        do_Event_IncrLineCount();
    virtual void        do_Event_SwBracketOpen();
    virtual void        do_Event_SwBracketClose();
    virtual void        do_Event_Semicolon();

    // Local types
    struct S_FileScopeInfo;
    struct S_OwnerStack;
    struct S_DocuDistributor;
    struct S_RecoveryGuard;

    // DATA
    ary::cpp::Gate *    pGate;
    TokenProcessing_Result
                        aTokenResult;
    Dyn<S_FileScopeInfo>
                        pFileScopeInfo;
    Dyn<S_OwnerStack>   pOwnerStack;
    Dyn<S_DocuDistributor>
                        pDocuDistributor;
    Dyn<S_RecoveryGuard>
                        pRecoveryGuard;
};

}   // namespace cpp
#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <SDL/SDL.h>

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif

extern "C" int main(int argc, char** argv) {
  printf("hello, world!\n");

  SDL_Init(SDL_INIT_VIDEO);
  SDL_Surface *screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);

#ifdef TEST_SDL_LOCK_OPTS
  EM_ASM("SDL.defaults.copyOnLock = false; SDL.defaults.discardOnLock = true; SDL.defaults.opaqueFrontBuffer = false;");
#endif

  if (SDL_MUSTLOCK(screen)) SDL_LockSurface(screen);
  for (int i = 0; i < 256; i++) {
    for (int j = 0; j < 256; j++) {
#ifdef TEST_SDL_LOCK_OPTS
      // Alpha behaves like in the browser, so write proper opaque pixels.
      int alpha = 255;
#else
      // To emulate native behavior with blitting to screen, alpha component is ignored. Test that it is so by outputting
      // data (and testing that it does get discarded)
      int alpha = (i+j) % 255;
#endif
      *((Uint32*)screen->pixels + i * 256 + j) = SDL_MapRGBA(screen->format, i, j, 255-i, alpha);
    }
  }
  if (SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen);
  SDL_Flip(screen);

  printf("you should see a smoothly-colored square - no sharp lines but the square borders!\n");
  printf("and here is some text that should be HTML-friendly: amp: |&| double-quote: |\"| quote: |'| less-than, greater-than, html-like tags: |<cheez></cheez>|\nanother line.\n");

  SDL_Quit();

  return 0;
}

<commit_msg>render test floor<commit_after>#include <stdio.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif

#define TILE_W      64
#define TILE_H      32

void project(float x, float y, float z, int* dx, int *dy) {
    *dx = x * (TILE_W/2) - y * (TILE_W/2);
    *dy = x * (TILE_H/2) + y * (TILE_H/2) - z;
}
extern "C" int main(int argc, char** argv) {

    SDL_Init(SDL_INIT_VIDEO);
    SDL_Surface *screen = SDL_SetVideoMode(1024,768, 32, SDL_SWSURFACE);

    SDL_Surface *image = IMG_Load("./img/floor1.png");
    if (!image)
    {
        printf("IMG_Load: %s\n", IMG_GetError());
        return 0;
    }
    for (int y = 0; y < 20; y++) {
        for (int x = 0; x < 20; x++) {
            SDL_Rect dst;
            dst.w = image->w;
            dst.h = image->h;
            project(x, y, 0, &dst.x, &dst.y);
            dst.x += 512;
            SDL_BlitSurface (image, NULL, screen, &dst);
        }
    }

    SDL_Flip(screen);

    SDL_Quit();

    return 0;
}

<|endoftext|>


<commit_before>/*
 * Some tests of Euler's Totient Function phi.
 *
 * Copyright (c) 2012 Christian Stigen Larsen
 * http://csl.sublevel3.org
 *
 * Distributed under the BSD 3-clause license; see the file LICENSE.
 */

#include <iostream>
#include <inttypes.h>
#include <cassert>
#include "phi.h"

using namespace std;

void test1()
{
  int n = phi<100>(12);
  assert(n == 4);
}

void test2()
{
  #define LIMIT1 1000000
  cout << "Calculating " << 10*(LIMIT1) << " prime numbers" << endl;

  for ( uint64_t n=0; n < LIMIT1; n += 56789 ) {
    cout << "phi(" << n << ") = "
         << phi<10*LIMIT1>(n) << endl;
  }

  #define LIMIT2 10000000
  cout << endl;
  cout << "Calculating " << 10*(LIMIT2) << " prime numbers" << endl;

  for ( uint64_t n=1000000; n < LIMIT2; n += 1122334/2 ) {
    cout << "phi(" << n << ") = "
         << phi<10*LIMIT2>(n) << endl;
  }
}

int main()
{
  test1();
  test2();
  return 0;
}
<commit_msg>Faster test<commit_after>/*
 * Some tests of Euler's Totient Function phi.
 *
 * Copyright (c) 2012 Christian Stigen Larsen
 * http://csl.sublevel3.org
 *
 * Distributed under the BSD 3-clause license; see the file LICENSE.
 */

#include <iostream>
#include <inttypes.h>
#include <cassert>
#include "phi.h"

using namespace std;

void test1()
{
  int n = phi<100>(12);
  assert(n == 4);
}

void test2()
{
  #define LIMIT 10000000
  cout << "Calculating " << 10*(LIMIT) << " prime numbers" << endl;

  for ( uint64_t n=0; n < LIMIT/10; n += 56789 ) {
    cout << "phi(" << n << ") = "
         << phi<LIMIT>(n) << endl;
  }

  for ( uint64_t n=1000000; n < LIMIT; n += 1122334/2 ) {
    cout << "phi(" << n << ") = "
         << phi<LIMIT>(n) << endl;
  }
}

int main()
{
  test1();
  test2();
  return 0;
}
<|endoftext|>


<commit_before>/*
 * nnet test
 * 2016.06.06
 * author:soma62jp
 *                  */

#include "test.h"

using namespace std;

nnet::nnet(int inputnum,int hiddennum,int outputnum,int patternnum):
      inputnum(inputnum)
     ,hiddennum(hiddennum)
     ,outputnum(outputnum)
     ,patternnum(patternnum)
     ,Eta(0.75)
     ,Alpha(0.8)
     ,ErrorEv(0.001)
     ,Rlow(-0.30)
     ,Rhigh(0.30)
     ,MaxGen(10000)
{
  //this->inputnum=inputnum;
  //this->hiddennum=hiddennum;
  //this->outputnum=outputnum;

  X_h = new double[hiddennum];
  X_o = new double[outputnum];

  bias_h = new double[hiddennum];
  bias_o = new double[outputnum];
  bias_h_prev = new double[hiddennum];
  bias_o_prev = new double[outputnum];

  // pattern*input
  X_i = new double*[patternnum];
  for(int i=0;i<patternnum;i++){
    X_i[i] = new double[inputnum];
  }

  // pattern*output
  T_signal = new double*[patternnum];
  for(int i=0;i<patternnum;i++){
    T_signal[i] = new double[outputnum];
  }

  // hidden*input
  W_itoh = new double*[hiddennum];
  for(int i=0;i<hiddennum;i++){
    W_itoh[i] = new double[inputnum];
  }
  W_itoh_prev = new double*[hiddennum];
  for(int i=0;i<hiddennum;i++){
    W_itoh_prev[i] = new double[inputnum];
  }

  // output*hidden
  W_htoo = new double*[outputnum];
  for(int i=0;i<outputnum;i++){
    W_htoo[i] = new double[hiddennum];
  }
  W_htoo_prev = new double*[outputnum];
  for(int i=0;i<outputnum;i++){
    W_htoo_prev[i] = new double[hiddennum];
  }

  //initialize parameter
  srand((unsigned int)time(NULL));

  for(int i=0;i<hiddennum;i++){
    for(int j=0;j<inputnum;j++){
      W_itoh[i][j]=urand();
    }
  }

  for(int i=0;i<outputnum;i++){
    for(int j=0;j<hiddennum;j++){
      W_htoo[i][j]=urand();
    }
  }

  for(int i=0;i<hiddennum;i++){
    bias_h[i] = 0;
  }

  for(int i=0;i<outputnum;i++){
    bias_o[i] = 0;
  }

}

nnet::~nnet()
{

  delete [] X_h;
  delete [] X_o;

  delete [] bias_h;
  delete [] bias_o;
  delete [] bias_h_prev;
  delete [] bias_o_prev;

  for( int i=0; i<patternnum; i++ ) {
    delete[] X_i[i];
  }
  delete [] X_i;

  for( int i=0; i<patternnum; i++ ) {
    delete[] T_signal[i];
  }
  delete [] T_signal;

  for( int i=0; i<hiddennum; i++ ) {
    delete[] W_itoh[i];
  }
  delete [] W_itoh;

  for( int i=0; i<hiddennum; i++ ) {
    delete[] W_itoh_prev[i];
  }
  delete [] W_itoh_prev;

  for( int i=0; i<outputnum; i++ ) {
    delete [] W_htoo[i];
  }
  delete [] W_htoo;

  for( int i=0; i<outputnum; i++ ) {
    delete [] W_htoo_prev[i];
  }
  delete [] W_htoo_prev;

}

void nnet::foward_propagation(const int pnum)
{
  int i,j;
  double sum;

  // 入力層ー＞隠れ層
  for(i=0;i<hiddennum;i++){
    sum=0;
    for(j=0;j<inputnum;j++){
      // 重み×入力値
      sum+=W_itoh[i][j]*X_i[pnum][j];
    }
    // 重み×入力値の総和にバイアス項を足してアクティベーション関数に通したものが中間層入力
    X_h[i] = activationFunc(sum+bias_h[i]);
  }

  // 隠れ層ー＞出力層
  for(i=0;i<outputnum;i++){
    sum=0;
    for(j=0;j<hiddennum;j++){
      // 重み×中間層入力
      sum+=W_htoo[i][j]*X_h[j];
    }
    // 重み×中間層入力値の総和にバイアス項を足してアクティベーション関数に通したものが出力層
    X_o[i]=activationFunc(sum+bias_o[i]);
  }

}

void nnet::back_propagation(const int pnum)
{
  int i,j;
  double sum;
  double *dwih = new double[hiddennum];   // 隠れ層での学習信号
  double *dwho = new double[outputnum];   // 出力層での学習信号

  // 出力層の学習信号から計算
  for(i=0;i<outputnum;i++){
    // 出力層での学習信号=(教師信号-出力） * f'(出力)
    // f'(出力)はシグモイド関数の微分
    dwho[i]=(T_signal[pnum][i]-X_o[i]) * activationFunc_diff(X_o[i]);
  }

  // 重みの変化量[隠れ層ー＞出力層]を計算
  // 隠れ層の学習信号を計算
  for(i=0;i<hiddennum;i++){
    sum=0;
    for(j=0;j<outputnum;j++){
      // 前回の重みの変化量[隠れ層->出力層] = η * 出力層での学習信号 * 隠れ層出力 * α * 前回の重みの変化量[隠れ層->出力層]
      W_htoo_prev[j][i]=Eta*dwho[j]*X_h[i]+Alpha*W_htoo_prev[j][i];
      // 重みの変化量[隠れ層ー＞出力層] = 重みの変化量[隠れ層ー＞出力層] + 前回の重みの変化量[隠れ層ー＞出力層]
      W_htoo[j][i]+=W_htoo_prev[j][i];
      // 出力層での学習信号 * 重みの変化量[隠れ層ー＞出力層]
      sum += dwho[j]*W_htoo[j][i];
    }
    // 隠れ層での学習信号 = f'(隠れ層出力) * sum
    dwih[i]=activationFunc_diff(X_h[i])*sum;
  }

  // 出力層のバイアス項を計算
  for(i=0;i<outputnum;i++){
    // 前回のバイアス項[出力層] = η * 出力層での学習信号 + α * 前回のバイアス項[出力層]
    bias_o_prev[i] = Eta*dwho[i]+Alpha*bias_o_prev[i];
    // 出力層バイアス項[出力層] = 出力層バイアス項[出力層] + 前回の出力層バイアス項[出力層]
    bias_o[i]+=bias_o_prev[i];
  }

  // 重みの変化量[入力層ー＞隠れ層]を計算
  for(i=0;i<inputnum;i++){
    for(j=0;j<hiddennum;j++){
      // 前回の重みの変化量[入力層ー＞隠れ層] = η * 隠れ層での学習信号 * 入力層出力 * α * 前回の重みの変化量[入力層ー＞隠れ層]
      W_itoh_prev[j][i]=Eta*dwih[j]*X_i[pnum][i]+Alpha*W_itoh_prev[j][i];
      // 重みの変化量[入力層ー＞隠れ層] = 重みの変化量[入力層ー＞隠れ層] + 前回の重みの変化量[入力層ー＞隠れ層]
      W_itoh[j][i]+=W_itoh_prev[j][i];
    }
  }

  // 隠れ層のバイアス項を計算
  for(i=0;i<hiddennum;i++){
    // 前回のバイアス項[隠れ層] = η * 隠れ層での学習信号 + α * 前回のバイアス項[隠れ層]
    bias_h_prev[i]=Eta*dwih[i]+Alpha*bias_h_prev[i];
    // 出力層バイアス項[隠れ層] = 出力層バイアス項[隠れ層] + 前回の出力層バイアス項[隠れ層]
    bias_h[i]+=bias_h_prev[i];
  }

  delete dwih;
  delete dwho;

}

void  nnet::setInData(const int pnum,const int i,const double value)
{
  if(pnum>=patternnum || i>=inputnum){
    cout << "can't set Indata." << endl;
    exit(1);
  }
  X_i[pnum][i] = value;
}

void nnet::setTeachData(const int pnum,const int i,const double value)
{
  if(pnum>=patternnum || i>=outputnum){
    cout << "can't set Teachdata." << endl;
    exit(1);
  }
  T_signal[pnum][i] = value;
}

void nnet::setPredictData(const int i,const double value)
{
  if(i>=inputnum){
    cout << "can't set Predictdata." << endl;
    exit(1);
  }
  X_i[patternnum-1][i] = value;
}

void nnet::train()
{
  double verror;
  int gen;
  int i,j,ip;

  gen = 0;
  verror = 20.0;
  while((verror > ErrorEv) && (gen < MaxGen))
  {
    gen++;

    // foward and back propagation
    for(i=0;i<patternnum;i++){
      ip = patternnum * random();
      foward_propagation(ip);
      back_propagation(ip);
    }

    // error calc
    verror = 0;
    for(i=0;i<patternnum;i++){
      foward_propagation(i);
      for(j=0;j<outputnum;j++){
          verror+=pow((T_signal[i][j] - X_o[j]) * 0.5 ,2.0);
      }
    }
    verror /= (double)patternnum;

    cout << verror << endl;

  }
}

void nnet::predict()
{
  int i;
  foward_propagation(patternnum-1);
  for(i=0;i<outputnum;i++){
    cout << X_o[i] << endl;
  }
}

double nnet::random()
{
	double r;
	int i;

	i = rand();
	if (i != 0)
		i--;
	r = (double)i / RAND_MAX;
	return (r);
}

int main()
{
  nnet net(2,2,1,4);

  net.setInData(0,0,0);
  net.setInData(0,1,0);
  net.setTeachData(0,0,0);

  net.setInData(1,0,1);
  net.setInData(1,1,1);
  net.setTeachData(1,0,0);

  net.setInData(2,0,1);
  net.setInData(2,1,0);
  net.setTeachData(2,0,1);

  net.setInData(3,0,0);
  net.setInData(3,1,1);
  net.setTeachData(3,0,1);

  net.train();

  cout << "--  Predict 00 --" << endl;
  net.setPredictData(0,0);
  net.setPredictData(1,0);
  net.predict();

  cout << "--  Predict 01 --" << endl;
  net.setPredictData(0,0);
  net.setPredictData(1,1);
  net.predict();

  cout << "--  Predict 10 --" << endl;
  net.setPredictData(0,1);
  net.setPredictData(1,0);
  net.predict();

  cout << "--  Predict 11 --" << endl;
  net.setPredictData(0,1);
  net.setPredictData(1,1);
  net.predict();

}
<commit_msg>modifyed<commit_after>/*
 * nnet test
 * 2016.06.06
 * author:soma62jp
 *                  */

#include "test.h"

using namespace std;

nnet::nnet(int inputnum,int hiddennum,int outputnum,int patternnum):
      inputnum(inputnum)
     ,hiddennum(hiddennum)
     ,outputnum(outputnum)
     ,patternnum(patternnum)
     ,Eta(0.75)
     ,Alpha(0.8)
     ,ErrorEv(0.001)
     ,Rlow(-0.30)
     ,Rhigh(0.30)
     ,MaxGen(10000)
{
  //this->inputnum=inputnum;
  //this->hiddennum=hiddennum;
  //this->outputnum=outputnum;

  X_h = new double[hiddennum];
  X_o = new double[outputnum];

  bias_h = new double[hiddennum];
  bias_o = new double[outputnum];
  bias_h_prev = new double[hiddennum];
  bias_o_prev = new double[outputnum];

  // pattern*input
  X_i = new double*[patternnum];
  for(int i=0;i<patternnum;i++){
    X_i[i] = new double[inputnum];
  }

  // pattern*output
  T_signal = new double*[patternnum];
  for(int i=0;i<patternnum;i++){
    T_signal[i] = new double[outputnum];
  }

  // hidden*input
  W_itoh = new double*[hiddennum];
  for(int i=0;i<hiddennum;i++){
    W_itoh[i] = new double[inputnum];
  }
  W_itoh_prev = new double*[hiddennum];
  for(int i=0;i<hiddennum;i++){
    W_itoh_prev[i] = new double[inputnum];
  }

  // output*hidden
  W_htoo = new double*[outputnum];
  for(int i=0;i<outputnum;i++){
    W_htoo[i] = new double[hiddennum];
  }
  W_htoo_prev = new double*[outputnum];
  for(int i=0;i<outputnum;i++){
    W_htoo_prev[i] = new double[hiddennum];
  }

  //initialize parameter
  srand((unsigned int)time(NULL));

  for(int i=0;i<hiddennum;i++){
    for(int j=0;j<inputnum;j++){
      W_itoh[i][j]=urand();
    }
  }

  for(int i=0;i<outputnum;i++){
    for(int j=0;j<hiddennum;j++){
      W_htoo[i][j]=urand();
    }
  }

  for(int i=0;i<hiddennum;i++){
    bias_h[i] = 0;
  }

  for(int i=0;i<outputnum;i++){
    bias_o[i] = 0;
  }

}

nnet::~nnet()
{

  delete [] X_h;
  delete [] X_o;

  delete [] bias_h;
  delete [] bias_o;
  delete [] bias_h_prev;
  delete [] bias_o_prev;

  for( int i=0; i<patternnum; i++ ) {
    delete[] X_i[i];
  }
  delete [] X_i;

  for( int i=0; i<patternnum; i++ ) {
    delete[] T_signal[i];
  }
  delete [] T_signal;

  for( int i=0; i<hiddennum; i++ ) {
    delete[] W_itoh[i];
  }
  delete [] W_itoh;

  for( int i=0; i<hiddennum; i++ ) {
    delete[] W_itoh_prev[i];
  }
  delete [] W_itoh_prev;

  for( int i=0; i<outputnum; i++ ) {
    delete [] W_htoo[i];
  }
  delete [] W_htoo;

  for( int i=0; i<outputnum; i++ ) {
    delete [] W_htoo_prev[i];
  }
  delete [] W_htoo_prev;

}

void nnet::foward_propagation(const int pnum)
{
  int i,j;
  double sum;

  // 入力層ー＞隠れ層
  for(i=0;i<hiddennum;i++){
    sum=0;
    for(j=0;j<inputnum;j++){
      // 重み×入力値
      sum+=W_itoh[i][j]*X_i[pnum][j];
    }
    // 重み×入力値の総和にバイアス項を足してアクティベーション関数に通したものが中間層入力
    X_h[i] = activationFunc(sum+bias_h[i]);
  }

  // 隠れ層ー＞出力層
  for(i=0;i<outputnum;i++){
    sum=0;
    for(j=0;j<hiddennum;j++){
      // 重み×中間層入力
      sum+=W_htoo[i][j]*X_h[j];
    }
    // 重み×中間層入力値の総和にバイアス項を足してアクティベーション関数に通したものが出力層
    X_o[i]=activationFunc(sum+bias_o[i]);
  }

}

void nnet::back_propagation(const int pnum)
{
  int i,j;
  double sum;
  double *dwih = new double[hiddennum];   // 隠れ層での学習信号
  double *dwho = new double[outputnum];   // 出力層での学習信号

  // 出力層の学習信号から計算
  for(i=0;i<outputnum;i++){
    // 出力層での学習信号=(教師信号-出力） * f'(出力)
    // f'(出力)はシグモイド関数の微分
    dwho[i]=(T_signal[pnum][i]-X_o[i]) * activationFunc_diff(X_o[i]);
  }

  // 重みの変化量[隠れ層ー＞出力層]を計算
  // 隠れ層の学習信号を計算
  for(i=0;i<hiddennum;i++){
    sum=0;
    for(j=0;j<outputnum;j++){
      // 前回の重みの変化量[隠れ層->出力層] = η * 出力層での学習信号 * 隠れ層出力 * α * 前回の重みの変化量[隠れ層->出力層]
      W_htoo_prev[j][i]=Eta*dwho[j]*X_h[i]+Alpha*W_htoo_prev[j][i];
      // 重みの変化量[隠れ層ー＞出力層] = 重みの変化量[隠れ層ー＞出力層] + 前回の重みの変化量[隠れ層ー＞出力層]
      W_htoo[j][i]+=W_htoo_prev[j][i];
      // 出力層での学習信号 * 重みの変化量[隠れ層ー＞出力層]
      sum += dwho[j]*W_htoo[j][i];
    }
    // 隠れ層での学習信号 = f'(隠れ層出力) * sum
    dwih[i]=activationFunc_diff(X_h[i])*sum;
  }

  // 出力層のバイアス項を計算
  for(i=0;i<outputnum;i++){
    // 前回のバイアス項[出力層] = η * 出力層での学習信号 + α * 前回のバイアス項[出力層]
    bias_o_prev[i] = Eta*dwho[i]+Alpha*bias_o_prev[i];
    // 出力層バイアス項[出力層] = 出力層バイアス項[出力層] + 前回の出力層バイアス項[出力層]
    bias_o[i]+=bias_o_prev[i];
  }

  // 重みの変化量[入力層ー＞隠れ層]を計算
  for(i=0;i<inputnum;i++){
    for(j=0;j<hiddennum;j++){
      // 前回の重みの変化量[入力層ー＞隠れ層] = η * 隠れ層での学習信号 * 入力層出力 * α * 前回の重みの変化量[入力層ー＞隠れ層]
      W_itoh_prev[j][i]=Eta*dwih[j]*X_i[pnum][i]+Alpha*W_itoh_prev[j][i];
      // 重みの変化量[入力層ー＞隠れ層] = 重みの変化量[入力層ー＞隠れ層] + 前回の重みの変化量[入力層ー＞隠れ層]
      W_itoh[j][i]+=W_itoh_prev[j][i];
    }
  }

  // 隠れ層のバイアス項を計算
  for(i=0;i<hiddennum;i++){
    // 前回のバイアス項[隠れ層] = η * 隠れ層での学習信号 + α * 前回のバイアス項[隠れ層]
    bias_h_prev[i]=Eta*dwih[i]+Alpha*bias_h_prev[i];
    // 出力層バイアス項[隠れ層] = 出力層バイアス項[隠れ層] + 前回の出力層バイアス項[隠れ層]
    bias_h[i]+=bias_h_prev[i];
  }

  delete [] dwih;
  delete [] dwho;

}

void  nnet::setInData(const int pnum,const int i,const double value)
{
  if(pnum>=patternnum || i>=inputnum){
    cout << "can't set Indata." << endl;
    exit(1);
  }
  X_i[pnum][i] = value;
}

void nnet::setTeachData(const int pnum,const int i,const double value)
{
  if(pnum>=patternnum || i>=outputnum){
    cout << "can't set Teachdata." << endl;
    exit(1);
  }
  T_signal[pnum][i] = value;
}

void nnet::setPredictData(const int i,const double value)
{
  if(i>=inputnum){
    cout << "can't set Predictdata." << endl;
    exit(1);
  }
  X_i[patternnum-1][i] = value;
}

void nnet::train()
{
  double verror;
  int gen;
  int i,j,ip;

  gen = 0;
  verror = 20.0;
  while((verror > ErrorEv) && (gen < MaxGen))
  {
    gen++;

    // foward and back propagation
    for(i=0;i<patternnum;i++){
      ip = patternnum * random();
      foward_propagation(ip);
      back_propagation(ip);
    }

    // error calc
    verror = 0;
    for(i=0;i<patternnum;i++){
      foward_propagation(i);
      for(j=0;j<outputnum;j++){
          verror+=pow((T_signal[i][j] - X_o[j]) * 0.5 ,2.0);
      }
    }
    verror /= (double)patternnum;

    cout << verror << endl;

  }
}

void nnet::predict()
{
  int i;
  foward_propagation(patternnum-1);
  for(i=0;i<outputnum;i++){
    cout << X_o[i] << endl;
  }
}

double nnet::random()
{
	double r;
	int i;

	i = rand();
	if (i != 0)
		i--;
	r = (double)i / RAND_MAX;
	return (r);
}

int main()
{
  nnet net(2,4,1,4);

  net.setInData(0,0,0);
  net.setInData(0,1,0);
  net.setTeachData(0,0,0);

  net.setInData(1,0,1);
  net.setInData(1,1,1);
  net.setTeachData(1,0,0);

  net.setInData(2,0,1);
  net.setInData(2,1,0);
  net.setTeachData(2,0,1);

  net.setInData(3,0,0);
  net.setInData(3,1,1);
  net.setTeachData(3,0,1);

  net.train();

  cout << "--  Predict 00 --" << endl;
  net.setPredictData(0,0);
  net.setPredictData(1,0);
  net.predict();

  cout << "--  Predict 01 --" << endl;
  net.setPredictData(0,0);
  net.setPredictData(1,1);
  net.predict();

  cout << "--  Predict 10 --" << endl;
  net.setPredictData(0,1);
  net.setPredictData(1,0);
  net.predict();

  cout << "--  Predict 11 --" << endl;
  net.setPredictData(0,1);
  net.setPredictData(1,1);
  net.predict();

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: mediawindow.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <cstdio>

#include <avmedia/mediawindow.hxx>
#include "mediawindow_impl.hxx"
#include "mediamisc.hxx"
#include "mediawindow.hrc"
#include <tools/urlobj.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/pathoptions.hxx>
#include <sfx2/filedlghelper.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/media/XManager.hpp>
#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"

#define AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME 3.0

using namespace ::com::sun::star;

namespace avmedia {

// ---------------
// - MediaWindow -
// ---------------

MediaWindow::MediaWindow( Window* parent, bool bInternalMediaControl ) :
    mpImpl( new priv::MediaWindowImpl( parent, this, bInternalMediaControl ) )
{
    mpImpl->Show();
}

// -------------------------------------------------------------------------

MediaWindow::~MediaWindow()
{
    mpImpl->cleanUp();
    delete mpImpl;
    mpImpl = NULL;
}

// -------------------------------------------------------------------------

void MediaWindow::setURL( const ::rtl::OUString& rURL )
{
    if( mpImpl )
        mpImpl->setURL( rURL );
}

// -------------------------------------------------------------------------

const ::rtl::OUString& MediaWindow::getURL() const
{
    return mpImpl->getURL();
}

// -------------------------------------------------------------------------

bool MediaWindow::isValid() const
{
    return( mpImpl != NULL && mpImpl->isValid() );
}

// -------------------------------------------------------------------------

void MediaWindow::MouseMove( const MouseEvent& /* rMEvt */ )
{
}

// ---------------------------------------------------------------------

void MediaWindow::MouseButtonDown( const MouseEvent& /* rMEvt */ )
{
}

// ---------------------------------------------------------------------

void MediaWindow::MouseButtonUp( const MouseEvent& /* rMEvt */ )
{
}

// -------------------------------------------------------------------------

void MediaWindow::KeyInput( const KeyEvent& /* rKEvt */ )
{
}

// -------------------------------------------------------------------------

void MediaWindow::KeyUp( const KeyEvent& /* rKEvt */ )
{
}

// -------------------------------------------------------------------------

void MediaWindow::Command( const CommandEvent& /* rCEvt */ )
{
}

// -------------------------------------------------------------------------

sal_Int8 MediaWindow::AcceptDrop( const AcceptDropEvent& /* rEvt */ )
{
    return 0;
}

// -------------------------------------------------------------------------

sal_Int8 MediaWindow::ExecuteDrop( const ExecuteDropEvent& /* rEvt */ )
{
    return 0;
}

// -------------------------------------------------------------------------

void MediaWindow::StartDrag( sal_Int8 /* nAction */, const Point& /* rPosPixel */ )
{
}

// -------------------------------------------------------------------------

bool MediaWindow::hasPreferredSize() const
{
    return( mpImpl != NULL && mpImpl->hasPreferredSize() );
}

// -------------------------------------------------------------------------

Size MediaWindow::getPreferredSize() const
{
    return mpImpl->getPreferredSize();
}

// -------------------------------------------------------------------------

void MediaWindow::setPosSize( const Rectangle& rNewRect )
{
    if( mpImpl )
        mpImpl->setPosSize( rNewRect );
}

// -------------------------------------------------------------------------

Rectangle MediaWindow::getPosSize() const
{
    return Rectangle( mpImpl->GetPosPixel(), mpImpl->GetSizePixel() );
}

// -------------------------------------------------------------------------

void MediaWindow::setPointer( const Pointer& rPointer )
{
    if( mpImpl )
        mpImpl->setPointer( rPointer );
}

// -------------------------------------------------------------------------

const Pointer& MediaWindow::getPointer() const
{
    return mpImpl->getPointer();
}

// -------------------------------------------------------------------------

bool MediaWindow::setZoom( ::com::sun::star::media::ZoomLevel eLevel )
{
    return( mpImpl != NULL && mpImpl->setZoom( eLevel ) );
}

// -------------------------------------------------------------------------

::com::sun::star::media::ZoomLevel MediaWindow::getZoom() const
{
    return mpImpl->getZoom();
}

// -------------------------------------------------------------------------

bool MediaWindow::start()
{
    return( mpImpl != NULL && mpImpl->start() );
}

// -------------------------------------------------------------------------

void MediaWindow::stop()
{
    if( mpImpl )
        mpImpl->stop();
}

// -------------------------------------------------------------------------

bool MediaWindow::isPlaying() const
{
    return( mpImpl != NULL && mpImpl->isPlaying() );
}

// -------------------------------------------------------------------------

double MediaWindow::getDuration() const
{
    return mpImpl->getDuration();
}

// -------------------------------------------------------------------------

void MediaWindow::setMediaTime( double fTime )
{
    if( mpImpl )
        mpImpl->setMediaTime( fTime );
}

// -------------------------------------------------------------------------

double MediaWindow::getMediaTime() const
{
    return mpImpl->getMediaTime();
}

// -------------------------------------------------------------------------

void MediaWindow::setStopTime( double fTime )
{
    if( mpImpl )
        mpImpl->setStopTime( fTime );
}

// -------------------------------------------------------------------------

double MediaWindow::getStopTime() const
{
    return mpImpl->getStopTime();
}

// -------------------------------------------------------------------------

void MediaWindow::setRate( double fRate )
{
    if( mpImpl )
        mpImpl->setRate( fRate );
}

// -------------------------------------------------------------------------

double MediaWindow::getRate() const
{
    return mpImpl->getRate();
}

// -------------------------------------------------------------------------

void MediaWindow::setPlaybackLoop( bool bSet )
{
    if( mpImpl )
        mpImpl->setPlaybackLoop( bSet );
}

// -------------------------------------------------------------------------

bool MediaWindow::isPlaybackLoop() const
{
    return mpImpl->isPlaybackLoop();
}

// -------------------------------------------------------------------------

void MediaWindow::setMute( bool bSet )
{
    if( mpImpl )
        mpImpl->setMute( bSet );
}

// -------------------------------------------------------------------------

bool MediaWindow::isMute() const
{
    return mpImpl->isMute();
}

// -------------------------------------------------------------------------

void MediaWindow::updateMediaItem( MediaItem& rItem ) const
{
    if( mpImpl )
        mpImpl->updateMediaItem( rItem );
}

// -------------------------------------------------------------------------

void MediaWindow::executeMediaItem( const MediaItem& rItem )
{
    if( mpImpl )
        mpImpl->executeMediaItem( rItem );
}

// -------------------------------------------------------------------------

void MediaWindow::show()
{
    if( mpImpl )
        mpImpl->Show();
}

// -------------------------------------------------------------------------

void MediaWindow::hide()
{
    if( mpImpl )
        mpImpl->Hide();
}

// -------------------------------------------------------------------------

void MediaWindow::enable()
{
    if( mpImpl )
        mpImpl->Enable();
}

// -------------------------------------------------------------------------

void MediaWindow::disable()
{
    if( mpImpl )
        mpImpl->Disable();
}

// -------------------------------------------------------------------------

Window* MediaWindow::getWindow() const
{
    return mpImpl;
}

// -------------------------------------------------------------------------

void MediaWindow::getMediaFilters( FilterNameVector& rFilterNameVector )
{
    static const char* pFilters[] = {   "AIF Audio", "aif;aiff",
                                        "AU Audio", "au",
                                        "AVI", "avi",
                                        "CD Audio", "cda",
                                        "MIDI Audio", "mid;midi",
                                        "MPEG Audio", "mp2;mp3;mpa",
                                        "MPEG Video", "mpg;mpeg;mpv;mp4",
                                        "Ogg bitstream", "ogg",
                                        "Quicktime Video", "mov",
                                        "Vivo Video", "viv",
                                        "WAVE Audio", "wav" };

    unsigned int i;
    for( i = 0; i < ( sizeof( pFilters ) / sizeof( char* ) ); i += 2 )
    {
        rFilterNameVector.push_back( ::std::make_pair< ::rtl::OUString, ::rtl::OUString >(
                                        ::rtl::OUString::createFromAscii( pFilters[ i ] ),
                                        ::rtl::OUString::createFromAscii( pFilters[ i + 1 ] ) ) );
    }
}

// -------------------------------------------------------------------------

bool MediaWindow::executeMediaURLDialog( Window* /* pParent */, ::rtl::OUString& rURL, bool bInsertDialog )
{
    ::sfx2::FileDialogHelper        aDlg( com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0 );
    static const ::rtl::OUString    aWildcard( RTL_CONSTASCII_USTRINGPARAM( "*." ) );
    FilterNameVector                aFilters;
    const ::rtl::OUString           aSeparator( RTL_CONSTASCII_USTRINGPARAM( ";" ) );
    ::rtl::OUString                 aAllTypes;

    aDlg.SetTitle( AVMEDIA_RESID( bInsertDialog ? AVMEDIA_STR_INSERTMEDIA_DLG : AVMEDIA_STR_OPENMEDIA_DLG ) );

    getMediaFilters( aFilters );

    unsigned int i;
    for( i = 0; i < aFilters.size(); ++i )
    {
        for( sal_Int32 nIndex = 0; nIndex >= 0; )
        {
            if( aAllTypes.getLength() )
                aAllTypes += aSeparator;

            ( aAllTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
        }
    }

    // add filter for all media types
    aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_MEDIAFILES ), aAllTypes );

    for( i = 0; i < aFilters.size(); ++i )
    {
        ::rtl::OUString aTypes;

        for( sal_Int32 nIndex = 0; nIndex >= 0; )
        {
            if( aTypes.getLength() )
                aTypes += aSeparator;

            ( aTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
        }

        // add single filters
        aDlg.AddFilter( aFilters[ i ].first, aTypes );
    }

    // add filter for all types
    aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_FILES ), String( RTL_CONSTASCII_USTRINGPARAM( "*.*" ) ) );

    if( aDlg.Execute() == ERRCODE_NONE )
    {
        const INetURLObject aURL( aDlg.GetPath() );
        rURL = aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS );
    }
    else if( rURL.getLength() )
        rURL = ::rtl::OUString();

    return( rURL.getLength() > 0 );
}

// -------------------------------------------------------------------------

void MediaWindow::executeFormatErrorBox( Window* pParent )
{
    ErrorBox aErrBox( pParent, AVMEDIA_RESID( AVMEDIA_ERR_URL ) );

    aErrBox.Execute();
}

// -------------------------------------------------------------------------

bool MediaWindow::isMediaURL( const ::rtl::OUString& rURL, bool bDeep, Size* pPreferredSizePixel )
{
    const INetURLObject aURL( rURL );
    bool                bRet = false;

    if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
    {
        if( bDeep || pPreferredSizePixel )
        {
            uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );

            if( xFactory.is() )
            {
                try
                {
                    fprintf(stderr, "-->%s uno reference \n\n",AVMEDIA_MANAGER_SERVICE_NAME);

                    uno::Reference< ::com::sun::star::media::XManager > xManager(
                        xFactory->createInstance( ::rtl::OUString::createFromAscii( AVMEDIA_MANAGER_SERVICE_NAME ) ),
                        uno::UNO_QUERY );

                    if( xManager.is() )
                    {
                        uno::Reference< media::XPlayer > xPlayer( xManager->createPlayer( aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS ) ) );

                        if( xPlayer.is() )
                        {
                            bRet = true;

                            if( pPreferredSizePixel )
                            {
                                const awt::Size aAwtSize( xPlayer->getPreferredPlayerWindowSize() );

                                pPreferredSizePixel->Width() = aAwtSize.Width;
                                pPreferredSizePixel->Height() = aAwtSize.Height;
                            }
                        }
                    }
                }
                catch( ... )
                {
                }
            }
        }
        else
        {
            FilterNameVector        aFilters;
            const ::rtl::OUString   aExt( aURL.getExtension() );

            getMediaFilters( aFilters );

            unsigned int i;
            for( i = 0; ( i < aFilters.size() ) && !bRet; ++i )
            {
                for( sal_Int32 nIndex = 0; nIndex >= 0 && !bRet; )
                {
                    if( aExt.equalsIgnoreAsciiCase( aFilters[ i ].second.getToken( 0, ';', nIndex ) ) )
                        bRet = true;
                }
            }
        }
    }

    return bRet;
}

// -------------------------------------------------------------------------

uno::Reference< media::XPlayer > MediaWindow::createPlayer( const ::rtl::OUString& rURL )
{
    return priv::MediaWindowImpl::createPlayer( rURL );
}

// -------------------------------------------------------------------------

uno::Reference< graphic::XGraphic > MediaWindow::grabFrame( const ::rtl::OUString& rURL,
                                                            bool bAllowToCreateReplacementGraphic,
                                                            double fMediaTime )
{
    uno::Reference< media::XPlayer >    xPlayer( createPlayer( rURL ) );
    uno::Reference< graphic::XGraphic > xRet;
    ::std::auto_ptr< Graphic >          apGraphic;

    if( xPlayer.is() )
    {
        uno::Reference< media::XFrameGrabber > xGrabber( xPlayer->createFrameGrabber() );

        if( xGrabber.is() )
        {
            if( AVMEDIA_FRAMEGRABBER_DEFAULTFRAME == fMediaTime )
                fMediaTime = AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME;

            if( fMediaTime >= xPlayer->getDuration() )
                fMediaTime = ( xPlayer->getDuration() * 0.5 );

            xRet = xGrabber->grabFrame( fMediaTime );
        }

        if( !xRet.is() && bAllowToCreateReplacementGraphic  )
        {
            awt::Size aPrefSize( xPlayer->getPreferredPlayerWindowSize() );

            if( !aPrefSize.Width && !aPrefSize.Height )
            {
                const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_AUDIOLOGO ) );
                apGraphic.reset( new Graphic( aBmpEx ) );
            }
        }
    }

    if( !xRet.is() && !apGraphic.get() && bAllowToCreateReplacementGraphic )
    {
        const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_EMPTYLOGO ) );
        apGraphic.reset( new Graphic( aBmpEx ) );
    }

    if( apGraphic.get() )
        xRet = apGraphic->GetXGraphic();

    return xRet;
}

} // namespace avemdia
<commit_msg>INTEGRATION: CWS hr51 (1.9.6); FILE MERGED 2008/06/06 14:14:11 hr 1.9.6.1: #i88947#: std namespace<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: mediawindow.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <cstdio>

#include <avmedia/mediawindow.hxx>
#include "mediawindow_impl.hxx"
#include "mediamisc.hxx"
#include "mediawindow.hrc"
#include <tools/urlobj.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/pathoptions.hxx>
#include <sfx2/filedlghelper.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/media/XManager.hpp>
#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"

#define AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME 3.0

using namespace ::com::sun::star;

namespace avmedia {

// ---------------
// - MediaWindow -
// ---------------

MediaWindow::MediaWindow( Window* parent, bool bInternalMediaControl ) :
    mpImpl( new priv::MediaWindowImpl( parent, this, bInternalMediaControl ) )
{
    mpImpl->Show();
}

// -------------------------------------------------------------------------

MediaWindow::~MediaWindow()
{
    mpImpl->cleanUp();
    delete mpImpl;
    mpImpl = NULL;
}

// -------------------------------------------------------------------------

void MediaWindow::setURL( const ::rtl::OUString& rURL )
{
    if( mpImpl )
        mpImpl->setURL( rURL );
}

// -------------------------------------------------------------------------

const ::rtl::OUString& MediaWindow::getURL() const
{
    return mpImpl->getURL();
}

// -------------------------------------------------------------------------

bool MediaWindow::isValid() const
{
    return( mpImpl != NULL && mpImpl->isValid() );
}

// -------------------------------------------------------------------------

void MediaWindow::MouseMove( const MouseEvent& /* rMEvt */ )
{
}

// ---------------------------------------------------------------------

void MediaWindow::MouseButtonDown( const MouseEvent& /* rMEvt */ )
{
}

// ---------------------------------------------------------------------

void MediaWindow::MouseButtonUp( const MouseEvent& /* rMEvt */ )
{
}

// -------------------------------------------------------------------------

void MediaWindow::KeyInput( const KeyEvent& /* rKEvt */ )
{
}

// -------------------------------------------------------------------------

void MediaWindow::KeyUp( const KeyEvent& /* rKEvt */ )
{
}

// -------------------------------------------------------------------------

void MediaWindow::Command( const CommandEvent& /* rCEvt */ )
{
}

// -------------------------------------------------------------------------

sal_Int8 MediaWindow::AcceptDrop( const AcceptDropEvent& /* rEvt */ )
{
    return 0;
}

// -------------------------------------------------------------------------

sal_Int8 MediaWindow::ExecuteDrop( const ExecuteDropEvent& /* rEvt */ )
{
    return 0;
}

// -------------------------------------------------------------------------

void MediaWindow::StartDrag( sal_Int8 /* nAction */, const Point& /* rPosPixel */ )
{
}

// -------------------------------------------------------------------------

bool MediaWindow::hasPreferredSize() const
{
    return( mpImpl != NULL && mpImpl->hasPreferredSize() );
}

// -------------------------------------------------------------------------

Size MediaWindow::getPreferredSize() const
{
    return mpImpl->getPreferredSize();
}

// -------------------------------------------------------------------------

void MediaWindow::setPosSize( const Rectangle& rNewRect )
{
    if( mpImpl )
        mpImpl->setPosSize( rNewRect );
}

// -------------------------------------------------------------------------

Rectangle MediaWindow::getPosSize() const
{
    return Rectangle( mpImpl->GetPosPixel(), mpImpl->GetSizePixel() );
}

// -------------------------------------------------------------------------

void MediaWindow::setPointer( const Pointer& rPointer )
{
    if( mpImpl )
        mpImpl->setPointer( rPointer );
}

// -------------------------------------------------------------------------

const Pointer& MediaWindow::getPointer() const
{
    return mpImpl->getPointer();
}

// -------------------------------------------------------------------------

bool MediaWindow::setZoom( ::com::sun::star::media::ZoomLevel eLevel )
{
    return( mpImpl != NULL && mpImpl->setZoom( eLevel ) );
}

// -------------------------------------------------------------------------

::com::sun::star::media::ZoomLevel MediaWindow::getZoom() const
{
    return mpImpl->getZoom();
}

// -------------------------------------------------------------------------

bool MediaWindow::start()
{
    return( mpImpl != NULL && mpImpl->start() );
}

// -------------------------------------------------------------------------

void MediaWindow::stop()
{
    if( mpImpl )
        mpImpl->stop();
}

// -------------------------------------------------------------------------

bool MediaWindow::isPlaying() const
{
    return( mpImpl != NULL && mpImpl->isPlaying() );
}

// -------------------------------------------------------------------------

double MediaWindow::getDuration() const
{
    return mpImpl->getDuration();
}

// -------------------------------------------------------------------------

void MediaWindow::setMediaTime( double fTime )
{
    if( mpImpl )
        mpImpl->setMediaTime( fTime );
}

// -------------------------------------------------------------------------

double MediaWindow::getMediaTime() const
{
    return mpImpl->getMediaTime();
}

// -------------------------------------------------------------------------

void MediaWindow::setStopTime( double fTime )
{
    if( mpImpl )
        mpImpl->setStopTime( fTime );
}

// -------------------------------------------------------------------------

double MediaWindow::getStopTime() const
{
    return mpImpl->getStopTime();
}

// -------------------------------------------------------------------------

void MediaWindow::setRate( double fRate )
{
    if( mpImpl )
        mpImpl->setRate( fRate );
}

// -------------------------------------------------------------------------

double MediaWindow::getRate() const
{
    return mpImpl->getRate();
}

// -------------------------------------------------------------------------

void MediaWindow::setPlaybackLoop( bool bSet )
{
    if( mpImpl )
        mpImpl->setPlaybackLoop( bSet );
}

// -------------------------------------------------------------------------

bool MediaWindow::isPlaybackLoop() const
{
    return mpImpl->isPlaybackLoop();
}

// -------------------------------------------------------------------------

void MediaWindow::setMute( bool bSet )
{
    if( mpImpl )
        mpImpl->setMute( bSet );
}

// -------------------------------------------------------------------------

bool MediaWindow::isMute() const
{
    return mpImpl->isMute();
}

// -------------------------------------------------------------------------

void MediaWindow::updateMediaItem( MediaItem& rItem ) const
{
    if( mpImpl )
        mpImpl->updateMediaItem( rItem );
}

// -------------------------------------------------------------------------

void MediaWindow::executeMediaItem( const MediaItem& rItem )
{
    if( mpImpl )
        mpImpl->executeMediaItem( rItem );
}

// -------------------------------------------------------------------------

void MediaWindow::show()
{
    if( mpImpl )
        mpImpl->Show();
}

// -------------------------------------------------------------------------

void MediaWindow::hide()
{
    if( mpImpl )
        mpImpl->Hide();
}

// -------------------------------------------------------------------------

void MediaWindow::enable()
{
    if( mpImpl )
        mpImpl->Enable();
}

// -------------------------------------------------------------------------

void MediaWindow::disable()
{
    if( mpImpl )
        mpImpl->Disable();
}

// -------------------------------------------------------------------------

Window* MediaWindow::getWindow() const
{
    return mpImpl;
}

// -------------------------------------------------------------------------

void MediaWindow::getMediaFilters( FilterNameVector& rFilterNameVector )
{
    static const char* pFilters[] = {   "AIF Audio", "aif;aiff",
                                        "AU Audio", "au",
                                        "AVI", "avi",
                                        "CD Audio", "cda",
                                        "MIDI Audio", "mid;midi",
                                        "MPEG Audio", "mp2;mp3;mpa",
                                        "MPEG Video", "mpg;mpeg;mpv;mp4",
                                        "Ogg bitstream", "ogg",
                                        "Quicktime Video", "mov",
                                        "Vivo Video", "viv",
                                        "WAVE Audio", "wav" };

    unsigned int i;
    for( i = 0; i < ( sizeof( pFilters ) / sizeof( char* ) ); i += 2 )
    {
        rFilterNameVector.push_back( ::std::make_pair< ::rtl::OUString, ::rtl::OUString >(
                                        ::rtl::OUString::createFromAscii( pFilters[ i ] ),
                                        ::rtl::OUString::createFromAscii( pFilters[ i + 1 ] ) ) );
    }
}

// -------------------------------------------------------------------------

bool MediaWindow::executeMediaURLDialog( Window* /* pParent */, ::rtl::OUString& rURL, bool bInsertDialog )
{
    ::sfx2::FileDialogHelper        aDlg( com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0 );
    static const ::rtl::OUString    aWildcard( RTL_CONSTASCII_USTRINGPARAM( "*." ) );
    FilterNameVector                aFilters;
    const ::rtl::OUString           aSeparator( RTL_CONSTASCII_USTRINGPARAM( ";" ) );
    ::rtl::OUString                 aAllTypes;

    aDlg.SetTitle( AVMEDIA_RESID( bInsertDialog ? AVMEDIA_STR_INSERTMEDIA_DLG : AVMEDIA_STR_OPENMEDIA_DLG ) );

    getMediaFilters( aFilters );

    unsigned int i;
    for( i = 0; i < aFilters.size(); ++i )
    {
        for( sal_Int32 nIndex = 0; nIndex >= 0; )
        {
            if( aAllTypes.getLength() )
                aAllTypes += aSeparator;

            ( aAllTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
        }
    }

    // add filter for all media types
    aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_MEDIAFILES ), aAllTypes );

    for( i = 0; i < aFilters.size(); ++i )
    {
        ::rtl::OUString aTypes;

        for( sal_Int32 nIndex = 0; nIndex >= 0; )
        {
            if( aTypes.getLength() )
                aTypes += aSeparator;

            ( aTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
        }

        // add single filters
        aDlg.AddFilter( aFilters[ i ].first, aTypes );
    }

    // add filter for all types
    aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_FILES ), String( RTL_CONSTASCII_USTRINGPARAM( "*.*" ) ) );

    if( aDlg.Execute() == ERRCODE_NONE )
    {
        const INetURLObject aURL( aDlg.GetPath() );
        rURL = aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS );
    }
    else if( rURL.getLength() )
        rURL = ::rtl::OUString();

    return( rURL.getLength() > 0 );
}

// -------------------------------------------------------------------------

void MediaWindow::executeFormatErrorBox( Window* pParent )
{
    ErrorBox aErrBox( pParent, AVMEDIA_RESID( AVMEDIA_ERR_URL ) );

    aErrBox.Execute();
}

// -------------------------------------------------------------------------

bool MediaWindow::isMediaURL( const ::rtl::OUString& rURL, bool bDeep, Size* pPreferredSizePixel )
{
    const INetURLObject aURL( rURL );
    bool                bRet = false;

    if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
    {
        if( bDeep || pPreferredSizePixel )
        {
            uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );

            if( xFactory.is() )
            {
                try
                {
                    std::fprintf(stderr, "-->%s uno reference \n\n",AVMEDIA_MANAGER_SERVICE_NAME);

                    uno::Reference< ::com::sun::star::media::XManager > xManager(
                        xFactory->createInstance( ::rtl::OUString::createFromAscii( AVMEDIA_MANAGER_SERVICE_NAME ) ),
                        uno::UNO_QUERY );

                    if( xManager.is() )
                    {
                        uno::Reference< media::XPlayer > xPlayer( xManager->createPlayer( aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS ) ) );

                        if( xPlayer.is() )
                        {
                            bRet = true;

                            if( pPreferredSizePixel )
                            {
                                const awt::Size aAwtSize( xPlayer->getPreferredPlayerWindowSize() );

                                pPreferredSizePixel->Width() = aAwtSize.Width;
                                pPreferredSizePixel->Height() = aAwtSize.Height;
                            }
                        }
                    }
                }
                catch( ... )
                {
                }
            }
        }
        else
        {
            FilterNameVector        aFilters;
            const ::rtl::OUString   aExt( aURL.getExtension() );

            getMediaFilters( aFilters );

            unsigned int i;
            for( i = 0; ( i < aFilters.size() ) && !bRet; ++i )
            {
                for( sal_Int32 nIndex = 0; nIndex >= 0 && !bRet; )
                {
                    if( aExt.equalsIgnoreAsciiCase( aFilters[ i ].second.getToken( 0, ';', nIndex ) ) )
                        bRet = true;
                }
            }
        }
    }

    return bRet;
}

// -------------------------------------------------------------------------

uno::Reference< media::XPlayer > MediaWindow::createPlayer( const ::rtl::OUString& rURL )
{
    return priv::MediaWindowImpl::createPlayer( rURL );
}

// -------------------------------------------------------------------------

uno::Reference< graphic::XGraphic > MediaWindow::grabFrame( const ::rtl::OUString& rURL,
                                                            bool bAllowToCreateReplacementGraphic,
                                                            double fMediaTime )
{
    uno::Reference< media::XPlayer >    xPlayer( createPlayer( rURL ) );
    uno::Reference< graphic::XGraphic > xRet;
    ::std::auto_ptr< Graphic >          apGraphic;

    if( xPlayer.is() )
    {
        uno::Reference< media::XFrameGrabber > xGrabber( xPlayer->createFrameGrabber() );

        if( xGrabber.is() )
        {
            if( AVMEDIA_FRAMEGRABBER_DEFAULTFRAME == fMediaTime )
                fMediaTime = AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME;

            if( fMediaTime >= xPlayer->getDuration() )
                fMediaTime = ( xPlayer->getDuration() * 0.5 );

            xRet = xGrabber->grabFrame( fMediaTime );
        }

        if( !xRet.is() && bAllowToCreateReplacementGraphic  )
        {
            awt::Size aPrefSize( xPlayer->getPreferredPlayerWindowSize() );

            if( !aPrefSize.Width && !aPrefSize.Height )
            {
                const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_AUDIOLOGO ) );
                apGraphic.reset( new Graphic( aBmpEx ) );
            }
        }
    }

    if( !xRet.is() && !apGraphic.get() && bAllowToCreateReplacementGraphic )
    {
        const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_EMPTYLOGO ) );
        apGraphic.reset( new Graphic( aBmpEx ) );
    }

    if( apGraphic.get() )
        xRet = apGraphic->GetXGraphic();

    return xRet;
}

} // namespace avemdia
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <ctime>
#include <stdint.h>

#include "libpopcnt.h"

int main(int argc, char** argv)
{
  srand((unsigned int) time(0));
  int max_size = 100000;

  // Generate vectors with random data and compute the bit
  // population count using 2 different algorithms and
  // check that the results match
  for (int size = 0; size < max_size; size++)
  {
    double percent = (100.0 * size) / max_size;
    std::cout << "\rStatus: " << (int) percent << "%" << std::flush;
    std::vector<uint8_t> data(size);

    for (int i = 0; i < size; i++)
      data[i] = (uint8_t) rand();

    uint64_t bits = popcnt(&data[0], size);
    uint64_t bits_verify = 0;

    for (int i = 0; i < size; i++)
      bits_verify += popcnt64(data[i]);

    if (bits != bits_verify)
    {
      std::cerr << std::endl;
      std::cerr << "libpopcnt test failed!" << std::endl;
      return 1;
    }
  }

  std::cout << "\rStatus: 100%" << std::flush;
  std::cout << std::endl;
  std::cout << "libpopcnt tested successfully!" << std::endl;

  return 0;
}
<commit_msg>Rename popcnt64() to popcnt_u64()<commit_after>#include <iostream>
#include <vector>
#include <ctime>
#include <stdint.h>

#include "libpopcnt.h"

int main(int argc, char** argv)
{
  srand((unsigned int) time(0));
  int max_size = 100000;

  // Generate vectors with random data and compute the bit
  // population count using 2 different algorithms and
  // check that the results match
  for (int size = 0; size < max_size; size++)
  {
    double percent = (100.0 * size) / max_size;
    std::cout << "\rStatus: " << (int) percent << "%" << std::flush;
    std::vector<uint8_t> data(size);

    for (int i = 0; i < size; i++)
      data[i] = (uint8_t) rand();

    uint64_t bits = popcnt(&data[0], size);
    uint64_t bits_verify = 0;

    for (int i = 0; i < size; i++)
      bits_verify += popcnt_u64(data[i]);

    if (bits != bits_verify)
    {
      std::cerr << std::endl;
      std::cerr << "libpopcnt test failed!" << std::endl;
      return 1;
    }
  }

  std::cout << "\rStatus: 100%" << std::flush;
  std::cout << std::endl;
  std::cout << "libpopcnt tested successfully!" << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>#include <sys/socket.h>
#include <sys/un.h>

#include <json/json.h>

#include "data/Event.h"
#include "ipc/server/Json.h"

namespace blitzortung {
  namespace ipc {
    namespace server {

      Json::Json(const unsigned int socket, const Process& process, const hardware::Pcb& hardware) :
	Base(socket),
	process_(process),
	hardware_(hardware),
	logger_("ipc.server.Json")
      {
	if (logger_.isDebugEnabled())
	  logger_.debugStream() << "initialize for socket " << socket;
      }

      std::string Json::respond(const std::string& input) {
	json_object* jsonResult = json_object_new_object();

	json_object* jsonObj = json_tokener_parse(input.c_str());
	if (int(jsonObj) > 0) {
	  json_object* cmd_obj = json_object_object_get(jsonObj, "cmd");
	  if (cmd_obj != 0) {
	    const char* command = json_object_get_string(cmd_obj);
	    json_object_object_add(jsonResult, "command", json_object_new_string(command));

	    json_object* jsonHardware = json_object_new_object();
	    json_object_object_add(jsonHardware, "firmware", json_object_new_string(hardware_.getFirmwareVersion().c_str()));
	    json_object_object_add(jsonResult, "hardware", jsonHardware);

	    const hardware::gps::Base& gps = hardware_.getGps();
	    json_object* jsonGps = json_object_new_object();
	    char gpsStatus = gps.getStatus();
	    json_object_object_add(jsonGps, "longitude", json_object_new_double(gps.getLocation().getLongitude()));
	    json_object_object_add(jsonGps, "longitudeError", json_object_new_double(gps.getLocation().getLongitudeError()));
	    json_object_object_add(jsonGps, "latitude", json_object_new_double(gps.getLocation().getLatitude()));
	    json_object_object_add(jsonGps, "latitudeError", json_object_new_double(gps.getLocation().getLatitudeError()));
	    json_object_object_add(jsonGps, "altitude", json_object_new_int(gps.getLocation().getAltitude()));
	    json_object_object_add(jsonGps, "altitudeError", json_object_new_int(gps.getLocation().getAltitudeError()));
	    pt::ptime gpsTime = gps.getTime();
	    std::ostringstream oss;
	    gr::date_facet *datefacet = new gr::date_facet();
	    datefacet->format("%Y-%m-%d");
	    oss.imbue(std::locale(std::locale::classic(), datefacet));
	    oss << gpsTime.date();
	    json_object_object_add(jsonGps, "date", json_object_new_string(oss.str().c_str()));
	    oss.str("");
	    oss << gpsTime.time_of_day();
	    json_object_object_add(jsonGps, "time", json_object_new_string(oss.str().c_str()));
	    json_object_object_add(jsonGps, "ticksPerSecond", json_object_new_double(gps.getTicksPerSecond()));
	    json_object_object_add(jsonGps, "tickError", json_object_new_double(gps.getTickError()));
	    json_object_object_add(jsonGps, "status", json_object_new_string_len(&gpsStatus, 1));
	    json_object_object_add(jsonGps, "satelliteCount", json_object_new_int(gps.getSatelliteCount()));
	    json_object_object_add(jsonGps, "type", json_object_new_string(gps.getType().c_str()));
	    json_object_object_add(jsonHardware, "gps", jsonGps);

	    const hardware::comm::Base& comm = hardware_.getComm();
	    json_object* jsonComm = json_object_new_object();
	    json_object_object_add(jsonGps, "baudRate", json_object_new_int(comm.getBaudRate()));
	    json_object_object_add(jsonGps, "interfaceName", json_object_new_string(comm.getInterfaceName().c_str()));
	    json_object_object_add(jsonHardware, "comm", jsonComm);

	    json_object* jsonProcess = json_object_new_object();
	    json_object_object_add(jsonProcess, "numberOfSeconds", json_object_new_int(process_.getEventCountBuffer().getActualSize()));
	    json_object_object_add(jsonProcess, "numberOfEvents", json_object_new_int(process_.getEventCountBuffer().getSum()));
	    json_object_object_add(jsonProcess, "eventsPerSecond", json_object_new_double(process_.getEventCountBuffer().getAverage()));
	    json_object_object_add(jsonResult, "process", jsonProcess);

	    json_object_put(cmd_obj);
	  }

	  json_object_put(jsonObj);
	} else {
	  std::string result = "could not parse command '" + input + "'";
	  json_object_object_add(jsonResult, "error", json_object_new_string(result.c_str()));
	  logger_.warnStream() << result;
	}

	std::string jsonString(json_object_to_json_string(jsonResult));
	json_object_put(jsonResult);

	return jsonString;
      }

    }
  }
}
<commit_msg>fix json ipc<commit_after>#include <sys/socket.h>
#include <sys/un.h>

#include <json/json.h>

#include "data/Event.h"
#include "ipc/server/Json.h"

namespace blitzortung {
  namespace ipc {
    namespace server {

      Json::Json(const unsigned int socket, const Process& process, const hardware::Pcb& hardware) :
	Base(socket),
	process_(process),
	hardware_(hardware),
	logger_("ipc.server.Json")
      {
	if (logger_.isDebugEnabled())
	  logger_.debugStream() << "initialize for socket " << socket;
      }

      std::string Json::respond(const std::string& input) {
	json_object* jsonResult = json_object_new_object();

	json_object* jsonObj = json_tokener_parse(input.c_str());
	if (int(jsonObj) > 0) {
	  json_object* cmd_obj = json_object_object_get(jsonObj, "cmd");
	  if (cmd_obj != 0) {
	    const char* command = json_object_get_string(cmd_obj);
	    json_object_object_add(jsonResult, "command", json_object_new_string(command));

	    json_object* jsonHardware = json_object_new_object();
	    json_object_object_add(jsonHardware, "firmware", json_object_new_string(hardware_.getFirmwareVersion().c_str()));
	    json_object_object_add(jsonResult, "hardware", jsonHardware);

	    const hardware::gps::Base& gps = hardware_.getGps();
	    json_object* jsonGps = json_object_new_object();
	    char gpsStatus = gps.getStatus();
	    json_object_object_add(jsonGps, "longitude", json_object_new_double(gps.getLocation().getLongitude()));
	    json_object_object_add(jsonGps, "longitudeError", json_object_new_double(gps.getLocation().getLongitudeError()));
	    json_object_object_add(jsonGps, "latitude", json_object_new_double(gps.getLocation().getLatitude()));
	    json_object_object_add(jsonGps, "latitudeError", json_object_new_double(gps.getLocation().getLatitudeError()));
	    json_object_object_add(jsonGps, "altitude", json_object_new_int(gps.getLocation().getAltitude()));
	    json_object_object_add(jsonGps, "altitudeError", json_object_new_int(gps.getLocation().getAltitudeError()));
	    pt::ptime gpsTime = gps.getTime();
	    std::ostringstream oss;
	    gr::date_facet *datefacet = new gr::date_facet();
	    datefacet->format("%Y-%m-%d");
	    oss.imbue(std::locale(std::locale::classic(), datefacet));
	    oss << gpsTime.date();
	    json_object_object_add(jsonGps, "date", json_object_new_string(oss.str().c_str()));
	    oss.str("");
	    oss << gpsTime.time_of_day();
	    json_object_object_add(jsonGps, "time", json_object_new_string(oss.str().c_str()));
	    json_object_object_add(jsonGps, "ticksPerSecond", json_object_new_double(gps.getTicksPerSecond()));
	    json_object_object_add(jsonGps, "tickError", json_object_new_double(gps.getTickError()));
	    json_object_object_add(jsonGps, "status", json_object_new_string_len(&gpsStatus, 1));
	    json_object_object_add(jsonGps, "satelliteCount", json_object_new_int(gps.getSatelliteCount()));
	    json_object_object_add(jsonGps, "type", json_object_new_string(gps.getType().c_str()));
	    json_object_object_add(jsonHardware, "gps", jsonGps);

	    const hardware::comm::Base& comm = hardware_.getComm();
	    json_object* jsonComm = json_object_new_object();
	    json_object_object_add(jsonComm, "baudRate", json_object_new_int(comm.getBaudRate()));
	    json_object_object_add(jsonComm, "interfaceName", json_object_new_string(comm.getInterfaceName().c_str()));
	    json_object_object_add(jsonHardware, "comm", jsonComm);

	    json_object* jsonProcess = json_object_new_object();
	    json_object_object_add(jsonProcess, "numberOfSeconds", json_object_new_int(process_.getEventCountBuffer().getActualSize()));
	    json_object_object_add(jsonProcess, "numberOfEvents", json_object_new_int(process_.getEventCountBuffer().getSum()));
	    json_object_object_add(jsonProcess, "eventsPerSecond", json_object_new_double(process_.getEventCountBuffer().getAverage()));
	    json_object_object_add(jsonResult, "process", jsonProcess);

	    json_object_put(cmd_obj);
	  }

	  json_object_put(jsonObj);
	} else {
	  std::string result = "could not parse command '" + input + "'";
	  json_object_object_add(jsonResult, "error", json_object_new_string(result.c_str()));
	  logger_.warnStream() << result;
	}

	std::string jsonString(json_object_to_json_string(jsonResult));
	json_object_put(jsonResult);

	return jsonString;
      }

    }
  }
}
<|endoftext|>