<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: command.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2007-04-11 20:06:36 $
 *
 *  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 COMMAND_HXX
#define COMMAND_HXX

#include <iostream.h>

#include <tools/stream.hxx>
#define STRLEN 100
#ifndef UNX
#define TMPNAME "\\command.tmp"
#else
#define TMPNAME "/tmp/command.tmp"
#endif

/** Different types of spawnable programs
*/
enum ExeType
{
    EXE,    /// programm is a native executable
    BAT,    /// programm is a DOS-Batch
    BTM     /// programm is a 4DOS-Batch
};

#define COMMAND_NOTFOUND    0x0001
#define COMMAND_TOOBIG      0x0002
#define COMMAND_INVALID     0x0004
#define COMMAND_NOEXEC      0x0008
#define COMMAND_NOMEM       0x0010
#define COMMAND_UNKNOWN     0x0020

#ifdef WNT
#define COMMAND_SHELL   "4nt.exe"
#endif
#ifdef UNX
#define COMMAND_SHELL   "csh"
#endif

class CommandLine;
class LogWindow;

class CommandLine
{
friend class ChildProcess;
private:
    char            *CommandBuffer;
    char            *ComShell;
    char            **ppArgv;
    BOOL            bTmpWrite;

public:
                    CommandLine(BOOL bTmpWrite = FALSE);
                    CommandLine(const char *, BOOL bTmpWrite = FALSE);
                    CommandLine(const CommandLine&, BOOL bTmpWrite = FALSE);
    virtual         ~CommandLine();

    int             nArgc;

    CommandLine&    operator=(const CommandLine&);
    CommandLine&    operator=(const char *);
    void            BuildCommand(const char *);
    char**          GetCommand(void) { return ppArgv; }
    void            Strtokens(const char *);
    void            Print();
};

static ByteString thePath( "PATH" );

/** Declares and spawns a child process.
    The spawned programm could be a native executable or a schell script.
*/
class CCommand
{
private:
    ByteString          aCommandLine;
    ByteString          aCommand;
    char                *pArgv;
    char                **ppArgv;
    ULONG               nArgc;
    int                 nError;

protected:
    void            ImplInit();
    void            Initpp( ULONG nCount, ByteString &rStr );

public:
                    /** Creates the process specified without spawning it
                        @param rString specifies the programm or shell scrip
                    */
                    CCommand( ByteString &rString );

                    /** Creates the process specified without spawning it
                        @param pChar specifies the programm or shell scrip
                    */
                    CCommand( const char *pChar );

                    /** Try to find the given programm in specified path
                        @param sEnv specifies the current search path, defaulted by environment
                        @param sItem specifies the system shell
                        @return the Location (when programm was found)
                    */
    static ByteString   Search( ByteString sEnv = thePath,
                                    ByteString sItem = COMMAND_SHELL );

                    /** Spawns the Process
                        @return 0 when spawned without errors, otherwise a error code
                    */
    operator const  int();

    ByteString          GetCommandLine_() { return aCommandLine; }
    ByteString          GetCommand() { return aCommand; }

    char**  GetCommandStr() { return ppArgv; }
};

#define COMMAND_EXECUTE_WINDOW  0x0000001
#define COMMAND_EXECUTE_CONSOLE 0x0000002
#define COMMAND_EXECUTE_HIDDEN  0x0000004
#define COMMAND_EXECUTE_START   0x0000008
#define COMMAND_EXECUTE_WAIT    0x0000010
#define COMMAND_EXECUTE_REMOTE  0x1000000

typedef ULONG CommandBits;

/** Allowes to spawn programms hidden, waiting etc.
    @see CCommand
*/
class CCommandd : public CCommand
{
    CommandBits     nFlag;
public:
                    CCommandd( ByteString &rString, CommandBits nBits );
                    CCommandd( const char *pChar, CommandBits nBits );
    operator const  int();
};

#endif
<commit_msg>INTEGRATION: CWS os2port02 (1.3.68); FILE MERGED 2007/09/30 12:08:49 ydario 1.3.68.1: Issue number: i82034 Submitted by: ydario Reviewed by:  ydario Commit of changes for OS/2 CWS source code integration.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: command.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 12:59:41 $
 *
 *  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 COMMAND_HXX
#define COMMAND_HXX

#include <iostream.h>

#include <tools/stream.hxx>
#define STRLEN 100
#ifndef UNX
#define TMPNAME "\\command.tmp"
#else
#define TMPNAME "/tmp/command.tmp"
#endif

/** Different types of spawnable programs
*/
enum ExeType
{
    EXE,    /// programm is a native executable
    BAT,    /// programm is a DOS-Batch
    BTM     /// programm is a 4DOS-Batch
};

#define COMMAND_NOTFOUND    0x0001
#define COMMAND_TOOBIG      0x0002
#define COMMAND_INVALID     0x0004
#define COMMAND_NOEXEC      0x0008
#define COMMAND_NOMEM       0x0010
#define COMMAND_UNKNOWN     0x0020

#ifdef WNT
#define COMMAND_SHELL   "4nt.exe"
#endif
#ifdef OS2
#define COMMAND_SHELL  "4os2.exe"
#endif
#ifdef UNX
#define COMMAND_SHELL   "csh"
#endif

class CommandLine;
class LogWindow;

class CommandLine
{
friend class ChildProcess;
private:
    char            *CommandBuffer;
    char            *ComShell;
    char            **ppArgv;
    BOOL            bTmpWrite;

public:
                    CommandLine(BOOL bTmpWrite = FALSE);
                    CommandLine(const char *, BOOL bTmpWrite = FALSE);
                    CommandLine(const CommandLine&, BOOL bTmpWrite = FALSE);
    virtual         ~CommandLine();

    int             nArgc;

    CommandLine&    operator=(const CommandLine&);
    CommandLine&    operator=(const char *);
    void            BuildCommand(const char *);
    char**          GetCommand(void) { return ppArgv; }
    void            Strtokens(const char *);
    void            Print();
};

static ByteString thePath( "PATH" );

/** Declares and spawns a child process.
    The spawned programm could be a native executable or a schell script.
*/
class CCommand
{
private:
    ByteString          aCommandLine;
    ByteString          aCommand;
    char                *pArgv;
    char                **ppArgv;
    ULONG               nArgc;
    int                 nError;

protected:
    void            ImplInit();
    void            Initpp( ULONG nCount, ByteString &rStr );

public:
                    /** Creates the process specified without spawning it
                        @param rString specifies the programm or shell scrip
                    */
                    CCommand( ByteString &rString );

                    /** Creates the process specified without spawning it
                        @param pChar specifies the programm or shell scrip
                    */
                    CCommand( const char *pChar );

                    /** Try to find the given programm in specified path
                        @param sEnv specifies the current search path, defaulted by environment
                        @param sItem specifies the system shell
                        @return the Location (when programm was found)
                    */
    static ByteString   Search( ByteString sEnv = thePath,
                                    ByteString sItem = COMMAND_SHELL );

                    /** Spawns the Process
                        @return 0 when spawned without errors, otherwise a error code
                    */
    operator const  int();

    ByteString          GetCommandLine_() { return aCommandLine; }
    ByteString          GetCommand() { return aCommand; }

    char**  GetCommandStr() { return ppArgv; }
};

#define COMMAND_EXECUTE_WINDOW  0x0000001
#define COMMAND_EXECUTE_CONSOLE 0x0000002
#define COMMAND_EXECUTE_HIDDEN  0x0000004
#define COMMAND_EXECUTE_START   0x0000008
#define COMMAND_EXECUTE_WAIT    0x0000010
#define COMMAND_EXECUTE_REMOTE  0x1000000

typedef ULONG CommandBits;

/** Allowes to spawn programms hidden, waiting etc.
    @see CCommand
*/
class CCommandd : public CCommand
{
    CommandBits     nFlag;
public:
                    CCommandd( ByteString &rString, CommandBits nBits );
                    CCommandd( const char *pChar, CommandBits nBits );
    operator const  int();
};

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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/extensions/extension.h"

#include "base/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "net/base/net_util.h"
#include "chrome/common/extensions/user_script.h"
#include "chrome/common/url_constants.h"

const char Extension::kManifestFilename[] = "manifest.json";

const wchar_t* Extension::kContentScriptsKey = L"content_scripts";
const wchar_t* Extension::kDescriptionKey = L"description";
const wchar_t* Extension::kFormatVersionKey = L"format_version";
const wchar_t* Extension::kIdKey = L"id";
const wchar_t* Extension::kJsKey = L"js";
const wchar_t* Extension::kMatchesKey = L"matches";
const wchar_t* Extension::kNameKey = L"name";
const wchar_t* Extension::kRunAtKey = L"run_at";
const wchar_t* Extension::kVersionKey = L"version";
const wchar_t* Extension::kZipHashKey = L"zip_hash";
const wchar_t* Extension::kPluginsDirKey = L"plugins_dir";

const char* Extension::kRunAtDocumentStartValue = "document_start";
const char* Extension::kRunAtDocumentEndValue = "document_end";

// Extension-related error messages. Some of these are simple patterns, where a
// '*' is replaced at runtime with a specific value. This is used instead of
// printf because we want to unit test them and scanf is hard to make
// cross-platform.
const char* Extension::kInvalidContentScriptError =
    "Invalid value for 'content_scripts[*]'.";
const char* Extension::kInvalidContentScriptsListError =
    "Invalid value for 'content_scripts'.";
const char* Extension::kInvalidDescriptionError =
    "Invalid value for 'description'.";
const char* Extension::kInvalidFormatVersionError =
    "Required value 'format_version' is missing or invalid.";
const char* Extension::kInvalidIdError =
    "Required value 'id' is missing or invalid.";
const char* Extension::kInvalidJsCountError =
    "Invalid value for 'content_scripts[*].js. Only one js file is currently "
    "supported per-content script.";
const char* Extension::kInvalidJsError =
    "Invalid value for 'content_scripts[*].js[*]'.";
const char* Extension::kInvalidJsListError =
    "Required value 'content_scripts[*].js is missing or invalid.";
const char* Extension::kInvalidManifestError =
    "Manifest is missing or invalid.";
const char* Extension::kInvalidMatchCountError =
    "Invalid value for 'content_scripts[*].matches. There must be at least one "
    "match specified.";
const char* Extension::kInvalidMatchError =
    "Invalid value for 'content_scripts[*].matches[*]'.";
const char* Extension::kInvalidMatchesError =
    "Required value 'content_scripts[*].matches' is missing or invalid.";
const char* Extension::kInvalidNameError =
    "Required value 'name' is missing or invalid.";
const char* Extension::kInvalidRunAtError =
    "Invalid value for 'content_scripts[*].run_at'.";
const char* Extension::kInvalidVersionError =
    "Required value 'version' is missing or invalid.";
const char* Extension::kInvalidZipHashError =
    "Required key 'zip_hash' is missing or invalid.";
const char* Extension::kInvalidPluginsDirError =
    "Invalid value for 'plugins_dir'.";

