<commit_before>/*
    SWARM

    Copyright (C) 2012-2019 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"

inline void nt_set(char * seq, unsigned int pos, unsigned int base)
{
  unsigned int whichlong = pos >> 5;
  uint64_t shift = (pos & 31) << 1;
  uint64_t mask = 3ULL << shift;
  uint64_t x = (reinterpret_cast<uint64_t *>(seq))[whichlong];
  x &= ~ mask;
  x |= (static_cast<uint64_t>(base)) << shift;
  (reinterpret_cast<uint64_t *>(seq))[whichlong] = x;
}

inline void seq_copy(char * a,
                     unsigned int a_start,
                     char * b,
                     unsigned int b_start,
                     unsigned int length)
{
  /* copy part of the compressed sequence b to a */
  for(unsigned int i = 0; i < length; i++)
    nt_set(a, a_start + i, nt_extract(b, b_start + i));
}

inline bool seq_identical(char * a,
                          unsigned int a_start,
                          char * b,
                          unsigned int b_start,
                          unsigned int length)
{
  /* compare parts of two compressed sequences a and b */
  /* return false if different, true if identical */

  for(unsigned int i = 0; i < length; i++)
    if (nt_extract(a, a_start + i) != nt_extract(b, b_start + i))
      return false;
  return true;
}

void generate_variant_sequence(char * seed_sequence,
                               unsigned int seed_seqlen,
                               struct var_s * var,
                               char * seq,
                               unsigned int * seqlen)
{
  /* generate the actual sequence of a variant */

  switch (var->type)
    {
    case identical:
      memcpy(seq, seed_sequence, nt_bytelength(seed_seqlen));
      * seqlen = seed_seqlen;
      break;

    case substitution:
      memcpy(seq, seed_sequence, nt_bytelength(seed_seqlen));
      nt_set(seq, var->pos, var->base);
      * seqlen = seed_seqlen;
      break;

    case deletion:
      seq_copy(seq, 0,
               seed_sequence, 0,
               var->pos);
      seq_copy(seq, var->pos,
               seed_sequence, var->pos + 1,
               seed_seqlen - var->pos - 1);
      * seqlen = seed_seqlen - 1;
      break;

    case insertion:
      seq_copy(seq, 0,
               seed_sequence, 0,
               var->pos);
      nt_set(seq, var->pos, var->base);
      seq_copy(seq, var->pos + 1,
               seed_sequence, var->pos,
               seed_seqlen - var->pos);
      * seqlen = seed_seqlen + 1;
      break;

    default:
      assert(0);
    }
}

bool check_variant(char * seed_sequence,
                   unsigned int seed_seqlen,
                   var_s * var,
                   char * amp_sequence,
                   unsigned int amp_seqlen)
{
  /* make sure seed with given variant is really identical to amp */
  /* we know the hashes are identical */

  switch (var->type)
    {
    case identical:
      if (seed_seqlen != amp_seqlen)
        return false;
      return seq_identical(seed_sequence, 0,
                           amp_sequence, 0,
                           seed_seqlen);

    case substitution:
      if (seed_seqlen != amp_seqlen)
        return false;
      if (! seq_identical(seed_sequence, 0,
                          amp_sequence, 0,
                          var->pos))
        return false;
      if (nt_extract(amp_sequence, var->pos) != var->base)
        return false;
      return seq_identical(seed_sequence, var->pos + 1,
                           amp_sequence,  var->pos + 1,
                           seed_seqlen - var->pos - 1);

    case deletion:
      if ((seed_seqlen - 1) != amp_seqlen)
        return false;
      if (! seq_identical(seed_sequence, 0,
                          amp_sequence, 0,
                          var->pos))
        return false;
      return seq_identical(seed_sequence, var->pos + 1,
                           amp_sequence,  var->pos,
                           seed_seqlen - var->pos - 1);

    case insertion:
      if ((seed_seqlen + 1) != amp_seqlen)
        return false;
      if (! seq_identical(seed_sequence, 0,
                          amp_sequence, 0,
                          var->pos))
        return false;
      if (nt_extract(amp_sequence, var->pos) != var->base)
        return false;
      return seq_identical(seed_sequence, var->pos,
                           amp_sequence,  var->pos + 1,
                           seed_seqlen - var->pos);

    default:
      assert(0);
    }
}

inline void add_variant(uint64_t hash,
                        unsigned char type,
                        unsigned int pos,
                        unsigned char base,
                        var_s * variant_list,
                        unsigned int * variant_count)
{
#ifdef HASHSTATS
  tries++;
#endif
  var_s * v = variant_list + (*variant_count)++;
  v->hash = hash;
  v->type = type;
  v->pos = pos;
  v->base = base;
}

void generate_variants(char * sequence,
                       unsigned int seqlen,
                       uint64_t hash,
                       var_s * variant_list,
                       unsigned int * variant_count)
{
  /* substitutions */

  for(unsigned int i = 0; i < seqlen; i++)
    {
      unsigned char base = nt_extract(sequence, i);
      uint64_t hash1 = hash ^ zobrist_value(i, base);
      for (unsigned char v = 0; v < 4; v ++)
        if (v != base)
          {
            uint64_t hash2 = hash1 ^ zobrist_value(i, v);
            add_variant(hash2, substitution, i, v,
                        variant_list, variant_count);
          }
    }

  /* deletions */

  hash = zobrist_hash_delete_first(reinterpret_cast<unsigned char *>(sequence), seqlen);
  add_variant(hash, deletion, 0, 0, variant_list, variant_count);
  unsigned char base_deleted = nt_extract(sequence, 0);
  for(unsigned int i = 1; i < seqlen; i++)
    {
      unsigned char v = nt_extract(sequence, i);
      if (v != base_deleted)
        {
          hash ^= zobrist_value(i - 1, base_deleted) ^ zobrist_value(i - 1, v);
          add_variant(hash, deletion, i, 0, variant_list, variant_count);
          base_deleted = v;
        }
    }

  /* insertions */

  hash = zobrist_hash_insert_first(reinterpret_cast<unsigned char *>(sequence), seqlen);
  for (unsigned char v = 0; v < 4; v++)
    {
      uint64_t hash1 = hash ^ zobrist_value(0, v);
      add_variant(hash1, insertion, 0, v, variant_list, variant_count);
    }
  for (unsigned int i = 0; i < seqlen; i++)
    {
      unsigned char base = nt_extract(sequence, i);
      hash ^= zobrist_value(i, base) ^ zobrist_value(i+1, base);
      for (unsigned char v = 0; v < 4; v++)
        if (v != base)
          {
            uint64_t hash1 = hash ^ zobrist_value(i + 1, v);
            add_variant(hash1, insertion, i + 1, v,
                        variant_list, variant_count);
          }
    }
}
<commit_msg>Fix compiler warning<commit_after>/*
    SWARM

    Copyright (C) 2012-2019 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"

inline void nt_set(char * seq, unsigned int pos, unsigned int base)
{
  unsigned int whichlong = pos >> 5;
  uint64_t shift = (pos & 31) << 1;
  uint64_t mask = 3ULL << shift;
  uint64_t x = (reinterpret_cast<uint64_t *>(seq))[whichlong];
  x &= ~ mask;
  x |= (static_cast<uint64_t>(base)) << shift;
  (reinterpret_cast<uint64_t *>(seq))[whichlong] = x;
}

inline void seq_copy(char * a,
                     unsigned int a_start,
                     char * b,
                     unsigned int b_start,
                     unsigned int length)
{
  /* copy part of the compressed sequence b to a */
  for(unsigned int i = 0; i < length; i++)
    nt_set(a, a_start + i, nt_extract(b, b_start + i));
}

inline bool seq_identical(char * a,
                          unsigned int a_start,
                          char * b,
                          unsigned int b_start,
                          unsigned int length)
{
  /* compare parts of two compressed sequences a and b */
  /* return false if different, true if identical */

  for(unsigned int i = 0; i < length; i++)
    if (nt_extract(a, a_start + i) != nt_extract(b, b_start + i))
      return false;
  return true;
}

void generate_variant_sequence(char * seed_sequence,
                               unsigned int seed_seqlen,
                               struct var_s * var,
                               char * seq,
                               unsigned int * seqlen)
{
  /* generate the actual sequence of a variant */

  switch (var->type)
    {
    case identical:
      memcpy(seq, seed_sequence, nt_bytelength(seed_seqlen));
      * seqlen = seed_seqlen;
      break;

    case substitution:
      memcpy(seq, seed_sequence, nt_bytelength(seed_seqlen));
      nt_set(seq, var->pos, var->base);
      * seqlen = seed_seqlen;
      break;

    case deletion:
      seq_copy(seq, 0,
               seed_sequence, 0,
               var->pos);
      seq_copy(seq, var->pos,
               seed_sequence, var->pos + 1,
               seed_seqlen - var->pos - 1);
      * seqlen = seed_seqlen - 1;
      break;

    case insertion:
      seq_copy(seq, 0,
               seed_sequence, 0,
               var->pos);
      nt_set(seq, var->pos, var->base);
      seq_copy(seq, var->pos + 1,
               seed_sequence, var->pos,
               seed_seqlen - var->pos);
      * seqlen = seed_seqlen + 1;
      break;

    default:
      assert(0);
    }
}

bool check_variant(char * seed_sequence,
                   unsigned int seed_seqlen,
                   var_s * var,
                   char * amp_sequence,
                   unsigned int amp_seqlen)
{
  /* make sure seed with given variant is really identical to amp */
  /* we know the hashes are identical */

  switch (var->type)
    {
    case identical:
      if (seed_seqlen != amp_seqlen)
        return false;
      return seq_identical(seed_sequence, 0,
                           amp_sequence, 0,
                           seed_seqlen);

    case substitution:
      if (seed_seqlen != amp_seqlen)
        return false;
      if (! seq_identical(seed_sequence, 0,
                          amp_sequence, 0,
                          var->pos))
        return false;
      if (nt_extract(amp_sequence, var->pos) != var->base)
        return false;
      return seq_identical(seed_sequence, var->pos + 1,
                           amp_sequence,  var->pos + 1,
                           seed_seqlen - var->pos - 1);

    case deletion:
      if ((seed_seqlen - 1) != amp_seqlen)
        return false;
      if (! seq_identical(seed_sequence, 0,
                          amp_sequence, 0,
                          var->pos))
        return false;
      return seq_identical(seed_sequence, var->pos + 1,
                           amp_sequence,  var->pos,
                           seed_seqlen - var->pos - 1);

    case insertion:
      if ((seed_seqlen + 1) != amp_seqlen)
        return false;
      if (! seq_identical(seed_sequence, 0,
                          amp_sequence, 0,
                          var->pos))
        return false;
      if (nt_extract(amp_sequence, var->pos) != var->base)
        return false;
      return seq_identical(seed_sequence, var->pos,
                           amp_sequence,  var->pos + 1,
                           seed_seqlen - var->pos);

    default:
      assert(0);
      return false;
    }
}

