<commit_before>//===-- lldb-log.cpp --------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/lldb-private-log.h"

// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Interpreter/Args.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/StreamFile.h"
#include <string.h>

using namespace lldb;
using namespace lldb_private;

// We want to avoid global constructors where code needs to be run so here we
// control access to our static g_log_sp by hiding it in a singleton function
// that will construct the static g_lob_sp the first time this function is
// called.

static bool g_log_enabled = false;
static Log * g_log = NULL;
static Log *
GetLog ()
{
    if (!g_log_enabled)
        return NULL;
    return g_log;
}

uint32_t
lldb_private::GetLogMask ()
{
    Log *log(GetLog ());
    if (log)
        return log->GetMask().Get();
    return 0;
}

bool
lldb_private::IsLogVerbose ()
{
    uint32_t mask = GetLogMask();
    return (mask & LIBLLDB_LOG_VERBOSE);
}

Log *
lldb_private::GetLogIfAllCategoriesSet (uint32_t mask)
{
    Log *log(GetLog ());
    if (log && mask)
    {
        uint32_t log_mask = log->GetMask().Get();
        if ((log_mask & mask) != mask)
            return NULL;
    }
    return log;
}

void
lldb_private::LogIfAllCategoriesSet (uint32_t mask, const char *format, ...)
{
    Log *log(GetLogIfAllCategoriesSet (mask));
    if (log)
    {
        va_list args;
        va_start (args, format);
        log->VAPrintf (format, args);
        va_end (args);
    }
}

void
lldb_private::LogIfAnyCategoriesSet (uint32_t mask, const char *format, ...)
{
    Log *log(GetLogIfAnyCategoriesSet (mask));
    if (log)
    {
        va_list args;
        va_start (args, format);
        log->VAPrintf (format, args);
        va_end (args);
    }
}

Log *
lldb_private::GetLogIfAnyCategoriesSet (uint32_t mask)
{
    Log *log(GetLog ());
    if (log && mask && (mask & log->GetMask().Get()))
        return log;
    return NULL;
}

void
lldb_private::DisableLog (const char **categories, Stream *feedback_strm)
{
    Log *log(GetLog ());

    if (log)
    {
        uint32_t flag_bits = 0;
        if (categories[0] != NULL)
        {
            flag_bits = log->GetMask().Get();
            for (size_t i = 0; categories[i] != NULL; ++i)
            {
                const char *arg = categories[i];

                if      (0 == ::strcasecmp(arg, "all"))         flag_bits &= ~LIBLLDB_LOG_ALL;
                else if (0 == ::strcasecmp(arg, "api"))         flag_bits &= ~LIBLLDB_LOG_API;
                else if (0 == ::strncasecmp(arg, "break", 5))   flag_bits &= ~LIBLLDB_LOG_BREAKPOINTS;
                else if (0 == ::strcasecmp(arg, "commands"))    flag_bits &= ~LIBLLDB_LOG_COMMANDS;
                else if (0 == ::strcasecmp(arg, "default"))     flag_bits &= ~LIBLLDB_LOG_DEFAULT;
                else if (0 == ::strcasecmp(arg, "dyld"))        flag_bits &= ~LIBLLDB_LOG_DYNAMIC_LOADER;
                else if (0 == ::strncasecmp(arg, "event", 5))   flag_bits &= ~LIBLLDB_LOG_EVENTS;
                else if (0 == ::strncasecmp(arg, "expr", 4))    flag_bits &= ~LIBLLDB_LOG_EXPRESSIONS;
                else if (0 == ::strncasecmp(arg, "object", 6))  flag_bits &= ~LIBLLDB_LOG_OBJECT;
                else if (0 == ::strcasecmp(arg, "process"))     flag_bits &= ~LIBLLDB_LOG_PROCESS;
                else if (0 == ::strcasecmp(arg, "script"))      flag_bits &= ~LIBLLDB_LOG_SCRIPT;
                else if (0 == ::strcasecmp(arg, "state"))       flag_bits &= ~LIBLLDB_LOG_STATE;
                else if (0 == ::strcasecmp(arg, "step"))        flag_bits &= ~LIBLLDB_LOG_STEP;
                else if (0 == ::strcasecmp(arg, "thread"))      flag_bits &= ~LIBLLDB_LOG_THREAD;
                else if (0 == ::strcasecmp(arg, "target"))      flag_bits &= ~LIBLLDB_LOG_TARGET;
                else if (0 == ::strcasecmp(arg, "verbose"))     flag_bits &= ~LIBLLDB_LOG_VERBOSE;
                else if (0 == ::strncasecmp(arg, "watch", 5))   flag_bits &= ~LIBLLDB_LOG_WATCHPOINTS;
                else if (0 == ::strncasecmp(arg, "temp", 4))    flag_bits &= ~LIBLLDB_LOG_TEMPORARY;
                else if (0 == ::strncasecmp(arg, "comm", 4))    flag_bits &= ~LIBLLDB_LOG_COMMUNICATION;
                else if (0 == ::strncasecmp(arg, "conn", 4))    flag_bits &= ~LIBLLDB_LOG_CONNECTION;
                else if (0 == ::strncasecmp(arg, "host", 4))    flag_bits &= ~LIBLLDB_LOG_HOST;
                else if (0 == ::strncasecmp(arg, "unwind", 6))  flag_bits &= ~LIBLLDB_LOG_UNWIND;
                else if (0 == ::strncasecmp(arg, "types", 5))   flag_bits &= ~LIBLLDB_LOG_TYPES;
                else if (0 == ::strncasecmp(arg, "symbol", 6))  flag_bits &= ~LIBLLDB_LOG_SYMBOLS;
                else if (0 == ::strncasecmp(arg, "module", 6))  flag_bits &= ~LIBLLDB_LOG_MODULES;
                else if (0 == ::strncasecmp(arg, "mmap", 4))    flag_bits &= ~LIBLLDB_LOG_MMAP;
                else
                {
                    feedback_strm->Printf ("error:  unrecognized log category '%s'\n", arg);
                    ListLogCategories (feedback_strm);
                    return;
                }

            }
        }
        log->GetMask().Reset (flag_bits);
        if (flag_bits == 0)
            g_log_enabled = false;
    }

    return;
}

Log *
lldb_private::EnableLog (StreamSP &log_stream_sp, uint32_t log_options, const char **categories, Stream *feedback_strm)
{
    // Try see if there already is a log - that way we can reuse its settings.
    // We could reuse the log in toto, but we don't know that the stream is the same.
    uint32_t flag_bits;
    if (g_log)
        flag_bits = g_log->GetMask().Get();
    else
        flag_bits = 0;

    // Now make a new log with this stream if one was provided
    if (log_stream_sp)
    {
        if (g_log)
            g_log->SetStream(log_stream_sp);
        else
            g_log = new Log(log_stream_sp);
    }

    if (g_log)
    {
        for (size_t i=0; categories[i] != NULL; ++i)
        {
            const char *arg = categories[i];

            if      (0 == ::strcasecmp(arg, "all"))         flag_bits |= LIBLLDB_LOG_ALL;
            else if (0 == ::strcasecmp(arg, "api"))         flag_bits |= LIBLLDB_LOG_API;
            else if (0 == ::strncasecmp(arg, "break", 5))   flag_bits |= LIBLLDB_LOG_BREAKPOINTS;
            else if (0 == ::strcasecmp(arg, "commands"))    flag_bits |= LIBLLDB_LOG_COMMANDS;
            else if (0 == ::strcasecmp(arg, "default"))     flag_bits |= LIBLLDB_LOG_DEFAULT;
            else if (0 == ::strcasecmp(arg, "dyld"))        flag_bits |= LIBLLDB_LOG_DYNAMIC_LOADER;
            else if (0 == ::strncasecmp(arg, "event", 5))   flag_bits |= LIBLLDB_LOG_EVENTS;
            else if (0 == ::strncasecmp(arg, "expr", 4))    flag_bits |= LIBLLDB_LOG_EXPRESSIONS;
            else if (0 == ::strncasecmp(arg, "object", 6))  flag_bits |= LIBLLDB_LOG_OBJECT;
            else if (0 == ::strcasecmp(arg, "process"))     flag_bits |= LIBLLDB_LOG_PROCESS;
            else if (0 == ::strcasecmp(arg, "script"))      flag_bits |= LIBLLDB_LOG_SCRIPT;
            else if (0 == ::strcasecmp(arg, "state"))       flag_bits |= LIBLLDB_LOG_STATE;
            else if (0 == ::strcasecmp(arg, "step"))        flag_bits |= LIBLLDB_LOG_STEP;
            else if (0 == ::strcasecmp(arg, "thread"))      flag_bits |= LIBLLDB_LOG_THREAD;
            else if (0 == ::strcasecmp(arg, "target"))      flag_bits |= LIBLLDB_LOG_TARGET;
            else if (0 == ::strcasecmp(arg, "verbose"))     flag_bits |= LIBLLDB_LOG_VERBOSE;
            else if (0 == ::strncasecmp(arg, "watch", 5))   flag_bits |= LIBLLDB_LOG_WATCHPOINTS;
            else if (0 == ::strncasecmp(arg, "temp", 4))    flag_bits |= LIBLLDB_LOG_TEMPORARY;
            else if (0 == ::strncasecmp(arg, "comm", 4))    flag_bits |= LIBLLDB_LOG_COMMUNICATION;
            else if (0 == ::strncasecmp(arg, "conn", 4))    flag_bits |= LIBLLDB_LOG_CONNECTION;
            else if (0 == ::strncasecmp(arg, "host", 4))    flag_bits |= LIBLLDB_LOG_HOST;
            else if (0 == ::strncasecmp(arg, "unwind", 6))  flag_bits |= LIBLLDB_LOG_UNWIND;
            else if (0 == ::strncasecmp(arg, "types", 5))   flag_bits |= LIBLLDB_LOG_TYPES;
            else if (0 == ::strncasecmp(arg, "symbol", 6))  flag_bits |= LIBLLDB_LOG_SYMBOLS;
            else if (0 == ::strncasecmp(arg, "module", 6))  flag_bits |= LIBLLDB_LOG_MODULES;
            else if (0 == ::strncasecmp(arg, "mmap", 4))    flag_bits |= LIBLLDB_LOG_MMAP;
            else
            {
                feedback_strm->Printf("error: unrecognized log category '%s'\n", arg);
                ListLogCategories (feedback_strm);
                return g_log;
            }
        }

        g_log->GetMask().Reset(flag_bits);
        g_log->GetOptions().Reset(log_options);
    }
    g_log_enabled = true;
    return g_log;
}