const int Extension::kIdSize = 20;  // SHA1 (160 bits) == 20 bytes

const std::string Extension::VersionString() const {
  return version_->GetString();
}

// static
GURL Extension::GetResourceURL(const GURL& extension_url,
                               const std::string& relative_path) {
  DCHECK(extension_url.SchemeIs(chrome::kExtensionScheme));
  DCHECK(extension_url.path() == "/");

  GURL ret_val = GURL(extension_url.spec() + relative_path);
  DCHECK(StartsWithASCII(ret_val.spec(), extension_url.spec(), false));

  return ret_val;
}

// static
FilePath Extension::GetResourcePath(const FilePath& extension_path,
                                    const std::string& relative_path) {
  // Build up a file:// URL and convert that back to a FilePath.  This avoids
  // URL encoding and path separator issues.

  // Convert the extension's root to a file:// URL.
  GURL extension_url = net::FilePathToFileURL(extension_path);
  if (!extension_url.is_valid())
    return FilePath();

  // Append the requested path.
  GURL::Replacements replacements;
  std::string new_path(extension_url.path());
  new_path += "/";
  new_path += relative_path;
  replacements.SetPathStr(new_path);
  GURL file_url = extension_url.ReplaceComponents(replacements);
  if (!file_url.is_valid())
    return FilePath();

  // Convert the result back to a FilePath.
  FilePath ret_val;
  if (!net::FileURLToFilePath(file_url, &ret_val))
    return FilePath();

  // Double-check that the path we ended up with is actually inside the
  // extension root. We can do this with a simple prefix match because:
  // a) We control the prefix on both sides, and they should match.
  // b) GURL normalizes things like "../" and "//" before it gets to us.
  if (ret_val.value().find(extension_path.value() +
                           FilePath::kSeparators[0]) != 0)
    return FilePath();

  return ret_val;
}

// Creates an error messages from a pattern.
static std::string FormatErrorMessage(const std::string& format,
                                      const std::string s1) {
  std::string ret_val = format;
  ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1);
  return ret_val;
}

static std::string FormatErrorMessage(const std::string& format,
                                      const std::string s1,
                                      const std::string s2) {
  std::string ret_val = format;
  ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1);
  ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s2);
  return ret_val;
}

Extension::Extension(const FilePath& path) {
  DCHECK(path.IsAbsolute());

#if defined(OS_WIN)
  // Normalize any drive letter to upper-case. We do this for consistency with
  // net_utils::FilePathToFileURL(), which does the same thing, to make string
  // comparisons simpler.
  std::wstring path_str = path.value();
  if (path_str.size() >= 2 && path_str[0] >= L'a' && path_str[0] <= L'z' &&
      path_str[1] == ':')
    path_str[0] += ('A' - 'a');

  path_ = FilePath(path_str);
#else
  path_ = path;
#endif
}

bool Extension::InitFromValue(const DictionaryValue& source,
                              std::string* error) {
  // Check format version.
  int format_version = 0;
  if (!source.GetInteger(kFormatVersionKey, &format_version) ||
      static_cast<uint32>(format_version) != kExpectedFormatVersion) {
    *error = kInvalidFormatVersionError;
    return false;
  }

  // Initialize id.
  if (!source.GetString(kIdKey, &id_)) {
    *error = kInvalidIdError;
    return false;
  }

  // Verify that the id is legal.  The id is a hex string of the SHA-1 hash of
  // the public key.
  std::vector<uint8> id_bytes;
  if (!HexStringToBytes(id_, &id_bytes) || id_bytes.size() != kIdSize) {
    *error = kInvalidIdError;
    return false;
  }

  // Initialize URL.
  extension_url_ = GURL(std::string(chrome::kExtensionScheme) +
                        chrome::kStandardSchemeSeparator + id_ + "/");

  // Initialize version.
  std::string version_str;
  if (!source.GetString(kVersionKey, &version_str)) {
    *error = kInvalidVersionError;
    return false;
  }
  version_.reset(Version::GetVersionFromString(version_str));
  if (!version_.get()) {
    *error = kInvalidVersionError;
    return false;
  }

  // Initialize name.
  if (!source.GetString(kNameKey, &name_)) {
    *error = kInvalidNameError;
    return false;
  }

  // Initialize description (optional).
  if (source.HasKey(kDescriptionKey)) {
    if (!source.GetString(kDescriptionKey, &description_)) {
      *error = kInvalidDescriptionError;
      return false;
    }
  }

  // Initialize zip hash (only present in zip)
  // There's no need to verify it at this point. If it's in a bogus format
  // it won't pass the hash verify step.
  if (source.HasKey(kZipHashKey)) {
    if (!source.GetString(kZipHashKey, &zip_hash_)) {
      *error = kInvalidZipHashError;
      return false;
    }
  }

  // Initialize plugins dir (optional).
  if (source.HasKey(kPluginsDirKey)) {
    std::string plugins_dir;
    if (!source.GetString(kPluginsDirKey, &plugins_dir)) {
      *error = kInvalidPluginsDirError;
      return false;
    }
    plugins_dir_ = path_.AppendASCII(plugins_dir);
  }

  // Initialize content scripts (optional).
  if (source.HasKey(kContentScriptsKey)) {
    ListValue* list_value;
    if (!source.GetList(kContentScriptsKey, &list_value)) {
      *error = kInvalidContentScriptsListError;
      return false;
    }

    for (size_t i = 0; i < list_value->GetSize(); ++i) {
      DictionaryValue* content_script;
      if (!list_value->GetDictionary(i, &content_script)) {
        *error = FormatErrorMessage(kInvalidContentScriptError, IntToString(i));
        return false;
      }

      ListValue* matches;
      ListValue* js;

      if (!content_script->GetList(kMatchesKey, &matches)) {
        *error = FormatErrorMessage(kInvalidMatchesError, IntToString(i));
        return false;
      }

      if (!content_script->GetList(kJsKey, &js)) {
        *error = FormatErrorMessage(kInvalidJsListError, IntToString(i));
        return false;
      }

      if (matches->GetSize() == 0) {
        *error = FormatErrorMessage(kInvalidMatchCountError, IntToString(i));
        return false;
      }

      // NOTE: Only one file is supported right now.
      if (js->GetSize() != 1) {
        *error = FormatErrorMessage(kInvalidJsCountError, IntToString(i));
        return false;
      }

      UserScript script;
      if (content_script->HasKey(kRunAtKey)) {
        std::string run_location;
        if (!content_script->GetString(kRunAtKey, &run_location)) {
          *error = FormatErrorMessage(kInvalidRunAtError, IntToString(i));
          return false;
        }

        if (run_location == kRunAtDocumentStartValue) {
          script.set_run_location(UserScript::DOCUMENT_START);
        } else if (run_location == kRunAtDocumentEndValue) {
          script.set_run_location(UserScript::DOCUMENT_END);
        } else {
          *error = FormatErrorMessage(kInvalidRunAtError, IntToString(i));
          return false;
        }
      }

      for (size_t j = 0; j < matches->GetSize(); ++j) {
        std::string match_str;
        if (!matches->GetString(j, &match_str)) {
          *error = FormatErrorMessage(kInvalidMatchError, IntToString(i),
                                      IntToString(j));
          return false;
        }

        URLPattern pattern;
        if (!pattern.Parse(match_str)) {
          *error = FormatErrorMessage(kInvalidMatchError, IntToString(i),
                                      IntToString(j));
          return false;
        }

        script.add_url_pattern(pattern);
      }

      // TODO(aa): Support multiple files.
      std::string file;
      if (!js->GetString(0, &file)) {
        *error = FormatErrorMessage(kInvalidJsError, IntToString(i),
                                    IntToString(0));
        return false;
      }
      script.set_path(Extension::GetResourcePath(path(), file));
      script.set_url(Extension::GetResourceURL(url(), file));

      content_scripts_.push_back(script);
    }
  }

  return true;
}

<commit_msg>Fix the linux modules build.  Comparision between signed and unsigned integers. Review URL: http://codereview.chromium.org/28232<commit_after>// Copyright (c) 2006-2008 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/extensions/extension.h"

#include "base/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "net/base/net_util.h"
#include "chrome/common/extensions/user_script.h"
#include "chrome/common/url_constants.h"

const char Extension::kManifestFilename[] = "manifest.json";

const wchar_t* Extension::kContentScriptsKey = L"content_scripts";
const wchar_t* Extension::kDescriptionKey = L"description";
const wchar_t* Extension::kFormatVersionKey = L"format_version";
const wchar_t* Extension::kIdKey = L"id";
const wchar_t* Extension::kJsKey = L"js";
const wchar_t* Extension::kMatchesKey = L"matches";
const wchar_t* Extension::kNameKey = L"name";
const wchar_t* Extension::kRunAtKey = L"run_at";
const wchar_t* Extension::kVersionKey = L"version";
const wchar_t* Extension::kZipHashKey = L"zip_hash";
const wchar_t* Extension::kPluginsDirKey = L"plugins_dir";

const char* Extension::kRunAtDocumentStartValue = "document_start";
const char* Extension::kRunAtDocumentEndValue = "document_end";

// Extension-related error messages. Some of these are simple patterns, where a
// '*' is replaced at runtime with a specific value. This is used instead of
// printf because we want to unit test them and scanf is hard to make
// cross-platform.
const char* Extension::kInvalidContentScriptError =
    "Invalid value for 'content_scripts[*]'.";
const char* Extension::kInvalidContentScriptsListError =
    "Invalid value for 'content_scripts'.";
const char* Extension::kInvalidDescriptionError =
    "Invalid value for 'description'.";
const char* Extension::kInvalidFormatVersionError =
    "Required value 'format_version' is missing or invalid.";
const char* Extension::kInvalidIdError =
    "Required value 'id' is missing or invalid.";
const char* Extension::kInvalidJsCountError =
    "Invalid value for 'content_scripts[*].js. Only one js file is currently "
    "supported per-content script.";
const char* Extension::kInvalidJsError =
    "Invalid value for 'content_scripts[*].js[*]'.";
const char* Extension::kInvalidJsListError =
    "Required value 'content_scripts[*].js is missing or invalid.";
const char* Extension::kInvalidManifestError =
    "Manifest is missing or invalid.";
const char* Extension::kInvalidMatchCountError =
    "Invalid value for 'content_scripts[*].matches. There must be at least one "
    "match specified.";
const char* Extension::kInvalidMatchError =
    "Invalid value for 'content_scripts[*].matches[*]'.";
const char* Extension::kInvalidMatchesError =
    "Required value 'content_scripts[*].matches' is missing or invalid.";
const char* Extension::kInvalidNameError =
    "Required value 'name' is missing or invalid.";
const char* Extension::kInvalidRunAtError =
    "Invalid value for 'content_scripts[*].run_at'.";
const char* Extension::kInvalidVersionError =
    "Required value 'version' is missing or invalid.";
const char* Extension::kInvalidZipHashError =
    "Required key 'zip_hash' is missing or invalid.";