inline void add_variant(uint64_t hash,
                        unsigned char type,
                        unsigned int pos,
                        unsigned char base,
                        var_s * variant_list,
                        unsigned int * variant_count)
{
#ifdef HASHSTATS
  tries++;
#endif
  var_s * v = variant_list + (*variant_count)++;
  v->hash = hash;
  v->type = type;
  v->pos = pos;
  v->base = base;
}

void generate_variants(char * sequence,
                       unsigned int seqlen,
                       uint64_t hash,
                       var_s * variant_list,
                       unsigned int * variant_count)
{
  /* substitutions */

  for(unsigned int i = 0; i < seqlen; i++)
    {
      unsigned char base = nt_extract(sequence, i);
      uint64_t hash1 = hash ^ zobrist_value(i, base);
      for (unsigned char v = 0; v < 4; v ++)
        if (v != base)
          {
            uint64_t hash2 = hash1 ^ zobrist_value(i, v);
            add_variant(hash2, substitution, i, v,
                        variant_list, variant_count);
          }
    }

  /* deletions */

  hash = zobrist_hash_delete_first(reinterpret_cast<unsigned char *>(sequence), seqlen);
  add_variant(hash, deletion, 0, 0, variant_list, variant_count);
  unsigned char base_deleted = nt_extract(sequence, 0);
  for(unsigned int i = 1; i < seqlen; i++)
    {
      unsigned char v = nt_extract(sequence, i);
      if (v != base_deleted)
        {
          hash ^= zobrist_value(i - 1, base_deleted) ^ zobrist_value(i - 1, v);
          add_variant(hash, deletion, i, 0, variant_list, variant_count);
          base_deleted = v;
        }
    }

  /* insertions */

  hash = zobrist_hash_insert_first(reinterpret_cast<unsigned char *>(sequence), seqlen);
  for (unsigned char v = 0; v < 4; v++)
    {
      uint64_t hash1 = hash ^ zobrist_value(0, v);
      add_variant(hash1, insertion, 0, v, variant_list, variant_count);
    }
  for (unsigned int i = 0; i < seqlen; i++)
    {
      unsigned char base = nt_extract(sequence, i);
      hash ^= zobrist_value(i, base) ^ zobrist_value(i+1, base);
      for (unsigned char v = 0; v < 4; v++)
        if (v != base)
          {
            uint64_t hash1 = hash ^ zobrist_value(i + 1, v);
            add_variant(hash1, insertion, i + 1, v,
                        variant_list, variant_count);
          }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Vcoin");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "54182cb"
#    define GIT_COMMIT_DATE "Wed, 1 Oct 2014 08:01:20 -0700"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>12.0.1<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Vcoin");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "54182cb"
#    define GIT_COMMIT_DATE "Thu, 1 Jan 2015 01:01:01 -0700"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "$Format:%h$"
#    define GIT_COMMIT_DATE "$Format:%cD$"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(PEERCOIN_VERSION_MAJOR, PEERCOIN_VERSION_MINOR, PEERCOIN_VERSION_REVISION, PEERCOIN_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(PEERCOIN_VERSION_MAJOR, PEERCOIN_VERSION_MINOR, PEERCOIN_VERSION_REVISION, PEERCOIN_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Remove -beta suffix on release-0.6 branch<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   ""

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "$Format:%h$"
#    define GIT_COMMIT_DATE "$Format:%cD$"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(PEERCOIN_VERSION_MAJOR, PEERCOIN_VERSION_MINOR, PEERCOIN_VERSION_REVISION, PEERCOIN_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(PEERCOIN_VERSION_MAJOR, PEERCOIN_VERSION_MINOR, PEERCOIN_VERSION_REVISION, PEERCOIN_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"

#include <Eigen/CXX11/Tensor>

using Eigen::Tensor;
using Eigen::RowMajor;

static void test_simple_lvalue_ref()
{
  Tensor<int, 1> input(6);
  input.setRandom();

  TensorRef<Tensor<int, 1>> ref3(input);
  TensorRef<Tensor<int, 1>> ref4 = input;

  VERIFY_IS_EQUAL(ref3.data(), input.data());
  VERIFY_IS_EQUAL(ref4.data(), input.data());

  for (int i = 0; i < 6; ++i) {
    VERIFY_IS_EQUAL(ref3(i), input(i));
    VERIFY_IS_EQUAL(ref4(i), input(i));
  }

  for (int i = 0; i < 6; ++i) {
    ref3.coeffRef(i) = i;
  }
  for (int i = 0; i < 6; ++i) {
    VERIFY_IS_EQUAL(input(i), i);
  }
  for (int i = 0; i < 6; ++i) {
    ref4.coeffRef(i) = -i * 2;
  }
  for (int i = 0; i < 6; ++i) {
    VERIFY_IS_EQUAL(input(i), -i*2);
  }
}

static void test_simple_rvalue_ref()
{
  Tensor<int, 1> input1(6);
  input1.setRandom();
  Tensor<int, 1> input2(6);
  input2.setRandom();

  TensorRef<Tensor<int, 1>> ref3(input1 + input2);
  TensorRef<Tensor<int, 1>> ref4 = input1 + input2;

  VERIFY_IS_NOT_EQUAL(ref3.data(), input1.data());
  VERIFY_IS_NOT_EQUAL(ref4.data(), input1.data());
  VERIFY_IS_NOT_EQUAL(ref3.data(), input2.data());
  VERIFY_IS_NOT_EQUAL(ref4.data(), input2.data());

  for (int i = 0; i < 6; ++i) {
    VERIFY_IS_EQUAL(ref3(i), input1(i) + input2(i));
    VERIFY_IS_EQUAL(ref4(i), input1(i) + input2(i));
  }
}

static void test_multiple_dims()
{
  Tensor<float, 3> input(3,5,7);
  input.setRandom();

  TensorRef<Tensor<float, 3>> ref(input);
  VERIFY_IS_EQUAL(ref.data(), input.data());
  VERIFY_IS_EQUAL(ref.dimension(0), 3);
  VERIFY_IS_EQUAL(ref.dimension(1), 5);
  VERIFY_IS_EQUAL(ref.dimension(2), 7);

  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 5; ++j) {
      for (int k = 0; k < 7; ++k) {
        VERIFY_IS_EQUAL(ref(i,j,k), input(i,j,k));
      }
    }
  }
}

static void test_slice()
{
  Tensor<float, 5> tensor(2,3,5,7,11);
  tensor.setRandom();

  Eigen::DSizes<ptrdiff_t, 5> indices(1,2,3,4,5);
  Eigen::DSizes<ptrdiff_t, 5> sizes(1,1,1,1,1);
  TensorRef<Tensor<float, 5>> slice = tensor.slice(indices, sizes);
  VERIFY_IS_EQUAL(slice(0,0,0,0,0), tensor(1,2,3,4,5));

  Eigen::DSizes<ptrdiff_t, 5> indices2(1,1,3,4,5);
  Eigen::DSizes<ptrdiff_t, 5> sizes2(1,1,2,2,3);
  slice = tensor.slice(indices2, sizes2);
  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 2; ++j) {
      for (int k = 0; k < 3; ++k) {
        VERIFY_IS_EQUAL(slice(0,0,i,j,k), tensor(1,1,3+i,4+j,5+k));
      }
    }
  }

  Eigen::DSizes<ptrdiff_t, 5> indices3(0,0,0,0,0);
  Eigen::DSizes<ptrdiff_t, 5> sizes3(2,3,1,1,1);
  slice = tensor.slice(indices3, sizes3);
  VERIFY_IS_EQUAL(slice.data(), tensor.data());
}

static void test_ref_of_ref()
{
  Tensor<float, 3> input(3,5,7);
  input.setRandom();

  TensorRef<Tensor<float, 3>> ref(input);
  TensorRef<Tensor<float, 3>> ref_of_ref(ref);
  TensorRef<Tensor<float, 3>> ref_of_ref2;
  ref_of_ref2 = ref;

  VERIFY_IS_EQUAL(ref_of_ref.data(), input.data());
  VERIFY_IS_EQUAL(ref_of_ref.dimension(0), 3);
  VERIFY_IS_EQUAL(ref_of_ref.dimension(1), 5);
  VERIFY_IS_EQUAL(ref_of_ref.dimension(2), 7);

  VERIFY_IS_EQUAL(ref_of_ref2.data(), input.data());
  VERIFY_IS_EQUAL(ref_of_ref2.dimension(0), 3);
  VERIFY_IS_EQUAL(ref_of_ref2.dimension(1), 5);
  VERIFY_IS_EQUAL(ref_of_ref2.dimension(2), 7);

  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 5; ++j) {
      for (int k = 0; k < 7; ++k) {
        VERIFY_IS_EQUAL(ref_of_ref(i,j,k), input(i,j,k));
        VERIFY_IS_EQUAL(ref_of_ref2(i,j,k), input(i,j,k));
     }
    }
  }
}

static void test_ref_in_expr()
{
  Tensor<float, 3> input(3,5,7);
  input.setRandom();
  TensorRef<Tensor<float, 3>> input_ref(input);

  Tensor<float, 3> result(3,5,7);
  result.setRandom();
  TensorRef<Tensor<float, 3>> result_ref(result);

  Tensor<float, 3> bias(3,5,7);
  bias.setRandom();

  result_ref = input_ref + bias;
  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 5; ++j) {
      for (int k = 0; k < 7; ++k) {
        VERIFY_IS_EQUAL(result_ref(i,j,k), input(i,j,k) + bias(i,j,k));
        VERIFY_IS_NOT_EQUAL(result(i,j,k), input(i,j,k) + bias(i,j,k));
      }
    }
  }

  result = result_ref;
  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 5; ++j) {
      for (int k = 0; k < 7; ++k) {
        VERIFY_IS_EQUAL(result(i,j,k), input(i,j,k) + bias(i,j,k));
      }
    }
  }
}