void
lldb_private::ListLogCategories (Stream *strm)
{
    strm->Printf("Logging categories for 'lldb':\n"
                 "  all - turn on all available logging categories\n"
                 "  api - enable logging of API calls and return values\n"
                 "  break - log breakpoints\n"
                 "  command - log command argument parsing\n"
                 "  default - enable the default set of logging categories for liblldb\n"
                 "  dyld - log shared library related activities\n"
                 "  events - log broadcaster, listener and event queue activities\n"
                 "  expr - log expressions\n"
                 "  object - log object construction/destruction for important objects\n"
                 "  module - log module activities such as when modules are created, detroyed, replaced, and more\n"
                 "  process - log process events and activities\n"
                 "  script - log events about the script interpreter\n"
                 "  state - log private and public process state changes\n"
                 "  step - log step related activities\n"
                 "  symbol - log symbol related issues and warnings\n"
                 "  target - log target events and activities\n"
                 "  thread - log thread events and activities\n"
                 "  types - log type system related activities\n"
                 "  unwind - log stack unwind activities\n"
                 "  verbose - enable verbose logging\n"
                 "  watch - log watchpoint related activities\n");
}
<commit_msg>Fixing lldb log list text for commands category<commit_after>//===-- lldb-log.cpp --------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/lldb-private-log.h"

// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Interpreter/Args.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/StreamFile.h"
#include <string.h>

using namespace lldb;
using namespace lldb_private;

// We want to avoid global constructors where code needs to be run so here we
// control access to our static g_log_sp by hiding it in a singleton function
// that will construct the static g_lob_sp the first time this function is
// called.

static bool g_log_enabled = false;
static Log * g_log = NULL;
static Log *
GetLog ()
{
    if (!g_log_enabled)
        return NULL;
    return g_log;
}

uint32_t
lldb_private::GetLogMask ()
{
    Log *log(GetLog ());
    if (log)
        return log->GetMask().Get();
    return 0;
}

bool
lldb_private::IsLogVerbose ()
{
    uint32_t mask = GetLogMask();
    return (mask & LIBLLDB_LOG_VERBOSE);
}

Log *
lldb_private::GetLogIfAllCategoriesSet (uint32_t mask)
{
    Log *log(GetLog ());
    if (log && mask)
    {
        uint32_t log_mask = log->GetMask().Get();
        if ((log_mask & mask) != mask)
            return NULL;
    }
    return log;
}

void
lldb_private::LogIfAllCategoriesSet (uint32_t mask, const char *format, ...)
{
    Log *log(GetLogIfAllCategoriesSet (mask));
    if (log)
    {
        va_list args;
        va_start (args, format);
        log->VAPrintf (format, args);
        va_end (args);
    }
}

void
lldb_private::LogIfAnyCategoriesSet (uint32_t mask, const char *format, ...)
{
    Log *log(GetLogIfAnyCategoriesSet (mask));
    if (log)
    {
        va_list args;
        va_start (args, format);
        log->VAPrintf (format, args);
        va_end (args);
    }
}

Log *
lldb_private::GetLogIfAnyCategoriesSet (uint32_t mask)
{
    Log *log(GetLog ());
    if (log && mask && (mask & log->GetMask().Get()))
        return log;
    return NULL;
}

void
lldb_private::DisableLog (const char **categories, Stream *feedback_strm)
{
    Log *log(GetLog ());

    if (log)
    {
        uint32_t flag_bits = 0;
        if (categories[0] != NULL)
        {
            flag_bits = log->GetMask().Get();
            for (size_t i = 0; categories[i] != NULL; ++i)
            {
                const char *arg = categories[i];

                if      (0 == ::strcasecmp(arg, "all"))         flag_bits &= ~LIBLLDB_LOG_ALL;
                else if (0 == ::strcasecmp(arg, "api"))         flag_bits &= ~LIBLLDB_LOG_API;
                else if (0 == ::strncasecmp(arg, "break", 5))   flag_bits &= ~LIBLLDB_LOG_BREAKPOINTS;
                else if (0 == ::strcasecmp(arg, "commands"))    flag_bits &= ~LIBLLDB_LOG_COMMANDS;
                else if (0 == ::strcasecmp(arg, "default"))     flag_bits &= ~LIBLLDB_LOG_DEFAULT;
                else if (0 == ::strcasecmp(arg, "dyld"))        flag_bits &= ~LIBLLDB_LOG_DYNAMIC_LOADER;
                else if (0 == ::strncasecmp(arg, "event", 5))   flag_bits &= ~LIBLLDB_LOG_EVENTS;
                else if (0 == ::strncasecmp(arg, "expr", 4))    flag_bits &= ~LIBLLDB_LOG_EXPRESSIONS;
                else if (0 == ::strncasecmp(arg, "object", 6))  flag_bits &= ~LIBLLDB_LOG_OBJECT;
                else if (0 == ::strcasecmp(arg, "process"))     flag_bits &= ~LIBLLDB_LOG_PROCESS;
                else if (0 == ::strcasecmp(arg, "script"))      flag_bits &= ~LIBLLDB_LOG_SCRIPT;
                else if (0 == ::strcasecmp(arg, "state"))       flag_bits &= ~LIBLLDB_LOG_STATE;
                else if (0 == ::strcasecmp(arg, "step"))        flag_bits &= ~LIBLLDB_LOG_STEP;
                else if (0 == ::strcasecmp(arg, "thread"))      flag_bits &= ~LIBLLDB_LOG_THREAD;
                else if (0 == ::strcasecmp(arg, "target"))      flag_bits &= ~LIBLLDB_LOG_TARGET;
                else if (0 == ::strcasecmp(arg, "verbose"))     flag_bits &= ~LIBLLDB_LOG_VERBOSE;
                else if (0 == ::strncasecmp(arg, "watch", 5))   flag_bits &= ~LIBLLDB_LOG_WATCHPOINTS;
                else if (0 == ::strncasecmp(arg, "temp", 4))    flag_bits &= ~LIBLLDB_LOG_TEMPORARY;
                else if (0 == ::strncasecmp(arg, "comm", 4))    flag_bits &= ~LIBLLDB_LOG_COMMUNICATION;
                else if (0 == ::strncasecmp(arg, "conn", 4))    flag_bits &= ~LIBLLDB_LOG_CONNECTION;
                else if (0 == ::strncasecmp(arg, "host", 4))    flag_bits &= ~LIBLLDB_LOG_HOST;
                else if (0 == ::strncasecmp(arg, "unwind", 6))  flag_bits &= ~LIBLLDB_LOG_UNWIND;
                else if (0 == ::strncasecmp(arg, "types", 5))   flag_bits &= ~LIBLLDB_LOG_TYPES;
                else if (0 == ::strncasecmp(arg, "symbol", 6))  flag_bits &= ~LIBLLDB_LOG_SYMBOLS;
                else if (0 == ::strncasecmp(arg, "module", 6))  flag_bits &= ~LIBLLDB_LOG_MODULES;
                else if (0 == ::strncasecmp(arg, "mmap", 4))    flag_bits &= ~LIBLLDB_LOG_MMAP;
                else
                {
                    feedback_strm->Printf ("error:  unrecognized log category '%s'\n", arg);
                    ListLogCategories (feedback_strm);
                    return;
                }

            }
        }
        log->GetMask().Reset (flag_bits);
        if (flag_bits == 0)
            g_log_enabled = false;
    }

    return;
}

Log *
lldb_private::EnableLog (StreamSP &log_stream_sp, uint32_t log_options, const char **categories, Stream *feedback_strm)
{
    // Try see if there already is a log - that way we can reuse its settings.
    // We could reuse the log in toto, but we don't know that the stream is the same.
    uint32_t flag_bits;
    if (g_log)
        flag_bits = g_log->GetMask().Get();
    else
        flag_bits = 0;

    // Now make a new log with this stream if one was provided
    if (log_stream_sp)
    {
        if (g_log)
            g_log->SetStream(log_stream_sp);
        else
            g_log = new Log(log_stream_sp);
    }

    if (g_log)
    {
        for (size_t i=0; categories[i] != NULL; ++i)
        {
            const char *arg = categories[i];

            if      (0 == ::strcasecmp(arg, "all"))         flag_bits |= LIBLLDB_LOG_ALL;
            else if (0 == ::strcasecmp(arg, "api"))         flag_bits |= LIBLLDB_LOG_API;
            else if (0 == ::strncasecmp(arg, "break", 5))   flag_bits |= LIBLLDB_LOG_BREAKPOINTS;
            else if (0 == ::strcasecmp(arg, "commands"))    flag_bits |= LIBLLDB_LOG_COMMANDS;
            else if (0 == ::strcasecmp(arg, "default"))     flag_bits |= LIBLLDB_LOG_DEFAULT;
            else if (0 == ::strcasecmp(arg, "dyld"))        flag_bits |= LIBLLDB_LOG_DYNAMIC_LOADER;
            else if (0 == ::strncasecmp(arg, "event", 5))   flag_bits |= LIBLLDB_LOG_EVENTS;
            else if (0 == ::strncasecmp(arg, "expr", 4))    flag_bits |= LIBLLDB_LOG_EXPRESSIONS;
            else if (0 == ::strncasecmp(arg, "object", 6))  flag_bits |= LIBLLDB_LOG_OBJECT;
            else if (0 == ::strcasecmp(arg, "process"))     flag_bits |= LIBLLDB_LOG_PROCESS;
            else if (0 == ::strcasecmp(arg, "script"))      flag_bits |= LIBLLDB_LOG_SCRIPT;
            else if (0 == ::strcasecmp(arg, "state"))       flag_bits |= LIBLLDB_LOG_STATE;
            else if (0 == ::strcasecmp(arg, "step"))        flag_bits |= LIBLLDB_LOG_STEP;
            else if (0 == ::strcasecmp(arg, "thread"))      flag_bits |= LIBLLDB_LOG_THREAD;
            else if (0 == ::strcasecmp(arg, "target"))      flag_bits |= LIBLLDB_LOG_TARGET;
            else if (0 == ::strcasecmp(arg, "verbose"))     flag_bits |= LIBLLDB_LOG_VERBOSE;
            else if (0 == ::strncasecmp(arg, "watch", 5))   flag_bits |= LIBLLDB_LOG_WATCHPOINTS;
            else if (0 == ::strncasecmp(arg, "temp", 4))    flag_bits |= LIBLLDB_LOG_TEMPORARY;
            else if (0 == ::strncasecmp(arg, "comm", 4))    flag_bits |= LIBLLDB_LOG_COMMUNICATION;
            else if (0 == ::strncasecmp(arg, "conn", 4))    flag_bits |= LIBLLDB_LOG_CONNECTION;
            else if (0 == ::strncasecmp(arg, "host", 4))    flag_bits |= LIBLLDB_LOG_HOST;
            else if (0 == ::strncasecmp(arg, "unwind", 6))  flag_bits |= LIBLLDB_LOG_UNWIND;
            else if (0 == ::strncasecmp(arg, "types", 5))   flag_bits |= LIBLLDB_LOG_TYPES;
            else if (0 == ::strncasecmp(arg, "symbol", 6))  flag_bits |= LIBLLDB_LOG_SYMBOLS;
            else if (0 == ::strncasecmp(arg, "module", 6))  flag_bits |= LIBLLDB_LOG_MODULES;
            else if (0 == ::strncasecmp(arg, "mmap", 4))    flag_bits |= LIBLLDB_LOG_MMAP;
            else
            {
                feedback_strm->Printf("error: unrecognized log category '%s'\n", arg);
                ListLogCategories (feedback_strm);
                return g_log;
            }
        }

        g_log->GetMask().Reset(flag_bits);
        g_log->GetOptions().Reset(log_options);
    }
    g_log_enabled = true;
    return g_log;
}