const char* Extension::kInvalidPluginsDirError =
    "Invalid value for 'plugins_dir'.";

const size_t Extension::kIdSize = 20;  // SHA1 (160 bits) == 20 bytes

const std::string Extension::VersionString() const {
  return version_->GetString();
}

// static
GURL Extension::GetResourceURL(const GURL& extension_url,
                               const std::string& relative_path) {
  DCHECK(extension_url.SchemeIs(chrome::kExtensionScheme));
  DCHECK(extension_url.path() == "/");

  GURL ret_val = GURL(extension_url.spec() + relative_path);
  DCHECK(StartsWithASCII(ret_val.spec(), extension_url.spec(), false));

  return ret_val;
}

// static
FilePath Extension::GetResourcePath(const FilePath& extension_path,
                                    const std::string& relative_path) {
  // Build up a file:// URL and convert that back to a FilePath.  This avoids
  // URL encoding and path separator issues.

  // Convert the extension's root to a file:// URL.
  GURL extension_url = net::FilePathToFileURL(extension_path);
  if (!extension_url.is_valid())
    return FilePath();

  // Append the requested path.
  GURL::Replacements replacements;
  std::string new_path(extension_url.path());
  new_path += "/";
  new_path += relative_path;
  replacements.SetPathStr(new_path);
  GURL file_url = extension_url.ReplaceComponents(replacements);
  if (!file_url.is_valid())
    return FilePath();

  // Convert the result back to a FilePath.
  FilePath ret_val;
  if (!net::FileURLToFilePath(file_url, &ret_val))
    return FilePath();

  // Double-check that the path we ended up with is actually inside the
  // extension root. We can do this with a simple prefix match because:
  // a) We control the prefix on both sides, and they should match.
  // b) GURL normalizes things like "../" and "//" before it gets to us.
  if (ret_val.value().find(extension_path.value() +
                           FilePath::kSeparators[0]) != 0)
    return FilePath();

  return ret_val;
}

// Creates an error messages from a pattern.
static std::string FormatErrorMessage(const std::string& format,
                                      const std::string s1) {
  std::string ret_val = format;
  ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1);
  return ret_val;
}

static std::string FormatErrorMessage(const std::string& format,
                                      const std::string s1,
                                      const std::string s2) {
  std::string ret_val = format;
  ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1);
  ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s2);
  return ret_val;
}

Extension::Extension(const FilePath& path) {
  DCHECK(path.IsAbsolute());

#if defined(OS_WIN)
  // Normalize any drive letter to upper-case. We do this for consistency with
  // net_utils::FilePathToFileURL(), which does the same thing, to make string
  // comparisons simpler.
  std::wstring path_str = path.value();
  if (path_str.size() >= 2 && path_str[0] >= L'a' && path_str[0] <= L'z' &&
      path_str[1] == ':')
    path_str[0] += ('A' - 'a');

  path_ = FilePath(path_str);
#else
  path_ = path;
#endif
}

bool Extension::InitFromValue(const DictionaryValue& source,
                              std::string* error) {
  // Check format version.
  int format_version = 0;
  if (!source.GetInteger(kFormatVersionKey, &format_version) ||
      static_cast<uint32>(format_version) != kExpectedFormatVersion) {
    *error = kInvalidFormatVersionError;
    return false;
  }

  // Initialize id.
  if (!source.GetString(kIdKey, &id_)) {
    *error = kInvalidIdError;
    return false;
  }

  // Verify that the id is legal.  The id is a hex string of the SHA-1 hash of
  // the public key.
  std::vector<uint8> id_bytes;
  if (!HexStringToBytes(id_, &id_bytes) || id_bytes.size() != kIdSize) {
    *error = kInvalidIdError;
    return false;
  }

  // Initialize URL.
  extension_url_ = GURL(std::string(chrome::kExtensionScheme) +
                        chrome::kStandardSchemeSeparator + id_ + "/");

  // Initialize version.
  std::string version_str;
  if (!source.GetString(kVersionKey, &version_str)) {
    *error = kInvalidVersionError;
    return false;
  }
  version_.reset(Version::GetVersionFromString(version_str));
  if (!version_.get()) {
    *error = kInvalidVersionError;
    return false;
  }

  // Initialize name.
  if (!source.GetString(kNameKey, &name_)) {
    *error = kInvalidNameError;
    return false;
  }

  // Initialize description (optional).
  if (source.HasKey(kDescriptionKey)) {
    if (!source.GetString(kDescriptionKey, &description_)) {
      *error = kInvalidDescriptionError;
      return false;
    }
  }

  // Initialize zip hash (only present in zip)
  // There's no need to verify it at this point. If it's in a bogus format
  // it won't pass the hash verify step.
  if (source.HasKey(kZipHashKey)) {
    if (!source.GetString(kZipHashKey, &zip_hash_)) {
      *error = kInvalidZipHashError;
      return false;
    }
  }

  // Initialize plugins dir (optional).
  if (source.HasKey(kPluginsDirKey)) {
    std::string plugins_dir;
    if (!source.GetString(kPluginsDirKey, &plugins_dir)) {
      *error = kInvalidPluginsDirError;
      return false;
    }
    plugins_dir_ = path_.AppendASCII(plugins_dir);
  }

  // Initialize content scripts (optional).
  if (source.HasKey(kContentScriptsKey)) {
    ListValue* list_value;
    if (!source.GetList(kContentScriptsKey, &list_value)) {
      *error = kInvalidContentScriptsListError;
      return false;
    }

    for (size_t i = 0; i < list_value->GetSize(); ++i) {
      DictionaryValue* content_script;
      if (!list_value->GetDictionary(i, &content_script)) {
        *error = FormatErrorMessage(kInvalidContentScriptError, IntToString(i));
        return false;
      }

      ListValue* matches;
      ListValue* js;

      if (!content_script->GetList(kMatchesKey, &matches)) {
        *error = FormatErrorMessage(kInvalidMatchesError, IntToString(i));
        return false;
      }

      if (!content_script->GetList(kJsKey, &js)) {
        *error = FormatErrorMessage(kInvalidJsListError, IntToString(i));
        return false;
      }

      if (matches->GetSize() == 0) {
        *error = FormatErrorMessage(kInvalidMatchCountError, IntToString(i));
        return false;
      }

      // NOTE: Only one file is supported right now.
      if (js->GetSize() != 1) {
        *error = FormatErrorMessage(kInvalidJsCountError, IntToString(i));
        return false;
      }

      UserScript script;
      if (content_script->HasKey(kRunAtKey)) {
        std::string run_location;
        if (!content_script->GetString(kRunAtKey, &run_location)) {
          *error = FormatErrorMessage(kInvalidRunAtError, IntToString(i));
          return false;
        }

        if (run_location == kRunAtDocumentStartValue) {
          script.set_run_location(UserScript::DOCUMENT_START);
        } else if (run_location == kRunAtDocumentEndValue) {
          script.set_run_location(UserScript::DOCUMENT_END);
        } else {
          *error = FormatErrorMessage(kInvalidRunAtError, IntToString(i));
          return false;
        }
      }

      for (size_t j = 0; j < matches->GetSize(); ++j) {
        std::string match_str;
        if (!matches->GetString(j, &match_str)) {
          *error = FormatErrorMessage(kInvalidMatchError, IntToString(i),
                                      IntToString(j));
          return false;
        }

        URLPattern pattern;
        if (!pattern.Parse(match_str)) {
          *error = FormatErrorMessage(kInvalidMatchError, IntToString(i),
                                      IntToString(j));
          return false;
        }

        script.add_url_pattern(pattern);
      }

      // TODO(aa): Support multiple files.
      std::string file;
      if (!js->GetString(0, &file)) {
        *error = FormatErrorMessage(kInvalidJsError, IntToString(i),
                                    IntToString(0));
        return false;
      }
      script.set_path(Extension::GetResourcePath(path(), file));
      script.set_url(Extension::GetResourceURL(url(), file));

      content_scripts_.push_back(script);
    }
  }

  return true;
}

<|endoftext|>


<commit_before>#include <stdio.h>

#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/VertexArray.hpp>
// #include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/RenderTarget.hpp>

#include "gui/cursor.hpp"

namespace qrw
{
	Cursor* Cursor::cursor = 0;

	Cursor::Cursor()
	: position(0, 0),
	  child(0)
	{}

	Cursor::~Cursor()
	{}

	Cursor* Cursor::getCursor()
	{
		if(cursor == 0)
			cursor = new Cursor();
		return cursor;
	}

	void Cursor::setBoard(Board* board)
	{
		this->board = board;
	}

	sf::Vector2i Cursor::getPosition()
	{
		return position;
	}

	bool Cursor::move(int dx, int dy)
	{
		if(child != 0)
		{
			return child->move(dx, dy);
		}
		if(board == 0)
			return false;
		if(board->getSquare(position.x + dx, position.y + dy) == 0)
			return false;
		position.x += dx;
		position.y += dy;
		return true;
	}

	bool Cursor::setPosition(int x, int y)
	{
		if(board == 0)
			return false;
		if(board->getSquare(x, y) == 0)
			return false;
		position.x = x;
		position.y = y;
		return true;
	}

	bool Cursor::setPosition(sf::Vector2i pos)
	{
		return setPosition(pos.x, pos.y);
	}

	Cursor* Cursor::spawnChild()
	{
		if(child != 0)
			return 0;
		else
		{
			child = new Cursor();
			child->setBoard(board);
			child->setPosition(position.x, position.y);
		}
		return child;
	}

	Cursor* Cursor::getChild()
	{
		return child;
	}

	void Cursor::despawnChild()
	{
		if(child != 0)
		{
			delete child;
			child = 0;
		}
	}

	void Cursor::draw(sf::RenderTarget& target, sf::Vector2f position, float size)
	{
		sf::Color col(218, 0, 0, 120);
		// Change color if child is present
		if(getChild() == 0)
			col += sf::Color(0, 218, 0, 0);
		sf::VertexArray quad(sf::Quads);
		quad.append(sf::Vertex(sf::Vector2f(position.x, position.y), col));
		quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y), col));
		quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y + size), col));
		quad.append(sf::Vertex(sf::Vector2f(position.x, position.y + size), col));
		target.draw(quad);
	}

	void Cursor::drawChild(sf::RenderTarget& target, sf::Vector2f position, float size)
	{
		if(getChild())
		{
			sf::Color col(218, 218, 0, 120);
			sf::VertexArray quad(sf::Quads);
			quad.append(sf::Vertex(sf::Vector2f(position.x, position.y), col));
			quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y), col));
			quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y + size), col));
			quad.append(sf::Vertex(sf::Vector2f(position.x, position.y + size), col));
			target.draw(quad);
		}
	}
}<commit_msg>Cursor::move() now uses setPosition() for updating cursor position.<commit_after>#include <stdio.h>

#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/VertexArray.hpp>
// #include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/RenderTarget.hpp>

#include "gui/cursor.hpp"

namespace qrw
{
	Cursor* Cursor::cursor = 0;