static void test_coeff_ref()
{
  Tensor<float, 5> tensor(2,3,5,7,11);
  tensor.setRandom();
  Tensor<float, 5> original = tensor;

  TensorRef<Tensor<float, 4>> slice = tensor.chip(7, 4);
  slice.coeffRef(0, 0, 0, 0) = 1.0f;
  slice.coeffRef(1, 0, 0, 0) += 2.0f;

  VERIFY_IS_EQUAL(tensor(0,0,0,0,7), 1.0f);
  VERIFY_IS_EQUAL(tensor(1,0,0,0,7), original(1,0,0,0,7) + 2.0f);
}

static void test_nested_ops_with_ref()
{
  Tensor<float, 4> t(2, 3, 5, 7);
  t.setRandom();
  TensorMap<Tensor<const float, 4> > m(t.data(), 2, 3, 5, 7);
  array<pair<ptrdiff_t, ptrdiff_t>, 4> paddings;
  paddings[0] = make_pair(0, 0);
  paddings[1] = make_pair(2, 1);
  paddings[2] = make_pair(3, 4);
  paddings[3] = make_pair(0, 0);
  Eigen::DSizes<Eigen::DenseIndex, 4> shuffle_dims{0, 1, 2, 3};
  TensorRef<Tensor<const float, 4> > ref(m.pad(paddings));
  array<pair<ptrdiff_t, ptrdiff_t>, 4> trivial;
  trivial[0] = make_pair(0, 0);
  trivial[1] = make_pair(0, 0);
  trivial[2] = make_pair(0, 0);
  trivial[3] = make_pair(0, 0);
  Tensor<float, 4> padded = ref.shuffle(shuffle_dims).pad(trivial);
  VERIFY_IS_EQUAL(padded.dimension(0), 2+0);
  VERIFY_IS_EQUAL(padded.dimension(1), 3+3);
  VERIFY_IS_EQUAL(padded.dimension(2), 5+7);
  VERIFY_IS_EQUAL(padded.dimension(3), 7+0);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 6; ++j) {
      for (int k = 0; k < 12; ++k) {
        for (int l = 0; l < 7; ++l) {
          if (j >= 2 && j < 5 && k >= 3 && k < 8) {
            VERIFY_IS_EQUAL(padded(i,j,k,l), t(i,j-2,k-3,l));
          } else {
            VERIFY_IS_EQUAL(padded(i,j,k,l), 0.0f);
          }
        }
      }
    }
  }
}

void test_cxx11_tensor_ref()
{
  CALL_SUBTEST(test_simple_lvalue_ref());
  CALL_SUBTEST(test_simple_rvalue_ref());
  CALL_SUBTEST(test_multiple_dims());
  CALL_SUBTEST(test_slice());
  CALL_SUBTEST(test_ref_of_ref());
  CALL_SUBTEST(test_ref_in_expr());
  CALL_SUBTEST(test_coeff_ref());
  CALL_SUBTEST(test_nested_ops_with_ref());
}
<commit_msg>Fixed compilation error with clang<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"

#include <Eigen/CXX11/Tensor>

using Eigen::Tensor;
using Eigen::RowMajor;

static void test_simple_lvalue_ref()
{
  Tensor<int, 1> input(6);
  input.setRandom();

  TensorRef<Tensor<int, 1>> ref3(input);
  TensorRef<Tensor<int, 1>> ref4 = input;

  VERIFY_IS_EQUAL(ref3.data(), input.data());
  VERIFY_IS_EQUAL(ref4.data(), input.data());

  for (int i = 0; i < 6; ++i) {
    VERIFY_IS_EQUAL(ref3(i), input(i));
    VERIFY_IS_EQUAL(ref4(i), input(i));
  }

  for (int i = 0; i < 6; ++i) {
    ref3.coeffRef(i) = i;
  }
  for (int i = 0; i < 6; ++i) {
    VERIFY_IS_EQUAL(input(i), i);
  }
  for (int i = 0; i < 6; ++i) {
    ref4.coeffRef(i) = -i * 2;
  }
  for (int i = 0; i < 6; ++i) {
    VERIFY_IS_EQUAL(input(i), -i*2);
  }
}

static void test_simple_rvalue_ref()
{
  Tensor<int, 1> input1(6);
  input1.setRandom();
  Tensor<int, 1> input2(6);
  input2.setRandom();

  TensorRef<Tensor<int, 1>> ref3(input1 + input2);
  TensorRef<Tensor<int, 1>> ref4 = input1 + input2;

  VERIFY_IS_NOT_EQUAL(ref3.data(), input1.data());
  VERIFY_IS_NOT_EQUAL(ref4.data(), input1.data());
  VERIFY_IS_NOT_EQUAL(ref3.data(), input2.data());
  VERIFY_IS_NOT_EQUAL(ref4.data(), input2.data());

  for (int i = 0; i < 6; ++i) {
    VERIFY_IS_EQUAL(ref3(i), input1(i) + input2(i));
    VERIFY_IS_EQUAL(ref4(i), input1(i) + input2(i));
  }
}

static void test_multiple_dims()
{
  Tensor<float, 3> input(3,5,7);
  input.setRandom();

  TensorRef<Tensor<float, 3>> ref(input);
  VERIFY_IS_EQUAL(ref.data(), input.data());
  VERIFY_IS_EQUAL(ref.dimension(0), 3);
  VERIFY_IS_EQUAL(ref.dimension(1), 5);
  VERIFY_IS_EQUAL(ref.dimension(2), 7);

  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 5; ++j) {
      for (int k = 0; k < 7; ++k) {
        VERIFY_IS_EQUAL(ref(i,j,k), input(i,j,k));
      }
    }
  }
}

static void test_slice()
{
  Tensor<float, 5> tensor(2,3,5,7,11);
  tensor.setRandom();

  Eigen::DSizes<ptrdiff_t, 5> indices(1,2,3,4,5);
  Eigen::DSizes<ptrdiff_t, 5> sizes(1,1,1,1,1);
  TensorRef<Tensor<float, 5>> slice = tensor.slice(indices, sizes);
  VERIFY_IS_EQUAL(slice(0,0,0,0,0), tensor(1,2,3,4,5));

  Eigen::DSizes<ptrdiff_t, 5> indices2(1,1,3,4,5);
  Eigen::DSizes<ptrdiff_t, 5> sizes2(1,1,2,2,3);
  slice = tensor.slice(indices2, sizes2);
  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 2; ++j) {
      for (int k = 0; k < 3; ++k) {
        VERIFY_IS_EQUAL(slice(0,0,i,j,k), tensor(1,1,3+i,4+j,5+k));
      }
    }
  }

  Eigen::DSizes<ptrdiff_t, 5> indices3(0,0,0,0,0);
  Eigen::DSizes<ptrdiff_t, 5> sizes3(2,3,1,1,1);
  slice = tensor.slice(indices3, sizes3);
  VERIFY_IS_EQUAL(slice.data(), tensor.data());
}

static void test_ref_of_ref()
{
  Tensor<float, 3> input(3,5,7);
  input.setRandom();

  TensorRef<Tensor<float, 3>> ref(input);
  TensorRef<Tensor<float, 3>> ref_of_ref(ref);
  TensorRef<Tensor<float, 3>> ref_of_ref2;
  ref_of_ref2 = ref;

  VERIFY_IS_EQUAL(ref_of_ref.data(), input.data());
  VERIFY_IS_EQUAL(ref_of_ref.dimension(0), 3);
  VERIFY_IS_EQUAL(ref_of_ref.dimension(1), 5);
  VERIFY_IS_EQUAL(ref_of_ref.dimension(2), 7);

  VERIFY_IS_EQUAL(ref_of_ref2.data(), input.data());
  VERIFY_IS_EQUAL(ref_of_ref2.dimension(0), 3);
  VERIFY_IS_EQUAL(ref_of_ref2.dimension(1), 5);
  VERIFY_IS_EQUAL(ref_of_ref2.dimension(2), 7);

  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 5; ++j) {
      for (int k = 0; k < 7; ++k) {
        VERIFY_IS_EQUAL(ref_of_ref(i,j,k), input(i,j,k));
        VERIFY_IS_EQUAL(ref_of_ref2(i,j,k), input(i,j,k));
     }
    }
  }
}

static void test_ref_in_expr()
{
  Tensor<float, 3> input(3,5,7);
  input.setRandom();
  TensorRef<Tensor<float, 3>> input_ref(input);

  Tensor<float, 3> result(3,5,7);
  result.setRandom();
  TensorRef<Tensor<float, 3>> result_ref(result);

  Tensor<float, 3> bias(3,5,7);
  bias.setRandom();

  result_ref = input_ref + bias;
  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 5; ++j) {
      for (int k = 0; k < 7; ++k) {
        VERIFY_IS_EQUAL(result_ref(i,j,k), input(i,j,k) + bias(i,j,k));
        VERIFY_IS_NOT_EQUAL(result(i,j,k), input(i,j,k) + bias(i,j,k));
      }
    }
  }

  result = result_ref;
  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 5; ++j) {
      for (int k = 0; k < 7; ++k) {
        VERIFY_IS_EQUAL(result(i,j,k), input(i,j,k) + bias(i,j,k));
      }
    }
  }
}

static void test_coeff_ref()
{
  Tensor<float, 5> tensor(2,3,5,7,11);
  tensor.setRandom();
  Tensor<float, 5> original = tensor;

  TensorRef<Tensor<float, 4>> slice = tensor.chip(7, 4);
  slice.coeffRef(0, 0, 0, 0) = 1.0f;
  slice.coeffRef(1, 0, 0, 0) += 2.0f;

  VERIFY_IS_EQUAL(tensor(0,0,0,0,7), 1.0f);
  VERIFY_IS_EQUAL(tensor(1,0,0,0,7), original(1,0,0,0,7) + 2.0f);
}