void
lldb_private::ListLogCategories (Stream *strm)
{
    strm->Printf("Logging categories for 'lldb':\n"
                 "  all - turn on all available logging categories\n"
                 "  api - enable logging of API calls and return values\n"
                 "  break - log breakpoints\n"
                 "  commands - log command argument parsing\n"
                 "  default - enable the default set of logging categories for liblldb\n"
                 "  dyld - log shared library related activities\n"
                 "  events - log broadcaster, listener and event queue activities\n"
                 "  expr - log expressions\n"
                 "  object - log object construction/destruction for important objects\n"
                 "  module - log module activities such as when modules are created, detroyed, replaced, and more\n"
                 "  process - log process events and activities\n"
                 "  script - log events about the script interpreter\n"
                 "  state - log private and public process state changes\n"
                 "  step - log step related activities\n"
                 "  symbol - log symbol related issues and warnings\n"
                 "  target - log target events and activities\n"
                 "  thread - log thread events and activities\n"
                 "  types - log type system related activities\n"
                 "  unwind - log stack unwind activities\n"
                 "  verbose - enable verbose logging\n"
                 "  watch - log watchpoint related activities\n");
}
<|endoftext|>


<commit_before>// @(#)root/pyroot:$Id$
// Author: Wim Lavrijsen, Jan 2005

// Bindings
#include "PyROOT.h"
#include "PyStrings.h"
#include "PropertyProxy.h"
#include "ObjectProxy.h"
#include "PyBufferFactory.h"
#include "RootWrapper.h"

// ROOT
#include "TROOT.h"
#include "TClass.h"
#include "TDataMember.h"
#include "TGlobal.h"
#include "TDataType.h"
#include "TClassEdit.h"

// CINT
#include "Api.h"

namespace PyROOT {

namespace {

//= PyROOT property proxy property behaviour =================================
   PyObject* pp_get( PropertyProxy* pyprop, ObjectProxy* pyobj, PyObject* )
   {
   // normal getter access
      Long_t address = pyprop->GetAddress( pyobj );
      if ( PyErr_Occurred() )
         return 0;

   // not-initialized or public data accesses through class (e.g. by help())
      if ( ! address ) {
         Py_INCREF( pyprop );
         return (PyObject*)pyprop;
      }

   // for fixed size arrays
      void* ptr = (void*)address;
      if ( pyprop->fProperty & kIsArray )
         ptr = &address;

      if ( pyprop->fConverter != 0 ) {
         PyObject* result = pyprop->fConverter->FromMemory( ptr );
         if ( ! result )
            return result;

         // ensure that the encapsulating class does not go away for the duration
         // of the data member's lifetime, if it is a bound type (it doesn't matter
         // for builtin types, b/c those are copied over into python types and thus
         // end up being "stand-alone")
         if ( ObjectProxy_Check( result ) ) {
            if ( PyObject_SetAttr( result, PyStrings::gLifeLine, (PyObject*)pyobj ) == -1 )
               PyErr_Clear();     // ignored
         }
         return result;
      }

      PyErr_Format( PyExc_NotImplementedError,
         "no converter available for \"%s\"", pyprop->GetName().c_str() );
      return 0;
   }

//____________________________________________________________________________
   int pp_set( PropertyProxy* pyprop, ObjectProxy* pyobj, PyObject* value )
   {
      const int errret = -1;

   // filter const objects and enums to prevent changing their values
      if ( ( pyprop->fProperty & kIsConstant ) ||
           ( ! ( ~pyprop->fProperty & ( kIsEnum | G__BIT_ISSTATIC ) ) ) ) {
         PyErr_SetString( PyExc_TypeError, "assignment to const data not allowed" );
         return errret;
      }

      Long_t address = pyprop->GetAddress( pyobj );
      if ( ! address || PyErr_Occurred() )
         return errret;

   // for fixed size arrays
      void* ptr = (void*)address;
      if ( pyprop->fProperty & kIsArray )
         ptr = &address;

   // actual conversion; return on success
      if ( pyprop->fConverter && pyprop->fConverter->ToMemory( value, ptr ) )
         return 0;

   // set a python error, if not already done
      if ( ! PyErr_Occurred() )
         PyErr_SetString( PyExc_RuntimeError, "property type mismatch or assignment not allowed" );

   // failure ...
      return errret;
   }

//= PyROOT property proxy construction/destruction ===========================
   PropertyProxy* pp_new( PyTypeObject* pytype, PyObject*, PyObject* )
   {
      PropertyProxy* pyprop = (PropertyProxy*)pytype->tp_alloc( pytype, 0 );
      pyprop->fConverter = 0;
      new ( &pyprop->fName ) std::string();

      return pyprop;
   }

//____________________________________________________________________________
   void pp_dealloc( PropertyProxy* pyprop )
   {
      using namespace std;
      pyprop->fName.~string();
      delete pyprop->fConverter;
      Py_TYPE(pyprop)->tp_free( (PyObject*)pyprop );
   }

} // unnamed namespace

//= PyROOT property proxy type ===============================================
PyTypeObject PropertyProxy_Type = {
   PyVarObject_HEAD_INIT( &PyType_Type, 0 )
   (char*)"ROOT.PropertyProxy",                  // tp_name
   sizeof(PropertyProxy),     // tp_basicsize
   0,                         // tp_itemsize
   (destructor)pp_dealloc,    // tp_dealloc
   0,                         // tp_print
   0,                         // tp_getattr
   0,                         // tp_setattr
   0,                         // tp_compare
   0,                         // tp_repr
   0,                         // tp_as_number
   0,                         // tp_as_sequence
   0,                         // tp_as_mapping
   0,                         // tp_hash
   0,                         // tp_call
   0,                         // tp_str
   0,                         // tp_getattro
   0,                         // tp_setattro
   0,                         // tp_as_buffer
   Py_TPFLAGS_DEFAULT,        // tp_flags
   (char*)"PyROOT property proxy (internal)",    // tp_doc
   0,                         // tp_traverse
   0,                         // tp_clear
   0,                         // tp_richcompare
   0,                         // tp_weaklistoffset
   0,                         // tp_iter
   0,                         // tp_iternext
   0,                         // tp_methods
   0,                         // tp_members
   0,                         // tp_getset
   0,                         // tp_base
   0,                         // tp_dict
   (descrgetfunc)pp_get,      // tp_descr_get
   (descrsetfunc)pp_set,      // tp_descr_set
   0,                         // tp_dictoffset
   0,                         // tp_init
   0,                         // tp_alloc
   (newfunc)pp_new,           // tp_new
   0,                         // tp_free
   0,                         // tp_is_gc
   0,                         // tp_bases
   0,                         // tp_mro
   0,                         // tp_cache
   0,                         // tp_subclasses
   0                          // tp_weaklist
#if PY_VERSION_HEX >= 0x02030000
   , 0                        // tp_del
#endif
#if PY_VERSION_HEX >= 0x02060000
   , 0                        // tp_version_tag
#endif
};

} // namespace PyROOT

//- public members -----------------------------------------------------------
void PyROOT::PropertyProxy::Set( TDataMember* dm )
{
// initialize from <dm> info
   fOffset    = dm->GetOffsetCint();
   std::string fullType = dm->GetFullTypeName();
   if ( (int)dm->GetArrayDim() != 0 || ( ! dm->IsBasic() && dm->IsaPointer() ) ) {
      fullType.append( "*" );
   }
   fProperty  = (Long_t)dm->Property();

// workaround for bug affecting "using" declared data members:
   if ( (fProperty & kIsStatic) && /* with offset smaller than class size, can't be static! */
        fOffset < ((G__ClassInfo*)dm->GetClass()->GetClassInfo())->Size() )
      fProperty &= ~kIsStatic;

   fConverter = CreateConverter( fullType, dm->GetMaxIndex( 0 ) );
   fName      = dm->GetName();

   if ( dm->GetClass()->GetClassInfo() ) {
      fOwnerTagnum = ((G__ClassInfo*)dm->GetClass()->GetClassInfo())->Tagnum();
      fOwnerIsNamespace = ((G__ClassInfo*)dm->GetClass()->GetClassInfo())->Property() & G__BIT_ISNAMESPACE;
   }
}

//____________________________________________________________________________
void PyROOT::PropertyProxy::Set( TGlobal* gbl )
{
// initialize from <gbl> info
   fOffset    = (Long_t)gbl->GetAddress();
   fProperty  = gbl->Property() | kIsStatic;    // force static flag
   std::string fullType = gbl->GetFullTypeName();
   if ( fullType == "void*" ) // actually treated as address to void*
      fullType = "void**";
   if ( (int)gbl->GetArrayDim() != 0 ) {
      fullType.append( "*" );
   }
   fConverter = CreateConverter( fullType, gbl->GetMaxIndex( 0 ) );
   fName      = gbl->GetName();

// no owner (global scope)
   fOwnerTagnum = -1;
   fOwnerIsNamespace = 0;
}

//____________________________________________________________________________
#ifdef PYROOT_USE_REFLEX
void PyROOT::PropertyProxy::Set( const ROOT::Reflex::Member& mb )
{
// initialize from Reflex <mb> info
   fOffset    = (Long_t)mb.Offset();
   fProperty  = ( mb.IsStatic()         ? kIsStatic : 0 ) |
                ( mb.TypeOf().IsEnum()  ? kIsEnum   : 0 ) |
                ( mb.TypeOf().IsArray() ? kIsArray  : 0 );
   fConverter = CreateConverter( mb.TypeOf().Name( ROOT::Reflex::SCOPED | ROOT::Reflex::FINAL ) );
   fName      = mb.Name();

// unknown owner (TODO: handle this case)
   fOwnerTagnum = -1;
   fOwnerIsNamespace = 0;
}
#endif