	Cursor::Cursor()
	: position(0, 0),
	  child(0)
	{}

	Cursor::~Cursor()
	{}

	Cursor* Cursor::getCursor()
	{
		if(cursor == 0)
			cursor = new Cursor();
		return cursor;
	}

	void Cursor::setBoard(Board* board)
	{
		this->board = board;
	}

	sf::Vector2i Cursor::getPosition()
	{
		return position;
	}

	bool Cursor::move(int dx, int dy)
	{
		if(child != 0)
		{
			return child->move(dx, dy);
		}
		if(board == 0)
			return false;
		if(board->getSquare(position.x + dx, position.y + dy) == 0)
			return false;
		setPosition(position.x + dx, position.y + dy);
		return true;
	}

	bool Cursor::setPosition(int x, int y)
	{
		if(board == 0)
			return false;
		if(board->getSquare(x, y) == 0)
			return false;
		position.x = x;
		position.y = y;
		return true;
	}

	bool Cursor::setPosition(sf::Vector2i pos)
	{
		return setPosition(pos.x, pos.y);
	}

	Cursor* Cursor::spawnChild()
	{
		if(child != 0)
			return 0;
		else
		{
			child = new Cursor();
			child->setBoard(board);
			child->setPosition(position.x, position.y);
		}
		return child;
	}

	Cursor* Cursor::getChild()
	{
		return child;
	}

	void Cursor::despawnChild()
	{
		if(child != 0)
		{
			delete child;
			child = 0;
		}
	}

	void Cursor::draw(sf::RenderTarget& target, sf::Vector2f position, float size)
	{
		sf::Color col(218, 0, 0, 120);
		// Change color if child is present
		if(getChild() == 0)
			col += sf::Color(0, 218, 0, 0);
		sf::VertexArray quad(sf::Quads);
		quad.append(sf::Vertex(sf::Vector2f(position.x, position.y), col));
		quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y), col));
		quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y + size), col));
		quad.append(sf::Vertex(sf::Vector2f(position.x, position.y + size), col));
		target.draw(quad);
	}

	void Cursor::drawChild(sf::RenderTarget& target, sf::Vector2f position, float size)
	{
		if(getChild())
		{
			sf::Color col(218, 218, 0, 120);
			sf::VertexArray quad(sf::Quads);
			quad.append(sf::Vertex(sf::Vector2f(position.x, position.y), col));
			quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y), col));
			quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y + size), col));
			quad.append(sf::Vertex(sf::Vector2f(position.x, position.y + size), col));
			target.draw(quad);
		}
	}
}<|endoftext|>


<commit_before>// @(#)root/tree:$Name:  $:$Id: TTreeFilePrefetch.cxx,v 1.10 2006/06/15 10:02:13 brun Exp $
// Author: Rene Brun   04/06/2006

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TTreeFilePrefetch                                                    //
//                                                                      //
//  A specialized TFilePrefetch object for a TTree                      //
//  This class acts as a file cache, registering automatically the      //
//  baskets from the branches being processed (TTree::Draw or           //
//  TTree::Process and TSelectors) when in the learning phase.          //
//  The learning phase is by default 100 entries.                       //
//  It can be changed via TTreeFileFrefetch::SetLearnEntries.           //
//                                                                      //
//  This cache speeds-up considerably the performance, in particular    //
//  when the Tree is accessed remotely via a high latency network.      //
//                                                                      //
//  The default cache size (10 Mbytes) may be changed via the function  //
//      TTreeFilePrefetch::SetCacheSize                                 //
//                                                                      //
//  Only the baskets for the requested entry range are put in the cache //
//                                                                      //
//  For each Tree being processed a TTreeFilePrefetch object is created.//
//  This object is automatically deleted when the Tree is deleted or    //
//  when the file is deleted.                                           //
//                                                                      //
//  -Special case of a TChain                                           //
//   Once the training is done on the first Tree, the list of branches  //
//   in the cache is kept for the following files.                      //
//                                                                      //
//  -Special case of a TEventlist                                       //
//   if the Tree or TChain has a TEventlist, only the buffers           //
//   referenced by the list are put in the cache.                       //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TTreeFilePrefetch.h"
#include "TChain.h"
#include "TBranch.h"
#include "TEventList.h"
#include "TObjString.h"

Int_t TTreeFilePrefetch::fgLearnEntries = 100;

ClassImp(TTreeFilePrefetch)

//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch() : TFilePrefetch(),
   fEntryMin(0),
   fEntryMax(1),
   fEntryNext(1),
   fZipBytes(0),
   fNbranches(0),
   fBranches(0),
   fBrNames(0),
   fOwner(0),
   fTree(0),
   fIsLearning(kTRUE)
{
   // Default Constructor.
}

//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch(TTree *tree, Int_t buffersize) : TFilePrefetch(tree->GetCurrentFile(),buffersize),
   fEntryMin(0),
   fEntryMax(tree->GetEntries()),
   fEntryNext(0),
   fZipBytes(0),
   fNbranches(0),
   fBranches(0),
   fBrNames(new TList),
   fOwner(tree),
   fTree(0),
   fIsLearning(kTRUE)
{
   // Constructor.

   fEntryNext = fEntryMin + fgLearnEntries;
   Int_t nleaves = tree->GetListOfLeaves()->GetEntries();
   fBranches = new TBranch*[nleaves+10]; //add a margin just in case in a TChain?
}

//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch(const TTreeFilePrefetch &pf) : TFilePrefetch(pf)
{
   // Copy Constructor.
}

//______________________________________________________________________________
TTreeFilePrefetch::~TTreeFilePrefetch()
{
   // destructor. (in general called by the TFile destructor

   delete [] fBranches;
   if (fBrNames) {fBrNames->Delete(); delete fBrNames;}
}

//______________________________________________________________________________
TTreeFilePrefetch& TTreeFilePrefetch::operator=(const TTreeFilePrefetch& pf)
{
   // Assignment.

   if (this != &pf) TFilePrefetch::operator=(pf);
   return *this;
}

//_____________________________________________________________________________
void TTreeFilePrefetch::AddBranch(TBranch *b)
{
   //add a branch to the list of branches to be stored in the cache
   //this function is called by TBranch::GetBasket

   if (!fIsLearning) return;

   //Is branch already in the cache?
   Bool_t isNew = kTRUE;
   for (int i=0;i<fNbranches;i++) {
      if (fBranches[i] == b) {isNew = kFALSE; break;}
   }
   if (isNew) {
      fTree = b->GetTree();
      fBranches[fNbranches] = b;
      fBrNames->Add(new TObjString(b->GetName()));
      fZipBytes += b->GetZipBytes();
      fNbranches++;
      if (gDebug > 0) printf("Entry: %lld, registering branch: %s\n",b->GetTree()->GetReadEntry(),b->GetName());
   }
}

//_____________________________________________________________________________
Bool_t TTreeFilePrefetch::FillBuffer()
{
   //Fill the cache buffer with the branchse in the cache

   if (fNbranches <= 0) return kFALSE;
   TTree *tree = fBranches[0]->GetTree();
   Long64_t entry = tree->GetReadEntry();
   if (entry < fEntryNext) return kFALSE;

   //estimate number of entries that can fit in the cache
   fEntryNext = entry + tree->GetEntries()*fBufferSize/fZipBytes;
   if (fEntryNext > fEntryMax) fEntryNext = fEntryMax+1;

   //check if owner has a TEventList set. If yes we optimize for this special case
   //reading only the baskets containing entries in the list
   TEventList *elist = fOwner->GetEventList();
   Long64_t chainOffset = 0;
   if (elist) {
      fEntryNext = fTree->GetEntries();
      if (fOwner->IsA() ==TChain::Class()) {
         TChain *chain = (TChain*)fOwner;
         Int_t t = chain->GetTreeNumber();
         chainOffset = chain->GetTreeOffset()[t];
      }
   }

   //clear cache buffer
   TFilePrefetch::Prefetch(0,0);
   //store baskets
   for (Int_t i=0;i<fNbranches;i++) {
      TBranch *b = fBranches[i];
      Int_t nb = b->GetMaxBaskets();
      Int_t *lbaskets   = b->GetBasketBytes();
      Long64_t *entries = b->GetBasketEntry();
      if (!lbaskets || !entries) continue;
      //we have found the branch. We now register all its baskets
      //from the requested offset to the basket below fEntrymax
      for (Int_t j=0;j<nb;j++) {
         Long64_t pos = b->GetBasketSeek(j);
         Int_t len = lbaskets[j];
         if (pos <= 0 || len <= 0) continue;
         if (entries[j] > fEntryNext) continue;
         if (entries[j] < entry && (j<nb-1 && entries[j+1] < entry)) continue;
         if (elist) {
            Long64_t emax = fEntryMax;
            if (j<nb-1) emax = entries[j+1]-1;
            if (!elist->ContainsRange(entries[j]+chainOffset,emax+chainOffset)) continue;
         }
         TFilePrefetch::Prefetch(pos,len);
      }
      if (gDebug > 0) printf("Entry: %lld, registering baskets branch %s, fEntryNext=%lld, fNseek=%d, fNtot=%d\n",entry,fBranches[i]->GetName(),fEntryNext,fNseek,fNtot);
   }
   fIsLearning = kFALSE;
   return kTRUE;
}

//_____________________________________________________________________________
Int_t TTreeFilePrefetch::GetLearnEntries()
{
   //static function returning the number of entries used to train the cache
   //see SetLearnEntries

   return fgLearnEntries;
}

//_____________________________________________________________________________
TTree *TTreeFilePrefetch::GetTree() const
{
   //return Tree in the cache
   if (fNbranches <= 0) return 0;
   return fBranches[0]->GetTree();
}

//_____________________________________________________________________________
Bool_t TTreeFilePrefetch::ReadBuffer(char *buf, Long64_t pos, Int_t len)
{
   // Read buffer at position pos.
   // If pos is in the list of prefetched blocks read from fBuffer,
   // then try to fill the cache from the list of selected branches,
   // otherwise normal read from file. Returns kTRUE in case of failure.
   // This function overloads TFilePrefetch::ReadBuffer.
   // It returns kFALSE if the requested block is in the cache

   //Is request already in the cache?
   Bool_t inCache = !TFilePrefetch::ReadBuffer(buf,pos,len);
   if (inCache) return kFALSE;

   //not found in cache. Do we need to fill the cache?
   Bool_t bufferFilled = FillBuffer();
   if (bufferFilled) return TFilePrefetch::ReadBuffer(buf,pos,len);
   return kTRUE;
}

//_____________________________________________________________________________
void TTreeFilePrefetch::SetEntryRange(Long64_t emin, Long64_t emax)
{
   // Set the minimum and maximum entry number to be processed
   // this information helps to optimize the number of baskets to read
   // when prefetching the branch buffers.

   fEntryMin  = emin;
   fEntryMax  = emax;
   fEntryNext  = fEntryMin + fgLearnEntries;
   fIsLearning = kTRUE;
   fNbranches  = 0;
   fZipBytes   = 0;
   if (fBrNames) fBrNames->Delete();
   if (gDebug > 0) printf("SetEntryRange: fEntryMin=%lld, fEntryMax=%lld, fEntryNext=%lld\n",fEntryMin,fEntryMax,fEntryNext);

}