static void test_nested_ops_with_ref()
{
  Tensor<float, 4> t(2, 3, 5, 7);
  t.setRandom();
  TensorMap<Tensor<const float, 4> > m(t.data(), 2, 3, 5, 7);
  array<std::pair<ptrdiff_t, ptrdiff_t>, 4> paddings;
  paddings[0] = std::make_pair(0, 0);
  paddings[1] = std::make_pair(2, 1);
  paddings[2] = std::make_pair(3, 4);
  paddings[3] = std::make_pair(0, 0);
  DSizes<Eigen::DenseIndex, 4> shuffle_dims{0, 1, 2, 3};
  TensorRef<Tensor<const float, 4> > ref(m.pad(paddings));
  array<std::pair<ptrdiff_t, ptrdiff_t>, 4> trivial;
  trivial[0] = std::make_pair(0, 0);
  trivial[1] = std::make_pair(0, 0);
  trivial[2] = std::make_pair(0, 0);
  trivial[3] = std::make_pair(0, 0);
  Tensor<float, 4> padded = ref.shuffle(shuffle_dims).pad(trivial);
  VERIFY_IS_EQUAL(padded.dimension(0), 2+0);
  VERIFY_IS_EQUAL(padded.dimension(1), 3+3);
  VERIFY_IS_EQUAL(padded.dimension(2), 5+7);
  VERIFY_IS_EQUAL(padded.dimension(3), 7+0);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 6; ++j) {
      for (int k = 0; k < 12; ++k) {
        for (int l = 0; l < 7; ++l) {
          if (j >= 2 && j < 5 && k >= 3 && k < 8) {
            VERIFY_IS_EQUAL(padded(i,j,k,l), t(i,j-2,k-3,l));
          } else {
            VERIFY_IS_EQUAL(padded(i,j,k,l), 0.0f);
          }
        }
      }
    }
  }
}

void test_cxx11_tensor_ref()
{
  CALL_SUBTEST(test_simple_lvalue_ref());
  CALL_SUBTEST(test_simple_rvalue_ref());
  CALL_SUBTEST(test_multiple_dims());
  CALL_SUBTEST(test_slice());
  CALL_SUBTEST(test_ref_of_ref());
  CALL_SUBTEST(test_ref_in_expr());
  CALL_SUBTEST(test_coeff_ref());
  CALL_SUBTEST(test_nested_ops_with_ref());
}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"
#include <unsupported/Eigen/Polynomials>
#include <iostream>
#include <algorithm>

using namespace std;

namespace Eigen {
namespace internal {
template<int Size>
struct increment_if_fixed_size
{
  enum {
    ret = (Size == Dynamic) ? Dynamic : Size+1
  };
};
}
}

template<int Deg, typename POLYNOMIAL, typename SOLVER>
bool aux_evalSolver( const POLYNOMIAL& pols, SOLVER& psolve )
{
  typedef typename POLYNOMIAL::Index Index;
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef typename SOLVER::RootsType    RootsType;
  typedef Matrix<Scalar,Deg,1>          EvalRootsType;

  const Index deg = pols.size()-1;

  psolve.compute( pols );
  const RootsType& roots( psolve.roots() );
  EvalRootsType evr( deg );
  for( int i=0; i<roots.size(); ++i ){
    evr[i] = std::abs( poly_eval( pols, roots[i] ) ); }

  bool evalToZero = evr.isZero( test_precision<Scalar>() );
  if( !evalToZero )
  {
    cerr << "WRONG root: " << endl;
    cerr << "Polynomial: " << pols.transpose() << endl;
    cerr << "Roots found: " << roots.transpose() << endl;
    cerr << "Abs value of the polynomial at the roots: " << evr.transpose() << endl;
    cerr << endl;
  }

  std::vector<Scalar> rootModuli( roots.size() );
  Map< EvalRootsType > aux( &rootModuli[0], roots.size() );
  aux = roots.array().abs();
  std::sort( rootModuli.begin(), rootModuli.end() );
  bool distinctModuli=true;
  for( size_t i=1; i<rootModuli.size() && distinctModuli; ++i )
  {
    if( internal::isApprox( rootModuli[i], rootModuli[i-1] ) ){
      distinctModuli = false; }
  }
  VERIFY( evalToZero || !distinctModuli );

  return distinctModuli;
}

template<int Deg, typename POLYNOMIAL>
void evalSolver( const POLYNOMIAL& pols )
{
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

  PolynomialSolverType psolve;
  aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve );
}

template< int Deg, typename POLYNOMIAL, typename ROOTS, typename REAL_ROOTS >
void evalSolverSugarFunction( const POLYNOMIAL& pols, const ROOTS& roots, const REAL_ROOTS& real_roots )
{
  using std::sqrt;
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

  PolynomialSolverType psolve;
  if( aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve ) )
  {
    //It is supposed that
    // 1) the roots found are correct
    // 2) the roots have distinct moduli

    typedef typename POLYNOMIAL::Scalar                 Scalar;
    typedef typename REAL_ROOTS::Scalar                 Real;
    typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

    //Test realRoots
    std::vector< Real > calc_realRoots;
    psolve.realRoots( calc_realRoots );
    VERIFY( calc_realRoots.size() == (size_t)real_roots.size() );

    const Scalar psPrec = sqrt( test_precision<Scalar>() );

    for( size_t i=0; i<calc_realRoots.size(); ++i )
    {
      bool found = false;
      for( size_t j=0; j<calc_realRoots.size()&& !found; ++j )
      {
        if( internal::isApprox( calc_realRoots[i], real_roots[j] ), psPrec ){
          found = true; }
      }
      VERIFY( found );
    }

    //Test greatestRoot
    VERIFY( internal::isApprox( roots.array().abs().maxCoeff(),
          abs( psolve.greatestRoot() ), psPrec ) );

    //Test smallestRoot
    VERIFY( internal::isApprox( roots.array().abs().minCoeff(),
          abs( psolve.smallestRoot() ), psPrec ) );

    bool hasRealRoot;
    //Test absGreatestRealRoot
    Real r = psolve.absGreatestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().abs().maxCoeff(), abs(r), psPrec ) );  }

    //Test absSmallestRealRoot
    r = psolve.absSmallestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().abs().minCoeff(), abs( r ), psPrec ) ); }

    //Test greatestRealRoot
    r = psolve.greatestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().maxCoeff(), r, psPrec ) ); }

    //Test smallestRealRoot
    r = psolve.smallestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
    VERIFY( internal::isApprox( real_roots.array().minCoeff(), r, psPrec ) ); }
  }
}

template<typename _Scalar, int _Deg>
void polynomialsolver(int deg)
{
  typedef internal::increment_if_fixed_size<_Deg>            Dim;
  typedef Matrix<_Scalar,Dim::ret,1>                  PolynomialType;
  typedef Matrix<_Scalar,_Deg,1>                      EvalRootsType;

  cout << "Standard cases" << endl;
  PolynomialType pols = PolynomialType::Random(deg+1);
  evalSolver<_Deg,PolynomialType>( pols );

  cout << "Hard cases" << endl;
  _Scalar multipleRoot = internal::random<_Scalar>();
  EvalRootsType allRoots = EvalRootsType::Constant(deg,multipleRoot);
  roots_to_monicPolynomial( allRoots, pols );
  evalSolver<_Deg,PolynomialType>( pols );

  cout << "Test sugar" << endl;
  EvalRootsType realRoots = EvalRootsType::Random(deg);
  roots_to_monicPolynomial( realRoots, pols );
  evalSolverSugarFunction<_Deg>(
      pols,
      realRoots.template cast <
                    std::complex<
                         typename NumTraits<_Scalar>::Real
                         >
                    >(),
      realRoots );
}

void test_polynomialsolver()
{
  for(int i = 0; i < g_repeat; i++)
  {
    CALL_SUBTEST_1( (polynomialsolver<float,1>(1)) );
    CALL_SUBTEST_2( (polynomialsolver<double,2>(2)) );
    CALL_SUBTEST_3( (polynomialsolver<double,3>(3)) );
    CALL_SUBTEST_4( (polynomialsolver<float,4>(4)) );
    CALL_SUBTEST_5( (polynomialsolver<double,5>(5)) );
    CALL_SUBTEST_6( (polynomialsolver<float,6>(6)) );
    CALL_SUBTEST_7( (polynomialsolver<float,7>(7)) );
    CALL_SUBTEST_8( (polynomialsolver<double,8>(8)) );

    CALL_SUBTEST_9( (polynomialsolver<float,Dynamic>(
            internal::random<int>(9,13)
            )) );
    CALL_SUBTEST_10((polynomialsolver<double,Dynamic>(
            internal::random<int>(9,13)
            )) );
  }
}
<commit_msg>fix typo in evalSolverSugarFunction()<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"
#include <unsupported/Eigen/Polynomials>
#include <iostream>
#include <algorithm>

using namespace std;

namespace Eigen {
namespace internal {
template<int Size>
struct increment_if_fixed_size
{
  enum {
    ret = (Size == Dynamic) ? Dynamic : Size+1
  };
};
}
}

template<int Deg, typename POLYNOMIAL, typename SOLVER>
bool aux_evalSolver( const POLYNOMIAL& pols, SOLVER& psolve )
{
  typedef typename POLYNOMIAL::Index Index;
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef typename SOLVER::RootsType    RootsType;
  typedef Matrix<Scalar,Deg,1>          EvalRootsType;

  const Index deg = pols.size()-1;

  psolve.compute( pols );
  const RootsType& roots( psolve.roots() );
  EvalRootsType evr( deg );
  for( int i=0; i<roots.size(); ++i ){
    evr[i] = std::abs( poly_eval( pols, roots[i] ) ); }

  bool evalToZero = evr.isZero( test_precision<Scalar>() );
  if( !evalToZero )
  {
    cerr << "WRONG root: " << endl;
    cerr << "Polynomial: " << pols.transpose() << endl;
    cerr << "Roots found: " << roots.transpose() << endl;
    cerr << "Abs value of the polynomial at the roots: " << evr.transpose() << endl;
    cerr << endl;
  }

  std::vector<Scalar> rootModuli( roots.size() );
  Map< EvalRootsType > aux( &rootModuli[0], roots.size() );
  aux = roots.array().abs();
  std::sort( rootModuli.begin(), rootModuli.end() );
  bool distinctModuli=true;
  for( size_t i=1; i<rootModuli.size() && distinctModuli; ++i )
  {
    if( internal::isApprox( rootModuli[i], rootModuli[i-1] ) ){
      distinctModuli = false; }
  }
  VERIFY( evalToZero || !distinctModuli );

  return distinctModuli;
}

template<int Deg, typename POLYNOMIAL>
void evalSolver( const POLYNOMIAL& pols )
{
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

  PolynomialSolverType psolve;
  aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve );
}