//____________________________________________________________________________
Long_t PyROOT::PropertyProxy::GetAddress( ObjectProxy* pyobj ) {
// class attributes, global properties
   if ( (fProperty & kIsStatic) || ( (fOwnerTagnum > -1) && fOwnerIsNamespace ) )
      return fOffset;

// special case: non-static lookup through class
   if ( ! pyobj )
      return 0;

// instance attributes; requires valid object for full address
   if ( ! ObjectProxy_Check( pyobj ) ) {
      PyErr_Format( PyExc_TypeError,
         "object instance required for access to property \"%s\"", GetName().c_str() );
      return 0;
   }

   void* obj = pyobj->GetObject();
   if ( ! obj ) {
      PyErr_SetString( PyExc_ReferenceError, "attempt to access a null-pointer" );
      return 0;
   }

   Long_t offset = 0;
   if ( 0 < fOwnerTagnum ) {
      Int_t realTagnum = ((G__ClassInfo*)pyobj->ObjectIsA()->GetClassInfo())->Tagnum();
      if ( fOwnerTagnum != realTagnum )
         offset = G__isanybase( fOwnerTagnum, realTagnum, (Long_t)obj );
   }

   return (Long_t)obj + offset + fOffset;
}
<commit_msg>only fixup kIsStatic for classes, not for namespaces<commit_after>// @(#)root/pyroot:$Id$
// Author: Wim Lavrijsen, Jan 2005

// Bindings
#include "PyROOT.h"
#include "PyStrings.h"
#include "PropertyProxy.h"
#include "ObjectProxy.h"
#include "PyBufferFactory.h"
#include "RootWrapper.h"

// ROOT
#include "TROOT.h"
#include "TClass.h"
#include "TDataMember.h"
#include "TGlobal.h"
#include "TDataType.h"
#include "TClassEdit.h"

// CINT
#include "Api.h"

namespace PyROOT {

namespace {

//= PyROOT property proxy property behaviour =================================
   PyObject* pp_get( PropertyProxy* pyprop, ObjectProxy* pyobj, PyObject* )
   {
   // normal getter access
      Long_t address = pyprop->GetAddress( pyobj );
      if ( PyErr_Occurred() )
         return 0;

   // not-initialized or public data accesses through class (e.g. by help())
      if ( ! address ) {
         Py_INCREF( pyprop );
         return (PyObject*)pyprop;
      }

   // for fixed size arrays
      void* ptr = (void*)address;
      if ( pyprop->fProperty & kIsArray )
         ptr = &address;

      if ( pyprop->fConverter != 0 ) {
         PyObject* result = pyprop->fConverter->FromMemory( ptr );
         if ( ! result )
            return result;

         // ensure that the encapsulating class does not go away for the duration
         // of the data member's lifetime, if it is a bound type (it doesn't matter
         // for builtin types, b/c those are copied over into python types and thus
         // end up being "stand-alone")
         if ( ObjectProxy_Check( result ) ) {
            if ( PyObject_SetAttr( result, PyStrings::gLifeLine, (PyObject*)pyobj ) == -1 )
               PyErr_Clear();     // ignored
         }
         return result;
      }

      PyErr_Format( PyExc_NotImplementedError,
         "no converter available for \"%s\"", pyprop->GetName().c_str() );
      return 0;
   }

//____________________________________________________________________________
   int pp_set( PropertyProxy* pyprop, ObjectProxy* pyobj, PyObject* value )
   {
      const int errret = -1;

   // filter const objects and enums to prevent changing their values
      if ( ( pyprop->fProperty & kIsConstant ) ||
           ( ! ( ~pyprop->fProperty & ( kIsEnum | G__BIT_ISSTATIC ) ) ) ) {
         PyErr_SetString( PyExc_TypeError, "assignment to const data not allowed" );
         return errret;
      }

      Long_t address = pyprop->GetAddress( pyobj );
      if ( ! address || PyErr_Occurred() )
         return errret;

   // for fixed size arrays
      void* ptr = (void*)address;
      if ( pyprop->fProperty & kIsArray )
         ptr = &address;

   // actual conversion; return on success
      if ( pyprop->fConverter && pyprop->fConverter->ToMemory( value, ptr ) )
         return 0;

   // set a python error, if not already done
      if ( ! PyErr_Occurred() )
         PyErr_SetString( PyExc_RuntimeError, "property type mismatch or assignment not allowed" );

   // failure ...
      return errret;
   }

//= PyROOT property proxy construction/destruction ===========================
   PropertyProxy* pp_new( PyTypeObject* pytype, PyObject*, PyObject* )
   {
      PropertyProxy* pyprop = (PropertyProxy*)pytype->tp_alloc( pytype, 0 );
      pyprop->fConverter = 0;
      new ( &pyprop->fName ) std::string();

      return pyprop;
   }

//____________________________________________________________________________
   void pp_dealloc( PropertyProxy* pyprop )
   {
      using namespace std;
      pyprop->fName.~string();
      delete pyprop->fConverter;
      Py_TYPE(pyprop)->tp_free( (PyObject*)pyprop );
   }

} // unnamed namespace

//= PyROOT property proxy type ===============================================
PyTypeObject PropertyProxy_Type = {
   PyVarObject_HEAD_INIT( &PyType_Type, 0 )
   (char*)"ROOT.PropertyProxy",                  // tp_name
   sizeof(PropertyProxy),     // tp_basicsize
   0,                         // tp_itemsize
   (destructor)pp_dealloc,    // tp_dealloc
   0,                         // tp_print
   0,                         // tp_getattr
   0,                         // tp_setattr
   0,                         // tp_compare
   0,                         // tp_repr
   0,                         // tp_as_number
   0,                         // tp_as_sequence
   0,                         // tp_as_mapping
   0,                         // tp_hash
   0,                         // tp_call
   0,                         // tp_str
   0,                         // tp_getattro
   0,                         // tp_setattro
   0,                         // tp_as_buffer
   Py_TPFLAGS_DEFAULT,        // tp_flags
   (char*)"PyROOT property proxy (internal)",    // tp_doc
   0,                         // tp_traverse
   0,                         // tp_clear
   0,                         // tp_richcompare
   0,                         // tp_weaklistoffset
   0,                         // tp_iter
   0,                         // tp_iternext
   0,                         // tp_methods
   0,                         // tp_members
   0,                         // tp_getset
   0,                         // tp_base
   0,                         // tp_dict
   (descrgetfunc)pp_get,      // tp_descr_get
   (descrsetfunc)pp_set,      // tp_descr_set
   0,                         // tp_dictoffset
   0,                         // tp_init
   0,                         // tp_alloc
   (newfunc)pp_new,           // tp_new
   0,                         // tp_free
   0,                         // tp_is_gc
   0,                         // tp_bases
   0,                         // tp_mro
   0,                         // tp_cache
   0,                         // tp_subclasses
   0                          // tp_weaklist
#if PY_VERSION_HEX >= 0x02030000
   , 0                        // tp_del
#endif
#if PY_VERSION_HEX >= 0x02060000
   , 0                        // tp_version_tag
#endif
};

} // namespace PyROOT

//- public members -----------------------------------------------------------
void PyROOT::PropertyProxy::Set( TDataMember* dm )
{
// initialize from <dm> info
   fOffset    = dm->GetOffsetCint();
   std::string fullType = dm->GetFullTypeName();
   if ( (int)dm->GetArrayDim() != 0 || ( ! dm->IsBasic() && dm->IsaPointer() ) ) {
      fullType.append( "*" );
   }
   fProperty  = (Long_t)dm->Property();

// workaround for bug affecting "using" declared data members:
   if ( (fProperty & kIsStatic) && (fProperty & (kIsClass|kIsStruct))
        && fOffset < ((G__ClassInfo*)dm->GetClass()->GetClassInfo())->Size() ) {
   // with offset smaller than class size, can't be static!
      fProperty &= ~kIsStatic;
   }

   fConverter = CreateConverter( fullType, dm->GetMaxIndex( 0 ) );
   fName      = dm->GetName();

   if ( dm->GetClass()->GetClassInfo() ) {
      fOwnerTagnum = ((G__ClassInfo*)dm->GetClass()->GetClassInfo())->Tagnum();
      fOwnerIsNamespace = ((G__ClassInfo*)dm->GetClass()->GetClassInfo())->Property() & G__BIT_ISNAMESPACE;
   }
}

//____________________________________________________________________________
void PyROOT::PropertyProxy::Set( TGlobal* gbl )
{
// initialize from <gbl> info
   fOffset    = (Long_t)gbl->GetAddress();
   fProperty  = gbl->Property() | kIsStatic;    // force static flag
   std::string fullType = gbl->GetFullTypeName();
   if ( fullType == "void*" ) // actually treated as address to void*
      fullType = "void**";
   if ( (int)gbl->GetArrayDim() != 0 ) {
      fullType.append( "*" );
   }
   fConverter = CreateConverter( fullType, gbl->GetMaxIndex( 0 ) );
   fName      = gbl->GetName();

// no owner (global scope)
   fOwnerTagnum = -1;
   fOwnerIsNamespace = 0;
}

//____________________________________________________________________________
#ifdef PYROOT_USE_REFLEX
void PyROOT::PropertyProxy::Set( const ROOT::Reflex::Member& mb )
{
// initialize from Reflex <mb> info
   fOffset    = (Long_t)mb.Offset();
   fProperty  = ( mb.IsStatic()         ? kIsStatic : 0 ) |
                ( mb.TypeOf().IsEnum()  ? kIsEnum   : 0 ) |
                ( mb.TypeOf().IsArray() ? kIsArray  : 0 );
   fConverter = CreateConverter( mb.TypeOf().Name( ROOT::Reflex::SCOPED | ROOT::Reflex::FINAL ) );
   fName      = mb.Name();

// unknown owner (TODO: handle this case)
   fOwnerTagnum = -1;
   fOwnerIsNamespace = 0;
}
#endif

//____________________________________________________________________________
Long_t PyROOT::PropertyProxy::GetAddress( ObjectProxy* pyobj ) {
// class attributes, global properties
   if ( (fProperty & kIsStatic) || ( (fOwnerTagnum > -1) && fOwnerIsNamespace ) )
      return fOffset;

// special case: non-static lookup through class
   if ( ! pyobj )
      return 0;

// instance attributes; requires valid object for full address
   if ( ! ObjectProxy_Check( pyobj ) ) {
      PyErr_Format( PyExc_TypeError,
         "object instance required for access to property \"%s\"", GetName().c_str() );
      return 0;
   }

   void* obj = pyobj->GetObject();
   if ( ! obj ) {
      PyErr_SetString( PyExc_ReferenceError, "attempt to access a null-pointer" );
      return 0;
   }

   Long_t offset = 0;
   if ( 0 < fOwnerTagnum ) {
      Int_t realTagnum = ((G__ClassInfo*)pyobj->ObjectIsA()->GetClassInfo())->Tagnum();
      if ( fOwnerTagnum != realTagnum )
         offset = G__isanybase( fOwnerTagnum, realTagnum, (Long_t)obj );
   }

   return (Long_t)obj + offset + fOffset;
}
<|endoftext|>