//_____________________________________________________________________________
void TTreeFilePrefetch::SetLearnEntries(Int_t n)
{
   // Static function to set the number of entries to be used in learning mode
   // The default value for n is 10. n must be >= 1

   if (n < 1) n = 1;
   fgLearnEntries = n;
}

//_____________________________________________________________________________
void TTreeFilePrefetch::UpdateBranches(TTree *tree)
{
   //update pointer to current Tree and recompute pointers to the branches in the cache

   fTree = tree;
   Prefetch(0,0);

   fEntryMin  = 0;
   fEntryMax  = fTree->GetEntries();
   fEntryNext = fEntryMin + fgLearnEntries;
   fZipBytes  = 0;
   fNbranches = 0;
   TIter next(fBrNames);
   TObjString *os;
   while ((os = (TObjString*)next())) {
      TBranch *b = fTree->GetBranch(os->GetName());
      if (!b) continue;
      fBranches[fNbranches] = b;
      fZipBytes   += b->GetZipBytes();
      fNbranches++;
   }
}
<commit_msg>Use GetEntriesFast instead of GetEntries in the constructor. This prevents a recursive call to TChain::LoadTree.<commit_after>// @(#)root/tree:$Name:  $:$Id: TTreeFilePrefetch.cxx,v 1.11 2006/06/16 11:01:16 brun Exp $
// Author: Rene Brun   04/06/2006

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TTreeFilePrefetch                                                    //
//                                                                      //
//  A specialized TFilePrefetch object for a TTree                      //
//  This class acts as a file cache, registering automatically the      //
//  baskets from the branches being processed (TTree::Draw or           //
//  TTree::Process and TSelectors) when in the learning phase.          //
//  The learning phase is by default 100 entries.                       //
//  It can be changed via TTreeFileFrefetch::SetLearnEntries.           //
//                                                                      //
//  This cache speeds-up considerably the performance, in particular    //
//  when the Tree is accessed remotely via a high latency network.      //
//                                                                      //
//  The default cache size (10 Mbytes) may be changed via the function  //
//      TTreeFilePrefetch::SetCacheSize                                 //
//                                                                      //
//  Only the baskets for the requested entry range are put in the cache //
//                                                                      //
//  For each Tree being processed a TTreeFilePrefetch object is created.//
//  This object is automatically deleted when the Tree is deleted or    //
//  when the file is deleted.                                           //
//                                                                      //
//  -Special case of a TChain                                           //
//   Once the training is done on the first Tree, the list of branches  //
//   in the cache is kept for the following files.                      //
//                                                                      //
//  -Special case of a TEventlist                                       //
//   if the Tree or TChain has a TEventlist, only the buffers           //
//   referenced by the list are put in the cache.                       //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TTreeFilePrefetch.h"
#include "TChain.h"
#include "TBranch.h"
#include "TEventList.h"
#include "TObjString.h"

Int_t TTreeFilePrefetch::fgLearnEntries = 100;

ClassImp(TTreeFilePrefetch)

//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch() : TFilePrefetch(),
   fEntryMin(0),
   fEntryMax(1),
   fEntryNext(1),
   fZipBytes(0),
   fNbranches(0),
   fBranches(0),
   fBrNames(0),
   fOwner(0),
   fTree(0),
   fIsLearning(kTRUE)
{
   // Default Constructor.
}

//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch(TTree *tree, Int_t buffersize) : TFilePrefetch(tree->GetCurrentFile(),buffersize),
   fEntryMin(0),
   fEntryMax(tree->GetEntriesFast()),
   fEntryNext(0),
   fZipBytes(0),
   fNbranches(0),
   fBranches(0),
   fBrNames(new TList),
   fOwner(tree),
   fTree(0),
   fIsLearning(kTRUE)
{
   // Constructor.

   fEntryNext = fEntryMin + fgLearnEntries;
   Int_t nleaves = tree->GetListOfLeaves()->GetEntries();
   fBranches = new TBranch*[nleaves+10]; //add a margin just in case in a TChain?
}

//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch(const TTreeFilePrefetch &pf) : TFilePrefetch(pf)
{
   // Copy Constructor.
}

//______________________________________________________________________________
TTreeFilePrefetch::~TTreeFilePrefetch()
{
   // destructor. (in general called by the TFile destructor

   delete [] fBranches;
   if (fBrNames) {fBrNames->Delete(); delete fBrNames;}
}

//______________________________________________________________________________
TTreeFilePrefetch& TTreeFilePrefetch::operator=(const TTreeFilePrefetch& pf)
{
   // Assignment.

   if (this != &pf) TFilePrefetch::operator=(pf);
   return *this;
}

//_____________________________________________________________________________
void TTreeFilePrefetch::AddBranch(TBranch *b)
{
   //add a branch to the list of branches to be stored in the cache
   //this function is called by TBranch::GetBasket

   if (!fIsLearning) return;

   //Is branch already in the cache?
   Bool_t isNew = kTRUE;
   for (int i=0;i<fNbranches;i++) {
      if (fBranches[i] == b) {isNew = kFALSE; break;}
   }
   if (isNew) {
      fTree = b->GetTree();
      fBranches[fNbranches] = b;
      fBrNames->Add(new TObjString(b->GetName()));
      fZipBytes += b->GetZipBytes();
      fNbranches++;
      if (gDebug > 0) printf("Entry: %lld, registering branch: %s\n",b->GetTree()->GetReadEntry(),b->GetName());
   }
}

//_____________________________________________________________________________
Bool_t TTreeFilePrefetch::FillBuffer()
{
   //Fill the cache buffer with the branchse in the cache

   if (fNbranches <= 0) return kFALSE;
   TTree *tree = fBranches[0]->GetTree();
   Long64_t entry = tree->GetReadEntry();
   if (entry < fEntryNext) return kFALSE;

   //estimate number of entries that can fit in the cache
   fEntryNext = entry + tree->GetEntries()*fBufferSize/fZipBytes;
   if (fEntryNext > fEntryMax) fEntryNext = fEntryMax+1;

   //check if owner has a TEventList set. If yes we optimize for this special case
   //reading only the baskets containing entries in the list
   TEventList *elist = fOwner->GetEventList();
   Long64_t chainOffset = 0;
   if (elist) {
      fEntryNext = fTree->GetEntries();
      if (fOwner->IsA() ==TChain::Class()) {
         TChain *chain = (TChain*)fOwner;
         Int_t t = chain->GetTreeNumber();
         chainOffset = chain->GetTreeOffset()[t];
      }
   }

   //clear cache buffer
   TFilePrefetch::Prefetch(0,0);
   //store baskets
   for (Int_t i=0;i<fNbranches;i++) {
      TBranch *b = fBranches[i];
      Int_t nb = b->GetMaxBaskets();
      Int_t *lbaskets   = b->GetBasketBytes();
      Long64_t *entries = b->GetBasketEntry();
      if (!lbaskets || !entries) continue;
      //we have found the branch. We now register all its baskets
      //from the requested offset to the basket below fEntrymax
      for (Int_t j=0;j<nb;j++) {
         Long64_t pos = b->GetBasketSeek(j);
         Int_t len = lbaskets[j];
         if (pos <= 0 || len <= 0) continue;
         if (entries[j] > fEntryNext) continue;
         if (entries[j] < entry && (j<nb-1 && entries[j+1] < entry)) continue;
         if (elist) {
            Long64_t emax = fEntryMax;
            if (j<nb-1) emax = entries[j+1]-1;
            if (!elist->ContainsRange(entries[j]+chainOffset,emax+chainOffset)) continue;
         }
         TFilePrefetch::Prefetch(pos,len);
      }
      if (gDebug > 0) printf("Entry: %lld, registering baskets branch %s, fEntryNext=%lld, fNseek=%d, fNtot=%d\n",entry,fBranches[i]->GetName(),fEntryNext,fNseek,fNtot);
   }
   fIsLearning = kFALSE;
   return kTRUE;
}

//_____________________________________________________________________________
Int_t TTreeFilePrefetch::GetLearnEntries()
{
   //static function returning the number of entries used to train the cache
   //see SetLearnEntries

   return fgLearnEntries;
}

//_____________________________________________________________________________
TTree *TTreeFilePrefetch::GetTree() const
{
   //return Tree in the cache
   if (fNbranches <= 0) return 0;
   return fBranches[0]->GetTree();
}

//_____________________________________________________________________________
Bool_t TTreeFilePrefetch::ReadBuffer(char *buf, Long64_t pos, Int_t len)
{
   // Read buffer at position pos.
   // If pos is in the list of prefetched blocks read from fBuffer,
   // then try to fill the cache from the list of selected branches,
   // otherwise normal read from file. Returns kTRUE in case of failure.
   // This function overloads TFilePrefetch::ReadBuffer.
   // It returns kFALSE if the requested block is in the cache

   //Is request already in the cache?
   Bool_t inCache = !TFilePrefetch::ReadBuffer(buf,pos,len);
   if (inCache) return kFALSE;

   //not found in cache. Do we need to fill the cache?
   Bool_t bufferFilled = FillBuffer();
   if (bufferFilled) return TFilePrefetch::ReadBuffer(buf,pos,len);
   return kTRUE;
}

//_____________________________________________________________________________
void TTreeFilePrefetch::SetEntryRange(Long64_t emin, Long64_t emax)
{
   // Set the minimum and maximum entry number to be processed
   // this information helps to optimize the number of baskets to read
   // when prefetching the branch buffers.

   fEntryMin  = emin;
   fEntryMax  = emax;
   fEntryNext  = fEntryMin + fgLearnEntries;
   fIsLearning = kTRUE;
   fNbranches  = 0;
   fZipBytes   = 0;
   if (fBrNames) fBrNames->Delete();
   if (gDebug > 0) printf("SetEntryRange: fEntryMin=%lld, fEntryMax=%lld, fEntryNext=%lld\n",fEntryMin,fEntryMax,fEntryNext);

}

//_____________________________________________________________________________
void TTreeFilePrefetch::SetLearnEntries(Int_t n)
{
   // Static function to set the number of entries to be used in learning mode
   // The default value for n is 10. n must be >= 1

   if (n < 1) n = 1;
   fgLearnEntries = n;
}

//_____________________________________________________________________________
void TTreeFilePrefetch::UpdateBranches(TTree *tree)
{
   //update pointer to current Tree and recompute pointers to the branches in the cache

   fTree = tree;
   Prefetch(0,0);

   fEntryMin  = 0;
   fEntryMax  = fTree->GetEntries();
   fEntryNext = fEntryMin + fgLearnEntries;
   fZipBytes  = 0;
   fNbranches = 0;
   TIter next(fBrNames);
   TObjString *os;
   while ((os = (TObjString*)next())) {
      TBranch *b = fTree->GetBranch(os->GetName());
      if (!b) continue;
      fBranches[fNbranches] = b;
      fZipBytes   += b->GetZipBytes();
      fNbranches++;
   }
}
<|endoftext|>