template< int Deg, typename POLYNOMIAL, typename ROOTS, typename REAL_ROOTS >
void evalSolverSugarFunction( const POLYNOMIAL& pols, const ROOTS& roots, const REAL_ROOTS& real_roots )
{
  using std::sqrt;
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

  PolynomialSolverType psolve;
  if( aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve ) )
  {
    //It is supposed that
    // 1) the roots found are correct
    // 2) the roots have distinct moduli

    typedef typename POLYNOMIAL::Scalar                 Scalar;
    typedef typename REAL_ROOTS::Scalar                 Real;
    typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

    //Test realRoots
    std::vector< Real > calc_realRoots;
    psolve.realRoots( calc_realRoots );
    VERIFY( calc_realRoots.size() == (size_t)real_roots.size() );

    const Scalar psPrec = sqrt( test_precision<Scalar>() );

    for( size_t i=0; i<calc_realRoots.size(); ++i )
    {
      bool found = false;
      for( size_t j=0; j<calc_realRoots.size()&& !found; ++j )
      {
        if( internal::isApprox( calc_realRoots[i], real_roots[j], psPrec ) ){
          found = true; }
      }
      VERIFY( found );
    }

    //Test greatestRoot
    VERIFY( internal::isApprox( roots.array().abs().maxCoeff(),
          abs( psolve.greatestRoot() ), psPrec ) );

    //Test smallestRoot
    VERIFY( internal::isApprox( roots.array().abs().minCoeff(),
          abs( psolve.smallestRoot() ), psPrec ) );

    bool hasRealRoot;
    //Test absGreatestRealRoot
    Real r = psolve.absGreatestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().abs().maxCoeff(), abs(r), psPrec ) );  }

    //Test absSmallestRealRoot
    r = psolve.absSmallestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().abs().minCoeff(), abs( r ), psPrec ) ); }

    //Test greatestRealRoot
    r = psolve.greatestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().maxCoeff(), r, psPrec ) ); }

    //Test smallestRealRoot
    r = psolve.smallestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
    VERIFY( internal::isApprox( real_roots.array().minCoeff(), r, psPrec ) ); }
  }
}

template<typename _Scalar, int _Deg>
void polynomialsolver(int deg)
{
  typedef internal::increment_if_fixed_size<_Deg>            Dim;
  typedef Matrix<_Scalar,Dim::ret,1>                  PolynomialType;
  typedef Matrix<_Scalar,_Deg,1>                      EvalRootsType;

  cout << "Standard cases" << endl;
  PolynomialType pols = PolynomialType::Random(deg+1);
  evalSolver<_Deg,PolynomialType>( pols );

  cout << "Hard cases" << endl;
  _Scalar multipleRoot = internal::random<_Scalar>();
  EvalRootsType allRoots = EvalRootsType::Constant(deg,multipleRoot);
  roots_to_monicPolynomial( allRoots, pols );
  evalSolver<_Deg,PolynomialType>( pols );

  cout << "Test sugar" << endl;
  EvalRootsType realRoots = EvalRootsType::Random(deg);
  roots_to_monicPolynomial( realRoots, pols );
  evalSolverSugarFunction<_Deg>(
      pols,
      realRoots.template cast <
                    std::complex<
                         typename NumTraits<_Scalar>::Real
                         >
                    >(),
      realRoots );
}

void test_polynomialsolver()
{
  for(int i = 0; i < g_repeat; i++)
  {
    CALL_SUBTEST_1( (polynomialsolver<float,1>(1)) );
    CALL_SUBTEST_2( (polynomialsolver<double,2>(2)) );
    CALL_SUBTEST_3( (polynomialsolver<double,3>(3)) );
    CALL_SUBTEST_4( (polynomialsolver<float,4>(4)) );
    CALL_SUBTEST_5( (polynomialsolver<double,5>(5)) );
    CALL_SUBTEST_6( (polynomialsolver<float,6>(6)) );
    CALL_SUBTEST_7( (polynomialsolver<float,7>(7)) );
    CALL_SUBTEST_8( (polynomialsolver<double,8>(8)) );

    CALL_SUBTEST_9( (polynomialsolver<float,Dynamic>(
            internal::random<int>(9,13)
            )) );
    CALL_SUBTEST_10((polynomialsolver<double,Dynamic>(
            internal::random<int>(9,13)
            )) );
  }
}
<|endoftext|>


<commit_before>#include "WebSocketConnector.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include "../cryptoplugin/ICryptoFactory.h"
#include "../urbackupcommon/WebSocketPipe.h"
#include <assert.h>

extern ICryptoFactory* crypto_fak;

void WebSocketConnector::Execute(str_map& GET, THREAD_ID tid, str_map& PARAMS, IPipe* pipe, const std::string& endpoint_name)
{
	if (PARAMS["CONNECTION"] != "Upgrade")
	{
		pipe->Write("HTTP/1.1 500 Expecting Connection: Upgrade\r\nConnection: Close\r\n\r\n");
		return;
	}

	std::string protocol_list = PARAMS["SEC-WEBSOCKET-PROTOCOL"];
	std::vector<std::string> protocols;
	Tokenize(protocol_list, protocols, ",");

	for (size_t i = 0; i < protocols.size(); ++i)
		protocols[i] = trim(protocols[i]);

	if (std::find(protocols.begin(), protocols.end(), "urbackup") == protocols.end())
	{
		pipe->Write("HTTP/1.1 500 urbackup protocol not supported\r\nConnection: Close\r\n\r\n");
		return;
	}

	if (PARAMS["SEC-WEBSOCKET-VERSION"] != "13")
	{
		pipe->Write("HTTP/1.1 500 websocket protocol version not supported\r\nConnection: Close\r\n\r\n");
		return;
	}

	std::string websocket_key = trim(PARAMS["SEC-WEBSOCKET-KEY"]);
	websocket_key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

	std::string key_response = crypto_fak->sha1Binary(websocket_key);
	pipe->Write(std::string("HTTP/1.1 101 Switching Protocols\r\n"
		"Upgrade: websocket\r\n"
		"Connection: Upgrade\r\n"
		"Sec-WebSocket-Accept: ") + base64_encode(reinterpret_cast<const unsigned char*>(key_response.data()),
			static_cast<unsigned int>(key_response.size())) + "\r\n"
		"Sec-WebSocket-Protocol: urbackup\r\n\r\n");

	ICustomClient* client = wrapped_service->createClient();

	str_map::iterator it_forwarded_for = PARAMS.find("X-FORWARDED-FOR");

	WebSocketPipe* ws_pipe = new WebSocketPipe(pipe, false, true, std::string(), false);

	client->Init(tid, ws_pipe, it_forwarded_for != PARAMS.end() ? it_forwarded_for->second : endpoint_name);

	while (true)
	{
		bool b = client->Run(NULL);
		if (!b)
		{
			break;
		}

		if (client->wantReceive())
		{
			if (ws_pipe->isReadable(10))
			{
				client->ReceivePackets(NULL);
			}
			else if (ws_pipe->hasError())
			{
				client->ReceivePackets(NULL);
				Server->wait(20);
			}
		}
		else
		{
			Server->wait(20);
		}
	}

	bool want_destory_pipe = client->closeSocket();

	wrapped_service->destroyClient(client);

	if (want_destory_pipe)
	{
		delete ws_pipe;
		delete pipe;
	}
}

std::string WebSocketConnector::getName()
{
	return name;
}
<commit_msg>Properly free web socket connections<commit_after>#include "WebSocketConnector.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include "../cryptoplugin/ICryptoFactory.h"
#include "../urbackupcommon/WebSocketPipe.h"
#include <assert.h>

extern ICryptoFactory* crypto_fak;

void WebSocketConnector::Execute(str_map& GET, THREAD_ID tid, str_map& PARAMS, IPipe* pipe, const std::string& endpoint_name)
{
	if (PARAMS["CONNECTION"] != "Upgrade")
	{
		pipe->Write("HTTP/1.1 500 Expecting Connection: Upgrade\r\nConnection: Close\r\n\r\n");
		delete pipe;
		return;
	}

	std::string protocol_list = PARAMS["SEC-WEBSOCKET-PROTOCOL"];
	std::vector<std::string> protocols;
	Tokenize(protocol_list, protocols, ",");

	for (size_t i = 0; i < protocols.size(); ++i)
		protocols[i] = trim(protocols[i]);

	if (std::find(protocols.begin(), protocols.end(), "urbackup") == protocols.end())
	{
		pipe->Write("HTTP/1.1 500 urbackup protocol not supported\r\nConnection: Close\r\n\r\n");
		delete pipe;
		return;
	}

	if (PARAMS["SEC-WEBSOCKET-VERSION"] != "13")
	{
		pipe->Write("HTTP/1.1 500 websocket protocol version not supported\r\nConnection: Close\r\n\r\n");
		delete pipe;
		return;
	}

	std::string websocket_key = trim(PARAMS["SEC-WEBSOCKET-KEY"]);
	websocket_key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

	std::string key_response = crypto_fak->sha1Binary(websocket_key);
	pipe->Write(std::string("HTTP/1.1 101 Switching Protocols\r\n"
		"Upgrade: websocket\r\n"
		"Connection: Upgrade\r\n"
		"Sec-WebSocket-Accept: ") + base64_encode(reinterpret_cast<const unsigned char*>(key_response.data()),
			static_cast<unsigned int>(key_response.size())) + "\r\n"
		"Sec-WebSocket-Protocol: urbackup\r\n\r\n");

	ICustomClient* client = wrapped_service->createClient();

	str_map::iterator it_forwarded_for = PARAMS.find("X-FORWARDED-FOR");

	WebSocketPipe* ws_pipe = new WebSocketPipe(pipe, false, true, std::string(), true);

	client->Init(tid, ws_pipe, it_forwarded_for != PARAMS.end() ? it_forwarded_for->second : endpoint_name);

	while (true)
	{
		bool b = client->Run(NULL);
		if (!b)
		{
			break;
		}

		if (client->wantReceive())
		{
			if (ws_pipe->isReadable(10))
			{
				client->ReceivePackets(NULL);
			}
			else if (ws_pipe->hasError())
			{
				client->ReceivePackets(NULL);
				Server->wait(20);
			}
		}
		else
		{
			Server->wait(20);
		}
	}

	bool want_destory_pipe = client->closeSocket();

	wrapped_service->destroyClient(client);

	if (want_destory_pipe)
	{
		delete ws_pipe;
	}
}