<commit_before>// @(#)root/pyroot:$Id$
// Author: Wim Lavrijsen, Jan 2005

// Bindings
#include "PyROOT.h"
#include "PyStrings.h"
#include "PropertyProxy.h"
#include "ObjectProxy.h"
#include "PyBufferFactory.h"
#include "RootWrapper.h"

// ROOT
#include "TROOT.h"
#include "TClass.h"
#include "TDataMember.h"
#include "TGlobal.h"
#include "TDataType.h"
#include "TClassEdit.h"
#include "TInterpreter.h"

namespace PyROOT {

namespace {

//= PyROOT property proxy property behaviour =================================
   PyObject* pp_get( PropertyProxy* pyprop, ObjectProxy* pyobj, PyObject* )
   {
   // normal getter access
      Long_t address = pyprop->GetAddress( pyobj );
      if ( PyErr_Occurred() )
         return 0;

   // not-initialized or public data accesses through class (e.g. by help())
      if ( ! address || address == -1 /* Cling error */ ) {
         Py_INCREF( pyprop );
         return (PyObject*)pyprop;
      }

   // for fixed size arrays
      void* ptr = (void*)address;
      if ( pyprop->fProperty & kIsArray )
         ptr = &address;

      if ( pyprop->fConverter != 0 ) {
         PyObject* result = pyprop->fConverter->FromMemory( ptr );
         if ( ! result )
            return result;

         // ensure that the encapsulating class does not go away for the duration
         // of the data member's lifetime, if it is a bound type (it doesn't matter
         // for builtin types, b/c those are copied over into python types and thus
         // end up being "stand-alone")
         if ( ObjectProxy_Check( result ) ) {
            if ( PyObject_SetAttr( result, PyStrings::gLifeLine, (PyObject*)pyobj ) == -1 )
               PyErr_Clear();     // ignored
         }
         return result;
      }

      PyErr_Format( PyExc_NotImplementedError,
         "no converter available for \"%s\"", pyprop->GetName().c_str() );
      return 0;
   }

//____________________________________________________________________________
   int pp_set( PropertyProxy* pyprop, ObjectProxy* pyobj, PyObject* value )
   {
   // Set the value of the C++ datum held.
      const int errret = -1;

   // filter const objects and enums to prevent changing their values
      if ( ( pyprop->fProperty & kIsConstant ) ||
           ( ! ( ~pyprop->fProperty & ( kIsEnum | kIsStatic ) ) ) ) {
         PyErr_SetString( PyExc_TypeError, "assignment to const data not allowed" );
         return errret;
      }

      Long_t address = pyprop->GetAddress( pyobj );
      if ( ! address || address == -1 /* Cling error */ || PyErr_Occurred() )
         return errret;

   // for fixed size arrays
      void* ptr = (void*)address;
      if ( pyprop->fProperty & kIsArray )
         ptr = &address;

   // actual conversion; return on success
      if ( pyprop->fConverter && pyprop->fConverter->ToMemory( value, ptr ) )
         return 0;

   // set a python error, if not already done
      if ( ! PyErr_Occurred() )
         PyErr_SetString( PyExc_RuntimeError, "property type mismatch or assignment not allowed" );

   // failure ...
      return errret;
   }

//= PyROOT property proxy construction/destruction ===========================
   PropertyProxy* pp_new( PyTypeObject* pytype, PyObject*, PyObject* )
   {
   // Create and initialize a new property descriptor.
      PropertyProxy* pyprop = (PropertyProxy*)pytype->tp_alloc( pytype, 0 );
      pyprop->fConverter = 0;
      new ( &pyprop->fName ) std::string();

      return pyprop;
   }

//____________________________________________________________________________
   void pp_dealloc( PropertyProxy* pyprop )
   {
   // Deallocate memory held by this descriptor.
      using namespace std;
      pyprop->fName.~string();
      delete pyprop->fConverter;
      Py_TYPE(pyprop)->tp_free( (PyObject*)pyprop );
   }

} // unnamed namespace

//= PyROOT property proxy type ===============================================
PyTypeObject PropertyProxy_Type = {
   PyVarObject_HEAD_INIT( &PyType_Type, 0 )
   (char*)"ROOT.PropertyProxy",                  // tp_name
   sizeof(PropertyProxy),     // tp_basicsize
   0,                         // tp_itemsize
   (destructor)pp_dealloc,    // tp_dealloc
   0,                         // tp_print
   0,                         // tp_getattr
   0,                         // tp_setattr
   0,                         // tp_compare
   0,                         // tp_repr
   0,                         // tp_as_number
   0,                         // tp_as_sequence
   0,                         // tp_as_mapping
   0,                         // tp_hash
   0,                         // tp_call
   0,                         // tp_str
   0,                         // tp_getattro
   0,                         // tp_setattro
   0,                         // tp_as_buffer
   Py_TPFLAGS_DEFAULT,        // tp_flags
   (char*)"PyROOT property proxy (internal)",    // tp_doc
   0,                         // tp_traverse
   0,                         // tp_clear
   0,                         // tp_richcompare
   0,                         // tp_weaklistoffset
   0,                         // tp_iter
   0,                         // tp_iternext
   0,                         // tp_methods
   0,                         // tp_members
   0,                         // tp_getset
   0,                         // tp_base
   0,                         // tp_dict
   (descrgetfunc)pp_get,      // tp_descr_get
   (descrsetfunc)pp_set,      // tp_descr_set
   0,                         // tp_dictoffset
   0,                         // tp_init
   0,                         // tp_alloc
   (newfunc)pp_new,           // tp_new
   0,                         // tp_free
   0,                         // tp_is_gc
   0,                         // tp_bases
   0,                         // tp_mro
   0,                         // tp_cache
   0,                         // tp_subclasses
   0                          // tp_weaklist
#if PY_VERSION_HEX >= 0x02030000
   , 0                        // tp_del
#endif
#if PY_VERSION_HEX >= 0x02060000
   , 0                        // tp_version_tag
#endif
};

} // namespace PyROOT

//- public members -----------------------------------------------------------
void PyROOT::PropertyProxy::Set( TDataMember* dm )
{
// initialize from <dm> info
   fOffset    = dm->GetOffsetCint();
   std::string fullType = dm->GetFullTypeName();
   if ( (int)dm->GetArrayDim() != 0 || ( ! dm->IsBasic() && dm->IsaPointer() ) ) {
      fullType.append( "*" );
   }
   fProperty  = (Long_t)dm->Property();

   fConverter = CreateConverter( fullType, dm->GetMaxIndex( 0 ) );
   fName      = dm->GetName();

   if (dm->GetClass())
      fParent = (void*)dm->GetClass()->GetClassInfo();
   else
      fParent = NULL;    // namespaces
}

//____________________________________________________________________________
void PyROOT::PropertyProxy::Set( TGlobal* gbl )
{
// initialize from <gbl> info
   fOffset    = (Long_t)gbl->GetAddress();
   fProperty  = gbl->Property() | kIsStatic;    // force static flag
   std::string fullType = gbl->GetFullTypeName();
   if ( fullType == "void*" ) // actually treated as address to void*
      fullType = "void**";
   if ( (int)gbl->GetArrayDim() != 0 ) {
      fullType.append( "*" );
   }
   fConverter = CreateConverter( fullType, gbl->GetMaxIndex( 0 ) );
   fName      = gbl->GetName();

// no parent (global scope)
   fParent = 0;
}

//____________________________________________________________________________
Long_t PyROOT::PropertyProxy::GetAddress( ObjectProxy* pyobj ) {
// class attributes, global properties
   if ( (fProperty & kIsStatic) || fParent == 0 )
      return fOffset;

// special case: non-static lookup through class
   if ( ! pyobj )
      return 0;

// instance attributes; requires valid object for full address
   if ( ! ObjectProxy_Check( pyobj ) ) {
      PyErr_Format( PyExc_TypeError,
         "object instance required for access to property \"%s\"", GetName().c_str() );
      return 0;
   }

   void* obj = pyobj->GetObject();
   if ( ! obj ) {
      PyErr_SetString( PyExc_ReferenceError, "attempt to access a null-pointer" );
      return 0;
   }

   Long_t offset = 0;
   if ( fParent != (void*)(pyobj->ObjectIsA()->GetClassInfo()) ) {
   // TODO: figure out how to do this with Cling ...
      offset = 0;
   }

   return (Long_t)obj + offset + fOffset;
}
<commit_msg>workaround for #100740: base class offsets<commit_after>// @(#)root/pyroot:$Id$
// Author: Wim Lavrijsen, Jan 2005

// Bindings
#include "PyROOT.h"
#include "PyStrings.h"
#include "PropertyProxy.h"
#include "ObjectProxy.h"
#include "PyBufferFactory.h"
#include "RootWrapper.h"

// ROOT
#include "TROOT.h"
#include "TClass.h"
#include "TDataMember.h"
#include "TGlobal.h"
#include "TDataType.h"
#include "TClassEdit.h"
#include "TInterpreter.h"

#include <sstream>