<commit_before>#include "world.h"
#include "roomsmodel.h"

World::World(const QString &name, const QSize &size, QObject *parent) :
    QObject(parent)
{
    this->name = name;
    this->size = size;
    rooms = new RoomsModel(this);
}

void World::addRoom(QString const& name)
{
    Room *room = new Room(name);
    rooms->appendRoom(room);
}

int World::countRooms() const
{
    return rooms->rowCount(QModelIndex());
}

Room *World::getRoom(int index) const
{
    return rooms->at(index);
}

QVector<Room*> *World::getRooms() const
{
    return rooms;
}

QSize World::getSize() const
{
    return size;
}

QAbstractItemModel *World::roomsModel() const
{
    return rooms;
}
<commit_msg>removing getRooms(): useless<commit_after>#include "world.h"
#include "roomsmodel.h"

World::World(const QString &name, const QSize &size, QObject *parent) :
    QObject(parent)
{
    this->name = name;
    this->size = size;
    rooms = new RoomsModel(this);
}

void World::addRoom(QString const& name)
{
    Room *room = new Room(name);
    rooms->appendRoom(room);
}

int World::countRooms() const
{
    return rooms->rowCount(QModelIndex());
}

Room *World::getRoom(int index) const
{
    return rooms->at(index);
}

QSize World::getSize() const
{
    return size;
}

QAbstractItemModel *World::roomsModel() const
{
    return rooms;
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Model matrix sliders
    ui->modelScaleXSlider->init();
    ui->modelScaleYSlider->init();
    ui->modelScaleZSlider->init();

    ui->modelRotateXSlider->init(1.0f, 0, "°");
    ui->modelRotateYSlider->init(1.0f, 0, "°");
    ui->modelRotateZSlider->init(1.0f, 0, "°");

    ui->modelTranslateXSlider->init();
    ui->modelTranslateYSlider->init();
    ui->modelTranslateZSlider->init();
}

MainWindow::~MainWindow()
{
    delete ui;
}
<commit_msg>Added initialisation of view widgets<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Model matrix sliders
    ui->modelScaleXSlider->init();
    ui->modelScaleYSlider->init();
    ui->modelScaleZSlider->init();

    ui->modelRotateXSlider->init(1.0f, 0, "°");
    ui->modelRotateYSlider->init(1.0f, 0, "°");
    ui->modelRotateZSlider->init(1.0f, 0, "°");

    ui->modelTranslateXSlider->init();
    ui->modelTranslateYSlider->init();
    ui->modelTranslateZSlider->init();

    // View matrix sliders
    ui->viewPositionXSlider->init();
    ui->viewPositionYSlider->init();
    ui->viewPositionZSlider->init();

    ui->viewTargetXSlider->init();
    ui->viewTargetYSlider->init();
    ui->viewTargetZSlider->init();

    ui->viewUpXSlider->init();
    ui->viewUpYSlider->init();
    ui->viewUpZSlider->init();
}

MainWindow::~MainWindow()
{
    delete ui;
}
<|endoftext|>


<commit_before>#include "mainwindow.hpp"

#include <QDebug>
#include <QComboBox>

#include "menupage.hpp"
#include "game_window.hpp"
#include "settingspage.hpp"
#include "gameoverpage.hpp"
#include "settings.hpp"
#include "except.hpp"
#include "scorespage.h"

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent)
{
  setMinimumSize(Globals::Width, Globals::Height);

  rootPageWidget = new QWidget;

  layoutRootPageWidget = new QVBoxLayout(rootPageWidget);

  pageWidget = new MenuPage(this);

  layoutRootPageWidget->addWidget(pageWidget);

  setCentralWidget(rootPageWidget);
}

MainWindow::~MainWindow()
{
}

void MainWindow::setCurrentIndex(int value)
{
  qDebug() << value;

  if (!layoutRootPageWidget->isEmpty())
  {
    layoutRootPageWidget->removeWidget(pageWidget);

    pageWidget->deleteLater();
    pageWidget = nullptr;
  }

  switch (value) {
    case 0:
      pageWidget = new MenuPage(this);
      break;
    case 1:
      pageWidget = new GameWindow(this, m_currentLevel);
      break;
    case 2:
      pageWidget = new SettingsPage(this);
      break;
    case 3:
      pageWidget = new GameOverPage(this, m_message);
      m_finalScore = 0;
      break;
    case 4:
      pageWidget = new ScoresPage(this);
      break;
    default:
      break;
  }

  if (pageWidget)
  {
    layoutRootPageWidget->addWidget(pageWidget);
  }
}

void MainWindow::moveToGamePage()
{
  qDebug() << "moveToGamePage";

  setCurrentIndex(1);
}

void MainWindow::exitFromGame()
{
  qDebug() << "exitFromGame";

  this->close();
}

void MainWindow::moveToMenuPage()
{
  qDebug() << "moveToMenuPage";

  m_currentLevel = 1;

  setCurrentIndex(0);
}

void MainWindow::moveToSettingsPage()
{
  qDebug() << "moveToSettingsPage";

  setCurrentIndex(2);
}

void MainWindow::moveToNextLevel()
{
  qDebug() << "moveToNextLevel";

  // Increase game level number.
  m_currentLevel++;

  // Load the next game level.
  setCurrentIndex(1);
}

void MainWindow::finishGame(GameState gameState, size_t score)
{
  switch (gameState)
  {
    case GameState::WIN:
    {
      m_finalScore += score;

      // Move to next level.
      if (m_currentLevel < Settings::Instance().m_mainParameters.m_levelsNumber)
      {
        moveToNextLevel();
      }
      else
      {
        m_message = "Game over. Congratulations! You win!\nYour score: " \
            + QString::number(m_finalScore);

        m_currentLevel = 1;

        m_finalScore = 0;

        // Stop the game.
        setCurrentIndex(3);
      }

      return;
    }
    case GameState::LOSE:
    {
      m_message = "Game over. You lose!\nYour score: " \
            + QString::number(m_finalScore);

      m_currentLevel = 1;

      m_finalScore = 0;

      // Stop the game.
      setCurrentIndex(3);

      return;
    }
    case GameState::MENU:
    {
      moveToMenuPage();

      return;
    }
    case GameState::PAUSE:
    {
      return;
    }
  }
}

void MainWindow::moveToScoresPage()
{
  qDebug() << "moveToScoresPage";

  setCurrentIndex(4);
}
<commit_msg>fix final score in case of failure<commit_after>#include "mainwindow.hpp"

#include <QDebug>
#include <QComboBox>

#include "menupage.hpp"
#include "game_window.hpp"
#include "settingspage.hpp"
#include "gameoverpage.hpp"
#include "settings.hpp"
#include "except.hpp"
#include "scorespage.h"

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent)
{
  setMinimumSize(Globals::Width, Globals::Height);

  rootPageWidget = new QWidget;

  layoutRootPageWidget = new QVBoxLayout(rootPageWidget);

  pageWidget = new MenuPage(this);

  layoutRootPageWidget->addWidget(pageWidget);

  setCentralWidget(rootPageWidget);
}

MainWindow::~MainWindow()
{
}

void MainWindow::setCurrentIndex(int value)
{
  qDebug() << value;

  if (!layoutRootPageWidget->isEmpty())
  {
    layoutRootPageWidget->removeWidget(pageWidget);

    pageWidget->deleteLater();
    pageWidget = nullptr;
  }

  switch (value) {
    case 0:
      pageWidget = new MenuPage(this);
      break;
    case 1:
      pageWidget = new GameWindow(this, m_currentLevel);
      break;
    case 2:
      pageWidget = new SettingsPage(this);
      break;
    case 3:
      pageWidget = new GameOverPage(this, m_message);
      m_finalScore = 0;
      break;
    case 4:
      pageWidget = new ScoresPage(this);
      break;
    default:
      break;
  }

  if (pageWidget)
  {
    layoutRootPageWidget->addWidget(pageWidget);
  }
}

void MainWindow::moveToGamePage()
{
  qDebug() << "moveToGamePage";

  setCurrentIndex(1);
}

void MainWindow::exitFromGame()
{
  qDebug() << "exitFromGame";

  this->close();
}

void MainWindow::moveToMenuPage()
{
  qDebug() << "moveToMenuPage";

  m_currentLevel = 1;

  setCurrentIndex(0);
}

void MainWindow::moveToSettingsPage()
{
  qDebug() << "moveToSettingsPage";

  setCurrentIndex(2);
}

void MainWindow::moveToNextLevel()
{
  qDebug() << "moveToNextLevel";

  // Increase game level number.
  m_currentLevel++;

  // Load the next game level.
  setCurrentIndex(1);
}

void MainWindow::finishGame(GameState gameState, size_t score)
{
  m_finalScore += score;

  switch (gameState)
  {
    case GameState::WIN:
    {
      // Move to next level.
      if (m_currentLevel < Settings::Instance().m_mainParameters.m_levelsNumber)
      {
        moveToNextLevel();
      }
      else
      {
        m_message = "Game over. Congratulations! You win!\nYour score: " \
            + QString::number(m_finalScore);

        m_currentLevel = 1;

        m_finalScore = 0;

        // Stop the game.
        setCurrentIndex(3);
      }

      return;
    }
    case GameState::LOSE:
    {
      m_message = "Game over. You lose!\nYour score: " \
            + QString::number(m_finalScore);

      m_currentLevel = 1;

      m_finalScore = 0;

      // Stop the game.
      setCurrentIndex(3);

      return;
    }
    case GameState::MENU:
    {
      moveToMenuPage();

      return;
    }
    case GameState::PAUSE:
    {
      return;
    }
  }
}

void MainWindow::moveToScoresPage()
{
  qDebug() << "moveToScoresPage";

  setCurrentIndex(4);
}
<|endoftext|>


<commit_before>//This tutorial illustrates how to create an histogram with polygonal
//bins (TH2Poly), fill it and draw it. The initial data are stored
//in TMultiGraphs. They represent the european countries.
//The histogram filling is done according to a Mercator projection,
//therefore the bin contains should be proportional to the real surface
//of the countries.
//
//The initial data have been downloaded from: http://www.maproom.psu.edu/dcw/
//This database was developed in 1991/1992 and national boundaries reflect
//political reality as of that time.
//
//Author: Olivier Couet