std::string WebSocketConnector::getName()
{
	return name;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

#include "GL/glut.h"   // - An interface and windows management library
#include "visuals.h"   // Header file for our OpenGL functions

myModel md;
static float tx = 0.0;
static float rotx = 0.0;
static bool animate = false;
static float red = 1.0;
static float green = 0.0;
static float blue = 0.0;

using namespace std;

Point::Point(float x, float y, float z) {
	this->x = x;
	this->y = y;
	this->z = z;
}
float Point::getX() {
	return this->x;
}

float Point::getY() {
	return this->y;
}

float Point::getZ() {
	return this->z;
}

void Point::print(void) {
	cout << this->x << " " << this->y << " " << this->z << endl;
}

Faces::Faces(float v1, float vn1, float v2, float vn2, float v3, float vn3) {
	this->v = new Point(v1, v2, v3);
	this->vn = new Point(vn1, vn2, vn3);
}

Point* Faces::getV() {
	return this->v;
}

Point* Faces::getVn() {
	return this->vn;
}

void Faces::print(void) {
	this->v->print();
	this->vn->print();
}

void keimeno(const char *str, float size) {
	glPushMatrix();
	glScalef(size,size,size);

	for (size_t i=0;i<strlen(str);i++) {
		glutStrokeCharacter(GLUT_STROKE_ROMAN,str[i]);
	}
	glPopMatrix();
}

void Render() {
	//CLEARS FRAME BUFFER ie COLOR BUFFER& DEPTH BUFFER (1.0)
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // Clean up the colour of the window and the depth buffer
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glTranslatef(0, 0, -100);
	glTranslatef(tx, 0.0, 0.0);
	glRotatef(rotx, 0, 1, 0);

	//(01)
	glColor3f(0.8, 0.1, 0.1);
	DisplayModel(md);

	glutSwapBuffers();	// All drawing commands applied to the hidden buffer, so now, bring forward the hidden buffer and hide the visible one
}

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

void Resize(int w, int h) {
	// define the visible area of the window ( in pixels )
	if (h == 0) {
		h = 1;
	}
	glViewport(0, 0, w, h);

	// Setup viewing volume
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	gluPerspective(2.0, (float)w/(float)h, 1.0, 500.0);
}

void Idle() {
	if (animate) {
		rotx += 0.4;
	}
	glutPostRedisplay();
}

void Keyboard(unsigned char key, int x, int y) {
	switch(key) {
		case 'q' :
			exit(0);
			break;
		case 'a' :
			tx -= 0.5f;
			break;
		case 'd' :
			tx += 0.5f;
			break;
		default :
			break;
	}
	glutPostRedisplay();
}

void Mouse(int button, int state, int x, int y) {
	if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON) {
		animate = !animate;
		glutPostRedisplay();
	}
}

void Setup() {
	char path[] = "../planet.obj";
	ReadFile(&md, path);

	//Parameter handling
	glShadeModel (GL_SMOOTH);

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);  //renders a fragment if its z value is less or equal of the stored value
	glClearDepth(1);

	// polygon rendering mode
	glEnable(GL_COLOR_MATERIAL);
	glColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE );

	//Set up light source
	GLfloat light_position[] = { 0.0, 30.0, 50.0, 0.0 };
	glLightfv( GL_LIGHT0, GL_POSITION, light_position);

	GLfloat ambientLight[] = { 0.3, 0.3, 0.3, 1.0 };
	GLfloat diffuseLight[] = { 0.8, 0.8, 0.8, 1.0 };
	// GLfloat specularLight[] = { 1.0, 1.0, 1.0, 1.0 };

	glLightfv( GL_LIGHT0, GL_AMBIENT, ambientLight );
	glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuseLight );

	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);

	glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

	glEnable(GL_CULL_FACE);
	glFrontFace(GL_CW);

	//01
	glFrontFace(GL_CCW);

	// Black background
	glClearColor(0.0f,0.0f,0.0f,1.0f);
}

void MenuSelect(int choice) {
	switch (choice) {
		case RED:
			red = 1.0;
			green = 0.0;
			blue = 0.0;
			break;
		case GREEN:
			red = 0.0;
			green = 1.0;
			blue = 0.0;
			break;
		case BLUE:
			red = 0.0;
			green = 0.0;
			blue = 1.0;
			break;
		case WHITE:
			red = 1.0;
			green = 1.0;
			blue = 1.0;
			break;
		default:
			break;
	}
}

void ReadFile(myModel *md, char *path) {
	string line;
	float x, y, z;
	string::size_type sz, sz2;
	ifstream myfile(path);
	if (myfile) {
		while (getline(myfile, line))	{
			if (line.find("v ") == 0) {
				string temp = line.substr(3);
				x = stod(temp, &sz);
				y = stod(temp.substr(sz), &sz2);
				z = stod(temp.substr(sz+sz2));
				md->v.push_back(new Point(x, y, z));
			} else if (line.find("vn ") == 0) {
				string temp = line.substr(3);
				x = stod(temp, &sz);
				y = stod(temp.substr(sz), &sz2);
				z = stod(temp.substr(sz+sz2));
				md->vn.push_back(new Point(x, y, z));
			} else if (line.find("f ") == 0) {
				int v1, vn1, v2, vn2, v3, vn3;
				string::size_type sz, sz2, sz3, sz4, sz5;
 				string temp = line.substr(3);
				v1 = stoi(temp, &sz);
				vn1 = stoi(temp.substr(sz+2), &sz2);
				v2 = stoi(temp.substr(sz+2+sz2), &sz3);
				vn2 = stoi(temp.substr(sz+2+sz2+sz3+2), &sz4);
				v3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4), &sz5);
				vn3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4+sz5+2));
				md->f.push_back(new Faces(v1, vn1, v2, vn2, v3, vn3));
			}
		}
		myfile.close();
	}
}

void DisplayModel(myModel md) {
	glPushMatrix();
	glBegin(GL_POINTS);

	for (size_t i = 0; i < md.f.size(); i++) {
		/* Vns */
		glVertex3f(md.vn[md.f[i]->getVn()->getX()-1]->getX(), md.vn[md.f[i]->getVn()->getX()-1]->getY(), md.vn[md.f[i]->getVn()->getX()-1]->getZ());
		glVertex3f(md.vn[md.f[i]->getVn()->getY()-1]->getX(), md.vn[md.f[i]->getVn()->getY()-1]->getY(), md.vn[md.f[i]->getVn()->getY()-1]->getZ());
		glVertex3f(md.vn[md.f[i]->getVn()->getZ()-1]->getX(), md.vn[md.f[i]->getVn()->getZ()-1]->getY(), md.vn[md.f[i]->getVn()->getZ()-1]->getZ());
		/* Vs */
		glVertex3f(md.v[md.f[i]->getV()->getX()-1]->getX(), md.v[md.f[i]->getV()->getX()-1]->getY(), md.v[md.f[i]->getV()->getX()-1]->getZ());
		glVertex3f(md.v[md.f[i]->getV()->getY()-1]->getX(), md.v[md.f[i]->getV()->getY()-1]->getY(), md.v[md.f[i]->getV()->getY()-1]->getZ());
		glVertex3f(md.v[md.f[i]->getV()->getZ()-1]->getX(), md.v[md.f[i]->getV()->getZ()-1]->getY(), md.v[md.f[i]->getV()->getZ()-1]->getZ());
	}

	glEnd();
	glPopMatrix();
}
<commit_msg>Planet printing update<commit_after>#include <stdio.h>
#include <string.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

#include "GL/glut.h"   // - An interface and windows management library
#include "visuals.h"   // Header file for our OpenGL functions

myModel md;
static float tx = 0.0;
static float rotx = 0.0;
static bool animate = false;
static float red = 1.0;
static float green = 0.0;
static float blue = 0.0;

using namespace std;

Point::Point(float x, float y, float z) {
	this->x = x;
	this->y = y;
	this->z = z;
}
float Point::getX() {
	return this->x;
}

float Point::getY() {
	return this->y;
}

float Point::getZ() {
	return this->z;
}

void Point::print(void) {
	cout << this->x << " " << this->y << " " << this->z << endl;
}

Faces::Faces(float v1, float vn1, float v2, float vn2, float v3, float vn3) {
	this->v = new Point(v1, v2, v3);
	this->vn = new Point(vn1, vn2, vn3);
}

Point* Faces::getV() {
	return this->v;
}

Point* Faces::getVn() {
	return this->vn;
}

void Faces::print(void) {
	this->v->print();
	this->vn->print();
}

void keimeno(const char *str, float size) {
	glPushMatrix();
	glScalef(size,size,size);

	for (size_t i=0;i<strlen(str);i++) {
		glutStrokeCharacter(GLUT_STROKE_ROMAN,str[i]);
	}
	glPopMatrix();
}

void Render() {
	//CLEARS FRAME BUFFER ie COLOR BUFFER& DEPTH BUFFER (1.0)
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // Clean up the colour of the window and the depth buffer
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glTranslatef(0, 0, -100);
	glTranslatef(tx, 0.0, 0.0);
	glRotatef(rotx, 0, 1, 0);

	//(01)
	glColor3f(0.75, 0.35, 0.05);
	DisplayModel(md);

	// glColor3f(0.8, 0.4, 0.1);
	// glutSolidSphere(0.999, 30, 24);

	glutSwapBuffers();	// All drawing commands applied to the hidden buffer, so now, bring forward the hidden buffer and hide the visible one
}

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

void Resize(int w, int h) {
	// define the visible area of the window ( in pixels )
	if (h == 0) {
		h = 1;
	}
	glViewport(0, 0, w, h);

	// Setup viewing volume
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	gluPerspective(2.0, (float)w/(float)h, 1.0, 500.0);
}

void Idle() {
	if (animate) {
		rotx += 0.4;
	}
	glutPostRedisplay();
}

void Keyboard(unsigned char key, int x, int y) {
	switch(key) {
		case 'q' :
			exit(0);
			break;
		case 'a' :
			tx -= 0.5f;
			break;
		case 'd' :
			tx += 0.5f;
			break;
		default :
			break;
	}
	glutPostRedisplay();
}

void Mouse(int button, int state, int x, int y) {
	if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON) {
		animate = !animate;
		glutPostRedisplay();
	}
}

void Setup() {
	char path[] = "../planet.obj";
	ReadFile(&md, path);

	//Parameter handling
	glShadeModel (GL_SMOOTH);

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);  //renders a fragment if its z value is less or equal of the stored value
	glClearDepth(1);

	// polygon rendering mode
	glEnable(GL_COLOR_MATERIAL);
	glColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE );

	//Set up light source
	GLfloat light_position[] = { 0.0, 30.0, 50.0, 0.0 };
	glLightfv( GL_LIGHT0, GL_POSITION, light_position);

	GLfloat ambientLight[] = { 0.3, 0.3, 0.3, 1.0 };
	GLfloat diffuseLight[] = { 0.8, 0.8, 0.8, 1.0 };
	// GLfloat specularLight[] = { 1.0, 1.0, 1.0, 1.0 };

	glLightfv( GL_LIGHT0, GL_AMBIENT, ambientLight );
	glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuseLight );

	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);

	glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

	glEnable(GL_CULL_FACE);
	glFrontFace(GL_CW);

	//01
	glFrontFace(GL_CCW);

	// Black background
	glClearColor(0.0f,0.0f,0.0f,1.0f);
}