namespace PyROOT {

namespace {

//= PyROOT property proxy property behaviour =================================
   PyObject* pp_get( PropertyProxy* pyprop, ObjectProxy* pyobj, PyObject* )
   {
   // normal getter access
      Long_t address = pyprop->GetAddress( pyobj );
      if ( PyErr_Occurred() )
         return 0;

   // not-initialized or public data accesses through class (e.g. by help())
      if ( ! address || address == -1 /* Cling error */ ) {
         Py_INCREF( pyprop );
         return (PyObject*)pyprop;
      }

   // for fixed size arrays
      void* ptr = (void*)address;
      if ( pyprop->fProperty & kIsArray )
         ptr = &address;

      if ( pyprop->fConverter != 0 ) {
         PyObject* result = pyprop->fConverter->FromMemory( ptr );
         if ( ! result )
            return result;

         // ensure that the encapsulating class does not go away for the duration
         // of the data member's lifetime, if it is a bound type (it doesn't matter
         // for builtin types, b/c those are copied over into python types and thus
         // end up being "stand-alone")
         if ( ObjectProxy_Check( result ) ) {
            if ( PyObject_SetAttr( result, PyStrings::gLifeLine, (PyObject*)pyobj ) == -1 )
               PyErr_Clear();     // ignored
         }
         return result;
      }

      PyErr_Format( PyExc_NotImplementedError,
         "no converter available for \"%s\"", pyprop->GetName().c_str() );
      return 0;
   }

//____________________________________________________________________________
   int pp_set( PropertyProxy* pyprop, ObjectProxy* pyobj, PyObject* value )
   {
   // Set the value of the C++ datum held.
      const int errret = -1;

   // filter const objects and enums to prevent changing their values
      if ( ( pyprop->fProperty & kIsConstant ) ||
           ( ! ( ~pyprop->fProperty & ( kIsEnum | kIsStatic ) ) ) ) {
         PyErr_SetString( PyExc_TypeError, "assignment to const data not allowed" );
         return errret;
      }

      Long_t address = pyprop->GetAddress( pyobj );
      if ( ! address || address == -1 /* Cling error */ || PyErr_Occurred() )
         return errret;

   // for fixed size arrays
      void* ptr = (void*)address;
      if ( pyprop->fProperty & kIsArray )
         ptr = &address;

   // actual conversion; return on success
      if ( pyprop->fConverter && pyprop->fConverter->ToMemory( value, ptr ) )
         return 0;

   // set a python error, if not already done
      if ( ! PyErr_Occurred() )
         PyErr_SetString( PyExc_RuntimeError, "property type mismatch or assignment not allowed" );

   // failure ...
      return errret;
   }

//= PyROOT property proxy construction/destruction ===========================
   PropertyProxy* pp_new( PyTypeObject* pytype, PyObject*, PyObject* )
   {
   // Create and initialize a new property descriptor.
      PropertyProxy* pyprop = (PropertyProxy*)pytype->tp_alloc( pytype, 0 );
      pyprop->fConverter = 0;
      new ( &pyprop->fName ) std::string();

      return pyprop;
   }

//____________________________________________________________________________
   void pp_dealloc( PropertyProxy* pyprop )
   {
   // Deallocate memory held by this descriptor.
      using namespace std;
      pyprop->fName.~string();
      delete pyprop->fConverter;
      Py_TYPE(pyprop)->tp_free( (PyObject*)pyprop );
   }

} // unnamed namespace

//= PyROOT property proxy type ===============================================
PyTypeObject PropertyProxy_Type = {
   PyVarObject_HEAD_INIT( &PyType_Type, 0 )
   (char*)"ROOT.PropertyProxy",                  // tp_name
   sizeof(PropertyProxy),     // tp_basicsize
   0,                         // tp_itemsize
   (destructor)pp_dealloc,    // tp_dealloc
   0,                         // tp_print
   0,                         // tp_getattr
   0,                         // tp_setattr
   0,                         // tp_compare
   0,                         // tp_repr
   0,                         // tp_as_number
   0,                         // tp_as_sequence
   0,                         // tp_as_mapping
   0,                         // tp_hash
   0,                         // tp_call
   0,                         // tp_str
   0,                         // tp_getattro
   0,                         // tp_setattro
   0,                         // tp_as_buffer
   Py_TPFLAGS_DEFAULT,        // tp_flags
   (char*)"PyROOT property proxy (internal)",    // tp_doc
   0,                         // tp_traverse
   0,                         // tp_clear
   0,                         // tp_richcompare
   0,                         // tp_weaklistoffset
   0,                         // tp_iter
   0,                         // tp_iternext
   0,                         // tp_methods
   0,                         // tp_members
   0,                         // tp_getset
   0,                         // tp_base
   0,                         // tp_dict
   (descrgetfunc)pp_get,      // tp_descr_get
   (descrsetfunc)pp_set,      // tp_descr_set
   0,                         // tp_dictoffset
   0,                         // tp_init
   0,                         // tp_alloc
   (newfunc)pp_new,           // tp_new
   0,                         // tp_free
   0,                         // tp_is_gc
   0,                         // tp_bases
   0,                         // tp_mro
   0,                         // tp_cache
   0,                         // tp_subclasses
   0                          // tp_weaklist
#if PY_VERSION_HEX >= 0x02030000
   , 0                        // tp_del
#endif
#if PY_VERSION_HEX >= 0x02060000
   , 0                        // tp_version_tag
#endif
};

} // namespace PyROOT

//- public members -----------------------------------------------------------
void PyROOT::PropertyProxy::Set( TDataMember* dm )
{
// initialize from <dm> info
   fOffset    = dm->GetOffsetCint();
   std::string fullType = dm->GetFullTypeName();
   if ( (int)dm->GetArrayDim() != 0 || ( ! dm->IsBasic() && dm->IsaPointer() ) ) {
      fullType.append( "*" );
   }
   fProperty  = (Long_t)dm->Property();

   fConverter = CreateConverter( fullType, dm->GetMaxIndex( 0 ) );
   fName      = dm->GetName();

   if (dm->GetClass())
      fParent = (void*)dm->GetClass()->GetClassInfo();
   else
      fParent = NULL;    // namespaces
}

//____________________________________________________________________________
void PyROOT::PropertyProxy::Set( TGlobal* gbl )
{
// initialize from <gbl> info
   fOffset    = (Long_t)gbl->GetAddress();
   fProperty  = gbl->Property() | kIsStatic;    // force static flag
   std::string fullType = gbl->GetFullTypeName();
   if ( fullType == "void*" ) // actually treated as address to void*
      fullType = "void**";
   if ( (int)gbl->GetArrayDim() != 0 ) {
      fullType.append( "*" );
   }
   fConverter = CreateConverter( fullType, gbl->GetMaxIndex( 0 ) );
   fName      = gbl->GetName();

// no parent (global scope)
   fParent = 0;
}

//____________________________________________________________________________
Long_t PyROOT::PropertyProxy::GetAddress( ObjectProxy* pyobj ) {
// class attributes, global properties
   if ( (fProperty & kIsStatic) || fParent == 0 )
      return fOffset;

// special case: non-static lookup through class
   if ( ! pyobj )
      return 0;

// instance attributes; requires valid object for full address
   if ( ! ObjectProxy_Check( pyobj ) ) {
      PyErr_Format( PyExc_TypeError,
         "object instance required for access to property \"%s\"", GetName().c_str() );
      return 0;
   }

   void* obj = pyobj->GetObject();
   if ( ! obj ) {
      PyErr_SetString( PyExc_ReferenceError, "attempt to access a null-pointer" );
      return 0;
   }

   Long_t offset = 0;
   if ( fParent != (void*)(pyobj->ObjectIsA()->GetClassInfo()) ) {
   // TODO: figure out how to do this efficiently with Cling, or lacking that
   //       at least memoize these results
      std::ostringstream interpcast;
      interpcast << "(long)(" << gInterpreter->ClassInfo_FullName( fParent ) << "*)("
                 << pyobj->ObjectIsA()->GetName() << "*)" << (void*)obj
                 << "-(long)(" << pyobj->ObjectIsA()->GetName() << "*)" << (void*)obj
                 << ";" << std::ends;
      offset = (Long_t)gROOT->ProcessLine(interpcast.str().c_str());
   }

   return (Long_t)obj + offset + fOffset;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$
// boost
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>
// stl
#include <sstream>
// mapnik
#include <mapnik/envelope.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/memory_datasource.hpp>

using mapnik::datasource;
using mapnik::point_datasource;

struct ds_pickle_suite : boost::python::pickle_suite
{
   static boost::python::tuple
   getinitargs(const datasource& ds)
   {
      mapnik::parameters params = ds.params();
      return boost::python::make_tuple(params);
   }
};

namespace
{
    //user-friendly wrapper that uses Python dictionary
    using namespace boost::python;
    boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d)
    {
        mapnik::parameters params;
        boost::python::list keys=d.keys();
        for (int i=0; i<len(keys); ++i)
        {
            std::string key = extract<std::string>(keys[i]);
            object obj = d[key];
            extract<std::string> ex0(obj);
            extract<int> ex1(obj);
            extract<double> ex2(obj);

            if (ex0.check())
            {
               params[key] = ex0();
            }
            else if (ex1.check())
            {
               params[key] = ex1();
            }
            else if (ex2.check())
            {
               params[key] = ex2();
            }
        }

        return mapnik::datasource_cache::create(params);
    }

    std::string describe(boost::shared_ptr<mapnik::datasource> const& ds)
    {
        std::stringstream ss;
        if (ds)
        {
            ss << ds->get_descriptor() << "\n";
        }
        else
        {
            ss << "Null\n";
        }
        return ss.str();
    }
}

void export_datasource()
{
    using namespace boost::python;

    class_<datasource,boost::shared_ptr<datasource>,
        boost::noncopyable>("Datasource",no_init)
        .def_pickle(ds_pickle_suite()
                )
        .def("envelope",&datasource::envelope)
        .def("descriptor",&datasource::get_descriptor) //todo
        .def("features",&datasource::features)
        .def("features_at_point",&datasource::features_at_point)
        .def("params",&datasource::params,return_value_policy<copy_const_reference>(),
             "The configuration parameters of the data source. "
             "These vary depending on the type of data source.")
        ;

    def("Describe",&describe);
    def("CreateDatasource",&create_datasource);

    class_<point_datasource, bases<datasource>, boost::noncopyable>("PointDatasource", init<>())
        .def("add_point",&point_datasource::add_point)
        ;
}
<commit_msg>formatting<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$
// boost
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>
// stl
#include <sstream>
// mapnik
#include <mapnik/envelope.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/memory_datasource.hpp>

using mapnik::datasource;
using mapnik::point_datasource;

struct ds_pickle_suite : boost::python::pickle_suite
{
   static boost::python::tuple
   getinitargs(const datasource& ds)
   {
      mapnik::parameters params = ds.params();
      return boost::python::make_tuple(params);
   }
};

namespace
{
    //user-friendly wrapper that uses Python dictionary
    using namespace boost::python;
    boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d)
    {
        mapnik::parameters params;
        boost::python::list keys=d.keys();
        for (int i=0; i<len(keys); ++i)
        {
            std::string key = extract<std::string>(keys[i]);
            object obj = d[key];
            extract<std::string> ex0(obj);
            extract<int> ex1(obj);
            extract<double> ex2(obj);

            if (ex0.check())
            {
               params[key] = ex0();
            }
            else if (ex1.check())
            {
               params[key] = ex1();
            }
            else if (ex2.check())
            {
               params[key] = ex2();
            }
        }

        return mapnik::datasource_cache::create(params);
    }

    std::string describe(boost::shared_ptr<mapnik::datasource> const& ds)
    {
        std::stringstream ss;
        if (ds)
        {
            ss << ds->get_descriptor() << "\n";
        }
        else
        {
            ss << "Null\n";
        }
        return ss.str();
    }
}