void th2polyEurope()
{
   Int_t i,j;
   Double_t lon1 = -25;
   Double_t lon2 =  35;
   Double_t lat1 =  34;
   Double_t lat2 =  72;
   Double_t R = (lat2-lat1)/(lon2-lon1);
   Int_t W    = 800;
   Int_t H    = (Int_t)(R*800);
   gStyle->SetTitleX(0.2);
   gStyle->SetStatY(0.89);
   gStyle->SetStatW(0.15);

   // Canvas used to draw TH2Poly (the map)
   TCanvas *ce = new TCanvas("ce", "ce",0,0,W,H);
   ce->ToggleEventStatus();
   ce->SetGridx();
   ce->SetGridy();

   // Real surfaces taken from Wikipedia.
   const Int_t nx = 36;
   // see http://en.wikipedia.org/wiki/Area_and_population_of_European_countries
   char *countries[nx] = { "france",     "spain",  "sweden",  "germany",       "finland",
                           "norway",     "poland", "italy",   "yugoslavia",    "united_kingdom",
			   "romania",    "belarus","greece",  "czechoslovakia","bulgaria",
			   "iceland",    "hungary","portugal","austria",       "ireland",
			   "lithuania",  "latvia", "estonia", "denmark",       "netherlands",
                           "switzerland","moldova","belgium", "albania",       "cyprus",
			   "luxembourg", "andorra","malta",   "liechtenstein", "san_marino",
			   "monaco" };
   Float_t surfaces[nx] = { 547030,        505580,   449964,      357021,        338145,
                            324220,        312685,   301230,      255438,        244820,
			    237500,        207600,   131940,      127711,        110910,
			    103000,         93030,    89242,       83870,         70280,
			     65200,         64589,    45226,       43094,         41526,
			     41290,         33843,    30528,       28748,          9250,
			      2586,           468,      316,         160,            61,
                                 2};

   TH1F *h = new TH1F("h","Countries surfaces (in km^{2})",3,0,3);
   for (i=0; i<nx; i++) h->Fill(countries[i], surfaces[i]);
   h->LabelsDeflate();

   TFile::SetCacheFileDir(".");
   TFile *f;
   f = TFile::Open("http://root.cern.ch/files/europe.root","cacheread");

   TH2Poly *p = new TH2Poly(
             "Europe",
             "Europe (bin contents are normalized to the surfaces in km^{2})",
             lon1,lon2,lat1,lat2);
   p->GetXaxis()->SetNdivisions(520);
   p->GetXaxis()->SetTitle("longitude");
   p->GetYaxis()->SetTitle("latitude");

   TMultiGraph *mg;
   TKey *key;
   TIter nextkey(gDirectory->GetListOfKeys());
   while (key = (TKey*)nextkey()) {
      obj = key->ReadObj();
      if (obj->InheritsFrom("TMultiGraph")) {
         mg = (TMultiGraph*)obj;
         p->AddBin(mg);
      }
   }

   TRandom r;
   Double_t longitude, latitude;
   Double_t x, y, pi4 = TMath::Pi()/4, alpha = TMath::Pi()/360;

   gBenchmark->Start("Partitioning");
   p->ChangePartition(100, 100);
   gBenchmark->Show("Partitioning");

   // Fill TH2Poly according to a Mercator projection.
   gBenchmark->Start("Filling");
   for (i=0; i<500000; i++) {
      longitude = r.Uniform(lon1,lon2);
      latitude  = r.Uniform(lat1,lat2);
      x         = longitude;
      y         = 38*TMath::Log(TMath::Tan(pi4+alpha*latitude));
      p->Fill(x,y);
   }
   gBenchmark->Show("Filling");

   Int_t nbins = p->GetNumberOfBins();
   Double_t maximum = p->GetMaximum();
   printf("Nbins = %d Minimum = %g Maximum = %g Integral = %f \n",
           nbins,
           p->GetMinimum(),
           maximum,
           p->Integral());

   // h2 contains the surfaces computed from TH2Poly.
   TH1F *h2 = h->Clone("h2");
   h2->Reset();
   for (j=0; j<nx; j++) {
      for (i=0; i<nbins; i++) {
         if (strstr(countries[j],p->GetBinName(i+1))) {
            h2->Fill(countries[j],p->GetBinContent(i+1));
            h2->SetBinError(j, p->GetBinError(i+1));
         }
      }
   }

   // Normalize the TH2Poly bin contents to the real surfaces.
   Double_t scale = surfaces[0]/maximum;
   for (i=0; i<nbins; i++) p->SetBinContent(i+1, scale*p->GetBinContent(i+1));

   gStyle->SetOptStat(1111);
   gStyle->SetPalette(1);
   p->Draw("COL");

   TCanvas *c1 = new TCanvas("c1", "c1",W+10,0,W-20,H);
   c1->SetRightMargin(0.047);

   Double_t scale = h->GetMaximum()/h2->GetMaximum();

   h->SetStats(0);
   h->SetLineColor(kRed-3);
   h->SetLineWidth(2);
   h->SetMarkerStyle(20);
   h->SetMarkerColor(kBlue);
   h->SetMarkerSize(0.8);
   h->Draw("LP");
   h->GetXaxis()->SetLabelFont(42);
   h->GetXaxis()->SetLabelSize(0.03);
   h->GetYaxis()->SetLabelFont(42);

   h2->Scale(scale);
   Double_t scale2=TMath::Sqrt(scale);
   for (i=0; i<nx; i++) h2->SetBinError(i+1, scale2*h2->GetBinError(i+1));
   h2->Draw("E SAME");
   h2->SetMarkerStyle(20);
   h2->SetMarkerSize(0.8);

   TLegend *leg = new TLegend(0.5,0.67,0.92,0.8,NULL,"NDC");
   leg->SetTextFont(42);
   leg->SetTextSize(0.025);
   leg->AddEntry(h,"Real countries surfaces from Wikipedia (in km^{2})","lp");
   leg->AddEntry(h2,"Countries surfaces from TH2Poly (with errors)","lp");
   leg->Draw();
}
<commit_msg>More improvements. Now printing an estimated error compared to wikipedia. the number of points is a script argument.<commit_after>//This tutorial illustrates how to create an histogram with polygonal
//bins (TH2Poly), fill it and draw it. The initial data are stored
//in TMultiGraphs. They represent the european countries.
//The histogram filling is done according to a Mercator projection,
//therefore the bin contains should be proportional to the real surface
//of the countries.
//
//The initial data have been downloaded from: http://www.maproom.psu.edu/dcw/
//This database was developed in 1991/1992 and national boundaries reflect
//political reality as of that time.
//
//The script is shooting npoints (script argument) randomly over the Europe area.
//The number of points inside the countries should be proportional to the country surface
//The estimated surface is compared to the surfaces taken from wikipedia.
//Author: Olivier Couet

void th2polyEurope(Int_t npoints=500000)
{
   Int_t i,j;
   Double_t lon1 = -25;
   Double_t lon2 =  35;
   Double_t lat1 =  34;
   Double_t lat2 =  72;
   Double_t R = (lat2-lat1)/(lon2-lon1);
   Int_t W    = 800;
   Int_t H    = (Int_t)(R*800);
   gStyle->SetTitleX(0.2);
   gStyle->SetStatY(0.89);
   gStyle->SetStatW(0.15);

   // Canvas used to draw TH2Poly (the map)
   TCanvas *ce = new TCanvas("ce", "ce",0,0,W,H);
   ce->ToggleEventStatus();
   ce->SetGridx();
   ce->SetGridy();

   // Real surfaces taken from Wikipedia.
   const Int_t nx = 36;
   // see http://en.wikipedia.org/wiki/Area_and_population_of_European_countries
   char *countries[nx] = { "france",     "spain",  "sweden",  "germany",       "finland",
                           "norway",     "poland", "italy",   "yugoslavia",    "united_kingdom",
			   "romania",    "belarus","greece",  "czechoslovakia","bulgaria",
			   "iceland",    "hungary","portugal","austria",       "ireland",
			   "lithuania",  "latvia", "estonia", "denmark",       "netherlands",
                           "switzerland","moldova","belgium", "albania",       "cyprus",
			   "luxembourg", "andorra","malta",   "liechtenstein", "san_marino",
			   "monaco" };
   Float_t surfaces[nx] = { 547030,        505580,   449964,      357021,        338145,
                            324220,        312685,   301230,      255438,        244820,
			    237500,        207600,   131940,      127711,        110910,
			    103000,         93030,    89242,       83870,         70280,
			     65200,         64589,    45226,       43094,         41526,
			     41290,         33843,    30528,       28748,          9250,
			      2586,           468,      316,         160,            61,
                                 2};

   TH1F *h = new TH1F("h","Countries surfaces (in km^{2})",3,0,3);
   for (i=0; i<nx; i++) h->Fill(countries[i], surfaces[i]);
   h->LabelsDeflate();

   TFile::SetCacheFileDir(".");
   TFile *f;
   f = TFile::Open("http://root.cern.ch/files/europe.root","cacheread");

   TH2Poly *p = new TH2Poly(
             "Europe",
             "Europe (bin contents are normalized to the surfaces in km^{2})",
             lon1,lon2,lat1,lat2);
   p->GetXaxis()->SetNdivisions(520);
   p->GetXaxis()->SetTitle("longitude");
   p->GetYaxis()->SetTitle("latitude");

   TMultiGraph *mg;
   TKey *key;
   TIter nextkey(gDirectory->GetListOfKeys());
   while (key = (TKey*)nextkey()) {
      obj = key->ReadObj();
      if (obj->InheritsFrom("TMultiGraph")) {
         mg = (TMultiGraph*)obj;
         p->AddBin(mg);
      }
   }

   TRandom r;
   Double_t longitude, latitude;
   Double_t x, y, pi4 = TMath::Pi()/4, alpha = TMath::Pi()/360;

   gBenchmark->Start("Partitioning");
   p->ChangePartition(100, 100);
   gBenchmark->Show("Partitioning");

   // Fill TH2Poly according to a Mercator projection.
   gBenchmark->Start("Filling");
   for (i=0; i<npoints; i++) {
      longitude = r.Uniform(lon1,lon2);
      latitude  = r.Uniform(lat1,lat2);
      x         = longitude;
      y         = 38*TMath::Log(TMath::Tan(pi4+alpha*latitude));
      p->Fill(x,y);
   }
   gBenchmark->Show("Filling");

   Int_t nbins = p->GetNumberOfBins();
   Double_t maximum = p->GetMaximum();

   // h2 contains the surfaces computed from TH2Poly.
   TH1F *h2 = h->Clone("h2");
   h2->Reset();
   for (j=0; j<nx; j++) {
      for (i=0; i<nbins; i++) {
         if (strstr(countries[j],p->GetBinName(i+1))) {
            h2->Fill(countries[j],p->GetBinContent(i+1));
            h2->SetBinError(j, p->GetBinError(i+1));
         }
      }
   }

   // Normalize the TH2Poly bin contents to the real surfaces.
   Double_t scale = surfaces[0]/maximum;
   for (i=0; i<nbins; i++) p->SetBinContent(i+1, scale*p->GetBinContent(i+1));

   gStyle->SetOptStat(1111);
   gStyle->SetPalette(1);
   p->Draw("COL");

   TCanvas *c1 = new TCanvas("c1", "c1",W+10,0,W-20,H);
   c1->SetRightMargin(0.047);

   Double_t scale = h->GetMaximum()/h2->GetMaximum();

   h->SetStats(0);
   h->SetLineColor(kRed-3);
   h->SetLineWidth(2);
   h->SetMarkerStyle(20);
   h->SetMarkerColor(kBlue);
   h->SetMarkerSize(0.8);
   h->Draw("LP");
   h->GetXaxis()->SetLabelFont(42);
   h->GetXaxis()->SetLabelSize(0.03);
   h->GetYaxis()->SetLabelFont(42);

   h2->Scale(scale);
   Double_t scale2=TMath::Sqrt(scale);
   for (i=0; i<nx; i++) h2->SetBinError(i+1, scale2*h2->GetBinError(i+1));
   h2->Draw("E SAME");
   h2->SetMarkerStyle(20);
   h2->SetMarkerSize(0.8);

   TLegend *leg = new TLegend(0.5,0.67,0.92,0.8,NULL,"NDC");
   leg->SetTextFont(42);
   leg->SetTextSize(0.025);
   leg->AddEntry(h,"Real countries surfaces from Wikipedia (in km^{2})","lp");
   leg->AddEntry(h2,"Countries surfaces from TH2Poly (with errors)","lp");
   leg->Draw();
   leg->Draw();

   Double_t wikiSum = h->Integral();
   Double_t polySum = h2->Integral();
   Double_t error = TMath::Abs(wikiSum-polySum)/wikiSum;
   printf("THPoly Europe surface estimation error wrt wikipedia = %f per cent when using %d points\n",100*error,npoints);
}
<|endoftext|>