void MenuSelect(int choice) {
	switch (choice) {
		case RED:
			red = 1.0;
			green = 0.0;
			blue = 0.0;
			break;
		case GREEN:
			red = 0.0;
			green = 1.0;
			blue = 0.0;
			break;
		case BLUE:
			red = 0.0;
			green = 0.0;
			blue = 1.0;
			break;
		case WHITE:
			red = 1.0;
			green = 1.0;
			blue = 1.0;
			break;
		default:
			break;
	}
}

void ReadFile(myModel *md, char *path) {
	string line;
	float x, y, z;
	string::size_type sz, sz2;
	ifstream myfile(path);
	if (myfile) {
		while (getline(myfile, line))	{
			if (line.find("v ") == 0) {
				string temp = line.substr(3);
				x = stod(temp, &sz);
				y = stod(temp.substr(sz), &sz2);
				z = stod(temp.substr(sz+sz2));
				md->v.push_back(new Point(x, y, z));
			} else if (line.find("vn ") == 0) {
				string temp = line.substr(3);
				x = stod(temp, &sz);
				y = stod(temp.substr(sz), &sz2);
				z = stod(temp.substr(sz+sz2));
				md->vn.push_back(new Point(x, y, z));
			} else if (line.find("f ") == 0) {
				int v1, vn1, v2, vn2, v3, vn3;
				string::size_type sz, sz2, sz3, sz4, sz5;
 				string temp = line.substr(3);
				v1 = stoi(temp, &sz);
				vn1 = stoi(temp.substr(sz+2), &sz2);
				v2 = stoi(temp.substr(sz+2+sz2), &sz3);
				vn2 = stoi(temp.substr(sz+2+sz2+sz3+2), &sz4);
				v3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4), &sz5);
				vn3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4+sz5+2));
				md->f.push_back(new Faces(v1, vn1, v2, vn2, v3, vn3));
			}
		}
		myfile.close();
	}
}

void DisplayModel(myModel md) {
	glPushMatrix();
	glBegin(GL_POINTS);

	for (size_t i = 0; i < md.f.size(); i++) {
		/* Vns */
		glVertex3f(md.vn[md.f[i]->getVn()->getX()-1]->getX(), md.vn[md.f[i]->getVn()->getX()-1]->getY(), md.vn[md.f[i]->getVn()->getX()-1]->getZ());
		glVertex3f(md.vn[md.f[i]->getVn()->getY()-1]->getX(), md.vn[md.f[i]->getVn()->getY()-1]->getY(), md.vn[md.f[i]->getVn()->getY()-1]->getZ());
		glVertex3f(md.vn[md.f[i]->getVn()->getZ()-1]->getX(), md.vn[md.f[i]->getVn()->getZ()-1]->getY(), md.vn[md.f[i]->getVn()->getZ()-1]->getZ());
		/* Vs */
		glVertex3f(md.v[md.f[i]->getV()->getX()-1]->getX(), md.v[md.f[i]->getV()->getX()-1]->getY(), md.v[md.f[i]->getV()->getX()-1]->getZ());
		glVertex3f(md.v[md.f[i]->getV()->getY()-1]->getX(), md.v[md.f[i]->getV()->getY()-1]->getY(), md.v[md.f[i]->getV()->getY()-1]->getZ());
		glVertex3f(md.v[md.f[i]->getV()->getZ()-1]->getX(), md.v[md.f[i]->getV()->getZ()-1]->getY(), md.v[md.f[i]->getV()->getZ()-1]->getZ());
	}

	glEnd();
	glPopMatrix();
}
<|endoftext|>


<commit_before>
#include "GameLogger.h"

using namespace std;

GameLogger::GameLogger()
  :
  lastCompleteFrameNumber(0),
  oldState(PlayerInfo::initial),
  firstRecording(true),
  lastAudioDataTimestamp(0),
  lastRecordedPlainImageID(CameraInfo::Bottom)
{
  const std::string gameLogPath = params.logDirPath + "/game.log";
  const std::string imageLogPath = params.logDirPath + "/images.log";

  logfileManager.openFile(gameLogPath);

  imageOutFile.open(imageLogPath, ios::out | ios::binary);
  lastTimeImageRecorded = getFrameInfo();

  getDebugParameterList().add(&params);
}

GameLogger::~GameLogger()
{
  logfileManager.closeFile();
  imageOutFile.close();
  getDebugParameterList().remove(&params);
}