void export_datasource()
{
    using namespace boost::python;

    class_<datasource,boost::shared_ptr<datasource>,
        boost::noncopyable>("Datasource",no_init)
        .def_pickle(ds_pickle_suite())
        .def("envelope",&datasource::envelope)
        .def("descriptor",&datasource::get_descriptor) //todo
        .def("features",&datasource::features)
        .def("features_at_point",&datasource::features_at_point)
        .def("params",&datasource::params,return_value_policy<copy_const_reference>(),
             "The configuration parameters of the data source. "
             "These vary depending on the type of data source.")
        ;

    def("Describe",&describe);
    def("CreateDatasource",&create_datasource);

    class_<point_datasource, bases<datasource>, boost::noncopyable>("PointDatasource", init<>())
        .def("add_point",&point_datasource::add_point)
        ;
}
<|endoftext|>


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

// Completely disable for now.
#if 0

#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/ui_layout_test.h"

// TODO(jorlow): Enable these tests when we remove them from the
//               test_exceptions.txt file.
//static const char* kTopLevelFiles[] = {
  //"window-attributes-exist.html"
//};

// TODO(jorlow): Enable these tests when we remove them from the
//               test_exceptions.txt file.
static const char* kSubDirFiles[] = {
  "clear.html",
  "delete-removal.html",
  "enumerate-storage.html",
  "enumerate-with-length-and-key.html",
  //"iframe-events.html",
  //"index-get-and-set.html",
  //"onstorage-attribute-markup.html",
  //"onstorage-attribute-setattribute.html",
  //"localstorage/onstorage-attribute-setwindow.html",
  //"simple-events.html",
  "simple-usage.html",
  //"string-conversion.html",
//  "window-open.html"
};

class DOMStorageTest : public UILayoutTest {
 protected:
  DOMStorageTest()
      : UILayoutTest(),
        test_dir_(FilePath().AppendASCII("LayoutTests").
                  AppendASCII("storage").AppendASCII("domstorage"))
  {
  }

  virtual ~DOMStorageTest() { }

  virtual void SetUp() {
    launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
    launch_arguments_.AppendSwitch(switches::kEnableLocalStorage);
    launch_arguments_.AppendSwitch(switches::kEnableSessionStorage);
    UILayoutTest::SetUp();
  }

  FilePath test_dir_;
};

TEST_F(DOMStorageTest, DISABLED_DOMStorageLayoutTests) {
  // TODO(jorlow): Enable these tests when we remove them from the
  //               test_exceptions.txt file.
  //InitializeForLayoutTest(test_dir_, FilePath(), false);
  //for (size_t i=0; i<arraysize(kTopLevelFiles); ++i)
  //  RunLayoutTest(kTopLevelFiles[i], false, true);
}

TEST_F(DOMStorageTest, DISABLED_LocalStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"),
                          false);
  for (size_t i=0; i<arraysize(kSubDirFiles); ++i)
    RunLayoutTest(kSubDirFiles[i], false);
}

TEST_F(DOMStorageTest, DISABLED_SessionStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"),
                          false);
  for (size_t i=0; i<arraysize(kSubDirFiles); ++i)
    RunLayoutTest(kSubDirFiles[i], false);
}

#endif

<commit_msg>Re-enable the ui test based layout tests for DOM Storage.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/ui_layout_test.h"

// TODO(jorlow): Enable these tests when we remove them from the
//               test_exceptions.txt file.
//static const char* kTopLevelFiles[] = {
  //"window-attributes-exist.html"
//};

// TODO(jorlow): Enable these tests when we remove them from the
//               test_exceptions.txt file.
static const char* kSubDirFiles[] = {
  "clear.html",
  "delete-removal.html",
  "enumerate-storage.html",
  "enumerate-with-length-and-key.html",
  //"iframe-events.html",
  //"index-get-and-set.html",
  //"onstorage-attribute-markup.html",
  //"onstorage-attribute-setattribute.html",
  //"localstorage/onstorage-attribute-setwindow.html",
  //"simple-events.html",
  "simple-usage.html",
  //"string-conversion.html",
//  "window-open.html"
};

class DOMStorageTest : public UILayoutTest {
 protected:
  DOMStorageTest()
      : UILayoutTest(),
        test_dir_(FilePath().AppendASCII("LayoutTests").
                  AppendASCII("storage").AppendASCII("domstorage"))
  {
  }

  virtual ~DOMStorageTest() { }

  virtual void SetUp() {
    launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
    launch_arguments_.AppendSwitch(switches::kEnableLocalStorage);
    launch_arguments_.AppendSwitch(switches::kEnableSessionStorage);
    UILayoutTest::SetUp();
  }

  FilePath test_dir_;
};

TEST_F(DOMStorageTest, DOMStorageLayoutTests) {
  // TODO(jorlow): Enable these tests when we remove them from the
  //               test_exceptions.txt file.
  //InitializeForLayoutTest(test_dir_, FilePath(), false);
  //for (size_t i=0; i<arraysize(kTopLevelFiles); ++i)
  //  RunLayoutTest(kTopLevelFiles[i], false, true);
}

TEST_F(DOMStorageTest, LocalStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"),
                          false);
  for (size_t i=0; i<arraysize(kSubDirFiles); ++i)
    RunLayoutTest(kSubDirFiles[i], false);
}

TEST_F(DOMStorageTest, SessionStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"),
                          false);
  for (size_t i=0; i<arraysize(kSubDirFiles); ++i)
    RunLayoutTest(kSubDirFiles[i], false);
}

<|endoftext|>


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

#include "chrome/browser/sync/glue/extension_model_associator.h"

#include "base/logging.h"
#include "chrome/browser/sync/engine/syncapi.h"
#include "chrome/browser/sync/glue/extension_data.h"
#include "chrome/browser/sync/glue/extension_sync_traits.h"
#include "chrome/browser/sync/glue/extension_sync.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/protocol/extension_specifics.pb.h"
#include "chrome/browser/sync/syncable/nigori_util.h"
#include "content/browser/browser_thread.h"

namespace browser_sync {

ExtensionModelAssociator::ExtensionModelAssociator(
    const ExtensionSyncTraits& traits,
    ExtensionServiceInterface* extension_service,
    sync_api::UserShare* user_share)
    : traits_(traits), extension_service_(extension_service),
      user_share_(user_share) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(extension_service_);
  DCHECK(user_share_);
}

ExtensionModelAssociator::~ExtensionModelAssociator() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

bool ExtensionModelAssociator::AssociateModels() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  ExtensionDataMap extension_data_map;
  if (!SlurpExtensionData(
          traits_, *extension_service_, user_share_, &extension_data_map)) {
    return false;
  }
  if (!FlushExtensionData(
          traits_, extension_data_map, extension_service_, user_share_)) {
    return false;
  }

  return true;
}

bool ExtensionModelAssociator::DisassociateModels() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // Nothing to do.
  return true;
}

bool ExtensionModelAssociator::SyncModelHasUserCreatedNodes(bool* has_nodes) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  return RootNodeHasChildren(traits_.root_node_tag, user_share_, has_nodes);
}

bool ExtensionModelAssociator::CryptoReadyIfNecessary() {
  // We only access the cryptographer while holding a transaction.
  sync_api::ReadTransaction trans(user_share_);
  const syncable::ModelTypeSet& encrypted_types =
      GetEncryptedDataTypes(trans.GetWrappedTrans());
  return encrypted_types.count(syncable::EXTENSIONS) == 0 ||
      trans.GetCryptographer()->is_ready();
}

}  // namespace browser_sync
<commit_msg>[Sync] Fix bug in ExtensionModelAssociator::CryptoReadyIfNecessary()<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/sync/glue/extension_model_associator.h"

#include "base/logging.h"
#include "chrome/browser/sync/engine/syncapi.h"
#include "chrome/browser/sync/glue/extension_data.h"
#include "chrome/browser/sync/glue/extension_sync_traits.h"
#include "chrome/browser/sync/glue/extension_sync.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/protocol/extension_specifics.pb.h"
#include "chrome/browser/sync/syncable/nigori_util.h"
#include "content/browser/browser_thread.h"

namespace browser_sync {

ExtensionModelAssociator::ExtensionModelAssociator(
    const ExtensionSyncTraits& traits,
    ExtensionServiceInterface* extension_service,
    sync_api::UserShare* user_share)
    : traits_(traits), extension_service_(extension_service),
      user_share_(user_share) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(extension_service_);
  DCHECK(user_share_);
}

ExtensionModelAssociator::~ExtensionModelAssociator() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

bool ExtensionModelAssociator::AssociateModels() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  ExtensionDataMap extension_data_map;
  if (!SlurpExtensionData(
          traits_, *extension_service_, user_share_, &extension_data_map)) {
    return false;
  }
  if (!FlushExtensionData(
          traits_, extension_data_map, extension_service_, user_share_)) {
    return false;
  }

  return true;
}

bool ExtensionModelAssociator::DisassociateModels() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // Nothing to do.
  return true;
}

bool ExtensionModelAssociator::SyncModelHasUserCreatedNodes(bool* has_nodes) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  return RootNodeHasChildren(traits_.root_node_tag, user_share_, has_nodes);
}

bool ExtensionModelAssociator::CryptoReadyIfNecessary() {
  // We only access the cryptographer while holding a transaction.
  sync_api::ReadTransaction trans(user_share_);
  const syncable::ModelTypeSet& encrypted_types =
      GetEncryptedDataTypes(trans.GetWrappedTrans());
  return encrypted_types.count(traits_.model_type) == 0 ||
      trans.GetCryptographer()->is_ready();
}

}  // namespace browser_sync
<|endoftext|>


<commit_before>#include "Arduino.h"
#include "Sampler.h"

int values[MAX];
int size = 0;

Sampler::Sampler() {
    this->pointer = 0;
    this->sum = 0;
}

void Sampler::sample(int value) {
    sum = sum - values[pointer];
    values[pointer] = value;
    sum = sum + value;
    pointer++;
    if (pointer > (MAX - 1)) pointer = 0;
    if (size < MAX) size++;
}

double Sampler::deviation() {
    if (size <= 1) return 0;
    double mean = sum / size;
    double tmp = 0;
    int i == 10 ? 0 : pointer - size;
    int count = 0;
    while (count < size) {
        tmp = tmp + sq(values[i] - mean);
        count++;
        i++;
        if (i > (MAX - 1)) i = 0;
    }
    return sqrt(tmp / (size - 1));
}
<commit_msg>deviation calculation emproved<commit_after>#include "Arduino.h"
#include "Sampler.h"