<commit_before>// @(#)root/cintex:$Id$
// Author: Pere Mato 2005

// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "Cintex/Cintex.h"
#include "CINTdefs.h"
#include "CINTScopeBuilder.h"
#include "CINTClassBuilder.h"
#include "CINTTypedefBuilder.h"
#include "Api.h"

using namespace ROOT::Reflex;
using namespace std;

namespace ROOT {

   namespace Cintex {

      int CINTTypedefBuilder::Setup(const Type& t) {
         // Setup typedef info.
         if ( t.IsTypedef() )  {

            std::string nam = CintName(t.Name(SCOPED));

            Type rt(t);
            Scope scope = rt.DeclaringScope();
            CINTScopeBuilder::Setup( scope );
            while ( rt.IsTypedef() ) rt = rt.ToType();

            Indirection indir = IndirectionGet(rt);
            Scope rscope = indir.second.DeclaringScope();

            if ( scope != rscope ) {
               if ( rscope ) CINTScopeBuilder::Setup(rscope);
               else {
                  rscope = Scope::ByName(Tools::GetScopeName(indir.second.Name(SCOPED)));
                  CINTScopeBuilder::Setup(rscope);
               }
            }

            if( -1 != G__defined_typename(nam.c_str()) ) return -1;

            if ( Cintex::Debug() )  {
               std::cout << "Cintex: Building typedef " << nam << std::endl;
            }

            int rtypenum;
            int rtagnum;
            CintType(rt, rtypenum, rtagnum );

            int stagnum = -1;
            if ( !scope.IsTopScope() ) stagnum = ::G__defined_tagname(CintName(scope.Name(SCOPED)).c_str(), 1);

            int r = ::G__search_typename2( t.Name().c_str(), rtypenum, rtagnum, 0, stagnum);
            ::G__setnewtype(-1,NULL,0);

            return r;
         }
         return -1;
      }

      void CINTTypedefBuilder::Set(const char* name, const char* value) {
         // As the function name indicates
         G__linked_taginfo taginfo;
         taginfo.tagnum  = -1;   // >> need to be pre-initialized to be understood by CINT
         taginfo.tagtype = 'c';
         taginfo.tagname = value;
         G__search_typename2(name, 117, G__get_linked_tagnum(&taginfo),0,-1);
         G__setnewtype(-1,NULL,0);
      }
   }
}
<commit_msg>Prevent Cintex from declaring typedef that are harmful to CINT<commit_after>// @(#)root/cintex:$Id$
// Author: Pere Mato 2005

// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "Cintex/Cintex.h"
#include "CINTdefs.h"
#include "CINTScopeBuilder.h"
#include "CINTClassBuilder.h"
#include "CINTTypedefBuilder.h"
#include "Api.h"

#include <set>

using namespace ROOT::Reflex;
using namespace std;

namespace ROOT {

   namespace Cintex {

      int CINTTypedefBuilder::Setup(const Type& t) {
         // Setup typedef info.
         if ( t.IsTypedef() )  {

            std::string nam = CintName(t.Name(SCOPED));

            static bool init = false;
            static std::set<std::string> exclusionList;
            if (!init) {
               exclusionList.insert("stringstream");
               init = true;
            }
            if ( exclusionList.find(nam) != exclusionList.end() ) {
               return -1;
            }

            Type rt(t);
            Scope scope = rt.DeclaringScope();
            CINTScopeBuilder::Setup( scope );
            while ( rt.IsTypedef() ) rt = rt.ToType();

            Indirection indir = IndirectionGet(rt);
            Scope rscope = indir.second.DeclaringScope();

            if ( scope != rscope ) {
               if ( rscope ) CINTScopeBuilder::Setup(rscope);
               else {
                  rscope = Scope::ByName(Tools::GetScopeName(indir.second.Name(SCOPED)));
                  CINTScopeBuilder::Setup(rscope);
               }
            }

            if( -1 != G__defined_typename(nam.c_str()) ) return -1;

            if ( Cintex::Debug() )  {
               std::cout << "Cintex: Building typedef " << nam << std::endl;
            }

            int rtypenum;
            int rtagnum;
            CintType(rt, rtypenum, rtagnum );

            int stagnum = -1;
            if ( !scope.IsTopScope() ) stagnum = ::G__defined_tagname(CintName(scope.Name(SCOPED)).c_str(), 1);

            int r = ::G__search_typename2( t.Name().c_str(), rtypenum, rtagnum, 0, stagnum);
            ::G__setnewtype(-1,NULL,0);

            return r;
         }
         return -1;
      }

      void CINTTypedefBuilder::Set(const char* name, const char* value) {
         // As the function name indicates
         G__linked_taginfo taginfo;
         taginfo.tagnum  = -1;   // >> need to be pre-initialized to be understood by CINT
         taginfo.tagtype = 'c';
         taginfo.tagname = value;
         G__search_typename2(name, 117, G__get_linked_tagnum(&taginfo),0,-1);
         G__setnewtype(-1,NULL,0);
      }
   }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

#include "PosixTimespec.hpp"

int main(int argc, char** argv)
{
    std::vector<timespec> timespecs;

    timespec tp;

    tp.tv_sec = 0;
    tp.tv_nsec = 0;
    timespecs.push_back(tp);

    tp.tv_sec = 1;
    tp.tv_nsec = 1;
    timespecs.push_back(tp);

    tp.tv_sec = 857693847;
    tp.tv_nsec = 736486;
    timespecs.push_back(tp);

    tp.tv_sec = 85769;
    tp.tv_nsec = 566486;
    timespecs.push_back(tp);

    std::vector<std::pair<unsigned int, unsigned int> > failed_cases;

    for (unsigned int i = 0; i < timespecs.size(); i++)
    {
        PosixTimespec ts1(timespecs[i]);

        for (unsigned int j = 0; j < timespecs.size(); j++)
        {
            PosixTimespec ts2(timespecs[j]);

            // Test addition
            PosixTimespec ts_sum1 = ts1 + ts2;
            PosixTimespec ts_sum2 = ts2 + ts1;
            if (!(ts_sum1 == ts_sum2 && ts_sum2 == ts_sum1))
            {
                failed_cases.push_back(
                    std::pair<unsigned int, unsigned int>(i, j));

                continue;
            }

            // Test equality and inequality
            if (i == j)
            {
                if (!(ts1 == ts2 && ts2 == ts1 &&
                      timespecs[i] == ts2 && ts2 == timespecs[i] &&
                      ts1 == timespecs[j] && timespecs[j] == ts1))
                {
                    failed_cases.push_back(
                        std::pair<unsigned int, unsigned int>(i, j));
                }
            }
            else
            {
                if (!(ts1 != ts2 && ts2 != ts1 &&
                      timespecs[i] != ts2 && ts2 != timespecs[i] &&
                      ts1 != timespecs[j] && timespecs[j] != ts1))
                {
                    failed_cases.push_back(
                        std::pair<unsigned int, unsigned int>(i, j));
                }
            }
        }
    }

    std::cout << "Failed cases: " << failed_cases.size() << "\n";

    // This unit test passes if no failed cases were recorded; remember that a
    // zero return value means success
    return failed_cases.size() != 0;
}
<commit_msg>Testing unit testing script in jenkins<commit_after>#include <iostream>
#include <vector>

#include "PosixTimespec.hpp"

int main(int argc, char** argv)
{
    std::vector<timespec> timespecs;

    timespec tp;

    tp.tv_sec = 0;
    tp.tv_nsec = 0;
    timespecs.push_back(tp);

    tp.tv_sec = 1;
    tp.tv_nsec = 1;
    timespecs.push_back(tp);

    tp.tv_sec = 857693847;
    tp.tv_nsec = 736486;
    timespecs.push_back(tp);

    tp.tv_sec = 85769;
    tp.tv_nsec = 566486;
    timespecs.push_back(tp);

    std::vector<std::pair<unsigned int, unsigned int> > failed_cases;

    for (unsigned int i = 0; i < timespecs.size(); i++)
    {
        PosixTimespec ts1(timespecs[i]);

        for (unsigned int j = 0; j < timespecs.size(); j++)
        {
            PosixTimespec ts2(timespecs[j]);

            // Test addition
            PosixTimespec ts_sum1 = ts1 + ts2;
            PosixTimespec ts_sum2 = ts2 + ts1;
            if (!(ts_sum1 == ts_sum2 && ts_sum2 == ts_sum1))
            {
                failed_cases.push_back(
                    std::pair<unsigned int, unsigned int>(i, j));

                continue;
            }

            // Test equality and inequality
            if (i == j)
            {
                if (!(ts1 == ts2 && ts2 == ts1 &&
                      timespecs[i] == ts2 && ts2 == timespecs[i] &&
                      ts1 == timespecs[j] && timespecs[j] == ts1))
                {
                    failed_cases.push_back(
                        std::pair<unsigned int, unsigned int>(i, j));
                }
            }
            else
            {
                if (!(ts1 != ts2 && ts2 != ts1 &&
                      timespecs[i] != ts2 && ts2 != timespecs[i] &&
                      ts1 != timespecs[j] && timespecs[j] != ts1))
                {
                    failed_cases.push_back(
                        std::pair<unsigned int, unsigned int>(i, j));
                }
            }
        }
    }

    std::cout << "Failed cases: " << failed_cases.size() << "\n";

    // This unit test passes if no failed cases were recorded; remember that a
    // zero return value means success
    return failed_cases.size() == 0;
}
<|endoftext|>