#define LOGSTUFF(name) \
  { std::ostream& dataStream = logfileManager.log(getFrameInfo().getFrameNumber(), #name); \
  Serializer<name>::serialize(get##name(), dataStream); } ((void)0)

void GameLogger::execute()
{
  // HACK: wait a bit before starting recording
  if(!logfileManager.is_ready()) {
    return;
  }

  if( getBehaviorStateComplete().state.IsInitialized() &&
      getBehaviorStateSparse().state.IsInitialized())
  {
    bool something_recorded = false;

    // write out the complete behavior state when it was just created in this frame
    if(getBehaviorStateComplete().state.framenumber() >= lastCompleteFrameNumber)
    {
      LOGSTUFF(BehaviorStateComplete);
      LOGSTUFF(RobotInfo);

      lastCompleteFrameNumber = getFrameInfo().getFrameNumber();
      something_recorded = true;
    }

    // condition wheather the current frame should be logged:
    bool log_this_frame = (getBehaviorStateSparse().state.framenumber() == getFrameInfo().getFrameNumber());

    // NOTE: record only the first frame if the state changed to initial or finished
    if(!firstRecording && oldState == getPlayerInfo().robotState) {
      log_this_frame = log_this_frame && getPlayerInfo().robotState != PlayerInfo::initial;
      log_this_frame = log_this_frame && getPlayerInfo().robotState != PlayerInfo::finished;
      log_this_frame = log_this_frame && getMotionStatus().currentMotion != motion::init;
    }

    if(log_this_frame)
    {
      LOGSTUFF(BehaviorStateSparse);

      // proprioception
      LOGSTUFF(OdometryData);
      LOGSTUFF(CameraMatrix);
      LOGSTUFF(CameraMatrixTop);

      if(params.logBodyStatus) {
        LOGSTUFF(BodyStatus);
      }

      // perception
      LOGSTUFF(GoalPercept);
      LOGSTUFF(GoalPerceptTop);

      LOGSTUFF(MultiBallPercept);
      LOGSTUFF(BallModel);

      if(params.logUltraSound) {
        LOGSTUFF(UltraSoundReceiveData);
      }

      LOGSTUFF(FieldPercept);
      LOGSTUFF(FieldPerceptTop);

      LOGSTUFF(ScanLineEdgelPercept);
      LOGSTUFF(ScanLineEdgelPerceptTop);
      LOGSTUFF(ShortLinePercept);
      LOGSTUFF(RansacLinePercept);
      LOGSTUFF(RansacCirclePercept2018);

      if(params.logBallCandidates) {
        LOGSTUFF(BallCandidates);
        LOGSTUFF(BallCandidatesTop);
      }

      LOGSTUFF(TeamMessage);

      // keep the audio device open for some time

      if(params.logAudioData)
      {
        // remember when the capture was on and keep recording for some time after the behavior says stop recording
        if(getAudioControl().capture) {
          timeOfLastCapture = getFrameInfo();
        } else if(getFrameInfo().getTimeSince(timeOfLastCapture.getTime()) < 3000) {
          getAudioControl().capture = true;
        }

        // new data avaliable and capture is still on
        if(lastAudioDataTimestamp < getAudioData().timestamp) {
          LOGSTUFF(AudioData);
          lastAudioDataTimestamp = getAudioData().timestamp;
        }
      }

      if (getWhistlePercept().whistleDetected) {
        LOGSTUFF(WhistlePercept);
      }

      // record images every 1s
      if(params.logPlainImages && getFrameInfo().getTimeSince(lastTimeImageRecorded) > params.logPlainImagesDelay && imageOutFile.is_open() && !imageOutFile.fail()) {
        unsigned int frameNumber = getFrameInfo().getFrameNumber();
        imageOutFile.write((const char*)(&frameNumber), sizeof(unsigned int));

        // switch camera each frame
        if(lastRecordedPlainImageID == CameraInfo::Top) {
          imageOutFile.write((const char*)getImage().data(), getImage().data_size());
          lastRecordedPlainImageID = CameraInfo::Bottom;
        } else {
          imageOutFile.write((const char*)getImageTop().data(), getImageTop().data_size());
          lastRecordedPlainImageID = CameraInfo::Top;
        }

        lastTimeImageRecorded = getFrameInfo();
      }

      something_recorded = true;
    }

    if(something_recorded) {
      LOGSTUFF(FrameInfo);
      firstRecording = false;
    }

    // remember the old state
    oldState = getPlayerInfo().robotState;
  }
}

<commit_msg>don't log in unstiff<commit_after>
#include "GameLogger.h"

using namespace std;

GameLogger::GameLogger()
  :
  lastCompleteFrameNumber(0),
  oldState(PlayerInfo::initial),
  firstRecording(true),
  lastAudioDataTimestamp(0),
  lastRecordedPlainImageID(CameraInfo::Bottom)
{
  const std::string gameLogPath = params.logDirPath + "/game.log";
  const std::string imageLogPath = params.logDirPath + "/images.log";

  logfileManager.openFile(gameLogPath);

  imageOutFile.open(imageLogPath, ios::out | ios::binary);
  lastTimeImageRecorded = getFrameInfo();

  getDebugParameterList().add(&params);
}

GameLogger::~GameLogger()
{
  logfileManager.closeFile();
  imageOutFile.close();
  getDebugParameterList().remove(&params);
}

#define LOGSTUFF(name) \
  { std::ostream& dataStream = logfileManager.log(getFrameInfo().getFrameNumber(), #name); \
  Serializer<name>::serialize(get##name(), dataStream); } ((void)0)

void GameLogger::execute()
{
  // HACK: wait a bit before starting recording
  if(!logfileManager.is_ready()) {
    return;
  }

  if( getBehaviorStateComplete().state.IsInitialized() &&
      getBehaviorStateSparse().state.IsInitialized())
  {
    bool something_recorded = false;

    // write out the complete behavior state when it was just created in this frame
    if(getBehaviorStateComplete().state.framenumber() >= lastCompleteFrameNumber)
    {
      LOGSTUFF(BehaviorStateComplete);
      LOGSTUFF(RobotInfo);

      lastCompleteFrameNumber = getFrameInfo().getFrameNumber();
      something_recorded = true;
    }

    // condition wheather the current frame should be logged:
    bool log_this_frame = (getBehaviorStateSparse().state.framenumber() == getFrameInfo().getFrameNumber());

    // NOTE: record only the first frame if the state changed to initial or finished
    if(!firstRecording && oldState == getPlayerInfo().robotState) {
      log_this_frame = log_this_frame && getPlayerInfo().robotState != PlayerInfo::initial;
      log_this_frame = log_this_frame && getPlayerInfo().robotState != PlayerInfo::finished;
      log_this_frame = log_this_frame && getPlayerInfo().robotState != PlayerInfo::unstiff;
      log_this_frame = log_this_frame && getMotionStatus().currentMotion != motion::init;
    }

    if(log_this_frame)
    {
      LOGSTUFF(BehaviorStateSparse);

      // proprioception
      LOGSTUFF(OdometryData);
      LOGSTUFF(CameraMatrix);
      LOGSTUFF(CameraMatrixTop);

      if(params.logBodyStatus) {
        LOGSTUFF(BodyStatus);
      }

      // perception
      LOGSTUFF(GoalPercept);
      LOGSTUFF(GoalPerceptTop);

      LOGSTUFF(MultiBallPercept);
      LOGSTUFF(BallModel);

      if(params.logUltraSound) {
        LOGSTUFF(UltraSoundReceiveData);
      }

      LOGSTUFF(FieldPercept);
      LOGSTUFF(FieldPerceptTop);

      LOGSTUFF(ScanLineEdgelPercept);
      LOGSTUFF(ScanLineEdgelPerceptTop);
      LOGSTUFF(ShortLinePercept);
      LOGSTUFF(RansacLinePercept);
      LOGSTUFF(RansacCirclePercept2018);

      if(params.logBallCandidates) {
        LOGSTUFF(BallCandidates);
        LOGSTUFF(BallCandidatesTop);
      }

      LOGSTUFF(TeamMessage);

      // keep the audio device open for some time

      if(params.logAudioData)
      {
        // remember when the capture was on and keep recording for some time after the behavior says stop recording
        if(getAudioControl().capture) {
          timeOfLastCapture = getFrameInfo();
        } else if(getFrameInfo().getTimeSince(timeOfLastCapture.getTime()) < 3000) {
          getAudioControl().capture = true;
        }

        // new data avaliable and capture is still on
        if(lastAudioDataTimestamp < getAudioData().timestamp) {
          LOGSTUFF(AudioData);
          lastAudioDataTimestamp = getAudioData().timestamp;
        }
      }

      if (getWhistlePercept().whistleDetected) {
        LOGSTUFF(WhistlePercept);
      }

      // record images every 1s
      if(params.logPlainImages && getFrameInfo().getTimeSince(lastTimeImageRecorded) > params.logPlainImagesDelay && imageOutFile.is_open() && !imageOutFile.fail()) {
        unsigned int frameNumber = getFrameInfo().getFrameNumber();
        imageOutFile.write((const char*)(&frameNumber), sizeof(unsigned int));

        // switch camera each frame
        if(lastRecordedPlainImageID == CameraInfo::Top) {
          imageOutFile.write((const char*)getImage().data(), getImage().data_size());
          lastRecordedPlainImageID = CameraInfo::Bottom;
        } else {
          imageOutFile.write((const char*)getImageTop().data(), getImageTop().data_size());
          lastRecordedPlainImageID = CameraInfo::Top;
        }

        lastTimeImageRecorded = getFrameInfo();
      }

      something_recorded = true;
    }

    if(something_recorded) {
      LOGSTUFF(FrameInfo);
      firstRecording = false;
    }

    // remember the old state
    oldState = getPlayerInfo().robotState;
  }
}

<|endoftext|>


<commit_before>//===-- SBSourceManager.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/API/SBDebugger.h"
#include "lldb/API/SBSourceManager.h"
#include "lldb/API/SBTarget.h"
#include "lldb/API/SBStream.h"

#include "lldb/API/SBFileSpec.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Stream.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Core/SourceManager.h"

#include "lldb/Target/Target.h"

namespace lldb_private
{
    class SourceManagerImpl
    {
    public:
        SourceManagerImpl (const lldb::DebuggerSP &debugger_sp)
        {
            m_debugger_sp = debugger_sp;
        }

        SourceManagerImpl (const lldb::TargetSP &target_sp)
        {
            m_target_sp = target_sp;
        }

        SourceManagerImpl (const SourceManagerImpl &rhs)
        {
            if (&rhs == this)
                return;
            m_debugger_sp = rhs.m_debugger_sp;
            m_target_sp   = rhs.m_target_sp;
        }

        size_t
        DisplaySourceLinesWithLineNumbers (const lldb_private::FileSpec &file,
                                           uint32_t line,
                                           uint32_t context_before,
                                           uint32_t context_after,
                                           const char* current_line_cstr,
                                           lldb_private::Stream *s)
        {
            if (file)
                return 0;

            if (m_debugger_sp)
                return m_debugger_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers (file,
                                                                                line,
                                                                                context_before,
                                                                                context_after,
                                                                                current_line_cstr,
                                                                                s);
            else if (m_target_sp)
                return m_target_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers (file,
                                                                                line,
                                                                                context_before,
                                                                                context_after,
                                                                                current_line_cstr,
                                                                                s);
            else
                return 0;
        }

    private:
        lldb::DebuggerSP m_debugger_sp;
        lldb::TargetSP   m_target_sp;

    };
}

using namespace lldb;
using namespace lldb_private;

SBSourceManager::SBSourceManager (const SBDebugger &debugger)
{
    m_opaque_ap.reset(new SourceManagerImpl (debugger.get_sp()));
}

SBSourceManager::SBSourceManager (const SBTarget &target)
{
    m_opaque_ap.reset(new SourceManagerImpl (target.get_sp()));
}

SBSourceManager::SBSourceManager (const SBSourceManager &rhs)
{
    if (&rhs == this)
        return;

    m_opaque_ap.reset(new SourceManagerImpl (*(rhs.m_opaque_ap.get())));
}

const lldb::SBSourceManager &
SBSourceManager::operator = (const lldb::SBSourceManager &rhs)
{
    m_opaque_ap.reset (new SourceManagerImpl (*(rhs.m_opaque_ap.get())));
    return *this;
}

SBSourceManager::~SBSourceManager()
{
}

size_t
SBSourceManager::DisplaySourceLinesWithLineNumbers
(
    const SBFileSpec &file,
    uint32_t line,
    uint32_t context_before,
    uint32_t context_after,
    const char* current_line_cstr,
    SBStream &s
)
{
    if (m_opaque_ap.get() == NULL)
        return 0;

    return m_opaque_ap->DisplaySourceLinesWithLineNumbers (file.ref(),
                                                           line,
                                                           context_before,
                                                           context_after,
                                                           current_line_cstr,
                                                           s.get());
}
<commit_msg>Fix regression of test SourceManagerTestCase.test_display_source_python.<commit_after>//===-- SBSourceManager.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/API/SBDebugger.h"
#include "lldb/API/SBSourceManager.h"
#include "lldb/API/SBTarget.h"
#include "lldb/API/SBStream.h"

#include "lldb/API/SBFileSpec.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Stream.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Core/SourceManager.h"

#include "lldb/Target/Target.h"

namespace lldb_private
{
    class SourceManagerImpl
    {
    public:
        SourceManagerImpl (const lldb::DebuggerSP &debugger_sp)
        {
            m_debugger_sp = debugger_sp;
        }

        SourceManagerImpl (const lldb::TargetSP &target_sp)
        {
            m_target_sp = target_sp;
        }

        SourceManagerImpl (const SourceManagerImpl &rhs)
        {
            if (&rhs == this)
                return;
            m_debugger_sp = rhs.m_debugger_sp;
            m_target_sp   = rhs.m_target_sp;
        }

        size_t
        DisplaySourceLinesWithLineNumbers (const lldb_private::FileSpec &file,
                                           uint32_t line,
                                           uint32_t context_before,
                                           uint32_t context_after,
                                           const char* current_line_cstr,
                                           lldb_private::Stream *s)
        {
            if (!file)
                return 0;

            if (m_debugger_sp)
                return m_debugger_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers (file,
                                                                                line,
                                                                                context_before,
                                                                                context_after,
                                                                                current_line_cstr,
                                                                                s);
            else if (m_target_sp)
                return m_target_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers (file,
                                                                                line,
                                                                                context_before,
                                                                                context_after,
                                                                                current_line_cstr,
                                                                                s);
            else
                return 0;
        }

    private:
        lldb::DebuggerSP m_debugger_sp;
        lldb::TargetSP   m_target_sp;

    };
}

using namespace lldb;
using namespace lldb_private;

SBSourceManager::SBSourceManager (const SBDebugger &debugger)
{
    m_opaque_ap.reset(new SourceManagerImpl (debugger.get_sp()));
}

SBSourceManager::SBSourceManager (const SBTarget &target)
{
    m_opaque_ap.reset(new SourceManagerImpl (target.get_sp()));
}

SBSourceManager::SBSourceManager (const SBSourceManager &rhs)
{
    if (&rhs == this)
        return;

    m_opaque_ap.reset(new SourceManagerImpl (*(rhs.m_opaque_ap.get())));
}

const lldb::SBSourceManager &
SBSourceManager::operator = (const lldb::SBSourceManager &rhs)
{
    m_opaque_ap.reset (new SourceManagerImpl (*(rhs.m_opaque_ap.get())));
    return *this;
}

SBSourceManager::~SBSourceManager()
{
}

size_t
SBSourceManager::DisplaySourceLinesWithLineNumbers
(
    const SBFileSpec &file,
    uint32_t line,
    uint32_t context_before,
    uint32_t context_after,
    const char* current_line_cstr,
    SBStream &s
)
{
    if (m_opaque_ap.get() == NULL)
        return 0;

    return m_opaque_ap->DisplaySourceLinesWithLineNumbers (file.ref(),
                                                           line,
                                                           context_before,
                                                           context_after,
                                                           current_line_cstr,
                                                           s.get());
}
<|endoftext|>