int values[MAX];
int size = 0;

Sampler::Sampler() {
    this->pointer = 0;
    this->sum = 0;
}

void Sampler::sample(int value) {
    sum = sum - values[pointer];
    values[pointer] = value;
    sum = sum + value;
    pointer++;
    if (pointer > (MAX - 1)) pointer = 0;
    if (size < MAX) size++;
}

double Sampler::deviation() {
    if (size <= 1) return 0;
    double mean = sum / size;
    double tmp = 0;
    for (int i = 0; i < size; i++) {
		tmp = tmp + sq(values[i] - mean);
	}
    return sqrt(tmp / (size - 1));
}
<|endoftext|>


<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of nc_handler, a data handler for the OPeNDAP data
// server.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your
// option) any later version.
//
// This software 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// NCRequestHandler.cc

#include <sstream>

using std::ostringstream;

#include "NCRequestHandler.h"
#include "NCTypeFactory.h"
#include "BESResponseHandler.h"
#include "BESResponseNames.h"
#include "BESDASResponse.h"
#include "BESDDSResponse.h"
#include "BESDataDDSResponse.h"
#include "BESConstraintFuncs.h"
#include "BESVersionInfo.h"
#include "Error.h"
#include "BESHandlerException.h"
#include "BESDataNames.h"

#include "config_nc.h"

extern void nc_read_variables(DAS & das,
                              const string & filename) throw(Error);
extern void nc_read_descriptors(DDS & dds,
                                const string & filename) throw(Error);

NCRequestHandler::NCRequestHandler(string name)
:  BESRequestHandler(name)
{
    add_handler(DAS_RESPONSE, NCRequestHandler::nc_build_das);
    add_handler(DDS_RESPONSE, NCRequestHandler::nc_build_dds);
    add_handler(DATA_RESPONSE, NCRequestHandler::nc_build_data);
    add_handler(HELP_RESPONSE, NCRequestHandler::nc_build_help);
    add_handler(VERS_RESPONSE, NCRequestHandler::nc_build_version);
}

NCRequestHandler::~NCRequestHandler()
{
}

bool NCRequestHandler::nc_build_das(BESDataHandlerInterface & dhi)
{
    BESResponseObject *response =
        dhi.response_handler->get_response_object();
    BESDASResponse *bdas = dynamic_cast < BESDASResponse * >(response);
    DAS *das = bdas->get_das();

    try {
        nc_read_variables(*das, dhi.container->access());
    }
    catch(Error & e) {
        ostringstream s;
        s << "libdap exception building DAS"
            << ": error_code = " << e.get_error_code()
            << ": " << e.get_error_message();
        BESHandlerException ex(s.str(), __FILE__, __LINE__);
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building DAS";
        BESHandlerException ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool NCRequestHandler::nc_build_dds(BESDataHandlerInterface & dhi)
{
    BESResponseObject *response =
        dhi.response_handler->get_response_object();
    BESDDSResponse *bdds = dynamic_cast < BESDDSResponse * >(response);
    DDS *dds = bdds->get_dds();

    try {
        NCTypeFactory *factory = new NCTypeFactory;
        dds->set_factory(factory);

        dds->filename(dhi.container->access());
        nc_read_descriptors(*dds, dhi.container->access());
        DAS das;
        nc_read_variables(das, dhi.container->access());

        dds->transfer_attributes(&das);

        dhi.data[POST_CONSTRAINT] = dhi.container->get_constraint();
#if 0
        // see ticket 720
        dds->set_factory(NULL);
        delete factory;
#endif
    }
    catch(Error & e) {
        ostringstream s;
        s << "libdap exception building DDS"
            << ": error_code = " << e.get_error_code()
            << ": " << e.get_error_message();
        BESHandlerException ex(s.str(), __FILE__, __LINE__);
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building DDS";
        BESHandlerException ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool NCRequestHandler::nc_build_data(BESDataHandlerInterface & dhi)
{
    BESResponseObject *response =
        dhi.response_handler->get_response_object();
    BESDataDDSResponse *bdds =
        dynamic_cast < BESDataDDSResponse * >(response);
    DataDDS *dds = bdds->get_dds();

    try {
        NCTypeFactory *factory = new NCTypeFactory;
        dds->set_factory(factory);

        dds->filename(dhi.container->access());
        nc_read_descriptors(*dds, dhi.container->access());
        DAS das;
        nc_read_variables(das, dhi.container->access());

        dds->transfer_attributes(&das);

        dhi.data[POST_CONSTRAINT] = dhi.container->get_constraint();

#if 0
        // see ticket 720
        dds->set_factory(NULL);
        delete factory;
#endif
    }
    catch(Error & e) {
        ostringstream s;
        s << "libdap exception reading variables"
            << ": error_code = " << e.get_error_code()
            << ": " << e.get_error_message();
        BESHandlerException ex(s.str(), __FILE__, __LINE__);
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building DAS";
        BESHandlerException ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool NCRequestHandler::nc_build_help(BESDataHandlerInterface & dhi)
{
    BESInfo *info =
        (BESInfo *) dhi.response_handler->get_response_object();
    info->begin_tag("Handler");
    info->add_tag("name", PACKAGE_NAME);
    string handles = (string) DAS_RESPONSE
        + "," + DDS_RESPONSE
        + "," + DATA_RESPONSE + "," + HELP_RESPONSE + "," + VERS_RESPONSE;
    info->add_tag("handles", handles);
    info->add_tag("version", PACKAGE_STRING);
    info->end_tag("Handler");

    return true;
}

bool NCRequestHandler::nc_build_version(BESDataHandlerInterface & dhi)
{
    BESVersionInfo *info =
        (BESVersionInfo *) dhi.response_handler->get_response_object();
    info->addHandlerVersion(PACKAGE_NAME, PACKAGE_VERSION);
    return true;
}
<commit_msg>Using the new BESDapHandlerExcpetion class to maintain more of the Error class information. M    NCRequestHandler.cc<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of nc_handler, a data handler for the OPeNDAP data
// server.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your
// option) any later version.
//
// This software 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// NCRequestHandler.cc

#include "NCRequestHandler.h"
#include "NCTypeFactory.h"
#include "BESResponseHandler.h"
#include "BESResponseNames.h"
#include "BESDASResponse.h"
#include "BESDDSResponse.h"
#include "BESDataDDSResponse.h"
#include "BESConstraintFuncs.h"
#include "BESVersionInfo.h"
#include "Error.h"
#include "BESDapHandlerException.h"
#include "BESDataNames.h"

#include "config_nc.h"

extern void nc_read_variables(DAS & das,
                              const string & filename) throw(Error);
extern void nc_read_descriptors(DDS & dds,
                                const string & filename) throw(Error);

NCRequestHandler::NCRequestHandler(string name)
:  BESRequestHandler(name)
{
    add_handler(DAS_RESPONSE, NCRequestHandler::nc_build_das);
    add_handler(DDS_RESPONSE, NCRequestHandler::nc_build_dds);
    add_handler(DATA_RESPONSE, NCRequestHandler::nc_build_data);
    add_handler(HELP_RESPONSE, NCRequestHandler::nc_build_help);
    add_handler(VERS_RESPONSE, NCRequestHandler::nc_build_version);
}

NCRequestHandler::~NCRequestHandler()
{
}

bool NCRequestHandler::nc_build_das(BESDataHandlerInterface & dhi)
{
    BESResponseObject *response =
        dhi.response_handler->get_response_object();
    BESDASResponse *bdas = dynamic_cast < BESDASResponse * >(response);
    DAS *das = bdas->get_das();

    try {
        nc_read_variables(*das, dhi.container->access());
    }
    catch(Error & e) {
        BESDapHandlerException ex( e.get_error_message(), __FILE__, __LINE__,
				   e.get_error_code() ) ;
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building DAS";
        BESHandlerException ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool NCRequestHandler::nc_build_dds(BESDataHandlerInterface & dhi)
{
    BESResponseObject *response =
        dhi.response_handler->get_response_object();
    BESDDSResponse *bdds = dynamic_cast < BESDDSResponse * >(response);
    DDS *dds = bdds->get_dds();

    try {
        NCTypeFactory *factory = new NCTypeFactory;
        dds->set_factory(factory);

        dds->filename(dhi.container->access());
        nc_read_descriptors(*dds, dhi.container->access());
        DAS das;
        nc_read_variables(das, dhi.container->access());

        dds->transfer_attributes(&das);

        dhi.data[POST_CONSTRAINT] = dhi.container->get_constraint();
#if 0
        // see ticket 720
        dds->set_factory(NULL);
        delete factory;
#endif
    }
    catch(Error & e) {
        BESDapHandlerException ex( e.get_error_message(), __FILE__, __LINE__,
				   e.get_error_code() ) ;
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building DDS";
        BESHandlerException ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool NCRequestHandler::nc_build_data(BESDataHandlerInterface & dhi)
{
    BESResponseObject *response =
        dhi.response_handler->get_response_object();
    BESDataDDSResponse *bdds =
        dynamic_cast < BESDataDDSResponse * >(response);
    DataDDS *dds = bdds->get_dds();

    try {
        NCTypeFactory *factory = new NCTypeFactory;
        dds->set_factory(factory);

        dds->filename(dhi.container->access());
        nc_read_descriptors(*dds, dhi.container->access());
        DAS das;
        nc_read_variables(das, dhi.container->access());

        dds->transfer_attributes(&das);

        dhi.data[POST_CONSTRAINT] = dhi.container->get_constraint();

#if 0
        // see ticket 720
        dds->set_factory(NULL);
        delete factory;
#endif
    }
    catch(Error & e) {
        BESDapHandlerException ex( e.get_error_message(), __FILE__, __LINE__,
				   e.get_error_code() ) ;
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building DAS";
        BESHandlerException ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool NCRequestHandler::nc_build_help(BESDataHandlerInterface & dhi)
{
    BESInfo *info =
        (BESInfo *) dhi.response_handler->get_response_object();
    info->begin_tag("Handler");
    info->add_tag("name", PACKAGE_NAME);
    string handles = (string) DAS_RESPONSE
        + "," + DDS_RESPONSE
        + "," + DATA_RESPONSE + "," + HELP_RESPONSE + "," + VERS_RESPONSE;
    info->add_tag("handles", handles);
    info->add_tag("version", PACKAGE_STRING);
    info->end_tag("Handler");

    return true;
}

bool NCRequestHandler::nc_build_version(BESDataHandlerInterface & dhi)
{
    BESVersionInfo *info =
        (BESVersionInfo *) dhi.response_handler->get_response_object();
    info->addHandlerVersion(PACKAGE_NAME, PACKAGE_VERSION);
    return true;
}
<|endoftext|>